qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
258,988
<p>I'm <a href="http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/" rel="noreferrer">listening to a talk</a> about <strong>C#4</strong>'s <code>dynamic</code> keyword and I'm wondering... Will this feature be orthogonal to other .NET features, for example will it support extension methods?</p> <pre><code>public static class StrExtension { public static string twice(this string str) { return str + str; } } ... dynamic x = "Yo"; x.twice(); // will this work? </code></pre> <hr> <p><strong>Note:</strong> This question was asked before C#4 was shipped which is why it's phrased in the future tense.</p>
[ { "answer_id": 258999, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>From the <a href=\"http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=csharpfuture&amp;DownloadId=3550\" rel=\"noreferrer\">\"New Features in C# 4\" word doc</a>:</p>\n\n<blockquote>\n <p>Dynamic lookup will not be able to\n find extension methods. Whether\n extension methods apply or not depends\n on the static context of the call\n (i.e. which using clauses occur), and\n this context information is not\n currently kept as part of the payload.</p>\n</blockquote>\n" }, { "answer_id": 306227, "author": "Olmo", "author_id": 38670, "author_profile": "https://Stackoverflow.com/users/38670", "pm_score": 2, "selected": false, "text": "<p>It can't work, Extension methods work depending on having the namespace included in the file and, as far as I know, MSIL has no idea about files and including namespaces. </p>\n" }, { "answer_id": 1822926, "author": "Ian Warburton", "author_id": 221683, "author_profile": "https://Stackoverflow.com/users/221683", "pm_score": 2, "selected": false, "text": "<p>This works which I find interesting at least...</p>\n\n<pre><code>public static class StrExtension\n{\n public static string twice(this string str) { return str + str; }\n}\n\n...\ndynamic x = \"Yo\";\nStrExtension.twice(x);\n</code></pre>\n\n<p>Still, if the compiler can find the correct extension method at compile time then I don't see why it can't package up a set of extension methods to be looked up at runtime? It would be like a v-table for non-member methods.</p>\n\n<p>EDIT:</p>\n\n<p>This is cool... <a href=\"http://www2.research.att.com/~bs/multimethods.pdf\" rel=\"nofollow noreferrer\">http://www2.research.att.com/~bs/multimethods.pdf</a></p>\n" }, { "answer_id": 14651601, "author": "JoelFan", "author_id": 16012, "author_profile": "https://Stackoverflow.com/users/16012", "pm_score": 1, "selected": false, "text": "<p>You can create an extension method for <em>object</em> and assign it to a <em>dynamic</em>:</p>\n\n<pre><code>public static void MyExt(this object o) {\n dynamic d = o;\n d.myProp = \"foo\";\n}\n</code></pre>\n\n<p>and call it like this:</p>\n\n<pre><code>ClassWithMyProp x;\nx.MyExt();\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/258988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
I'm [listening to a talk](http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/) about **C#4**'s `dynamic` keyword and I'm wondering... Will this feature be orthogonal to other .NET features, for example will it support extension methods? ``` public static class StrExtension { public static string twice(this string str) { return str + str; } } ... dynamic x = "Yo"; x.twice(); // will this work? ``` --- **Note:** This question was asked before C#4 was shipped which is why it's phrased in the future tense.
From the ["New Features in C# 4" word doc](http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=csharpfuture&DownloadId=3550): > > Dynamic lookup will not be able to > find extension methods. Whether > extension methods apply or not depends > on the static context of the call > (i.e. which using clauses occur), and > this context information is not > currently kept as part of the payload. > > >
259,000
<p>I have a system which is using phone numbers as unique identifiers. For this reason, I want to format all phone numbers as they come in using a normalized format. Because I have no control over my source data, I need to parse out these numbers myself and format them before adding them to my DB.</p> <p>I'm about to write a parser that can read phone numbers in and output a normalized phone format, but before I do I was wondering if anyone knew of any pre-existing libraries I could use to format phone numbers.</p> <p>If there are no pre-existing libraries out there, what things should I be keeping in mind when creating this feature that may not be obvious?</p> <p>Although my system is only dealing with US numbers right now, I plan to try to include support for international numbers just in case since there is a chance it will be needed.</p> <p><strong>Edit</strong> I forgot to mention I'm using C#.NET 2.0.</p>
[ { "answer_id": 259016, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Just strip out any non-digits, possibly using a RegEx: <code>[^\\d]</code></p>\n\n<p>The only exception might be if you want to handle extensions, to distinguish a number without an area code but with a 3 digit extension, or if you need to handle international numbers.</p>\n" }, { "answer_id": 259071, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": false, "text": "<p>I'm currently involved in the <a href=\"http://openmoko.org\" rel=\"noreferrer\">OpenMoko</a> project, which is developing a completely open source cell phone (including hardware). There has been a lot of trouble around normalizing phone numbers. I don't know if anyone has come up with a good solution yet. The biggest problem seems to be with US phone numbers, since sometimes they come in with a 1 on the front and sometimes not. Depending on what you have stored in your contacts list, it may or may not display the caller ID info correctly. I'd recommend stripping off the 1 on the phone number (though I'd expect most people wouldn't enter it in the first place). You may also need to look for a plus sign or country code on the front of international numbers.</p>\n\n<p>You can check around the OpenMoko website, mailing list, and source control to see if they've solved this bug yet.</p>\n" }, { "answer_id": 259228, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 2, "selected": false, "text": "<p>perl and rails examples</p>\n\n<hr>\n\n<p><a href=\"http://validates-as-phone.googlecode.com/svn/trunk/README\" rel=\"nofollow noreferrer\">http://validates-as-phone.googlecode.com/svn/trunk/README</a></p>\n\n<p><a href=\"http://www.perlmonks.org/?node_id=159645\" rel=\"nofollow noreferrer\">http://www.perlmonks.org/?node_id=159645</a></p>\n" }, { "answer_id": 9137831, "author": "friism", "author_id": 2942, "author_profile": "https://Stackoverflow.com/users/2942", "pm_score": 5, "selected": false, "text": "<p>You could use <code>libphonenumber</code> from Google. Here's a blog post: </p>\n\n<p><a href=\"http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber\" rel=\"noreferrer\">http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber</a></p>\n\n<p>Parsing numbers is as easy as installing the <a href=\"http://nuget.org/packages/libphonenumber-csharp\" rel=\"noreferrer\">NuGet package</a> and then doing this:</p>\n\n<pre><code>var util = PhoneNumberUtil.GetInstance();\nvar number = util.Parse(\"555-555-5555\", \"US\");\n</code></pre>\n\n<p>You can then format the number like this:</p>\n\n<pre><code>util.Format(number, PhoneNumberFormat.E164);\n</code></pre>\n\n<p><code>libphonenumber</code> supports several formats other than E.164.</p>\n" }, { "answer_id": 39196341, "author": "Korayem", "author_id": 80434, "author_profile": "https://Stackoverflow.com/users/80434", "pm_score": 0, "selected": false, "text": "<p>What you need is list of all country codes and start matching your string first few characters against list of country codes to make sure it's correct then for the rest of the number, make sure it's all digits and of proper length which usually varies from 5-10 digits.</p>\n\n<p>To achieve checking against country codes, install <a href=\"https://github.com/RobThree/NGeoNames\" rel=\"nofollow\">NGeoNames nuget</a> which uses website <a href=\"http://www.geonames.org\" rel=\"nofollow\">www.geonames.org</a> to get list of all country codes to use to match against them.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I have a system which is using phone numbers as unique identifiers. For this reason, I want to format all phone numbers as they come in using a normalized format. Because I have no control over my source data, I need to parse out these numbers myself and format them before adding them to my DB. I'm about to write a parser that can read phone numbers in and output a normalized phone format, but before I do I was wondering if anyone knew of any pre-existing libraries I could use to format phone numbers. If there are no pre-existing libraries out there, what things should I be keeping in mind when creating this feature that may not be obvious? Although my system is only dealing with US numbers right now, I plan to try to include support for international numbers just in case since there is a chance it will be needed. **Edit** I forgot to mention I'm using C#.NET 2.0.
You could use `libphonenumber` from Google. Here's a blog post: <http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber> Parsing numbers is as easy as installing the [NuGet package](http://nuget.org/packages/libphonenumber-csharp) and then doing this: ``` var util = PhoneNumberUtil.GetInstance(); var number = util.Parse("555-555-5555", "US"); ``` You can then format the number like this: ``` util.Format(number, PhoneNumberFormat.E164); ``` `libphonenumber` supports several formats other than E.164.
259,014
<p>I'm reading up on event-driven design. I am having trouble getting my head around some of it in practice. I'm considering using this for a windows service that monitors, parses, and handles information coming from a 3rd party TCP stream. Is the following a decent approach, or am I missing something? </p> <p>My plan is to have a the main service be simply a container for events:</p> <pre><code>public class MyService { public void RegisterAgent(ServiceAgent agent) { Log("Initializing agent " + agent); agent.Initialize(this); Log("Done intializing agent " + agent); } public void Log(string messageText) { OnSimpleLogEventLogged(this, new SimpleLogEventArgs(messageText)); } protected void Raise&lt;T&gt;(EventHandler&lt;T&gt; eventHandler, object sender, T args) where T : EventArgs { var handler = eventHandler; if (handler == null) return; handler(sender, args); } public event EventHandler&lt;SimpleLogEventArgs&gt; SimpleLogEventLogged; protected void OnSimpleLogEventLogged(object sender, SimpleLogEventArgs args) { Raise(SimpleLogEventLogged, sender, args); } public event EventHandler&lt;TextRecievedEventArgs &gt; TextRecieved; public void OnTextRecieved(object sender, TextRecievedEventArgs args) { Raise(TextRecieved, sender, args); } public event EventHandler&lt;TextParsedEventArgs&gt; TextParsed; public void OnTextParsed(object sender, TextParsedEventArgs args) { Raise(TextParsed, sender, args); } ... } </code></pre> <p>Then, using MEF or similar, I'll register "ServiceAgent" instances, which simply handle and/or raise events, optionally doing so on a background thread. For example:</p> <pre><code>public class TextParsingAgent : ServiceAgent { public override void Initialize(MyService service) { service.TextRecieved += TextRecieved; base.Initialize(service); } void TextRecieved(object sender, TextRecievedEventArgs e) { ThreadPool.QueueUserWorkItem(TextRecievedAsync, e); } private void TextRecieved(object state) { var e = (TextRecievedEventArgs)state; //TODO:Parse text into something meaningful and store in textParseEventArgs service.OnTextParsed(textParseEventArgs); } } </code></pre>
[ { "answer_id": 259016, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Just strip out any non-digits, possibly using a RegEx: <code>[^\\d]</code></p>\n\n<p>The only exception might be if you want to handle extensions, to distinguish a number without an area code but with a 3 digit extension, or if you need to handle international numbers.</p>\n" }, { "answer_id": 259071, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": false, "text": "<p>I'm currently involved in the <a href=\"http://openmoko.org\" rel=\"noreferrer\">OpenMoko</a> project, which is developing a completely open source cell phone (including hardware). There has been a lot of trouble around normalizing phone numbers. I don't know if anyone has come up with a good solution yet. The biggest problem seems to be with US phone numbers, since sometimes they come in with a 1 on the front and sometimes not. Depending on what you have stored in your contacts list, it may or may not display the caller ID info correctly. I'd recommend stripping off the 1 on the phone number (though I'd expect most people wouldn't enter it in the first place). You may also need to look for a plus sign or country code on the front of international numbers.</p>\n\n<p>You can check around the OpenMoko website, mailing list, and source control to see if they've solved this bug yet.</p>\n" }, { "answer_id": 259228, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 2, "selected": false, "text": "<p>perl and rails examples</p>\n\n<hr>\n\n<p><a href=\"http://validates-as-phone.googlecode.com/svn/trunk/README\" rel=\"nofollow noreferrer\">http://validates-as-phone.googlecode.com/svn/trunk/README</a></p>\n\n<p><a href=\"http://www.perlmonks.org/?node_id=159645\" rel=\"nofollow noreferrer\">http://www.perlmonks.org/?node_id=159645</a></p>\n" }, { "answer_id": 9137831, "author": "friism", "author_id": 2942, "author_profile": "https://Stackoverflow.com/users/2942", "pm_score": 5, "selected": false, "text": "<p>You could use <code>libphonenumber</code> from Google. Here's a blog post: </p>\n\n<p><a href=\"http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber\" rel=\"noreferrer\">http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber</a></p>\n\n<p>Parsing numbers is as easy as installing the <a href=\"http://nuget.org/packages/libphonenumber-csharp\" rel=\"noreferrer\">NuGet package</a> and then doing this:</p>\n\n<pre><code>var util = PhoneNumberUtil.GetInstance();\nvar number = util.Parse(\"555-555-5555\", \"US\");\n</code></pre>\n\n<p>You can then format the number like this:</p>\n\n<pre><code>util.Format(number, PhoneNumberFormat.E164);\n</code></pre>\n\n<p><code>libphonenumber</code> supports several formats other than E.164.</p>\n" }, { "answer_id": 39196341, "author": "Korayem", "author_id": 80434, "author_profile": "https://Stackoverflow.com/users/80434", "pm_score": 0, "selected": false, "text": "<p>What you need is list of all country codes and start matching your string first few characters against list of country codes to make sure it's correct then for the rest of the number, make sure it's all digits and of proper length which usually varies from 5-10 digits.</p>\n\n<p>To achieve checking against country codes, install <a href=\"https://github.com/RobThree/NGeoNames\" rel=\"nofollow\">NGeoNames nuget</a> which uses website <a href=\"http://www.geonames.org\" rel=\"nofollow\">www.geonames.org</a> to get list of all country codes to use to match against them.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm reading up on event-driven design. I am having trouble getting my head around some of it in practice. I'm considering using this for a windows service that monitors, parses, and handles information coming from a 3rd party TCP stream. Is the following a decent approach, or am I missing something? My plan is to have a the main service be simply a container for events: ``` public class MyService { public void RegisterAgent(ServiceAgent agent) { Log("Initializing agent " + agent); agent.Initialize(this); Log("Done intializing agent " + agent); } public void Log(string messageText) { OnSimpleLogEventLogged(this, new SimpleLogEventArgs(messageText)); } protected void Raise<T>(EventHandler<T> eventHandler, object sender, T args) where T : EventArgs { var handler = eventHandler; if (handler == null) return; handler(sender, args); } public event EventHandler<SimpleLogEventArgs> SimpleLogEventLogged; protected void OnSimpleLogEventLogged(object sender, SimpleLogEventArgs args) { Raise(SimpleLogEventLogged, sender, args); } public event EventHandler<TextRecievedEventArgs > TextRecieved; public void OnTextRecieved(object sender, TextRecievedEventArgs args) { Raise(TextRecieved, sender, args); } public event EventHandler<TextParsedEventArgs> TextParsed; public void OnTextParsed(object sender, TextParsedEventArgs args) { Raise(TextParsed, sender, args); } ... } ``` Then, using MEF or similar, I'll register "ServiceAgent" instances, which simply handle and/or raise events, optionally doing so on a background thread. For example: ``` public class TextParsingAgent : ServiceAgent { public override void Initialize(MyService service) { service.TextRecieved += TextRecieved; base.Initialize(service); } void TextRecieved(object sender, TextRecievedEventArgs e) { ThreadPool.QueueUserWorkItem(TextRecievedAsync, e); } private void TextRecieved(object state) { var e = (TextRecievedEventArgs)state; //TODO:Parse text into something meaningful and store in textParseEventArgs service.OnTextParsed(textParseEventArgs); } } ```
You could use `libphonenumber` from Google. Here's a blog post: <http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber> Parsing numbers is as easy as installing the [NuGet package](http://nuget.org/packages/libphonenumber-csharp) and then doing this: ``` var util = PhoneNumberUtil.GetInstance(); var number = util.Parse("555-555-5555", "US"); ``` You can then format the number like this: ``` util.Format(number, PhoneNumberFormat.E164); ``` `libphonenumber` supports several formats other than E.164.
259,015
<p>Can every possible value of a <code>float</code> variable can be represented exactly in a <code>double</code> variable?</p> <p>In other words, for all possible values <code>X</code> will the following be successful:</p> <pre><code>float f1 = X; double d = f1; float f2 = (float)d; if(f1 == f2) System.out.println("Success!"); else System.out.println("Failure!"); </code></pre> <p>My suspicion is that there is no exception, or if there is it is only for an edge case (like +/- infinity or NaN).</p> <p><strong>Edit</strong>: Original wording of question was confusing (stated two ways, one which would be answered "no" the other would be answered "yes" for the same answer). I've reworded it so that it matches the question title.</p>
[ { "answer_id": 259029, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>In theory, there is not such a value, so \"yes\", every float should be representable as a double.. Converting from a float to a double should involve just tacking four bytes of 00 on the end -- they are stored using the same format, just with different sized fields.</p>\n" }, { "answer_id": 259030, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": false, "text": "<p>Yes, floats are a subset of doubles. Both floats and doubles have the form (sign * a * 2^b). The difference between floats and doubles is the number of bits in a &amp; b. Since doubles have more bits available, assigning a float value to a double effectively means inserting extra 0 bits.</p>\n" }, { "answer_id": 259040, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "<p>As everyone has already said, \"no\". But that's actually a \"yes\" to the question itself, i.e. every float <strong>can</strong> be exactly expressed as a double. Confusing. :)</p>\n" }, { "answer_id": 259051, "author": "Mitch Flax", "author_id": 1216, "author_profile": "https://Stackoverflow.com/users/1216", "pm_score": 2, "selected": false, "text": "<p>If I'm reading the <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3\" rel=\"nofollow noreferrer\">language specification</a> correctly (and as everyone else is confirming), there is no such value.</p>\n\n<p>That is, each claims only to hold only IEEE 754 standard values, so casts between the two should incur no change except in memory given.</p>\n\n<p>(clarification: There would be no change as long as the value was small enough to be held in a float; obviously if the value was too many bits to be held in a float to begin with, casting from double to float would result in a loss of precision.)</p>\n" }, { "answer_id": 259113, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 0, "selected": false, "text": "<p><strong>Snark:</strong> <code>NaN</code>s will compare differently after (or indeed before) conversion.</p>\n\n<p>This does not, however, invalidate the answers already given.</p>\n" }, { "answer_id": 259130, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 0, "selected": false, "text": "<p>I took the code you listed and decided to try it in C++ since I thought it might execute a little faster and it is significantly easier to do unsafe casting. :-D</p>\n\n<p>I found out that for valid numbers, the conversion works and you get the exact bitwise representation after the cast. However, for non-numbers, e.g. 1.#QNAN0, etc., the result will use a simplified representation of the non-number rather than the exact bits of the source. For example:</p>\n\n<blockquote>\n <p>**** FAILURE **** 2140188725 | 1.#QNAN0 -- 0xa0000000 0x7ffa1606</p>\n</blockquote>\n\n<p>I cast an unsigned int to float then to double and back to float. The number 2140188725 (0x7F90B035) results in a NAN and converting to double and back is still a NAN but not the <em>exact</em> same NAN.</p>\n\n<p>Here is the simple C++ code:</p>\n\n<pre><code>typedef unsigned int uint;\nfor (uint i = 0; i &lt; 0xFFFFFFFF; ++i)\n{\n float f1 = *(float *)&amp;i;\n double d = f1;\n float f2 = (float)d;\n if(f1 != f2)\n printf(\"**** FAILURE **** %u | %f -- 0x%08x 0x%08x\\n\", i, f1, f1, f2);\n if ((i % 1000000) == 0)\n printf(\"Iteration: %d\\n\", i);\n}\n</code></pre>\n" }, { "answer_id": 259356, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "<p>@KenG: This code:</p>\n\n<pre><code>float a = 0.1F\nprintln \"a=${a}\"\ndouble d = a\nprintln \"d=${d}\"\n</code></pre>\n\n<p>fails not because 0.1f can't be exactly represented. The question was \"is there a float value that cannot be represented as a double\", which this code doesn't prove. Although 0.1f can't be stored exactly, the value that a is given (which isn't 0.1f exactly) can be stored as a double (which also won't be 0.1f exactly). Assuming an Intel FPU, the bit pattern for a is:</p>\n\n<blockquote>\n <p>0 01111011 10011001100110011001101</p>\n</blockquote>\n\n<p>and the bit pattern for d is:</p>\n\n<blockquote>\n <p>0 01111111011 100110011001100110011010 (followed by lots more zeros)</p>\n</blockquote>\n\n<p>which has the same sign, exponent (-4 in both cases) and the same fractional part (separated by spaces above). The difference in the output is due to the position of the second non-zero digit in the number (the first is the 1 after the point) which can only be represented with a double. The code that outputs the string format stores intermediate values in memory and is specific to floats and doubles (i.e. there is a function double-to-string and another float-to-string). If the to-string function was optimised to use the FPU stack to store the intermediate results of the to-string process, the output would be the same for float and double since the FPU uses the same, larger format (80bits) for both float and double.</p>\n\n<p>There are no float values that can't be stored identically in a double, i.e. the set of float values is a sub-set of the the set of double values.</p>\n" }, { "answer_id": 259514, "author": "mfx", "author_id": 8015, "author_profile": "https://Stackoverflow.com/users/8015", "pm_score": 6, "selected": true, "text": "<p>Yes.</p>\n\n<p>Proof by enumeration of all possible cases:</p>\n\n<pre><code>public class TestDoubleFloat {\n public static void main(String[] args) {\n for (long i = Integer.MIN_VALUE; i &lt;= Integer.MAX_VALUE; i++) {\n float f1 = Float.intBitsToFloat((int) i);\n double d = (double) f1;\n float f2 = (float) d;\n if (f1 != f2) {\n if (Float.isNaN(f1) &amp;&amp; Float.isNaN(f2)) {\n continue; // ok, NaN\n }\n fail(\"oops: \" + f1 + \" != \" + f2);\n }\n }\n }\n}\n</code></pre>\n\n<p>finishes in 12 seconds on my machine. 32 bits are <em>small</em>.</p>\n" }, { "answer_id": 260459, "author": "Chris Dodd", "author_id": 29759, "author_profile": "https://Stackoverflow.com/users/29759", "pm_score": 0, "selected": false, "text": "<p>The answer to the first question is yes, the answer to the 'in other words', however is no. If you change the test in the code to be <code>if (!(f1 != f2))</code> the answer to the second question becomes yes -- it will print 'Success' for all float values.</p>\n" }, { "answer_id": 262197, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 0, "selected": false, "text": "<p>In theory every normal single can have the exponent and mantissa padded to create a double and then remove the padding and you return to the original single.</p>\n\n<p>When you go from theory to reality is when you will have problems. I dont know if you were interested in theory or implementation. If it is implementation then you can rapidly get into trouble.</p>\n\n<p>IEEE is a horrible format, my understanding it was intentionally designed to be so tough that nobody could meet it and allow the market to catch up to intel (this was a while back) allowing for more competition. If that is true it failed, either way we are stuck with this dreadful spec. Something like the TI format is far superior for the real world in so many ways. I have no connection to either company or any of these formats.</p>\n\n<p>Thanks to this spec there are very few if any fpus that actually meet it (in hardware or even in hardware plus the operating system), and those that do often fail on the next generation. (google: TestFloat). The problems these days tend to lie in the int to float and float to int and not single to double and double to single as you have specified above. Of course what operation is the fpu going to perform to do that conversion? Add 0? Multiply by 1? Depends on the fpu and the compiler.</p>\n\n<p>The problem with IEEE related to your question above is that there is more than one way a number, not every number but many numbers can be represented. If I wanted to break your code I would start with minus zero in the hope that one of the two operations would convert it to a plus zero. Then I would try denormals. And it should fail with a signaling nan, but you called that out as a known exception.</p>\n\n<p>The problem is that equal sign, here is rule number one about floating point, never use an equal sign. Equals is a bit comparison not a value comparison, if you have two values represented in different ways (plus zero and minus zero for example) the bit comparison will fail even though its the same number. Greater than and less than are done in the fpu, equals is done with the integer alu. </p>\n\n<p>I realize that you probably used the equal to explain the problem and not necessarily the code you wanted to succeed or fail.</p>\n" }, { "answer_id": 12152511, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "<p>If a floating-point type is viewed as representing a precise value, then as other posters have noted, every <code>float</code> value is representable as a <code>double</code>, but only a few values of <code>double</code> can be represented by <code>float</code>. On the other hand, if one recognizes that floating-point values are approximations, one will realize the real situation is reversed. If one uses a very precise instrument to measure something which is 3.437mm, one may correctly describe is size as 3.4mm. if one uses a ruler to measure the object as 3.4mm, it would be incorrect to describe its size as 3.400mm.</p>\n\n<p>Even bigger problems exist at the top of the range. There is a <code>float</code> value that represents: \"computed value exceeded 2^127 by an unknown amount\", but there's no <code>double</code> value that indicates such a thing. Casting an \"infinity\" from single to double will yield a value \"computed value exceeded 2^1023 by an unknown amount\" which is off by a factor of over a googol.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
Can every possible value of a `float` variable can be represented exactly in a `double` variable? In other words, for all possible values `X` will the following be successful: ``` float f1 = X; double d = f1; float f2 = (float)d; if(f1 == f2) System.out.println("Success!"); else System.out.println("Failure!"); ``` My suspicion is that there is no exception, or if there is it is only for an edge case (like +/- infinity or NaN). **Edit**: Original wording of question was confusing (stated two ways, one which would be answered "no" the other would be answered "yes" for the same answer). I've reworded it so that it matches the question title.
Yes. Proof by enumeration of all possible cases: ``` public class TestDoubleFloat { public static void main(String[] args) { for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) { float f1 = Float.intBitsToFloat((int) i); double d = (double) f1; float f2 = (float) d; if (f1 != f2) { if (Float.isNaN(f1) && Float.isNaN(f2)) { continue; // ok, NaN } fail("oops: " + f1 + " != " + f2); } } } } ``` finishes in 12 seconds on my machine. 32 bits are *small*.
259,018
<p>This is what I have written:</p> <pre><code>if ((lstProperty[i].PropertyIdentifier as string).CompareTo("Name") == 0) </code></pre> <p>Resharper put me an error (I am new with ReSharper... I am trying it) and it suggests me :</p> <pre><code> if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0) </code></pre> <p>Why is the second is NullException safe? For me both will crash if null value appear?</p>
[ { "answer_id": 259062, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 4, "selected": true, "text": "<p>The 'as' operator will return null if the cast cannot be executed, while a C-style cast will throw an exception if it can't cast.</p>\n\n<p>I suggest breaking this out into multiple statements:</p>\n\n<pre><code>string propertyIdentifier = lstProperty[u].PropertyIdentifier as string;\nif(propertyIdentifier != null &amp;&amp; propertyIdentifier.CompareTo(\"Name\") == 0)\n{\n ... your if statement ...\n}\n</code></pre>\n\n<p>Resharper shouldn't complain about this, and you also won't get a NullReferenceException if the PropertyIdentifier is null or not a string.</p>\n" }, { "answer_id": 259114, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "<p>Both examples will succeed or fail in the same circumstances, and when they succeed, the behavior will be identical.</p>\n\n<p>When they fail, the result will be slightly different: the second example fails slightly earlier (at the cast), and with a more specific exception (<code>InvalidCastException</code> vs. <code>NullReferenceException</code>). </p>\n\n<p>The main benefit is for debugging: when they fail, you have more information about why it failed in the second example than in the first. Specifically, if the PropertyIdentifier is <code>null</code> vs. non-<code>string</code>, you can tell in the second case, but not in the first case.</p>\n\n<p>Also, if you are in a <code>try/catch</code>, you can handle the non-<code>string</code> case in a separate code path than the <code>null</code> case. However, you probably shouldn't be coding this way: if you are, you're doing something else wrong.</p>\n\n<p>It might help illuminate the situation if you step through the following code in the various cases:</p>\n\n<pre><code>var propertyI = lstProperty[i];\nvar propertyIdentifier = propertyI.PropertyIdentifier;\n\n// pick one of these:\nvar propertyIdentifierAsString = propertyIdentifier as string;\nvar propertyIdentifierAsString = (string)propertyIdentifier;\n\nif (propertyIdentifierAsString.CompareTo(\"Name\") == 0)\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
This is what I have written: ``` if ((lstProperty[i].PropertyIdentifier as string).CompareTo("Name") == 0) ``` Resharper put me an error (I am new with ReSharper... I am trying it) and it suggests me : ``` if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0) ``` Why is the second is NullException safe? For me both will crash if null value appear?
The 'as' operator will return null if the cast cannot be executed, while a C-style cast will throw an exception if it can't cast. I suggest breaking this out into multiple statements: ``` string propertyIdentifier = lstProperty[u].PropertyIdentifier as string; if(propertyIdentifier != null && propertyIdentifier.CompareTo("Name") == 0) { ... your if statement ... } ``` Resharper shouldn't complain about this, and you also won't get a NullReferenceException if the PropertyIdentifier is null or not a string.
259,024
<p>I am trying to use WScript.Shell SendKeys method to emulate sending a key press from the Number Pad.</p> <p>I have an application that I am writing automated testing for using QTP. It is a Web Browser based application and the input is into a Java App within the web page. The input only accepts key presses from the Number Pad and the Enter key.</p> <p>So far I am using this code:</p> <pre><code>Dim strInputKey strInputKey = &quot;{ENTER}&quot; Set objWsh = CreateObject(&quot;WScript.Shell&quot;) Browser(&quot;Launch Browser&quot;).Page(&quot;Test Application&quot;).WebElement(&quot;Item ID&quot;).Click objWsh.SendKeys strInputKey </code></pre> <p>This works fine for sending the Enter key, but I can't quite figure out if there is a way to send Number Keys. Any help would be greatly appreciated.</p> <p>I am not sure if there are any undocumented ways of achieving this. I have read <a href="http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx</a> but it doesn't go into great detail.</p>
[ { "answer_id": 259298, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 0, "selected": false, "text": "<p>Not sure that this can be answered with the information that you have provided so far. My gut feeling would be that you should use powershell since it sounds like you may already have some .Net code. But it really does just depend on exactly what you are trying to do.</p>\n" }, { "answer_id": 259625, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 4, "selected": true, "text": "<p>I would choose PowerShell over WMI for the following reasons:</p>\n\n<ol>\n<li>Writing a cmdlet is only adding a .NET Class.</li>\n<li>The PowerShell runtime provides command line parsing built in.</li>\n<li>Writing your management interface in PowerShell allows administrators the ability to integrate management of your application with that of other applications and services (like Exchange, Active Directory, or SQL Server).</li>\n<li>The PowerShell environment makes the pipeline available to administrators, enabling management tasks for your application to be done more efficiently.</li>\n<li>Discoverability. PowerShell, via Get-Command, Get-Member, and Get-Help, provides an extremely discoverable environment for admins to work in, resulting in a shorter learning curve to maintaining your application.</li>\n</ol>\n\n<p>Even if you go the WMI route, PowerShell does have support for working with WMI (though there are a few glitches).</p>\n\n<p>To me, PowerShell is the best way to surface a <strong>task oriented</strong> interface to an application. With the support Microsoft has been providing PowerShell, it is and will be a consistent interface to managing applications and services throughout the enterprise.</p>\n\n<p>My day job is as an admin and I'm pushing all the vendors I work with towards surfacing a PowerShell management API, as this makes the learning curve and context switching for managing applications much lower. On the development side, I have written (and am still working on) a series of PowerShell cmdlets for one open source product I work with and am working on another set for a separate application.</p>\n" }, { "answer_id": 259672, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 2, "selected": false, "text": "<p>Jeffrey Snover answers the \"why PowerShell\" <a href=\"http://blogs.msdn.com/powershell/archive/2008/08/30/powershell-vs-tsql-why-learn-powershell.aspx\" rel=\"nofollow noreferrer\">here</a>. The post is in the context of SQL, but very much applicable here.</p>\n" }, { "answer_id": 315636, "author": "Don Jones", "author_id": 40405, "author_profile": "https://Stackoverflow.com/users/40405", "pm_score": 2, "selected": false, "text": "<p>I'm not sure I'd make the decision. It's not exactly either-or... you can choose to do both.</p>\n\n<p>WMI can be consumed by a number of different things, not just PowerShell. Why not write your management instrumentation in PowerShell, and then wrap that WMI in some task-oriented cmdlets to make things easier on administrators? That's what some MS product teams are choosing to do, especially when they have other consumers of WMI they want to continue supporting.</p>\n\n<p>If you've already got suitable .NET code, turning that into a cmdlet may be faster than turning it into a WMI provider. If that's the case, and speed is a concern, go with what's easier. But no matter what you do, you can always wrap it in a PowerShell cmdlet for admins, which is definitely the recommended approach.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26950/" ]
I am trying to use WScript.Shell SendKeys method to emulate sending a key press from the Number Pad. I have an application that I am writing automated testing for using QTP. It is a Web Browser based application and the input is into a Java App within the web page. The input only accepts key presses from the Number Pad and the Enter key. So far I am using this code: ``` Dim strInputKey strInputKey = "{ENTER}" Set objWsh = CreateObject("WScript.Shell") Browser("Launch Browser").Page("Test Application").WebElement("Item ID").Click objWsh.SendKeys strInputKey ``` This works fine for sending the Enter key, but I can't quite figure out if there is a way to send Number Keys. Any help would be greatly appreciated. I am not sure if there are any undocumented ways of achieving this. I have read <http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx> but it doesn't go into great detail.
I would choose PowerShell over WMI for the following reasons: 1. Writing a cmdlet is only adding a .NET Class. 2. The PowerShell runtime provides command line parsing built in. 3. Writing your management interface in PowerShell allows administrators the ability to integrate management of your application with that of other applications and services (like Exchange, Active Directory, or SQL Server). 4. The PowerShell environment makes the pipeline available to administrators, enabling management tasks for your application to be done more efficiently. 5. Discoverability. PowerShell, via Get-Command, Get-Member, and Get-Help, provides an extremely discoverable environment for admins to work in, resulting in a shorter learning curve to maintaining your application. Even if you go the WMI route, PowerShell does have support for working with WMI (though there are a few glitches). To me, PowerShell is the best way to surface a **task oriented** interface to an application. With the support Microsoft has been providing PowerShell, it is and will be a consistent interface to managing applications and services throughout the enterprise. My day job is as an admin and I'm pushing all the vendors I work with towards surfacing a PowerShell management API, as this makes the learning curve and context switching for managing applications much lower. On the development side, I have written (and am still working on) a series of PowerShell cmdlets for one open source product I work with and am working on another set for a separate application.
259,026
<p>Why was C# designed this way?</p> <p>As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.</p> <p>If classes wish to implement that behavour in a shared method, why shouldn't they?</p> <p>Here is an example of what I have in mind:</p> <pre><code>// These items will be displayed in a list on the screen. public interface IListItem { string ScreenName(); ... } public class Animal: IListItem { // All animals will be called "Animal". public static string ScreenName() { return "Animal"; } .... } public class Person: IListItem { private string name; // All persons will be called by their individual names. public string ScreenName() { return name; } .... } </code></pre>
[ { "answer_id": 259033, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Because interfaces are in inheritance structure, and static methods don't inherit well.</p>\n" }, { "answer_id": 259042, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": false, "text": "<p>Short-sightedness, I'd guess.</p>\n\n<p>When originally designed, interfaces were intended only to be used with instances of class</p>\n\n<pre><code>IMyInterface val = GetObjectImplementingIMyInterface();\nval.SomeThingDefinedinInterface();\n</code></pre>\n\n<p>It was only with the introduction of interfaces as constraints for generics did adding a static method to an interface have a practical use.</p>\n\n<p>(responding to comment:) I believe changing it now would require a change to the CLR, which would lead to incompatibilities with existing assemblies.</p>\n" }, { "answer_id": 259044, "author": "John Kraft", "author_id": 7495, "author_profile": "https://Stackoverflow.com/users/7495", "pm_score": 4, "selected": false, "text": "<p>Interfaces specify behavior of an object.</p>\n\n<p>Static methods do not specify a behavior of an object, but behavior that affects an object in some way.</p>\n" }, { "answer_id": 259079, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 9, "selected": true, "text": "<p>Assuming you are asking why you can't do this:</p>\n\n<pre><code>public interface IFoo {\n void Bar();\n}\n\npublic class Foo: IFoo {\n public static void Bar() {}\n}\n</code></pre>\n\n<p>This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.\n<hr/>\nTo implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.</p>\n\n<pre><code>public class Animal: IListItem {\n /* Can be tough to come up with a different, yet meaningful name!\n * A different casing convention, like Java has, would help here.\n */\n public const string AnimalScreenName = \"Animal\";\n public string ScreenName(){ return AnimalScreenName; }\n}\n</code></pre>\n\n<p>For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.</p>\n" }, { "answer_id": 259190, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 2, "selected": false, "text": "<p>What you seem to want would allow for a static method to be called via both the Type or any instance of that type. This would at very least result in ambiguity which is not a desirable trait.</p>\n\n<p>There would be endless debates about whether it mattered, which is best practice and whether there are performance issues doing it one way or another. By simply not supporting it C# saves us having to worry about it.</p>\n\n<p>Its also likely that a compilier that conformed to this desire would lose some optimisations that may come with a more strict separation between instance and static methods.</p>\n" }, { "answer_id": 259194, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 1, "selected": false, "text": "<p>Interfaces are abstract sets of defined available functionality.</p>\n\n<p><strong>Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface</strong>. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.</p>\n\n<p>If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: <a href=\"http://en.wikipedia.org/wiki/Object-oriented\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Object-oriented</a>). For this reason, static methods aren't permitted in interfaces.</p>\n" }, { "answer_id": 259232, "author": "Daniel Auger", "author_id": 1644, "author_profile": "https://Stackoverflow.com/users/1644", "pm_score": 1, "selected": false, "text": "<p>FYI: You could get a similar behavior to what you want by creating extension methods for the interface. The extension method would be a shared, non overridable static behavior. However, unfortunately, this static method would not be part of the contract.</p>\n" }, { "answer_id": 259244, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 2, "selected": false, "text": "<p>You can think of the static methods and non-static methods of a class as being different interfaces. When called, static methods resolve to the singleton static class object, and non-static methods resolve to the instance of the class you deal with. So, if you use static and non-static methods in an interface, you'd effectively be declaring two interfaces when really we want interfaces to be used to access one cohesive thing.</p>\n" }, { "answer_id": 259360, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 0, "selected": false, "text": "<p>I think the short answer is \"because it is of zero usefulness\". \nTo call an interface method, you need an instance of the type. From instance methods you can call any static methods you want to.</p>\n" }, { "answer_id": 259378, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 7, "selected": false, "text": "<p>My (simplified) technical reason is that static methods are not in the <a href=\"http://en.wikipedia.org/wiki/Virtual_table\" rel=\"noreferrer\">vtable</a>, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.</p>\n\n<p>For the political reason, I'll <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/calling-static-methods-on-type-parameters-is-illegal-part-one\" rel=\"noreferrer\">quote Eric Lippert</a> (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: <a href=\"https://www.linkedin.com/pub/eric-lippert/85/934/a38\" rel=\"noreferrer\">LinkedIn</a>): </p>\n\n<blockquote>\n <p>...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.</p>\n</blockquote>\n\n<p>Note that Lippert does leave room for a so-called type method:</p>\n\n<blockquote>\n <p>That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).</p>\n</blockquote>\n\n<p>but is yet to be convinced of its usefulness.</p>\n" }, { "answer_id": 259413, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 3, "selected": false, "text": "<p>Because the purpose of an interface is to allow polymorphism, being able to pass an instance of any number of defined classes that have all been defined to implement the defined interface... guaranteeing that within your polymorphic call, the code will be able to find the method you are calling. it makes no sense to allow a static method to implement the interface, </p>\n\n<p>How would you call it?? </p>\n\n<hr>\n\n<pre><code>public interface MyInterface { void MyMethod(); }\npublic class MyClass: MyInterface\n{\n public static void MyMethod() { //Do Something; }\n}\n\n // inside of some other class ... \n // How would you call the method on the interface ???\n MyClass.MyMethod(); // this calls the method normally \n // not through the interface...\n\n // This next fails you can't cast a classname to a different type... \n // Only instances can be Cast to a different type...\n MyInterface myItf = MyClass as MyInterface; \n</code></pre>\n" }, { "answer_id": 589484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>To give an example where I am missing either static implementation of interface methods or what Mark Brackett introduced as the \"so-called type method\":</p>\n\n<p>When reading from a database storage, we have a generic DataTable class that handles reading from a table of any structure. All table specific information is put in one class per table that also holds data for one row from the DB and which must implement an IDataRow interface. Included in the IDataRow is a description of the structure of the table to read from the database. The DataTable must ask for the datastructure from the IDataRow before reading from the DB. Currently this looks like:</p>\n\n<pre><code>interface IDataRow {\n string GetDataSTructre(); // How to read data from the DB\n void Read(IDBDataRow); // How to populate this datarow from DB data\n}\n\npublic class DataTable&lt;T&gt; : List&lt;T&gt; where T : IDataRow {\n\n public string GetDataStructure()\n // Desired: Static or Type method:\n // return (T.GetDataStructure());\n // Required: Instantiate a new class:\n return (new T().GetDataStructure());\n }\n\n}\n</code></pre>\n\n<p>The GetDataStructure is only required once for each table to read, the overhead for instantiating one more instance is minimal. However, it would be nice in this case here.</p>\n" }, { "answer_id": 4738440, "author": "Louis Rebolloso", "author_id": 581827, "author_profile": "https://Stackoverflow.com/users/581827", "pm_score": 1, "selected": false, "text": "<p>Static classes should be able to do this so they can be used generically. I had to instead implement a Singleton to achieve the desired results.</p>\n\n<p>I had a bunch of Static Business Layer classes that implemented CRUD methods like \"Create\", \"Read\", \"Update\", \"Delete\" for each entity type like \"User\", \"Team\", ect.. Then I created a base control that had an abstract property for the Business Layer class that implemented the CRUD methods. This allowed me to automate the \"Create\", \"Read\", \"Update\", \"Delete\" operations from the base class. I had to use a Singleton because of the Static limitation.</p>\n" }, { "answer_id": 7945206, "author": "Ivan Arjentinski", "author_id": 1020711, "author_profile": "https://Stackoverflow.com/users/1020711", "pm_score": 7, "selected": false, "text": "<p>Most answers here seem to miss the whole point. Polymorphism can be used not only between instances, but also between types. This is often needed, when we use generics.</p>\n<p>Suppose we have type parameter in generic method and we need to do some operation with it. We dont want to instantinate, because we are unaware of the constructors.</p>\n<p>For example:</p>\n<pre><code>Repository GetRepository&lt;T&gt;()\n{\n //need to call T.IsQueryable, but can't!!!\n //need to call T.RowCount\n //need to call T.DoSomeStaticMath(int param)\n}\n\n...\nvar r = GetRepository&lt;Customer&gt;()\n</code></pre>\n<p>Unfortunately, I can come up only with &quot;ugly&quot; alternatives:</p>\n<ul>\n<li><p><strong>Use reflection</strong>\nUgly and beats the idea of interfaces and polymorphism.</p>\n</li>\n<li><p><strong>Create completely separate factory class</strong></p>\n<p>This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class.</p>\n</li>\n<li><p><strong>Instantiate and then call the desired interface method</strong></p>\n<p>This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, &quot;connected to DB&quot; state.</p>\n</li>\n</ul>\n<p>Example:</p>\n<pre><code>public class Customer \n{\n //create new customer\n public Customer(Transaction t) { ... }\n\n //open existing customer\n public Customer(Transaction t, int id) { ... }\n\n void SomeOtherMethod() \n { \n //do work...\n }\n}\n</code></pre>\n<p>in order to use instantination for solving the static interface problem we need to do the following thing:</p>\n<pre><code>public class Customer: IDoSomeStaticMath\n{\n //create new customer\n public Customer(Transaction t) { ... }\n\n //open existing customer\n public Customer(Transaction t, int id) { ... }\n\n //dummy instance\n public Customer() { IsDummy = true; }\n\n int DoSomeStaticMath(int a) { }\n\n void SomeOtherMethod() \n { \n if(!IsDummy) \n {\n //do work...\n }\n }\n}\n</code></pre>\n<p>This is obviously ugly and also unnecessary complicates the code for all other methods. Obviously, not an elegant solution either!</p>\n" }, { "answer_id": 8171262, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 4, "selected": false, "text": "<p>I know it's an old question, but it's interesting. The example isn't the best. I think it would be much clearer if you showed a usage case:</p>\n\n<pre>\nstring DoSomething&lt;T&gt;() where T:ISomeFunction\n{\n if (T.someFunction())\n ...\n}\n</pre>\n\n<p>Merely being able to have static methods <i>implement</i> an interface would not achieve what you want; what would be needed would be to have static members as <i>part</i> of an interface. I can certainly imagine many usage cases for that, especially when it comes to being able to create things. Two approaches I could offer which might be helpful:</p>\n\n<ol>\n<li>Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a \"register information\" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer&lt;T&gt;.Default().\n<li>For each class T of interest, define a class or struct which implements IGetWhateverClassInfo&lt;T&gt; and satisfies a \"new\" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.\n</ol>\n\n<p>None of these approaches is really appealing. On the other hand, I would expect that if the mechanisms existed in CLR to provide this sort of functionality cleanly, .net would allow one to specify parameterized \"new\" constraints (since knowing if a class has a constructor with a particular signature would seem to be comparable in difficulty to knowing if it has a static method with a particular signature).</p>\n" }, { "answer_id": 12066061, "author": "George", "author_id": 1612190, "author_profile": "https://Stackoverflow.com/users/1612190", "pm_score": 4, "selected": false, "text": "<p>To the extent that interfaces represent \"contracts\", it seems quiet reasonable for static classes to implement interfaces. </p>\n\n<p>The above arguments all seem to miss this point about contracts.</p>\n" }, { "answer_id": 17661755, "author": "Mar Bar", "author_id": 2584698, "author_profile": "https://Stackoverflow.com/users/2584698", "pm_score": 1, "selected": false, "text": "<p>Most people seem to forget that in OOP Classes are objects too, and so they have messages, which for some reason c# calls \"static method\".\nThe fact that differences exist between instance objects and class objects only shows flaws or shortcomings in the language.\nOptimist about c# though...</p>\n" }, { "answer_id": 17925193, "author": "Stephen Westlake", "author_id": 934859, "author_profile": "https://Stackoverflow.com/users/934859", "pm_score": 1, "selected": false, "text": "<p>OK here is an example of needing a 'type method'. I am creating one of a set of classes based on some source XML. So I have a </p>\n\n<pre><code> static public bool IsHandled(XElement xml)\n</code></pre>\n\n<p>function which is called in turn on each class.</p>\n\n<p>The function should be static as otherwise we waste time creating inappropriate objects.\nAs @Ian Boyde points out it could be done in a factory class, but this just adds complexity.</p>\n\n<p>It would be nice to add it to the interface to force class implementors to implement it. This would not cause significant overhead - it is only a compile/link time check and does not affect the vtable.</p>\n\n<p>However, it would also be a fairly minor improvement. As the method is static, I as the caller, must call it explicitly and so get an immediate compile error if it is not implemented. Allowing it to be specified on the interface would mean this error comes marginally earlier in the development cycle, but this is trivial compared to other broken-interface issues.</p>\n\n<p>So it is a minor potential feature which on balance is probably best left out.</p>\n" }, { "answer_id": 18215459, "author": "Jeremy Sorensen", "author_id": 2325220, "author_profile": "https://Stackoverflow.com/users/2325220", "pm_score": 2, "selected": false, "text": "<p>Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:</p>\n\n<pre><code>T SumElements&lt;T&gt;(T initVal, T[] values)\n{\n foreach (var v in values)\n {\n initVal += v;\n }\n}\n</code></pre>\n\n<p>Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.</p>\n\n<p>What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:</p>\n\n<pre><code>constraint CHasPlusEquals\n{\n static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);\n}\n\nT SumElements&lt;T&gt;(T initVal, T[] values) where T : CHasPlusEquals\n{\n foreach (var v in values)\n {\n initVal += v;\n }\n}\n</code></pre>\n\n<p>There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.</p>\n" }, { "answer_id": 29149949, "author": "William Jockusch", "author_id": 246568, "author_profile": "https://Stackoverflow.com/users/246568", "pm_score": 0, "selected": false, "text": "<p>I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it \"static\" if said type is unknown. But once the type becomes known, it will become static. \"Unresolved static\" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.</p>\n\n<p>Since it's not available, I have taken to using non-static methods in the way shown below. Not exactly ideal, but I can't see any approach that makes more sense, at least not for me.</p>\n\n<pre><code>public interface IZeroWrapper&lt;TNumber&gt; {\n TNumber Zero {get;}\n}\n\npublic class DoubleWrapper: IZeroWrapper&lt;double&gt; {\n public double Zero { get { return 0; } }\n}\n</code></pre>\n" }, { "answer_id": 31632377, "author": "Thomas Phaneuf", "author_id": 3152063, "author_profile": "https://Stackoverflow.com/users/3152063", "pm_score": 1, "selected": false, "text": "<p>The fact that a static class is implemented in C# by Microsoft creating a special instance of a class with the static elements is just an oddity of how static functionality is achieved. It is isn't a theoretical point.</p>\n\n<p>An interface SHOULD be a descriptor of the class interface - or how it is interacted with, and that should include interactions that are static. The general definition of interface (from Meriam-Webster): the place or area at which different things meet and communicate with or affect each other. When you omit static components of a class or static classes entirely, we are ignoring large sections of how these bad boys interact.</p>\n\n<p>Here is a very clear example of where being able to use interfaces with static classes would be quite useful: </p>\n\n<pre><code>public interface ICrudModel&lt;T, Tk&gt;\n{\n Boolean Create(T obj);\n T Retrieve(Tk key);\n Boolean Update(T obj);\n Boolean Delete(T obj);\n}\n</code></pre>\n\n<p>Currently, I write the static classes that contain these methods without any kind of checking to make sure that I haven't forgotten anything. Is like the bad old days of programming before OOP.</p>\n" }, { "answer_id": 34865307, "author": "Daniel Barbalace", "author_id": 4076267, "author_profile": "https://Stackoverflow.com/users/4076267", "pm_score": 1, "selected": false, "text": "<p>C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.</p>\n\n<p>That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.</p>\n" }, { "answer_id": 44871347, "author": "Sanjeev Saraswat", "author_id": 8244223, "author_profile": "https://Stackoverflow.com/users/8244223", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>As per Object oriented concept Interface implemented by classes and\n have contract to access these implemented function(or methods) using\n object.</p>\n</blockquote>\n\n<p>So if you want to access Interface Contract methods you have to create object. It is always must that is not allowed in case of Static methods. Static classes ,method and variables never require objects and load in memory without creating object of that area(or class) or you can say do not require Object Creation.</p>\n" }, { "answer_id": 50700464, "author": "Vinay Chanumolu", "author_id": 9821585, "author_profile": "https://Stackoverflow.com/users/9821585", "pm_score": -1, "selected": false, "text": "<p>When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.</p>\n" }, { "answer_id": 56137022, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p><strong><em>Conceptually</em></strong> there is no reason why an interface could not define a contract that includes static methods.</p>\n\n<p>For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If \"class SomeBaseClass\" implements \"interface ISomeInterface\" and \"class SomeDerivedClass : SomeBaseClass, ISomeInterface\" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).</p>\n\n<p>A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.</p>\n\n<p>So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be \"upgraded\" to support static method contracts (interfaces).</p>\n" }, { "answer_id": 68374839, "author": "Wolfgang Grinfeld", "author_id": 6522669, "author_profile": "https://Stackoverflow.com/users/6522669", "pm_score": 1, "selected": false, "text": "<p>Static Methods within an Interface are allowed as of c# 9 (see <a href=\"https://www.dotnetcurry.com/csharp/simpler-code-with-csharp-9\" rel=\"nofollow noreferrer\">https://www.dotnetcurry.com/csharp/simpler-code-with-csharp-9</a>).</p>\n" }, { "answer_id": 70913376, "author": "unknown6656", "author_id": 3902603, "author_profile": "https://Stackoverflow.com/users/3902603", "pm_score": 3, "selected": false, "text": "<h1>Actually, it does.</h1>\n<p>As of Mid-2022, the current version of C# has full support for so-called <code>static abstract</code> members:</p>\n<pre><code>interface INumber&lt;T&gt;\n{\n static abstract T Zero { get; }\n}\n\nstruct Fraction : INumber&lt;Fraction&gt;\n{\n public static Fraction Zero { get; } = new Fraction();\n\n public long Numerator;\n public ulong Denominator;\n\n ....\n}\n</code></pre>\n<p>Please note that depending on your version of Visual Studio and your installed .NET SDK, you'll either have to update at least one of them (or maybe both), or that you'll have to enable preview features (see <a href=\"https://stackoverflow.com/questions/56639685/use-preview-features-preview-language-in-visual-studio\">Use preview features &amp; preview language in Visual Studio</a>).</p>\n<p>See more:</p>\n<ul>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members</a></li>\n<li><a href=\"https://blog.ndepend.com/c-11-static-abstract-members/\" rel=\"nofollow noreferrer\">https://blog.ndepend.com/c-11-static-abstract-members/</a></li>\n<li><a href=\"https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces#:%7E:text=Static%20abstract%20members%20allow%20each,like%20any%20other%20interface%20definition\" rel=\"nofollow noreferrer\">https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces#:~:text=Static%20abstract%20members%20allow%20each,like%20any%20other%20interface%20definition</a>.</li>\n</ul>\n" }, { "answer_id": 74255218, "author": "user20373360", "author_id": 20373360, "author_profile": "https://Stackoverflow.com/users/20373360", "pm_score": 0, "selected": false, "text": "<p>An interface is an OOPS concept, which means every member of the interface should get used through an object or instance. Hence, an interface can not have static methods.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11514/" ]
Why was C# designed this way? As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented. If classes wish to implement that behavour in a shared method, why shouldn't they? Here is an example of what I have in mind: ``` // These items will be displayed in a list on the screen. public interface IListItem { string ScreenName(); ... } public class Animal: IListItem { // All animals will be called "Animal". public static string ScreenName() { return "Animal"; } .... } public class Person: IListItem { private string name; // All persons will be called by their individual names. public string ScreenName() { return name; } .... } ```
Assuming you are asking why you can't do this: ``` public interface IFoo { void Bar(); } public class Foo: IFoo { public static void Bar() {} } ``` This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface. --- To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation. ``` public class Animal: IListItem { /* Can be tough to come up with a different, yet meaningful name! * A different casing convention, like Java has, would help here. */ public const string AnimalScreenName = "Animal"; public string ScreenName(){ return AnimalScreenName; } } ``` For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.
259,031
<p>Consider that I have a transaction:</p> <pre><code>BEGIN TRANSACTION DECLARE MONEY @amount SELECT Amount AS @amount FROM Deposits WHERE UserId = 123 UPDATE Deposits SET Amount = @amount + 100.0 WHERE UserId = 123 COMMIT </code></pre> <p>And it gets executed on 2 threads, in the order:</p> <ol> <li>thread 1 - select</li> <li>thread 2 - select</li> <li>thread 1 - update</li> <li>thread 2 - update</li> </ol> <p>Assume that before execution Amount is 0.</p> <p>What will happen in this case in the different settings of SQL Server (read uncommited, read commited, repeatable read, serializable), what will be amount at the end, will there be a deadlock?</p>
[ { "answer_id": 259097, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I believe that you would want to use Repeatable read, which would lock the records, the first select would get the value, then it would update blocking thread two until it was completed. Thus an end result of 200 in your example</p>\n\n<p>Read uncommitted would result in both records setting the value to 100.</p>\n\n<p>Read committed might have a bit of an intersting result, depending on timing of the two threads....</p>\n\n<p>Here is a nice article I found about <a href=\"http://blogs.msdn.com/craigfr/archive/2007/05/09/repeatable-read-isolation-level.aspx\" rel=\"nofollow noreferrer\">Repeatable Read</a> as well, that provides a good example</p>\n" }, { "answer_id": 259399, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "<p>Yes, you probably want repeatable read. </p>\n\n<p>I'd probably handle this via optimistic locking wherein you only update if the existing value is the same as it was when you read (test-and-set). If the value isn't the same, raise an error. This allows you to run read-uncommitted, without deadlocks, and without data corruption.</p>\n\n<pre><code>BEGIN TRANSACTION\nDECLARE MONEY @amount\nSELECT Amount AS @amount\n FROM Deposits\n WHERE UserId = 123\nUPDATE Deposits\n SET Amount = @amount + 100.0\n WHERE UserId = 123 AND Amount = @amount\nIF @@ROWCOUNT &lt;&gt; 1 BEGIN ROLLBACK; RAISERROR(...) END\nELSE COMMIT END\n</code></pre>\n" }, { "answer_id": 259423, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 2, "selected": false, "text": "<p>Others already addressed the issue of using REPEATABLE READ.</p>\n\n<p>So I'll chime in with a different piece of advice...</p>\n\n<p>Why use two statements and not just one statement like the following?</p>\n\n<pre><code>UPDATE Deposits\nSET Amount = Amount + 100.0\nWHERE UserId = 123\n</code></pre>\n\n<p>Also, your real transactions are going off of something more than a UserID, right? If not, you run the risk of working with more records than you originally intended.</p>\n" }, { "answer_id": 259505, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "<p>Nice well stated scenario. I decided to test it.</p>\n\n<p>Here's my setup script:</p>\n\n<pre><code>CREATE TABLE Deposits(Amount Money, UserID int)\nINSERT INTO Deposits (Amount, UserID)\nSELECT 0.0, 123\n--Reset\nUPDATE Deposits\nSET Amount = 0.00\nWHERE UserID = 123\n</code></pre>\n\n<p>Here's my test script.</p>\n\n<pre><code>SET TRANSACTION ISOLATION LEVEL Serializable\n----------------------------------------\n-- Part 1\n----------------------------------------\nBEGIN TRANSACTION\nDECLARE @amount MONEY\nSET @amount =\n(\nSELECT Amount\nFROM Deposits\nWHERE UserId = 123\n)\nSELECT @amount as Amount\n----------------------------------------\n-- Part 2\n----------------------------------------\nDECLARE @amount MONEY\nSET @amount = *value from step 1*\nUPDATE Deposits\nSET Amount = @amount + 100.0\nWHERE UserId = 123\nCOMMIT\nSELECT *\nFROM Deposits\nWHERE UserID = 123\n</code></pre>\n\n<p>I loaded up this test script in two query analyzer windows and ran each part as described by the question.</p>\n\n<p>All of the reading happens before any of the writing, so all threads/scenarios will read the value of 0 into @amount.</p>\n\n<p>Here are the results:</p>\n\n<p>Read committed</p>\n\n<pre><code>1 T1.@Amount = 0.00\n2 T1.@Amount = 0.00\n3 Deposits.Amount = 100.00\n4 Deposits.Amount = 100.00\n</code></pre>\n\n<p>Read uncommitted</p>\n\n<pre><code>1 T1.@Amount = 0.00\n2 T1.@Amount = 0.00\n3 Deposits.Amount = 100.00\n4 Deposits.Amount = 100.00\n</code></pre>\n\n<p>Repeatable Read</p>\n\n<pre><code>1 T1.@Amount = 0.00 (locks out changes by others on Deposit.UserID = 123)\n2 T1.@Amount = 0.00 (locks out changes by others on Deposit.UserID = 123)\n3 Hangs until step 4. (due to lock in step 2)\n4 Deadlock!\nFinal result: Deposits.Amount = 100.00\n</code></pre>\n\n<p>Serializable</p>\n\n<pre><code>1 T1.@Amount = 0.00 (locks out changes by others on Deposit)\n2 T1.@Amount = 0.00 (locks out changes by others on Deposit)\n3 Hangs until step 4. (due to lock in step 2)\n4 Deadlock!\nFinal result: Deposits.Amount = 100.00\n</code></pre>\n\n<p>Here's an explanation of each type which can be used to reach these results through thought simulations.</p>\n\n<p><strong>Read Committed</strong> and <strong>Read Uncommited</strong>, both do not lock the data that was read against modifications by other users. The difference is that read uncommitted will allow you to see data that is not yet committed (downside) and will not block your read if there is data locked by others against reading (upside), which is really saying the same thing twice.</p>\n\n<p><strong>Repeatable Read</strong> and <strong>Serializable</strong>, both behave like read committed for reading. For locking, both lock data which has been read against modification by other users. The difference is that serializable blocks more than the row which has been read, it also blocks inserts that would introduce records that were not present before.</p>\n\n<p>So with repeatable read, you could see new records (termed : phantom records) in later reads. With serializable, you block the creation of those records until you commit.</p>\n\n<p>The above explanations come from my interpretation of this <a href=\"http://msdn.microsoft.com/en-us/library/aa259216(SQL.80).aspx\" rel=\"nofollow noreferrer\">msdn</a> article.</p>\n" }, { "answer_id": 259520, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 1, "selected": false, "text": "<p>Otherwise you can use locking hint to avoid deadlocks (in case you have server in read commited mode):</p>\n\n<pre><code>BEGIN TRANSACTION\nDECLARE MONEY @amount\nSELECT Amount AS @amount\n FROM Deposits WITH(UPDLOCK)\n WHERE UserId = 123\nUPDATE Deposits\n SET Amount = @amount + 100.0\n WHERE UserId = 123\nCOMMIT\n</code></pre>\n\n<p>In this specific procedure of course single statement (like Kevin Fairchild posted) is preferred and doesn't cause side effects, but in more complex situations UPDLOCK hint may become handy.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6176/" ]
Consider that I have a transaction: ``` BEGIN TRANSACTION DECLARE MONEY @amount SELECT Amount AS @amount FROM Deposits WHERE UserId = 123 UPDATE Deposits SET Amount = @amount + 100.0 WHERE UserId = 123 COMMIT ``` And it gets executed on 2 threads, in the order: 1. thread 1 - select 2. thread 2 - select 3. thread 1 - update 4. thread 2 - update Assume that before execution Amount is 0. What will happen in this case in the different settings of SQL Server (read uncommited, read commited, repeatable read, serializable), what will be amount at the end, will there be a deadlock?
Nice well stated scenario. I decided to test it. Here's my setup script: ``` CREATE TABLE Deposits(Amount Money, UserID int) INSERT INTO Deposits (Amount, UserID) SELECT 0.0, 123 --Reset UPDATE Deposits SET Amount = 0.00 WHERE UserID = 123 ``` Here's my test script. ``` SET TRANSACTION ISOLATION LEVEL Serializable ---------------------------------------- -- Part 1 ---------------------------------------- BEGIN TRANSACTION DECLARE @amount MONEY SET @amount = ( SELECT Amount FROM Deposits WHERE UserId = 123 ) SELECT @amount as Amount ---------------------------------------- -- Part 2 ---------------------------------------- DECLARE @amount MONEY SET @amount = *value from step 1* UPDATE Deposits SET Amount = @amount + 100.0 WHERE UserId = 123 COMMIT SELECT * FROM Deposits WHERE UserID = 123 ``` I loaded up this test script in two query analyzer windows and ran each part as described by the question. All of the reading happens before any of the writing, so all threads/scenarios will read the value of 0 into @amount. Here are the results: Read committed ``` 1 T1.@Amount = 0.00 2 T1.@Amount = 0.00 3 Deposits.Amount = 100.00 4 Deposits.Amount = 100.00 ``` Read uncommitted ``` 1 T1.@Amount = 0.00 2 T1.@Amount = 0.00 3 Deposits.Amount = 100.00 4 Deposits.Amount = 100.00 ``` Repeatable Read ``` 1 T1.@Amount = 0.00 (locks out changes by others on Deposit.UserID = 123) 2 T1.@Amount = 0.00 (locks out changes by others on Deposit.UserID = 123) 3 Hangs until step 4. (due to lock in step 2) 4 Deadlock! Final result: Deposits.Amount = 100.00 ``` Serializable ``` 1 T1.@Amount = 0.00 (locks out changes by others on Deposit) 2 T1.@Amount = 0.00 (locks out changes by others on Deposit) 3 Hangs until step 4. (due to lock in step 2) 4 Deadlock! Final result: Deposits.Amount = 100.00 ``` Here's an explanation of each type which can be used to reach these results through thought simulations. **Read Committed** and **Read Uncommited**, both do not lock the data that was read against modifications by other users. The difference is that read uncommitted will allow you to see data that is not yet committed (downside) and will not block your read if there is data locked by others against reading (upside), which is really saying the same thing twice. **Repeatable Read** and **Serializable**, both behave like read committed for reading. For locking, both lock data which has been read against modification by other users. The difference is that serializable blocks more than the row which has been read, it also blocks inserts that would introduce records that were not present before. So with repeatable read, you could see new records (termed : phantom records) in later reads. With serializable, you block the creation of those records until you commit. The above explanations come from my interpretation of this [msdn](http://msdn.microsoft.com/en-us/library/aa259216(SQL.80).aspx) article.
259,038
<p>I am trying to fetch an RTSP stream over HTTP using a proxy. The behavior of the Real client seems to be a bit hectic: it tries all the possible ports, methods and protocols at once. The only thing that should work is HTTP GET over port 80. Such a request is indeed issued, and is received on the server. Here's how the request looks when it is sent by the proxy to the server:</p> <pre><code>GET /SmpDsBhgRl83c52ef2-d0f4-41ac-bada-93e5350f67d1?1="1" HTTP/1.0\r\n Connection: Keep-Alive\r\n Host: 10.194.5.162:80\r\n Pragma: no-cache\r\n User-Agent: RealPlayer G2\r\n Expires: Mon, 18 May 1974 00:00:00 GMT\r\n Accept: application/x-rtsp-tunnelled, */*\r\n ClientID: WinNT_5.1_6.0.14.806_RealPlayer_R41UKD_en-GB_686\r\n X-Actual-URL: rtsp://10.194.5.162:554/01.mp3\r\n \r\n </code></pre> <p>Here's the server's response:</p> <pre><code>HTTP/1.0 200 OK\r\n Server: RMServer 1.0\r\n Expires: Mon, 18 May 1974 00:00:00 GMT\r\n Pragma: no-cache\r\n x-server-ipaddress: 10.194.5.162\r\n Content-type: audio/x-pn-realaudio\r\n \r\n </code></pre> <p>At this point 4 more bytes arrive from the server (their values are 48 02 02 00) - and that's it, nothing more. Does the server expect anything from the client at this point, and if so - what? Does this mode of operation work at all?</p> <p>Some more info on this problem: apparently, the intended mechanism of working with RTSP over HTTP built into RealPlayer is as follows:</p> <ol> <li>Try to connect to the following ports: 80, 8080, 554, 7070. (Try also to download the file directly, just for the heck of it, by issuing GET <a href="http://hostname:port/mediafilename" rel="nofollow noreferrer">http://hostname:port/mediafilename</a> on port 80)</li> <li>For each of the above ports, create 2 connections. </li> <li>Send a GET request to one of the connections to the url <a href="http://hostname:port/SmpDsBhgRl" rel="nofollow noreferrer">http://hostname:port/SmpDsBhgRl</a><code>&lt;guid&gt;</code>?1="1", where <code>&lt;guid&gt;</code> is, yes, a freshly created GUID. Add a header to this request called X-Actual-URL containing the original RTSP URL.</li> <li>Send a POST request on the other connection, to the URL <a href="http://hostname:port/SmpDsBhgRl" rel="nofollow noreferrer">http://hostname:port/SmpDsBhgRl</a> with the GUID above as part of the body of the request. Send a Content-Length header of 32767 bytes, to prevent the proxy from closing the connection prematurely.</li> <li>Start issuing commands to the server through the POST request, and get the corresponding RTSP stream as part of the GET response.</li> </ol> <p>The strange stuff (if the above isn't strange enough) is that, for example, it works with Squid, but not if you use either of the ports 3128 or 8080! Somehow, the client uses the port it connects to to decide on the order of the requests or on when a request should be canceled, but anyway, as hard to believe as it is, it works with proxy port 9090, 3129, 8081, but not with 3128 or 8080.</p> <p>Update #2: <a href="https://helixcommunity.org/viewcvs/protocol/common/util/hxcloakedsocket.cpp?view=markup" rel="nofollow noreferrer">Here</a>'s the source of the RealPlayer with the explanation of the above behavior. Still no solution though.</p> <p>Update #3: OK, in the light of the above, the magic value of 48 02 02 00 is clear: 48 == 'h' is for <code>HTTP_RESPONSE</code>, the next 02 is the length of the following data, the next 02 is called <code>POST_NOT_RECEIVED</code> (meaning that the POST request did not reach the server within a second from the corresponding GET request).</p> <p>Update #4: This behavior (i.e. POST requests with huge Content-Length) is also characteristic of an ActiveX used by WebEx (and, possibly, many other web apps that need an open channel to the server).</p>
[ { "answer_id": 260232, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "<ol>\n<li>See whether issuing the same request but bypassing the proxy (e.g., replay the request you posted above using Netcat) results in more than four bytes streamed in the response body.</li>\n<li>See what TCP packets the proxy is receiving, for example, by eavesdropping on the TCP \ntraffic on the machine that's running the proxy, say, using Wireshark.</li>\n</ol>\n" }, { "answer_id": 265889, "author": "Ori Pessach", "author_id": 9047, "author_profile": "https://Stackoverflow.com/users/9047", "pm_score": 2, "selected": false, "text": "<p>First, you might want to read this:</p>\n\n<p><a href=\"http://developer.apple.com/quicktime/icefloe/dispatch028.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/quicktime/icefloe/dispatch028.html</a></p>\n\n<p>Second, the HTTP requests (both GET and POST) need to be formatted so that they get proxied properly. I've seen proxies that insist on caching too much of the POST request, preventing it from reaching the server. Those proxies are buggy, but there's nothing you can do about that, and I was not able to work around that issue. Mostly I've seen this with anti-virus software that attempts to do transparent proxying of POST requests coming from the browser to scan them for private information like social security numbers. You might be running into the same problem.</p>\n\n<p>Are you using McAfee's anti virus by any chance?</p>\n\n<p>Also, it appears that Real invented its own way of doing the same thing, but the basic design is very similar - GET for the downstream link, POST for the upstream, with some magic cookie (in this case, the GUID) to tie the two together on the server. Either way, the POST should get to the server, and in your case it seems like it doesn't.</p>\n\n<p>By the way, since the problem seems to be with the POST request not going through the proxy, how about posting that request, in addition to the GET?</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29402/" ]
I am trying to fetch an RTSP stream over HTTP using a proxy. The behavior of the Real client seems to be a bit hectic: it tries all the possible ports, methods and protocols at once. The only thing that should work is HTTP GET over port 80. Such a request is indeed issued, and is received on the server. Here's how the request looks when it is sent by the proxy to the server: ``` GET /SmpDsBhgRl83c52ef2-d0f4-41ac-bada-93e5350f67d1?1="1" HTTP/1.0\r\n Connection: Keep-Alive\r\n Host: 10.194.5.162:80\r\n Pragma: no-cache\r\n User-Agent: RealPlayer G2\r\n Expires: Mon, 18 May 1974 00:00:00 GMT\r\n Accept: application/x-rtsp-tunnelled, */*\r\n ClientID: WinNT_5.1_6.0.14.806_RealPlayer_R41UKD_en-GB_686\r\n X-Actual-URL: rtsp://10.194.5.162:554/01.mp3\r\n \r\n ``` Here's the server's response: ``` HTTP/1.0 200 OK\r\n Server: RMServer 1.0\r\n Expires: Mon, 18 May 1974 00:00:00 GMT\r\n Pragma: no-cache\r\n x-server-ipaddress: 10.194.5.162\r\n Content-type: audio/x-pn-realaudio\r\n \r\n ``` At this point 4 more bytes arrive from the server (their values are 48 02 02 00) - and that's it, nothing more. Does the server expect anything from the client at this point, and if so - what? Does this mode of operation work at all? Some more info on this problem: apparently, the intended mechanism of working with RTSP over HTTP built into RealPlayer is as follows: 1. Try to connect to the following ports: 80, 8080, 554, 7070. (Try also to download the file directly, just for the heck of it, by issuing GET <http://hostname:port/mediafilename> on port 80) 2. For each of the above ports, create 2 connections. 3. Send a GET request to one of the connections to the url <http://hostname:port/SmpDsBhgRl>`<guid>`?1="1", where `<guid>` is, yes, a freshly created GUID. Add a header to this request called X-Actual-URL containing the original RTSP URL. 4. Send a POST request on the other connection, to the URL <http://hostname:port/SmpDsBhgRl> with the GUID above as part of the body of the request. Send a Content-Length header of 32767 bytes, to prevent the proxy from closing the connection prematurely. 5. Start issuing commands to the server through the POST request, and get the corresponding RTSP stream as part of the GET response. The strange stuff (if the above isn't strange enough) is that, for example, it works with Squid, but not if you use either of the ports 3128 or 8080! Somehow, the client uses the port it connects to to decide on the order of the requests or on when a request should be canceled, but anyway, as hard to believe as it is, it works with proxy port 9090, 3129, 8081, but not with 3128 or 8080. Update #2: [Here](https://helixcommunity.org/viewcvs/protocol/common/util/hxcloakedsocket.cpp?view=markup)'s the source of the RealPlayer with the explanation of the above behavior. Still no solution though. Update #3: OK, in the light of the above, the magic value of 48 02 02 00 is clear: 48 == 'h' is for `HTTP_RESPONSE`, the next 02 is the length of the following data, the next 02 is called `POST_NOT_RECEIVED` (meaning that the POST request did not reach the server within a second from the corresponding GET request). Update #4: This behavior (i.e. POST requests with huge Content-Length) is also characteristic of an ActiveX used by WebEx (and, possibly, many other web apps that need an open channel to the server).
First, you might want to read this: <http://developer.apple.com/quicktime/icefloe/dispatch028.html> Second, the HTTP requests (both GET and POST) need to be formatted so that they get proxied properly. I've seen proxies that insist on caching too much of the POST request, preventing it from reaching the server. Those proxies are buggy, but there's nothing you can do about that, and I was not able to work around that issue. Mostly I've seen this with anti-virus software that attempts to do transparent proxying of POST requests coming from the browser to scan them for private information like social security numbers. You might be running into the same problem. Are you using McAfee's anti virus by any chance? Also, it appears that Real invented its own way of doing the same thing, but the basic design is very similar - GET for the downstream link, POST for the upstream, with some magic cookie (in this case, the GUID) to tie the two together on the server. Either way, the POST should get to the server, and in your case it seems like it doesn't. By the way, since the problem seems to be with the POST request not going through the proxy, how about posting that request, in addition to the GET?
259,063
<h3>Problem</h3> <p>I've got a collection of <code>IThing</code>s and I'd like to create a <code>HierarchicalDataTemplate</code> for a <code>TreeView</code>. The straightforward <code>DataType={x:Type local:IThing}</code> of course doesn't work, probably because the WPF creators didn't want to handle the possible ambiguities.</p> <p>Since this should handle <code>IThing</code>s from different sources at the same time, referencing the implementing class is out of question. </p> <h3>Current solution</h3> <p>For now I'm using a ViewModel which proxies IThing through a concrete implementation:</p> <pre><code>public interface IThing { string SomeString { get; } ObservableCollection&lt;IThing&gt; SomeThings { get; } // many more stuff } public class IThingViewModel { public IThing Thing { get; } public IThingViewModel(IThing it) { this.Thing = it; } } &lt;!-- is never applied --&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:IThing}"&gt; &lt;!-- is applied, but looks strange --&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:IThingViewModel}" ItemsSource="{Binding Thing.SomeThings}"&gt; &lt;TextBox Text="{Binding Thing.SomeString}"/&gt; &lt;/HierarchicalDataTemplate&gt; </code></pre> <h3>Question</h3> <p>Is there a better (i.e. no proxy) way?</p>
[ { "answer_id": 371948, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>The reason for this is that the default template selector supports only concrete types, not interfaces. You need to create a custom DataTemplateSelector and apply it to the ItemTemplateSelector property of the TreeView. I can't find the URL where I found an example of it, but hopefully with this info, you can Google it.</p>\n" }, { "answer_id": 2565665, "author": "jing boxian", "author_id": 307538, "author_profile": "https://Stackoverflow.com/users/307538", "pm_score": 2, "selected": false, "text": "<p>Another solution is you give a key to the HierarchicalDataTemplate and put it in the Windows.Resources, and manually reference to it in the TreeView. <code>&lt;TreeView ItemDataTemplate={StaticResource templateKey}/&gt;</code> </p>\n\n<p>But that limits the autoselection of data template according to data type, which is provided by WPF TreeView.</p>\n" }, { "answer_id": 9804166, "author": "Daniel Rose", "author_id": 318317, "author_profile": "https://Stackoverflow.com/users/318317", "pm_score": 3, "selected": false, "text": "<p>Another alternative (similar to jing's solution): If you only have one type of item, you can set the ItemTemplate directly. Then you don't need to set a key or a datatype.</p>\n\n<p>In your ViewModel:</p>\n\n<pre><code>public ObservableCollection&lt;IThing&gt; Thingies { get; private set; }\n</code></pre>\n\n<p>In the View:</p>\n\n<pre><code>&lt;TreeView ItemsSource=\"{Binding Thingies}\"&gt;\n &lt;TreeView.ItemTemplate&gt;\n &lt;HierarchicalDataTemplate ItemsSource=\"{Binding SomeThings}\"&gt;\n &lt;TextBox Text=\"{Binding SomeString}\" /&gt; \n &lt;/HierarchicalDataTemplate&gt;\n &lt;/TreeView.ItemTemplate&gt;\n&lt;/TreeView&gt;\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ]
### Problem I've got a collection of `IThing`s and I'd like to create a `HierarchicalDataTemplate` for a `TreeView`. The straightforward `DataType={x:Type local:IThing}` of course doesn't work, probably because the WPF creators didn't want to handle the possible ambiguities. Since this should handle `IThing`s from different sources at the same time, referencing the implementing class is out of question. ### Current solution For now I'm using a ViewModel which proxies IThing through a concrete implementation: ``` public interface IThing { string SomeString { get; } ObservableCollection<IThing> SomeThings { get; } // many more stuff } public class IThingViewModel { public IThing Thing { get; } public IThingViewModel(IThing it) { this.Thing = it; } } <!-- is never applied --> <HierarchicalDataTemplate DataType="{x:Type local:IThing}"> <!-- is applied, but looks strange --> <HierarchicalDataTemplate DataType="{x:Type local:IThingViewModel}" ItemsSource="{Binding Thing.SomeThings}"> <TextBox Text="{Binding Thing.SomeString}"/> </HierarchicalDataTemplate> ``` ### Question Is there a better (i.e. no proxy) way?
The reason for this is that the default template selector supports only concrete types, not interfaces. You need to create a custom DataTemplateSelector and apply it to the ItemTemplateSelector property of the TreeView. I can't find the URL where I found an example of it, but hopefully with this info, you can Google it.
259,111
<p>I'm running in a strange issue. My controller calls a drb object</p> <pre><code>@request_handler = DRbObject.new(nil, url) availability_result = @request_handler.fetch_availability(request, @reservation_search, params[:selected_room_rates]) </code></pre> <p>and this Drb object is making some searches.</p> <p>but sometimes, in a linux environments, I get a "0xdba87b30 is recycled object" with this stacktrace</p> <pre><code>--- - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:375:in `_id2ref' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:375:in `to_obj' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1402:in `to_obj' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1704:in `to_obj' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:613:in `recv_request' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:911:in `recv_request' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1530:in `init_with_client' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1542:in `setup_message' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1494:in `perform' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1589:in `main_loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1585:in `loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1585:in `main_loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1581:in `start' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1581:in `main_loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1430:in `run' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1427:in `start' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1427:in `run' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1347:in `initialize' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1627:in `new' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1627:in `start_service' - (druby://10.254.143.159:9001) ./core/request_handler.rb:244 - (druby://10.254.143.159:9001) /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' - (druby://10.254.143.159:9001) /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' - (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' - (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' - (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' - (druby://10.254.143.159:9001) core/request_handler.rb:31 - (druby://10.254.143.159:9001) core/request_handler.rb:29:in `each' - (druby://10.254.143.159:9001) core/request_handler.rb:29 - app/drops/room_drop.rb:18:in `room_rates' - lib/liquid/liquid_templates.rb:47:in `parse_template' - lib/liquid/liquid_templates.rb:21:in `render_liquid_template_without_layout' - app/helpers/skins_helper.rb:6:in `render_respond_by_format' - app/helpers/skins_helper.rb:4:in `render_respond_by_format' - app/helpers/skins_helper.rb:25:in `render_availability_action' - app/controllers/web_reservations_controller.rb:109:in `availability_simplified' - /usr/bin/mongrel_rails:19:in `load' - /usr/bin/mongrel_rails:19 </code></pre> <p>The strange thing is that I can't reproduce the error in my (windows) development machine, but I get it only in my linux testing server (2 mongrels instead of one in my machine).</p> <p>What's wrong? I think it is a garbage collector problem (object collected before reusing it), but I don't understand where I'm doing something wrong. I simply create the object in my controller and call a method on it.</p> <p>Any idea?</p> <p>Thanks! Roberto</p>
[ { "answer_id": 299258, "author": "Max Caceres", "author_id": 4842, "author_profile": "https://Stackoverflow.com/users/4842", "pm_score": 0, "selected": false, "text": "<p>Is it possible you are calling DRb.start_service more than once in the server?</p>\n" }, { "answer_id": 367394, "author": "Ripta Pasay", "author_id": 46227, "author_profile": "https://Stackoverflow.com/users/46227", "pm_score": 4, "selected": true, "text": "<p>The error means that you're trying to serve an object that's been garbage collected, which usually happens because the object went out of scope on the <strong>server</strong>.</p>\n\n<p>Your safest bet is figuring out why the object was prematurely garbage-collected in the first place. Alternatively, you could disable the server's GC by calling <code>GC.disable</code>, which is usually a bad idea, especially if your server is long-running.</p>\n" }, { "answer_id": 54403314, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 2, "selected": false, "text": "<p>There is a way to delay garbage collection <strong>for the object passed to the client</strong> on the server:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code> DRb.install_id_conv TimerIdConv.new 60 # one minute\n</code></pre>\n\n<p>See <a href=\"https://ruby-doc.org/stdlib-2.5.3/libdoc/drb/rdoc/DRb/TimerIdConv.html\" rel=\"nofollow noreferrer\">https://ruby-doc.org/stdlib-2.5.3/libdoc/drb/rdoc/DRb/TimerIdConv.html</a> </p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22083/" ]
I'm running in a strange issue. My controller calls a drb object ``` @request_handler = DRbObject.new(nil, url) availability_result = @request_handler.fetch_availability(request, @reservation_search, params[:selected_room_rates]) ``` and this Drb object is making some searches. but sometimes, in a linux environments, I get a "0xdba87b30 is recycled object" with this stacktrace ``` --- - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:375:in `_id2ref' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:375:in `to_obj' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1402:in `to_obj' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1704:in `to_obj' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:613:in `recv_request' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:911:in `recv_request' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1530:in `init_with_client' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1542:in `setup_message' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1494:in `perform' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1589:in `main_loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1585:in `loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1585:in `main_loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1581:in `start' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1581:in `main_loop' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1430:in `run' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1427:in `start' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1427:in `run' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1347:in `initialize' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1627:in `new' - (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1627:in `start_service' - (druby://10.254.143.159:9001) ./core/request_handler.rb:244 - (druby://10.254.143.159:9001) /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' - (druby://10.254.143.159:9001) /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' - (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' - (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' - (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' - (druby://10.254.143.159:9001) core/request_handler.rb:31 - (druby://10.254.143.159:9001) core/request_handler.rb:29:in `each' - (druby://10.254.143.159:9001) core/request_handler.rb:29 - app/drops/room_drop.rb:18:in `room_rates' - lib/liquid/liquid_templates.rb:47:in `parse_template' - lib/liquid/liquid_templates.rb:21:in `render_liquid_template_without_layout' - app/helpers/skins_helper.rb:6:in `render_respond_by_format' - app/helpers/skins_helper.rb:4:in `render_respond_by_format' - app/helpers/skins_helper.rb:25:in `render_availability_action' - app/controllers/web_reservations_controller.rb:109:in `availability_simplified' - /usr/bin/mongrel_rails:19:in `load' - /usr/bin/mongrel_rails:19 ``` The strange thing is that I can't reproduce the error in my (windows) development machine, but I get it only in my linux testing server (2 mongrels instead of one in my machine). What's wrong? I think it is a garbage collector problem (object collected before reusing it), but I don't understand where I'm doing something wrong. I simply create the object in my controller and call a method on it. Any idea? Thanks! Roberto
The error means that you're trying to serve an object that's been garbage collected, which usually happens because the object went out of scope on the **server**. Your safest bet is figuring out why the object was prematurely garbage-collected in the first place. Alternatively, you could disable the server's GC by calling `GC.disable`, which is usually a bad idea, especially if your server is long-running.
259,123
<p>My app has a DataGridView object and a List of type MousePos. MousePos is a custom class that holds mouse X,Y coordinates (of type "Point") and a running count of this position. I have a thread (System.Timers.Timer) that raises an event once every second, checks the mouse position, adds and/or updates the count of the mouse position on this List.</p> <p>I would like to have a similar running thread (again, I think System.Timers.Timer is a good choice) which would again raise an event once a second to automatically Refresh() the DataGridView so that the user can see the data on the screen update. (like TaskManager does.)</p> <p>Unfortunately, calling the DataGridView.Refresh() method results in VS2005 stopping execution and noting that I've run into a cross-threading situation.</p> <p>If I'm understanding correctly, I have 3 threads now:</p> <ul> <li>Primary UI thread</li> <li>MousePos List thread (Timer)</li> <li>DataGridView Refresh thread (Timer)</li> </ul> <p>To see if I could Refresh() the DataGridView on the primary thread, I added a button to the form which called DataGridView.Refresh(), but this (strangely) didn't do anything. I found a topic which seemed to indicate that if I set DataGridView.DataSource = null and back to my List, that it would refresh the datagrid. And indeed this worked, but only thru the button (which gets handled on the primary thread.)</p> <hr> <p>So this question has turned into a two-parter:</p> <ol> <li>Is setting DataGridView.DataSource to null and back to my List an acceptable way to refresh the datagrid? (It seems inefficient to me...)</li> <li>How do I safely do this in a multi-threaded environment?</li> </ol> <hr> <p>Here's the code I've written so far (C#/.Net 2.0)</p> <pre><code>public partial class Form1 : Form { private static List&lt;MousePos&gt; mousePositionList = new List&lt;MousePos&gt;(); private static System.Timers.Timer mouseCheck = new System.Timers.Timer(1000); private static System.Timers.Timer refreshWindow = new System.Timers.Timer(1000); public Form1() { InitializeComponent(); mousePositionList.Add(new MousePos()); // ANSWER! Must have at least 1 entry before binding to DataSource dataGridView1.DataSource = mousePositionList; mouseCheck.Elapsed += new System.Timers.ElapsedEventHandler(mouseCheck_Elapsed); mouseCheck.Start(); refreshWindow.Elapsed += new System.Timers.ElapsedEventHandler(refreshWindow_Elapsed); refreshWindow.Start(); } public void mouseCheck_Elapsed(object source, EventArgs e) { Point mPnt = Control.MousePosition; MousePos mPos = mousePositionList.Find(ByPoint(mPnt)); if (mPos == null) { mousePositionList.Add(new MousePos(mPnt)); } else { mPos.Count++; } } public void refreshWindow_Elapsed(object source, EventArgs e) { //dataGridView1.DataSource = null; // Old way //dataGridView1.DataSource = mousePositionList; // Old way dataGridView1.Invalidate(); // &lt;= ANSWER!! } private static Predicate&lt;MousePos&gt; ByPoint(Point pnt) { return delegate(MousePos mPos) { return (mPos.Pnt == pnt); }; } } public class MousePos { private Point position = new Point(); private int count = 1; public Point Pnt { get { return position; } } public int X { get { return position.X; } set { position.X = value; } } public int Y { get { return position.Y; } set { position.Y = value; } } public int Count { get { return count; } set { count = value; } } public MousePos() { } public MousePos(Point mouse) { position = mouse; } } </code></pre>
[ { "answer_id": 259133, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 3, "selected": false, "text": "<p>You have to update the grid on the main UI thread, like all the other controls. See control.Invoke or Control.BeginInvoke.</p>\n" }, { "answer_id": 259477, "author": "Pretzel", "author_id": 21244, "author_profile": "https://Stackoverflow.com/users/21244", "pm_score": 4, "selected": true, "text": "<p><strong>UPDATE!</strong> -- I <em>partially</em> figured out the answer to <strong>part #1</strong> in the book \"Pro .NET 2.0 Windows Forms and Customer Controls in C#\"</p>\n\n<p>I had originally thought that <strong>Refresh()</strong> wasn't doing anything and that I needed to call the <strong>Invalidate()</strong> method, to tell Windows to repaint my control at it's leisure. (which is usually right away, but if you need a guarantee to repaint it <em>now</em>, then follow up with an immediate call to the Update() method.)</p>\n\n<pre><code> dataGridView1.Invalidate();\n</code></pre>\n\n<p>But, it turns out that the <strong>Refresh()</strong> method is merely an alias for:</p>\n\n<pre><code> dataGridView1.Invalidate(true);\n dataGridView1.Update(); // &lt;== forces immediate redraw\n</code></pre>\n\n<p>The only glitch I found with this was that if there was no data in the dataGridView, no amount of invalidating would refresh the control. I had to reassign the datasource. Then it worked fine after that. But only for the amount of rows (or items in my list) -- If new items were added, the dataGridView would be unaware that there were more rows to display.</p>\n\n<p>So it seems that when binding a source of data (List or Table) to the Datasource, the dataGridView counts the items (rows) and then sets this internally and never checks to see if there are new rows/items or rows/items deleted. This is why re-binding the datasource repeatedly was working before.</p>\n\n<p>Now to figure out how to update the number of rows to display in dataGridView without having to re-bind the datasource... fun, fun, fun! :-)</p>\n\n<hr>\n\n<p>After doing some digging, I think I have my answer to <strong>part #2</strong> of my question (aka. safe Multi-threading):</p>\n\n<p>Rather than using <em>System.Timers.Timer</em>, I found that I should be using <strong>System.Windows.Forms.Timer</strong> instead.</p>\n\n<p>The event occurs such that the method that is used in the Callback automatically happens on the primary thread. No cross-threading issues!</p>\n\n<p>The declaration looks like this:</p>\n\n<pre><code>private static System.Windows.Forms.Timer refreshWindow2;\nrefreshWindow2 = new Timer();\nrefreshWindow2.Interval = 1000;\nrefreshWindow2.Tick += new EventHandler(refreshWindow2_Tick);\nrefreshWindow2.Start();\n</code></pre>\n\n<p>And the method is like this:</p>\n\n<pre><code>private void refreshWindow2_Tick(object sender, EventArgs e)\n{\n dataGridView1.Invalidate();\n}\n</code></pre>\n" }, { "answer_id": 768143, "author": "Fredrik Bonde", "author_id": 45187, "author_profile": "https://Stackoverflow.com/users/45187", "pm_score": 2, "selected": false, "text": "<p>Looks like you have your answer right there!\nJust in cawse you're curious about how to do cross thread calls back to ui:\nAll controls have a Invoke() method (or BEginInvoke()- in case you want to do things asynchronously), this is used to call any method on the control within the context of the main UI thread.\nSo, if you were going to call your datagridview from another thread you would need to do the following:</p>\n\n<pre><code>public void refreshWindow_Elapsed(object source, EventArgs e)\n{\n\n // we use anonymous delgate here as it saves us declaring a named delegate in our class\n // however, as c# type inference sometimes need a bit of 'help' we need to cast it \n // to an instance of MethodInvoker\n dataGridView1.Invoke((MethodInvoker)delegate() { dataGridView1.Invalidate(); });\n}\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21244/" ]
My app has a DataGridView object and a List of type MousePos. MousePos is a custom class that holds mouse X,Y coordinates (of type "Point") and a running count of this position. I have a thread (System.Timers.Timer) that raises an event once every second, checks the mouse position, adds and/or updates the count of the mouse position on this List. I would like to have a similar running thread (again, I think System.Timers.Timer is a good choice) which would again raise an event once a second to automatically Refresh() the DataGridView so that the user can see the data on the screen update. (like TaskManager does.) Unfortunately, calling the DataGridView.Refresh() method results in VS2005 stopping execution and noting that I've run into a cross-threading situation. If I'm understanding correctly, I have 3 threads now: * Primary UI thread * MousePos List thread (Timer) * DataGridView Refresh thread (Timer) To see if I could Refresh() the DataGridView on the primary thread, I added a button to the form which called DataGridView.Refresh(), but this (strangely) didn't do anything. I found a topic which seemed to indicate that if I set DataGridView.DataSource = null and back to my List, that it would refresh the datagrid. And indeed this worked, but only thru the button (which gets handled on the primary thread.) --- So this question has turned into a two-parter: 1. Is setting DataGridView.DataSource to null and back to my List an acceptable way to refresh the datagrid? (It seems inefficient to me...) 2. How do I safely do this in a multi-threaded environment? --- Here's the code I've written so far (C#/.Net 2.0) ``` public partial class Form1 : Form { private static List<MousePos> mousePositionList = new List<MousePos>(); private static System.Timers.Timer mouseCheck = new System.Timers.Timer(1000); private static System.Timers.Timer refreshWindow = new System.Timers.Timer(1000); public Form1() { InitializeComponent(); mousePositionList.Add(new MousePos()); // ANSWER! Must have at least 1 entry before binding to DataSource dataGridView1.DataSource = mousePositionList; mouseCheck.Elapsed += new System.Timers.ElapsedEventHandler(mouseCheck_Elapsed); mouseCheck.Start(); refreshWindow.Elapsed += new System.Timers.ElapsedEventHandler(refreshWindow_Elapsed); refreshWindow.Start(); } public void mouseCheck_Elapsed(object source, EventArgs e) { Point mPnt = Control.MousePosition; MousePos mPos = mousePositionList.Find(ByPoint(mPnt)); if (mPos == null) { mousePositionList.Add(new MousePos(mPnt)); } else { mPos.Count++; } } public void refreshWindow_Elapsed(object source, EventArgs e) { //dataGridView1.DataSource = null; // Old way //dataGridView1.DataSource = mousePositionList; // Old way dataGridView1.Invalidate(); // <= ANSWER!! } private static Predicate<MousePos> ByPoint(Point pnt) { return delegate(MousePos mPos) { return (mPos.Pnt == pnt); }; } } public class MousePos { private Point position = new Point(); private int count = 1; public Point Pnt { get { return position; } } public int X { get { return position.X; } set { position.X = value; } } public int Y { get { return position.Y; } set { position.Y = value; } } public int Count { get { return count; } set { count = value; } } public MousePos() { } public MousePos(Point mouse) { position = mouse; } } ```
**UPDATE!** -- I *partially* figured out the answer to **part #1** in the book "Pro .NET 2.0 Windows Forms and Customer Controls in C#" I had originally thought that **Refresh()** wasn't doing anything and that I needed to call the **Invalidate()** method, to tell Windows to repaint my control at it's leisure. (which is usually right away, but if you need a guarantee to repaint it *now*, then follow up with an immediate call to the Update() method.) ``` dataGridView1.Invalidate(); ``` But, it turns out that the **Refresh()** method is merely an alias for: ``` dataGridView1.Invalidate(true); dataGridView1.Update(); // <== forces immediate redraw ``` The only glitch I found with this was that if there was no data in the dataGridView, no amount of invalidating would refresh the control. I had to reassign the datasource. Then it worked fine after that. But only for the amount of rows (or items in my list) -- If new items were added, the dataGridView would be unaware that there were more rows to display. So it seems that when binding a source of data (List or Table) to the Datasource, the dataGridView counts the items (rows) and then sets this internally and never checks to see if there are new rows/items or rows/items deleted. This is why re-binding the datasource repeatedly was working before. Now to figure out how to update the number of rows to display in dataGridView without having to re-bind the datasource... fun, fun, fun! :-) --- After doing some digging, I think I have my answer to **part #2** of my question (aka. safe Multi-threading): Rather than using *System.Timers.Timer*, I found that I should be using **System.Windows.Forms.Timer** instead. The event occurs such that the method that is used in the Callback automatically happens on the primary thread. No cross-threading issues! The declaration looks like this: ``` private static System.Windows.Forms.Timer refreshWindow2; refreshWindow2 = new Timer(); refreshWindow2.Interval = 1000; refreshWindow2.Tick += new EventHandler(refreshWindow2_Tick); refreshWindow2.Start(); ``` And the method is like this: ``` private void refreshWindow2_Tick(object sender, EventArgs e) { dataGridView1.Invalidate(); } ```
259,126
<p>Is there any way to change the entire width of the horizontal scroll bar on a scrolling div (including the nudge arrows and the handle).</p> <p>EDIT: I only need an IE7 solution - it's for a scrolling DIV on a touch screen terminal</p> <p>Thanks</p> <p>Matt</p>
[ { "answer_id": 259270, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": true, "text": "<p>Actually, I revise my statement... <strong>in IE7</strong>, you <strong>CAN</strong> do some scaling.</p>\n\n<pre><code>&lt;div style=\"zoom:5;font-size:20%;overflow-x:auto;\"&gt;\n Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!\n&lt;/div&gt;\n</code></pre>\n\n<p>zoom tells IE to scale up the contents by 500%, and I've set the font-size to be 1/5 of normal (thus remain the same)... this scales the scrollbars (but it looks a bit ugly at this zoom, since the images are raster based, not vector based.</p>\n" }, { "answer_id": 259296, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 0, "selected": false, "text": "<p>There is a way, but it's IMO not possible with JS or CSS.</p>\n\n<p>If you have access to the terminal in question, you can set the theme property to have a larger scrollbar. It's at Control Panels -> Display -> tab Appearance -> Advanced -> item Scrollbar -> adjust size as desired\n(<a href=\"http://i33.tinypic.com/idt7x1.png\" rel=\"nofollow noreferrer\">screenshot</a>)</p>\n" }, { "answer_id": 259342, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 0, "selected": false, "text": "<p>You may want to roll your own scrollbar - manipulating the position of the div that is being scrolled using Javascript. I've seen it being done with big \"up\" and \"down\" arrows on touchscreen applications before. Using this approach you can style the scrolling control however you prefer to match your design.</p>\n\n<p>Here's a <a href=\"http://blog.paranoidferret.com/index.php/2008/10/24/using-jquery-slider-to-scroll-a-div/\" rel=\"nofollow noreferrer\" title=\"recent example\">recent example</a> that uses jQuery's slider to control a div.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5185/" ]
Is there any way to change the entire width of the horizontal scroll bar on a scrolling div (including the nudge arrows and the handle). EDIT: I only need an IE7 solution - it's for a scrolling DIV on a touch screen terminal Thanks Matt
Actually, I revise my statement... **in IE7**, you **CAN** do some scaling. ``` <div style="zoom:5;font-size:20%;overflow-x:auto;"> Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! </div> ``` zoom tells IE to scale up the contents by 500%, and I've set the font-size to be 1/5 of normal (thus remain the same)... this scales the scrollbars (but it looks a bit ugly at this zoom, since the images are raster based, not vector based.
259,139
<p>Use case:</p> <ol> <li>A does something on his box and gots stuck. He asks B (remote) for support.</li> <li>B logs into the session of A, sees all windows, A was seeing and is able to manipulate the GUI.</li> </ol> <p>If A uses Windows it is very convenient to log into a running session e.g. via VNC. But if A uses Linux, AFAIK, this is not possible. Using VNC requires a "vncserver"-session, which is a separate session. You could get screen captures from remote by querying the X-server, but you cannot press buttons on the screen.</p> <p>Is there some workaround for this?</p>
[ { "answer_id": 259270, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": true, "text": "<p>Actually, I revise my statement... <strong>in IE7</strong>, you <strong>CAN</strong> do some scaling.</p>\n\n<pre><code>&lt;div style=\"zoom:5;font-size:20%;overflow-x:auto;\"&gt;\n Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!\n&lt;/div&gt;\n</code></pre>\n\n<p>zoom tells IE to scale up the contents by 500%, and I've set the font-size to be 1/5 of normal (thus remain the same)... this scales the scrollbars (but it looks a bit ugly at this zoom, since the images are raster based, not vector based.</p>\n" }, { "answer_id": 259296, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 0, "selected": false, "text": "<p>There is a way, but it's IMO not possible with JS or CSS.</p>\n\n<p>If you have access to the terminal in question, you can set the theme property to have a larger scrollbar. It's at Control Panels -> Display -> tab Appearance -> Advanced -> item Scrollbar -> adjust size as desired\n(<a href=\"http://i33.tinypic.com/idt7x1.png\" rel=\"nofollow noreferrer\">screenshot</a>)</p>\n" }, { "answer_id": 259342, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 0, "selected": false, "text": "<p>You may want to roll your own scrollbar - manipulating the position of the div that is being scrolled using Javascript. I've seen it being done with big \"up\" and \"down\" arrows on touchscreen applications before. Using this approach you can style the scrolling control however you prefer to match your design.</p>\n\n<p>Here's a <a href=\"http://blog.paranoidferret.com/index.php/2008/10/24/using-jquery-slider-to-scroll-a-div/\" rel=\"nofollow noreferrer\" title=\"recent example\">recent example</a> that uses jQuery's slider to control a div.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11344/" ]
Use case: 1. A does something on his box and gots stuck. He asks B (remote) for support. 2. B logs into the session of A, sees all windows, A was seeing and is able to manipulate the GUI. If A uses Windows it is very convenient to log into a running session e.g. via VNC. But if A uses Linux, AFAIK, this is not possible. Using VNC requires a "vncserver"-session, which is a separate session. You could get screen captures from remote by querying the X-server, but you cannot press buttons on the screen. Is there some workaround for this?
Actually, I revise my statement... **in IE7**, you **CAN** do some scaling. ``` <div style="zoom:5;font-size:20%;overflow-x:auto;"> Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! </div> ``` zoom tells IE to scale up the contents by 500%, and I've set the font-size to be 1/5 of normal (thus remain the same)... this scales the scrollbars (but it looks a bit ugly at this zoom, since the images are raster based, not vector based.
259,140
<p>How do I search the whole classpath for an annotated class?</p> <p>I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.</p> <p>I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with <code>@WebService</code> or <code>@EJB</code> and the system finds these classes while loading so they are accessible remotely.</p>
[ { "answer_id": 259351, "author": "mfx", "author_id": 8015, "author_profile": "https://Stackoverflow.com/users/8015", "pm_score": 2, "selected": false, "text": "<p>The Classloader API doesn't have an \"enumerate\" method, because class loading is an \"on-demand\" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).</p>\n\n<p>So, even if you <em>could</em> enumerate all classes, this would be very time- and memory-consuming. </p>\n\n<p>The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory. </p>\n" }, { "answer_id": 1415338, "author": "Arthur Ronald", "author_id": 127359, "author_profile": "https://Stackoverflow.com/users/127359", "pm_score": 9, "selected": true, "text": "<p>Use <a href=\"http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html\" rel=\"noreferrer\">org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider</a> </p>\n\n<p>API</p>\n\n<blockquote>\n <p>A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates. </p>\n</blockquote>\n\n<pre><code>ClassPathScanningCandidateComponentProvider scanner =\nnew ClassPathScanningCandidateComponentProvider(&lt;DO_YOU_WANT_TO_USE_DEFALT_FILTER&gt;);\n\nscanner.addIncludeFilter(new AnnotationTypeFilter(&lt;TYPE_YOUR_ANNOTATION_HERE&gt;.class));\n\nfor (BeanDefinition bd : scanner.findCandidateComponents(&lt;TYPE_YOUR_BASE_PACKAGE_HERE&gt;))\n System.out.println(bd.getBeanClassName());\n</code></pre>\n" }, { "answer_id": 3391773, "author": "Jonathan", "author_id": 374664, "author_profile": "https://Stackoverflow.com/users/374664", "pm_score": 7, "selected": false, "text": "<p>And another solution is <a href=\"https://github.com/ronmamo\" rel=\"nofollow noreferrer\">ronmamo's</a> <a href=\"https://github.com/ronmamo/reflections\" rel=\"nofollow noreferrer\">Reflections</a>.</p>\n<p>Quick review:</p>\n<ul>\n<li>Spring solution is the way to go if you're using Spring. Otherwise it's a big dependency.</li>\n<li>Using ASM directly is a bit cumbersome.</li>\n<li>Using Java Assist directly is clunky too.</li>\n<li>Annovention is super lightweight and convenient. No maven integration yet.</li>\n<li>Reflections indexes everything and then is super fast.</li>\n</ul>\n" }, { "answer_id": 8209445, "author": "rmuller", "author_id": 868941, "author_profile": "https://Stackoverflow.com/users/868941", "pm_score": 5, "selected": false, "text": "<p>If you want a really <strong>light weight</strong> (no dependencies, simple API, 15 kb jar file) and <strong>very fast</strong> solution, take a look at <code>annotation-detector</code> found at <a href=\"https://github.com/rmuller/infomas-asl\">https://github.com/rmuller/infomas-asl</a> </p>\n\n<p>Disclaimer: I am the author.</p>\n" }, { "answer_id": 8642568, "author": "Sławek", "author_id": 1116153, "author_profile": "https://Stackoverflow.com/users/1116153", "pm_score": 4, "selected": false, "text": "<p>You can use Java Pluggable Annotation Processing API to write annotation processor which will be executed during the compilation process and will collect all annotated classes and build the index file for runtime use.</p>\n\n<p>This is the fastest way possible to do annotated class discovery because you don't need to scan your classpath at runtime, which is usually very slow operation. Also this approach works with any classloader and not only with URLClassLoaders usually supported by runtime scanners.</p>\n\n<p>The above mechanism is already implemented in <a href=\"https://github.com/atteo/classindex\" rel=\"noreferrer\">ClassIndex</a> library.</p>\n\n<p>To use it annotate your custom annotation with <a href=\"http://www.atteo.org/static/classindex/apidocs/org/atteo/evo/classindex/IndexAnnotated.html\" rel=\"noreferrer\">@IndexAnnotated</a> meta-annotation. This will create at compile time an index file: META-INF/annotations/com/test/YourCustomAnnotation listing all annotated classes. You can acccess the index at runtime by executing:</p>\n\n<pre><code>ClassIndex.getAnnotated(com.test.YourCustomAnnotation.class)\n</code></pre>\n" }, { "answer_id": 11486359, "author": "Martin Aubele", "author_id": 1525977, "author_profile": "https://Stackoverflow.com/users/1525977", "pm_score": 0, "selected": false, "text": "<p>Google <a href=\"http://code.google.com/p/reflections/\" rel=\"nofollow\">Reflections</a> seems to be much faster than Spring. Found this feature request that adresses this difference: <a href=\"http://www.opensaga.org/jira/browse/OS-738\" rel=\"nofollow\">http://www.opensaga.org/jira/browse/OS-738</a></p>\n\n<p>This is a reason to use Reflections as startup time of my application is really important during development. Reflections seems also to be very easy to use for my use case (find all implementers of an interface).</p>\n" }, { "answer_id": 25354394, "author": "Luke Hutchison", "author_id": 3950982, "author_profile": "https://Stackoverflow.com/users/3950982", "pm_score": 5, "selected": false, "text": "<p>You can find classes with any given annotation with <a href=\"https://github.com/classgraph/classgraph\" rel=\"noreferrer\">ClassGraph</a>, as well as searching for other criteria of interest, e.g. classes that implement a given interface. (Disclaimer, I am the author of ClassGraph.) ClassGraph can build an abstract representation of the entire class graph (all classes, annotations, methods, method parameters, and fields) in memory, for all classes on the classpath, or for classes in whitelisted packages, and you can query that class graph however you want. ClassGraph supports <a href=\"https://github.com/classgraph/classgraph/wiki/Classpath-Specification-Mechanisms\" rel=\"noreferrer\">more classpath specification mechanisms and classloaders</a> than any other scanner, and also works seamlessly with the new JPMS module system, so if you base your code on ClassGraph, your code will be maximally portable. <a href=\"https://github.com/classgraph/classgraph/wiki/ClassGraph-API\" rel=\"noreferrer\">See the API here.</a></p>\n" }, { "answer_id": 33091899, "author": "magiccrafter", "author_id": 896981, "author_profile": "https://Stackoverflow.com/users/896981", "pm_score": 2, "selected": false, "text": "<p>With Spring you can also just write the following using AnnotationUtils class. i.e.:</p>\n\n<pre><code>Class&lt;?&gt; clazz = AnnotationUtils.findAnnotationDeclaringClass(Target.class, null);\n</code></pre>\n\n<p>For more details and all different methods check official docs: \n<a href=\"https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/AnnotationUtils.html\" rel=\"nofollow noreferrer\">https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/AnnotationUtils.html</a></p>\n" }, { "answer_id": 47428495, "author": "voucher_wolves", "author_id": 6249539, "author_profile": "https://Stackoverflow.com/users/6249539", "pm_score": 3, "selected": false, "text": "<p>Is it too late to answer. \nI would say, its better to go by Libraries like <a href=\"https://docs.spring.io/spring/docs/2.5.x/javadoc-api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html\" rel=\"noreferrer\">ClassPathScanningCandidateComponentProvider</a> or like <a href=\"http://scannotation.sourceforge.net/\" rel=\"noreferrer\">Scannotations</a></p>\n\n<p>But even after somebody wants to try some hands on it with classLoader, I have written some on my own to print the annotations from classes in a package: </p>\n\n<pre><code>public class ElementScanner {\n\npublic void scanElements(){\n try {\n //Get the package name from configuration file\n String packageName = readConfig();\n\n //Load the classLoader which loads this class.\n ClassLoader classLoader = getClass().getClassLoader();\n\n //Change the package structure to directory structure\n String packagePath = packageName.replace('.', '/');\n URL urls = classLoader.getResource(packagePath);\n\n //Get all the class files in the specified URL Path.\n File folder = new File(urls.getPath());\n File[] classes = folder.listFiles();\n\n int size = classes.length;\n List&lt;Class&lt;?&gt;&gt; classList = new ArrayList&lt;Class&lt;?&gt;&gt;();\n\n for(int i=0;i&lt;size;i++){\n int index = classes[i].getName().indexOf(\".\");\n String className = classes[i].getName().substring(0, index);\n String classNamePath = packageName+\".\"+className;\n Class&lt;?&gt; repoClass;\n repoClass = Class.forName(classNamePath);\n Annotation[] annotations = repoClass.getAnnotations();\n for(int j =0;j&lt;annotations.length;j++){\n System.out.println(\"Annotation in class \"+repoClass.getName()+ \" is \"+annotations[j].annotationType().getName());\n }\n classList.add(repoClass);\n }\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n}\n\n/**\n * Unmarshall the configuration file\n * @return\n */\npublic String readConfig(){\n try{\n URL url = getClass().getClassLoader().getResource(\"WEB-INF/config.xml\");\n JAXBContext jContext = JAXBContext.newInstance(RepositoryConfig.class);\n Unmarshaller um = jContext.createUnmarshaller();\n RepositoryConfig rc = (RepositoryConfig) um.unmarshal(new File(url.getFile()));\n return rc.getRepository().getPackageName();\n }catch(Exception e){\n e.printStackTrace();\n }\n return null;\n\n}\n}\n</code></pre>\n\n<p>And in config File, you put the package name and unmarshall it to a class . </p>\n" }, { "answer_id": 51842140, "author": "dzikoysk", "author_id": 3426515, "author_profile": "https://Stackoverflow.com/users/3426515", "pm_score": 1, "selected": false, "text": "<p>If you're looking for an alternative to <a href=\"https://github.com/ronmamo/reflections\" rel=\"nofollow noreferrer\">reflections</a> I'd like to recommend <a href=\"https://github.com/Panda-Programming-Language/Panda/wiki/Panda-Utilities:-AnnotationsScanner\" rel=\"nofollow noreferrer\">Panda Utilities - AnnotationsScanner</a>. It's a Guava-free (Guava has ~3MB, Panda Utilities has ~200kb) scanner based on the reflections library source code. </p>\n\n<p>It's also dedicated for future-based searches. If you'd like to scan multiple times included sources or even provide an API, which allows someone scanning current classpath, <code>AnnotationsScannerProcess</code> caches all fetched <code>ClassFiles</code>, so it's really fast.</p>\n\n<p>Simple example of <code>AnnotationsScanner</code> usage:</p>\n\n<pre><code>AnnotationsScanner scanner = AnnotationsScanner.createScanner()\n .includeSources(ExampleApplication.class)\n .build();\n\nAnnotationsScannerProcess process = scanner.createWorker()\n .addDefaultProjectFilters(\"net.dzikoysk\")\n .fetch();\n\nSet&lt;Class&lt;?&gt;&gt; classes = process.createSelector()\n .selectTypesAnnotatedWith(AnnotationTest.class);\n</code></pre>\n" }, { "answer_id": 53972609, "author": "madhu_karnati", "author_id": 2333311, "author_profile": "https://Stackoverflow.com/users/2333311", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://github.com/ronmamo/reflections\" rel=\"nofollow noreferrer\">Google Reflection</a> if you want to discover interfaces as well. </p>\n\n<p>Spring <code>ClassPathScanningCandidateComponentProvider</code> is not discovering interfaces.</p>\n" }, { "answer_id": 56339620, "author": "swayamraina", "author_id": 6183182, "author_profile": "https://Stackoverflow.com/users/6183182", "pm_score": 3, "selected": false, "text": "<p>Spring has something called a <code>AnnotatedTypeScanner</code> class. <br>\nThis class internally uses </p>\n\n<pre><code>ClassPathScanningCandidateComponentProvider\n</code></pre>\n\n<p>This class has the code for actual scanning of the <strong>classpath</strong> resources. It does this by using the class metadata available at runtime.<br></p>\n\n<p>One can simply extend this class or use the same class for scanning. Below is the constructor definition.</p>\n\n<pre><code>/**\n * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.\n * \n * @param considerInterfaces whether to consider interfaces as well.\n * @param annotationTypes the annotations to scan for.\n */\n public AnnotatedTypeScanner(boolean considerInterfaces, Class&lt;? extends Annotation&gt;... annotationTypes) {\n\n this.annotationTypess = Arrays.asList(annotationTypes);\n this.considerInterfaces = considerInterfaces;\n }\n</code></pre>\n" }, { "answer_id": 59239204, "author": "Zon", "author_id": 1112963, "author_profile": "https://Stackoverflow.com/users/1112963", "pm_score": 4, "selected": false, "text": "<p>There's a wonderful comment by <a href=\"https://stackoverflow.com/users/1424321/zapp\">zapp</a> that sinks in all those answers:</p>\n\n<pre><code>new Reflections(\"my.package\").getTypesAnnotatedWith(MyAnnotation.class)\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2937/" ]
How do I search the whole classpath for an annotated class? I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation. I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with `@WebService` or `@EJB` and the system finds these classes while loading so they are accessible remotely.
Use [org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html) API > > A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates. > > > ``` ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>); scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class)); for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>)) System.out.println(bd.getBeanClassName()); ```
259,147
<p>I'm using <a href="http://urlrewriter.net/" rel="nofollow noreferrer">http://urlrewriter.net/</a> to rewrite urls at my website. For example, I'm rewriting:</p> <blockquote> <p><a href="http://www.example.com/schedule.aspx?state=ca" rel="nofollow noreferrer">http://www.example.com/schedule.aspx?state=ca</a></p> </blockquote> <p>to</p> <blockquote> <p><a href="http://www.example.com/california.aspx" rel="nofollow noreferrer">http://www.example.com/california.aspx</a></p> </blockquote> <p>What I'm trying to do (for SEO purposes) to to dynamically add the meta tag:</p> <pre><code>&lt;meta name="robots" content="noindex,follow" /&gt; </code></pre> <p><em>only</em> to the page that hasn't been rewritten. This is because I want both URLs to work, but only the rewritten one to be indexed by search engines. </p> <p>How do I determine which version of the page has been requested?</p> <p><strong>EDIT</strong></p> <p>Answers below suggest a 301 redirect instead of using a meta tag. Maybe I'll do this, but I still want to know the answer to the underlying question... how do I know if the page has been rewritten?</p>
[ { "answer_id": 259175, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "<p>If you need to do this you can probably do something like:</p>\n\n<pre><code>&lt;add header=\"X-WasRewritten\" value=\"true\" /&gt;\n</code></pre>\n\n<p>And you can check for the header in your view and add the robots meta tag if you need it.</p>\n\n<p>This will get returned to the client too, so if you want to hide that you can write a CustomAction (<a href=\"http://urlrewriter.net/index.php/support/reference/actions/custom-action\" rel=\"nofollow noreferrer\">http://urlrewriter.net/index.php/support/reference/actions/custom-action</a>) which will set some kind of state value in your request.</p>\n\n<p>However, having two URIs for the same resource is something I would not recommend. I suggest you just keep the one representation. If you're worried about invalidating old bookmarks you can set the old one to redirect to the new one.</p>\n" }, { "answer_id": 259177, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "<p>Most obvious method is to use the Request.Url object in your page to get information about the URL and query string. For example:</p>\n\n<pre><code>if (Path.GetFileName(Request.Url.FilePath) == \"schedule.aspx\")\n //Not rewritten\nelse\n //rewritten\n</code></pre>\n" }, { "answer_id": 259189, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": true, "text": "<p>personally, I would 301 redirect from the un-rewritten one to the re-written one, and only use the single copy of the page. It is easier for users, and from an SEO perspective, you have 1 copy of the content.</p>\n" }, { "answer_id": 274797, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>I think that's the job of <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx\" rel=\"nofollow noreferrer\">HttpContext.Current.Items</a>.</p>\n\n<p>You can save the \"Redirection\" in HttpContext.Current.Items and then in your pages, you can check it for a certain added value.</p>\n\n<p>I believe you can add hooks to urlrewriter.net that could do it, something alongs:</p>\n\n<pre><code>HttpContext.Current.Items[\"Redirected_From\"] = currentUrlHere;\n</code></pre>\n\n<p>And then in your webpages, you could check it by:</p>\n\n<pre><code>if (!string.IsNullOrEmpty(HttpContext.Current.Items[\"Redirected_From\"]))\n // the page's been redirected, do something!\nelse\n // no it's visited normally.\n</code></pre>\n\n<p>I have long since left it for the ASP.NET Routing framework in .NET 3.5 SP1, it is better than urlrewriter.net IMO.</p>\n" }, { "answer_id": 294818, "author": "Chris Fulstow", "author_id": 38126, "author_profile": "https://Stackoverflow.com/users/38126", "pm_score": 2, "selected": false, "text": "<p>Further to chakrit's answer, it looks like UrlRewriter.NET stores the original URL in the HttpContext, in a key called <strong>UrlRewriter.NET.RawUrl</strong>. So, you could try something like:</p>\n\n<pre><code>bool isPageRewritten = \n !string.IsNullOrEmpty(HttpContext.Current.Items[\"UrlRewriter.NET.RawUrl\"]);\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28260/" ]
I'm using <http://urlrewriter.net/> to rewrite urls at my website. For example, I'm rewriting: > > <http://www.example.com/schedule.aspx?state=ca> > > > to > > <http://www.example.com/california.aspx> > > > What I'm trying to do (for SEO purposes) to to dynamically add the meta tag: ``` <meta name="robots" content="noindex,follow" /> ``` *only* to the page that hasn't been rewritten. This is because I want both URLs to work, but only the rewritten one to be indexed by search engines. How do I determine which version of the page has been requested? **EDIT** Answers below suggest a 301 redirect instead of using a meta tag. Maybe I'll do this, but I still want to know the answer to the underlying question... how do I know if the page has been rewritten?
personally, I would 301 redirect from the un-rewritten one to the re-written one, and only use the single copy of the page. It is easier for users, and from an SEO perspective, you have 1 copy of the content.
259,150
<p>I have an incoming soap message wich form is TStream (Delphi7), server that send this soap is in development mode and adds a html header to the message for debugging purposes. Now i need to cut out the html header part from it before i can pass it to soap converter. It starts from the beginning with 'pre' tag and ends with '/pre' tag. Im thinking it should be fairly easy to but i havent done it before in Delphi7, so can someone help me? </p>
[ { "answer_id": 259216, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 1, "selected": false, "text": "<p>Make a new TStream (use TMemoryStream) and move any stuff you want to keep over from one stream to the other with TStream.CopyFrom or the TStream.ReadBuffer/WriteBuffer methods.</p>\n" }, { "answer_id": 259700, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 2, "selected": true, "text": "<p>I think the following code would do what you want, assuming you only have one &lt;pre&gt; block in your document.</p>\n\n<pre><code>function DepreStream(Stm : tStream):tStream;\nvar\n sTemp : String;\n oStrStm : tStringStream;\n i : integer;\nbegin\n oStrStm := tStringStream.create('');\n try\n Stm.Seek(0,soFromBeginning);\n oStrStm.copyfrom(Stm,Stm.Size);\n sTemp := oStrStm.DataString;\n if (Pos('&lt;pre&gt;',sTemp) &gt; 0) and (Pos('&lt;/pre&gt;',sTemp) &gt; 0) then\n begin\n delete(sTemp,Pos('&lt;pre&gt;',sTemp),(Pos('&lt;/pre&gt;',sTemp)-Pos('&lt;pre&gt;',sTemp))+6);\n oStrStm.free;\n oStrStm := tStringStream.Create(sTemp);\n end;\n Result := tMemoryStream.create;\n oStrStm.Seek(0,soFromBeginning);\n Result.CopyFrom(oStrStm,oStrStm.Size);\n Result.Seek(0,soFromBeginning);\n finally\n oStrStm.free;\n end;\nend;\n</code></pre>\n\n<p>Another option I believe would be to use an xml transform to remove the unwanted tags, but I don't do much in the way of transforms so if anyone else wants that torch...</p>\n\n<p><strong>EDIT:</strong> Corrected code so that it works. Teaches me for coding directly into SO rather than into the IDE first.</p>\n" }, { "answer_id": 261192, "author": "Frank Shearar", "author_id": 10259, "author_profile": "https://Stackoverflow.com/users/10259", "pm_score": 0, "selected": false, "text": "<p>An XPath expression of \"<code>//pre[1][1]</code>\" will haul out the first node of the first &lt;pre&gt; tag in the XML message: from your description, that should contain the SOAP message you want.</p>\n\n<p>It's been many years since I last used it, but I think Dieter Koehler's <a href=\"http://www.philo.de/xml/\" rel=\"nofollow noreferrer\">OpenXML library</a> supports XPath.</p>\n" }, { "answer_id": 267277, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 2, "selected": false, "text": "<p>Another solution, more in line with Lars' suggestion and somehow more worked out.<br>\nIt's faster, especially when the size of the Stream is above 100, and even more so on really big ones. It avoids copying to an intermediate string.<br>\n<strong>FilterBeginStream</strong> is simpler and follows the \"specs\" in removing everything up until the end of the header.<br>\n<strong>FilterMiddleStream</strong> does the same as DepreStream, leaving what's before and after the header.</p>\n\n<p><strong>Warning</strong>: this code is for Delphi up to D2007, not D2009. </p>\n\n<pre><code>// returns position of a string token (its 1st char) into a Stream. 0 if not found\nfunction StreamPos(Token: string; AStream: TStream): Int64;\nvar\n TokenLength: Integer;\n StringToMatch: string;\nbegin\n Result := 0;\n TokenLength := Length(Token);\n if TokenLength &gt; 0 then\n begin\n SetLength(StringToMatch, TokenLength);\n while AStream.Read(StringToMatch[1], 1) &gt; 0 do\n begin\n if (StringToMatch[1] = Token[1]) and\n ((TokenLength = 1) or\n ((AStream.Read(StringToMatch[2], Length(Token)-1) = Length(Token)-1) and\n (Token = StringToMatch))) then\n begin\n Result := AStream.Seek(0, soCurrent) - (Length(Token) - 1); // i.e. AStream.Position - (Length(Token) - 1);\n Break;\n end;\n end;\n end;\nend;\n\n// Returns portion of a stream after the end of a tag delimited header. Works for 1st header.\n// Everything preceding the header is removed too. Returns same stream if no valid header detected.\n// Result is True if valid header found and stream has been filtered.\nfunction FilterBeginStream(const AStartTag, AEndTag: string; const AStreamIn, AStreamOut: TStream): Boolean;\nbegin\n AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;\n Result := (StreamPos(AStartTag, TStream(AStreamIn)) &gt; 0) and (StreamPos(AEndTag, AStreamIn) &gt; 0);\n if Result then\n AStreamOut.CopyFrom(AStreamIn, AStreamIn.Size - AStreamIn.Position)\n else\n AStreamOut.CopyFrom(AStreamIn, 0);\nend;\n\n// Returns a stream after removal of a tag delimited portion. Works for 1st encountered tag.\n// Returns same stream if no valid tag detected.\n// Result is True if valid tag found and stream has been filtered.\nfunction FilterMiddleStream(const AStartTag, AEndTag: string; const AStreamIn, AStreamOut: TStream): Boolean;\nvar\n StartPos, EndPos: Int64;\nbegin\n Result := False;\n AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;\n StartPos := StreamPos(AStartTag, TStream(AStreamIn));\n if StartPos &gt; 0 then\n begin\n EndPos := StreamPos(AEndTag, AStreamIn);\n Result := EndPos &gt; 0;\n end;\n if Result then\n begin\n if StartPos &gt; 1 then\n begin\n AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;\n AStreamOut.CopyFrom(AStreamIn, StartPos - 1);\n AStreamIn.Seek(EndPos - StartPos + Length(AEndTag), soCurrent);\n end;\n AStreamOut.CopyFrom(AStreamIn, AStreamIn.Size - AStreamIn.Position);\n end\n else\n AStreamOut.CopyFrom(AStreamIn, 0);\nend;\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26207/" ]
I have an incoming soap message wich form is TStream (Delphi7), server that send this soap is in development mode and adds a html header to the message for debugging purposes. Now i need to cut out the html header part from it before i can pass it to soap converter. It starts from the beginning with 'pre' tag and ends with '/pre' tag. Im thinking it should be fairly easy to but i havent done it before in Delphi7, so can someone help me?
I think the following code would do what you want, assuming you only have one <pre> block in your document. ``` function DepreStream(Stm : tStream):tStream; var sTemp : String; oStrStm : tStringStream; i : integer; begin oStrStm := tStringStream.create(''); try Stm.Seek(0,soFromBeginning); oStrStm.copyfrom(Stm,Stm.Size); sTemp := oStrStm.DataString; if (Pos('<pre>',sTemp) > 0) and (Pos('</pre>',sTemp) > 0) then begin delete(sTemp,Pos('<pre>',sTemp),(Pos('</pre>',sTemp)-Pos('<pre>',sTemp))+6); oStrStm.free; oStrStm := tStringStream.Create(sTemp); end; Result := tMemoryStream.create; oStrStm.Seek(0,soFromBeginning); Result.CopyFrom(oStrStm,oStrStm.Size); Result.Seek(0,soFromBeginning); finally oStrStm.free; end; end; ``` Another option I believe would be to use an xml transform to remove the unwanted tags, but I don't do much in the way of transforms so if anyone else wants that torch... **EDIT:** Corrected code so that it works. Teaches me for coding directly into SO rather than into the IDE first.
259,180
<p>I am trying to get my development environment up and running, and I am having trouble with Tomcat trying to load JSF classes for some reason. My application does not use JSF; in fact, I haven't even deployed my application to tomcat yet. I am getting a number of stack traces in the startup logs and I cannot load the default tomcat homepage when I try to open <a href="http://localhost:8080" rel="nofollow noreferrer">http://localhost:8080</a> (I just get the tomcat 404 page).</p> <p>Here is what the first stack trace is:</p> <pre><code>SEVERE: Error configuring application listener of class com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener java.lang.ClassNotFoundException: com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3712) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4216) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) </code></pre> <p>I also get similar stack traces for the following other classes:</p> <pre><code>com.sun.faces.config.ConfigureListener com.sun.faces.application.WebappLifecycleListener </code></pre> <p>I'm not sure if this is relevant, but I am running Tomcat 5.5.27 with the 1.4 compatibility pack installed, with Java 1.4.2, on Mas OS 10.5.</p> <p>Thanks for any ideas!</p> <p><strong>EDIT:</strong> It seems that each of the default applications that come with Tomcat (host-manager, balancer, tomcat-docs, jsp-examples, etc) was relying on these JSF classes. I removed these default applications, and everything seems to be working.</p> <p>So, my question is now: <strong>Why does tomcat come with applications that don't include their dependencies, and what do I need to do to make those default applicaitons work?</strong></p>
[ { "answer_id": 259250, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 3, "selected": true, "text": "<p>Is your tomcat installation totally clean, or is it one you have inherited?</p>\n\n<p>Check if the webapps contains existing wars/directories which may be referencing JSF classes?</p>\n\n<p>UPDATE: Ah -- I see you found this was the case :-)</p>\n\n<p>Not sure why tomcat doesn't include all its dependencies. Perhaps you downloaded a developer release instead of a stable one?</p>\n" }, { "answer_id": 481056, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You might have to clean the Tomcat work directory.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
I am trying to get my development environment up and running, and I am having trouble with Tomcat trying to load JSF classes for some reason. My application does not use JSF; in fact, I haven't even deployed my application to tomcat yet. I am getting a number of stack traces in the startup logs and I cannot load the default tomcat homepage when I try to open <http://localhost:8080> (I just get the tomcat 404 page). Here is what the first stack trace is: ``` SEVERE: Error configuring application listener of class com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener java.lang.ClassNotFoundException: com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3712) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4216) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) ``` I also get similar stack traces for the following other classes: ``` com.sun.faces.config.ConfigureListener com.sun.faces.application.WebappLifecycleListener ``` I'm not sure if this is relevant, but I am running Tomcat 5.5.27 with the 1.4 compatibility pack installed, with Java 1.4.2, on Mas OS 10.5. Thanks for any ideas! **EDIT:** It seems that each of the default applications that come with Tomcat (host-manager, balancer, tomcat-docs, jsp-examples, etc) was relying on these JSF classes. I removed these default applications, and everything seems to be working. So, my question is now: **Why does tomcat come with applications that don't include their dependencies, and what do I need to do to make those default applicaitons work?**
Is your tomcat installation totally clean, or is it one you have inherited? Check if the webapps contains existing wars/directories which may be referencing JSF classes? UPDATE: Ah -- I see you found this was the case :-) Not sure why tomcat doesn't include all its dependencies. Perhaps you downloaded a developer release instead of a stable one?
259,212
<p>I am trying to find an algorithm to count from 0 to 2<sup>n</sup>-1 but their bit pattern reversed. I care about only n LSB of a word. As you may have guessed I failed.</p> <p>For n=3: </p> <pre><code>000 -&gt; 0 100 -&gt; 4 010 -&gt; 2 110 -&gt; 6 001 -&gt; 1 101 -&gt; 5 011 -&gt; 3 111 -&gt; 7 </code></pre> <p>You get the idea.</p> <p>Answers in pseudo-code is great. Code fragments in any language are welcome, answers without bit operations are preferred.</p> <p>Please don't just post a fragment without even a short explanation or a pointer to a source.</p> <p>Edit: I forgot to add, I already have a naive implementation which just bit-reverses a count variable. In a sense, this method is not really counting.</p>
[ { "answer_id": 259246, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>This solution was originally in binary and converted to conventional math as the requester specified.</p>\n\n<p>It would make more sense as binary, at least the multiply by 2 and divide by 2 should be &lt;&lt; 1 and >> 1 for speed, the additions and subtractions probably don't matter one way or the other.</p>\n\n<p>If you pass in mask instead of nBits, and use bitshifting instead of multiplying or dividing, and change the tail recursion to a loop, this will probably be the most performant solution you'll find since every other call it will be nothing but a single add, it would only be as slow as Alnitak's solution once every 4, maybe even 8 calls.</p>\n\n<pre><code>int incrementBizarre(int initial, int nBits)\n // in the 3 bit example, this should create 100\n mask=2^(nBits-1)\n // This should only return true if the first (least significant) bit is not set\n // if initial is 011 and mask is 100\n // 3 4, bit is not set\n if(initial &lt; mask)\n // If it was not, just set it and bail.\n return initial+ mask // 011 (3) + 100 (4) = 111 (7)\n else\n // it was set, are we at the most significant bit yet?\n // mask 100 (4) / 2 = 010 (2), 001/2 = 0 indicating overflow\n if(mask / 2) &gt; 0\n // No, we were't, so unset it (initial-mask) and increment the next bit\n return incrementBizarre(initial - mask, mask/2)\n else\n // Whoops we were at the most significant bit. Error condition\n throw new OverflowedMyBitsException()\n</code></pre>\n\n<p>Wow, that turned out kinda cool. I didn't figure in the recursion until the last second there.</p>\n\n<p>It feels wrong--like there are some operations that should not work, but they do because of the nature of what you are doing (like it feels like you should get into trouble when you are operating on a bit and some bits to the left are non-zero, but it turns out you can't ever be operating on a bit unless all the bits to the left are zero--which is a very strange condition, but true.</p>\n\n<p>Example of flow to get from 110 to 001 (backwards 3 to backwards 4):</p>\n\n<pre><code>mask 100 (4), initial 110 (6); initial &lt; mask=false; initial-mask = 010 (2), now try on the next bit\nmask 010 (2), initial 010 (2); initial &lt; mask=false; initial-mask = 000 (0), now inc the next bit\nmask 001 (1), initial 000 (0); initial &lt; mask=true; initial + mask = 001--correct answer\n</code></pre>\n" }, { "answer_id": 259254, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 0, "selected": false, "text": "<pre><code>void reverse(int nMaxVal, int nBits)\n{\n int thisVal, bit, out;\n\n // Calculate for each value from 0 to nMaxVal.\n for (thisVal=0; thisVal&lt;=nMaxVal; ++thisVal)\n {\n out = 0;\n\n // Shift each bit from thisVal into out, in reverse order.\n for (bit=0; bit&lt;nBits; ++bit)\n out = (out&lt;&lt;1) + ((thisVal&gt;&gt;bit) &amp; 1)\n\n }\n printf(\"%d -&gt; %d\\n\", thisVal, out);\n}\n</code></pre>\n" }, { "answer_id": 259258, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": true, "text": "<p>This is, I think easiest with bit operations, even though you said this wasn't preferred</p>\n\n<p>Assuming 32 bit ints, here's a nifty chunk of code that can reverse <em>all</em> of the bits without doing it in 32 steps:</p>\n\n<pre><code> unsigned int i;\n i = (i &amp; 0x55555555) &lt;&lt; 1 | (i &amp; 0xaaaaaaaa) &gt;&gt; 1;\n i = (i &amp; 0x33333333) &lt;&lt; 2 | (i &amp; 0xcccccccc) &gt;&gt; 2;\n i = (i &amp; 0x0f0f0f0f) &lt;&lt; 4 | (i &amp; 0xf0f0f0f0) &gt;&gt; 4;\n i = (i &amp; 0x00ff00ff) &lt;&lt; 8 | (i &amp; 0xff00ff00) &gt;&gt; 8;\n i = (i &amp; 0x0000ffff) &lt;&lt; 16 | (i &amp; 0xffff0000) &gt;&gt; 16;\n i &gt;&gt;= (32 - n);\n</code></pre>\n\n<p>Essentially this does an interleaved shuffle of all of the bits. Each time around half of the bits in the value are swapped with the other half.</p>\n\n<p>The last line is necessary to realign the bits so that bin \"n\" is the most significant bit.</p>\n\n<p>Shorter versions of this are possible if \"n\" is &lt;= 16, or &lt;= 8</p>\n" }, { "answer_id": 259319, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>At each step, find the leftmost 0 digit of your value. Set it, and clear all digits to the left of it. If you don't find a 0 digit, then you've overflowed: return 0, or stop, or crash, or whatever you want.</p>\n\n<p>This is what happens on a normal binary increment (by which I mean it's the effect, not how it's implemented in hardware), but we're doing it on the left instead of the right.</p>\n\n<p>Whether you do this in bit ops, strings, or whatever, is up to you. If you do it in bitops, then a clz (or call to an equivalent hibit-style function) on <code>~value</code> might be the most efficient way: __builtin_clz where available. But that's an implementation detail.</p>\n" }, { "answer_id": 259331, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 0, "selected": false, "text": "<p>Maybe increment from 0 to N (the \"usual\" way\") and do ReverseBitOrder() for each iteration. You can find several implementations <a href=\"http://www-graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious\" rel=\"nofollow noreferrer\">here</a> (I like the LUT one the best).\nShould be really quick.</p>\n" }, { "answer_id": 259653, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>Here's an answer in Perl. You don't say what comes after the all ones pattern, so I just return zero. I took out the bitwise operations so that it should be easy to translate into another language.</p>\n\n<pre><code>sub reverse_increment {\n my($n, $bits) = @_;\n\n my $carry = 2**$bits;\n while($carry &gt; 1) {\n $carry /= 2;\n if($carry &gt; $n) {\n return $carry + $n;\n } else {\n $n -= $carry;\n }\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 259666, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "<p>With n as your power of 2 and x the variable you want to step:</p>\n\n<pre><code>(defun inv-step (x n) ; the following is a function declaration\n \"returns a bit-inverse step of x, bounded by 2^n\" ; documentation\n (do ((i (expt 2 (- n 1)) ; loop, init of i\n (/ i 2)) ; stepping of i\n (s x)) ; init of s as x\n ((not (integerp i)) ; breaking condition\n s) ; returned value if all bits are 1 (is 0 then)\n (if (&lt; s i) ; the loop's body: if s &lt; i\n (return-from inv-step (+ s i)) ; -&gt; add i to s and return the result\n (decf s i)))) ; else: reduce s by i\n</code></pre>\n\n<p>I commented it thoroughly as you may not be familiar with this syntax.</p>\n\n<p><em>edit</em>: here is the tail recursive version. It seems to be a little faster, provided that you have a compiler with tail call optimization.</p>\n\n<pre><code>(defun inv-step (x n)\n (let ((i (expt 2 (- n 1))))\n (cond ((= n 1)\n (if (zerop x) 1 0)) ; this is really (logxor x 1) \n ((&lt; x i)\n (+ x i))\n (t\n (inv-step (- x i) (- n 1))))))\n</code></pre>\n" }, { "answer_id": 259727, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 0, "selected": false, "text": "<p>Here's a solution which doesn't actually try to do any addition, but exploits the on/off pattern of the seqence (most sig bit alternates every time, next most sig bit alternates every other time, etc), adjust n as desired:</p>\n\n<pre><code>#define FLIP(x, i) do { (x) ^= (1 &lt;&lt; (i)); } while(0)\n\nint main() {\n int n = 3;\n int max = (1 &lt;&lt; n);\n int x = 0;\n\n for(int i = 1; i &lt;= max; ++i) {\n std::cout &lt;&lt; x &lt;&lt; std::endl;\n /* if n == 3, this next part is functionally equivalent to this:\n *\n * if((i % 1) == 0) FLIP(x, n - 1);\n * if((i % 2) == 0) FLIP(x, n - 2);\n * if((i % 4) == 0) FLIP(x, n - 3);\n */\n for(int j = 0; j &lt; n; ++j) {\n if((i % (1 &lt;&lt; j)) == 0) FLIP(x, n - (j + 1));\n } \n }\n}\n</code></pre>\n" }, { "answer_id": 260068, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "<p>How about adding 1 to the most significant bit, then carrying to the next (less significant) bit, if necessary. You could speed this up by operating on bytes:</p>\n\n<ol>\n<li>Precompute a lookup table for counting in bit-reverse from 0 to 256 (00000000 -> 10000000, 10000000 -> 01000000, ..., 11111111 -> 00000000).</li>\n<li>Set all bytes in your multi-byte number to zero.</li>\n<li>Increment the most significant byte using the lookup table. If the byte is 0, increment the next byte using the lookup table. If the byte is 0, increment the next byte...</li>\n<li>Go to step 3.</li>\n</ol>\n" }, { "answer_id": 14416167, "author": "vaishuraj", "author_id": 1993166, "author_profile": "https://Stackoverflow.com/users/1993166", "pm_score": 0, "selected": false, "text": "<p>When you reverse <code>0 to 2^n-1</code> but their bit pattern reversed, you pretty much cover the entire <code>0-2^n-1</code> sequence</p>\n\n<pre><code>Sum = 2^n * (2^n+1)/2\n</code></pre>\n\n<p><code>O(1)</code> operation. No need to do bit reversals</p>\n" }, { "answer_id": 45531406, "author": "eXtranium", "author_id": 8424358, "author_profile": "https://Stackoverflow.com/users/8424358", "pm_score": 0, "selected": false, "text": "<p>Edit: Of course original poster's question was about to do increment by (reversed) one, which makes things more simple than adding two random values. So nwellnhof's <a href=\"https://stackoverflow.com/questions/259212/counting-reversed-bit-pattern/45531781#45531781\">answer</a> contains the algorithm already.</p>\n\n<hr>\n\n<h3>Summing two bit-reversal values</h3>\n\n<p>Here is one solution in php:</p>\n\n<pre><code>function RevSum ($a,$b) {\n\n // loop until our adder, $b, is zero\n while ($b) {\n\n // get carry (aka overflow) bit for every bit-location by AND-operation\n // 0 + 0 --&gt; 00 no overflow, carry is \"0\"\n // 0 + 1 --&gt; 01 no overflow, carry is \"0\"\n // 1 + 0 --&gt; 01 no overflow, carry is \"0\"\n // 1 + 1 --&gt; 10 overflow! carry is \"1\"\n\n $c = $a &amp; $b;\n\n\n // do 1-bit addition for every bit location at once by XOR-operation\n // 0 + 0 --&gt; 00 result = 0\n // 0 + 1 --&gt; 01 result = 1\n // 1 + 0 --&gt; 01 result = 1\n // 1 + 1 --&gt; 10 result = 0 (ignored that \"1\", already taken care above)\n\n $a ^= $b;\n\n\n // now: shift carry bits to the next bit-locations to be added to $a in\n // next iteration.\n // PHP_INT_MAX here is used to ensure that the most-significant bit of the\n // $b will be cleared after shifting. see link in the side note below.\n\n $b = ($c &gt;&gt; 1) &amp; PHP_INT_MAX;\n\n }\n\n return $a;\n}\n</code></pre>\n\n<p>Side note: See <a href=\"https://stackoverflow.com/questions/26821728/why-does-right-shifting-1-always-gives-1-in-php\">this question</a> about shifting negative values.</p>\n\n<p>And as for test; start from zero and increment value by 8-bit reversed one (10000000):</p>\n\n<pre><code>$value = 0;\n$add = 0x80; // 10000000 &lt;-- \"one\" as bit reversed\n\nfor ($count = 20; $count--;) { // loop 20 times\n printf(\"%08b\\n\", $value); // show value as 8-bit binary\n $value = RevSum($value, $add); // do addition\n}\n</code></pre>\n\n<p>... will output:</p>\n\n<pre><code> 00000000\n 10000000\n 01000000\n 11000000\n 00100000\n 10100000\n 01100000\n 11100000\n 00010000\n 10010000\n 01010000\n 11010000\n 00110000\n 10110000\n 01110000\n 11110000\n 00001000\n 10001000\n 01001000\n 11001000\n</code></pre>\n" }, { "answer_id": 45531781, "author": "nwellnhof", "author_id": 1956010, "author_profile": "https://Stackoverflow.com/users/1956010", "pm_score": 2, "selected": false, "text": "<p>Here's a solution from my <a href=\"https://stackoverflow.com/questions/932079/in-place-bit-reversed-shuffle-on-an-array/40533543#40533543\">answer to a different question</a> that computes the next bit-reversed index without looping. It relies heavily on bit operations, though.</p>\n\n<p>The key idea is that incrementing a number simply flips a sequence of least-significant bits, for example from <code>nnnn0111</code> to <code>nnnn1000</code>. So in order to compute the next bit-reversed index, you have to flip a sequence of most-significant bits. If your target platform has a CTZ (\"count trailing zeros\") instruction, this can be done efficiently.</p>\n\n<p>Example in C using GCC's <code>__builtin_ctz</code>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void iter_reversed(unsigned bits) {\n unsigned n = 1 &lt;&lt; bits;\n\n for (unsigned i = 0, j = 0; i &lt; n; i++) {\n printf(\"%x\\n\", j);\n\n // Compute a mask of LSBs.\n unsigned mask = i ^ (i + 1);\n // Length of the mask.\n unsigned len = __builtin_ctz(~mask);\n // Align the mask to MSB of n.\n mask &lt;&lt;= bits - len;\n // XOR with mask.\n j ^= mask;\n }\n}\n</code></pre>\n\n<p>Without a CTZ instruction, you can also use integer division:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void iter_reversed(unsigned bits) {\n unsigned n = 1 &lt;&lt; bits;\n\n for (unsigned i = 0, j = 0; i &lt; n; i++) {\n printf(\"%x\\n\", j);\n\n // Find least significant zero bit.\n unsigned bit = ~i &amp; (i + 1);\n // Using division to bit-reverse a single bit.\n unsigned rev = (n / 2) / bit;\n // XOR with mask.\n j ^= (n - 1) &amp; ~(rev - 1);\n }\n}\n</code></pre>\n" }, { "answer_id": 59217692, "author": "Marek Basovník", "author_id": 5767740, "author_profile": "https://Stackoverflow.com/users/5767740", "pm_score": 0, "selected": false, "text": "<p>Let assume number 1110101 and our task is to find next one.</p>\n\n<p>1) Find zero on highest position and mark position as <em>index</em>.</p>\n\n<p>111<strong>0</strong>1010 (4th position, so <em>index</em> = 4)</p>\n\n<p>2) Set to zero all bits on position higher than <em>index</em>.</p>\n\n<p><strong>000</strong>01010</p>\n\n<p>3) Change founded zero from step 1) to '1'</p>\n\n<p>000<strong>1</strong>1010</p>\n\n<p>That's it. This is by far the fastest algorithm since most of cpu's has instructions to achieve this very efficiently. Here is a C++ implementation which increment 64bit number in reversed patern.</p>\n\n<pre><code>#include &lt;intrin.h&gt;\nunsigned __int64 reversed_increment(unsigned __int64 number) \n{\n unsigned long index, result;\n _BitScanReverse64(&amp;index, ~number); // returns index of the highest '1' on bit-reverse number (trick to find the highest '0')\n result = _bzhi_u64(number, index); // set to '0' all bits at number higher than index position\n result |= (unsigned __int64) 1 &lt;&lt; index; // changes to '1' bit on index position\n return result;\n}\n</code></pre>\n\n<p>Its not hit your requirements to have \"no bits\" operations, however i fear there is now way how to achieve something similar without them. </p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7988/" ]
I am trying to find an algorithm to count from 0 to 2n-1 but their bit pattern reversed. I care about only n LSB of a word. As you may have guessed I failed. For n=3: ``` 000 -> 0 100 -> 4 010 -> 2 110 -> 6 001 -> 1 101 -> 5 011 -> 3 111 -> 7 ``` You get the idea. Answers in pseudo-code is great. Code fragments in any language are welcome, answers without bit operations are preferred. Please don't just post a fragment without even a short explanation or a pointer to a source. Edit: I forgot to add, I already have a naive implementation which just bit-reverses a count variable. In a sense, this method is not really counting.
This is, I think easiest with bit operations, even though you said this wasn't preferred Assuming 32 bit ints, here's a nifty chunk of code that can reverse *all* of the bits without doing it in 32 steps: ``` unsigned int i; i = (i & 0x55555555) << 1 | (i & 0xaaaaaaaa) >> 1; i = (i & 0x33333333) << 2 | (i & 0xcccccccc) >> 2; i = (i & 0x0f0f0f0f) << 4 | (i & 0xf0f0f0f0) >> 4; i = (i & 0x00ff00ff) << 8 | (i & 0xff00ff00) >> 8; i = (i & 0x0000ffff) << 16 | (i & 0xffff0000) >> 16; i >>= (32 - n); ``` Essentially this does an interleaved shuffle of all of the bits. Each time around half of the bits in the value are swapped with the other half. The last line is necessary to realign the bits so that bin "n" is the most significant bit. Shorter versions of this are possible if "n" is <= 16, or <= 8
259,234
<p>How do I run a function on a loop so all the results go straight into a list and is there a way to run a function which acts on all the values in a list?</p>
[ { "answer_id": 259259, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>This example shows how to do it (run it in an interpreter)</p>\n\n<pre><code>&gt;&gt;&gt; def square(x):\n... return x*x\n...\n&gt;&gt;&gt; a = [1,2,3,4,5,6,7,8,9]\n\n&gt;&gt;&gt; map(square,a)\n[1, 4, 9, 16, 25, 36, 49, 64, 81]\n</code></pre>\n" }, { "answer_id": 259260, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p>Your question needs clarification.</p>\n\n<h3>run a function on a loop</h3>\n\n<pre><code>new_list= [yourfunction(item) for item in a_sequence]\n</code></pre>\n\n<h3>run a function acting on all values in a list</h3>\n\n<p>Your function should have some form of iteration in its code to process all items of a sequence, something like:</p>\n\n<pre><code>def yourfunction(sequence):\n for item in sequence:\n …\n</code></pre>\n\n<p>Then you just call it with a sequence (i.e. a list, a string, an iterator etc)</p>\n\n<pre><code>yourfunction(range(10))\nyourfunction(\"a string\")\n</code></pre>\n\n<p>YMMV.</p>\n" }, { "answer_id": 259266, "author": "gone", "author_id": 26880, "author_profile": "https://Stackoverflow.com/users/26880", "pm_score": 4, "selected": true, "text": "<p>Theres a couple ways to run a function on a loop like that - You can either use a list comprehension</p>\n\n<pre><code>test = list('asdf')\n[function(x) for x in test]\n</code></pre>\n\n<p>and use that result</p>\n\n<p>Or you could use the map function</p>\n\n<pre><code>test = list('asdf')\nmap(function, test)\n</code></pre>\n\n<p>The first answer is more \"pythonic\", while the second is more functional. </p>\n\n<p>EDIT: The second way is also a lot faster, as it's not running arbitrary code to call a function, but directly calling a function using <code>map</code>, which is implemented in C.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33061/" ]
How do I run a function on a loop so all the results go straight into a list and is there a way to run a function which acts on all the values in a list?
Theres a couple ways to run a function on a loop like that - You can either use a list comprehension ``` test = list('asdf') [function(x) for x in test] ``` and use that result Or you could use the map function ``` test = list('asdf') map(function, test) ``` The first answer is more "pythonic", while the second is more functional. EDIT: The second way is also a lot faster, as it's not running arbitrary code to call a function, but directly calling a function using `map`, which is implemented in C.
259,240
<p>I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C.</p> <p>One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this facility with its Keys and Values properties of its Dictionary class. Objective-C's NSDictionary, similarly, has allKeys and allValues.</p> <p>Since I've been "away", Boost has acquired the Range and ForEach libraries, which I am now using extensively. I wondered if between the two there was some facility to do the same, but I haven't been able to find anything.</p> <p>I'm thinking of knocking something up using Boost's iterator adapters, but before I go down that route I thought I'd ask here if anyone knows of such a facility in Boost, or somewhere else ready made?</p>
[ { "answer_id": 259377, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 5, "selected": true, "text": "<p>I don't think there's anything out of the box. You can use boost::make_transform.</p>\n\n<pre><code>template&lt;typename T1, typename T2&gt; T2&amp; take_second(const std::pair&lt;T1, T2&gt; &amp;a_pair) \n{\n return a_pair.second;\n}\n\nvoid run_map_value()\n{\n map&lt;int,string&gt; a_map;\n a_map[0] = \"zero\";\n a_map[1] = \"one\";\n a_map[2] = \"two\";\n copy( boost::make_transform_iterator(a_map.begin(), take_second&lt;int, string&gt;),\n boost::make_transform_iterator(a_map.end(), take_second&lt;int, string&gt;),\n ostream_iterator&lt;string&gt;(cout, \"\\n\")\n );\n}\n</code></pre>\n" }, { "answer_id": 2316626, "author": "klaus triendl", "author_id": 279251, "author_profile": "https://Stackoverflow.com/users/279251", "pm_score": 3, "selected": false, "text": "<p>Continuing David's answer, there's another possibility to put the boile by creating a derived class from boost::transform_iterator. I'm using this solution in my projects:</p>\n\n<pre><code>namespace detail\n{\n\ntemplate&lt;bool IsConst, bool IsVolatile, typename T&gt;\nstruct add_cv_if_c\n{\n typedef T type;\n};\ntemplate&lt;typename T&gt;\nstruct add_cv_if_c&lt;true, false, T&gt;\n{\n typedef const T type;\n};\ntemplate&lt;typename T&gt;\nstruct add_cv_if_c&lt;false, true, T&gt;\n{\n typedef volatile T type;\n};\ntemplate&lt;typename T&gt;\nstruct add_cv_if_c&lt;true, true, T&gt;\n{\n typedef const volatile T type;\n};\n\ntemplate&lt;typename TestConst, typename TestVolatile, typename T&gt;\nstruct add_cv_if: public add_cv_if_c&lt;TestConst::value, TestVolatile::value, T&gt;\n{};\n\n} // namespace detail\n\n\n/** An unary function that accesses the member of class T specified in the MemberPtr template parameter.\n\n The cv-qualification of T is preserved for MemberType\n */\ntemplate&lt;typename T, typename MemberType, MemberType T::*MemberPtr&gt;\nstruct access_member_f\n{\n // preserve cv-qualification of T for T::second_type\n typedef typename detail::add_cv_if&lt;\n std::tr1::is_const&lt;T&gt;, \n std::tr1::is_volatile&lt;T&gt;, \n MemberType\n &gt;::type&amp; result_type;\n\n result_type operator ()(T&amp; t) const\n {\n return t.*MemberPtr;\n }\n};\n\n/** @short An iterator adaptor accessing the member called 'second' of the class the \n iterator is pointing to.\n */\ntemplate&lt;typename Iterator&gt;\nclass accessing_second_iterator: public \n boost::transform_iterator&lt;\n access_member_f&lt;\n // note: we use the Iterator's reference because this type \n // is the cv-qualified iterated type (as opposed to value_type).\n // We want to preserve the cv-qualification because the iterator \n // might be a const_iterator e.g. iterating a const \n // std::pair&lt;&gt; but std::pair&lt;&gt;::second_type isn't automatically \n // const just because the pair is const - access_member_f is \n // preserving the cv-qualification, otherwise compiler errors will \n // be the result\n typename std::tr1::remove_reference&lt;\n typename std::iterator_traits&lt;Iterator&gt;::reference\n &gt;::type, \n typename std::iterator_traits&lt;Iterator&gt;::value_type::second_type, \n &amp;std::iterator_traits&lt;Iterator&gt;::value_type::second\n &gt;, \n Iterator\n &gt;\n{\n typedef boost::transform_iterator&lt;\n access_member_f&lt;\n typename std::tr1::remove_reference&lt;\n typename std::iterator_traits&lt;Iterator&gt;::reference\n &gt;::type, \n typename std::iterator_traits&lt;Iterator&gt;::value_type::second_type, \n &amp;std::iterator_traits&lt;Iterator&gt;::value_type::second\n &gt;, \n Iterator\n &gt; baseclass;\n\npublic:\n accessing_second_iterator(): \n baseclass()\n {}\n\n // note: allow implicit conversion from Iterator\n accessing_second_iterator(Iterator it): \n baseclass(it)\n {}\n};\n</code></pre>\n\n<p>This leads to even cleaner code:</p>\n\n<pre><code>void run_map_value()\n{\n typedef map&lt;int, string&gt; a_map_t;\n a_map_t a_map;\n a_map[0] = \"zero\";\n a_map[1] = \"one\";\n a_map[2] = \"two\";\n\n typedef accessing_second_iterator&lt;a_map_t::const_iterator&gt; ia_t;\n // note: specify the iterator adaptor type explicitly as template type, enabling \n // implicit conversion from begin()/end()\n copy&lt;ia_t&gt;(a_map.begin(), a_map.end(),\n ostream_iterator&lt;string&gt;(cout, \"\\n\")\n );\n}\n</code></pre>\n" }, { "answer_id": 5148170, "author": "Matt Chambers", "author_id": 638445, "author_profile": "https://Stackoverflow.com/users/638445", "pm_score": 5, "selected": false, "text": "<p>Replacing the previous answer, in case anybody else finds this like I did. As of boost 1.43, there are some commonly used range adaptors provided. In this case, you want boost::adaptors::map_values. The relevant example:\n<a href=\"http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html#range.reference.adaptors.reference.map_values.map_values_example\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html#range.reference.adaptors.reference.map_values.map_values_example</a></p>\n" }, { "answer_id": 15143836, "author": "Kibbick", "author_id": 837030, "author_profile": "https://Stackoverflow.com/users/837030", "pm_score": 3, "selected": false, "text": "<p>There is a boost range adaptor for exactly this purpose. \nSee <a href=\"http://www.boost.org/doc/libs/1_53_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html\">http://www.boost.org/doc/libs/1_53_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html</a></p>\n\n<p>(This example cribbed from there)</p>\n\n<pre><code>int main(int argc, const char* argv[])\n{\n using namespace boost::assign;\n using namespace boost::adaptors;\n\n std::map&lt;int,int&gt; input;\n for (int i = 0; i &lt; 10; ++i)\n input.insert(std::make_pair(i, i * 10));\n\n boost::copy(\n input | map_values,\n std::ostream_iterator&lt;int&gt;(std::cout, \",\"));\n\n return 0;\n}\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32136/" ]
I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C. One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this facility with its Keys and Values properties of its Dictionary class. Objective-C's NSDictionary, similarly, has allKeys and allValues. Since I've been "away", Boost has acquired the Range and ForEach libraries, which I am now using extensively. I wondered if between the two there was some facility to do the same, but I haven't been able to find anything. I'm thinking of knocking something up using Boost's iterator adapters, but before I go down that route I thought I'd ask here if anyone knows of such a facility in Boost, or somewhere else ready made?
I don't think there's anything out of the box. You can use boost::make\_transform. ``` template<typename T1, typename T2> T2& take_second(const std::pair<T1, T2> &a_pair) { return a_pair.second; } void run_map_value() { map<int,string> a_map; a_map[0] = "zero"; a_map[1] = "one"; a_map[2] = "two"; copy( boost::make_transform_iterator(a_map.begin(), take_second<int, string>), boost::make_transform_iterator(a_map.end(), take_second<int, string>), ostream_iterator<string>(cout, "\n") ); } ```
259,248
<p>I would like to include a different file depending on the version of GCC. More precisely I want to write:</p> <pre><code>#if GCC_VERSION &gt;= 4.2 # include &lt;unordered_map&gt; # define EXT std #elif GCC_VERSION &gt;= 4 # include &lt;tr1/unordered_map&gt; # define EXT std #else # include &lt;ext/hash_map&gt; # define unordered_map __gnu_cxx::hash_map # define EXT __gnu_cxx #endif </code></pre> <p>I don't care about gcc before 3.2.</p> <p>I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.</p>
[ { "answer_id": 259277, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 6, "selected": false, "text": "<p>There are a number of macros that should be defined for your needs:</p>\n\n<pre><code>__GNUC__ // major\n__GNUC_MINOR__ // minor\n__GNUC_PATCHLEVEL__ // patch\n</code></pre>\n\n<p>The version format is major.minor.patch, e.g. 4.0.2</p>\n\n<p>The documentation for these can be found <a href=\"http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 259279, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 6, "selected": true, "text": "<p>Ok, after more searches, it one possible way of doing it is using <code>__GNUC_PREREQ</code> defined in <code>features.h</code>.</p>\n\n<pre><code>#ifdef __GNUC__\n# include &lt;features.h&gt;\n# if __GNUC_PREREQ(4,0)\n// If gcc_version &gt;= 4.0\n# elif __GNUC_PREREQ(3,2)\n// If gcc_version &gt;= 3.2\n# else\n// Else\n# endif\n#else\n// If not gcc\n#endif\n</code></pre>\n" }, { "answer_id": 259383, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": false, "text": "<p>As a side note:</p>\n\n<p>To find all the predefined macros:</p>\n\n<ul>\n<li>Create empty file t.cpp</li>\n<li><code>g++ -E -dM t.cpp</code></li>\n</ul>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7136/" ]
I would like to include a different file depending on the version of GCC. More precisely I want to write: ``` #if GCC_VERSION >= 4.2 # include <unordered_map> # define EXT std #elif GCC_VERSION >= 4 # include <tr1/unordered_map> # define EXT std #else # include <ext/hash_map> # define unordered_map __gnu_cxx::hash_map # define EXT __gnu_cxx #endif ``` I don't care about gcc before 3.2. I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.
Ok, after more searches, it one possible way of doing it is using `__GNUC_PREREQ` defined in `features.h`. ``` #ifdef __GNUC__ # include <features.h> # if __GNUC_PREREQ(4,0) // If gcc_version >= 4.0 # elif __GNUC_PREREQ(3,2) // If gcc_version >= 3.2 # else // Else # endif #else // If not gcc #endif ```
259,269
<p>I have a loop that reads each line in a file using <code>getline()</code>:</p> <pre><code>istream is; string line; while (!getline(is, line).eof()) { // ... } </code></pre> <p>I noticed that calling <code>getline()</code> like this also seems to work:</p> <pre><code>while (getline(is, line)) </code></pre> <p>What's going on here? <code>getline()</code> returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?</p>
[ { "answer_id": 259284, "author": "Todd Gamblin", "author_id": 9122, "author_profile": "https://Stackoverflow.com/users/9122", "pm_score": 3, "selected": false, "text": "<p><strong>Updated:</strong></p>\n\n<p>I had mistakenly pointed to the <a href=\"http://www.unc.edu/depts/case/pgi/pgC++_lib/stdlibcr/bas_3074.htm#Sentry%20Classbool()\" rel=\"nofollow noreferrer\">basic_istream documentation</a> for the operator bool() method on the basic_istream::sentry class, but as has been pointed out this is not actually what's happening. I've voted up Charles and Luc's correct answers. It's actually operator void*() that's getting called. More on this <a href=\"http://parashift.com/c++-faq-lite/input-output.html#faq-15.4\" rel=\"nofollow noreferrer\">in the C++ FAQ</a>.</p>\n" }, { "answer_id": 259286, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 6, "selected": true, "text": "<p>The <code>istream</code> returned by <code>getline()</code> is having its operator <code>void*()</code> method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to <code>eof()</code>.</p>\n" }, { "answer_id": 259304, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": -1, "selected": false, "text": "<p>I would stick with the first form. While the second form may work, it is hardly explicit. Your original code clearly describes what is being done and how it is expected to behave.</p>\n" }, { "answer_id": 259430, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 3, "selected": false, "text": "<p>Charles did give the <a href=\"https://stackoverflow.com/questions/259269/stdgetline-returns#259286\">correct answer</a>.</p>\n\n<p>What is called is indeed <code>std::basic_ios::operator void*()</code>, and not <code>sentry::operator bool()</code>, which is consistant with the fact that <code>std::getline()</code> returns a <code>std::basic_istream</code> (thus, a <code>std::basic_ios</code>), and not a sentry.</p>\n\n<p>For the non believers, see:</p>\n\n<ul>\n<li><a href=\"http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool\" rel=\"nofollow noreferrer\">std::basic_ios::operator void</a>*() documentation on cppreference site,</li>\n<li>The <a href=\"http://www.artima.com/cppsource/safebool.html\" rel=\"nofollow noreferrer\"><em>The Safe Bool Idiom</em></a> article on artima,</li>\n<li><a href=\"http://parashift.com/c++-faq-lite/input-output.html#faq-15.4\" rel=\"nofollow noreferrer\">C++ FAQ lite §15.4</a>,</li>\n<li>the standard, ...</li>\n</ul>\n\n<p>Otherwise, as other have already said, prefer the second form which is canonical. Use not <code>fail()</code> if really you want a verbose code -- I never remember whether <code>xxx.good()</code> can be used instead of <code>!xxx.fail()</code></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
I have a loop that reads each line in a file using `getline()`: ``` istream is; string line; while (!getline(is, line).eof()) { // ... } ``` I noticed that calling `getline()` like this also seems to work: ``` while (getline(is, line)) ``` What's going on here? `getline()` returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?
The `istream` returned by `getline()` is having its operator `void*()` method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to `eof()`.
259,290
<p><a href="http://biochrom.fivesite.co.uk/catalogue4.asp" rel="nofollow noreferrer">http://biochrom.fivesite.co.uk/catalogue4.asp</a></p> <p>On the page above there is an image floated to the left. To the right of it is a list, titled "features". The list items have a background image, however, it isn't appearing. List 2 shows how the background image looks.</p> <p>Does anyone know how I can make the bullets visible?</p>
[ { "answer_id": 259305, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 3, "selected": true, "text": "<p>Your image has a float:left property. The list items are therefore rendered \"behind\" the image.</p>\n\n<pre><code>margin-left:200px;\n</code></pre>\n\n<p>on the UL element will solve your problem.</p>\n\n<p>Alternatively, you can apply a float:left on your UL-element. This will make it float right to the image, but will make the following content appear on the same line. You can prevent this by <a href=\"http://www.positioniseverything.net/easyclearing.html\" rel=\"nofollow noreferrer\">clearing the UL-element</a>, or adding element after the UL-element with...</p>\n\n<pre><code>clear:both\n</code></pre>\n\n<p>...applied to it.</p>\n\n<p>More information about this behaviour can be found at <a href=\"http://www.positioniseverything.net/easyclearing.html\" rel=\"nofollow noreferrer\">http://www.positioniseverything.net/easyclearing.html</a>.</p>\n" }, { "answer_id": 259327, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 1, "selected": false, "text": "<p>Alternatively, you could use the list-style-image property instead of background-image. I ran into this very problem the other day: the text-wrapping behaviour that floats exhibit on their 'neighbours' only applies to 'content', not background images (for example).</p>\n" }, { "answer_id": 1907977, "author": "Helping Others", "author_id": 232165, "author_profile": "https://Stackoverflow.com/users/232165", "pm_score": 3, "selected": false, "text": "<p>I know this is a year old post but others may want to know...</p>\n\n<p>What happens if you are using a content management system and some pages have images &amp; some don't you wouldn't want your list items to be 200px in the content?</p>\n\n<p>You can add this CSS to your UL/OL element:</p>\n\n<pre><code>overflow:hidden;\n</code></pre>\n\n<p>I hope that helps.</p>\n" }, { "answer_id": 5928033, "author": "onearmfrog", "author_id": 743956, "author_profile": "https://Stackoverflow.com/users/743956", "pm_score": 2, "selected": false, "text": "<p>This thread is old indeed, but always relevant...</p>\n\n<p>Another alternative solution: </p>\n\n<pre><code>display: inline-block;\n</code></pre>\n\n<p>Put this <strong>on the UL</strong>. It forces the entire ul to appear after the float. That way you can have a page with or without the image and it will always display correctly (checked on FF4, IE7 &amp; 8, Chrome 11).</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10023/" ]
<http://biochrom.fivesite.co.uk/catalogue4.asp> On the page above there is an image floated to the left. To the right of it is a list, titled "features". The list items have a background image, however, it isn't appearing. List 2 shows how the background image looks. Does anyone know how I can make the bullets visible?
Your image has a float:left property. The list items are therefore rendered "behind" the image. ``` margin-left:200px; ``` on the UL element will solve your problem. Alternatively, you can apply a float:left on your UL-element. This will make it float right to the image, but will make the following content appear on the same line. You can prevent this by [clearing the UL-element](http://www.positioniseverything.net/easyclearing.html), or adding element after the UL-element with... ``` clear:both ``` ...applied to it. More information about this behaviour can be found at <http://www.positioniseverything.net/easyclearing.html>.
259,297
<p>I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a <code>std::vector</code>. I don't want to have to do the standard loop to <code>push_back</code> all the values individually, it would be nice if I could just copy it all using something similar to <code>memcpy</code>.</p>
[ { "answer_id": 259307, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.cppreference.com/wiki/stl/algorithm/copy\" rel=\"noreferrer\">std::copy</a> is what you're looking for.</p>\n" }, { "answer_id": 259312, "author": "bsruth", "author_id": 23504, "author_profile": "https://Stackoverflow.com/users/23504", "pm_score": 4, "selected": false, "text": "<p>Since I can only edit my own answer, I'm going to make a composite answer from the other answers to my question. Thanks to all of you who answered.</p>\n\n<p>Using <a href=\"http://www.cppreference.com/wiki/stl/algorithm/copy\" rel=\"noreferrer\">std::copy</a>, this still iterates in the background, but you don't have to type out the code.</p>\n\n<pre><code>int foo(int* data, int size)\n{\n static std::vector&lt;int&gt; my_data; //normally a class variable\n std::copy(data, data + size, std::back_inserter(my_data));\n return 0;\n}\n</code></pre>\n\n<p>Using regular <a href=\"http://www.cppreference.com/wiki/c/string/memcpy?s[]=memcpy\" rel=\"noreferrer\">memcpy</a>. This is probably best used for basic data types (i.e. int) but not for more complex arrays of structs or classes.</p>\n\n<pre><code>vector&lt;int&gt; x(size);\nmemcpy(&amp;x[0], source, size*sizeof(int));\n</code></pre>\n" }, { "answer_id": 259316, "author": "Thomas Jones-Low", "author_id": 23030, "author_profile": "https://Stackoverflow.com/users/23030", "pm_score": 0, "selected": false, "text": "<p>Assuming you know how big the item in the vector are: </p>\n\n<pre><code>std::vector&lt;int&gt; myArray;\nmyArray.resize (item_count, 0);\nmemcpy (&amp;myArray.front(), source, item_count * sizeof(int));\n</code></pre>\n\n<p><a href=\"http://www.cppreference.com/wiki/stl/vector/start\" rel=\"nofollow noreferrer\">http://www.cppreference.com/wiki/stl/vector/start</a> </p>\n" }, { "answer_id": 259339, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 2, "selected": false, "text": "<p>avoid the memcpy, I say. No reason to mess with pointer operations unless you really have to. Also, it will only work for POD types (like int) but would fail if you're dealing with types that require construction. </p>\n" }, { "answer_id": 259357, "author": "Thomas Jones-Low", "author_id": 23030, "author_profile": "https://Stackoverflow.com/users/23030", "pm_score": 1, "selected": false, "text": "<p>In addition to the methods presented above, you need to make sure you use either std::Vector.reserve(), std::Vector.resize(), or construct the vector to size, to make sure your vector has enough elements in it to hold your data. if not, you will corrupt memory. This is true of either std::copy() or memcpy(). </p>\n\n<p>This is the reason to use vector.push_back(), you can't write past the end of the vector. </p>\n" }, { "answer_id": 259379, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 8, "selected": true, "text": "<p>If you can construct the vector after you've gotten the array and array size, you can just say:</p>\n\n<pre><code>std::vector&lt;ValueType&gt; vec(a, a + n);\n</code></pre>\n\n<p>...assuming <code>a</code> is your array and <code>n</code> is the number of elements it contains. Otherwise, <code>std::copy()</code> w/<code>resize()</code> will do the trick.</p>\n\n<p>I'd stay away from <code>memcpy()</code> unless you can be sure that the values are plain-old data (POD) types.</p>\n\n<p>Also, worth noting that none of these really avoids the for loop--it's just a question of whether you have to see it in your code or not. O(n) runtime performance is unavoidable for copying the values.</p>\n\n<p>Finally, note that C-style arrays are perfectly valid containers for most STL algorithms--the raw pointer is equivalent to <code>begin()</code>, and (<code>ptr + n</code>) is equivalent to <code>end()</code>.</p>\n" }, { "answer_id": 259381, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 6, "selected": false, "text": "<p>If all you are doing is replacing the existing data, then you can do this</p>\n\n<pre><code>std::vector&lt;int&gt; data; // evil global :)\n\nvoid CopyData(int *newData, size_t count)\n{\n data.assign(newData, newData + count);\n}\n</code></pre>\n" }, { "answer_id": 259580, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 2, "selected": false, "text": "<p>Yet another answer, since the person said \"I don't know how many times my function will be called\", you could use the vector insert method like so to append arrays of values to the end of the vector:</p>\n\n<pre><code>vector&lt;int&gt; x;\n\nvoid AddValues(int* values, size_t size)\n{\n x.insert(x.end(), values, values+size);\n}\n</code></pre>\n\n<p>I like this way because the implementation of the vector should be able to optimize for the best way to insert the values based on the iterator type and the type itself. You are somewhat replying on the implementation of stl.</p>\n\n<p>If you need to guarantee the fastest speed and you know your type is a POD type then I would recommend the resize method in Thomas's answer:</p>\n\n<pre><code>vector&lt;int&gt; x;\n\nvoid AddValues(int* values, size_t size)\n{\n size_t old_size(x.size());\n x.resize(old_size + size, 0);\n memcpy(&amp;x[old_size], values, size * sizeof(int));\n}\n</code></pre>\n" }, { "answer_id": 261607, "author": "MattyT", "author_id": 7405, "author_profile": "https://Stackoverflow.com/users/7405", "pm_score": 8, "selected": false, "text": "<p>There have been many answers here and just about all of them will get the job done. </p>\n\n<p>However there is some misleading advice!</p>\n\n<p>Here are the options:</p>\n\n<pre><code>vector&lt;int&gt; dataVec;\n\nint dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\nunsigned dataArraySize = sizeof(dataArray) / sizeof(int);\n\n// Method 1: Copy the array to the vector using back_inserter.\n{\n copy(&amp;dataArray[0], &amp;dataArray[dataArraySize], back_inserter(dataVec));\n}\n\n// Method 2: Same as 1 but pre-extend the vector by the size of the array using reserve\n{\n dataVec.reserve(dataVec.size() + dataArraySize);\n copy(&amp;dataArray[0], &amp;dataArray[dataArraySize], back_inserter(dataVec));\n}\n\n// Method 3: Memcpy\n{\n dataVec.resize(dataVec.size() + dataArraySize);\n memcpy(&amp;dataVec[dataVec.size() - dataArraySize], &amp;dataArray[0], dataArraySize * sizeof(int));\n}\n\n// Method 4: vector::insert\n{\n dataVec.insert(dataVec.end(), &amp;dataArray[0], &amp;dataArray[dataArraySize]);\n}\n\n// Method 5: vector + vector\n{\n vector&lt;int&gt; dataVec2(&amp;dataArray[0], &amp;dataArray[dataArraySize]);\n dataVec.insert(dataVec.end(), dataVec2.begin(), dataVec2.end());\n}\n</code></pre>\n\n<p><strong>To cut a long story short Method 4, using vector::insert, is the best for bsruth's scenario.</strong> </p>\n\n<p>Here are some gory details:</p>\n\n<p><em>Method 1</em> is probably the easiest to understand. Just copy each element from the array and push it into the back of the vector. Alas, it's slow. Because there's a loop (implied with the copy function), each element must be treated individually; no performance improvements can be made based on the fact that we know the array and vectors are contiguous blocks.</p>\n\n<p><em>Method 2</em> is a suggested performance improvement to Method 1; just pre-reserve the size of the array before adding it. For large arrays this <em>might</em> help. However the best advice here is never to use reserve unless profiling suggests you may be able to get an improvement (or you need to ensure your iterators are not going to be invalidated). <a href=\"http://www.research.att.com/~bs/bs_faq2.html#slow-containers\" rel=\"noreferrer\">Bjarne agrees</a>. Incidentally, I found that this method performed the <em>slowest</em> most of the time though I'm struggling to comprehensively explain why it was regularly <em>significantly</em> slower than method 1...</p>\n\n<p><em>Method 3</em> is the old school solution - throw some C at the problem! Works fine and fast for POD types. In this case resize is required to be called since memcpy works outside the bounds of vector and there is no way to tell a vector that its size has changed. Apart from being an ugly solution (byte copying!) remember that this can <em>only be used for POD types</em>. I would never use this solution.</p>\n\n<p><em>Method 4</em> is the best way to go. It's meaning is clear, it's (usually) the fastest and it works for any objects. There is no downside to using this method for this application.</p>\n\n<p><em>Method 5</em> is a tweak on Method 4 - copy the array into a vector and then append it. Good option - generally fast-ish and clear. </p>\n\n<p>Finally, you are aware that you can use vectors in place of arrays, right? Even when a function expects c-style arrays you can use vectors:</p>\n\n<pre><code>vector&lt;char&gt; v(50); // Ensure there's enough space\nstrcpy(&amp;v[0], \"prefer vectors to c arrays\");\n</code></pre>\n\n<p>Hope that helps someone out there! </p>\n" }, { "answer_id": 42535004, "author": "Antonio Ramasco", "author_id": 7642034, "author_profile": "https://Stackoverflow.com/users/7642034", "pm_score": 2, "selected": false, "text": "<pre><code>int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };//source\n\nunsigned dataArraySize = sizeof(dataArray) / sizeof(int);\n\nstd::vector&lt;int&gt; myvector (dataArraySize );//target\n\nstd::copy ( myints, myints+dataArraySize , myvector.begin() );\n\n//myvector now has 1,2,3,...10 :-)\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23504/" ]
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a `std::vector`. I don't want to have to do the standard loop to `push_back` all the values individually, it would be nice if I could just copy it all using something similar to `memcpy`.
If you can construct the vector after you've gotten the array and array size, you can just say: ``` std::vector<ValueType> vec(a, a + n); ``` ...assuming `a` is your array and `n` is the number of elements it contains. Otherwise, `std::copy()` w/`resize()` will do the trick. I'd stay away from `memcpy()` unless you can be sure that the values are plain-old data (POD) types. Also, worth noting that none of these really avoids the for loop--it's just a question of whether you have to see it in your code or not. O(n) runtime performance is unavoidable for copying the values. Finally, note that C-style arrays are perfectly valid containers for most STL algorithms--the raw pointer is equivalent to `begin()`, and (`ptr + n`) is equivalent to `end()`.
259,309
<p>Is there a way using JSF to group two or more columns under a single parent column in JSF? I have a dataTableEx with hx:columnEx columns inside of it. What I want is something like this:</p> <pre><code> [MAIN HEADER FOR COL1+2 ][Header for Col 3+4] [ COL1 Header][COL2 Header][COL3 ][COL 4 ] Data Data Data Data Data Data Data Data Data Data Data Data Data Data Data Data </code></pre> <p>Data Data Data Data</p> <p>Thanks</p>
[ { "answer_id": 259348, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 0, "selected": false, "text": "<p>Your best bet is likely to use nested tables for the first header (first header in the outer table, and your second header and data inside a nested table) so that it looks like two headers.</p>\n" }, { "answer_id": 261188, "author": "Romain Linsolas", "author_id": 26457, "author_profile": "https://Stackoverflow.com/users/26457", "pm_score": 0, "selected": false, "text": "<p>Maybe you can have a look to advanced components libraries, such as RichFaces that offer more complex structures for datatables, like in this <a href=\"http://livedemo.exadel.com/richfaces-demo/richfaces/dataTable.jsf\" rel=\"nofollow noreferrer\">example</a>.</p>\n" }, { "answer_id": 265964, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": true, "text": "<p>You can probably achieve what you want with the table header, a panelGrid and a little CSS.</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n.colstyle {\n width: 25%\n}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;f:view&gt;\n &lt;h:dataTable border=\"1\" value=\"#{columnsBean.rows}\" var=\"row\"\n columnClasses=\"colstyle\"&gt;\n &lt;f:facet name=\"header\"&gt;\n &lt;h:panelGrid columns=\"2\" border=\"1\" style=\"width: 100%\"&gt;\n &lt;h:outputLabel style=\"width: 100%\" value=\"MAIN HEADER FOR COL1+2\" /&gt;\n &lt;h:outputLabel style=\"width: 100%\" value=\"MAIN HEADER FOR COL3+4\" /&gt;\n &lt;/h:panelGrid&gt;\n &lt;/f:facet&gt;\n &lt;h:column&gt;\n &lt;f:facet name=\"header\"&gt;\n &lt;h:outputText value=\"COL1 Header\" /&gt;\n &lt;/f:facet&gt;\n &lt;h:outputLabel value=\"#{row.col1}\" /&gt;\n &lt;/h:column&gt;\n &lt;h:column&gt;\n &lt;f:facet name=\"header\"&gt;\n &lt;h:outputText value=\"COL2 Header\" /&gt;\n &lt;/f:facet&gt;\n &lt;h:outputLabel value=\"#{row.col2}\" /&gt;\n &lt;/h:column&gt;\n &lt;h:column&gt;\n &lt;f:facet name=\"header\"&gt;\n &lt;h:outputText value=\"COL3 Header\" /&gt;\n &lt;/f:facet&gt;\n &lt;h:outputLabel value=\"#{row.col3}\" /&gt;\n &lt;/h:column&gt;\n &lt;h:column&gt;\n &lt;f:facet name=\"header\"&gt;\n &lt;h:outputText value=\"COL4 Header\" /&gt;\n &lt;/f:facet&gt;\n &lt;h:outputLabel value=\"#{row.col4}\" /&gt;\n &lt;/h:column&gt;\n &lt;/h:dataTable&gt;\n&lt;/f:view&gt;\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32812/" ]
Is there a way using JSF to group two or more columns under a single parent column in JSF? I have a dataTableEx with hx:columnEx columns inside of it. What I want is something like this: ``` [MAIN HEADER FOR COL1+2 ][Header for Col 3+4] [ COL1 Header][COL2 Header][COL3 ][COL 4 ] Data Data Data Data Data Data Data Data Data Data Data Data Data Data Data Data ``` Data Data Data Data Thanks
You can probably achieve what you want with the table header, a panelGrid and a little CSS. ``` <style type="text/css"> .colstyle { width: 25% } </style> </head> <body> <f:view> <h:dataTable border="1" value="#{columnsBean.rows}" var="row" columnClasses="colstyle"> <f:facet name="header"> <h:panelGrid columns="2" border="1" style="width: 100%"> <h:outputLabel style="width: 100%" value="MAIN HEADER FOR COL1+2" /> <h:outputLabel style="width: 100%" value="MAIN HEADER FOR COL3+4" /> </h:panelGrid> </f:facet> <h:column> <f:facet name="header"> <h:outputText value="COL1 Header" /> </f:facet> <h:outputLabel value="#{row.col1}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="COL2 Header" /> </f:facet> <h:outputLabel value="#{row.col2}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="COL3 Header" /> </f:facet> <h:outputLabel value="#{row.col3}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="COL4 Header" /> </f:facet> <h:outputLabel value="#{row.col4}" /> </h:column> </h:dataTable> </f:view> ```
259,311
<p>I am working in Visual Studio 2008 on an ASP.NET application, which has been deployed to a test server. I would like to make a build without debug information to place in production, but the configuration manager only shows "Debug" in the configuration dropdown for my project.</p> <p>My other Visual Studio projects show "Debug", "Release", "New...", and "Edit...".</p> <p>Why do I not see a release option, or the new and edit commands?</p>
[ { "answer_id": 260921, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>The Configuration Manager for the Solution allows you to delete either (or both) of these default build configurations (through the Edit... option you mention above). I would bet that someone deleted the Release configuration.</p>\n\n<p>You can get it back by recreating it, or copy the appropriate lines from a solution you make from scratch real quick. A file diff shows the following:</p>\n\n<p>Default solution file:</p>\n\n<pre><code>GlobalSection(SolutionConfigurationPlatforms) = preSolution\n Debug|Any CPU = Debug|Any CPU\n Release|Any CPU = Release|Any CPU\nEndGlobalSection\nGlobalSection(ProjectConfigurationPlatforms) = postSolution\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.ActiveCfg = Release|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.Build.0 = Release|Any CPU\nEndGlobalSection\n</code></pre>\n\n<p>Solution after I manually deleted the Release configuration:</p>\n\n<pre><code>GlobalSection(SolutionConfigurationPlatforms) = preSolution\n Debug|Any CPU = Debug|Any CPU\nEndGlobalSection\nGlobalSection(ProjectConfigurationPlatforms) = postSolution\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU\nEndGlobalSection\n</code></pre>\n" }, { "answer_id": 334736, "author": "Keith Walton", "author_id": 22448, "author_profile": "https://Stackoverflow.com/users/22448", "pm_score": 6, "selected": true, "text": "<p>ASP.NET web sites do not use the configuration manager to determine if debug information is included in the compile. You must set it in the <code>web.config</code> file. Visual Studio will never change debug to \"false\" for you automactially, as far as I know.</p>\n\n<p>Find this section in your <code>web.config</code> file and change it to \"false\":</p>\n\n<pre><code>&lt;!--\n Set compilation debug=\"true\" to insert debugging\n symbols into the compiled page. Because this\n affects performance, set this value to true only\n during development.\n--&gt;\n\n&lt;compilation debug=\"true\"&gt;\n</code></pre>\n\n<p>Visual Studio will ask you if you want it changed from false to true if you are running your web site in the IDE, but unfortunately it does not do the reverse for publishing (which seems more important to me).</p>\n\n<p>If you have multiple projects in your solution, and at least one of them supports a release configuration (such as a DLL) - it will appear in the configuration drop-down list. Building with Release selected still does not affect the website, however.</p>\n" }, { "answer_id": 35190427, "author": "mike", "author_id": 5880694, "author_profile": "https://Stackoverflow.com/users/5880694", "pm_score": 1, "selected": false, "text": "<p>After reviewing the best answer and wrestling with this problem for a couple of hours, I ran across this answer. My solution was to add a full application: usually use an empty web site, but had the same problem of the release not displaying. I added a full application to the solution and it then allowed me to deploy my project within the solution, since adding the complete application also added the option of 'release' in the dropdown. I very much appreciate the advice, but not sure why this tool is so quirky. Thanks again for your suggestion.</p>\n" }, { "answer_id": 42556026, "author": "eiran", "author_id": 1063776, "author_profile": "https://Stackoverflow.com/users/1063776", "pm_score": 0, "selected": false, "text": "<p>the process was changed, you just need to check the 2 bottom check boxes during the settings part of the publish process, as shown in the image. in the bin folder you'll find the dlls. </p>\n\n<p><img src=\"https://i.imgur.com/vCHgcrz.png\" alt=\"image\"></p>\n\n<p>hope that helps</p>\n\n<p>eiran</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21253/" ]
I am working in Visual Studio 2008 on an ASP.NET application, which has been deployed to a test server. I would like to make a build without debug information to place in production, but the configuration manager only shows "Debug" in the configuration dropdown for my project. My other Visual Studio projects show "Debug", "Release", "New...", and "Edit...". Why do I not see a release option, or the new and edit commands?
ASP.NET web sites do not use the configuration manager to determine if debug information is included in the compile. You must set it in the `web.config` file. Visual Studio will never change debug to "false" for you automactially, as far as I know. Find this section in your `web.config` file and change it to "false": ``` <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> <compilation debug="true"> ``` Visual Studio will ask you if you want it changed from false to true if you are running your web site in the IDE, but unfortunately it does not do the reverse for publishing (which seems more important to me). If you have multiple projects in your solution, and at least one of them supports a release configuration (such as a DLL) - it will appear in the configuration drop-down list. Building with Release selected still does not affect the website, however.
259,314
<p>Hey I have a windows server running python CGI scripts and I'm having a little trouble with smtplib. The server is running python 2.1 (unfortunately and I can not upgrade it). Anyway I have the following code:</p> <pre><code>session = smtplib.SMTP(&quot;smtp-auth.ourhosting.com&quot;, 587) session.login(smtpuser, smtppass) </code></pre> <p>and it's giving me this error:</p> <pre><code>exceptions.AttributeError : SMTP instance has no attribute 'login' : &lt;traceback object at 006BB1D0&gt; </code></pre> <p>I'm assuming this is because the <code>login()</code> method was added after python 2.1. so how do I fix this?</p> <p>I have to either add the module by uploading the files to the same directory as the cgi script (though I believe smtplib is written in C and needs to be compiled which we can't do on this server)</p> <p>OR</p> <p>Do it whatever way is expected by the libsmtp in python 2.1.</p>
[ { "answer_id": 259324, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Do it whatever way is expected by the libsmtp in python 2.1</p>\n</blockquote>\n" }, { "answer_id": 259432, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": true, "text": "<p>login() was introduced in Python 2.2, unluckily for you! The only way to do it in Python 2.1's own smtplib would be to issue the AUTH commands manually, which wouldn't be much fun.</p>\n\n<p>I haven't tested it fully but it seems Python 2.2's smtplib should more or less work on 2.1 if you copy it across as you describe (perhaps call it smtplib2.py). It's only a Python module, no C compilation should be necessary. However you will at least need to copy the hmac.py library it relies on from 2.2's lib as well. If you use a later Python version to steal from it starts requiring the email package too which might be more work.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
Hey I have a windows server running python CGI scripts and I'm having a little trouble with smtplib. The server is running python 2.1 (unfortunately and I can not upgrade it). Anyway I have the following code: ``` session = smtplib.SMTP("smtp-auth.ourhosting.com", 587) session.login(smtpuser, smtppass) ``` and it's giving me this error: ``` exceptions.AttributeError : SMTP instance has no attribute 'login' : <traceback object at 006BB1D0> ``` I'm assuming this is because the `login()` method was added after python 2.1. so how do I fix this? I have to either add the module by uploading the files to the same directory as the cgi script (though I believe smtplib is written in C and needs to be compiled which we can't do on this server) OR Do it whatever way is expected by the libsmtp in python 2.1.
login() was introduced in Python 2.2, unluckily for you! The only way to do it in Python 2.1's own smtplib would be to issue the AUTH commands manually, which wouldn't be much fun. I haven't tested it fully but it seems Python 2.2's smtplib should more or less work on 2.1 if you copy it across as you describe (perhaps call it smtplib2.py). It's only a Python module, no C compilation should be necessary. However you will at least need to copy the hmac.py library it relies on from 2.2's lib as well. If you use a later Python version to steal from it starts requiring the email package too which might be more work.
259,320
<p>I'm still learning Grails and seem to have hit a stumbling block.</p> <p><strong>Here are the 2 domain classes:</strong></p> <pre><code>class Photo { byte[] file static belongsTo = Profile } class Profile { String fullName Set photos static hasMany = [photos:Photo] } </code></pre> <p><strong>The relevant controller snippet:</strong> </p> <pre><code>class PhotoController { def viewImage = { def photo = Photo.get( params.id ) byte[] image = photo.file response.outputStream &lt;&lt; image } } </code></pre> <p><strong>Finally the GSP snippet:</strong></p> <pre><code>&lt;img class="Photo" src="${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}" /&gt; </code></pre> <p>Now how do I access the photo so that it will be shown on the GSP? I'm pretty sure that <code>profileInstance.photos.get(1).id</code> is not correct.</p>
[ { "answer_id": 259361, "author": "Hates_", "author_id": 3410, "author_profile": "https://Stackoverflow.com/users/3410", "pm_score": 3, "selected": true, "text": "<p>As it is a Set, if you want the first element, you will have to go:</p>\n\n<pre><code>profileInstance.photos.toArray()[0].id\n</code></pre>\n\n<p>or</p>\n\n<pre><code>profileInstance.photos.iterator().next()\n</code></pre>\n" }, { "answer_id": 260022, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": "<p>My guess is you need to set the content type of the response stream. Something like:</p>\n\n<pre><code>response.ContentType = \"image/jpeg\"\n</code></pre>\n\n<p>This may or may not need to be before you stream to the response stream (can't imagine that it would matter). I'd just put it before the outputStream line in your code above.</p>\n" }, { "answer_id": 268678, "author": "Chii", "author_id": 17335, "author_profile": "https://Stackoverflow.com/users/17335", "pm_score": 2, "selected": false, "text": "<p>now, i actually think storing the photo as a binary blob in the database isnt the best solution - though you might have reasons why it needs to be done that way. </p>\n\n<p>how about storing the name of the photo (and/or the path) instead? If name clashing issues are probable, use the md5 checksum of the photo as the name. Then the photo becomes a static resource, a simple file, instead of a more complicated and slower MVC request.</p>\n" }, { "answer_id": 275877, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 2, "selected": false, "text": "<p>If you have a url for the image, you just have to make sure you return the appropriate anser in the controller:</p>\n\n<pre><code> def viewImage= {\n //retrieve photo code here\n response.setHeader(\"Content-disposition\", \"attachment; filename=${photo.name}\")\n response.contentType = photo.fileType //'image/jpeg' will do too\n response.outputStream &lt;&lt; photo.file //'myphoto.jpg' will do too\n response.outputStream.flush()\n return;\n }\n</code></pre>\n" }, { "answer_id": 2441055, "author": "leroy zhu", "author_id": 293241, "author_profile": "https://Stackoverflow.com/users/293241", "pm_score": 0, "selected": false, "text": "<p>id:'profileInstance.photos.get(1).id' should be id:profileInstance.photos.get(1).id. no quota</p>\n" }, { "answer_id": 9901244, "author": "stitakis", "author_id": 704264, "author_profile": "https://Stackoverflow.com/users/704264", "pm_score": 1, "selected": false, "text": "<p>I´m learning grails too was searching for an example like this one.\nThe GSP snipplet didn´t work for me. I resolved by replacing the single quotes around profileInstance.photos.get(1).id</p>\n\n<pre><code>&lt;img class=\"Photo\" src=\"${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}\" /&gt;\n</code></pre>\n\n<p>with double quotes:</p>\n\n<pre><code>&lt;img class=\"Photo\" src=\"${createLink(controller:'photo', action:'viewImage', id:\"profileInstance.photos.get(1).id\")}\" /&gt;\n</code></pre>\n\n<p>Now grails resolves the expression around the double quotes. Otherwise it takes it as string.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27163/" ]
I'm still learning Grails and seem to have hit a stumbling block. **Here are the 2 domain classes:** ``` class Photo { byte[] file static belongsTo = Profile } class Profile { String fullName Set photos static hasMany = [photos:Photo] } ``` **The relevant controller snippet:** ``` class PhotoController { def viewImage = { def photo = Photo.get( params.id ) byte[] image = photo.file response.outputStream << image } } ``` **Finally the GSP snippet:** ``` <img class="Photo" src="${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}" /> ``` Now how do I access the photo so that it will be shown on the GSP? I'm pretty sure that `profileInstance.photos.get(1).id` is not correct.
As it is a Set, if you want the first element, you will have to go: ``` profileInstance.photos.toArray()[0].id ``` or ``` profileInstance.photos.iterator().next() ```
259,343
<p>Is there any way to reboot the JVM? As in don't actually exit, but close and reload all classes, and run main from the top?</p>
[ { "answer_id": 259450, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 0, "selected": false, "text": "<p>AFAIK there is no such way. </p>\n\n<p>Notice that if there were a way to do that, it would highly depend on the current loaded code to properly release all held resources in order to provide a graceful restart (think about files, socket/tcp/http/database connections, threads, etc).</p>\n\n<p>Some applications, like Jboss AS, capture Ctrl+C on the console and provide a graceful shutdown, closing all resources, but this is application-specific code and not a JVM feature.</p>\n" }, { "answer_id": 259453, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 3, "selected": false, "text": "<p>IBM's JVM has a feature called \"resettable\" which allows you to effectively do what you are asking.</p>\n\n<p><a href=\"http://publib.boulder.ibm.com/infocenter/cicsts/v3r1/index.jsp?topic=/com.ibm.cics.ts31.doc/dfhpj/topics/dfhpje9.htm\" rel=\"noreferrer\">http://publib.boulder.ibm.com/infocenter/cicsts/v3r1/index.jsp?topic=/com.ibm.cics.ts31.doc/dfhpj/topics/dfhpje9.htm</a></p>\n\n<p>Other than the IBM JVM, I don't think it is possible.</p>\n" }, { "answer_id": 259463, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 1, "selected": false, "text": "<p>If you're working in an application server, they typically come with built-in hot deployment mechanisms that'll reload all classes in your application (web app, enterprise app) when you redeploy it.</p>\n\n<p>Otherwise, you'll have to look into commercial solutions. Java Rebel (<a href=\"http://www.zeroturnaround.com/javarebel/\" rel=\"nofollow noreferrer\">http://www.zeroturnaround.com/javarebel/</a>) is one such option.</p>\n" }, { "answer_id": 259464, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 5, "selected": true, "text": "<p>Your best bet is probably to run the java interpreter within a loop, and just exit. For example:</p>\n\n<pre><code>#!/bin/sh\nwhile true\ndo\n java MainClass\ndone\n</code></pre>\n\n<p>If you want the ability to reboot or shutdown entirely, you could test the exit status:</p>\n\n<pre><code>#!/bin/sh\nSTATUS=0\nwhile [ $STATUS -eq 0 ]\ndo\n java MainClass\n STATUS=$?\ndone\n</code></pre>\n\n<p>Within the java program, you can use System.exit(0) to indicate that you want to \"reboot,\" and System.exit(1) to indicate that you want to stop and stay stopped.</p>\n" }, { "answer_id": 259834, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 0, "selected": false, "text": "<p>I do something similar using JMX, I will 'unload' a module using JMX and then 'reload' it. Behind the scenes I am sure they are using a different class loader.</p>\n" }, { "answer_id": 261000, "author": "Ran Biron", "author_id": 931, "author_profile": "https://Stackoverflow.com/users/931", "pm_score": 2, "selected": false, "text": "<p>Not a real \"reboot\" but:</p>\n\n<p>You can build your own class loader and load all your classes (except a bootstrap) with it. Then, when you want to \"reboot\", make sure you do the following:</p>\n\n<ol>\n<li>End any threads that you've opened and are using your classes.</li>\n<li>Dispose any Window / Dialog / Applet you've created (UI application).</li>\n<li>Close / dispose any other GC root / OS resources hungry peered resource (database connections, etc).</li>\n<li>Throw away your customized class loader, create another instance of it and reload all the classes. You can probably optimize this step by pre-processing the classes from files so you won't have to access the codebase again.</li>\n<li>Call your main point of entry.</li>\n</ol>\n\n<p>This procedure is used (to some extent) while \"hot-swapping\" webapps in web servers.</p>\n\n<p>Note though, static class members and JVM \"global\" objects (ones that are accessed by a GC root that isn't under your control) will stay. For example, Locale.setLocale() effects a static member on Locale. Since the Locale class is loaded by the system class loader, it will not be \"restarted\". That means that the old Locale object that was used in Locale.setLocale() will be available afterward if not explicitly cleaned.</p>\n\n<p>Yet another route to take is instrumentation of classes. However, since I know little of it, I'm hesitant to offer advice.</p>\n\n<p><a href=\"http://www.pabrantes.net/blog/comments/start/2007-07-23/1\" rel=\"nofollow noreferrer\" title=\"Java Programming: Hot Deploy\">Explanation about hot deploy with some examples</a></p>\n" }, { "answer_id": 23980517, "author": "2xsaiko", "author_id": 3074505, "author_profile": "https://Stackoverflow.com/users/3074505", "pm_score": 0, "selected": false, "text": "<p>Well, I currently have this, it works perfectly, and completely OS-independent. The only thing that must work: executing the java process without any path/etc, but I think this can also be fixed.</p>\n\n<p>The little code pieces are all from stackoverflow except RunnableWithObject and restartMinecraft() :)</p>\n\n<p>You need to call it like this:</p>\n\n<pre><code>restartMinecraft(getCommandLineArgs());\n</code></pre>\n\n<p>So what it basically does, is:</p>\n\n<ol>\n<li>Spawns a new Process and stores it in the p variable</li>\n<li>Makes two RunnableWithObject instances and fills the process object into their data value, then starts two threads, they just print the inputStream and errorStream when it has available data until the process is exited</li>\n<li>Waits for the process to exit</li>\n<li>prints debug message about process exit</li>\n<li>Terminates with the exit value of the process(not necessary)</li>\n</ol>\n\n<p>And yes it is directly pulled from my minecraft project:)</p>\n\n<p>The code:</p>\n\n<p>Tools.isProcessExited() method:</p>\n\n<pre><code>public static boolean isProcessExited(Process p) {\n try {\n p.exitValue();\n } catch (IllegalThreadStateException e) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Tools.restartMinecraft() method:</p>\n\n<pre><code> public static void restartMinecraft(String args) throws IOException, InterruptedException {\n//Here you can do shutdown code etc\n Process p = Runtime.getRuntime().exec(args);\n RunnableWithObject&lt;Process&gt; inputStreamPrinter = new RunnableWithObject&lt;Process&gt;() {\n\n @Override\n public void run() {\n // TODO Auto-generated method stub\n while (!Tools.isProcessExited(data)) {\n try {\n while (data.getInputStream().available() &gt; 0) {\n System.out.print((char) data.getInputStream().read());\n }\n } catch (IOException e) {\n }\n }\n }\n };\n RunnableWithObject&lt;Process&gt; errorStreamPrinter = new RunnableWithObject&lt;Process&gt;() {\n\n @Override\n public void run() {\n // TODO Auto-generated method stub\n while (!Tools.isProcessExited(data)) {\n try {\n while (data.getErrorStream().available() &gt; 0) {\n System.err.print((char) data.getErrorStream().read());\n }\n } catch (IOException e) {\n }\n }\n }\n };\n\n inputStreamPrinter.data = p;\n errorStreamPrinter.data = p;\n\n new Thread(inputStreamPrinter).start();\n new Thread(errorStreamPrinter).start();\n p.waitFor();\n System.out.println(\"Minecraft exited. (\" + p.exitValue() + \")\");\n System.exit(p.exitValue());\n }\n</code></pre>\n\n<p>Tools.getCommandLineArgs() method:</p>\n\n<pre><code>public static String getCommandLineArgs() {\n String cmdline = \"\";\n List&lt;String&gt; l = ManagementFactory.getRuntimeMXBean().getInputArguments();\n cmdline += \"java \";\n for (int i = 0; i &lt; l.size(); i++) {\n cmdline += l.get(i) + \" \";\n }\n cmdline += \"-cp \" + System.getProperty(\"java.class.path\") + \" \" + System.getProperty(\"sun.java.command\");\n\n return cmdline;\n}\n</code></pre>\n\n<p>Aaaaand finally the RunnableWithObject class:</p>\n\n<pre><code>package generic.minecraft.infinityclient;\n\npublic abstract class RunnableWithObject&lt;T&gt; implements Runnable {\n public T data;\n}\n</code></pre>\n\n<p>Good luck :)</p>\n" }, { "answer_id": 38725332, "author": "Stefan Reich", "author_id": 947488, "author_profile": "https://Stackoverflow.com/users/947488", "pm_score": 0, "selected": false, "text": "<p>It's easy in JavaX: You can use the standard functions <a href=\"http://tinybrain.de/1001372\" rel=\"nofollow\">nohupJavax()</a> or <a href=\"http://tinybrain.de/1003781\" rel=\"nofollow\">restart()</a>.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420/" ]
Is there any way to reboot the JVM? As in don't actually exit, but close and reload all classes, and run main from the top?
Your best bet is probably to run the java interpreter within a loop, and just exit. For example: ``` #!/bin/sh while true do java MainClass done ``` If you want the ability to reboot or shutdown entirely, you could test the exit status: ``` #!/bin/sh STATUS=0 while [ $STATUS -eq 0 ] do java MainClass STATUS=$? done ``` Within the java program, you can use System.exit(0) to indicate that you want to "reboot," and System.exit(1) to indicate that you want to stop and stay stopped.
259,354
<p>Is there a substitute in emacs for the vi "gf" command? meaning try to open the file which is under the cursor right now if a real file name is in fact there.</p> <p>Thanks</p>
[ { "answer_id": 259376, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 7, "selected": true, "text": "<p>You want the <code>find-file-at-point</code> function (which is also aliased to <code>ffap</code>). It's not bound to a key by default, but you can use</p>\n\n<pre><code>M-x ffap\n</code></pre>\n\n<p>Or, you can put in your <code>.emacs</code> file:</p>\n\n<pre><code>(ffap-bindings)\n</code></pre>\n\n<p>This will replace many of the normal <code>find-file</code> key bindings (like <code>C-x C-f</code>) with <code>ffap</code>-based versions. See the commentary in <code>ffap.el</code> for details.</p>\n" }, { "answer_id": 261257, "author": "Nir", "author_id": 33707, "author_profile": "https://Stackoverflow.com/users/33707", "pm_score": 3, "selected": false, "text": "<p>Thanks, it works quite well but somehow the vi (gf) version is\nstill somewhat smarter. I think it looks at some path variable for search paths.</p>\n\n<p>I made something which is needlessly complicated but works for me (only in linux).\nIt uses the \"locate\" command to search for the path under the cursor.\nI guess it could be made smarter by searching the relative path to the current file first.\nsorry for my bad elisp skills...It can probably be achieved in a much nicer way.</p>\n\n<p>put in your .emacs, then use with M-x goto-file</p>\n\n<pre><code>(defun shell-command-to-string (command)\n \"Execute shell command COMMAND and return its output as a string.\"\n (with-output-to-string\n (with-current-buffer standard-output\n (call-process shell-file-name nil t nil shell-command-switch command))))\n\n(defun goto-file ()\n \"open file under cursor\"\n (interactive)\n (find-file (shell-command-to-string (concat \"locate \" (current-word) \"|head -c -1\" )) ))\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33707/" ]
Is there a substitute in emacs for the vi "gf" command? meaning try to open the file which is under the cursor right now if a real file name is in fact there. Thanks
You want the `find-file-at-point` function (which is also aliased to `ffap`). It's not bound to a key by default, but you can use ``` M-x ffap ``` Or, you can put in your `.emacs` file: ``` (ffap-bindings) ``` This will replace many of the normal `find-file` key bindings (like `C-x C-f`) with `ffap`-based versions. See the commentary in `ffap.el` for details.
259,355
<blockquote> <p>It turns out this whole misunderstanding of the open() versus fopen() stems from a buggy I2C driver in the Linux 2.6.14 kernel on an ARM. Backporting a working bit bashed driver solved the root cause of the problem I was trying to address here.</p> </blockquote> <p>I'm trying to figure out an issue with a serial device driver in Linux (I2C). It appears that by adding timed OS pauses (sleeps) between writes and reads on the device things work ... (much) better. </p> <blockquote> <p>Aside: <em>The nature of I2C is that each byte read or written by the master is acknowledged by the device on the other end of the wire (slave) - the pauses improving things encourage me to think of the driver as working asynchronously - something that I can't reconcile with how the bus works. Anyhoo ...</em></p> </blockquote> <p>I'd either like to <strong>flush</strong> the write to be sure (rather than using fixed duration pause), <strong><em>or</em></strong> somehow test that the write/read transaction has <strong>completed</strong> in an multi-threaded friendly way. </p> <p>The trouble with using <code>fflush(fd);</code> is that it requires 'fd' to be stream pointer (not a file descriptor) i.e.</p> <pre><code>FILE * fd = fopen("filename","r+"); ... // do read and writes fflush(fd); </code></pre> <p>My problem is that I require the use of the <code>ioctl()</code>, which doesn't use a stream pointer. i.e.</p> <pre><code>int fd = open("filename",O_RDWR); ioctl(fd,...); </code></pre> <p>Suggestions?</p>
[ { "answer_id": 259370, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 6, "selected": true, "text": "<p>You have two choices:</p>\n\n<ol>\n<li><p>Use <code>fileno()</code> to obtain the file descriptor associated with the <code>stdio</code> stream pointer</p></li>\n<li><p>Don't use <code>&lt;stdio.h&gt;</code> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the <code>write()</code> call won't even return until the lower-level IO has completed (in theory).</p></li>\n</ol>\n\n<p>For device-level IO I'd say it's pretty unusual to use <code>stdio</code>. I'd strongly recommend using the lower-level <code>open()</code>, <code>read()</code> and <code>write()</code> functions instead (based on your later reply):</p>\n\n<pre><code>int fd = open(\"/dev/i2c\", O_RDWR);\nioctl(fd, IOCTL_COMMAND, args);\nwrite(fd, buf, length);\n</code></pre>\n" }, { "answer_id": 261163, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": false, "text": "<p><code>fflush()</code> only flushes the buffering added by the stdio <code>fopen()</code> layer, as managed by the <code>FILE *</code> object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the <code>FILE *</code> layer, using <code>fileno()</code> and a raw <code>write()</code>, are also not buffered in a way that <code>fflush()</code> would flush.</p>\n\n<p>As others have pointed out, try <strong>not</strong> mixing the two. If you need to use \"raw\" I/O functions such as <code>ioctl()</code>, then <code>open()</code> the file yourself directly, <strong>without</strong> using <code>fopen&lt;()</code> and friends from stdio.</p>\n" }, { "answer_id": 261994, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :</p>\n\n<pre><code> FDOPEN(P)\n\nNAME\n\n fdopen - associate a stream with a file descriptor\n\nSYNOPSIS\n\n #include &lt;stdio.h&gt;\n\n FILE *fdopen(int fildes, const char *mode);\n</code></pre>\n" }, { "answer_id": 1696723, "author": "jstedfast", "author_id": 87117, "author_profile": "https://Stackoverflow.com/users/87117", "pm_score": 2, "selected": false, "text": "<p>It sounds like what you are looking for is the fsync() function (or fdatasync()?), or you could use the O_SYNC flag in your open() call.</p>\n" }, { "answer_id": 3173139, "author": "Danke Xie", "author_id": 382871, "author_profile": "https://Stackoverflow.com/users/382871", "pm_score": 6, "selected": false, "text": "<p>I think what you are looking for may be</p>\n\n<pre><code>int fsync(int fd);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int fdatasync(int fd);\n</code></pre>\n\n<p><code>fsync</code> will flush the file from kernel buffer to the disk. <code>fdatasync</code> will also do except for the meta data.</p>\n" }, { "answer_id": 38752910, "author": "rustyx", "author_id": 485343, "author_profile": "https://Stackoverflow.com/users/485343", "pm_score": 3, "selected": false, "text": "<p>Have you tried disabling buffering?</p>\n\n<pre><code>setvbuf(fd, NULL, _IONBF, 0);\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32836/" ]
> > It turns out this whole misunderstanding of the open() versus fopen() stems from a buggy I2C driver in the Linux 2.6.14 kernel on an ARM. Backporting a working bit bashed driver solved the root cause of the problem I was trying to address here. > > > I'm trying to figure out an issue with a serial device driver in Linux (I2C). It appears that by adding timed OS pauses (sleeps) between writes and reads on the device things work ... (much) better. > > Aside: *The nature of I2C is that each byte read or written by the master is acknowledged by the device on the other end of the wire (slave) - the pauses improving things encourage me to think of the driver as working asynchronously - something that I can't reconcile with how the bus works. Anyhoo ...* > > > I'd either like to **flush** the write to be sure (rather than using fixed duration pause), ***or*** somehow test that the write/read transaction has **completed** in an multi-threaded friendly way. The trouble with using `fflush(fd);` is that it requires 'fd' to be stream pointer (not a file descriptor) i.e. ``` FILE * fd = fopen("filename","r+"); ... // do read and writes fflush(fd); ``` My problem is that I require the use of the `ioctl()`, which doesn't use a stream pointer. i.e. ``` int fd = open("filename",O_RDWR); ioctl(fd,...); ``` Suggestions?
You have two choices: 1. Use `fileno()` to obtain the file descriptor associated with the `stdio` stream pointer 2. Don't use `<stdio.h>` at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the `write()` call won't even return until the lower-level IO has completed (in theory). For device-level IO I'd say it's pretty unusual to use `stdio`. I'd strongly recommend using the lower-level `open()`, `read()` and `write()` functions instead (based on your later reply): ``` int fd = open("/dev/i2c", O_RDWR); ioctl(fd, IOCTL_COMMAND, args); write(fd, buf, length); ```
259,364
<p>I'm using Emacs with <a href="http://mfgames.com/linux/csharp-mode" rel="nofollow noreferrer">C# Mode</a> and when I turn on the speedbar, no files show up by default. I can choose "show all files" on the speedbar mode, but then every .cs file shows up with a '[?]' next to the name. How do I properly configure speedbar so it shows up with .cs files by default? How do I get the '[+]' next to each file so I can navigate inside the file?</p>
[ { "answer_id": 261279, "author": "Vagmi Mudumbai", "author_id": 617, "author_profile": "https://Stackoverflow.com/users/617", "pm_score": 2, "selected": false, "text": "<p>I used speedbar earlier and got really irritated. I now use <a href=\"http://ecb.sourceforge.net/\" rel=\"nofollow noreferrer\">ECB</a>. <a href=\"http://ecb.sourceforge.net/\" rel=\"nofollow noreferrer\">ECB</a> uses its own buffer for the tree and can optionally show the outline of the CS file in a separate buffer. They all fit in the same frame while Speedbar has its own frame. </p>\n\n<p>I have some <a href=\"http://lisp.pastebin.com/m2a590520\" rel=\"nofollow noreferrer\">custom stuff</a> setup for ECB. You can see it here.</p>\n" }, { "answer_id": 425847, "author": "user9252", "author_id": 9252, "author_profile": "https://Stackoverflow.com/users/9252", "pm_score": 3, "selected": true, "text": "<p>I think ECB with CEDET is simply too bloated. I use speedbar alone with emacs and I use the original parser for C/C++. Just add this line to your .emacs and you'll be ok:</p>\n\n<pre><code> (speedbar-add-supported-extension \".cs\")\n (add-to-list 'speedbar-fetch-etags-parse-list\n '(\"\\\\.cs\" . speedbar-parse-c-or-c++tag))\n</code></pre>\n\n<p>This handles C# perfectly without a problem. Hope this helps.</p>\n" }, { "answer_id": 2790500, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 2, "selected": false, "text": "<p>It works for me. </p>\n\n<p>I used</p>\n\n<pre><code>(speedbar-add-supported-extension \".cs\") \n</code></pre>\n\n<p>and got this: </p>\n\n<p><img src=\"https://i.imgur.com/d1vMA.png\" alt=\"alt text\"></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ]
I'm using Emacs with [C# Mode](http://mfgames.com/linux/csharp-mode) and when I turn on the speedbar, no files show up by default. I can choose "show all files" on the speedbar mode, but then every .cs file shows up with a '[?]' next to the name. How do I properly configure speedbar so it shows up with .cs files by default? How do I get the '[+]' next to each file so I can navigate inside the file?
I think ECB with CEDET is simply too bloated. I use speedbar alone with emacs and I use the original parser for C/C++. Just add this line to your .emacs and you'll be ok: ``` (speedbar-add-supported-extension ".cs") (add-to-list 'speedbar-fetch-etags-parse-list '("\\.cs" . speedbar-parse-c-or-c++tag)) ``` This handles C# perfectly without a problem. Hope this helps.
259,369
<p>I want to be able to rewrite a URL from:</p> <pre><code>// examples http://example.com/location/New York, NY --&gt; http://example.com/location/index.html?location=New York, NY http://example.com/location/90210 --&gt; http://example.com/location/index.html?location=90210 http://example.com/location/Texas --&gt; http://example.com/location/index.html?location=Texas http://example.com/location/ANYTHING.... --&gt; http://example.com/location/index.html?location=ANYTHING... </code></pre> <p>using <code>.htaccess</code> and mod_rewrite.</p> <p>Anyone know how to do this?</p> <p>I have tried:</p> <pre><code>RewriteEngine on RewriteCond %{REQUEST_URI} !location/index.html RewriteRule ^location/(.*)$ /location/index.html?location=$1 </code></pre> <p>However, it is not passing the GET location variable to the /location/index.html page when you use the "pretty url" (e.g. <a href="http://example.com/location/90210" rel="nofollow noreferrer">http://example.com/location/90210</a>).</p> <p>I know this b/c when I echo out to the screen (<strong>using javascript</strong>) the location GET variable when the long url is used, it's set but when the pretty (short) url is used, the location GET variable is undefined.</p>
[ { "answer_id": 259406, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 2, "selected": false, "text": "<p>Your last example should work; I'd also check the condition to be case-insensitive (to avoid /LoCation/indeX.htmL from being parsed), terminate rewrite with [L] (to prevent infinite loops) and add QSA (for appending queries):</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{REQUEST_URI} !location/index.html [NC]\nRewriteRule ^location/(.*)$ /location/index.html?location=$1 [L,QSA]\n</code></pre>\n\n<p>How do you read out (and echo) the location GET variable? \"I'm using JavaScript to echo out an alert that prints the \"location\" variable.\"</p>\n\n<p>JavaScript runs inside your browser (\"client-side\"), therefore it works with the same data that your browser sees. I.e., if you point your browser at <code>http://www.example.com/foo/bar/</code> , then no matter what rewriting you use at the server, Javascript will still see \"<code>http://www.example.com/foo/bar/</code>\" as the location.</p>\n\n<p>To access the GET variables, you need some code to access them when the page is generated (\"server-side\"), before it is sent to the browser. For example, when you have a PHP-capable server, the following script at <a href=\"http://www.example.com/location/index.php\" rel=\"nofollow noreferrer\">http://www.example.com/location/index.php</a> and you redirect to it through something like the above code, it will be able to access and work with the GET variables:</p>\n\n<pre><code>&lt;?php\necho 'The location you entered is ' . $_GET['location'] . '.';\n?&gt;\n</code></pre>\n\n<p>When combined with the rewrite, for URL <code>http://www.example.com/location/Houston,TX</code> it will print out this:</p>\n\n<pre><code>The location you entered is Austin,TX.\n</code></pre>\n\n<p>(of course, there are many server-side languages, I'm using PHP as an example I'm most familiar with)</p>\n" }, { "answer_id": 259597, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 0, "selected": false, "text": "<p>Just to reiterate, the solution posted by Piskvor does work as expected. As per the comments on that, you're using javascript to pick up the query string, which is the problem. As far as javascript is concerned, the original URL is the one it sees. You can confirm this for yourself quickly:</p>\n\n<pre><code>alert(document.location.href);\n</code></pre>\n\n<p>if you need to get the value in javascript, i'd suggest using something like:</p>\n\n<pre><code>var regex = /location\\/(.*)$/;\nvar query = document.location.href.match(regex);\nalert(query[1]);\n\n// query[1] will contain \"90210\" in your example\n// http://example.com/location/90210\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33554/" ]
I want to be able to rewrite a URL from: ``` // examples http://example.com/location/New York, NY --> http://example.com/location/index.html?location=New York, NY http://example.com/location/90210 --> http://example.com/location/index.html?location=90210 http://example.com/location/Texas --> http://example.com/location/index.html?location=Texas http://example.com/location/ANYTHING.... --> http://example.com/location/index.html?location=ANYTHING... ``` using `.htaccess` and mod\_rewrite. Anyone know how to do this? I have tried: ``` RewriteEngine on RewriteCond %{REQUEST_URI} !location/index.html RewriteRule ^location/(.*)$ /location/index.html?location=$1 ``` However, it is not passing the GET location variable to the /location/index.html page when you use the "pretty url" (e.g. <http://example.com/location/90210>). I know this b/c when I echo out to the screen (**using javascript**) the location GET variable when the long url is used, it's set but when the pretty (short) url is used, the location GET variable is undefined.
Your last example should work; I'd also check the condition to be case-insensitive (to avoid /LoCation/indeX.htmL from being parsed), terminate rewrite with [L] (to prevent infinite loops) and add QSA (for appending queries): ``` RewriteEngine on RewriteCond %{REQUEST_URI} !location/index.html [NC] RewriteRule ^location/(.*)$ /location/index.html?location=$1 [L,QSA] ``` How do you read out (and echo) the location GET variable? "I'm using JavaScript to echo out an alert that prints the "location" variable." JavaScript runs inside your browser ("client-side"), therefore it works with the same data that your browser sees. I.e., if you point your browser at `http://www.example.com/foo/bar/` , then no matter what rewriting you use at the server, Javascript will still see "`http://www.example.com/foo/bar/`" as the location. To access the GET variables, you need some code to access them when the page is generated ("server-side"), before it is sent to the browser. For example, when you have a PHP-capable server, the following script at <http://www.example.com/location/index.php> and you redirect to it through something like the above code, it will be able to access and work with the GET variables: ``` <?php echo 'The location you entered is ' . $_GET['location'] . '.'; ?> ``` When combined with the rewrite, for URL `http://www.example.com/location/Houston,TX` it will print out this: ``` The location you entered is Austin,TX. ``` (of course, there are many server-side languages, I'm using PHP as an example I'm most familiar with)
259,389
<p>On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using <code>gethostbyname</code> or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant.</p> <p>Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of <code>gethostbyinterface("eth0")</code>?</p>
[ { "answer_id": 259422, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 2, "selected": false, "text": "<p><strong>edit:</strong> I saw you don't like shelling. Then you can look at how ifconfig does its job (it extracts at least some information from /proc).</p>\n\n<p>When you have interface name, you can do this (in your shell):</p>\n\n<pre><code>ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'\n</code></pre>\n\n<p>To enumerate interfaces you can use this:</p>\n\n<pre><code>ifconfig | egrep '^[^ ]' | awk '{print $1}'\n</code></pre>\n\n<p>Combined:</p>\n\n<pre><code>for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do\n echo -n \"${x}\"\n echo -n \" \"\n ifconfig \"${x}\" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'\ndone\n</code></pre>\n" }, { "answer_id": 259424, "author": "Walter", "author_id": 23840, "author_profile": "https://Stackoverflow.com/users/23840", "pm_score": 4, "selected": true, "text": "<pre class=\"lang-c prettyprint-override\"><code>// Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address\n\n#include &lt;sys/types.h&gt;\n#include &lt;sys/socket.h&gt;\n#include &lt;sys/ioctl.h&gt;\n#include &lt;net/if.h&gt;\n#include &lt;netinet/in.h&gt;\n#include &lt;arpa/inet.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n\n/**\n * getIPv4()\n *\n * This function takes a network identifier such as \"eth0\" or \"eth0:0\" and\n * a pointer to a buffer of at least 16 bytes and then stores the IP of that\n * device gets stored in that buffer.\n *\n * it return 0 on success or -1 on failure.\n *\n * Author: Jaco Kroon &lt;[email protected]&gt;\n */\nint getIPv4(const char * dev, char * ipv4) {\n struct ifreq ifc;\n int res;\n int sockfd = socket(AF_INET, SOCK_DGRAM, 0);\n\n if(sockfd &lt; 0)\n return -1;\n strcpy(ifc.ifr_name, dev);\n res = ioctl(sockfd, SIOCGIFADDR, &amp;ifc);\n close(sockfd);\n if(res &lt; 0)\n return -1; \n strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&amp;ifc.ifr_addr)-&gt;sin_addr));\n return 0;\n}\n\n\nint main() {\n char ip[16];\n if(getIPv4(\"eth0\", ip) == 0)\n printf(\"IPv4: %s\\n\", ip);\n else\n printf(\"No IP\\n\");\n return 0;\n }\n</code></pre>\n\n<p><strong>Update</strong>: Moved dead link to a comment (for posterity) (thanks @obayhan), and added syntax highlighting.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using `gethostbyname` or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant. Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of `gethostbyinterface("eth0")`?
```c // Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <unistd.h> /** * getIPv4() * * This function takes a network identifier such as "eth0" or "eth0:0" and * a pointer to a buffer of at least 16 bytes and then stores the IP of that * device gets stored in that buffer. * * it return 0 on success or -1 on failure. * * Author: Jaco Kroon <[email protected]> */ int getIPv4(const char * dev, char * ipv4) { struct ifreq ifc; int res; int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if(sockfd < 0) return -1; strcpy(ifc.ifr_name, dev); res = ioctl(sockfd, SIOCGIFADDR, &ifc); close(sockfd); if(res < 0) return -1; strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&ifc.ifr_addr)->sin_addr)); return 0; } int main() { char ip[16]; if(getIPv4("eth0", ip) == 0) printf("IPv4: %s\n", ip); else printf("No IP\n"); return 0; } ``` **Update**: Moved dead link to a comment (for posterity) (thanks @obayhan), and added syntax highlighting.
259,415
<p>When I changed the rankdir of my graph from LR to TD, my record nodes also changed their layout direction so they no longer look like a 'record'. I tried applying a separate rankdir to the nodes, but this had no effect.</p> <p>How does one keep the record nodes with the correct layout?</p> <pre><code>digraph sample { graph [rankdir=TD]; node [shape=record]; A [label="ShouldBeTop | ShouldBeBottom"]; B [label="Top | Bottom"]; A -&gt; B; } </code></pre>
[ { "answer_id": 259535, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 5, "selected": true, "text": "<p>Taking into account that rankdir effectively replaces the notion of \"top\" and \"bottom\" for the given graph, that's not surprising. </p>\n\n<p>I am afraid that there is no easy remedy for this, save hacking the source (and that would not be easy at all). You can surround your labels in \"{}\" with some kind of mass search-replace solution to get the requested effect:</p>\n\n<pre><code>digraph sample { graph [rankdir=TD]; node [shape=record];\n\nA [label=\"{ShouldBeTop | ShouldBeBottom}\"]; \nB [label=\"{Top | Bottom}\"]; A -&gt; B; \n}\n</code></pre>\n" }, { "answer_id": 6319544, "author": "Henrik Lindberg", "author_id": 327930, "author_profile": "https://Stackoverflow.com/users/327930", "pm_score": 3, "selected": false, "text": "<p>You can use html table like labels instead of records. IIRC the table based labels do not rotate with the rank direction. See <a href=\"http://www.graphviz.org/doc/info/shapes.html#html\" rel=\"noreferrer\">http://www.graphviz.org/doc/info/shapes.html#html</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32973/" ]
When I changed the rankdir of my graph from LR to TD, my record nodes also changed their layout direction so they no longer look like a 'record'. I tried applying a separate rankdir to the nodes, but this had no effect. How does one keep the record nodes with the correct layout? ``` digraph sample { graph [rankdir=TD]; node [shape=record]; A [label="ShouldBeTop | ShouldBeBottom"]; B [label="Top | Bottom"]; A -> B; } ```
Taking into account that rankdir effectively replaces the notion of "top" and "bottom" for the given graph, that's not surprising. I am afraid that there is no easy remedy for this, save hacking the source (and that would not be easy at all). You can surround your labels in "{}" with some kind of mass search-replace solution to get the requested effect: ``` digraph sample { graph [rankdir=TD]; node [shape=record]; A [label="{ShouldBeTop | ShouldBeBottom}"]; B [label="{Top | Bottom}"]; A -> B; } ```
259,435
<p>I'm trying to create a jqgrid, but the table is empty. The table renders, but the data doesn't show.</p> <p>The data I'm getting back from the php call is:</p> <pre><code>{ "page":"1", "total":1, "records":"10", "rows":[ {"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]}, {"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]}, {"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}, {"id":"2:4","cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]}, {"id":"2:5","cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]}, {"id":"2:6","cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]}, {"id":"2:7","cell":["7","image","Photography","To recognize photography knowledge and skills","0"]}, {"id":"2:8","cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]}, {"id":"2:10","cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]}, {"id":"2:11","cell":["11","image","World Conservation","World Conservation Badge","0"]} ]} </code></pre> <p>The javascript configuration looks like so:</p> <pre><code>$("#"+tableId).jqGrid ({ url:'getAwards.php?id='+classId, dataType : 'json', mtype:'POST', colNames:['Id','Badge','Name','Description',''], colModel : [ {name:'awardId', width:30, sortable:true, align:'center'}, {name:'badge', width:40, sortable:false, align:'center'}, {name:'name', width:180, sortable:true, align:'left'}, {name:'description', width:380, sortable:true, align:'left'}, {name:'selected', width:0, sortable:false, align:'center'} ], sortname: "awardId", sortorder: "asc", pager: $('#'+tableId+'_pager'), rowNum:15, rowList:[15,30,50], caption: 'Awards', viewrecords:true, imgpath: 'scripts/jqGrid/themes/green/images', jsonReader : { root: "rows", page: "page", total: "total", records: "records", repeatitems: true, cell: "cell", id: "id", userdata: "userdata", subgrid: {root:"rows", repeatitems: true, cell:"cell" } }, width: 700, height: 200 }); </code></pre> <p>The HTML looks like:</p> <pre><code>&lt;table class="awardsList" id="awardsList2" class="scroll" name="awardsList" /&gt; &lt;div id="awardsList2_pager" class="scroll"&gt;&lt;/div&gt; </code></pre> <p>I'm not sure that I needed to define jsonReader, since I've tried to keep to the default. If the php code will help, I can post it too.</p>
[ { "answer_id": 260059, "author": "jgreep", "author_id": 16345, "author_profile": "https://Stackoverflow.com/users/16345", "pm_score": 5, "selected": true, "text": "<p>I got it to work!</p>\n\n<p>The <strong>dataType</strong> field should be <strong>datatype</strong>. It's case sensitive.</p>\n" }, { "answer_id": 711585, "author": "darren", "author_id": 51688, "author_profile": "https://Stackoverflow.com/users/51688", "pm_score": 0, "selected": false, "text": "<p>I don't think your ID is the correct type, I think it should be an int.</p>\n\n<p>For the given json you really don't need the jsonreader settings. What you have listed is the defaults anyway, plus you don't have a subgrid in your json.</p>\n\n<p>Try this:</p>\n\n<pre><code>{\n\"page\":\"1\",\n\"total\":1,\n\"records\":\"10\",\n\"rows\":[\n{\"id\":1 ,\"cell\":[\"1\",\"image\",\"Chief Scout\",\"Highest Award test\",\"0\"]},\n{\"id\":2,\"cell\":[\"2\",\"image\",\"Link Badge\",\"When you are invested as a Scout, you maybe eligible to receive a Link Badge. (See page 45)\",\"0\"]},\n{\"id\":3,\"cell\":[\"3\",\"image\",\"Pioneer Scout\",\"Upon completion of requirements, the youth is invested as a Pioneer Scout\",\"0\"]},\n{\"id\":4,\"cell\":[\"4\",\"image\",\"Voyageur Scout Award\",\"Voyageur Scout Award is the right after Pioneer Scout.\",\"0\"]},\n{\"id\":5,\"cell\":[\"5\",\"image\",\"Voyageur Citizenship\",\"Learning about and caring for your community.\",\"0\"]},\n{\"id\":6,\"cell\":[\"6\",\"image\",\"Fish and Wildlife\",\"Demonstrate your knowledge and involvement in fish and wildlife management.\",\"0\"]},\n{\"id\":7,\"cell\":[\"7\",\"image\",\"Photography\",\"To recognize photography knowledge and skills\",\"0\"]},\n{\"id\":8,\"cell\":[\"8\",\"image\",\"Recycling\",\"Demonstrate your knowledge and involvement in Recycling\",\"0\"]},\n{\"id\":9,\"cell\":[\"10\",\"image\",\"Voyageur Leadership \",\"Show leadership ability\",\"0\"]},\n{\"id\":10,\"cell\":[\"11\",\"image\",\"World Conservation\",\"World Conservation Badge\",\"0\"]}\n]}\n</code></pre>\n" }, { "answer_id": 2639229, "author": "StuFuller", "author_id": 307838, "author_profile": "https://Stackoverflow.com/users/307838", "pm_score": 1, "selected": false, "text": "<p>I also got it to work: datatype is the correct spelling -- it's shown that way in the example but it is inconsistent with <em>everything</em> else in the library so it was easy to get wrong</p>\n\n<p>I'm getting very tired chasing this sparse documentation around and I really feel like JSON, which is right and proper to be using in JavaScript, has really been given short coverage in favor of XML. Python and JavaScript together, through JSON, is a really strong combination, but it's a constant struggle with this particular library.</p>\n\n<p>Anyone with an alternative that:</p>\n\n<p>1> Properly supports jQuery UI themes (including rounded corners!) (<a href=\"http://datatables.net\" rel=\"nofollow noreferrer\">http://datatables.net</a> has much nicer support for themes)</p>\n\n<p>2> Allows resizing of columns (<a href=\"http://datatables.net\" rel=\"nofollow noreferrer\">http://datatables.net</a> doesn't support this out of the box)</p>\n\n<p>3> Allows sub-grids (<a href=\"http://datatables.net\" rel=\"nofollow noreferrer\">http://datatables.net</a> lets you do whatever you want here, through an event)</p>\n\n<p>please let me know. I'm spending more time on this one part of my interface than on the whole rest of it combined and it's all the time spent searching for working examples and \"trying things\" which is just getting annoying.</p>\n\n<p>S</p>\n" }, { "answer_id": 2988424, "author": "katrin", "author_id": 360259, "author_profile": "https://Stackoverflow.com/users/360259", "pm_score": 3, "selected": false, "text": "<p>The problem also occures when you include script <em>jquery.jqGrid.min.js</em> before then <em>grid.locale-en.js</em>. Check this if there are any problems with controller's method call.</p>\n" }, { "answer_id": 3714881, "author": "Rosdi Kasim", "author_id": 193634, "author_profile": "https://Stackoverflow.com/users/193634", "pm_score": 2, "selected": false, "text": "<p>I experienced the same problem when migrating from jqGrid 3.6 to jqGrid 3.7.2. The problem was my JSON was not properly double-quoted (as required by JSON spec). jqGrid 3.6 tolerated my invalid JSON but jqGrid 3.7 is stricter.</p>\n\n<p>Refer here: <a href=\"http://simonwillison.net/2006/Oct/11/json/\" rel=\"nofollow noreferrer\">http://simonwillison.net/2006/Oct/11/json/</a></p>\n\n<p><strong>Invalid</strong>:</p>\n\n<pre><code>{\npage:\"1\",\ntotal:1,\nrecords:\"10\",\nrows:[\n {\"id\":\"2:1\",\"cell\":[\"1\",\"image\",\"Chief Scout\",\"Highest Award test\",\"0\"]},\n {\"id\":\"2:2\",\"cell\":[\"2\",\"image\",\"Link Badge\",\"When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)\",\"0\"]},\n {\"id\":\"2:3\",\"cell\":[\"3\",\"image\",\"Pioneer Scout\",\"Upon completion of requirements, the youth is invested as a Pioneer Scout\",\"0\"]}\n]}\n</code></pre>\n\n<p><strong>Valid</strong>:</p>\n\n<pre><code>{\n\"page\":\"1\",\n\"total\":1,\n\"records\":\"10\",\n\"rows\":[\n {\"id\":\"2:1\",\"cell\":[\"1\",\"image\",\"Chief Scout\",\"Highest Award test\",\"0\"]},\n {\"id\":\"2:2\",\"cell\":[\"2\",\"image\",\"Link Badge\",\"When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)\",\"0\"]},\n {\"id\":\"2:3\",\"cell\":[\"3\",\"image\",\"Pioneer Scout\",\"Upon completion of requirements, the youth is invested as a Pioneer Scout\",\"0\"]}\n]}\n</code></pre>\n" }, { "answer_id": 5037871, "author": "jejernig", "author_id": 616499, "author_profile": "https://Stackoverflow.com/users/616499", "pm_score": 1, "selected": false, "text": "<p>This might be a older post but I will post my success just to help others.</p>\n\n<p>Your JSON needs to be in this format:</p>\n\n<pre><code>{\n\"rows\": [\n {\n \"id\": 1,\n \"cell\": [\n 1,\n \"lname\",\n \"fname\",\n \"mi\",\n phone,\n \"cell1\",\n \"cell2\",\n \"address\",\n \"email\"\n ]\n },\n {\n \"id\": 2,\n \"cell\": [\n 2,\n \"lname\",\n \"fname\",\n \"mi\",\n phone,\n \"cell1\",\n \"cell2\",\n \"address\",\n \"email\"\n ]\n }\n]\n</code></pre>\n\n<p>}</p>\n\n<p>and I wrote this model in Zend so you can use it if you feel like it. Manipulate it how you want.</p>\n\n<pre><code>public function fetchall ($sid, $sord)\n{\n $select = $this-&gt;getDbTable()-&gt;select(Zend_Db_Table::SELECT_WITH_FROM_PART);\n $select-&gt;setIntegrityCheck(false)\n -&gt;join('Subdiv', 'Subdiv.SID = Contacts.SID', array(\"RepLastName\" =&gt; \"LastName\", \n \"Subdivision\" =&gt; \"Subdivision\",\n \"RepFirstName\" =&gt; \"FirstName\"))\n -&gt;order($sid . \" \". $sord);\n\n $resultset = $this-&gt;getDbTable()-&gt;fetchAll($select);\n $i=0;\n foreach ($resultset as $row) {\n $entry = new Application_Model_Contacts();\n\n $entry-&gt;setId($row-&gt;id);\n $entry-&gt;setLastName($row-&gt;LastName);\n $entry-&gt;setFirstName1($row-&gt;FirstName1);\n $entry-&gt;setFirstName2($row-&gt;FirstName2);\n $entry-&gt;setHomePhone($row-&gt;HomePhone);\n $entry-&gt;setCell1($row-&gt;Cell1);\n $entry-&gt;setCell2($row-&gt;Cell2);\n $entry-&gt;setAddress($row-&gt;Address);\n $entry-&gt;setSubdivision($row-&gt;Subdivision);\n $entry-&gt;setRepName($row-&gt;RepFirstName . \" \" . $row-&gt;RepLastName);\n $entry-&gt;setEmail1($row-&gt;Email1); \n $entry-&gt;setEmail2($row-&gt;Email2);\n\n $response['rows'][$i]['id'] = $entry-&gt;getId(); //id\n $response['rows'][$i]['cell'] = array (\n $entry-&gt;getId(),\n $entry-&gt;getLastName(),\n $entry-&gt;getFirstName1(),\n $entry-&gt;getFirstName2(),\n $entry-&gt;getHomePhone(),\n $entry-&gt;getCell1(),\n $entry-&gt;getCell2(),\n $entry-&gt;getAddress(),\n $entry-&gt;getSubdivision(),\n $entry-&gt;getRepName(),\n $entry-&gt;getEmail1(),\n $entry-&gt;getEmail2()\n );\n $i++;\n\n }\n return $response;\n}\n</code></pre>\n" }, { "answer_id": 8325828, "author": "Anil Baviskar", "author_id": 1073303, "author_profile": "https://Stackoverflow.com/users/1073303", "pm_score": 1, "selected": false, "text": "<p>Guys just want to help you in this. I got following worked:</p>\n\n<p><strong>JSON</strong></p>\n\n<pre><code>var mydata1 = { \"page\": \"1\", \"total\": 1, \"records\": \"4\",\"rows\": [{ \"id\": 1, \"cell\": [\"1\", \"cell11\", \"values1\" ] },\n { \"id\": 2, \"cell\": [\"2\", \"cell21\", \"values1\"] },\n { \"id\": 3, \"cell\": [\"3\", \"cell21\", \"values1\"] },\n { \"id\": 4, \"cell\": [\"4\", \"cell21\", \"values1\"] }\n]};\n</code></pre>\n\n<p><strong>//Mark below important line. datatype \"jsonstring\" worked for me instead of \"json\".</strong></p>\n\n<pre><code>datatype: \"jsonstring\",\n\ncontentType: \"application/json; charset=utf-8\",\n\ndatastr: mydata1,\n\ncolNames: ['Id1', 'Name1', 'Values1'],\n\ncolModel: [\n { name: 'id1', index: 'id1', width: 55 },\n { name: 'name1', index: 'name1', width: 80, align: 'right', sorttype: 'string' },\n { name: 'values1', index: 'values1', width: 80, align: 'right', sorttype: 'string'}],\n</code></pre>\n\n<p>Regards,</p>\n" }, { "answer_id": 8719851, "author": "Mariusz", "author_id": 1128843, "author_profile": "https://Stackoverflow.com/users/1128843", "pm_score": 1, "selected": false, "text": "<p>In my case, the problem was caused by the following line of PHP code (which was taken from jqGrid demo): </p>\n\n<pre><code>$responce-&gt;page = $page;\n</code></pre>\n\n<p>What is wrong here is that: I am accessing property page of object <code>$responce</code> without creating it first. This caused Apache to display the following error message: </p>\n\n<pre><code>Strict Standards: Creating default object from empty value in /home/mariusz/public_html/rezerwacja/apps/frontend/modules/service/actions/actions.class.php on line 35\n</code></pre>\n\n<p>And finally the error message used to be send to json reader within the script. </p>\n\n<p>I fixed the problem by creating empty object: </p>\n\n<pre><code>$responce = new stdClass();\n</code></pre>\n" }, { "answer_id": 20460166, "author": "Alfx2", "author_id": 3078388, "author_profile": "https://Stackoverflow.com/users/3078388", "pm_score": 0, "selected": false, "text": "<p>I was working with WAMP 2.4, I was being crazy with this problem, I tried lot of things, like install previous versions of PHP and like 5.2, een I tried in Windows XP, and lots of jqGrid options.\nWell thank to Oleg finally and Mariusz I find the only line: </p>\n\n<pre><code>$responce = new stdClass(); \n</code></pre>\n\n<p>Before the use of $responce could solve all, and now my grid is works Great!!!</p>\n\n<p>Thanks my friends.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16345/" ]
I'm trying to create a jqgrid, but the table is empty. The table renders, but the data doesn't show. The data I'm getting back from the php call is: ``` { "page":"1", "total":1, "records":"10", "rows":[ {"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]}, {"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]}, {"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}, {"id":"2:4","cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]}, {"id":"2:5","cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]}, {"id":"2:6","cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]}, {"id":"2:7","cell":["7","image","Photography","To recognize photography knowledge and skills","0"]}, {"id":"2:8","cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]}, {"id":"2:10","cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]}, {"id":"2:11","cell":["11","image","World Conservation","World Conservation Badge","0"]} ]} ``` The javascript configuration looks like so: ``` $("#"+tableId).jqGrid ({ url:'getAwards.php?id='+classId, dataType : 'json', mtype:'POST', colNames:['Id','Badge','Name','Description',''], colModel : [ {name:'awardId', width:30, sortable:true, align:'center'}, {name:'badge', width:40, sortable:false, align:'center'}, {name:'name', width:180, sortable:true, align:'left'}, {name:'description', width:380, sortable:true, align:'left'}, {name:'selected', width:0, sortable:false, align:'center'} ], sortname: "awardId", sortorder: "asc", pager: $('#'+tableId+'_pager'), rowNum:15, rowList:[15,30,50], caption: 'Awards', viewrecords:true, imgpath: 'scripts/jqGrid/themes/green/images', jsonReader : { root: "rows", page: "page", total: "total", records: "records", repeatitems: true, cell: "cell", id: "id", userdata: "userdata", subgrid: {root:"rows", repeatitems: true, cell:"cell" } }, width: 700, height: 200 }); ``` The HTML looks like: ``` <table class="awardsList" id="awardsList2" class="scroll" name="awardsList" /> <div id="awardsList2_pager" class="scroll"></div> ``` I'm not sure that I needed to define jsonReader, since I've tried to keep to the default. If the php code will help, I can post it too.
I got it to work! The **dataType** field should be **datatype**. It's case sensitive.
259,451
<p>I want to record sound (voice) using PortAudio (PyAudio) and output the corresponding sound wave on the screen. Hopeless as I am, I am unable to extract the frequency information from the audio stream so that I can draw it in Hz/time form.</p> <hr> <p>Here's an example code snippet that records and plays recorded audio for five seconds, in case it helps any:</p> <pre><code>p = pyaudio.PyAudio() chunk = 1024 seconds = 5 stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, output=True) for i in range(0, 44100 / chunk * seconds): data = stream.read(chunk) stream.write(data, chunk) </code></pre> <p>I wish to extract the needed information from the above variable "data". (Or use some other high-level approach with PortAudio or another library with Python bindings.)</p> <hr> <p>I'd be very grateful for any help! Even vaguely related tidbits of audio-analyzing wisdom are appreciated. :)</p>
[ { "answer_id": 259521, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": true, "text": "<p>What you want is probably the Fourier transform of the audio data. There is several packages that can calculate that for you. <code>scipy</code> and <code>numpy</code> is two of them. It is often named \"Fast Fourier Transform\" (FFT), but that is just the name of the algorithm.</p>\n\n<p>Here is an example of it's usage: <a href=\"https://svn.enthought.com/enthought/browser/Chaco/trunk/examples/advanced/spectrum.py\" rel=\"nofollow noreferrer\">https://svn.enthought.com/enthought/browser/Chaco/trunk/examples/advanced/spectrum.py</a></p>\n" }, { "answer_id": 569314, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The Fourier Transform will not help you a lot if you want the analysis to be conducted in both the frequency and time domain. You might want to have a look at \"Wavelet Transforms\". There is a package called pywavelets...\n<a href=\"http://www.pybytes.com/pywavelets/#discrete-wavelet-transform-dwt\" rel=\"nofollow noreferrer\">http://www.pybytes.com/pywavelets/#discrete-wavelet-transform-dwt</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to record sound (voice) using PortAudio (PyAudio) and output the corresponding sound wave on the screen. Hopeless as I am, I am unable to extract the frequency information from the audio stream so that I can draw it in Hz/time form. --- Here's an example code snippet that records and plays recorded audio for five seconds, in case it helps any: ``` p = pyaudio.PyAudio() chunk = 1024 seconds = 5 stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, output=True) for i in range(0, 44100 / chunk * seconds): data = stream.read(chunk) stream.write(data, chunk) ``` I wish to extract the needed information from the above variable "data". (Or use some other high-level approach with PortAudio or another library with Python bindings.) --- I'd be very grateful for any help! Even vaguely related tidbits of audio-analyzing wisdom are appreciated. :)
What you want is probably the Fourier transform of the audio data. There is several packages that can calculate that for you. `scipy` and `numpy` is two of them. It is often named "Fast Fourier Transform" (FFT), but that is just the name of the algorithm. Here is an example of it's usage: <https://svn.enthought.com/enthought/browser/Chaco/trunk/examples/advanced/spectrum.py>
259,455
<p>In the following code, both the INPUT and TEXTAREA elements render wider than they should. How can I limit them to 100% of the usable area within the div?</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;style&gt; .mywidth{ width:100%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div style="border: 3px solid green; width: 100px;"&gt; &lt;input class="mywidth" &gt;&lt;br /&gt; &lt;textarea class="mywidth"&gt;&lt;/textarea&gt;&lt;br /&gt; &lt;div style="background-color: yellow;" class="mywidth"&gt;test&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Note: If I remove the DOCTYPE, it renders as expected, with the INPUT, TEXTAREA and inner DIV all the same width and not going outside the containing DIV.</p> <p>Update: Not withstanding the default borders on those elements, it still appears to render incorrectly in <strong>IE7</strong>.</p>
[ { "answer_id": 259479, "author": "Jaime Garcia", "author_id": 32812, "author_profile": "https://Stackoverflow.com/users/32812", "pm_score": 0, "selected": false, "text": "<p>You could try using this DOCTYPE instead</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n</code></pre>\n" }, { "answer_id": 259481, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 4, "selected": true, "text": "<p>Inputs and textareas both have borders by default</p>\n\n<pre><code>&lt;style&gt;\n .mywidth{ \n width:100%;\n border:0;\n } \n&lt;/style&gt;\n</code></pre>\n\n<p>will render all the elements within your container.</p>\n\n<p><strong>Update</strong></p>\n\n<p>IE also has left and right padding on each element and the following css fits all the elements within the container in FF3, FF2, Safari 3, IE6 and IE7.</p>\n\n<pre><code>&lt;style&gt;\n .mywidth{ width:100%; border:0; padding-left:0; padding-right:0; }\n&lt;/style&gt;\n</code></pre>\n\n<p>However, don't forget that you will probably need a border, and perhaps the padding too, in order to make the fields appear to users as normal. If you set that border and padding yourself then you will know what the difference is, across browsers, between the width of the container and the width you will need to give to the input/textarea elements.</p>\n" }, { "answer_id": 259495, "author": "Toby Mills", "author_id": 12377, "author_profile": "https://Stackoverflow.com/users/12377", "pm_score": 0, "selected": false, "text": "<p>Add \"padding-right:3px;\" to the div so it reads as:</p>\n\n<pre><code>&lt;div style=\"border: 3px solid green;padding-right:3px; width: 100px;\"&gt;\n</code></pre>\n\n<p>Because you have added a border to the div that also counts as internal space of the div.</p>\n\n<p>The reason it works without the doc declaration is that the browser does not render the page as transitional XHTML but plain old html which has a different rendering method for div's etc.</p>\n" }, { "answer_id": 259499, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 1, "selected": false, "text": "<p>@Phil has the answer, above.</p>\n\n<p>Incidentally, using <a href=\"http://getfirebug.com/\" rel=\"nofollow noreferrer\">Firebug</a> does, indeed, show the default borders on the textarea and input elements. So, using Firebug might have helped.</p>\n" }, { "answer_id": 1147755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>xhtml strict code seems to do that with forms. \ni just make the inputs and textareas stretch at 99% and that seems to work.\ngive that a try.</p>\n" }, { "answer_id": 3309303, "author": "bmaupin", "author_id": 399105, "author_profile": "https://Stackoverflow.com/users/399105", "pm_score": 4, "selected": false, "text": "<p>I had this same problem. I used the box-sizing property mentioned here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/271067/how-can-i-make-a-textarea-100-width-without-overflowing-when-padding-is-present#answer-2515439\">How can I make a TextArea 100% width without overflowing when padding is present in CSS?</a></p>\n\n<p>Here's what it looked like for me:</p>\n\n<pre><code>&lt;style&gt;\n .mywidth{ \n width:100%;\n -moz-box-sizing: border-box;\n -ms-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n } \n&lt;/style&gt;\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
In the following code, both the INPUT and TEXTAREA elements render wider than they should. How can I limit them to 100% of the usable area within the div? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <style> .mywidth{ width:100%; } </style> </head> <body> <div style="border: 3px solid green; width: 100px;"> <input class="mywidth" ><br /> <textarea class="mywidth"></textarea><br /> <div style="background-color: yellow;" class="mywidth">test</div> </div> </body> </html> ``` Note: If I remove the DOCTYPE, it renders as expected, with the INPUT, TEXTAREA and inner DIV all the same width and not going outside the containing DIV. Update: Not withstanding the default borders on those elements, it still appears to render incorrectly in **IE7**.
Inputs and textareas both have borders by default ``` <style> .mywidth{ width:100%; border:0; } </style> ``` will render all the elements within your container. **Update** IE also has left and right padding on each element and the following css fits all the elements within the container in FF3, FF2, Safari 3, IE6 and IE7. ``` <style> .mywidth{ width:100%; border:0; padding-left:0; padding-right:0; } </style> ``` However, don't forget that you will probably need a border, and perhaps the padding too, in order to make the fields appear to users as normal. If you set that border and padding yourself then you will know what the difference is, across browsers, between the width of the container and the width you will need to give to the input/textarea elements.
259,456
<p>I am working on implementing Zend Framework within an existing project that has a public marketing area, a private members area, an administration site, and a marketing campaign management site. Currently these are poorly organized with the controller scripts for the marketing area and the members area all being under the root of the site and then a separate folder for admin and another folder for the marketing campaign site.</p> <p>In implementing the Zend Framework, I would like to create be able to split the controllers and views into modules (one for the members area, one for the public marketing area, one for the admin site, and one for the marketing campaign admin site) but I need to be able to point each module to the same model's since all three components work on the same database and on the same business objects.</p> <p>However, I haven't been able to find any information on how to do this in the documentation. Can anyone help with either a link on how to do this or some simple instructions on how to accomplish it?</p>
[ { "answer_id": 259489, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "<p>What I do is keep common classes in a \"library\" directory outside of the modules hierarchy. Then set my <code>INCLUDE_PATH</code> to use the \"models\" directory of the respective module, plus the common \"library\" directory.</p>\n\n<pre><code>docroot/\n index.php\napplication/\n library/ &lt;-- common classes go here\n default/\n controllers/\n models/\n views/\n members/\n controllers/\n models/\n views/\n admin/\n controllers/\n models/\n views/\n. . .\n</code></pre>\n\n<p>In my bootstrap script, I'd add \"<code>application/library/</code>\" to the <code>INCLUDE_PATH</code>. Then in each controller's <code>init()</code> function, I'd add that module's \"<code>models/</code>\" directory to the <code>INCLUDE_PATH</code>.</p>\n\n<p><strong>edit:</strong> Functions like <code>setControllerDirectory()</code> and <code>setModuleDirectory()</code> don't add the respective models directories to the <code>INCLUDE_PATH</code>. You have to do this yourself in any case. Here's one example of how to do it:</p>\n\n<pre><code>$app = APPLICATION_HOME; // you should define this in your bootstrap\n$d = DIRECTORY_SEPARATOR;\n$module = $this-&gt;_request-&gt;getModuleName(); // available after routing\nset_include_path(\n join(PATH_SEPARATOR,\n array(\n \"$app{$d}library\",\n \"$app{$d}$module{$d}models\",\n get_include_path()\n )\n )\n);\n</code></pre>\n\n<p>You could add the \"<code>library</code>\" to your path in the bootstrap, but you can't add the \"<code>models</code>\" directory for the correct module in the bootstrap, because the module depends on routing. Some people do this in the <code>init()</code> method of their controllers, and some people write a plugin for the ActionController's preDispatch hook to set the <code>INCLUDE_PATH</code>.</p>\n" }, { "answer_id": 293481, "author": "D-Rock", "author_id": 36780, "author_profile": "https://Stackoverflow.com/users/36780", "pm_score": 2, "selected": false, "text": "<p>This can also be accomplished through a naming convention to follow <code>Zend_Loader</code>. Keep your model files in the models folder under their module folder. Name them as <code>Module_Models_ModelName</code> and save them in a file name ModelName.php in the models folder for that module. Make sure the application folder is in your include path and assuming you are using <code>Zend_Loader</code> for auto loading, you can then just reference the models by their class name.</p>\n\n<p>This has the advantage of keeping your model code grouped in with the actual module it is for. This keeps the module contained within a single folder structure which helps encourage encapsulation. This will also help in the future if you need to port the module to another project.</p>\n" }, { "answer_id": 890622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm having the same problem.\nBill's answer doesn't fit for me - cos i tend to divide my modules, not by 'who is seeing them', but by 'what they do'. E.g a 'forum module' might be managed by both admin and public.\nI'm trying to have front end modules, like admin, members , public - but these then use other modules like 'forum/validatepost', 'forum/show users personal info'. \nIf anyone could shed light on how they protect a back-end module from the public , then that would be handy. I guess ACL may be the key but it still makes me nervous having access controlled by objects as opposed 'file system/.htaccess' etc. </p>\n\n<p>To answer PHPoet's question : \n(i) Paths to module's controller directories can be specified by calls to front controller: \ne.g see : \"12.11.2. Specifying Module Controller Directories\" (Zend Framework Docs)</p>\n\n<p>(ii) Paths to views can be set using ViewRenderer (Controller Action Helper)\ne.g. see: 'Example 12.12. Choosing a Different View Script' (Zend Framework Docs)</p>\n\n<p>By playing around its possible to alter the default paths to views and controllers, thus freeing up your autoloader to run as normal.</p>\n\n<p>(I have not looked into the way autoloader works, but it would make sense for it to have some mapper system to solve this kind of issue.)</p>\n" }, { "answer_id": 942394, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 1, "selected": false, "text": "<p>I just built this custom Action Helper for the problem you describe:</p>\n\n<pre><code>&lt;?php\n\nclass My_Controller_Action_Helper_GetModel extends Zend_Controller_Action_Helper_Abstract\n{\n /**\n * @var Zend_Loader_PluginLoader\n */\n protected $_loader;\n\n /**\n * Initialize plugin loader for models\n * \n * @return void\n */\n public function __construct()\n {\n // Get all models across all modules\n $front = Zend_Controller_Front::getInstance();\n $curModule = $front-&gt;getRequest()-&gt;getModuleName();\n\n // Get all module names, move default and current module to\n // back of the list so their models get precedence\n $modules = array_diff(\n array_keys($front-&gt;getDispatcher()-&gt;getControllerDirectory()),\n array('default', $curModule)\n );\n $modules[] = 'default';\n if ($curModule != 'default') {\n $modules[] = $curModule;\n }\n\n // Generate namespaces and paths for plugin loader\n $pluginPaths = array();\n foreach($modules as $module) {\n $pluginPaths[ucwords($module)] = $front-&gt;getModuleDirectory($module) . '/models';\n }\n\n // Load paths\n $this-&gt;_loader = new Zend_Loader_PluginLoader($pluginPaths);\n }\n\n /**\n * Load a model class and return an object instance\n * \n * @param string $model \n * @return object\n */\n public function getModel($model)\n {\n $class = $this-&gt;_loader-&gt;load($model);\n return new $class;\n }\n\n /**\n * Proxy to getModel()\n * \n * @param string $model \n * @return object\n */\n public function direct($model)\n {\n return $this-&gt;getModel($model);\n }\n}\n</code></pre>\n\n<p>So in your Bootstrap.php:</p>\n\n<pre><code>Zend_Controller_Action_HelperBroker::addPrefix('My_Controller_Action_Helper');\n</code></pre>\n\n<p>And in any of your controllers:</p>\n\n<pre><code>&lt;?php\n\nclass IndexController extends Zend_Controller_Action \n{\n public function indexAction() \n {\n $model = $this-&gt;_helper-&gt;getModel('SomeModel');\n }\n}\n</code></pre>\n\n<p>And this will allow your access to models in any controller across all modules.</p>\n" }, { "answer_id": 19151620, "author": "Dharmesh Vasani", "author_id": 5748531, "author_profile": "https://Stackoverflow.com/users/5748531", "pm_score": 0, "selected": false, "text": "<p></p>\n\n<pre><code>&lt;?php\nreturn array(\n'modules' =&gt; array(\n 'Application',\n 'DoctrineModule',\n 'DoctrineORMModule',\n 'Merchant',\n),\n'module_listener_options' =&gt; array(\n 'config_glob_paths' =&gt; array(\n 'config/autoload/{,*.}{global,local}.php',\n ),\n 'module_paths' =&gt; array(\n './module',\n '../vendor',\n// 'here we can load module'\n 'comomonmodule' \n\n ),\n),\n);\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178/" ]
I am working on implementing Zend Framework within an existing project that has a public marketing area, a private members area, an administration site, and a marketing campaign management site. Currently these are poorly organized with the controller scripts for the marketing area and the members area all being under the root of the site and then a separate folder for admin and another folder for the marketing campaign site. In implementing the Zend Framework, I would like to create be able to split the controllers and views into modules (one for the members area, one for the public marketing area, one for the admin site, and one for the marketing campaign admin site) but I need to be able to point each module to the same model's since all three components work on the same database and on the same business objects. However, I haven't been able to find any information on how to do this in the documentation. Can anyone help with either a link on how to do this or some simple instructions on how to accomplish it?
What I do is keep common classes in a "library" directory outside of the modules hierarchy. Then set my `INCLUDE_PATH` to use the "models" directory of the respective module, plus the common "library" directory. ``` docroot/ index.php application/ library/ <-- common classes go here default/ controllers/ models/ views/ members/ controllers/ models/ views/ admin/ controllers/ models/ views/ . . . ``` In my bootstrap script, I'd add "`application/library/`" to the `INCLUDE_PATH`. Then in each controller's `init()` function, I'd add that module's "`models/`" directory to the `INCLUDE_PATH`. **edit:** Functions like `setControllerDirectory()` and `setModuleDirectory()` don't add the respective models directories to the `INCLUDE_PATH`. You have to do this yourself in any case. Here's one example of how to do it: ``` $app = APPLICATION_HOME; // you should define this in your bootstrap $d = DIRECTORY_SEPARATOR; $module = $this->_request->getModuleName(); // available after routing set_include_path( join(PATH_SEPARATOR, array( "$app{$d}library", "$app{$d}$module{$d}models", get_include_path() ) ) ); ``` You could add the "`library`" to your path in the bootstrap, but you can't add the "`models`" directory for the correct module in the bootstrap, because the module depends on routing. Some people do this in the `init()` method of their controllers, and some people write a plugin for the ActionController's preDispatch hook to set the `INCLUDE_PATH`.
259,457
<p>If I've got an array of values that are basically zerofilled string representations of various numbers and another array of integers, will <code>array_intersect()</code> still match elements of different types?</p> <p>For example, would this work:</p> <pre><code>$arrayOne = array('0003', '0004', '0005'); $arrayTwo = array(4, 5, 6); $intersect = array_intersect($arrayOne, $arrayTwo); // $intersect would then be = "array(4, 5)" </code></pre> <p>And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run <code>array_intersect()</code> after?</p>
[ { "answer_id": 259467, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 3, "selected": true, "text": "<p>$ cat > test.php</p>\n\n<pre><code>&lt;?php\n$arrayOne = array('0003', '0004', '0005');\n$arrayTwo = array(4, 5, 6);\n\n$intersect = array_intersect($arrayOne, $arrayTwo);\n\nprint_r($intersect );\n\n?&gt;\n</code></pre>\n\n<p>$ php test.php </p>\n\n<p>Array\n(\n)</p>\n\n<p>$</p>\n\n<p>So no, it will not. But if you add </p>\n\n<pre><code>foreach($arrayOne as $key =&gt; $value)\n{\n $arrayOne[$key] = intval($value);\n}\n</code></pre>\n\n<p>you will get </p>\n\n<p>$ php test.php</p>\n\n<p>Array\n(\n [1] => 4\n [2] => 5\n)</p>\n" }, { "answer_id": 259469, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://it2.php.net/manual/en/function.array-intersect.php\" rel=\"nofollow noreferrer\">http://it2.php.net/manual/en/function.array-intersect.php</a>:</p>\n\n<blockquote>\n<pre><code>Note: Two elements are considered equal if and only if\n(string) $elem1 === (string) $elem2.\nIn words: when the string representation is the same. \n</code></pre>\n</blockquote>\n\n<p>In your example, $intersect will be an empty array because 5 !== \"005\" and 4 !== \"004\"</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
If I've got an array of values that are basically zerofilled string representations of various numbers and another array of integers, will `array_intersect()` still match elements of different types? For example, would this work: ``` $arrayOne = array('0003', '0004', '0005'); $arrayTwo = array(4, 5, 6); $intersect = array_intersect($arrayOne, $arrayTwo); // $intersect would then be = "array(4, 5)" ``` And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run `array_intersect()` after?
$ cat > test.php ``` <?php $arrayOne = array('0003', '0004', '0005'); $arrayTwo = array(4, 5, 6); $intersect = array_intersect($arrayOne, $arrayTwo); print_r($intersect ); ?> ``` $ php test.php Array ( ) $ So no, it will not. But if you add ``` foreach($arrayOne as $key => $value) { $arrayOne[$key] = intval($value); } ``` you will get $ php test.php Array ( [1] => 4 [2] => 5 )
259,480
<p>I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:</p> <pre><code>bool isNull = (i == null); </code></pre> <p>or</p> <pre><code>bool isNull = !i.HasValue; </code></pre> <p>Also when assigning to a non-null type is this:</p> <pre><code>long? i = 1; long j = (long)i; </code></pre> <p>better than:</p> <pre><code>long? i = 1; long j = i.Value; </code></pre>
[ { "answer_id": 259490, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 3, "selected": false, "text": "<p>I would always use the (i==null) form. It expresses what you are doing.</p>\n\n<p>WRT the second question, I think either form is fine. However I'd always check it against null first and take appropriate action - perhaps wrapping that check and action up in a helper method (often it just sets a default value).</p>\n" }, { "answer_id": 259494, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 0, "selected": false, "text": "<p>They're both the same, but I would use the former version on both, since it's more common in the language: comparison to null and casting to a type.</p>\n" }, { "answer_id": 259496, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 0, "selected": false, "text": "<p>I usually tend to lean towards the first option in both scenarios, since it's more 'primitive' oriented opposed to object oriented (which was really what we were going for), but it really doesn't matter that much</p>\n" }, { "answer_id": 259500, "author": "Seiti", "author_id": 27959, "author_profile": "https://Stackoverflow.com/users/27959", "pm_score": 4, "selected": false, "text": "<p>I would use this:</p>\n\n<pre><code>long? i = 1;\n...some code...\nlong j = i ?? 0;\n</code></pre>\n\n<p>That means, if <em>i</em> is <strong>null</strong>, than 0 will be assigned.</p>\n" }, { "answer_id": 259509, "author": "Marc Bollinger", "author_id": 12866, "author_profile": "https://Stackoverflow.com/users/12866", "pm_score": 2, "selected": false, "text": "<p>I haven't used Nullable Types in practice, but for the second, I'd actually suggest using j.GetValueOrDefault(). The documentation suggests that the latter would actually throw an InvalidOperationException in the event of a null value. Depending on the internal implementation of the explict cast operator for long?, the former might, too. I'd stick with GetValueOrDefault and treat the null/default case appropriately.</p>\n" }, { "answer_id": 259604, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 5, "selected": true, "text": "<p>Use the forms that were specially implemented for you by the C# team. If anyone objects, tell them Anders said it was okay.</p>\n\n<p>What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience.</p>\n\n<p>Note that in terms of performance, both forms compile down to the same IL, ie:</p>\n\n<pre><code>int? i = 1;\nbool isINull = i == null;\nint j = (int)i;\n</code></pre>\n\n<p>Ends up like this after the C# compiler has got to it:</p>\n\n<pre><code>int? i = 1;\nbool isINull = !i.HasValue;\nint j = i.Value;\n</code></pre>\n" }, { "answer_id": 259707, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 1, "selected": false, "text": "<p>I tend to use the first on both, because as it needs to be supported later in its life-cycle, these seem easier to understand what the intent of the original writer.</p>\n" }, { "answer_id": 259756, "author": "AdamSane", "author_id": 805, "author_profile": "https://Stackoverflow.com/users/805", "pm_score": 1, "selected": false, "text": "<p>Opened up Reflector. HasValue is a lookup on a boolean flag which is set when the value is changed. So in terms of cycles a lookup is going to be faster then compare.</p>\n\n<pre><code>public Nullable(T value)\n{\n this.value = value;\n this.hasValue = true;\n}\n\nprivate bool hasValue;\n\ninternal T value;\n\npublic bool HasValue\n{\n get\n {\n return this.hasValue;\n }\n}\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20553/" ]
I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null: ``` bool isNull = (i == null); ``` or ``` bool isNull = !i.HasValue; ``` Also when assigning to a non-null type is this: ``` long? i = 1; long j = (long)i; ``` better than: ``` long? i = 1; long j = i.Value; ```
Use the forms that were specially implemented for you by the C# team. If anyone objects, tell them Anders said it was okay. What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience. Note that in terms of performance, both forms compile down to the same IL, ie: ``` int? i = 1; bool isINull = i == null; int j = (int)i; ``` Ends up like this after the C# compiler has got to it: ``` int? i = 1; bool isINull = !i.HasValue; int j = i.Value; ```
259,486
<p>SQL Server 2005.</p> <p>I'm adding Foreign Key constraints to the database of an application that allegedly didn't need them. Naturally, the data has become unreliable and there are orphaned entries in the foreign key field.</p> <p>Setup:<br/> Two tables, TableUser and TableOrder. TableUser has Primary Key 'UserID', and TableOrder has Foreign Key 'UserID'.</p> <p>How do I find the rows where TableOrder.UserID has no matching entry in TableUser.UserID?</p> <p>For example, TableOrder.UserID has a value of 250, but there is no matching TableUser.UserID key for 250.</p>
[ { "answer_id": 259498, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>Here's one way:</p>\n\n<pre><code>select * from TableOrder where UserID not in (select UserID from TableUser);\n</code></pre>\n\n<p>There are many different ways to write this sort of query.</p>\n" }, { "answer_id": 259586, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 3, "selected": false, "text": "<p>The other common approach is a left-outer join:</p>\n\n<pre><code>SELECT * FROM TableOrder o\nLEFT OUTER JOIN TableUser u ON o.UserID = u.UserID\nWHERE u.UserID is NULL\n</code></pre>\n\n<p>This query can also be useful without the where clause, to browse through and see the corresponding values (if they exist), and see which ones have no match.</p>\n" }, { "answer_id": 261992, "author": "Dave", "author_id": 26508, "author_profile": "https://Stackoverflow.com/users/26508", "pm_score": 0, "selected": false, "text": "<p>There were no FK Constraints in the tables to begin with. The were used like FK and PK but not coded -- the belief was that they were unnecessary overhead. So we have all the columns, but no coded constraints. When I went to put them in so that they would be enforced, I discovered that there were lots of violations.</p>\n\n<p>Your question highlights the problem. They are not unnecessary overhead, they prevent people from general database asshattery.</p>\n\n<p>Both Greg and Brad's answers helped me out.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26508/" ]
SQL Server 2005. I'm adding Foreign Key constraints to the database of an application that allegedly didn't need them. Naturally, the data has become unreliable and there are orphaned entries in the foreign key field. Setup: Two tables, TableUser and TableOrder. TableUser has Primary Key 'UserID', and TableOrder has Foreign Key 'UserID'. How do I find the rows where TableOrder.UserID has no matching entry in TableUser.UserID? For example, TableOrder.UserID has a value of 250, but there is no matching TableUser.UserID key for 250.
Here's one way: ``` select * from TableOrder where UserID not in (select UserID from TableUser); ``` There are many different ways to write this sort of query.
259,524
<p>I have started using Linq to SQL in a (bit DDD like) system which looks (overly simplified) like this:</p> <pre><code>public class SomeEntity // Imagine this is a fully mapped linq2sql class. { public Guid SomeEntityId { get; set; } public AnotherEntity Relation { get; set; } } public class AnotherEntity // Imagine this is a fully mapped linq2sql class. { public Guid AnotherEntityId { get; set; } } public interface IRepository&lt;TId, TEntity&gt; { Entity Get(TId id); } public class SomeEntityRepository : IRepository&lt;Guid, SomeEntity&gt; { public SomeEntity Get(Guid id) { SomeEntity someEntity = null; using (DataContext context = new DataContext()) { someEntity = ( from e in context.SomeEntity where e.SomeEntityId == id select e).SingleOrDefault&lt;SomeEntity&gt;(); } return someEntity; } } </code></pre> <p>Now, I got a problem. When I try to use SomeEntityRepository like this</p> <pre><code>public static class Program { public static void Main(string[] args) { IRepository&lt;Guid, SomeEntity&gt; someEntityRepository = new SomeEntityRepository(); SomeEntity someEntity = someEntityRepository.Get(new Guid("98011F24-6A3D-4f42-8567-4BEF07117F59")); Console.WriteLine(someEntity.SomeEntityId); Console.WriteLine(someEntity.Relation.AnotherEntityId); } } </code></pre> <p>everything works nicely until the program gets to the last WriteLine, because it throws an <code>ObjectDisposedException</code>, because the DataContext does not exist any more.</p> <p>I do see the actual problem, but how do I solve this? I guess there are several solutions, but none of those I have thought of to date would be good in my situation.</p> <ul> <li>Get away from the repository pattern and using a new DataContext for each atomic part of work. <ul> <li>I really would not want to do this. A reason is that I do not want to be the applications to be aware of the repository. Another one is that I do not think making linq2sql stuff COM visible would be good.</li> <li>Also, I think that doing <code>context.SubmitChanges()</code> would probably commit much more than I intended to.</li> </ul></li> <li>Specifying DataLoadOptions to fetch related elements. <ul> <li>As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use.</li> </ul></li> <li>Disabling lazy loading/delayed loading for all properties. <ul> <li>Not an option, because there are quite a few tables and they are heavily linked. This could cause a lot of unnecessary traffic and database load.</li> </ul></li> <li>Some post on the internet said that using .Single() should help. <ul> <li>Apparently it does not ...</li> </ul></li> </ul> <p>Is there any way to solve this misery?</p> <p>BTW: We decided to use Linq t0 SQL because it is a relatively lightweight ORM solution and included with the .NET framework and Visual Studio. If the .NET Entity Framework would fit better in this pattern, it may be an option to switch to it. (We are not that far in the implementation, yet.)</p>
[ { "answer_id": 259570, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Specifying DataLoadOptions to fetch related elements. As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use. </p>\n</blockquote>\n\n<p>If the caller is granted the coupling necessary to use the .Relation property, then the caller might as well specify the DataLoadOptions.</p>\n\n<pre><code>DataLoadOptions loadOptions = new DataLoadOptions();\nloadOptions.LoadWith&lt;Entity&gt;(e =&gt; e.Relation);\nSomeEntity someEntity = someEntityRepository\n .Get(new Guid(\"98011F24-6A3D-4f42-8567-4BEF07117F59\"),\n loadOptions);\n</code></pre>\n\n<p>//</p>\n\n<pre><code>using (DataContext context = new DataContext())\n{\n context.LoadOptions = loadOptions;\n</code></pre>\n" }, { "answer_id": 259606, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 3, "selected": true, "text": "<p>Rick Strahl has a nice article about DataContext lifecycle management here: <a href=\"http://www.west-wind.com/weblog/posts/246222.aspx\" rel=\"nofollow noreferrer\">http://www.west-wind.com/weblog/posts/246222.aspx</a>.</p>\n\n<p>Basically, the atomic action approach is nice in theory but you're going to need to keep your DataContext around to be able to track changes (and fetch children) in your data objects.</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/226127/multiplesingle-instance-of-linq-to-sql-datacontext\">Multiple/single instance of Linq to SQL DataContext</a> and <a href=\"https://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live\">LINQ to SQL - where does your DataContext live?</a>.</p>\n" }, { "answer_id": 259718, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "<p>You have to either:</p>\n\n<p>1) Leave the context open because you haven't fully decided what data will be used yet (aka, Lazy Loading).</p>\n\n<p>or 2) Pull more data on the initial load if you know you will need that other property.</p>\n\n<p>Explaination of the latter: <a href=\"http://www.singingeels.com/Blogs/Nullable/2008/10/27/EntityFramework_Include_Equivalent_in_LINQ_to_SQL.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 259760, "author": "Daniel Crenna", "author_id": 18440, "author_profile": "https://Stackoverflow.com/users/18440", "pm_score": 1, "selected": false, "text": "<p>I'm not sure you have to abandon Repository if you go with atomic units of work. I use both, though I admit to throwing out the optimistic concurrency checks since they don't work out in layers anyway (without using a timestamp or some other required convention). What I end up with is a repository that uses a DataContext and throws it away when it's done. </p>\n\n<p>This is part of an unrelated Silverlight example, but the first three parts show how I'm using a Repository pattern with a throwaway LINQ to SQL context, FWIW: <a href=\"http://www.dimebrain.com/2008/09/linq-wcf-silver.html\" rel=\"nofollow noreferrer\">http://www.dimebrain.com/2008/09/linq-wcf-silver.html</a></p>\n" }, { "answer_id": 1376494, "author": "Tom Lianza", "author_id": 26624, "author_profile": "https://Stackoverflow.com/users/26624", "pm_score": 0, "selected": false, "text": "<p>This is what I do, and so far it's worked really well. </p>\n\n<p>1) Make the DataContext a member variable in your repository. Yes, this means you're repository should now implement IDisposable and not be left open... maybe something you want to avoid having to do, but I haven't found it to be inconvenient.</p>\n\n<p>2) Add some methods to your repository like this:</p>\n\n<pre><code>public SomeEntityRepository WithSomethingElseTheCallerMightNeed()\n{\n dlo.LoadWith&lt;SomeEntity&gt;(se =&gt; se.RelatedEntities);\n return this; //so you can do method chaining\n}\n</code></pre>\n\n<p>Then, your caller looks like this:</p>\n\n<pre><code>SomeEntity someEntity = someEntityRepository.WithSomethingElseTheCallerMightNeed().Get(new Guid(\"98011F24-6A3D-4f42-8567-4BEF07117F59\"));\n</code></pre>\n\n<p>You just need to make sure that when your repository hits the db, it uses the data load options specified in those helper methods... in my case \"dlo\" is kept as a member variable, and then set right before hitting the db.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11963/" ]
I have started using Linq to SQL in a (bit DDD like) system which looks (overly simplified) like this: ``` public class SomeEntity // Imagine this is a fully mapped linq2sql class. { public Guid SomeEntityId { get; set; } public AnotherEntity Relation { get; set; } } public class AnotherEntity // Imagine this is a fully mapped linq2sql class. { public Guid AnotherEntityId { get; set; } } public interface IRepository<TId, TEntity> { Entity Get(TId id); } public class SomeEntityRepository : IRepository<Guid, SomeEntity> { public SomeEntity Get(Guid id) { SomeEntity someEntity = null; using (DataContext context = new DataContext()) { someEntity = ( from e in context.SomeEntity where e.SomeEntityId == id select e).SingleOrDefault<SomeEntity>(); } return someEntity; } } ``` Now, I got a problem. When I try to use SomeEntityRepository like this ``` public static class Program { public static void Main(string[] args) { IRepository<Guid, SomeEntity> someEntityRepository = new SomeEntityRepository(); SomeEntity someEntity = someEntityRepository.Get(new Guid("98011F24-6A3D-4f42-8567-4BEF07117F59")); Console.WriteLine(someEntity.SomeEntityId); Console.WriteLine(someEntity.Relation.AnotherEntityId); } } ``` everything works nicely until the program gets to the last WriteLine, because it throws an `ObjectDisposedException`, because the DataContext does not exist any more. I do see the actual problem, but how do I solve this? I guess there are several solutions, but none of those I have thought of to date would be good in my situation. * Get away from the repository pattern and using a new DataContext for each atomic part of work. + I really would not want to do this. A reason is that I do not want to be the applications to be aware of the repository. Another one is that I do not think making linq2sql stuff COM visible would be good. + Also, I think that doing `context.SubmitChanges()` would probably commit much more than I intended to. * Specifying DataLoadOptions to fetch related elements. + As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use. * Disabling lazy loading/delayed loading for all properties. + Not an option, because there are quite a few tables and they are heavily linked. This could cause a lot of unnecessary traffic and database load. * Some post on the internet said that using .Single() should help. + Apparently it does not ... Is there any way to solve this misery? BTW: We decided to use Linq t0 SQL because it is a relatively lightweight ORM solution and included with the .NET framework and Visual Studio. If the .NET Entity Framework would fit better in this pattern, it may be an option to switch to it. (We are not that far in the implementation, yet.)
Rick Strahl has a nice article about DataContext lifecycle management here: <http://www.west-wind.com/weblog/posts/246222.aspx>. Basically, the atomic action approach is nice in theory but you're going to need to keep your DataContext around to be able to track changes (and fetch children) in your data objects. See also: [Multiple/single instance of Linq to SQL DataContext](https://stackoverflow.com/questions/226127/multiplesingle-instance-of-linq-to-sql-datacontext) and [LINQ to SQL - where does your DataContext live?](https://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live).
259,532
<p>I'm getting something pretty strange going on when trying to read some data using the MySql .net connector. Here's the code:</p> <pre><code>IDataReader reader = null; using (MySqlConnection connection = new MySqlConnection(this.ConnectionString)) { String getSearch = "select * from organization"; MySqlCommand cmd = new MySqlCommand(getSearch, connection); cmd.CommandType = CommandType.Text; connection.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { // response write some stuff to the screen (snipped for brevity) } } </code></pre> <p>If I put a breakpoint after the ExecuteReader and expand the results view in Visual Studio (hovering over reader and expanding), I can see the rows returned by the query. If I then let that close and expand the results view again, I get the message 'Enumeration yielded no results'.</p> <p>It seems as if the contents of the reader are getting reset as soon as they're viewed.</p> <p>As for what we've tried:<br> - the SQL runs fine directly on to DB<br> - Binding the results of the query directly to a datagrid just returns an empty datagrid<br> - got the latest version of the .net connector<br> - tried on two different machines to rule out any local errors</p> <p>So far nothing's worked.</p> <p>If anyone could offer any ideas or suggestions they would be very much appreciated.</p>
[ { "answer_id": 259548, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Since a datareader reads in information, your using block closes the connection to the reader just after assigning its value to the variable. <a href=\"http://www.simple-talk.com/dotnet/.net-framework/should-you-use-ado.net-datareader-or-dataset/\" rel=\"nofollow noreferrer\">Here is an article</a> that shows you some examples of code that might get you to where you need to be.</p>\n\n<p>The key is that the connection MUST be open, when trying to read from the reader.</p>\n" }, { "answer_id": 259556, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 3, "selected": true, "text": "<p>from what I understand the SqlDataReader is intended to be used for a one-time enumeration of the data you've returned. Once you've cycled through the results once, the object has done its duty. Here are a couple ideas for working around this, one or the other of which may solve this for you depending on your needs:</p>\n\n<ol>\n<li><p>Re-execute the query to generate another SqlDataReader when needed</p></li>\n<li><p>Instead of using the SqlDataReader, store the results of your original query into a System.Data.DataTable, where you can then re-read and manipulate the data however you like.</p></li>\n</ol>\n\n<p>Hope this helps!</p>\n\n<p>Adam</p>\n" }, { "answer_id": 259595, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "<p>Here is the explanation:</p>\n\n<p>This is because, you have already looped through the reader once in the debugger (the first time you expanded the view). This is the way the readers work, and from what I know, there is no way to reset a reader to go and read again from the beginning, excepting the re-execution option:</p>\n\n<blockquote>\n <p>You just have to run again the\n <code>cmd.ExecuteReader();</code> line (by right\n click in the source and using \"set\n next statement\" menu option).</p>\n</blockquote>\n\n<p>This is the behaviour of data readers. If you have already looped through it, you cannot go back. You have to execute the command again and retrieve a new one.</p>\n\n<p>If you need to use your data after closing the reader, you might choose to use a <code>Typed DataSet</code>, or the untyped <code>DataSet</code> as specified in Adam's <a href=\"https://stackoverflow.com/questions/259532/idatareader-empties-when-viewing-for-a-second-time#259556\">answer</a>.</p>\n\n<p>By the way, here are some <code>optimizations</code> you could make:</p>\n\n<ul>\n<li>Move the reader inside the\n<code>Connection</code> using block to make it\ngo out of scope after finishing\nusing it (once you are out the using\nblock, the connection will be closed\nand you won't be able to use it anyway, so it doesn't make sense leaving it outside)</li>\n<li>Run <code>ExecuteReader</code> in\nanother <code>using</code> block (as it implements <code>IDisposable</code>) and do the same thing with the Sql <code>Command</code> (the same <code>IDisposable</code> interface)</li>\n<li>Don't retrieve\nall the fields from the database</li>\n</ul>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33721/" ]
I'm getting something pretty strange going on when trying to read some data using the MySql .net connector. Here's the code: ``` IDataReader reader = null; using (MySqlConnection connection = new MySqlConnection(this.ConnectionString)) { String getSearch = "select * from organization"; MySqlCommand cmd = new MySqlCommand(getSearch, connection); cmd.CommandType = CommandType.Text; connection.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { // response write some stuff to the screen (snipped for brevity) } } ``` If I put a breakpoint after the ExecuteReader and expand the results view in Visual Studio (hovering over reader and expanding), I can see the rows returned by the query. If I then let that close and expand the results view again, I get the message 'Enumeration yielded no results'. It seems as if the contents of the reader are getting reset as soon as they're viewed. As for what we've tried: - the SQL runs fine directly on to DB - Binding the results of the query directly to a datagrid just returns an empty datagrid - got the latest version of the .net connector - tried on two different machines to rule out any local errors So far nothing's worked. If anyone could offer any ideas or suggestions they would be very much appreciated.
from what I understand the SqlDataReader is intended to be used for a one-time enumeration of the data you've returned. Once you've cycled through the results once, the object has done its duty. Here are a couple ideas for working around this, one or the other of which may solve this for you depending on your needs: 1. Re-execute the query to generate another SqlDataReader when needed 2. Instead of using the SqlDataReader, store the results of your original query into a System.Data.DataTable, where you can then re-read and manipulate the data however you like. Hope this helps! Adam
259,534
<p>Thanks for going to answer my question. I have the folowing pages.</p> <ul> <li>login.aspx</li> <li>default.aspx</li> <li>xxx.aspx</li> </ul> <p>After logging into application default.aspx will be displayed. Now if the user is trying to open <a href="http://server/" rel="nofollow noreferrer">http://server/</a><strong>xxx.aspx</strong>?Id=1234 by specifying its URL directly in a browser, the login screen is displayed and after successfull login, system redirects to "default.aspx" and not to "<a href="http://server/" rel="nofollow noreferrer">http://server/</a><strong>xxx.aspx</strong>?Id=1234". Actually there is an external application that would call my system like that. So Please let me know why is this happening. The .Net login control is used to login into the application. Kindly help me to solve this issue.</p> <p>Thanks,<br> Ang Vin</p>
[ { "answer_id": 259541, "author": "Markus Nigbur", "author_id": 33231, "author_profile": "https://Stackoverflow.com/users/33231", "pm_score": 0, "selected": false, "text": "<pre><code>Response.Redirect(Request.UrlReferrer.ToString());\n</code></pre>\n" }, { "answer_id": 259579, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 2, "selected": false, "text": "<p>Are you using Forms Authentication or doing this directly in the application? If you do something like this in your web.config it will handle all the redirecting for you.</p>\n\n<pre><code>&lt;authentication mode=\"Forms\"&gt;\n &lt;forms name=\"FwLoginCookie\" loginUrl=\"Login.aspx\"\n protection=\"All\" \n path=\"/\" &gt;\n &lt;/forms&gt;\n &lt;/authentication&gt;\n &lt;authorization&gt;\n &lt;deny users=\"?\"/&gt;\n &lt;/authorization&gt;\n</code></pre>\n\n<p>Is there anything in the URL stating the ReturnURL? With the above setting if the user tries to go to xxx.aspx I would expect the URL of the login dialog to look like \"Login.aspx?ReturnUrl=xxx.aspx\"</p>\n" }, { "answer_id": 259608, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 1, "selected": false, "text": "<p>Check that you are NOT setting the DestinationPageUrl property in the login control:</p>\n\n<pre><code>&lt;asp:Login \n ID=\"Login1\" \n runat=\"server\" \n DestinationPageUrl=\"~/Default.aspx\"&gt;\n&lt;/asp:Login&gt;\n</code></pre>\n\n<p>I assume you have as this property overrides the default behaviour you are actually looking for.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33722/" ]
Thanks for going to answer my question. I have the folowing pages. * login.aspx * default.aspx * xxx.aspx After logging into application default.aspx will be displayed. Now if the user is trying to open <http://server/>**xxx.aspx**?Id=1234 by specifying its URL directly in a browser, the login screen is displayed and after successfull login, system redirects to "default.aspx" and not to "<http://server/>**xxx.aspx**?Id=1234". Actually there is an external application that would call my system like that. So Please let me know why is this happening. The .Net login control is used to login into the application. Kindly help me to solve this issue. Thanks, Ang Vin
Are you using Forms Authentication or doing this directly in the application? If you do something like this in your web.config it will handle all the redirecting for you. ``` <authentication mode="Forms"> <forms name="FwLoginCookie" loginUrl="Login.aspx" protection="All" path="/" > </forms> </authentication> <authorization> <deny users="?"/> </authorization> ``` Is there anything in the URL stating the ReturnURL? With the above setting if the user tries to go to xxx.aspx I would expect the URL of the login dialog to look like "Login.aspx?ReturnUrl=xxx.aspx"
259,536
<p>Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.</p>
[ { "answer_id": 259544, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 6, "selected": true, "text": "<p>Try using this instead. </p>\n\n<pre><code>System.Reflection.MethodBase.GetCurrentMethod().Name\n</code></pre>\n\n<p>C# doesn't have <code>__LINE__</code> or <code>__FUNCTION__</code> macros like C++ but there are equivalents</p>\n" }, { "answer_id": 259545, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 3, "selected": false, "text": "<p>The following should work, although it will be evaluated at runtime instead of during compilation.</p>\n\n<pre><code>System.Reflection.MethodBase.GetCurrentMethod().Name\n</code></pre>\n" }, { "answer_id": 259546, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "<p>Unfortunately there is no equivalent version of that macro in C#. I don't consider the GetCurrentMethodName() solution equivalent to the C++ __FUNCTION__ macro. Namely becase the C++ version is a compile time computation of the name. For C# this is a runtime calculation and incurs a performance hit.</p>\n\n<p>I'm not making any assumtions about the severity of the cost but there is one</p>\n" }, { "answer_id": 334255, "author": "Mark Booth", "author_id": 42473, "author_profile": "https://Stackoverflow.com/users/42473", "pm_score": 3, "selected": false, "text": "<p>What I currently use is a function like this:</p>\n<pre><code>using System.Diagnostics;\n\npublic string __Function() {\n StackTrace stackTrace = new StackTrace();\n return stackTrace.GetFrame(1).GetMethod().Name;\n}\n</code></pre>\n<p>When I need __FUNCTION__, I just call the __Function() instead. For example:</p>\n<pre><code>Debug.Assert(false, __Function() + &quot;: Unhandled option&quot;);\n</code></pre>\n<p>Of course this solution uses reflection too, but it is the best option I can find. Since I only use it for Debugging (not Tracing in release builds) the performance hit is not important.</p>\n<p>I guess what I should do is create debug functions and tag them with</p>\n<pre><code>[ Conditional(&quot;Debug&quot;) ]\n</code></pre>\n<p>instead, but I haven't got around to that.</p>\n<p>Thanks to Jeff Mastry for his <a href=\"http://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&amp;ixPost=6163\" rel=\"noreferrer\">solution</a> to this.</p>\n" }, { "answer_id": 31132484, "author": "ShloEmi", "author_id": 2759057, "author_profile": "https://Stackoverflow.com/users/2759057", "pm_score": 2, "selected": false, "text": "<p>I use this:</p>\n\n<pre><code>public static string CallerName([CallerMemberName] string callerName = \"\")\n{\n return callerName;\n}\n</code></pre>\n\n<p>Usage example: </p>\n\n<pre><code>s_log.DebugFormat(\"{0}\", CallerName());\n</code></pre>\n\n<p>The down side of using it is that every time you want to print the caller name, you need to jump to the function ==> time consuming &amp; performance hit!\nSo, I use it for debugging perpose and if I need to print also in production code, I usually inline the function name into the log.Debug, e.g. :</p>\n\n<pre><code>s_log.Debug(\"CallerName\");\n</code></pre>\n\n<p>HTH..</p>\n" }, { "answer_id": 32342830, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 2, "selected": false, "text": "<p>This is added in .NET 4.5.</p>\n\n<p>See @roken's answer here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/696218/do-line-file-equivalents-exist-in-c\">Do __LINE__ __FILE__ equivalents exist in C#?</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21704/" ]
Does anyone has a good solution for a C# version of the C++ \_\_FUNCTION\_\_ macro? The compiler does not seem to like it.
Try using this instead. ``` System.Reflection.MethodBase.GetCurrentMethod().Name ``` C# doesn't have `__LINE__` or `__FUNCTION__` macros like C++ but there are equivalents
259,540
<p>It seems that the following piece of HTML is ignored in IE7 but works ok in IE6/FF. It supposes to override all the html links to be opened in the desired frame</p> <pre><code>&lt;HEAD&gt; &lt;title&gt;LeftPane&lt;/title&gt; &lt;base target="rightFrame"&gt; &lt;/HEAD&gt; </code></pre> <p>The above code is the header of a left frame that holds an Infragistics UltraWebTree (tree menu) which doesn't support the TargetFrame property.</p> <p>Is there another way to add the target attribute to all the links elements on the desired page. </p> <p>Any server or client-side code workarounds?</p> <p>The site is built on ASP.Net 1.1 and Infragistics V 2.0</p> <p><strong>Update</strong> the web page is aspx an the doctype is </p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" &gt; </code></pre>
[ { "answer_id": 259549, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<p>The <code>href=\"\"</code> attibute is <a href=\"http://www.w3schools.com/TAGS/tag_base.asp\" rel=\"nofollow noreferrer\">mandatory on the base tag</a> - that's one possible explanation. You don't say what doctype you're using, but <a href=\"http://www.devguru.com/Technologies/xhtml/quickref/xhtml_base.html\" rel=\"nofollow noreferrer\">target is not allowed in strict XHTML</a>.</p>\n\n<p>Edit: tested it without href and it worked ok... that leaves the doctype, or something else.</p>\n" }, { "answer_id": 259592, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 0, "selected": false, "text": "<p>Honestly, I know this isn't what you're asking but <strong>PLEASE</strong> don't use frames. They're already on their way out of the HTML/XHTML DTD's, are butt ugly and cause all kinds of issues browser-to-browser.</p>\n\n<p>If you're looking for an easy to manage template system then I'd suggest just use simple <a href=\"http://ca.php.net/include/\" rel=\"nofollow noreferrer\">PHP includes</a> which may sound intimidating, but is actually extremely simple. Chances are if you have a cheap webserver PHP is already installed.</p>\n" }, { "answer_id": 260172, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": 1, "selected": true, "text": "<p>i dont know what was the issue because i test the base target in pure HTML and it works, wondering if ASP.net has to do something with it. but here is a piece of javascript code that add the target attribute to all link elements that doesnt have one</p>\n\n<pre><code>&lt;script language=\"javascript\"&gt;\n\n var tags=document.getElementsByTagName(\"a\");\n for (i=0;i&lt;tags.length;i++)\n { \n if(!tags[i].getAttribute('target'))\n {\n tags[i].setAttribute('target',\"right\")\n }\n }\n\n\n &lt;/script&gt; \n</code></pre>\n" }, { "answer_id": 13844085, "author": "Peter", "author_id": 1898468, "author_profile": "https://Stackoverflow.com/users/1898468", "pm_score": 1, "selected": false, "text": "<p>IE does no longer allow <code>BASE</code> tags outside of the <code>HEAD</code> of the document.</p>\n\n<p>The standard specifies that the base element must appear within the <code>head</code> of the document, <em>before any elements</em> that refer to an external source.</p>\n\n<p>So if you place the code right after <code>&lt;/head&gt;</code> it works!</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14440/" ]
It seems that the following piece of HTML is ignored in IE7 but works ok in IE6/FF. It supposes to override all the html links to be opened in the desired frame ``` <HEAD> <title>LeftPane</title> <base target="rightFrame"> </HEAD> ``` The above code is the header of a left frame that holds an Infragistics UltraWebTree (tree menu) which doesn't support the TargetFrame property. Is there another way to add the target attribute to all the links elements on the desired page. Any server or client-side code workarounds? The site is built on ASP.Net 1.1 and Infragistics V 2.0 **Update** the web page is aspx an the doctype is ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > ```
i dont know what was the issue because i test the base target in pure HTML and it works, wondering if ASP.net has to do something with it. but here is a piece of javascript code that add the target attribute to all link elements that doesnt have one ``` <script language="javascript"> var tags=document.getElementsByTagName("a"); for (i=0;i<tags.length;i++) { if(!tags[i].getAttribute('target')) { tags[i].setAttribute('target',"right") } } </script> ```
259,542
<p>I have installed Phusion Passenger 2.0.3 on Apache 2.2.3 on Centos 2.6.18-92.el5 #1 SMP and I am getting the following on the httpd error log</p> <pre><code>Cannot initialize Passenger in an Apache child process: Could not connect to the ApplicationPool server: Broken pipe (32) </code></pre> <p>I have removed the modules that Passenger conflicts with as per the <a href="http://www.modrails.com/documentation/Users%20guide.html#conflicting_apache_modules" rel="nofollow noreferrer">documentation</a>.</p> <p>Thoughts?</p> <p>Best,</p>
[ { "answer_id": 2942793, "author": "Spasm", "author_id": 180935, "author_profile": "https://Stackoverflow.com/users/180935", "pm_score": 1, "selected": false, "text": "<p>Please take a look at the following tutorial for setting up Passenger correctly:\n<a href=\"http://www.modrails.com/documentation/Users%20guide%20Apache.html#_deploying_to_a_virtual_host_8217_s_root\" rel=\"nofollow noreferrer\">Deploying to a virtual host</a></p>\n\n<p>I had the same issue with Enterprise Ruby and Passenger</p>\n" }, { "answer_id": 3081587, "author": "mfcabrera", "author_id": 77035, "author_profile": "https://Stackoverflow.com/users/77035", "pm_score": 0, "selected": false, "text": "<p>I had the same problem. The problem was because accidentally installed the native package (debian in my case) and also the gem. So for some reason it was causing the conflict. I removed the package and restarted Apache and it worked. Hope that helps.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have installed Phusion Passenger 2.0.3 on Apache 2.2.3 on Centos 2.6.18-92.el5 #1 SMP and I am getting the following on the httpd error log ``` Cannot initialize Passenger in an Apache child process: Could not connect to the ApplicationPool server: Broken pipe (32) ``` I have removed the modules that Passenger conflicts with as per the [documentation](http://www.modrails.com/documentation/Users%20guide.html#conflicting_apache_modules). Thoughts? Best,
Please take a look at the following tutorial for setting up Passenger correctly: [Deploying to a virtual host](http://www.modrails.com/documentation/Users%20guide%20Apache.html#_deploying_to_a_virtual_host_8217_s_root) I had the same issue with Enterprise Ruby and Passenger
259,547
<p>If I have a table like this:</p> <pre><code>CREATE TABLE sizes ( name ENUM('small', 'medium', 'large') ); </code></pre> <p>Is MySQL going to store those strings in every row, or internally will it use something smaller like integers to know which enum value to refer to?</p> <p>I want to use an enum in a table but I'm worried if it's as wasteful as storing a string in every row.</p>
[ { "answer_id": 259561, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 6, "selected": true, "text": "<p>It converts them to integers on INSERT / UPDATE and back to strings on SELECT so the internal storage is as integers but you don't get exposed to that.</p>\n\n<p>You can retrieve the integer like <code>SELECT mycolumn + 0</code>.</p>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/enum.html\" rel=\"noreferrer\">ENUMs in MySQL 5</a></p>\n" }, { "answer_id": 259564, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 1, "selected": false, "text": "<p>First, I wouldn't worry about space consumption when deciding whether or not to use an enum. Disk space is both plentiful and cheap. </p>\n\n<p>Second, it stores the strings in the column definition and then stores the appropriate enum within each record. According to <a href=\"http://www.making-the-web.com/2008/03/24/saving-bytes-efficient-data-storage-mysql-part-1/\" rel=\"nofollow noreferrer\">this</a> the value stored with each record is a numeric representation of the values position within the enum.</p>\n" }, { "answer_id": 259567, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "<p>As explained <a href=\"http://dev.mysql.com/doc/refman/5.0/en/enum.html\" rel=\"nofollow noreferrer\">here</a>, enums are stored as values between 0 (no valid value set) and 65,535 that are associated with an enumeration index. The value that is stored in the table is a 2 byte value, not a string.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
If I have a table like this: ``` CREATE TABLE sizes ( name ENUM('small', 'medium', 'large') ); ``` Is MySQL going to store those strings in every row, or internally will it use something smaller like integers to know which enum value to refer to? I want to use an enum in a table but I'm worried if it's as wasteful as storing a string in every row.
It converts them to integers on INSERT / UPDATE and back to strings on SELECT so the internal storage is as integers but you don't get exposed to that. You can retrieve the integer like `SELECT mycolumn + 0`. See [ENUMs in MySQL 5](http://dev.mysql.com/doc/refman/5.0/en/enum.html)
259,562
<p>I'm an old hand at embedded programming but new to CE and having a lot of trouble doing reasonably simple things, because I am not familiar with the API and struggling to understand the obscure MSDN docs.</p> <p>All I want to do is minimize and maximise two separate applications that are running from one of the applications.</p> <p>E.g. Application A decides that now it is time for it to appear and then minimises application B (App B being a third party application e.g. Notepad, no access to source code etc) and then at a later stage maximising B and minimising itself.</p> <p>Application A would be written by myself.</p> <p>I'm sure this must be very simple, but where to find answers.. :)</p> <p>Thanks in advance. EOI</p>
[ { "answer_id": 259582, "author": "Craig Nicholson", "author_id": 28305, "author_profile": "https://Stackoverflow.com/users/28305", "pm_score": 1, "selected": false, "text": "<p>Firstly you will need to locate the window handle (hwnd) using the <a href=\"http://msdn.microsoft.com/en-us/library/aa453070.aspx\" rel=\"nofollow noreferrer\">FindWindow</a> API function or some alternate means. Next use the <a href=\"http://msdn.microsoft.com/en-us/library/aa453731.aspx\" rel=\"nofollow noreferrer\">ShowWindow</a> API function specifying either <strong>SW_HIDE</strong> or <strong>SW_SHOW</strong> to hide or show the window respectively. Note that Windows CE 5.0 does not technically support the Win32 window states like SW_MINIMIZE, SW_MAXIMIZE, etc.</p>\n\n<p>A simple example would be:</p>\n\n<pre><code>HWND hWnd = ::FindWindow( _T(\"Notepad\"), NULL); \n::ShowWindow(hWnd, SW_HIDE); \n</code></pre>\n" }, { "answer_id": 268279, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 0, "selected": false, "text": "<p>You may also find SetForegroundWindow and SetWindowPos useful.</p>\n\n<p>This is how I've used them to show and hide applications:</p>\n\n<pre><code>SetWindowPos(windowToHide, 0, 0, 0, 0, 0, SWP_HIDEWINDOW);\nSetWindowPos(windowToShowInFullScreen, HWND_TOP, 0, 0, 240, 320, SWP_SHOWWINDOW);\nSetForegroundWindow(windowToShow);\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33720/" ]
I'm an old hand at embedded programming but new to CE and having a lot of trouble doing reasonably simple things, because I am not familiar with the API and struggling to understand the obscure MSDN docs. All I want to do is minimize and maximise two separate applications that are running from one of the applications. E.g. Application A decides that now it is time for it to appear and then minimises application B (App B being a third party application e.g. Notepad, no access to source code etc) and then at a later stage maximising B and minimising itself. Application A would be written by myself. I'm sure this must be very simple, but where to find answers.. :) Thanks in advance. EOI
Firstly you will need to locate the window handle (hwnd) using the [FindWindow](http://msdn.microsoft.com/en-us/library/aa453070.aspx) API function or some alternate means. Next use the [ShowWindow](http://msdn.microsoft.com/en-us/library/aa453731.aspx) API function specifying either **SW\_HIDE** or **SW\_SHOW** to hide or show the window respectively. Note that Windows CE 5.0 does not technically support the Win32 window states like SW\_MINIMIZE, SW\_MAXIMIZE, etc. A simple example would be: ``` HWND hWnd = ::FindWindow( _T("Notepad"), NULL); ::ShowWindow(hWnd, SW_HIDE); ```
259,575
<p>I am writing a java program that needs a file open dialog. The file open dialog isn't difficult, I'm hoping to use a <code>JFileChooser</code>. My problem is that I would like to have a dual pane <code>JFrame</code> (consisting of 2 <code>JPanels</code>). The left panel would have a <code>JList</code>, and the right panel would have a file open dialog. </p> <p>When I use <code>JFileChooser.showOpenDialog()</code> this opens the dialog box above all other windows, which isn't what I want. Is there any way to have the <code>JFileChooser</code> (or maybe another file selection dialog) display inside a <code>JPanel</code> and not pop-up above it?</p> <p>Here is the code that I've tried, at this point it's very simplified. I'm only trying to get the <code>JFileChooser</code> to be embedded in the <code>JPanel</code> at this point.</p> <pre><code>public class JFC extends JFrame{ public JFC() { setSize(800,600); JPanel panel= new JPanel(); JFileChooser chooser = new JFileChooser(); panel.add(chooser); setVisible(true); chooser.showOpenDialog(null); } public static void main(String[] args) { JFC blah = new JFC(); } } </code></pre> <p>I have also tried calling <code>chooser.showOpenDialog</code> with <code>this</code> and <code>panel</code>, but to no avail. Also, I have tried adding the <code>JFileChooser</code> directly to the frame. Both of the attempts listed above still have the <code>JFileChooser</code> pop up in front of the frame or panel (depending on which I add the <code>JFileChooser</code> to).</p>
[ { "answer_id": 259583, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 5, "selected": true, "text": "<p>JFileChooser extends JComponent and Component so you should be able to add it directly to your frame.</p>\n\n<pre><code>JFileChooser fc = ...\nJPanel panel ...\npanel.add(fc);\n</code></pre>\n" }, { "answer_id": 259629, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 2, "selected": false, "text": "<p>If you are adding the JFileChooser on the fly, you will need to call revalidate().</p>\n\n<p>Steve's answer is correct. You can add a JFileChooser to other containers.</p>\n" }, { "answer_id": 264697, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>To access the \"buttons\" in the file chooser, you will have to add an ActionListener to it:</p>\n\n<pre><code>fileChooser.addActionListener(this);\n[...]\n\npublic void actionPerformed(ActionEvent action)\n{\n if (action.getActionCommand().equals(\"CancelSelection\"))\n {\n System.out.printf(\"CancelSelection\\n\");\n this.setVisible(false);\n this.dispose();\n }\n if (action.getActionCommand().equals(\"ApproveSelection\"))\n {\n System.out.printf(\"ApproveSelection\\n\");\n this.setVisible(false);\n this.dispose();\n }\n}\n</code></pre>\n" }, { "answer_id": 1406359, "author": "Carles Barrobés", "author_id": 166761, "author_profile": "https://Stackoverflow.com/users/166761", "pm_score": 2, "selected": false, "text": "<p>To Johannes: thanks for your useful snippet.</p>\n\n<p>Instead of \"ApproveSelection\" and \"CancelSelection\" I used the defined constants <code>JFileChooser.APPROVE_SELECTION</code> and <code>JFileChooser.CANCEL_SELECTION</code></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33725/" ]
I am writing a java program that needs a file open dialog. The file open dialog isn't difficult, I'm hoping to use a `JFileChooser`. My problem is that I would like to have a dual pane `JFrame` (consisting of 2 `JPanels`). The left panel would have a `JList`, and the right panel would have a file open dialog. When I use `JFileChooser.showOpenDialog()` this opens the dialog box above all other windows, which isn't what I want. Is there any way to have the `JFileChooser` (or maybe another file selection dialog) display inside a `JPanel` and not pop-up above it? Here is the code that I've tried, at this point it's very simplified. I'm only trying to get the `JFileChooser` to be embedded in the `JPanel` at this point. ``` public class JFC extends JFrame{ public JFC() { setSize(800,600); JPanel panel= new JPanel(); JFileChooser chooser = new JFileChooser(); panel.add(chooser); setVisible(true); chooser.showOpenDialog(null); } public static void main(String[] args) { JFC blah = new JFC(); } } ``` I have also tried calling `chooser.showOpenDialog` with `this` and `panel`, but to no avail. Also, I have tried adding the `JFileChooser` directly to the frame. Both of the attempts listed above still have the `JFileChooser` pop up in front of the frame or panel (depending on which I add the `JFileChooser` to).
JFileChooser extends JComponent and Component so you should be able to add it directly to your frame. ``` JFileChooser fc = ... JPanel panel ... panel.add(fc); ```
259,587
<p>We have 3 applications using 3 different spring configuration files. But we have one database and one datasource, so one session factory.Hhow can we import the session factory bean into the 3 different spring config files?</p>
[ { "answer_id": 259599, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 2, "selected": false, "text": "<p>If you are using XML configuration:</p>\n\n<p>Put your database settings in a Spring configuration called \"database-config.xml\" and import it in the other configuration files.</p>\n\n<pre><code>&lt;import resource=\"database-config.xml\"/&gt;\n</code></pre>\n\n<p>As to how you share it among three applications is more of a Configuration Management issue. You could use ant / maven to check it out of a repository and move it into the correct location.</p>\n" }, { "answer_id": 259779, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 2, "selected": false, "text": "<p>Configure your SessionFactory in a single XML file and import this configuration into whichever applications' Spring contexts need it.</p>\n\n<p>If you use classpath-based importing like this:</p>\n\n<pre><code>&lt;beans&gt;\n &lt;import resource=\"classpath:path/to/session-factory-beans.xml\"/&gt;\n &lt;... other bean definitions.../&gt;\n&lt;/beans&gt;\n</code></pre>\n\n<p>Then your distribution mechanism is pretty flexible, since the classloader will resolve the resource for you. You could </p>\n\n<ul>\n<li>copy session-factory-beans.xml into each project that requires it, or </li>\n<li>add it to a jarfile and share that amongst the applications, or </li>\n<li>add it to shared/classes if the applications are all running inside the same application server.</li>\n</ul>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We have 3 applications using 3 different spring configuration files. But we have one database and one datasource, so one session factory.Hhow can we import the session factory bean into the 3 different spring config files?
If you are using XML configuration: Put your database settings in a Spring configuration called "database-config.xml" and import it in the other configuration files. ``` <import resource="database-config.xml"/> ``` As to how you share it among three applications is more of a Configuration Management issue. You could use ant / maven to check it out of a repository and move it into the correct location.
259,589
<p>I am developing a page view counter to track the amount of views a page is having on our site and displaying it to the user. (I asked an intro question before: <a href="https://stackoverflow.com/questions/246919/page-view-counter-like-on-stackoverflow">Page View Counter like on StackOverFlow</a>).</p> <p>Using the recommendations, I developed a httpHandler which will handle the request whenever this gets fired off: </p> <pre><code>&lt;link rel="stylesheet" href="cn.axd?t=1&amp;id=232" type="text/css" /&gt; </code></pre> <ol> <li><p>Just wondering if the end-user would need to wait for the request to be finish processing before they can view/interact with the page.</p></li> <li><p>Would a better choice be implementing an asynchronous queue where information gets logged to an MS Queue and eventually logged in the database via (Exception Policy)</p></li> <li><p>Would it be slower to check if a certain record exist (PageID) and increment a counter or insert the record into the database and aggregate later when needed. We would just need to run an aggregation at the end of the week to see the total amount of pageviews a particular page got over the week.</p></li> </ol> <p>Thanks all.</p>
[ { "answer_id": 259619, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I would go with the logging method referenced in the other page, unless you need to track specific time/date of views. My reasoning is simply due to the sheer number of items that you might get as you application starts to scale up in size.</p>\n\n<p>Linking to the handler as a CSS style, should not really stop load time very much, but it could have some effect.</p>\n\n<p>With a simple insert/update script, I can't imagine that the performance overhead of doing the statement would be worth trying to do a queue style system...</p>\n" }, { "answer_id": 259624, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 2, "selected": true, "text": "<p>interesting questions! Like a lot of other performance-tuning questions, there are some tradeoffs.</p>\n\n<ol>\n<li><p>Possibly. It may be a better idea to load this handler inside an IMG href=\"\", setting the sizes to 0 so it is invisible to the user.</p></li>\n<li><p>With heavy load this would be preferable, that way your handler can return immediately after queuing the operation. For most loads, however, it is probably just as quick to run a simple T-SQL query to increment a counter.</p></li>\n<li><p>Adding +1 to the value directly within your T-SQL query would probably be the best, \"count = count + 1\" etc. That would be quick to run and would result in subsequent retrieval of your data without aggregation.</p></li>\n</ol>\n\n<p>Hope this helps!</p>\n\n<p>Adam</p>\n" }, { "answer_id": 259626, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "<p>Developing a MQ just for tracking pageviews/hits sounds a little over complicated.</p>\n\n<p>If you are concerned about any perceived latency by the user, why not just fire off a XmlHttpRequest in JavaScript to your URL? That will be processed asynchronously.</p>\n" }, { "answer_id": 262045, "author": "Jonas Stawski", "author_id": 34155, "author_profile": "https://Stackoverflow.com/users/34155", "pm_score": 2, "selected": false, "text": "<p>At my old company we also maintained a Page View counter and as the number of hits increased so did the database table which brought down the website to it's knees.</p>\n\n<p>Whatever method you implement I recommend the following:</p>\n\n<ol>\n<li>Do inserts all the time (they are faster than updates).</li>\n<li>Do them asynchronous so it doesn't block the main thread and won't block future requests.</li>\n<li>Have a nightly process that sumarizes the data and clears the table in point 1.</li>\n<li>Do your selects against the summed up data.</li>\n</ol>\n\n<p>We've found this was the most efficient and scalable solution, although you will not have real time data.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
I am developing a page view counter to track the amount of views a page is having on our site and displaying it to the user. (I asked an intro question before: [Page View Counter like on StackOverFlow](https://stackoverflow.com/questions/246919/page-view-counter-like-on-stackoverflow)). Using the recommendations, I developed a httpHandler which will handle the request whenever this gets fired off: ``` <link rel="stylesheet" href="cn.axd?t=1&id=232" type="text/css" /> ``` 1. Just wondering if the end-user would need to wait for the request to be finish processing before they can view/interact with the page. 2. Would a better choice be implementing an asynchronous queue where information gets logged to an MS Queue and eventually logged in the database via (Exception Policy) 3. Would it be slower to check if a certain record exist (PageID) and increment a counter or insert the record into the database and aggregate later when needed. We would just need to run an aggregation at the end of the week to see the total amount of pageviews a particular page got over the week. Thanks all.
interesting questions! Like a lot of other performance-tuning questions, there are some tradeoffs. 1. Possibly. It may be a better idea to load this handler inside an IMG href="", setting the sizes to 0 so it is invisible to the user. 2. With heavy load this would be preferable, that way your handler can return immediately after queuing the operation. For most loads, however, it is probably just as quick to run a simple T-SQL query to increment a counter. 3. Adding +1 to the value directly within your T-SQL query would probably be the best, "count = count + 1" etc. That would be quick to run and would result in subsequent retrieval of your data without aggregation. Hope this helps! Adam
259,600
<p>I've read quite a bit of the Red Bean Software SVN Book, and some of the questions here on SO, but I want to make sure I'm going about this in the right way the first time around step-by-step before I begin using it. Is this correct?</p> <ol> <li>Install SVN.</li> <li><p>Create SVN repository at /usr/local/svn. Directory structure looks like this:</p> <pre><code>-- conf -- db -- format -- hooks -- locks -- README.txt </code></pre></li> <li><p>Create folders through command line for repository organization (including projects and vendors).</p> <pre><code>-- conf -- db -- format -- hooks -- locks -- projects -- project_name -- vendor -- trunk -- branches -- tags -- project_name -- vendor -- trunk -- branches -- tags -- README.txt </code></pre></li> <li><p>Checkout vendor code into vendor folder under the correct project name.</p></li> <li>Export vendor code into trunk under the correct project name (no merge necessary, as I have no project trunk files yet).</li> <li>Create users/permissions in /svnroot/conf/passwd and /svnroot/conf/svnserve.conf.</li> <li>Make sure that svnserve is running, and on my local SVN client (TortoiseSVN), checkout the trunk for the project that I need.</li> </ol> <p>I don't need to serve this up by public URL, so I'm not configuring for Apache. The server is not in our network, but is a dedicated CentOS box we rent. Thanks for any thoughts and advice.</p> <p><strong>EDIT:</strong></p> <p>I guess I'm confused because I don't have code or a project to begin with, so I am starting fresh from the vendor's code. Do I need to create a directory structure somewhere on the server that includes my project_name w/ vendor, trunk, branches and tags subfolders, import that into my repo, and then import the code from the vendor into the vendor folder? The idea is that I can get updates from the vendor, and then merge those updates with any changes I made to my trunk.</p>
[ { "answer_id": 259628, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>Create folders through command line for repository organization (including projects and vendors).</p>\n</blockquote>\n\n<p>Do you mean creating the repository structure by making directories inside the subversion intallation directory? That's very wrong.</p>\n\n<p>You have to create the necessary folders via the <code>svn mkdir</code> command and not via filesystem.</p>\n\n<p>In <code>/usr/local/svn</code> you have the physical implementation of the Subversion repository, and you must access it only via a client, and never touch it \"by hand\".</p>\n\n<p>For example, using the file:// URL scheme</p>\n\n<pre><code>svn mkdir file:///usr/local/svn/projects -m \"Parent dir for projects created\"\n</code></pre>\n" }, { "answer_id": 259715, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": false, "text": "<p>You seem to have mostly the right idea, but your terminology is a bit wrong. That will really confuse the SVN people, since you're using words that have specific meanings in the context of SVN. To expand on what Davide said:</p>\n\n<p>2) create your repository by doing something like <code>svnadmin create /usr/local/svn</code>.</p>\n\n<p>3) create your folders. You don't need (or want) the parts of your list that aren't below <code>projects/</code>. Those other directories are what SVN uses to keep track of revisions, they're not actually in the repository. If you create a directory hierarchy somewhere on your system that contains the <code>project_name/</code> subtree, you can then run <code>svn import</code> on it as many times as you want, once for each project (giving a different name for the destination each time). That will create your directory structure.</p>\n\n<p>4) Instead of \"checkout\", I think you mean either \"import\" or \"checkin\" (usually called \"commit\" in SVN parlance, but \"checkin\" will be understood). Importing will add the vendor files to the repository. Checkout means \"create a local copy of this versioned directory for me to work with\" known as a Working Copy. Every developer on your team should have their own working copy. After a developer makes changes to their working copy, they then <code>svn commit</code> them which sends the changes to the repository. The other developers on the team will run <code>svn update</code> to get those changes from the repository into their own working copies.</p>\n\n<p>5) I haven't read the SVN book lately, but I think it instructs you to copy the version of the vendor branch into the trunk, not export it. Exporting in SVN terms means to un-version the directory tree, which is clearly not what you want.</p>\n\n<p>You may find things easier if you do steps 6 and 7 right after step 2, since then you can use the <code>svn://</code> protocol to access your repository for the remaining steps instead of <code>file://</code> as suggested by Davide, which only works on the local machine.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've read quite a bit of the Red Bean Software SVN Book, and some of the questions here on SO, but I want to make sure I'm going about this in the right way the first time around step-by-step before I begin using it. Is this correct? 1. Install SVN. 2. Create SVN repository at /usr/local/svn. Directory structure looks like this: ``` -- conf -- db -- format -- hooks -- locks -- README.txt ``` 3. Create folders through command line for repository organization (including projects and vendors). ``` -- conf -- db -- format -- hooks -- locks -- projects -- project_name -- vendor -- trunk -- branches -- tags -- project_name -- vendor -- trunk -- branches -- tags -- README.txt ``` 4. Checkout vendor code into vendor folder under the correct project name. 5. Export vendor code into trunk under the correct project name (no merge necessary, as I have no project trunk files yet). 6. Create users/permissions in /svnroot/conf/passwd and /svnroot/conf/svnserve.conf. 7. Make sure that svnserve is running, and on my local SVN client (TortoiseSVN), checkout the trunk for the project that I need. I don't need to serve this up by public URL, so I'm not configuring for Apache. The server is not in our network, but is a dedicated CentOS box we rent. Thanks for any thoughts and advice. **EDIT:** I guess I'm confused because I don't have code or a project to begin with, so I am starting fresh from the vendor's code. Do I need to create a directory structure somewhere on the server that includes my project\_name w/ vendor, trunk, branches and tags subfolders, import that into my repo, and then import the code from the vendor into the vendor folder? The idea is that I can get updates from the vendor, and then merge those updates with any changes I made to my trunk.
> > Create folders through command line for repository organization (including projects and vendors). > > > Do you mean creating the repository structure by making directories inside the subversion intallation directory? That's very wrong. You have to create the necessary folders via the `svn mkdir` command and not via filesystem. In `/usr/local/svn` you have the physical implementation of the Subversion repository, and you must access it only via a client, and never touch it "by hand". For example, using the file:// URL scheme ``` svn mkdir file:///usr/local/svn/projects -m "Parent dir for projects created" ```
259,634
<p>ok so basically I am asking the question of their name I want this to be one input rather than Forename and Surname.</p> <p>Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g.</p> <pre><code>name = "Thomas Winter" print name.split() </code></pre> <p>and what would be output is just "Winter"</p>
[ { "answer_id": 259638, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>print name.split()[-1]\n</code></pre>\n" }, { "answer_id": 259639, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 0, "selected": false, "text": "<p>You would probably want to use rsplit for this:</p>\n\n<pre><code>rsplit([sep [,maxsplit]])\n</code></pre>\n\n<p>Return a list of the words in the string, using <code>sep</code> as the delimiter string. If <code>maxsplit</code> is given, at most <code>maxsplit</code> splits are done, the rightmost ones. If <code>sep</code> is not specified or <code>None</code>, any whitespace string is a separator. Except for splitting from the right, <code>rsplit()</code> behaves like <code>split()</code> which is described in detail below. New in version 2.4. </p>\n" }, { "answer_id": 259643, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 4, "selected": false, "text": "<p>The problem with trying to split the names from a single input is that you won't get the full surname for people with spaces in their surname, and I don't believe you'll be able to write code to manage that completely.</p>\n\n<p>I would recommend that you ask for the names separately if it is at all possible.</p>\n" }, { "answer_id": 259659, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 2, "selected": false, "text": "<p>Splitting names is harder than it looks. Some names have two word last names; some people will enter a first, middle, and last name; some names have two work first names. The more reliable (or least unreliable) way to handle names is to always capture first and last name in separate fields. Of course this raises its own issues, like how to handle people with only one name, making sure it works for users that have a different ordering of name parts.</p>\n\n<p>Names are hard, handle with care.</p>\n" }, { "answer_id": 259662, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/159567/how-can-i-parse-the-first-middle-and-last-name-from-a-full-name-field-in-sql#159760\">Here's how to do it in SQL</a>. But data normalization with this kind of thing is really a bear. I agree with Dave DuPlantis about asking for separate inputs.</p>\n" }, { "answer_id": 259694, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 6, "selected": false, "text": "<p>You'll find that your key problem with this approach isn't a technical one, but a human one - different people write their names in different ways.</p>\n\n<p>In fact, the terminology of \"forename\" and \"surname\" is itself flawed.</p>\n\n<p>While many blended families use a hyphenated family name, such as Smith-Jones, there are some who just use both names separately, \"Smith Jones\" where both names are the family name.</p>\n\n<p>Many european family names have multiple parts, such as \"de Vere\" and \"van den Neiulaar\". Sometimes these extras have important family history - for example, a prefix awarded by a king hundreds of years ago.</p>\n\n<p>Side issue: I've capitalised these correctly for the people I'm referencing - \"de\" and \"van den\" don't get captial letters for some families, but do for others. </p>\n\n<p>Conversely, many Asian cultures put the family name first, because the family is considered more important than the individual.</p>\n\n<p>Last point - some people place great store in being \"Junior\" or \"Senior\" or \"III\" - and your code shouldn't treat those as the family name.</p>\n\n<p>Also noting that there are a fair number of people who use a name that isn't the one bestowed by their parents, I've used the following scheme with some success:</p>\n\n<p>Full Name (as normally written for addressing mail); \nFamily Name; \nKnown As (the name commonly used in conversation).</p>\n\n<p>e.g:</p>\n\n<p>Full Name: William Gates III; Family Name: Gates; Known As: Bill</p>\n\n<p>Full Name: Soong Li; Family Name: Soong; Known As: Lisa</p>\n" }, { "answer_id": 259735, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 0, "selected": false, "text": "<p>I would specify a standard format (some forms use them), such as \"Please write your name in <em>First name, Surname</em> form\".</p>\n\n<p>It makes it easier for you, as names don't usually contain a comma. It also verifies that your users actually enter both first name and surname.</p>\n" }, { "answer_id": 259804, "author": "CAD bloke", "author_id": 492, "author_profile": "https://Stackoverflow.com/users/492", "pm_score": 3, "selected": false, "text": "<p>Golden rule of data - don't aggregate too early - it is much easier to glue fields together than separate them. Most people also have a middle name which should be an optional field. Some people have a plethora of middle names. Some people only have <a href=\"https://stilgherrian.com/category/only-one-name/\" rel=\"nofollow noreferrer\">one name</a>, one word. Some cultures commonly have a dictionary of middle names, paying homage to the family tree back to the Golgafrincham Ark landing.</p>\n\n<p>You don't need a code solution here - you need a business rule.</p>\n" }, { "answer_id": 259809, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 3, "selected": false, "text": "<p>An easy way to do exactly what you asked in python is </p>\n\n<pre><code>name = \"Thomas Winter\"\nLastName = name.split()[1]\n</code></pre>\n\n<p>(note the parantheses on the function call split.)</p>\n\n<p>split() creates a list where each element is from your original string, delimited by whitespace. You can now grab the second element using name.split()[1] or the last element using name.split()[-1]</p>\n\n<p>However, as others said, unless you're SURE you're just getting a string like \"First_Name Last_Name\", there are a lot more issues involved. </p>\n" }, { "answer_id": 263331, "author": "UberJumper", "author_id": 34395, "author_profile": "https://Stackoverflow.com/users/34395", "pm_score": 2, "selected": false, "text": "<p>Since there are so many different variation's of how people write their names, but here's how a basic way to get the first/lastname via regex.</p>\n\n<pre><code>import re\np = re.compile(r'^(\\s+)?(Mr(\\.)?|Mrs(\\.)?)?(?P&lt;FIRST_NAME&gt;.+)(\\s+)(?P&lt;LAST_NAME&gt;.+)$', re.IGNORECASE)\nm = p.match('Mr. Dingo Bat')\nif(m != None):\n first_name = m.group('FIRST_NAME')\n last_name = m.group('LAST_NAME')\n</code></pre>\n" }, { "answer_id": 1656251, "author": "Jonathon Hill", "author_id": 168815, "author_profile": "https://Stackoverflow.com/users/168815", "pm_score": 2, "selected": false, "text": "<p>If you're trying to parse apart a human name in PHP, I recomment <a href=\"http://jonathonhill.net/2009-10-31/human-name-parsing-in-php/\" rel=\"nofollow noreferrer\">Keith Beckman's nameparse.php script</a>.</p>\n" }, { "answer_id": 2862586, "author": "Xealot", "author_id": 272079, "author_profile": "https://Stackoverflow.com/users/272079", "pm_score": 4, "selected": false, "text": "<p>This is a pretty old issue but I found it searching around for a solution to parsing out pieces from a globbed together name.</p>\n\n<p><a href=\"http://code.google.com/p/python-nameparser/\" rel=\"noreferrer\">http://code.google.com/p/python-nameparser/</a></p>\n" }, { "answer_id": 3688828, "author": "Josh Fraser", "author_id": 84387, "author_profile": "https://Stackoverflow.com/users/84387", "pm_score": 1, "selected": false, "text": "<p>It's definitely a more complicated task than it appears on the surface. I wrote up some of the challenges as well as my algorithm for solving it on my blog. Be sure to check out my Google Code project for it if you want the latest version in PHP:</p>\n\n<p><a href=\"http://www.onlineaspect.com/2009/08/17/splitting-names/\" rel=\"nofollow noreferrer\">http://www.onlineaspect.com/2009/08/17/splitting-names/</a></p>\n" }, { "answer_id": 9305240, "author": "Ryan Flores", "author_id": 1212961, "author_profile": "https://Stackoverflow.com/users/1212961", "pm_score": 2, "selected": false, "text": "<p>This is how I do it in my application:</p>\n\n<pre><code>def get_first_name(fullname):\n firstname = ''\n try:\n firstname = fullname.split()[0] \n except Exception as e:\n print str(e)\n return firstname\n\ndef get_last_name(fullname):\n lastname = ''\n try:\n index=0\n for part in fullname.split():\n if index &gt; 0:\n if index &gt; 1:\n lastname += ' ' \n lastname += part\n index += 1\n except Exception as e:\n print str(e)\n return lastname\n\ndef get_last_word(string):\n return string.split()[-1]\n\nprint get_first_name('Jim Van Loon')\nprint get_last_name('Jim Van Loon')\nprint get_last_word('Jim Van Loon')\n</code></pre>\n" }, { "answer_id": 56150253, "author": "Kurtis Pykes", "author_id": 10511518, "author_profile": "https://Stackoverflow.com/users/10511518", "pm_score": 0, "selected": false, "text": "<pre><code>name = \"Thomas Winter\"\nfirst, last = name.split()\nprint(\"First = {first}\".format(first=first))\n#First = Thomas\nprint(\"Last = {last}\".format(last=\" \".join(last)))\n#Last = Winter\n</code></pre>\n" }, { "answer_id": 59272196, "author": "Gaurav Meena", "author_id": 12421161, "author_profile": "https://Stackoverflow.com/users/12421161", "pm_score": 0, "selected": false, "text": "<p>You can use <code>str.find()</code> for this. </p>\n\n<pre><code>x=input(\"enter your name \")\nl=x.find(\" \")\nprint(\"your first name is\",x[:l])\nprint(\"your last name is\",x[l:])\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
ok so basically I am asking the question of their name I want this to be one input rather than Forename and Surname. Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g. ``` name = "Thomas Winter" print name.split() ``` and what would be output is just "Winter"
You'll find that your key problem with this approach isn't a technical one, but a human one - different people write their names in different ways. In fact, the terminology of "forename" and "surname" is itself flawed. While many blended families use a hyphenated family name, such as Smith-Jones, there are some who just use both names separately, "Smith Jones" where both names are the family name. Many european family names have multiple parts, such as "de Vere" and "van den Neiulaar". Sometimes these extras have important family history - for example, a prefix awarded by a king hundreds of years ago. Side issue: I've capitalised these correctly for the people I'm referencing - "de" and "van den" don't get captial letters for some families, but do for others. Conversely, many Asian cultures put the family name first, because the family is considered more important than the individual. Last point - some people place great store in being "Junior" or "Senior" or "III" - and your code shouldn't treat those as the family name. Also noting that there are a fair number of people who use a name that isn't the one bestowed by their parents, I've used the following scheme with some success: Full Name (as normally written for addressing mail); Family Name; Known As (the name commonly used in conversation). e.g: Full Name: William Gates III; Family Name: Gates; Known As: Bill Full Name: Soong Li; Family Name: Soong; Known As: Lisa
259,656
<p>I'm running through an XML document, selecting all the elements, and creating links based on the ancestor which is usually two nodes up in the tree, but occasionally 3 or 4 nodes up. For the majority of the elements, using <code>&lt;xsl:value-of select="translate(../../@name,$uc,$lc)" /&gt;</code> works just fine, but for the cases where the ancestor is 3 or so nodes up, I'd like to use <code>&lt;xsl:value-of select="translate(ancestor::package/@name,$uc,$lc)" /&gt;</code>, but this doesn't work.</p> <p>I'm using xsltproc from Ruby to do my XSL transforms.</p> <p>Sample tree (yes, it has XSLT in it, no, I'm not trying to process it):</p> <pre><code>&lt;package name="blork!" xmlns="http://xml.snapin.com/XBL"&gt; &lt;xsl:template name="doSomething"&gt; &lt;tokens&gt; &lt;token name="text-from-resource" export="public" /&gt; &lt;/tokens&gt; &lt;/xsl:template&gt; &lt;/package&gt; </code></pre> <p>The XSL I'm using:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s4="http://xml.snapin.com/XBL"&gt; &lt;xsl:template match="/"&gt; &lt;xsl:if test="count(//s4:token) &gt;0"&gt; &lt;xsl:text&gt;Tokens!&lt;/xsl:text&gt; &lt;xsl:for-each select="//s4:token"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@export='global'" /&gt; &lt;xsl:otherwise&gt; &lt;xsl:value-of select="translate(ancestor::s4:package/@name,$uc,$lc)" /&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:for-each&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><em>Edit:</em> Ah, right, forgot the namespace on the select. The parser's finding that ancestor properly for most cases, but it still can't find it when there's an xsl: node in there, and the target file has no namespace for xsl. I'd prefer not to modify the target file, because it's production code---I'm just writing an autodoc tool.</p>
[ { "answer_id": 259664, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": true, "text": "<p>Your problem is probably namespace related. You haven't included those in the sample tree - can you be a bit more precise in what you've pasted? Assuming the package node is in the same namespace as the token node, try:</p>\n\n<pre><code>&lt;xsl:value-of select=\"translate(ancestor::s4:package/@name,$uc,$lc)\" /&gt;\n</code></pre>\n\n<p>You can also test just the unqualified name, though it will be slower:</p>\n\n<pre><code>&lt;xsl:value-of select=\"translate(ancestor::*[local-name()='package']/@name,$uc,$lc)\" /&gt;\n</code></pre>\n\n<p>W3C local-name() spec <a href=\"http://www.w3.org/TR/xpath#function-local-name\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 260190, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 1, "selected": false, "text": "<p>I think there's no way around declaring the namespace for the 'xsl' prefix in the target doc as long as you're using namespace-aware XML processors. Are you not seeing any errors when you try to transform the target doc with xsltproc and the given stylesheet?</p>\n" }, { "answer_id": 260219, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 0, "selected": false, "text": "<p>You might double-check what version of XSLT your tools are using. I believe XSLT 1.0 does not support \"ancestor::&lt;tag&gt;...\"</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26257/" ]
I'm running through an XML document, selecting all the elements, and creating links based on the ancestor which is usually two nodes up in the tree, but occasionally 3 or 4 nodes up. For the majority of the elements, using `<xsl:value-of select="translate(../../@name,$uc,$lc)" />` works just fine, but for the cases where the ancestor is 3 or so nodes up, I'd like to use `<xsl:value-of select="translate(ancestor::package/@name,$uc,$lc)" />`, but this doesn't work. I'm using xsltproc from Ruby to do my XSL transforms. Sample tree (yes, it has XSLT in it, no, I'm not trying to process it): ``` <package name="blork!" xmlns="http://xml.snapin.com/XBL"> <xsl:template name="doSomething"> <tokens> <token name="text-from-resource" export="public" /> </tokens> </xsl:template> </package> ``` The XSL I'm using: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s4="http://xml.snapin.com/XBL"> <xsl:template match="/"> <xsl:if test="count(//s4:token) >0"> <xsl:text>Tokens!</xsl:text> <xsl:for-each select="//s4:token"> <xsl:choose> <xsl:when test="@export='global'" /> <xsl:otherwise> <xsl:value-of select="translate(ancestor::s4:package/@name,$uc,$lc)" /> </xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:if> </xsl:template> </xsl:stylesheet> ``` *Edit:* Ah, right, forgot the namespace on the select. The parser's finding that ancestor properly for most cases, but it still can't find it when there's an xsl: node in there, and the target file has no namespace for xsl. I'd prefer not to modify the target file, because it's production code---I'm just writing an autodoc tool.
Your problem is probably namespace related. You haven't included those in the sample tree - can you be a bit more precise in what you've pasted? Assuming the package node is in the same namespace as the token node, try: ``` <xsl:value-of select="translate(ancestor::s4:package/@name,$uc,$lc)" /> ``` You can also test just the unqualified name, though it will be slower: ``` <xsl:value-of select="translate(ancestor::*[local-name()='package']/@name,$uc,$lc)" /> ``` W3C local-name() spec [here](http://www.w3.org/TR/xpath#function-local-name).
259,709
<p>I the following styles:</p> <pre><code>a.button { background-color: orange; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } a.buttonMouseover { background-color: darkGoldenRod; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } </code></pre> <p>And the following javascript code (my first ever btw):</p> <pre><code>function backgroundChangeIn(element){ if (element.className = "a.button"){element.className = "buttonMouseover";} } function backgroundChangeOut(element){ if (element.className = "a.buttonMouseover"){element.className = "button";} } </code></pre> <p>And, the following element that should change the background on mouseover:</p> <pre><code>&lt;a class="button" href="" onmouseover="backgroundChangeIn(this)" onmouseout="backgroundChangeOut(this)"&gt;A Button&lt;/a&gt; </code></pre> <p>It is working for me so far. But I was wondering if there was a better way.</p> <p>(Sorry about all the code)</p>
[ { "answer_id": 259712, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "<p>Depending on your target browsers, you could use the <code>hover</code> pseudo tag.</p>\n\n<pre><code>a.button {\n background-color: orange;\n margin: .2cm;\n padding: .2cm;\n color: black;\n font-family: sans-serif;\n text-decoration: none;\n font-weight: bold;\n border: solid #000000;\n}\n\na.button:hover {\n background-color: darkGoldenRod;\n}\n</code></pre>\n\n<p>Here's a bit of documentation on it at <a href=\"http://www.w3schools.com/css/pr_pseudo_hover.asp\" rel=\"nofollow noreferrer\">w3schools</a>. It looks like it's well supported on all remotely modern browsers.</p>\n\n<p>Note that both the normal and the hover styling rules are applied, hover taking precedence. So you just need to put what changes in the hover rule.</p>\n" }, { "answer_id": 259713, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 1, "selected": false, "text": "<pre><code>a.button, a.button:hover {\n margin: .2cm;\n padding: .2cm;\n color: black;\n font-family: sans-serif;\n text-decoration: none;\n font-weight: bold;\n border: solid #000000;\n}\n\na.button {\n background-color: orange;\n}\n\na.button:hover {\n background-color: darkGoldenRod;\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>&lt;a class=\"button\" href=\"\"&gt;A Button&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 259714, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": -1, "selected": false, "text": "<p>You can use a library like <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\" title=\"jQuery\">jQuery</a> to make things simpler.</p>\n" }, { "answer_id": 259739, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 3, "selected": false, "text": "<p>sblundy has the basics right. To add to that, all modern browsers will allow you to use the hover pseudo element on the &lt;a&gt; however IE6 won't recognise this on any other element.</p>\n\n<p>In IE6 you would need some sort of JavaScript to add a class name when you hover. I like using jQuery, and the way I would do it like that is as follows:</p>\n\n<pre><code>$(function(){\n $('.hoverable').hover(function(){\n $(this).addClass('hover');\n },\n function(){\n $(this).removeClass('hover');\n })\n})\n</code></pre>\n\n<p>which would give all elements with the class 'hoverable' a class of hover when they are hovered over.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I the following styles: ``` a.button { background-color: orange; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } a.buttonMouseover { background-color: darkGoldenRod; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } ``` And the following javascript code (my first ever btw): ``` function backgroundChangeIn(element){ if (element.className = "a.button"){element.className = "buttonMouseover";} } function backgroundChangeOut(element){ if (element.className = "a.buttonMouseover"){element.className = "button";} } ``` And, the following element that should change the background on mouseover: ``` <a class="button" href="" onmouseover="backgroundChangeIn(this)" onmouseout="backgroundChangeOut(this)">A Button</a> ``` It is working for me so far. But I was wondering if there was a better way. (Sorry about all the code)
Depending on your target browsers, you could use the `hover` pseudo tag. ``` a.button { background-color: orange; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } a.button:hover { background-color: darkGoldenRod; } ``` Here's a bit of documentation on it at [w3schools](http://www.w3schools.com/css/pr_pseudo_hover.asp). It looks like it's well supported on all remotely modern browsers. Note that both the normal and the hover styling rules are applied, hover taking precedence. So you just need to put what changes in the hover rule.
259,719
<p>I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:</p> <pre><code>$doc-&gt;addChild('myToken'); </code></pre> <p>This generates (what I know as) a self-closing or single tag:</p> <pre><code>&lt;myToken/&gt; </code></pre> <p>However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:</p> <pre><code>&lt;myToken&gt;&lt;/myToken&gt; </code></pre> <p>The question is, how do I do this, outside of running the generated XML through a <strong>preg_replace</strong>?</p>
[ { "answer_id": 259754, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 3, "selected": true, "text": "<p>From the documentation at <a href=\"http://www.php.net/manual/en/function.simplexml-element-construct.php\" rel=\"nofollow noreferrer\">SimpleXMLElement->__construct</a> and <a href=\"http://cz2.php.net/manual/en/libxml.constants.php\" rel=\"nofollow noreferrer\">LibXML Predefined Constants</a>, I think this should work:</p>\n\n<pre><code>&lt;?php\n$sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG);\n\n// some processing here\n\n$out = $sxe-&gt;asXML();\n?&gt;\n</code></pre>\n\n<p>Try that and see if it works. Otherwise, I'm afraid, it's preg_replace-land.</p>\n" }, { "answer_id": 25036442, "author": "Milos Cuculovic", "author_id": 1018270, "author_profile": "https://Stackoverflow.com/users/1018270", "pm_score": 2, "selected": false, "text": "<p>At the moment, it is not possible to avoid self closing tags wiht LibXML. One of the proposed solution by @Piskvor will not work:</p>\n\n<p>LIBXML_NOEMPTYTAG does not work with simplexml, as mentionned <a href=\"http://us2.php.net/manual/en/libxml.constants.php\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.\n</code></pre>\n\n<p>A workaround for that will be to use the answer from <a href=\"https://stackoverflow.com/questions/19629379/how-to-prevent-self-closing-tag-in-php-simplexml#answer-19630648\">this question</a></p>\n" }, { "answer_id": 29581022, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 2, "selected": false, "text": "<p>If you set the value to something empty (i.e. null, empty string) it will use open/close brackets.</p>\n\n<pre><code>$tag = '&lt;SomeTagName/&gt;';\n\necho \"Tag: '$tag'\\n\\n\";\n\n$x = new SimpleXMLElement($tag);\necho \"Autoclosed: {$x-&gt;asXML()}\\n\";\n\n$x = new SimpleXMLElement($tag);\n$x[0] = null;\necho \"Null: {$x-&gt;asXML()}\\n\";\n\n$x = new SimpleXMLElement($tag);\n$x[0] = '';\necho \"Empty: {$x-&gt;asXML()}\\n\";\n</code></pre>\n\n<p>See example: <a href=\"http://sandbox.onlinephpfunctions.com/code/10642a84dca5a50eba882a347f152fc480bc47b5\" rel=\"nofollow\">http://sandbox.onlinephpfunctions.com/code/10642a84dca5a50eba882a347f152fc480bc47b5</a></p>\n" }, { "answer_id": 31028384, "author": "Rochdi", "author_id": 5044882, "author_profile": "https://Stackoverflow.com/users/5044882", "pm_score": 0, "selected": false, "text": "<p>May be not the best solution but got same problem and solved it with using pre_replace to change all the self closing tags to full form...</p>\n\n<pre><code>$xml_reader = new XMLReader;\n$xml_reader-&gt;open($xml_file);\n\n$data = preg_replace('/\\&lt;(\\w+)\\s*\\/\\s*\\&gt;/i', '&lt;$1&gt;&lt;/$1&gt;', $xml_reader-&gt;readOuterXML());\n</code></pre>\n" }, { "answer_id": 56356569, "author": "Petr Gürth", "author_id": 3241655, "author_profile": "https://Stackoverflow.com/users/3241655", "pm_score": 0, "selected": false, "text": "<p><code>LIBXML_NOEMPTYTAG</code> works but only if you use <code>DOMDocument::save</code> or <code>DOMDocument::saveXML</code></p>\n\n<pre><code>$dom = dom_import_simplexml(SimpleXMLElement)-&gt;ownerDocument;\n$dom-&gt;formatOutput = true;\n$dom-&gt;save($save_path, LIBXML_NOEMPTYTAG);\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33739/" ]
I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file: ``` $doc->addChild('myToken'); ``` This generates (what I know as) a self-closing or single tag: ``` <myToken/> ``` However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag: ``` <myToken></myToken> ``` The question is, how do I do this, outside of running the generated XML through a **preg\_replace**?
From the documentation at [SimpleXMLElement->\_\_construct](http://www.php.net/manual/en/function.simplexml-element-construct.php) and [LibXML Predefined Constants](http://cz2.php.net/manual/en/libxml.constants.php), I think this should work: ``` <?php $sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG); // some processing here $out = $sxe->asXML(); ?> ``` Try that and see if it works. Otherwise, I'm afraid, it's preg\_replace-land.
259,726
<p>I am using XmlSerializer to write and read an object to xml in C#. I currently use the attributes <code>XmlElement</code> and <code>XmlIgnore</code> to manipulate the serialization of the object.</p> <p>If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine. How do I indicate (preferably via Attributes) that a certain field is "required"?</p> <p>Here is a sample method of what I am using currently:</p> <pre><code>[XmlElement(ElementName="numberOfWidgets")] public int NumberThatIsRequired { set ...; get ...; } </code></pre> <p>My ideal solution would be to add something like an <code>XmlRequired</code> attribute. </p> <p>Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?</p>
[ { "answer_id": 259732, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>I've got an answer for the second part: <a href=\"http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx\" rel=\"nofollow noreferrer\">\"Attributes that control XML serialization\"</a>.</p>\n\n<p>Still investigating the first part...</p>\n\n<p>EDIT: I strongly suspect you can't do this through XML deserialization itself. I've just run xsd.exe on a sample schema which includes a required attribute - and it's exactly the same if the attribute is marked as being optional. If there were a way of requiring properties to be set, I'd expect it to be implemented in that case.</p>\n\n<p>I suspect you've basically got to just validate your tree of objects after deserializing it. Sorry about that...</p>\n" }, { "answer_id": 259969, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 4, "selected": false, "text": "<p>The only way I've found to do this is via XSD. What you can do is validate while you deserialize:</p>\n\n<pre><code>static T Deserialize&lt;T&gt;(string xml, XmlSchemaSet schemas)\n{\n //List&lt;XmlSchemaException&gt; exceptions = new List&lt;XmlSchemaException&gt;();\n ValidationEventHandler validationHandler = (s, e) =&gt;\n {\n //you could alternatively catch all the exceptions\n //exceptions.Add(e.Exception);\n throw e.Exception;\n };\n\n XmlReaderSettings settings = new XmlReaderSettings();\n settings.Schemas.Add(schemas);\n settings.ValidationType = ValidationType.Schema;\n settings.ValidationEventHandler += validationHandler;\n\n XmlSerializer serializer = new XmlSerializer(typeof(T));\n using (StringReader sr = new StringReader(xml))\n using (XmlReader books = XmlReader.Create(sr, settings))\n return (T)serializer.Deserialize(books);\n}\n</code></pre>\n" }, { "answer_id": 260955, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>For extensibility reasons, <code>XmlSerializer</code> is very forgiving when it comes to deserialization; things like <code>[DefaultValue]</code>, <code>ShouldSerialize{Foo}</code> and <code>{Foo}Specified</code> are <em>mainly</em> used during <em>serialization</em> (the exception being <code>{Foo}Specified</code>, which is set during deserialization as well as queried during serialization).</p>\n<p>As such; there isn't an easy way to do this, unless you implement <code>IXmlSerializable</code> and do it yourself. Richard shows an xsd option, which is also an option.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ]
I am using XmlSerializer to write and read an object to xml in C#. I currently use the attributes `XmlElement` and `XmlIgnore` to manipulate the serialization of the object. If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine. How do I indicate (preferably via Attributes) that a certain field is "required"? Here is a sample method of what I am using currently: ``` [XmlElement(ElementName="numberOfWidgets")] public int NumberThatIsRequired { set ...; get ...; } ``` My ideal solution would be to add something like an `XmlRequired` attribute. Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?
I've got an answer for the second part: ["Attributes that control XML serialization"](http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx). Still investigating the first part... EDIT: I strongly suspect you can't do this through XML deserialization itself. I've just run xsd.exe on a sample schema which includes a required attribute - and it's exactly the same if the attribute is marked as being optional. If there were a way of requiring properties to be set, I'd expect it to be implemented in that case. I suspect you've basically got to just validate your tree of objects after deserializing it. Sorry about that...
259,730
<p>I have two vb.net class:</p> <pre><code>Public MustInherit Class Class1 Private m_sProperty1 As String = "" Public Property sProperty1() As String Get Return m_sProperty1 End Get Set(ByVal value As String) m_sProperty1 = value End Set End Property End Class &lt;ComClass("classid","interfaceid","eventid")&gt; _ Public Class Class2 Inherits Class1 Private m_sProperty2 As String = "" Public Property sProperty2() As String Get Return m_sProperty2 End Get Set(ByVal value As String) m_sProperty2 = value End Set End Property End Class </code></pre> <p>When I reference the compiled DLL through VB6, Class2 only exposes sProperty2. How can I access the inherited property of the base class (sProperty1) through COM?</p>
[ { "answer_id": 546498, "author": "Toby Allen", "author_id": 6244, "author_profile": "https://Stackoverflow.com/users/6244", "pm_score": 0, "selected": false, "text": "<p>I'll take a guess as I'm not up to speed on .NET</p>\n\n<p>I would imagine your declaration is taking your public methods of Class2 and creating a COM interface out of them. It will only take methods (and properties) on Class2 and not inherited ones (otherwise you would get all public methods all the way down to your base class).</p>\n\n<p>The solution would probably be to declare Class1 as a COM class also (it may be possible to mark it as private) then specify that the COM interfaceid of Class2 descends from the COM interfaceid of Class1.</p>\n\n<p>Some thing like that shoudl do the trick.</p>\n" }, { "answer_id": 546595, "author": "CraigTP", "author_id": 57477, "author_profile": "https://Stackoverflow.com/users/57477", "pm_score": 1, "selected": false, "text": "<p>This seems to answer your question:</p>\n<p><strong>Exporting Inheritance Hierarchies</strong></p>\n<p>Managed class hierarchies flatten out when exposed as COM objects. For example, if you define a base class with a member, and then inherit the base class in a derived class that is exposed as a COM object, clients that use the derived class in the COM object will not be able to use the inherited members. Base class members are accessible from COM objects only as instances of a base class, and then only if the base class is also created as a COM object.</p>\n<p>Taken from here: <a href=\"https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/com-interop/troubleshooting-interoperability\" rel=\"nofollow noreferrer\">Troubleshooting Interoperability</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have two vb.net class: ``` Public MustInherit Class Class1 Private m_sProperty1 As String = "" Public Property sProperty1() As String Get Return m_sProperty1 End Get Set(ByVal value As String) m_sProperty1 = value End Set End Property End Class <ComClass("classid","interfaceid","eventid")> _ Public Class Class2 Inherits Class1 Private m_sProperty2 As String = "" Public Property sProperty2() As String Get Return m_sProperty2 End Get Set(ByVal value As String) m_sProperty2 = value End Set End Property End Class ``` When I reference the compiled DLL through VB6, Class2 only exposes sProperty2. How can I access the inherited property of the base class (sProperty1) through COM?
This seems to answer your question: **Exporting Inheritance Hierarchies** Managed class hierarchies flatten out when exposed as COM objects. For example, if you define a base class with a member, and then inherit the base class in a derived class that is exposed as a COM object, clients that use the derived class in the COM object will not be able to use the inherited members. Base class members are accessible from COM objects only as instances of a base class, and then only if the base class is also created as a COM object. Taken from here: [Troubleshooting Interoperability](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/com-interop/troubleshooting-interoperability)
259,751
<p>Need a function like: </p> <pre><code>function isGoogleURL(url) { ... } </code></pre> <p>that returns true iff URL belongs to Google. No false positives; no false negatives.</p> <p>Luckily there's <a href="http://www.google.com/supported_domains" rel="nofollow noreferrer">this</a> as a reference:</p> <blockquote> <p>.google.com .google.ad .google.ae .google.com.af .google.com.ag .google.com.ai .google.am .google.it.ao .google.com.ar .google.as .google.at .google.com.au .google.az .google.ba .google.com.bd .google.be .google.bg .google.com.bh .google.bi .google.com.bn .google.com.bo .google.com.br .google.bs .google.co.bw .google.com.by .google.com.bz .google.ca .google.cd .google.cg .google.ch .google.ci .google.co.ck .google.cl .google.cn .google.com.co .google.co.cr .google.com.cu .google.cz .google.de .google.dj .google.dk .google.dm .google.com.do .google.dz .google.com.ec .google.ee .google.com.eg .google.es .google.com.et .google.fi .google.com.fj .google.fm .google.fr .google.ge .google.gg .google.com.gh .google.com.gi .google.gl .google.gm .google.gp .google.gr .google.com.gt .google.gy .google.com.hk .google.hn .google.hr .google.ht .google.hu .google.co.id .google.ie .google.co.il .google.im .google.co.in .google.is .google.it .google.je .google.com.jm .google.jo .google.co.jp .google.co.ke .google.com.kh .google.ki .google.kg .google.co.kr .google.kz .google.la .google.li .google.lk .google.co.ls .google.lt .google.lu .google.lv .google.com.ly .google.co.ma .google.md .google.mn .google.ms .google.com.mt .google.mu .google.mv .google.mw .google.com.mx .google.com.my .google.co.mz .google.com.na .google.com.nf .google.com.ng .google.com.ni .google.nl .google.no .google.com.np .google.nr .google.nu .google.co.nz .google.com.om .google.com.pa .google.com.pe .google.com.ph .google.com.pk .google.pl .google.pn .google.com.pr .google.pt .google.com.py .google.com.qa .google.ro .google.ru .google.rw .google.com.sa .google.com.sb .google.sc .google.se .google.com.sg .google.sh .google.si .google.sk .google.sn .google.sm .google.st .google.com.sv .google.co.th .google.com.tj .google.tk .google.tl .google.tm .google.to .google.com.tr .google.tt .google.com.tw .google.co.tz .google.com.ua .google.co.ug .google.co.uk .google.com.uy .google.co.uz .google.com.vc .google.co.ve .google.vg .google.co.vi .google.com.vn .google.vu .google.ws .google.rs .google.co.za .google.co.zm .google.co.zw .google.cat</p> </blockquote> <p>Any ideas how to do this elegantly?</p> <p><strong>Some Clarifications:</strong></p> <ul> <li>I need this for a greasemonkey script I wrote that currently only works for google.com (and should work for all other TLDs as well). <a href="http://userscripts.org/scripts/show/6415" rel="nofollow noreferrer">Here</a> is the script (it modifies Google Reader to work on wide screens better).</li> <li>It should work on URLs that belong to the above domains (not blogger.com, etc.).</li> </ul>
[ { "answer_id": 259768, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Do you count other Google properties as \"belonging to Google\"? FeedBurner, Blogger etc?</p>\n\n<p>Can I ask what the purpose of this is? There may be a better way of doing what you want... and if it's reasonable I can ask internally for you.</p>\n" }, { "answer_id": 259773, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 0, "selected": false, "text": "<p>I wouldn't do this client-side.</p>\n\n<p>The list of Google domains doesn't change so frequently, so you could store a list server-side and then dynamically generate the .js to check it.</p>\n" }, { "answer_id": 259781, "author": "Echilon", "author_id": 30512, "author_profile": "https://Stackoverflow.com/users/30512", "pm_score": -1, "selected": false, "text": "<p>Without a regex to individually match each and every TLD, there isn't really an 'elegant way of doing it'.</p>\n" }, { "answer_id": 259788, "author": "luiscubal", "author_id": 32775, "author_profile": "https://Stackoverflow.com/users/32775", "pm_score": 0, "selected": false, "text": "<p>A regular expression may be what you need.\nAn example is:</p>\n\n<pre><code>&lt;script&gt;\nvar elem = document.getElementById(\"a\");\nvar regex = new RegExp(\"(http://)?(www\\\\.)?google\\\\.com\");\n\nelem.innerHTML = regex.test(elem.innerHTML);\n&lt;/script&gt;\n</code></pre>\n\n<p>This would get the content of a span element \"a\", and would change it to \"true\" if google.com, and \"false\" otherwise.\nNote that it doesn't consider all other URLs(although the regex could easily be modified to do so), and \"pages.google.com\", for example, wouldn't match.</p>\n\n<p>Also, your URLs all have a \".\" before them(\".google.com\" instead of \"google.com\"). Does this have any reason or is it just a mistake?</p>\n" }, { "answer_id": 259830, "author": "Berzemus", "author_id": 2452, "author_profile": "https://Stackoverflow.com/users/2452", "pm_score": 1, "selected": false, "text": "<p>If you don't need the test to be 100% accurate, this simple regex would do for all the domains you posted above:</p>\n\n<pre><code>\"(http://)?([\\w]+)?\\.google\\.([\\w]{2,3})\"\n</code></pre>\n\n<p>Just testing the presence of \".google.\" would suffice in most cases, although it could easily be fooled by adding a \"google\" domain in the url (not so easy though, nor quickly done).</p>\n\n<p>Or just wait for google to buy their own google TLD.</p>\n" }, { "answer_id": 259893, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 0, "selected": false, "text": "<p>You could use a regular expression like....</p>\n\n<pre><code>^https?://[-A-Za-z0-9\\.]+(\\.google\\.com|\\.google\\.ad|\\.google\\.ae|\\.google\\.com\\.af|\\.google\\.com\\.ag|\\.google\\.com\\.ai|\\.google\\.am|\\.google\\.it\\.ao|\\.google\\.com\\.ar|\\.google\\.as|\\.google\\.at|\\.google\\.com\\.au|\\.google\\.az|\\.google\\.ba|\\.google\\.com\\.bd|\\.google\\.be|\\.google\\.bg|\\.google\\.com\\.bh|\\.google\\.bi|\\.google\\.com\\.bn|\\.google\\.com\\.bo|\\.google\\.com\\.br|\\.google\\.bs|\\.google\\.co\\.bw|\\.google\\.com\\.by|\\.google\\.com\\.bz|\\.google\\.ca|\\.google\\.cd|\\.google\\.cg|\\.google\\.ch|\\.google\\.ci|\\.google\\.co\\.ck|\\.google\\.cl|\\.google\\.cn|\\.google\\.com\\.co|\\.google\\.co\\.cr|\\.google\\.com\\.cu|\\.google\\.cz|\\.google\\.de|\\.google\\.dj|\\.google\\.dk|\\.google\\.dm|\\.google\\.com\\.do|\\.google\\.dz|\\.google\\.com\\.ec|\\.google\\.ee|\\.google\\.com\\.eg|\\.google\\.es|\\.google\\.com\\.et|\\.google\\.fi|\\.google\\.com\\.fj|\\.google\\.fm|\\.google\\.fr|\\.google\\.ge|\\.google\\.gg|\\.google\\.com\\.gh|\\.google\\.com\\.gi|\\.google\\.gl|\\.google\\.gm|\\.google\\.gp|\\.google\\.gr|\\.google\\.com\\.gt|\\.google\\.gy|\\.google\\.com\\.hk|\\.google\\.hn|\\.google\\.hr|\\.google\\.ht|\\.google\\.hu|\\.google\\.co\\.id|\\.google\\.ie|\\.google\\.co\\.il|\\.google\\.im|\\.google\\.co\\.in|\\.google\\.is|\\.google\\.it|\\.google\\.je|\\.google\\.com\\.jm|\\.google\\.jo|\\.google\\.co\\.jp|\\.google\\.co\\.ke|\\.google\\.com\\.kh|\\.google\\.ki|\\.google\\.kg|\\.google\\.co\\.kr|\\.google\\.kz|\\.google\\.la|\\.google\\.li|\\.google\\.lk|\\.google\\.co\\.ls|\\.google\\.lt|\\.google\\.lu|\\.google\\.lv|\\.google\\.com\\.ly|\\.google\\.co\\.ma|\\.google\\.md|\\.google\\.mn|\\.google\\.ms|\\.google\\.com\\.mt|\\.google\\.mu|\\.google\\.mv|\\.google\\.mw|\\.google\\.com\\.mx|\\.google\\.com\\.my|\\.google\\.co\\.mz|\\.google\\.com\\.na|\\.google\\.com\\.nf|\\.google\\.com\\.ng|\\.google\\.com\\.ni|\\.google\\.nl|\\.google\\.no|\\.google\\.com\\.np|\\.google\\.nr|\\.google\\.nu|\\.google\\.co\\.nz|\\.google\\.com\\.om|\\.google\\.com\\.pa|\\.google\\.com\\.pe|\\.google\\.com\\.ph|\\.google\\.com\\.pk|\\.google\\.pl|\\.google\\.pn|\\.google\\.com\\.pr|\\.google\\.pt|\\.google\\.com\\.py|\\.google\\.com\\.qa|\\.google\\.ro|\\.google\\.ru|\\.google\\.rw|\\.google\\.com\\.sa|\\.google\\.com\\.sb|\\.google\\.sc|\\.google\\.se|\\.google\\.com\\.sg|\\.google\\.sh|\\.google\\.si|\\.google\\.sk|\\.google\\.sn|\\.google\\.sm|\\.google\\.st|\\.google\\.com\\.sv|\\.google\\.co\\.th|\\.google\\.com\\.tj|\\.google\\.tk|\\.google\\.tl|\\.google\\.tm|\\.google\\.to|\\.google\\.com\\.tr|\\.google\\.tt|\\.google\\.com\\.tw|\\.google\\.co\\.tz|\\.google\\.com\\.ua|\\.google\\.co\\.ug|\\.google\\.co\\.uk|\\.google\\.com\\.uy|\\.google\\.co\\.uz|\\.google\\.com\\.vc|\\.google\\.co\\.ve|\\.google\\.vg|\\.google\\.co\\.vi|\\.google\\.com\\.vn|\\.google\\.vu|\\.google\\.ws|\\.google\\.rs|\\.google\\.co\\.za|\\.google\\.co\\.zm|\\.google\\.co\\.zw|\\.google\\.cat)\n</code></pre>\n\n<p>and I'd imagine generating that in JavaScript (or whatever language you choose) from an array or some other data set would be relatively easy.</p>\n" }, { "answer_id": 259918, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 1, "selected": false, "text": "<p>I agree that you probably shouldn't do this... However, if you are going to do it (and you aren't content with the previously offered solutions that just check for a google-like pattern) then this is how I would approach it:</p>\n\n<pre><code>var GOOGLE_DOMAINS = ([\n '.google.com',\n '.google.ad',\n '.google.ae',\n '.google.com.af',\n '.google.com.ag',\n '.google.com.ai',\n '.google.am',\n '.google.it.ao',\n '.google.com.ar',\n '.google.as',\n '.google.at',\n '.google.com.au',\n '.google.az',\n '.google.ba',\n '.google.com.bd'\n]).join('\\n');\n\nfunction isGoogleUrl(url) {\n var url = 'http://www.google.ba/the/page.html';\n\n // get the domain from the url\n var domain = /\\.google\\.[^\\/\\\\]+/i.exec(url) + '';\n if(!domain) return false;\n\n // create a regex to check to see if the domain is supported\n var re = new RegExp('^' + domain.replace(/\\./g, '\\\\.') + '$', 'mi');\n return re.test(GOOGLE_DOMAINS);\n}\n</code></pre>\n\n<p>This creates a regex based on the domain your url and uses it to test the list of domains.</p>\n\n<p>Note: The <code>GOOGLE_DOMAINS</code> variable is just a string that holds the contents returned from the url you posted. There is no way for you to retrieve that string via AJAX or iframe because you cannot make such a request across domains. You'll have to hard code it or make a request server-side to retrieve that list.</p>\n" }, { "answer_id": 294197, "author": "wimh", "author_id": 33499, "author_profile": "https://Stackoverflow.com/users/33499", "pm_score": 4, "selected": true, "text": "<p>Here is an updated version of Prestaul's answer which solves the two problems I mentioned in the comment there.</p>\n\n<pre><code>var GOOGLE_DOMAINS = ([\n '.google.com',\n '.google.ad',\n '.google.ae',\n '.google.com.af',\n '.google.com.ag',\n '.google.com.ai',\n '.google.am',\n '.google.it.ao',\n '.google.com.ar',\n '.google.as',\n '.google.at',\n '.google.com.au',\n '.google.az',\n '.google.ba',\n '.google.com.bd'\n]).join('\\n');\n\nfunction isGoogleUrl(url) {\n // get the 2nd level domain from the url\n var domain = /^https?:\\/\\/[^\\///]*(google\\.[^\\/\\\\]+)\\//i.exec(url);\n if(!domain) return false;\n\n domain = '.'+domain[1];\n // create a regex to check to see if the domain is supported\n var re = new RegExp('^' + domain.replace(/\\./g, '\\\\.') + '$', 'mi');\n return re.test(GOOGLE_DOMAINS);\n}\n\nalert(isGoogleUrl('http://www.google.ba/the/page.html')); // true\nalert(isGoogleUrl('http://some_mal_site.com/http://www.google.ba/')); // false\nalert(isGoogleUrl('https://google.com.au/')); // true\nalert(isGoogleUrl('http://www.google.com.some_mal_site.com/')); // false\nalert(isGoogleUrl('http://yahoo.com/')); // false\n</code></pre>\n" }, { "answer_id": 294269, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 2, "selected": false, "text": "<p>All the domains end in either \"google.xx\", \"google.co.xx\", or \"google.com.xx\" except \"google.it.ao\" and \"google.com\", so if you just look at the domain, this regular expression should work for most cases (it's not perfect, but it accepts all the listed domains, and rejects most other valid domains that happen to include \"google\"):</p>\n\n<pre><code>/^(\\w+\\.)*google\\.((com\\.|co\\.|it\\.)?([a-z]{2})|com)$/i\n</code></pre>\n\n<p>As a function you could do something like this:</p>\n\n<pre><code>function isGoogleUrl(url) {\n url = url.replace(/^https?:\\/\\//i, ''); // Strip \"http://\" from the beginning\n url = url.replace(/\\/.*/, ''); // Strip off the path\n return /^(\\w+\\.)*google\\.((com\\.|co\\.|it\\.)?([a-z]{2})|com)$/i.test(url);\n}\n</code></pre>\n\n<p>You could simplify it if you use <code>window.location.hostname</code>:</p>\n\n<pre><code>function isGoogleUrl() {\n return /^(\\w+\\.)*google\\.((com\\.|co\\.|it\\.)?([a-z]{2})|com)$/i.test(window.location.hostname);\n}\n</code></pre>\n\n<p>The only way this should allow a false positive is if there is a \"google.(some other TLD)\". For example, \"google.tv\", is not on the list (it redirects to google.com), but it would pass.</p>\n\n<p><strong>Edit:</strong> Like Wimmel pointed out, it also accepts invalid domains like \"google.com.fr\" which are not listed. It will basically accept any \"google.whatever\" domain name.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11208/" ]
Need a function like: ``` function isGoogleURL(url) { ... } ``` that returns true iff URL belongs to Google. No false positives; no false negatives. Luckily there's [this](http://www.google.com/supported_domains) as a reference: > > .google.com .google.ad .google.ae .google.com.af .google.com.ag .google.com.ai .google.am .google.it.ao .google.com.ar .google.as .google.at .google.com.au .google.az .google.ba .google.com.bd .google.be .google.bg .google.com.bh .google.bi .google.com.bn .google.com.bo .google.com.br .google.bs .google.co.bw .google.com.by .google.com.bz .google.ca .google.cd .google.cg .google.ch .google.ci .google.co.ck .google.cl .google.cn .google.com.co .google.co.cr .google.com.cu .google.cz .google.de .google.dj .google.dk .google.dm .google.com.do .google.dz .google.com.ec .google.ee .google.com.eg .google.es .google.com.et .google.fi .google.com.fj .google.fm .google.fr .google.ge .google.gg .google.com.gh .google.com.gi .google.gl .google.gm .google.gp .google.gr .google.com.gt .google.gy .google.com.hk .google.hn .google.hr .google.ht .google.hu .google.co.id .google.ie .google.co.il .google.im .google.co.in .google.is .google.it .google.je .google.com.jm .google.jo .google.co.jp .google.co.ke .google.com.kh .google.ki .google.kg .google.co.kr .google.kz .google.la .google.li .google.lk .google.co.ls .google.lt .google.lu .google.lv .google.com.ly .google.co.ma .google.md .google.mn .google.ms .google.com.mt .google.mu .google.mv .google.mw .google.com.mx .google.com.my .google.co.mz .google.com.na .google.com.nf .google.com.ng .google.com.ni .google.nl .google.no .google.com.np .google.nr .google.nu .google.co.nz .google.com.om .google.com.pa .google.com.pe .google.com.ph .google.com.pk .google.pl .google.pn .google.com.pr .google.pt .google.com.py .google.com.qa .google.ro .google.ru .google.rw .google.com.sa .google.com.sb .google.sc .google.se .google.com.sg .google.sh .google.si .google.sk .google.sn .google.sm .google.st .google.com.sv .google.co.th .google.com.tj .google.tk .google.tl .google.tm .google.to .google.com.tr .google.tt .google.com.tw .google.co.tz .google.com.ua .google.co.ug .google.co.uk .google.com.uy .google.co.uz .google.com.vc .google.co.ve .google.vg .google.co.vi .google.com.vn .google.vu .google.ws .google.rs .google.co.za .google.co.zm .google.co.zw .google.cat > > > Any ideas how to do this elegantly? **Some Clarifications:** * I need this for a greasemonkey script I wrote that currently only works for google.com (and should work for all other TLDs as well). [Here](http://userscripts.org/scripts/show/6415) is the script (it modifies Google Reader to work on wide screens better). * It should work on URLs that belong to the above domains (not blogger.com, etc.).
Here is an updated version of Prestaul's answer which solves the two problems I mentioned in the comment there. ``` var GOOGLE_DOMAINS = ([ '.google.com', '.google.ad', '.google.ae', '.google.com.af', '.google.com.ag', '.google.com.ai', '.google.am', '.google.it.ao', '.google.com.ar', '.google.as', '.google.at', '.google.com.au', '.google.az', '.google.ba', '.google.com.bd' ]).join('\n'); function isGoogleUrl(url) { // get the 2nd level domain from the url var domain = /^https?:\/\/[^\///]*(google\.[^\/\\]+)\//i.exec(url); if(!domain) return false; domain = '.'+domain[1]; // create a regex to check to see if the domain is supported var re = new RegExp('^' + domain.replace(/\./g, '\\.') + '$', 'mi'); return re.test(GOOGLE_DOMAINS); } alert(isGoogleUrl('http://www.google.ba/the/page.html')); // true alert(isGoogleUrl('http://some_mal_site.com/http://www.google.ba/')); // false alert(isGoogleUrl('https://google.com.au/')); // true alert(isGoogleUrl('http://www.google.com.some_mal_site.com/')); // false alert(isGoogleUrl('http://yahoo.com/')); // false ```
259,753
<p>I can't get the inner div (with Hello World) to fit inside the "box" div in this code example (also at <a href="http://www.toad-software.com/test.html" rel="nofollow noreferrer">http://www.toad-software.com/test.html</a>).</p> <p>Despite the body being set to 100%, the inner div will not be contained! This is a test case for a larger project in which a variable-width table exceeds the boundaries of its container. The table would be in the inner div and the container would the "box."</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; /*html { width: 100%; height: 100%; position: relative; background: #c0c0c0; } body { position: absolute; width: 100%; height: 100%; background: #f9f9f9; }*/ body, html { margin: 0; padding: 0; } body { width: 100%; } div.box { padding: 10px; background: #ff33ff; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="box"&gt; &lt;div style="width: 1500px; height: 900px; background: #f12;"&gt;Hello World&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 259761, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 4, "selected": false, "text": "<p>add <code>overflow:hidden;</code> to the container <code>&lt;div&gt;</code></p>\n" }, { "answer_id": 260792, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 4, "selected": true, "text": "<p>The 100% width on the body element is in relation to the view port, which is why you're background color is cutting when you scroll. Either set a width to your body at 1520px to encompase the contained div or add another div and do the following:</p>\n\n<pre><code>div.box { width: 100px; overflow: auto; }\n</code></pre>\n\n<p>However, as a word of warning, heading down the path of horizontal scrolling is a bad idea for a first project in css and in user experience. </p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335036/" ]
I can't get the inner div (with Hello World) to fit inside the "box" div in this code example (also at <http://www.toad-software.com/test.html>). Despite the body being set to 100%, the inner div will not be contained! This is a test case for a larger project in which a variable-width table exceeds the boundaries of its container. The table would be in the inner div and the container would the "box." ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <style type="text/css"> /*html { width: 100%; height: 100%; position: relative; background: #c0c0c0; } body { position: absolute; width: 100%; height: 100%; background: #f9f9f9; }*/ body, html { margin: 0; padding: 0; } body { width: 100%; } div.box { padding: 10px; background: #ff33ff; } </style> </head> <body> <div class="box"> <div style="width: 1500px; height: 900px; background: #f12;">Hello World</div> </div> </body> </html> ```
The 100% width on the body element is in relation to the view port, which is why you're background color is cutting when you scroll. Either set a width to your body at 1520px to encompase the contained div or add another div and do the following: ``` div.box { width: 100px; overflow: auto; } ``` However, as a word of warning, heading down the path of horizontal scrolling is a bad idea for a first project in css and in user experience.
259,759
<p>I am using JQuery to post with AJAX to another ASP page. Do I need this ASP page to return a full html page. Or can I just have it send back a value ( I just need a status ) . Here is my function.</p> <pre><code> $.ajax({ url: "X.asp", cache: false, type: "POST", data: queryString, success: function(html){ $('#x_'+Num).append(html); } }); </code></pre>
[ { "answer_id": 259790, "author": "Berzemus", "author_id": 2452, "author_profile": "https://Stackoverflow.com/users/2452", "pm_score": 5, "selected": true, "text": "<p>If it's just a simple value you need, I'd simple use Json (JQuery has a dedicated method for that : <a href=\"http://docs.jquery.com/Ajax/jQuery.getJSON\" rel=\"nofollow noreferrer\">$.getJSON()</a>).</p>\n\n<p>So no, you don't need your ASP page to return a full html page, just the value in simple JSON notation.</p>\n" }, { "answer_id": 259812, "author": "Marek Blotny", "author_id": 33744, "author_profile": "https://Stackoverflow.com/users/33744", "pm_score": 1, "selected": false, "text": "<p>You can return anything you want (even single character), but remember to change content type of your page X.asp to ContentType=\"text/plain\" if you don't want to return HTML.</p>\n" }, { "answer_id": 259960, "author": "Rene Saarsoo", "author_id": 15982, "author_profile": "https://Stackoverflow.com/users/15982", "pm_score": 1, "selected": false, "text": "<p>Well, the whole point of AJAX is IMHO that you don't need to return the whole page. The server just sends the simple answer that you need.</p>\n" }, { "answer_id": 273603, "author": "Ahmad", "author_id": 22449, "author_profile": "https://Stackoverflow.com/users/22449", "pm_score": 1, "selected": false, "text": "<p>You can return anything from the backend, I personally prefer JSON, but you have to specify the dataType property in your $.ajax options</p>\n" }, { "answer_id": 279347, "author": "Malfist", "author_id": 12243, "author_profile": "https://Stackoverflow.com/users/12243", "pm_score": 0, "selected": false, "text": "<p>Using AJAX, you can return anything, even binary data. Although it was designed for XML, you can use it for anything you can transfer across a web server. However, HTTP Requests are expensive, so don't abuse them too much!</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I am using JQuery to post with AJAX to another ASP page. Do I need this ASP page to return a full html page. Or can I just have it send back a value ( I just need a status ) . Here is my function. ``` $.ajax({ url: "X.asp", cache: false, type: "POST", data: queryString, success: function(html){ $('#x_'+Num).append(html); } }); ```
If it's just a simple value you need, I'd simple use Json (JQuery has a dedicated method for that : [$.getJSON()](http://docs.jquery.com/Ajax/jQuery.getJSON)). So no, you don't need your ASP page to return a full html page, just the value in simple JSON notation.
259,763
<p>Ok, so I'm binding a DataGridView to a BindingSource in a background thread while a little, "Please Wait" model window keeps the user entertained. No problem. </p> <p>However, I need to change some of the rows background colors based on the row's databounditem type. Like this:</p> <pre><code>for (int i = 0; i &lt; dgItemMaster.Rows.Count; i++) { if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "Package") { dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.PowderBlue; } } </code></pre> <p>Programatically I can do this but it is enough rows that it will lock up the GUI while it is iterating the rows. I'm looking for ideas on the best way to deal with the situation.</p> <p>This is what I'm doing now:</p> <pre><code>void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { dgItemMaster.DataSource = products; dgItemMaster.BeginInvoke((Action)(() =&gt; { for (int i = 0; i &lt; dgItemMaster.Rows.Count; i++) { if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "Package") { dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.PowderBlue; } else if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "PackageKit") { dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.Pink; } } })); } </code></pre>
[ { "answer_id": 259790, "author": "Berzemus", "author_id": 2452, "author_profile": "https://Stackoverflow.com/users/2452", "pm_score": 5, "selected": true, "text": "<p>If it's just a simple value you need, I'd simple use Json (JQuery has a dedicated method for that : <a href=\"http://docs.jquery.com/Ajax/jQuery.getJSON\" rel=\"nofollow noreferrer\">$.getJSON()</a>).</p>\n\n<p>So no, you don't need your ASP page to return a full html page, just the value in simple JSON notation.</p>\n" }, { "answer_id": 259812, "author": "Marek Blotny", "author_id": 33744, "author_profile": "https://Stackoverflow.com/users/33744", "pm_score": 1, "selected": false, "text": "<p>You can return anything you want (even single character), but remember to change content type of your page X.asp to ContentType=\"text/plain\" if you don't want to return HTML.</p>\n" }, { "answer_id": 259960, "author": "Rene Saarsoo", "author_id": 15982, "author_profile": "https://Stackoverflow.com/users/15982", "pm_score": 1, "selected": false, "text": "<p>Well, the whole point of AJAX is IMHO that you don't need to return the whole page. The server just sends the simple answer that you need.</p>\n" }, { "answer_id": 273603, "author": "Ahmad", "author_id": 22449, "author_profile": "https://Stackoverflow.com/users/22449", "pm_score": 1, "selected": false, "text": "<p>You can return anything from the backend, I personally prefer JSON, but you have to specify the dataType property in your $.ajax options</p>\n" }, { "answer_id": 279347, "author": "Malfist", "author_id": 12243, "author_profile": "https://Stackoverflow.com/users/12243", "pm_score": 0, "selected": false, "text": "<p>Using AJAX, you can return anything, even binary data. Although it was designed for XML, you can use it for anything you can transfer across a web server. However, HTTP Requests are expensive, so don't abuse them too much!</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
Ok, so I'm binding a DataGridView to a BindingSource in a background thread while a little, "Please Wait" model window keeps the user entertained. No problem. However, I need to change some of the rows background colors based on the row's databounditem type. Like this: ``` for (int i = 0; i < dgItemMaster.Rows.Count; i++) { if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "Package") { dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.PowderBlue; } } ``` Programatically I can do this but it is enough rows that it will lock up the GUI while it is iterating the rows. I'm looking for ideas on the best way to deal with the situation. This is what I'm doing now: ``` void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { dgItemMaster.DataSource = products; dgItemMaster.BeginInvoke((Action)(() => { for (int i = 0; i < dgItemMaster.Rows.Count; i++) { if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "Package") { dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.PowderBlue; } else if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "PackageKit") { dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.Pink; } } })); } ```
If it's just a simple value you need, I'd simple use Json (JQuery has a dedicated method for that : [$.getJSON()](http://docs.jquery.com/Ajax/jQuery.getJSON)). So no, you don't need your ASP page to return a full html page, just the value in simple JSON notation.
259,784
<p>Compiling a program on Linux that calls POSIX timer functions (eg: timer_create, timer_settime) returns errors such as:</p> <pre> In function `foo': timer.c:(.text+0xbb): undefined reference to `timer_create' timer.c:(.text+0x187): undefined reference to `timer_settime' collect2: ld returned 1 exit status </pre> <p>Which library do I need to link?</p>
[ { "answer_id": 259789, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This should be documented in the man page. Given it isn't add <code>-lrt</code>.</p>\n" }, { "answer_id": 552654, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Compile it with <code>-lrt</code> option. It will get compiled.</p>\n" }, { "answer_id": 673047, "author": "dragonfly", "author_id": 81259, "author_profile": "https://Stackoverflow.com/users/81259", "pm_score": 2, "selected": false, "text": "<p>please try the following:</p>\n\n<pre><code>gcc -lrt\n</code></pre>\n" }, { "answer_id": 13542061, "author": "steve-o", "author_id": 1459666, "author_profile": "https://Stackoverflow.com/users/1459666", "pm_score": 2, "selected": false, "text": "<p>The -lrt forces the link but you have to have the real-time library in place before you can link to it. Most of the time it's included automatically, but if not you'll need to install a real-time library using apt-get. Then you will be able to link to it at the following (or similar) location: </p>\n\n<p><code>/lib/i386-linux-gnu/librt.so.1</code></p>\n\n<p>If you're using codeblocks and for some reason -lrt doesn't include it, you can add the above library path &amp; filename using the following menu sequence:</p>\n\n<p><code>Project-&gt;Build Options-&gt;Linker Settings-&gt;Link Libraries-&gt;Add</code> </p>\n" }, { "answer_id": 37349343, "author": "bedio", "author_id": 6361634, "author_profile": "https://Stackoverflow.com/users/6361634", "pm_score": 3, "selected": false, "text": "<p>you can try <code>gcc -o mytemer mytimer.c -lrt</code>\nit works for me like that but not in this order\n<code>gcc -lrt mytimer.c -o mytimer</code></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Compiling a program on Linux that calls POSIX timer functions (eg: timer\_create, timer\_settime) returns errors such as: ``` In function `foo': timer.c:(.text+0xbb): undefined reference to `timer_create' timer.c:(.text+0x187): undefined reference to `timer_settime' collect2: ld returned 1 exit status ``` Which library do I need to link?
Compile it with `-lrt` option. It will get compiled.
259,798
<p>I've got a (SQL Server 2005) database where I'd like to create views on-the-fly. In my code, I'm building a CREATE VIEW statement, but the only way I can get it to work is by building the entire query string and running it bare. I'd like to use parameters, but this:</p> <pre><code>SqlCommand cmd = new SqlCommand("CREATE VIEW @name AS SELECT @body"); cmd.Parameters.AddWithValue("@name", "foo"); cmd.Parameters.AddWithValue("@body", "* from bar"); </code></pre> <p>tells me there's an error "near the keyword VIEW" (presumably the "@name") -- needless to say <code>"CREATE VIEW foo AS SELECT * FROM bar"</code> works like a champ.</p> <p>Is this just not possible? If not, is there a better way to clean up the input before running the CREATE statement? In some cases, the query body could have user input and I'd just feel safer if there was some way that I could say "treat this as the body of a single select statement". Maybe what I'm asking for is just too weird?</p> <p><hr/> FOLLOWUP 04 Nov: OK, yes, what I want is sort of like SQL injection when you get down to it, but I would like to at least minimize (if not totally remove) the option of running this command and dropping a table or something. Granted, the user this is running as doesn't have permissions to drop any tables in the first place, but I think you get the idea. I'd love to have a way of saying, in effect, <code>"This statement will not alter any existing data in any way{ ... }"</code>.</p> <p>The way it's coded right now is to do string concatenation like in <strong>friol</strong>'s answer, but that does no sanitization at all. I'd feel better if I could at least scrub it for suspect characters, like ; or -- or what have you. I was hoping there might be a library function to do the scrub for me, or something along those lines.</p>
[ { "answer_id": 259808, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 2, "selected": true, "text": "<p>Maybe I've not understood it correctly, but what prevents you to do:</p>\n\n<pre><code>viewname=\"foo\";\nviewwhere=\"* from bar\";\n\nSqlCommand cmd = new SqlCommand(\"CREATE VIEW \"+viewname+\" AS SELECT \"+viewwhere);\n</code></pre>\n" }, { "answer_id": 259872, "author": "Soraz", "author_id": 24610, "author_profile": "https://Stackoverflow.com/users/24610", "pm_score": 2, "selected": false, "text": "<p>Parameters are not simply string substitutions. That is why your code won't work.</p>\n\n<p>Its like you cant do</p>\n\n<p>sql = \"select * from orders where orders_id in (?)\"</p>\n\n<p>and pass \"1,2,3,5\" as parameter.</p>\n\n<p>Parameters are type checked and can only contain scalar values IIRC.</p>\n" }, { "answer_id": 259885, "author": "Bart", "author_id": 16980, "author_profile": "https://Stackoverflow.com/users/16980", "pm_score": 0, "selected": false, "text": "<p>It looks to me like you are trying to create a dynamic query using parameters, which is not how a parameterized query is intended to work. They do not simply get concatenated into the string. </p>\n\n<p>If what you are trying to prevent is SQL injection, what I would do is validate that the view name only contains alphanumerics and no T-SQL keywords. I would alos be very careful about dymanically creating the body.</p>\n" }, { "answer_id": 259892, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>SQL injection. You want it, that's the point. You should be concatenating this stuff.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
I've got a (SQL Server 2005) database where I'd like to create views on-the-fly. In my code, I'm building a CREATE VIEW statement, but the only way I can get it to work is by building the entire query string and running it bare. I'd like to use parameters, but this: ``` SqlCommand cmd = new SqlCommand("CREATE VIEW @name AS SELECT @body"); cmd.Parameters.AddWithValue("@name", "foo"); cmd.Parameters.AddWithValue("@body", "* from bar"); ``` tells me there's an error "near the keyword VIEW" (presumably the "@name") -- needless to say `"CREATE VIEW foo AS SELECT * FROM bar"` works like a champ. Is this just not possible? If not, is there a better way to clean up the input before running the CREATE statement? In some cases, the query body could have user input and I'd just feel safer if there was some way that I could say "treat this as the body of a single select statement". Maybe what I'm asking for is just too weird? --- FOLLOWUP 04 Nov: OK, yes, what I want is sort of like SQL injection when you get down to it, but I would like to at least minimize (if not totally remove) the option of running this command and dropping a table or something. Granted, the user this is running as doesn't have permissions to drop any tables in the first place, but I think you get the idea. I'd love to have a way of saying, in effect, `"This statement will not alter any existing data in any way{ ... }"`. The way it's coded right now is to do string concatenation like in **friol**'s answer, but that does no sanitization at all. I'd feel better if I could at least scrub it for suspect characters, like ; or -- or what have you. I was hoping there might be a library function to do the scrub for me, or something along those lines.
Maybe I've not understood it correctly, but what prevents you to do: ``` viewname="foo"; viewwhere="* from bar"; SqlCommand cmd = new SqlCommand("CREATE VIEW "+viewname+" AS SELECT "+viewwhere); ```
259,803
<p>Let's say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):</p> <pre><code>CREATE PROCEDURE incrementCounter AS DECLARE @current int SET @current = (select CounterColumn from MyTable) + 1 UPDATE MyTable SET CounterColumn = current GO </code></pre> <p>We're assuming I have a table called 'myTable' that contains one row, with the 'CounterColumn' containing our current count.</p> <p>Can this stored procedure be executed multiple times, at the same time? </p> <p>i.e. is this possible:</p> <p>I call 'incrementCounter' twice. Call A gets to the point where it sets the 'current' variable (let's say it is 5). Call B gets to the point where it sets the 'current' variable (which would also be 5). Call A finishes executing, then Call B finishes. In the end, the table should contain the value of 6, but instead contains 5 due to the overlap of execution</p>
[ { "answer_id": 259827, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 5, "selected": true, "text": "<p>This is for SQL Server.</p>\n\n<p>Each statement is atomic, but if you want the stored procedure to be atomic (or any sequence of statements in general), you need to explicitly surround the statements with </p>\n\n<p>BEGIN TRANSACTION<br>\nStatement ...<br>\nStatement ...<br>\nCOMMIT TRANSACTION</p>\n\n<p>(It's common to use BEGIN TRAN and END TRAN for short.)</p>\n\n<p>Of course there are lots of ways to get into lock trouble depending what else is going on at the same time, so you may need a strategy for dealing with failed transactions. (A complete discussion of all the circumstances that might result in locks, no matter how you contrive this particular SP, is beyond the scope of the question.) But they will still be resubmittable because of the atomicity. And in my experience you'll probably be fine, without knowing about your transaction volumes and the other activities on the database. Excuse me for stating the obvious.</p>\n\n<p>Contrary to a popular misconception, this will work in your case with default transaction level settings.</p>\n" }, { "answer_id": 259931, "author": "Dave Cluderay", "author_id": 30933, "author_profile": "https://Stackoverflow.com/users/30933", "pm_score": 4, "selected": false, "text": "<p>In addition to placing the code between a <code>BEGIN TRANSACTION</code> and <code>END TRANSACTION</code>, you'd need to ensure that your transaction isolation level is set correctly.</p>\n\n<p>For example, <code>SERIALIZABLE</code> isolation level will prevent lost updates when the code runs concurrently, but <code>READ COMMITTED</code> (the default in SQL Server Management Studio) will not.</p>\n\n<pre><code>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE\n</code></pre>\n\n<p>As others have already mentioned, whilst ensuring consistency, this can cause blocking and deadlocks and so may not be the best solution in practice.</p>\n" }, { "answer_id": 2090940, "author": "SqlRyan", "author_id": 8114, "author_profile": "https://Stackoverflow.com/users/8114", "pm_score": 0, "selected": false, "text": "<p>Maybe I'm reading too much into your example (and your real situation may be significantly more complicated), but why wouldn't you just do this in a single statement?</p>\n\n<pre><code>CREATE PROCEDURE incrementCounter AS\n\nUPDATE\n MyTable\nSET\n CounterColumn = CounterColumn + 1\n\nGO\n</code></pre>\n\n<p>That way, it's automatically atomic and if two updates are executued at the same time, they'll always be ordered by SQL Server so as to avoid the conflict you describe. If, however, your real situation is much more complicated, then wrapping it in a transaction is the best way to do this.</p>\n\n<p>However, if another process has enabled a \"less safe\" isolation level (like one that allows dirty reads or non-repeatable reads), then I don't think a transaction will protect against this, as another process can see into the partially updated data if it's elected to allow unsafe reads.</p>\n" }, { "answer_id": 18809072, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 1, "selected": false, "text": "<p>I use this method</p>\n\n<pre><code>CREATE PROCEDURE incrementCounter\nAS\n\nDECLARE @current int\n\nUPDATE MyTable\nSET\n @current = CounterColumn = CounterColumn + 1\n\nReturn @current\n</code></pre>\n\n<p>this procedure do all two command at one time and it is isolate from other transaction.</p>\n" }, { "answer_id": 28392693, "author": "sqlfool", "author_id": 4542710, "author_profile": "https://Stackoverflow.com/users/4542710", "pm_score": 0, "selected": false, "text": "<p>Short answer to your question is YES it can and will come up short. If you want to block concurrent execution of stored procedures start a transaction and update the same data in every execution of the stored procedure before continuing to do any work within the procedure.</p>\n\n<pre><code>CREATE PROCEDURE ..\nBEGIN TRANSACTION\nUPDATE mylock SET ref = ref + 1\n...\n</code></pre>\n\n<p>This will force other concurrent executions to wait their turn since they will not be able to change 'ref' value until the other transaction(s) complete and associated update lock is lifted.</p>\n\n<p>In general it is a good idea to assume result of any and all SELECT queries are stale <strong>before</strong> they are ever even executed. Using \"heavy\" isolation levels to workaround this unfortunate reality severely limits scalability. Much better to structure changes in a way which make optimistic assumptions about state of system you expect to exist during the update so when your assumption fail you can try again later and hope for a better outcome. For example:</p>\n\n<pre><code>UPDATE\n MyTable\nSET\n CounterColumn = current \nWHERE CounterColumn = current - 1\n</code></pre>\n\n<p>Using your example with added WHERE clause this update does not affect any rows if assumption about its current state fails. Check @@ROWCOUNT to test number of rows and rollback or some other action as appropriate while it differs from expected outcome.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30006/" ]
Let's say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure): ``` CREATE PROCEDURE incrementCounter AS DECLARE @current int SET @current = (select CounterColumn from MyTable) + 1 UPDATE MyTable SET CounterColumn = current GO ``` We're assuming I have a table called 'myTable' that contains one row, with the 'CounterColumn' containing our current count. Can this stored procedure be executed multiple times, at the same time? i.e. is this possible: I call 'incrementCounter' twice. Call A gets to the point where it sets the 'current' variable (let's say it is 5). Call B gets to the point where it sets the 'current' variable (which would also be 5). Call A finishes executing, then Call B finishes. In the end, the table should contain the value of 6, but instead contains 5 due to the overlap of execution
This is for SQL Server. Each statement is atomic, but if you want the stored procedure to be atomic (or any sequence of statements in general), you need to explicitly surround the statements with BEGIN TRANSACTION Statement ... Statement ... COMMIT TRANSACTION (It's common to use BEGIN TRAN and END TRAN for short.) Of course there are lots of ways to get into lock trouble depending what else is going on at the same time, so you may need a strategy for dealing with failed transactions. (A complete discussion of all the circumstances that might result in locks, no matter how you contrive this particular SP, is beyond the scope of the question.) But they will still be resubmittable because of the atomicity. And in my experience you'll probably be fine, without knowing about your transaction volumes and the other activities on the database. Excuse me for stating the obvious. Contrary to a popular misconception, this will work in your case with default transaction level settings.
259,819
<p>I want to create a view that consists solely of a <code>UITextView</code>. When the view is first shown, by default, I'd like the keyboard to be visible and ready for text entry. This way, the user does not have to touch the <code>UITextView</code> first in order to begin editing.</p> <p>Is this possible? I see the class has a notification called <code>UITextViewTextDidBeginEditingNotification</code> but I'm not sure how to send that, or if that is even the right approach. </p>
[ { "answer_id": 259842, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 7, "selected": true, "text": "<p>to accomplish that just send the becomeFirstResponder message to your UITextField, as follows (assuming you have an outlet called textField, pointing to the field in question):</p>\n\n<pre><code>- (void)viewWillAppear:(BOOL)animated {\n [super viewWillAppear:animated];\n [textField becomeFirstResponder];\n}\n</code></pre>\n" }, { "answer_id": 37086832, "author": "Suragch", "author_id": 3681880, "author_profile": "https://Stackoverflow.com/users/3681880", "pm_score": 4, "selected": false, "text": "<h1>In Swift</h1>\n<p>To automatically show the keyboard, to the following:</p>\n<pre><code>override func viewDidLoad() {\n super.viewDidLoad()\n \n // show keyboard\n textView.becomeFirstResponder()\n}\n</code></pre>\n<p><strong>Notes</strong></p>\n<ul>\n<li>This assumes that the text view is editable.</li>\n<li>Works for both <code>UITextView</code> and <code>UITextField</code></li>\n<li>To hide the keyboard use <code>textView.resignFirstResponder()</code></li>\n</ul>\n" }, { "answer_id": 39336732, "author": "Usman", "author_id": 184759, "author_profile": "https://Stackoverflow.com/users/184759", "pm_score": 3, "selected": false, "text": "<p>Following worked fine for me using Swift</p>\n\n<pre><code>override func viewDidAppear(animated: Bool) {\n super.viewDidAppear(animated)\n\n // Show keyboard by default\n billField.becomeFirstResponder()\n}\n</code></pre>\n\n<p>Key is to use the viewDidAppear function. </p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
I want to create a view that consists solely of a `UITextView`. When the view is first shown, by default, I'd like the keyboard to be visible and ready for text entry. This way, the user does not have to touch the `UITextView` first in order to begin editing. Is this possible? I see the class has a notification called `UITextViewTextDidBeginEditingNotification` but I'm not sure how to send that, or if that is even the right approach.
to accomplish that just send the becomeFirstResponder message to your UITextField, as follows (assuming you have an outlet called textField, pointing to the field in question): ``` - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [textField becomeFirstResponder]; } ```
259,836
<p>What is the best way to convert an array of bytes declared as TBytes to a unicode string in Delphi 2009? In my particular case, the TBytes array has UTF-16 encoded data already (2 bytes for each char).</p> <p>Since TBytes doesn't store a null terminator, the following will only work if the array happens to have #0 in the memory adjacent to it. </p> <pre><code>MyString := string( myBytes ); </code></pre> <p>If not, the string result will have random data at the end (it could also probably cause a read violation depending on how long it took to encounter a #0 in memory).</p> <p>If I use the ToBytes function, it returns 't'#0'e'#0's'#0't'#0, which is not what I want.</p>
[ { "answer_id": 259904, "author": "Bruce McGee", "author_id": 19183, "author_profile": "https://Stackoverflow.com/users/19183", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://docwiki.embarcadero.com/Libraries/Rio/en/System.SysUtils.StringOf\" rel=\"nofollow noreferrer\">StringOf</a> converts TBytes to a UnicodeString. <a href=\"http://docwiki.embarcadero.com/Libraries/Rio/en/System.SysUtils.BytesOf\" rel=\"nofollow noreferrer\">BytesOf</a> converts a UnicodeString to TBytes.</p>\n" }, { "answer_id": 259962, "author": "Bruce McGee", "author_id": 19183, "author_profile": "https://Stackoverflow.com/users/19183", "pm_score": 2, "selected": false, "text": "<p>If your TBytes contains UTF-16 characters, look at WideStringOf and WideBytesOf.</p>\n" }, { "answer_id": 259973, "author": "Jeremy Mullin", "author_id": 7893, "author_profile": "https://Stackoverflow.com/users/7893", "pm_score": 5, "selected": true, "text": "<p>I ended up using </p>\n\n<pre><code>TEncoding.Unicode.GetString( MyByteArray );\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7893/" ]
What is the best way to convert an array of bytes declared as TBytes to a unicode string in Delphi 2009? In my particular case, the TBytes array has UTF-16 encoded data already (2 bytes for each char). Since TBytes doesn't store a null terminator, the following will only work if the array happens to have #0 in the memory adjacent to it. ``` MyString := string( myBytes ); ``` If not, the string result will have random data at the end (it could also probably cause a read violation depending on how long it took to encounter a #0 in memory). If I use the ToBytes function, it returns 't'#0'e'#0's'#0't'#0, which is not what I want.
I ended up using ``` TEncoding.Unicode.GetString( MyByteArray ); ```
259,841
<p>The company I work for writes a lot smallish Perl and Bash scripts to massage data into something usable for our software. These scripts, like any code, can change. I provided them CVS because of the file versioning rather than repository versioning. Anyway, I am thinking out a deploy tool to get the scripts from development to production. The production server will have it's own simple versioning system in that if one of the scripts' md5 sum does not match the one in a database it will not run the script and email the appropriate parties. </p> <p>I want to force the programmers to deploy the most current CVS version of the script. If it is not the most current it should die with a message telling them they have to check in their version first. I realize there might be cases where you need to deploy an old file. Those would be exceptions and could be handled as such.</p> <p>What's the best to do this? Is it just as simple as doing a 'cvs diff' ? </p>
[ { "answer_id": 259899, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 2, "selected": true, "text": "<p>if you going to write some kind of distribution script it should be relatively simple </p>\n\n<p>1) The script should be committed in your cvs repository </p>\n\n<p>2) I advice to call the script from your makefile (or any build system you use)\n something like this </p>\n\n<pre><code>make dist\n</code></pre>\n\n<p>and the dist rule will call your script.<br>\n3) script will perform </p>\n\n<pre><code> cvs up -An \n</code></pre>\n\n<p>and analyze the output to look for M or C or A or R status\n by redirecting the output to grep for example. </p>\n\n<pre><code>grep -c ^[MCAR] \n</code></pre>\n\n<p>if count > 0 you got a problem. </p>\n\n<p>4) if one of above found fail the build script </p>\n\n<p>5) if not create the tar or any other form of distribution you are using</p>\n\n<p>To deploy older version you can make an -A as a parameter by default set to -A and overridden for example by shell variable to be for example -r tag-3.14.4 . </p>\n" }, { "answer_id": 259948, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 0, "selected": false, "text": "<p>I worked on an internal tool that did deployments.\nIt was designed for the enterprise (and to meet SOX regulations), and so it relied on approvals to deploy code.</p>\n\n<p>Because of this, we deployed the version of code the developer specified in the request, not the latest version. The reason is that a developer may need to make changes, place into test, meanwhile other changes take place. These newer changes have not gone through the test (QA) phases, but the developers original version has, so we would deploy that version.</p>\n\n<p>All that to say, I would design it in such a way that a version number could be specified, and if no version number then push the latest.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28714/" ]
The company I work for writes a lot smallish Perl and Bash scripts to massage data into something usable for our software. These scripts, like any code, can change. I provided them CVS because of the file versioning rather than repository versioning. Anyway, I am thinking out a deploy tool to get the scripts from development to production. The production server will have it's own simple versioning system in that if one of the scripts' md5 sum does not match the one in a database it will not run the script and email the appropriate parties. I want to force the programmers to deploy the most current CVS version of the script. If it is not the most current it should die with a message telling them they have to check in their version first. I realize there might be cases where you need to deploy an old file. Those would be exceptions and could be handled as such. What's the best to do this? Is it just as simple as doing a 'cvs diff' ?
if you going to write some kind of distribution script it should be relatively simple 1) The script should be committed in your cvs repository 2) I advice to call the script from your makefile (or any build system you use) something like this ``` make dist ``` and the dist rule will call your script. 3) script will perform ``` cvs up -An ``` and analyze the output to look for M or C or A or R status by redirecting the output to grep for example. ``` grep -c ^[MCAR] ``` if count > 0 you got a problem. 4) if one of above found fail the build script 5) if not create the tar or any other form of distribution you are using To deploy older version you can make an -A as a parameter by default set to -A and overridden for example by shell variable to be for example -r tag-3.14.4 .
259,850
<p>I am performing two validations on the client side on the samve event. I have defined my validations as shown below</p> <pre><code>btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();" </code></pre> <p>Pseudo code for </p> <pre><code>prepareSave(): { if (bPendingchanges) { return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first') } else {return true} } </code></pre> <p>Pseudo code for </p> <pre><code>prepareSearch(): { if (bNoSearchText) { alert('Please specify search criteria before proceeding') return false; } else {return true;} } </code></pre> <p>When <code>bPendingchanges=false</code>, I never get the second validation running. Anyone who can quickly spot what I have overlooked here? Please?</p>
[ { "answer_id": 259869, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": true, "text": "<p>Your second <code>return</code> statement will never be reached. Execution stops after <code>javascript:return prepareSave()</code>.</p>\n\n<p>Looks like you want to return true if both functions return true - therefore, do:</p>\n\n<pre><code>btnSearch.Attributes[\"OnClick\"] = javascript: return prepareSave() &amp;&amp; prepareSearch();\n</code></pre>\n" }, { "answer_id": 259871, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>That's because the return prevents the second validation from running. Try this</p>\n\n<pre><code>btnSearch.Attributes[\"OnClick\"] = \"javascript:return prepareSave() &amp;&amp; prepareSearch();\"\n</code></pre>\n" }, { "answer_id": 259875, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p><code>\"javascript:return prepareSave(); return prepareSearch();\"</code></p>\n\n<p>1) You shouldn't have the \"javascript:\"<br>\n2) <code>return prepareSearch();</code> will never be executed, because <code>\"return prepareSave();</code> exits your event handler</p>\n\n<p>Try <code>\"return (prepareSave() &amp;&amp; prepareSearch());\"</code></p>\n" }, { "answer_id": 259878, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 2, "selected": false, "text": "<p><code>return</code>, as the name implies, returns control back to whatever called the code in question. Therefore, anything that's after a return statement</p>\n\n<pre><code>return prepareSave(); return prepareSearch();\n// ^^^^^^^^^^^^^^^^^^^^^^^ e.g. this part\n</code></pre>\n\n<p>never executes. Try <code>return (prepareSave() &amp;&amp; prepareSearch());</code></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
I am performing two validations on the client side on the samve event. I have defined my validations as shown below ``` btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();" ``` Pseudo code for ``` prepareSave(): { if (bPendingchanges) { return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first') } else {return true} } ``` Pseudo code for ``` prepareSearch(): { if (bNoSearchText) { alert('Please specify search criteria before proceeding') return false; } else {return true;} } ``` When `bPendingchanges=false`, I never get the second validation running. Anyone who can quickly spot what I have overlooked here? Please?
Your second `return` statement will never be reached. Execution stops after `javascript:return prepareSave()`. Looks like you want to return true if both functions return true - therefore, do: ``` btnSearch.Attributes["OnClick"] = javascript: return prepareSave() && prepareSearch(); ```
259,853
<p>As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared:</p> <pre><code>class Base { virtual Base* clone() const = 0; }; class Derived : public Base { virtual Derived* clone() const }; </code></pre> <p>The compiler detects that clone() returns an pointer to the type of the object, and allows Derived to override it to return a pointer to derived.</p> <p>It would desirable to have clone() return a smart pointer that implies transfer of ownership semantics, like the following:</p> <pre><code>class Base { virtual std::auto_ptr&lt;Base&gt; clone() const = 0; }; class Derived : public Base { virtual std::auto_ptr&lt;Derived&gt; clone() const; }; </code></pre> <p>Unfortunately, the relaxation of the conventions does not apply to templated smart pointers, and the compiler will not allow the override.</p> <p>So, it seems I am left with two options:</p> <ol> <li>Have clone() return a "dumb" pointer, and document that clients are responsible for disposing of it.</li> <li>Have clone() return a smart base pointer, and have clients use dynamic_cast to save them to a Derived pointer if they need it.</li> </ol> <p>Is one of these approaches preferred? Or is there a way for me to eat my transfer of ownership semantics and have my strong type safety too?</p>
[ { "answer_id": 259946, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": true, "text": "<p>It depends on your use case. If you ever think you will need to call <code>clone</code> on a derived object whose dynamic type you know (remember, the whole point of <code>clone</code> is to allow copying <em>without</em> knowing the dynamic type), then you should probably return a dumb pointer and load that into a smart pointer in the calling code. If not, then you only need to return a smart_ptr and so you can feel free to return it in all overrides.</p>\n" }, { "answer_id": 260009, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>You could have two methods, a virtual clone() that returns a smart pointer wrapper around the base type, and a non-virtual clone2() that returns the correct type of smart pointer. </p>\n\n<p>clone2 would obviously be implemented in terms of clone and encapsulate the cast.</p>\n\n<p>That way can get the most derived smart pointer that you know at compile time. It may not be the most derived type overall, but it uses all the information available to the compiler.</p>\n\n<p>Another option would be to create a template version of clone that accepts the type you are expecting, but that adds more burden on the caller.</p>\n" }, { "answer_id": 260028, "author": "Gorpik", "author_id": 25824, "author_profile": "https://Stackoverflow.com/users/25824", "pm_score": 3, "selected": false, "text": "<p>I think the function semantics are so clear in this case that there is little space for confusion. So I think you can use the covariant version (the one returning a dumb pointer to the real type) with an easy conscience, and your callers will know that they are getting a new object whose property is transferred to them.</p>\n" }, { "answer_id": 260054, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 4, "selected": false, "text": "<p>The syntax isn't quite as nice, but if you add this to your code above, doesn't it solve all your problems?</p>\n\n<pre><code>template &lt;typename T&gt;\nstd::auto_ptr&lt;T&gt; clone(T const* t)\n{\n return t-&gt;clone();\n}\n</code></pre>\n" }, { "answer_id": 260063, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 1, "selected": false, "text": "<p>That's one reason to use <code>boost::intrusive_ptr</code> instead of <code>shared_ptr</code> or <code>auto/unique_ptr</code>. The raw pointer contains the reference count and can be used more seamlessly in situations like this. </p>\n" }, { "answer_id": 260231, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 2, "selected": false, "text": "<p><code>Tr1::shared_ptr&lt;&gt;</code> can be casted like it were a raw pointer.</p>\n\n<p>I think have clone() return a <code>shared_ptr&lt;Base&gt;</code> pointer is a pretty clean solution. You can cast the pointer to <code>shared_ptr&lt;Derived&gt;</code> by means of <strong><code>tr1::static_pointer_cast&lt;Derived&gt;</code></strong> or <strong><code>tr1::dynamic_pointer_cast&lt;Derived&gt;</code></strong> in case it is not possible to determine the kind of cloned object at compile time.</p>\n\n<p>To ensure the kind of object is predictible you can use a polymorphic cast for shared_ptr like this one:</p>\n\n<pre><code>template &lt;typename R, typename T&gt;\ninline std::tr1::shared_ptr&lt;R&gt; polymorphic_pointer_downcast(T &amp;p)\n{\n assert( std::tr1::dynamic_pointer_cast&lt;R&gt;(p) );\n return std::tr1::static_pointer_cast&lt;R&gt;(p);\n}\n</code></pre>\n\n<p>The overhead added by the assert will be thrown away in the release version.</p>\n" }, { "answer_id": 261278, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 5, "selected": false, "text": "<p>Use the Public non-virtual / Private virtual pattern :</p>\n\n<pre><code>class Base {\n public:\n std::auto_ptr&lt;Base&gt; clone () { return doClone(); }\n private:\n virtual Base* doClone() { return new (*this); }\n};\nclass Derived : public Base {\n public:\n std::auto_ptr&lt;Derived&gt; clone () { return doClone(); }\n private:\n virtual Derived* doClone() { return new (*this); }\n};\n</code></pre>\n" }, { "answer_id": 38709290, "author": "Daniel", "author_id": 2970186, "author_profile": "https://Stackoverflow.com/users/2970186", "pm_score": 1, "selected": false, "text": "<p>Updating <a href=\"https://stackoverflow.com/a/261278\">MSalters answer</a> for C++14:</p>\n\n<pre><code>#include &lt;memory&gt;\n\nclass Base\n{\npublic:\n std::unique_ptr&lt;Base&gt; clone() const\n {\n return do_clone();\n }\nprivate:\n virtual std::unique_ptr&lt;Base&gt; do_clone() const\n {\n return std::make_unique&lt;Base&gt;(*this);\n }\n};\n\nclass Derived : public Base\n{\nprivate:\n virtual std::unique_ptr&lt;Base&gt; do_clone() const override\n {\n return std::make_unique&lt;Derived&gt;(*this);\n }\n}\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1674/" ]
As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared: ``` class Base { virtual Base* clone() const = 0; }; class Derived : public Base { virtual Derived* clone() const }; ``` The compiler detects that clone() returns an pointer to the type of the object, and allows Derived to override it to return a pointer to derived. It would desirable to have clone() return a smart pointer that implies transfer of ownership semantics, like the following: ``` class Base { virtual std::auto_ptr<Base> clone() const = 0; }; class Derived : public Base { virtual std::auto_ptr<Derived> clone() const; }; ``` Unfortunately, the relaxation of the conventions does not apply to templated smart pointers, and the compiler will not allow the override. So, it seems I am left with two options: 1. Have clone() return a "dumb" pointer, and document that clients are responsible for disposing of it. 2. Have clone() return a smart base pointer, and have clients use dynamic\_cast to save them to a Derived pointer if they need it. Is one of these approaches preferred? Or is there a way for me to eat my transfer of ownership semantics and have my strong type safety too?
It depends on your use case. If you ever think you will need to call `clone` on a derived object whose dynamic type you know (remember, the whole point of `clone` is to allow copying *without* knowing the dynamic type), then you should probably return a dumb pointer and load that into a smart pointer in the calling code. If not, then you only need to return a smart\_ptr and so you can feel free to return it in all overrides.
259,883
<p>I'd like to strip out occurrences of a specific tag, leaving the inner XML intact. I'd like to do this with one pass (rather than searching, replacing, and starting from scratch again). For instance, from the source:</p> <pre><code>&lt;element&gt; &lt;RemovalTarget Attribute="Something"&gt; Content Here &lt;/RemovalTarget&gt; &lt;/element&gt; &lt;element&gt; More Here &lt;/element&gt; </code></pre> <p>I'd like the result to be:</p> <pre><code>&lt;element&gt; Content Here &lt;/element&gt; &lt;element&gt; More Here &lt;/element&gt; </code></pre> <p>I've tried something like this (forgive me, I'm new to Linq):</p> <pre><code>var elements = from element in doc.Descendants() where element.Name.LocalName == "RemovalTarget" select element; foreach (var element in elements) { element.AddAfterSelf(element.Value); element.Remove(); } </code></pre> <p>but on the second time through the loop I get a null reference, presumably because the collection is invalidated by changing it. What is an efficient way to make remove these tags on a potentially large document?</p>
[ { "answer_id": 259895, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "<p>Have you considered using XSLT? Seems like the perfect soution, as you are doing exactly what XSLT is meant for, transforming one XML doc into another. The templating system will delve into nested nastiness for you without problems.</p>\n\n<p><a href=\"http://www.w3schools.com/xsl/xsl_transformation.asp\" rel=\"nofollow noreferrer\">Here</a> is a basic example</p>\n" }, { "answer_id": 259926, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I would recommend either doing XSLT as Trull recommended as the best solution.</p>\n\n<p>Or you might look at using a string builder and regex matching to remove the items.</p>\n\n<p>You could look at walking through the document, and working with nodes and parent nodes to effectively move the code from inside the node to the parent, but it would be tedious, and very un-necessary with the other potential solutions out there.</p>\n" }, { "answer_id": 259954, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>A lightweight solution would be to use XmlReader to go trough the input document and XmlWriter to write the output.</p>\n\n<p>Note: XmlReader and XmlWriter clases are abstract, use the appropriate for your situation derived classes.</p>\n" }, { "answer_id": 259987, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": true, "text": "<p>You'll have to skip the deferred execution with a call to ToList, which probably won't hurt your performance in large documents as you're just going to be iterating and replacing at a much lower big-O than the original search. As @jacob_c pointed out, I should be using element.Nodes() to replace it properly, and as @Panos pointed out, I should reverse the list in order to handle nested replacements accurately.</p>\n\n<p>Also, use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.replacewith.aspx\" rel=\"nofollow noreferrer\">XElement.ReplaceWith</a>, much faster than your current approach in large documents:</p>\n\n<pre><code>var elements = doc.Descendants(\"RemovalTarget\").ToList().Reverse();\n/* reverse on the IList&lt;T&gt; may be faster than Reverse on the IEnumerable&lt;T&gt;,\n * needs benchmarking, but can't be any slower\n */\n\nforeach (var element in elements) {\n element.ReplaceWith(element.Nodes());\n}\n</code></pre>\n\n<p>One last point, in reviewing what this MAY be used for, I tend to agree with @Trull that XSLT may be what you're actually looking for, if say you're removing all say &lt;b&gt; tags from a document. Otherwise, enjoy this fairly decent and fairly well performing LINQ to XML implementation.</p>\n" }, { "answer_id": 260216, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 0, "selected": false, "text": "<p>Depending on how you manage your XML, you could use a regular expression to remove the tags. </p>\n\n<p>Here's a simple console application that demonstrates the use of a regex:</p>\n\n<pre><code> static void Main(string[] args)\n {\n string content = File.ReadAllText(args[0]);\n\n Regex openTag = new Regex(\"&lt;([/]?)RemovalTarget([^&gt;]*)&gt;\", RegexOptions.Multiline);\n\n string cleanContent = openTag.Replace(content, string.Empty);\n File.WriteAllText(args[1], cleanContent);\n }\n</code></pre>\n\n<p>This leaves newline characters in the file, but it shouldn't be too difficult to augment the regular expression.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ]
I'd like to strip out occurrences of a specific tag, leaving the inner XML intact. I'd like to do this with one pass (rather than searching, replacing, and starting from scratch again). For instance, from the source: ``` <element> <RemovalTarget Attribute="Something"> Content Here </RemovalTarget> </element> <element> More Here </element> ``` I'd like the result to be: ``` <element> Content Here </element> <element> More Here </element> ``` I've tried something like this (forgive me, I'm new to Linq): ``` var elements = from element in doc.Descendants() where element.Name.LocalName == "RemovalTarget" select element; foreach (var element in elements) { element.AddAfterSelf(element.Value); element.Remove(); } ``` but on the second time through the loop I get a null reference, presumably because the collection is invalidated by changing it. What is an efficient way to make remove these tags on a potentially large document?
You'll have to skip the deferred execution with a call to ToList, which probably won't hurt your performance in large documents as you're just going to be iterating and replacing at a much lower big-O than the original search. As @jacob\_c pointed out, I should be using element.Nodes() to replace it properly, and as @Panos pointed out, I should reverse the list in order to handle nested replacements accurately. Also, use [XElement.ReplaceWith](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.replacewith.aspx), much faster than your current approach in large documents: ``` var elements = doc.Descendants("RemovalTarget").ToList().Reverse(); /* reverse on the IList<T> may be faster than Reverse on the IEnumerable<T>, * needs benchmarking, but can't be any slower */ foreach (var element in elements) { element.ReplaceWith(element.Nodes()); } ``` One last point, in reviewing what this MAY be used for, I tend to agree with @Trull that XSLT may be what you're actually looking for, if say you're removing all say <b> tags from a document. Otherwise, enjoy this fairly decent and fairly well performing LINQ to XML implementation.
259,884
<p>I have a very standard <code>Gridview</code>, with Edit and Delete buttons auto-generated. It is bound to a <code>tableadapter</code> which is linked to my <code>RelationshipTypes</code> table.</p> <pre><code>dbo.RelationshipTypes: ID, Name, OriginConfigTypeID, DestinationConfigTypeID </code></pre> <p>I wish to use a label that will pull the name from the <code>ConfigTypes</code> table, using the <code>OriginConfigTypeID</code> and <code>DestinationTypeID</code> as the link.</p> <pre><code>dbo.ConfigTypes: ID, Name </code></pre> <p>My problem is, I can't automatically generate Edit and Delete buttons using an <code>Inner Join</code> in my dataset. Or can I?</p> <p>Here is my code:</p> <pre><code>&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" CssClass="TableList" DataKeyNames="ID" DataSourceID="dsRelationShipTypes1"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" Visible=False/&gt; &lt;asp:TemplateField HeaderText="Origin" SortExpression="OriginCIType_ID"&gt; &lt;EditItemTemplate&gt; &amp;nbsp;&lt;asp:DropDownList Enabled=true ID="DropDownList2" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='&lt;%# Bind("OriginCIType_ID") %&gt;'&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &amp;nbsp; &lt;asp:Label ID="Label2" runat="server" Text='&lt;%# Bind("OriginCIType_ID") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Name" SortExpression="Name"&gt; &lt;EditItemTemplate&gt; &lt;asp:TextBox ID="TextBox3" runat="server" Text='&lt;%# Bind("Name") %&gt;'&gt;&lt;/asp:TextBox&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label3" runat="server" Text='&lt;%# Bind("Name") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Destination" SortExpression="DestinationCIType_ID"&gt; &lt;EditItemTemplate&gt; &lt;asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='&lt;%# Bind("DestinationCIType_ID") %&gt;'&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label1" runat="server" Text='&lt;%# Bind("DestinationCIType_ID") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>So I did try to create my own edit and delete buttons, but kept receiving the error </p> <blockquote> <p>"cannot find update method"</p> </blockquote> <p>or something similar. Do I have to manually code the delete and update methods in my code-behind?</p>
[ { "answer_id": 259895, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "<p>Have you considered using XSLT? Seems like the perfect soution, as you are doing exactly what XSLT is meant for, transforming one XML doc into another. The templating system will delve into nested nastiness for you without problems.</p>\n\n<p><a href=\"http://www.w3schools.com/xsl/xsl_transformation.asp\" rel=\"nofollow noreferrer\">Here</a> is a basic example</p>\n" }, { "answer_id": 259926, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I would recommend either doing XSLT as Trull recommended as the best solution.</p>\n\n<p>Or you might look at using a string builder and regex matching to remove the items.</p>\n\n<p>You could look at walking through the document, and working with nodes and parent nodes to effectively move the code from inside the node to the parent, but it would be tedious, and very un-necessary with the other potential solutions out there.</p>\n" }, { "answer_id": 259954, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>A lightweight solution would be to use XmlReader to go trough the input document and XmlWriter to write the output.</p>\n\n<p>Note: XmlReader and XmlWriter clases are abstract, use the appropriate for your situation derived classes.</p>\n" }, { "answer_id": 259987, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": true, "text": "<p>You'll have to skip the deferred execution with a call to ToList, which probably won't hurt your performance in large documents as you're just going to be iterating and replacing at a much lower big-O than the original search. As @jacob_c pointed out, I should be using element.Nodes() to replace it properly, and as @Panos pointed out, I should reverse the list in order to handle nested replacements accurately.</p>\n\n<p>Also, use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.replacewith.aspx\" rel=\"nofollow noreferrer\">XElement.ReplaceWith</a>, much faster than your current approach in large documents:</p>\n\n<pre><code>var elements = doc.Descendants(\"RemovalTarget\").ToList().Reverse();\n/* reverse on the IList&lt;T&gt; may be faster than Reverse on the IEnumerable&lt;T&gt;,\n * needs benchmarking, but can't be any slower\n */\n\nforeach (var element in elements) {\n element.ReplaceWith(element.Nodes());\n}\n</code></pre>\n\n<p>One last point, in reviewing what this MAY be used for, I tend to agree with @Trull that XSLT may be what you're actually looking for, if say you're removing all say &lt;b&gt; tags from a document. Otherwise, enjoy this fairly decent and fairly well performing LINQ to XML implementation.</p>\n" }, { "answer_id": 260216, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 0, "selected": false, "text": "<p>Depending on how you manage your XML, you could use a regular expression to remove the tags. </p>\n\n<p>Here's a simple console application that demonstrates the use of a regex:</p>\n\n<pre><code> static void Main(string[] args)\n {\n string content = File.ReadAllText(args[0]);\n\n Regex openTag = new Regex(\"&lt;([/]?)RemovalTarget([^&gt;]*)&gt;\", RegexOptions.Multiline);\n\n string cleanContent = openTag.Replace(content, string.Empty);\n File.WriteAllText(args[1], cleanContent);\n }\n</code></pre>\n\n<p>This leaves newline characters in the file, but it shouldn't be too difficult to augment the regular expression.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13959/" ]
I have a very standard `Gridview`, with Edit and Delete buttons auto-generated. It is bound to a `tableadapter` which is linked to my `RelationshipTypes` table. ``` dbo.RelationshipTypes: ID, Name, OriginConfigTypeID, DestinationConfigTypeID ``` I wish to use a label that will pull the name from the `ConfigTypes` table, using the `OriginConfigTypeID` and `DestinationTypeID` as the link. ``` dbo.ConfigTypes: ID, Name ``` My problem is, I can't automatically generate Edit and Delete buttons using an `Inner Join` in my dataset. Or can I? Here is my code: ``` <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" CssClass="TableList" DataKeyNames="ID" DataSourceID="dsRelationShipTypes1"> <Columns> <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" Visible=False/> <asp:TemplateField HeaderText="Origin" SortExpression="OriginCIType_ID"> <EditItemTemplate> &nbsp;<asp:DropDownList Enabled=true ID="DropDownList2" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='<%# Bind("OriginCIType_ID") %>'> </asp:DropDownList> </EditItemTemplate> <ItemTemplate> &nbsp; <asp:Label ID="Label2" runat="server" Text='<%# Bind("OriginCIType_ID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Name" SortExpression="Name"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("Name") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Destination" SortExpression="DestinationCIType_ID"> <EditItemTemplate> <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='<%# Bind("DestinationCIType_ID") %>'> </asp:DropDownList> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("DestinationCIType_ID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> ``` So I did try to create my own edit and delete buttons, but kept receiving the error > > "cannot find update method" > > > or something similar. Do I have to manually code the delete and update methods in my code-behind?
You'll have to skip the deferred execution with a call to ToList, which probably won't hurt your performance in large documents as you're just going to be iterating and replacing at a much lower big-O than the original search. As @jacob\_c pointed out, I should be using element.Nodes() to replace it properly, and as @Panos pointed out, I should reverse the list in order to handle nested replacements accurately. Also, use [XElement.ReplaceWith](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.replacewith.aspx), much faster than your current approach in large documents: ``` var elements = doc.Descendants("RemovalTarget").ToList().Reverse(); /* reverse on the IList<T> may be faster than Reverse on the IEnumerable<T>, * needs benchmarking, but can't be any slower */ foreach (var element in elements) { element.ReplaceWith(element.Nodes()); } ``` One last point, in reviewing what this MAY be used for, I tend to agree with @Trull that XSLT may be what you're actually looking for, if say you're removing all say <b> tags from a document. Otherwise, enjoy this fairly decent and fairly well performing LINQ to XML implementation.
259,886
<p>I want to assign a resource I already have a second name, similar to using the BasedOn property of Styles. Specifically I have a brush that I use for a group of elements called ForegroundColor and I would like to use it in a control template (a ComboBox) calling it MouseOverBackgroundBrush. I would like to do something like this:</p> <pre><code>&lt;ResourceCopy x:key="MouseOverBackgroundBrush" Value="{StaticResource ForegroundColor}" /&gt; </code></pre> <p>Is there a way to do this or is there a better way to go about this in Xaml?</p>
[ { "answer_id": 259976, "author": "Amanda Mitchell", "author_id": 26628, "author_profile": "https://Stackoverflow.com/users/26628", "pm_score": 3, "selected": true, "text": "<p>This is a feature that doesn't have very good support in XAML. I believe that you'll either need to repeat yourself (and change both locations anytime you need to change the brush) <em>or</em> if you don't mind a bit of code behind, you can accomplish the duplication like this:</p>\n\n<pre><code>Resources[\"MouseOverBackgroundBrush\"] = Resources[\"ForegroundColor\"];\n</code></pre>\n" }, { "answer_id": 259992, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 1, "selected": false, "text": "<p>I don't know about how to copy a resource in xaml (can it even be done?) like you are asking ... but here is one way to accomplish what you are trying to do:</p>\n\n<pre><code>&lt;Color x:Key=\"firstColor\"&gt;#FFD97A7A&lt;/Color&gt;\n&lt;Color x:Key=\"secondColor\"&gt;#FFF4BFBF&lt;/Color&gt;\n&lt;LinearGradientBrush x:Key=\"firstGradientBrush\" EndPoint=\"0.5,1\" StartPoint=\"0.5,0\"&gt;\n &lt;GradientStop Color=\"{DynamicResource firstColor}\" Offset=\"0\"/&gt;\n &lt;GradientStop Color=\"{DynamicResource secondColor}\" Offset=\"1\"/&gt;\n&lt;/LinearGradientBrush&gt;\n&lt;LinearGradientBrush x:Key=\"secondGradientBrush\" EndPoint=\"0.5,1\" StartPoint=\"0.5,0\"&gt;\n &lt;GradientStop Color=\"{DynamicResource firstColor}\" Offset=\"0\"/&gt;\n &lt;GradientStop Color=\"{DynamicResource secondColor}\" Offset=\"1\"/&gt;\n&lt;/LinearGradientBrush&gt;\n</code></pre>\n\n<p>Basically, create two different brushes based on some common colors.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21186/" ]
I want to assign a resource I already have a second name, similar to using the BasedOn property of Styles. Specifically I have a brush that I use for a group of elements called ForegroundColor and I would like to use it in a control template (a ComboBox) calling it MouseOverBackgroundBrush. I would like to do something like this: ``` <ResourceCopy x:key="MouseOverBackgroundBrush" Value="{StaticResource ForegroundColor}" /> ``` Is there a way to do this or is there a better way to go about this in Xaml?
This is a feature that doesn't have very good support in XAML. I believe that you'll either need to repeat yourself (and change both locations anytime you need to change the brush) *or* if you don't mind a bit of code behind, you can accomplish the duplication like this: ``` Resources["MouseOverBackgroundBrush"] = Resources["ForegroundColor"]; ```
259,887
<p>In writing the code that throws the exception I asked about <a href="https://stackoverflow.com/questions/259800/is-there-a-built-in-net-exception-that-indicates-an-illegal-object-state">here</a>, I came to the end of my message, and paused at the punctuation. I realized that nearly every exception message I've ever thrown probably has a ! somewhere.</p> <pre><code>throw new InvalidOperationException("I'm not configured correctly!"); throw new ArgumentNullException("You passed a null!"); throw new StupidUserException("You can't divide by 0! What the hell were you THINKING??? DUMMY!!!!!"); </code></pre> <p>What tone do you take when writing exception messages? When going through logs, do you find any certain style of message actually helps more than another?</p>
[ { "answer_id": 259894, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 2, "selected": false, "text": "<p>Taking responsibility, even when it really was the user's fault, is the best option I've seen.</p>\n\n<p>Things along the lines of \"I can't find the file you wanted, would you check to see I have it correctly?\" or \"Something went wrong. Dunno what, but the only way I can get fixed is by stopping. Please restart me.\"</p>\n" }, { "answer_id": 259896, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Just be matter of fact. Include all the information you're likely to need when debugging, but no more than that.</p>\n\n<p>The only time I'd include an exclamation mark in an exception message is if it indicates that something really, really bizarre has happened. Most errors <em>aren't</em> really bizarre, just the product of an incorrect environment, user error, or a simple programming mistake.</p>\n" }, { "answer_id": 259898, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": false, "text": "<p>I try to mirror the tone, grammar and punctuation style of the framework against which I'm coding. You never know when one of these messages might actually make it out in front of a client or user, so I keep everything professional, non-judgmental and specific enough for troubleshooting -- without being so specific as to give away any security issues in the code.</p>\n\n<p>I avoid exclamation marks in all strings (UI and exception) like the plague, except (ocasionally) in my unit tests.</p>\n" }, { "answer_id": 259907, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 2, "selected": false, "text": "<p>Concise, detailed and little redundant information (i.e. ArgumentNullException obviously involved a null).</p>\n\n<p>But here's the best i've read for a while, first answer to <a href=\"https://stackoverflow.com/questions/140376/what-easter-eggs-have-you-placed-in-code\">this</a>.</p>\n" }, { "answer_id": 259917, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 2, "selected": false, "text": "<p>I wouldn't use exclamation marks too much. They express too much, think about the fact that \"No disk in drive!\" can be read as \"No disk in drive you crazy user.\" ;)</p>\n\n<p>I think that it's wise to throw exceptions that contain internationalized text. You never know who will use your code, catch your exception and display the text to the user.\nSo that would be:</p>\n\n<pre><code>throw new MagicalException(getText(\"magical.exception.text\"));\n</code></pre>\n\n<p>I also recommend wrapping the underlying exception (if you have one) when throwing it. It really helps debugging.</p>\n\n<p>Don't think that runtime exceptions won't be seen by the user. If you are logging to a file appender some curious user might just open the log and peek into your <em>dirty</em> secrets.</p>\n" }, { "answer_id": 259919, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "<p>A conversational tone in system messages makes the software look unprofessional and sloppy. Exclamation points, insults, and slang don't really have a place in polished exception messages.</p>\n\n<p>Also, I tend to use different styles in Java for runtime exceptions and checked exceptions, since runtime exceptions are addressed to the programmer that made the mistake. Since runtime exceptions might be displayed to end users, I still \"keep it clean,\" but they can be a little more terse and cryptic. Checked exception messages should be more helpful, since it may be that the user can fix the problem if you describe it (e.g., file not found, disk full, no route to host, etc.).</p>\n\n<p>One thing that is helpful, in the absence of a specific field on the exception for the information, is the offending data:</p>\n\n<pre><code>throw new IndexOutOfBoundsException(\"offset &lt; 0: \" + off);\n</code></pre>\n" }, { "answer_id": 259925, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 1, "selected": false, "text": "<p>I tend to work my exception messages into the exception themselves. E.g. a file_not_found should say \"file not found\". Specific data should only be included if the user can't figure it out; in this case, the user knows the filename, so I don't add that data. Formatting can be done by whatever outputs the information if necessary, so I try to make them as friendly to reformatting as possible.</p>\n" }, { "answer_id": 263759, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 1, "selected": false, "text": "<p>Polite, terse, simple, specific. Often, including state values in message is helpful.</p>\n" }, { "answer_id": 263989, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "<p>I find the most helpful messages provide:</p>\n\n<ul>\n<li>A <em>consistent format</em> that makes it easy to understand what they're telling you.</li>\n<li>A <em>time stamp,</em> so you can get a feel for the dynamics of your program.</li>\n<li>A <em>terse summary</em> of the error. If you provide tech support, add an <em>error code</em> for quick identification.</li>\n<li>An <em>explanation of what went wrong,</em> differentiating between an <em>invalid user input</em> and a <em>coding error.</em></li>\n<li><em>Detailed information</em>, including the <em>line of code</em> or <em>values</em> involved.</li>\n</ul>\n\n<p>And most important:</p>\n\n<ul>\n<li><strong>They tell the user how to fix the problem.</strong></li>\n</ul>\n\n<p>Example: <pre>Error 203 (Timeout) in commit.c line 42:\nUnable to save salary data for user 'Linus' to database at '10.10.1.21'\nafter 1500ms. Verify database address and login credentials.</pre></p>\n\n<p>One of the hardest lessons to learn is that your users are far less interested in the internals of your code than they are in <em>getting their jobs done.</em> Make it as easy as possible for them to do their jobs, and you've added tremendous value to your software.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
In writing the code that throws the exception I asked about [here](https://stackoverflow.com/questions/259800/is-there-a-built-in-net-exception-that-indicates-an-illegal-object-state), I came to the end of my message, and paused at the punctuation. I realized that nearly every exception message I've ever thrown probably has a ! somewhere. ``` throw new InvalidOperationException("I'm not configured correctly!"); throw new ArgumentNullException("You passed a null!"); throw new StupidUserException("You can't divide by 0! What the hell were you THINKING??? DUMMY!!!!!"); ``` What tone do you take when writing exception messages? When going through logs, do you find any certain style of message actually helps more than another?
A conversational tone in system messages makes the software look unprofessional and sloppy. Exclamation points, insults, and slang don't really have a place in polished exception messages. Also, I tend to use different styles in Java for runtime exceptions and checked exceptions, since runtime exceptions are addressed to the programmer that made the mistake. Since runtime exceptions might be displayed to end users, I still "keep it clean," but they can be a little more terse and cryptic. Checked exception messages should be more helpful, since it may be that the user can fix the problem if you describe it (e.g., file not found, disk full, no route to host, etc.). One thing that is helpful, in the absence of a specific field on the exception for the information, is the offending data: ``` throw new IndexOutOfBoundsException("offset < 0: " + off); ```
259,889
<p>If I have a button like the one in this image :</p> <p><strong><a href="http://www.freeimagehosting.net/image.php?4cd775814c.png" rel="nofollow noreferrer">http://www.freeimagehosting.net/image.php?4cd775814c.png</a></strong></p> <p>how could I make the text display itself vertically ? As in </p> <pre> j B u t t o n 1 </pre> <p>I would like to know how to do the same thing for JLabel . I'm sure there has to be a better way than to create as many labels as there are characters in the string . Right ?</p> <p><strong>EDIT:</strong> how can I insert an image into my post ? The button for the image shows the image in the preview section , but when I actually post the data , I only get some text back , like the tags are getting messed up .</p>
[ { "answer_id": 259928, "author": "asalamon74", "author_id": 21348, "author_profile": "https://Stackoverflow.com/users/21348", "pm_score": 4, "selected": true, "text": "<p>You can use HTML for JButton or JLabel. So </p>\n\n<pre><code>button = new JButton(\"&lt;html&gt;J&lt;br&gt;b&lt;br&gt;u&lt;br&gt;t&lt;br&gt;t&lt;br&gt;o&lt;br&gt;n&lt;br&gt;1&lt;/html&gt;\");\n</code></pre>\n\n<p>should do the trick.</p>\n" }, { "answer_id": 260099, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": false, "text": "<p>I don't know if this is useful to you, but <a href=\"http://www.codeguru.com/java/articles/199.shtml\" rel=\"noreferrer\">this sample</a> shows how to make a vertical label. The difference is that it rotates all of the text (and/or the icon) instead of stacking the letters. I don't know how difficult it would be to modify it to do what you're asking.</p>\n\n<p>The advantage of doing it this way is if your labels can change at runtime; generating big HTML strings might be a pain compared to a simple <code>label.setUI(new VerticalLabelUI(true));</code> (and you don't have to worry about &lt;> in the label text).</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
If I have a button like the one in this image : **<http://www.freeimagehosting.net/image.php?4cd775814c.png>** how could I make the text display itself vertically ? As in ``` j B u t t o n 1 ``` I would like to know how to do the same thing for JLabel . I'm sure there has to be a better way than to create as many labels as there are characters in the string . Right ? **EDIT:** how can I insert an image into my post ? The button for the image shows the image in the preview section , but when I actually post the data , I only get some text back , like the tags are getting messed up .
You can use HTML for JButton or JLabel. So ``` button = new JButton("<html>J<br>b<br>u<br>t<br>t<br>o<br>n<br>1</html>"); ``` should do the trick.
259,890
<p>How do you draw the following dynamic <strong>3D</strong> array with OpenGL <strong>glDrawPixels()</strong>? You can find the documentation here: <a href="http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html" rel="nofollow noreferrer">http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html</a></p> <pre><code>float ***array3d; void InitScreenArray() { int i, j; int screenX = scene.camera.vres; int screenY = scene.camera.hres; array3d = (float ***)malloc(sizeof(float **) * screenX); for (i = 0 ; i &lt; screenX; i++) { array3d[i] = (float **)malloc(sizeof(float *) * screenY); for (j = 0; j &lt; screenY; j++) array3d[i][j] = (float *)malloc(sizeof(float) * /*Z_SIZE*/ 3); } } </code></pre> <p>I can use only the following header files:</p> <pre><code>#include &lt;math.h&gt; #include &lt;stdlib.h&gt; #include &lt;windows.h&gt; #include &lt;GL/gl.h&gt; #include &lt;GL/glu.h&gt; #include &lt;GL/glut.h&gt; </code></pre>
[ { "answer_id": 261776, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": true, "text": "<p>Uh ... Since you're allocating <i>each single pixel</i> with a separate <code>malloc()</code>, you will have to draw each pixel with a separate call to <code>glDrawPixels()</code>, too. This is (obviously) insane; the idea of bitmapped graphics is that the pixels are stored in an adjacent, compact, format, so that it is quick and fast (<i>O(1)</i>) to move from one pixel to another. This looks very confused to me.</p>\n\n<p>A more sensible approach would be to allocate the \"3D array\" (which is often referred to as a 2D array of pixels, where each pixel happens to consist of a red, green and blue component) with a single call to <code>malloc()</code>, like so (in C):</p>\n\n<pre><code>float *array3d;\narray3d = malloc(scene.camera.hres * scene.camera.vres * 3 * sizeof *array3d);\n</code></pre>\n" }, { "answer_id": 262119, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 1, "selected": false, "text": "<p>Thanks unwind. I got the same advice on <a href=\"http://www.gamedev.net/community/forums/topic.asp?topic_id=513674\" rel=\"nofollow noreferrer\">gamedev.net</a> so I have implemented the following algorithm:</p>\n\n<pre><code>typedef struct\n{\n GLfloat R, G, B;\n} color_t;\n\ncolor_t *array1d;\n\nvoid InitScreenArray()\n{ \n long screenX = scene.camera.vres;\n long screenY = scene.camera.hres;\n array1d = (color_t *)malloc(screenX * screenY * sizeof(color_t));\n}\n\nvoid SetScreenColor(int x, int y, float red, float green, float blue)\n{\n int screenX = scene.camera.vres;\n int screenY = scene.camera.hres;\n\n array1d[x + y*screenY].R = red;\n array1d[x + y*screenY].G = green;\n array1d[x + y*screenY].B = blue;\n}\n\nvoid onDisplay( ) \n{\n glClearColor(0.1f, 0.2f, 0.3f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glRasterPos2i(0,0); \n glDrawPixels(scene.camera.hres, scene.camera.vres, GL_RGB, GL_FLOAT, array1d);\n\n glFinish();\n glutSwapBuffers();\n}\n</code></pre>\n\n<p>My application doesn't work yet (nothing appears on screen), but I think it's my fault and this code will work.</p>\n" }, { "answer_id": 1964810, "author": "Naveen", "author_id": 124802, "author_profile": "https://Stackoverflow.com/users/124802", "pm_score": 0, "selected": false, "text": "<p>wouldn't you want to use glTexImage2D() instead: see <a href=\"https://stackoverflow.com/questions/1080545/how-to-display-a-raw-yuv-frame-in-a-cocoa-opengl-program\">here</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13937/" ]
How do you draw the following dynamic **3D** array with OpenGL **glDrawPixels()**? You can find the documentation here: <http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html> ``` float ***array3d; void InitScreenArray() { int i, j; int screenX = scene.camera.vres; int screenY = scene.camera.hres; array3d = (float ***)malloc(sizeof(float **) * screenX); for (i = 0 ; i < screenX; i++) { array3d[i] = (float **)malloc(sizeof(float *) * screenY); for (j = 0; j < screenY; j++) array3d[i][j] = (float *)malloc(sizeof(float) * /*Z_SIZE*/ 3); } } ``` I can use only the following header files: ``` #include <math.h> #include <stdlib.h> #include <windows.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> ```
Uh ... Since you're allocating *each single pixel* with a separate `malloc()`, you will have to draw each pixel with a separate call to `glDrawPixels()`, too. This is (obviously) insane; the idea of bitmapped graphics is that the pixels are stored in an adjacent, compact, format, so that it is quick and fast (*O(1)*) to move from one pixel to another. This looks very confused to me. A more sensible approach would be to allocate the "3D array" (which is often referred to as a 2D array of pixels, where each pixel happens to consist of a red, green and blue component) with a single call to `malloc()`, like so (in C): ``` float *array3d; array3d = malloc(scene.camera.hres * scene.camera.vres * 3 * sizeof *array3d); ```
259,900
<p>Check it out: this little .NET Console Program yields interesting results...notice how I'm converting a float to an integer in two different ways:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CastVsConvert { class Program { static void Main(string[] args) { int newWidth = 0; CalculateResizeSizes(600, 500, out newWidth); } static void CalculateResizeSizes(int originalWidth, int maxWidth, out int newWidth) { float percentage = 1.0F; percentage = maxWidth / (float)originalWidth; newWidth = (int)((float)originalWidth * percentage); int newWidthConvert = Convert.ToInt32((float)originalWidth * percentage); Console.Write("Percentage: {0}\n", percentage.ToString()); Console.Write("Cast: {0}\n", newWidth.ToString()); Console.Write("Convert: {0}\n", newWidthConvert.ToString()); } } } </code></pre> <p>I would expect the output for "Cast" and "Convert" to be the same, but they're not...here's the output:</p> <pre><code>C:\Documents and Settings\Scott\My Documents\Visual Studio 2008\Projects\CastVsC onvert\CastVsConvert\bin\Debug&gt;CastVsConvert.exe Percentage: 0.8333333 Cast: 499 Convert: 500 </code></pre> <p>Does anybody know why .NET is returning different values here? </p>
[ { "answer_id": 259905, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 3, "selected": false, "text": "<p>The cast is chopping off the portion of the number after the decimal point while the conversion is rounding.</p>\n" }, { "answer_id": 259906, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 4, "selected": false, "text": "<p>Its not a bug, <code>cast</code> truncates, <code>convert</code> rounds.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/104063/systemconverttoint-vs-int\">this</a></p>\n" }, { "answer_id": 259909, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>From the docs for the return value of <a href=\"http://msdn.microsoft.com/en-us/library/303w38b8.aspx\" rel=\"nofollow noreferrer\">Convert.ToInt32</a>:</p>\n\n<blockquote>\n <p><em>value</em> rounded to the nearest 32-bit signed integer. If value is halfway\n between two whole numbers, the even\n number is returned; that is, 4.5 is\n converted to 4, and 5.5 is converted\n to 6.</p>\n</blockquote>\n\n<p>Casting doesn't round up - it just truncates. The result of the multiplication is very slightly under 500, so casting will truncate that to 499 whereas Convert.ToInt32 will round it up to 500.</p>\n" }, { "answer_id": 259937, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 1, "selected": false, "text": "<p>There's an extra, hidden cast that's probably causing this. For example, if you use this instead of a recalculation:</p>\n\n<pre><code>int newWidthConvert = Convert.ToInt32(newWidth);\n</code></pre>\n\n<p>You'll get the same result. What's happening becomes more clear when you use Reflector to peek at <code>Convert.ToInt32(float)</code>:</p>\n\n<pre><code>public static int ToInt32(float value)\n{\n return ToInt32((double) value);\n}\n</code></pre>\n\n<p>There's a hidden cast to <code>Double</code>.</p>\n\n<p>If you add a couple of lines to investigate, then use the debugger to take a look, you'll see what happens:</p>\n\n<pre><code>float newWidth1 = ((float)originalWidth * percentage);\ndouble newWidth2 = ((float)originalWidth * percentage); \n</code></pre>\n\n<p><code>double</code> is more precise and saves the value as 499.999999 and a few more decimal digits. <code>float</code> is less precise and stores 500.0. The integer conversion truncates the decimal part, so you end up with 500 or 499 based on the intermediate cast. When you call <code>Convert.ToInt32()</code>, the result is already cast to a <code>float</code> so you get the <code>Double</code> representation of 500.0. Personally I prefer always using <code>double</code> when I can.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33754/" ]
Check it out: this little .NET Console Program yields interesting results...notice how I'm converting a float to an integer in two different ways: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CastVsConvert { class Program { static void Main(string[] args) { int newWidth = 0; CalculateResizeSizes(600, 500, out newWidth); } static void CalculateResizeSizes(int originalWidth, int maxWidth, out int newWidth) { float percentage = 1.0F; percentage = maxWidth / (float)originalWidth; newWidth = (int)((float)originalWidth * percentage); int newWidthConvert = Convert.ToInt32((float)originalWidth * percentage); Console.Write("Percentage: {0}\n", percentage.ToString()); Console.Write("Cast: {0}\n", newWidth.ToString()); Console.Write("Convert: {0}\n", newWidthConvert.ToString()); } } } ``` I would expect the output for "Cast" and "Convert" to be the same, but they're not...here's the output: ``` C:\Documents and Settings\Scott\My Documents\Visual Studio 2008\Projects\CastVsC onvert\CastVsConvert\bin\Debug>CastVsConvert.exe Percentage: 0.8333333 Cast: 499 Convert: 500 ``` Does anybody know why .NET is returning different values here?
Its not a bug, `cast` truncates, `convert` rounds. See [this](https://stackoverflow.com/questions/104063/systemconverttoint-vs-int)
259,902
<p>I have the following solution project structure:</p> <blockquote> <p>Application.Core.Entities</p> <p>Application.Xtend.CustomerName.Entities</p> </blockquote> <p>In the Core project I have an entity <strong>Customer</strong> defiend. In the XTend project, I have an entity defined that subclasses Customer named <strong>xCustomer</strong> (for lack of a better name at this time...).</p> <p>The idea here is that we have a Core domain model in our application. A customer can then create a new assembly that contains extensions to our core model. When the extension assembly is present a smart <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="noreferrer">IRepository</a> class will return a subclass of the core class instead.</p> <p>I am attempting to map this relationship in <a href="http://nhforge.org/" rel="noreferrer">NHibernate</a>. Using <a href="http://code.google.com/p/fluent-nhibernate/" rel="noreferrer">Fluent NHibernate</a> I was able to generate this mapping:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;hibernate-mapping xmlns=&quot;urn:nhibernate-mapping-2.2&quot; default-lazy=&quot;false&quot; assembly=&quot;NHibernate.Core.Entites&quot; namespace=&quot;NHibernate.Entites&quot; default-access=&quot;field.camelcase-underscore&quot;&gt; &lt;!-- Customer is located in assembly Application.Core.Entities --&gt; &lt;class name=&quot;Customer&quot; table=&quot;Customers&quot; xmlns=&quot;urn:nhibernate-mapping-2.2&quot;&gt; &lt;id name=&quot;Id&quot; column=&quot;Id&quot; type=&quot;Int64&quot;&gt; &lt;generator class=&quot;native&quot; /&gt; &lt;/id&gt; &lt;component name=&quot;Name&quot; insert=&quot;true&quot; update=&quot;true&quot;&gt; &lt;property name=&quot;LastName&quot; column=&quot;LastName&quot; length=&quot;255&quot; type=&quot;String&quot; not-null=&quot;true&quot;&gt; &lt;column name=&quot;LastName&quot; /&gt; &lt;/property&gt; &lt;property name=&quot;FirstName&quot; column=&quot;FirstName&quot; length=&quot;255&quot; type=&quot;String&quot; not-null=&quot;true&quot;&gt; &lt;column name=&quot;FirstName&quot; /&gt; &lt;/property&gt; &lt;/component&gt; &lt;!-- xCustomer is located in assembly Application.XTend.CustomerName.Entities --&gt; &lt;joined-subclass name=&quot;xCustomer&quot; table=&quot;xCustomer&quot;&gt; &lt;key column=&quot;CustomerId&quot; /&gt; &lt;property name=&quot;CustomerType&quot; column=&quot;CustomerType&quot; length=&quot;255&quot; type=&quot;String&quot; not-null=&quot;true&quot;&gt; &lt;column name=&quot;CustomerType&quot; /&gt; &lt;/property&gt; &lt;/joined-subclass&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>But NHib throws the following error:</p> <blockquote> <p>NHibernate.MappingException: persistent class Application.Entites.xCustomer, Application.Core.Entites not found ---&gt; System.TypeLoadException: Could not load type 'Application.Entites.xCustomer' from assembly 'Application.Core.Entites, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'..</p> </blockquote> <p>Which makes sense xCustomer is not defined in the Core library.</p> <p>Is it possible to span different assemblies like this? Am I approaching the problem wrong?</p>
[ { "answer_id": 261820, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": false, "text": "<p>You need to map using the <code>extends</code> attribute of the <code>&lt;class&gt;</code> element (AFAIK, this is new in NHibernate 2.0). Then you can have your subclass mapping (<code>.hbm.xml</code>) in the XTend assembly. </p>\n\n<p>You might have to use the AddAttribute/AddProperty (can't remember what it's called) to do this using Fluent NHibernate. (Or submit a patch).</p>\n" }, { "answer_id": 262419, "author": "NotMyself", "author_id": 303, "author_profile": "https://Stackoverflow.com/users/303", "pm_score": 4, "selected": true, "text": "<p>I asked this same question on the NHibernate Users mailing list and the solution was so obvious that I am somewhat embarrassed that I couldn't see it. </p>\n\n<p>The hibernate-mapping attributes assembly and namespace are convenient short cuts that allow you to not have to fully qualify your class names. This lets you have the nice mark up , but the name attribute of both class and joined-subclass elements can take a fully qualified assembly name as well.</p>\n\n<p>So the above broken mapping file can be fixed like so:</p>\n\n<pre><code>&lt;joined-subclass name=\"Application.XTend.CustomerName.Entities.xCustomer, \n Application.XTend.CustomerName.Entities, Version=1.0.0.0, \n Culture=neutral, PublicKeyToken=null\" \n table=\"xCustomer\"&gt;\n &lt;key column=\"CustomerId\" /&gt;\n &lt;property name=\"CustomerType\" column=\"CustomerType\" length=\"255\" \n type=\"String\" not-null=\"true\"&gt;\n &lt;column name=\"CustomerType\" /&gt;\n &lt;/property&gt;\n&lt;/joined-subclass&gt;\n</code></pre>\n\n<p>This works as I expected it to. So I then took a look at the Fluent-NHibernate source and created a patch complete with working unit tests to resolve the issue and <a href=\"http://code.google.com/p/fluent-nhibernate/issues/detail?id=70\" rel=\"noreferrer\">submitted it to the project</a>.</p>\n\n<p>Thanks for you help @David Kemp</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ]
I have the following solution project structure: > > Application.Core.Entities > > > Application.Xtend.CustomerName.Entities > > > In the Core project I have an entity **Customer** defiend. In the XTend project, I have an entity defined that subclasses Customer named **xCustomer** (for lack of a better name at this time...). The idea here is that we have a Core domain model in our application. A customer can then create a new assembly that contains extensions to our core model. When the extension assembly is present a smart [IRepository](http://martinfowler.com/eaaCatalog/repository.html) class will return a subclass of the core class instead. I am attempting to map this relationship in [NHibernate](http://nhforge.org/). Using [Fluent NHibernate](http://code.google.com/p/fluent-nhibernate/) I was able to generate this mapping: ``` <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false" assembly="NHibernate.Core.Entites" namespace="NHibernate.Entites" default-access="field.camelcase-underscore"> <!-- Customer is located in assembly Application.Core.Entities --> <class name="Customer" table="Customers" xmlns="urn:nhibernate-mapping-2.2"> <id name="Id" column="Id" type="Int64"> <generator class="native" /> </id> <component name="Name" insert="true" update="true"> <property name="LastName" column="LastName" length="255" type="String" not-null="true"> <column name="LastName" /> </property> <property name="FirstName" column="FirstName" length="255" type="String" not-null="true"> <column name="FirstName" /> </property> </component> <!-- xCustomer is located in assembly Application.XTend.CustomerName.Entities --> <joined-subclass name="xCustomer" table="xCustomer"> <key column="CustomerId" /> <property name="CustomerType" column="CustomerType" length="255" type="String" not-null="true"> <column name="CustomerType" /> </property> </joined-subclass> </class> </hibernate-mapping> ``` But NHib throws the following error: > > NHibernate.MappingException: > persistent class > Application.Entites.xCustomer, > Application.Core.Entites not found > ---> System.TypeLoadException: Could not load type > 'Application.Entites.xCustomer' from > assembly 'Application.Core.Entites, > Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'.. > > > Which makes sense xCustomer is not defined in the Core library. Is it possible to span different assemblies like this? Am I approaching the problem wrong?
I asked this same question on the NHibernate Users mailing list and the solution was so obvious that I am somewhat embarrassed that I couldn't see it. The hibernate-mapping attributes assembly and namespace are convenient short cuts that allow you to not have to fully qualify your class names. This lets you have the nice mark up , but the name attribute of both class and joined-subclass elements can take a fully qualified assembly name as well. So the above broken mapping file can be fixed like so: ``` <joined-subclass name="Application.XTend.CustomerName.Entities.xCustomer, Application.XTend.CustomerName.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="xCustomer"> <key column="CustomerId" /> <property name="CustomerType" column="CustomerType" length="255" type="String" not-null="true"> <column name="CustomerType" /> </property> </joined-subclass> ``` This works as I expected it to. So I then took a look at the Fluent-NHibernate source and created a patch complete with working unit tests to resolve the issue and [submitted it to the project](http://code.google.com/p/fluent-nhibernate/issues/detail?id=70). Thanks for you help @David Kemp
259,929
<p>In C#4.0 we're going to get dynamic types, or objects whose "static type is dynamic", according to Anders. This will allow any method invocation resolution to happen at runtime rather than compile time. But will there be facility to bind the dynamic object to some sort of contract (and thereby also get full intellisense for it back), rather than allowing any call on it even if you know that is not likely to be valid.</p> <p>I.e. instead of just</p> <pre><code>dynamic foo = GetSomeDynamicObject(); </code></pre> <p>have the ability to cast or transform it to constrain it to a known contract, such as</p> <pre><code>IFoo foo2 = foo.To&lt;IFoo&gt;; </code></pre> <p>or even just</p> <pre><code>IFoo foo2 = foo as IFoo; </code></pre> <p>Can't find anything like that in the existing materials for C#4.0, but it seems like a logical extension of the dynamic paradigm. Anyone with more info?</p>
[ { "answer_id": 259985, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>I'm not aware of anything really resembling duck typing, I'm afraid. I've <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx\" rel=\"nofollow noreferrer\">blogged about the idea</a>, but I don't expect any support. It probably wouldn't be too hard to use Reflection.Emit to make a class which will generate an implementation of any given interface, taking a dynamic object in the constructor and just proxying each call through to it. Not ideal, but it might be a stopgap.</p>\n" }, { "answer_id": 260074, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 1, "selected": false, "text": "<p>That's a cool idea.\nIf I understand you, you're describing/proposing a capability of the CLR, whereby, when you try and cast a dynamic object to an interface, it should look at what methods/properties the dynamic object supports and see if it has ones that effectively implement that interface. Then the CLR would take care of 'implementing IFoo' on the object, so you can then cast the dynamic object to an IFoo.\nAlmost certain that that will not be supported, but it's a interesting idea.</p>\n" }, { "answer_id": 261248, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 1, "selected": false, "text": "<p>Tobias Hertkorn answered my question <a href=\"https://stackoverflow.com/questions/245975/how-do-you-implement-c4s-idynamicobject-interface#260440\">here</a> with a link to his <a href=\"http://saftsack.fs.uni-bayreuth.de/~dun3/archives/first-look-ducktyping-c-4-0-idynamicobject-metaobject/202.html\" rel=\"nofollow noreferrer\">blogpost</a> showing an example of how to use the Convert() method on MetaObject to return a dynamic proxy. It looks <em>very</em> promising.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32577/" ]
In C#4.0 we're going to get dynamic types, or objects whose "static type is dynamic", according to Anders. This will allow any method invocation resolution to happen at runtime rather than compile time. But will there be facility to bind the dynamic object to some sort of contract (and thereby also get full intellisense for it back), rather than allowing any call on it even if you know that is not likely to be valid. I.e. instead of just ``` dynamic foo = GetSomeDynamicObject(); ``` have the ability to cast or transform it to constrain it to a known contract, such as ``` IFoo foo2 = foo.To<IFoo>; ``` or even just ``` IFoo foo2 = foo as IFoo; ``` Can't find anything like that in the existing materials for C#4.0, but it seems like a logical extension of the dynamic paradigm. Anyone with more info?
I'm not aware of anything really resembling duck typing, I'm afraid. I've [blogged about the idea](http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx), but I don't expect any support. It probably wouldn't be too hard to use Reflection.Emit to make a class which will generate an implementation of any given interface, taking a dynamic object in the constructor and just proxying each call through to it. Not ideal, but it might be a stopgap.
259,941
<p>Wondering if my approach is ok or could be improved:</p> <pre><code>Public Class Company private _id as Integer private _name as String private _location as String Public Function LoadMultipleByLocation(Byval searchStr as String) as List(Of Company) 'sql etc here to build the list End Function End Classs </code></pre> <p>Thoughts on having the object mapping like this?</p>
[ { "answer_id": 259964, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>In this case, you would create an instance of Company, and then use it to return a List of Companies?</p>\n\n<p>Some people do this, but I prefer to seperate my data object into a dumb data container:</p>\n\n<pre><code>public class Company : EntityBase\n{\n private int _id;\n private string _name;\n private string _location;\n}\n</code></pre>\n\n<p>I use a base class (EntityBase) that contains common methods for converting the dumb entity back into a collection of SQLParameters (for persisting), as well as instantiating it from a passed in SQLReader (this gets overridden in each concrete class, to map the reader to the private variables).</p>\n\n<p>I then prefer to use a \"Service\" class that actually makes the database calls, creates the appropriate entity object, and returns it, I can utilize polymorphism here to reduce code duplication heavily.</p>\n" }, { "answer_id": 260159, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>@Dan</p>\n\n<p>EntityBase would be a base class that each entity object would inherit, something like:</p>\n\n<pre><code>public class EntityBase\n{\n public virtual string SaveSproc { get; }\n\n public virtual void LoadFromReader(SqlReader reader)\n {\n }\n\n public virtual void Save()\n {\n List&lt;SqlParameters&gt; paramList = = this.CreateParamsList();\n DoSqlStuff(this.SaveSproc, paramList);\n }\n\n public virtual List&lt;SqlParamenter&gt; CreateParamsList()\n { \n return new List&lt;SqlParameter&gt;\n }\n}\n\npublic Company : EntityBase\n{\n\n private string _data;\n\npublic override string SaveSproc { get { return \"SprocThatSaves\"; } }\n\n public override List&lt;SqlParameter&gt; CreateParamList()\n{ \n List&lt;SqlParameter&gt; param = new List&lt;SqlParameter&gt;\n param.Add(new SqlParameter(\"Data\",_data);\n\n return param; \n}\n\npublic override void LoadFromReader(SqlReader reader)\n{\n // PsuedoCode\n _data = reader[\"data\"];\n}\n}\n</code></pre>\n\n<p>Now, your DB tier can get a reader with company data, and do something like:</p>\n\n<pre><code>Company = new Company();\nCompany.LoadFromReader(reader);\n</code></pre>\n\n<p>And elsewhere, to save your data back:</p>\n\n<pre><code>Company.Save();\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Wondering if my approach is ok or could be improved: ``` Public Class Company private _id as Integer private _name as String private _location as String Public Function LoadMultipleByLocation(Byval searchStr as String) as List(Of Company) 'sql etc here to build the list End Function End Classs ``` Thoughts on having the object mapping like this?
In this case, you would create an instance of Company, and then use it to return a List of Companies? Some people do this, but I prefer to seperate my data object into a dumb data container: ``` public class Company : EntityBase { private int _id; private string _name; private string _location; } ``` I use a base class (EntityBase) that contains common methods for converting the dumb entity back into a collection of SQLParameters (for persisting), as well as instantiating it from a passed in SQLReader (this gets overridden in each concrete class, to map the reader to the private variables). I then prefer to use a "Service" class that actually makes the database calls, creates the appropriate entity object, and returns it, I can utilize polymorphism here to reduce code duplication heavily.
259,956
<p>What is the best way to tokenize/split a NSString in Objective-C?</p>
[ { "answer_id": 259966, "author": "Adam Alexander", "author_id": 33164, "author_profile": "https://Stackoverflow.com/users/33164", "pm_score": 9, "selected": true, "text": "<p>Found answer <a href=\"http://borkware.com/quickies/one?topic=NSString\" rel=\"nofollow noreferrer\">here</a>:</p>\n<pre><code>NSString *string = @&quot;oop:ack:bork:greeble:ponies&quot;;\nNSArray *chunks = [string componentsSeparatedByString: @&quot;:&quot;];\n</code></pre>\n" }, { "answer_id": 261105, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 4, "selected": false, "text": "<p>If you just want to split a string, use <code>-[NSString componentsSeparatedByString:]</code>. For more complex tokenization, use the NSScanner class.</p>\n" }, { "answer_id": 267486, "author": "Todd Ditchendorf", "author_id": 34934, "author_profile": "https://Stackoverflow.com/users/34934", "pm_score": 3, "selected": false, "text": "<p>If your tokenization needs are more complex, check out my open source Cocoa String tokenizing/parsing toolkit: ParseKit:</p>\n\n<p><a href=\"http://parsekit.com\" rel=\"nofollow noreferrer\">http://parsekit.com</a></p>\n\n<p>For simple splitting of strings using a delimiter char (like ':'), ParseKit would definitely be overkill. But again, for complex tokenization needs, ParseKit is extremely powerful/flexible. </p>\n\n<p>Also see the <a href=\"http://parsekit.com/tokenization.html\" rel=\"nofollow noreferrer\">ParseKit Tokenization documentation</a>.</p>\n" }, { "answer_id": 432796, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 5, "selected": false, "text": "<p>Everyone has mentioned <code>componentsSeparatedByString:</code> but you can also use <code>CFStringTokenizer</code> (remember that an <code>NSString</code> and <code>CFString</code> are interchangeable) which will tokenize natural languages too (like Chinese/Japanese which don't split words on spaces).</p>\n" }, { "answer_id": 12151143, "author": "Wienke", "author_id": 471678, "author_profile": "https://Stackoverflow.com/users/471678", "pm_score": 3, "selected": false, "text": "<p>If you want to tokenize on multiple characters, you can use NSString's <code>componentsSeparatedByCharactersInSet</code>. NSCharacterSet has some handy pre-made sets like the <code>whitespaceCharacterSet</code> and the <code>illegalCharacterSet</code>. And it has initializers for Unicode ranges.</p>\n\n<p>You can also combine character sets and use them to tokenize, like this:</p>\n\n <pre class=\"lang-c prettyprint-override\"><code>// Tokenize sSourceEntityName on both whitespace and punctuation.\nNSMutableCharacterSet *mcharsetWhitePunc = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];\n[mcharsetWhitePunc formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];\nNSArray *sarrTokenizedName = [self.sSourceEntityName componentsSeparatedByCharactersInSet:mcharsetWhitePunc];\n[mcharsetWhitePunc release];\n</code></pre>\n\n<p>Be aware that <code>componentsSeparatedByCharactersInSet</code> will produce blank strings if it encounters more than one member of the charSet in a row, so you might want to test for lengths less than 1.</p>\n" }, { "answer_id": 16321262, "author": "Rosario Carcò", "author_id": 2332617, "author_profile": "https://Stackoverflow.com/users/2332617", "pm_score": 0, "selected": false, "text": "<p>I had a case where I had to split the console output after an LDAP query with ldapsearch. First set up and execute the NSTask (I found a good code sample here: <a href=\"https://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app\">Execute a terminal command from a Cocoa app</a>). But then I had to split and parse the output so as to extract only the print-server names out of the Ldap-query-output. Unfortunately it is rather tedious string-manipulation which would be no problem at all if we were to manipulate C-strings/arrays with simple C-array operations. So here is my code using cocoa objects. If you have better suggestions, let me know.</p>\n\n<pre><code>//as the ldap query has to be done when the user selects one of our Active Directory Domains\n//(an according comboBox should be populated with print-server names we discover from AD)\n//my code is placed in the onSelectDomain event code\n\n//the following variables are declared in the interface .h file as globals\n@protected NSArray* aDomains;//domain combo list array\n@protected NSMutableArray* aPrinters;//printer combo list array\n@protected NSMutableArray* aPrintServers;//print server combo list array\n\n@protected NSString* sLdapQueryCommand;//for LDAP Queries\n@protected NSArray* aLdapQueryArgs;\n@protected NSTask* tskLdapTask;\n@protected NSPipe* pipeLdapTask;\n@protected NSFileHandle* fhLdapTask;\n@protected NSMutableData* mdLdapTask;\n\nIBOutlet NSComboBox* comboDomain;\nIBOutlet NSComboBox* comboPrinter;\nIBOutlet NSComboBox* comboPrintServer;\n//end of interface globals\n\n//after collecting the print-server names they are displayed in an according drop-down comboBox\n//as soon as the user selects one of the print-servers, we should start a new query to find all the\n//print-queues on that server and display them in the comboPrinter drop-down list\n//to find the shares/print queues of a windows print-server you need samba and the net -S command like this:\n// net -S yourPrintServerName.yourBaseDomain.com -U yourLdapUser%yourLdapUserPassWord -W adm rpc share -l\n//which dispalays a long list of the shares\n\n- (IBAction)onSelectDomain:(id)sender\n{\n static int indexOfLastItem = 0; //unfortunately we need to compare this because we are called also if the selection did not change!\n\n if ([comboDomain indexOfSelectedItem] != indexOfLastItem &amp;&amp; ([comboDomain indexOfSelectedItem] != 0))\n {\n\n indexOfLastItem = [comboDomain indexOfSelectedItem]; //retain this index for next call\n\n //the print-servers-list has to be loaded on a per univeristy or domain basis from a file dynamically or from AN LDAP-QUERY\n\n //initialize an LDAP-Query-Task or console-command like this one with console output\n /*\n\n ldapsearch -LLL -s sub -D \"cn=yourLdapUser,ou=yourOuWithLdapUserAccount,dc=yourDomain,dc=com\" -h \"yourLdapServer.com\" -p 3268 -w \"yourLdapUserPassWord\" -b \"dc=yourBaseDomainToSearchIn,dc=com\" \"(&amp;(objectcategory=computer)(cn=ps*))\" \"dn\"\n\n//our print-server names start with ps* and we want the dn as result, wich comes like this:\n\n dn: CN=PSyourPrintServerName,CN=Computers,DC=yourBaseDomainToSearchIn,DC=com\n\n */\n\n sLdapQueryCommand = [[NSString alloc] initWithString: @\"/usr/bin/ldapsearch\"];\n\n\n if ([[comboDomain stringValue] compare: @\"firstDomain\"] == NSOrderedSame) {\n\n aLdapQueryArgs = [NSArray arrayWithObjects: @\"-LLL\",@\"-s\", @\"sub\",@\"-D\", @\"cn=yourLdapUser,ou=yourOuWithLdapUserAccount,dc=yourDomain,dc=com\",@\"-h\", @\"yourLdapServer.com\",@\"-p\",@\"3268\",@\"-w\",@\"yourLdapUserPassWord\",@\"-b\",@\"dc=yourFirstDomainToSearchIn,dc=com\",@\"(&amp;(objectcategory=computer)(cn=ps*))\",@\"dn\",nil];\n }\n else {\n aLdapQueryArgs = [NSArray arrayWithObjects: @\"-LLL\",@\"-s\", @\"sub\",@\"-D\", @\"cn=yourLdapUser,ou=yourOuWithLdapUserAccount,dc=yourDomain,dc=com\",@\"-h\", @\"yourLdapServer.com\",@\"-p\",@\"3268\",@\"-w\",@\"yourLdapUserPassWord\",@\"-b\",@\"dc=yourSecondDomainToSearchIn,dc=com\",@\"(&amp;(objectcategory=computer)(cn=ps*))\",@\"dn\",nil];\n\n }\n\n\n //prepare and execute ldap-query task\n\n tskLdapTask = [[NSTask alloc] init];\n pipeLdapTask = [[NSPipe alloc] init];//instead of [NSPipe pipe]\n [tskLdapTask setStandardOutput: pipeLdapTask];//hope to get the tasks output in this file/pipe\n\n //The magic line that keeps your log where it belongs, has to do with NSLog (see https://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app and here http://www.cocoadev.com/index.pl?NSTask )\n [tskLdapTask setStandardInput:[NSPipe pipe]];\n\n //fhLdapTask = [[NSFileHandle alloc] init];//would be redundand here, next line seems to do the trick also\n fhLdapTask = [pipeLdapTask fileHandleForReading];\n mdLdapTask = [NSMutableData dataWithCapacity:512];//prepare capturing the pipe buffer which is flushed on read and can overflow, start with 512 Bytes but it is mutable, so grows dynamically later\n [tskLdapTask setLaunchPath: sLdapQueryCommand];\n [tskLdapTask setArguments: aLdapQueryArgs];\n\n#ifdef bDoDebug\n NSLog (@\"sLdapQueryCommand: %@\\n\", sLdapQueryCommand);\n NSLog (@\"aLdapQueryArgs: %@\\n\", aLdapQueryArgs );\n NSLog (@\"tskLdapTask: %@\\n\", [tskLdapTask arguments]);\n#endif\n\n [tskLdapTask launch];\n\n while ([tskLdapTask isRunning]) {\n [mdLdapTask appendData: [fhLdapTask readDataToEndOfFile]];\n }\n [tskLdapTask waitUntilExit];//might be redundant here.\n\n [mdLdapTask appendData: [fhLdapTask readDataToEndOfFile]];//add another read for safety after process/command stops\n\n NSString* sLdapOutput = [[NSString alloc] initWithData: mdLdapTask encoding: NSUTF8StringEncoding];//convert output to something readable, as NSData and NSMutableData are mere byte buffers\n\n#ifdef bDoDebug\n NSLog(@\"LdapQueryOutput: %@\\n\", sLdapOutput);\n#endif\n\n //Ok now we have the printservers from Active Directory, lets parse the output and show the list to the user in its combo box\n //output is formatted as this, one printserver per line\n //dn: CN=PSyourPrintServer,OU=Computers,DC=yourBaseDomainToSearchIn,DC=com\n\n //so we have to search for \"dn: CN=\" to retrieve each printserver's name\n //unfortunately splitting this up will give us a first line containing only \"\" empty string, which we can replace with the word \"choose\"\n //appearing as first entry in the comboBox\n\n aPrintServers = (NSMutableArray*)[sLdapOutput componentsSeparatedByString:@\"dn: CN=\"];//split output into single lines and store it in the NSMutableArray aPrintServers\n\n#ifdef bDoDebug\n NSLog(@\"aPrintServers: %@\\n\", aPrintServers);\n#endif\n\n if ([[aPrintServers objectAtIndex: 0 ] compare: @\"\" options: NSLiteralSearch] == NSOrderedSame){\n [aPrintServers replaceObjectAtIndex: 0 withObject: slChoose];//replace with localized string \"choose\"\n\n#ifdef bDoDebug\n NSLog(@\"aPrintServers: %@\\n\", aPrintServers);\n#endif\n\n }\n\n//Now comes the tedious part to extract only the print-server-names from the single lines\n NSRange r;\n NSString* sTemp;\n\n for (int i = 1; i &lt; [aPrintServers count]; i++) {//skip first line with \"choose\". To get rid of the rest of the line, we must isolate/preserve the print server's name to the delimiting comma and remove all the remaining characters\n sTemp = [aPrintServers objectAtIndex: i];\n sTemp = [sTemp stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];//remove newlines and line feeds\n\n#ifdef bDoDebug\n NSLog(@\"sTemp: %@\\n\", sTemp);\n#endif\n r = [sTemp rangeOfString: @\",\"];//now find first comma to remove the whole rest of the line\n //r.length = [sTemp lengthOfBytesUsingEncoding:NSUTF8StringEncoding];\n r.length = [sTemp length] - r.location;//calculate number of chars between first comma found and lenght of string\n#ifdef bDoDebug\n NSLog(@\"range: %i, %i\\n\", r.location, r.length);\n#endif\n\n sTemp = [sTemp stringByReplacingCharactersInRange:r withString: @\"\" ];//remove rest of line\n#ifdef bDoDebug\n NSLog(@\"sTemp after replace: %@\\n\", sTemp);\n#endif\n\n [aPrintServers replaceObjectAtIndex: i withObject: sTemp];//put back string into array for display in comboBox\n\n#ifdef bDoDebug\n NSLog(@\"aPrintServer: %@\\n\", [aPrintServers objectAtIndex: i]);\n#endif\n\n }\n\n [comboPrintServer removeAllItems];//reset combo box\n [comboPrintServer addItemsWithObjectValues:aPrintServers];\n [comboPrintServer setNumberOfVisibleItems:aPrintServers.count];\n [comboPrintServer selectItemAtIndex:0];\n\n#ifdef bDoDebug\n NSLog(@\"comboPrintServer reloaded with new values.\");\n#endif\n\n\n//release memory we used for LdapTask\n [sLdapQueryCommand release];\n [aLdapQueryArgs release];\n [sLdapOutput release];\n\n [fhLdapTask release];\n\n [pipeLdapTask release];\n// [tskLdapTask release];//strangely can not be explicitely released, might be autorelease anyway\n// [mdLdapTask release];//strangely can not be explicitely released, might be autorelease anyway\n\n [sTemp release];\n\n }\n}\n</code></pre>\n" }, { "answer_id": 21137815, "author": "amar", "author_id": 1206172, "author_profile": "https://Stackoverflow.com/users/1206172", "pm_score": 0, "selected": false, "text": "<p>I have my self come across instance where it was not enough to just separate string by component many tasks such as <br>1) Categorizing token into types<br> 2) Adding new tokens <br> 3)Separating string between custom closures like all words between \"{\" and \"}\"<br>For any such requirements i found <a href=\"http://parsekit.com/\" rel=\"nofollow\">Parse Kit</a> a life saver.</p>\n\n<p>I used it to parse .PGN (prtable gaming notation) files successfully its very fast and lite.</p>\n" }, { "answer_id": 22761154, "author": "Michael Waterfall", "author_id": 106244, "author_profile": "https://Stackoverflow.com/users/106244", "pm_score": 3, "selected": false, "text": "<p>If you're looking to tokenise a string into search terms while preserving \"quoted phrases\", here's an <code>NSString</code> category that respects various types of quote pairs: <code>\"\"</code> <code>''</code> <code>‘’</code> <code>“”</code></p>\n\n<p>Usage:</p>\n\n<pre><code>NSArray *terms = [@\"This is my \\\"search phrase\\\" I want to split\" searchTerms];\n// results in: [\"This\", \"is\", \"my\", \"search phrase\", \"I\", \"want\", \"to\", \"split\"]\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>@interface NSString (Search)\n- (NSArray *)searchTerms;\n@end\n\n@implementation NSString (Search)\n\n- (NSArray *)searchTerms {\n\n // Strip whitespace and setup scanner\n NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];\n NSString *searchString = [self stringByTrimmingCharactersInSet:whitespace];\n NSScanner *scanner = [NSScanner scannerWithString:searchString];\n [scanner setCharactersToBeSkipped:nil]; // we'll handle whitespace ourselves\n\n // A few types of quote pairs to check\n NSDictionary *quotePairs = @{@\"\\\"\": @\"\\\"\",\n @\"'\": @\"'\",\n @\"\\u2018\": @\"\\u2019\",\n @\"\\u201C\": @\"\\u201D\"};\n\n // Scan\n NSMutableArray *results = [[NSMutableArray alloc] init];\n NSString *substring = nil;\n while (scanner.scanLocation &lt; searchString.length) {\n // Check for quote at beginning of string\n unichar unicharacter = [self characterAtIndex:scanner.scanLocation];\n NSString *startQuote = [NSString stringWithFormat:@\"%C\", unicharacter];\n NSString *endQuote = [quotePairs objectForKey:startQuote];\n if (endQuote != nil) { // if it's a valid start quote we'll have an end quote\n // Scan quoted phrase into substring (skipping start &amp; end quotes)\n [scanner scanString:startQuote intoString:nil];\n [scanner scanUpToString:endQuote intoString:&amp;substring];\n [scanner scanString:endQuote intoString:nil];\n } else {\n // Single word that is non-quoted\n [scanner scanUpToCharactersFromSet:whitespace intoString:&amp;substring];\n }\n // Process and add the substring to results\n if (substring) {\n substring = [substring stringByTrimmingCharactersInSet:whitespace];\n if (substring.length) [results addObject:substring];\n }\n // Skip to next word\n [scanner scanCharactersFromSet:whitespace intoString:nil];\n }\n\n // Return non-mutable array\n return results.copy;\n\n}\n\n@end\n</code></pre>\n" }, { "answer_id": 25105997, "author": "Robert", "author_id": 296446, "author_profile": "https://Stackoverflow.com/users/296446", "pm_score": 2, "selected": false, "text": "<p>If you are looking for splitting linguistic feature's of a string (Words, paragraphs, characters, sentences and lines), use string enumeration:</p>\n\n<pre><code>NSString * string = @\" \\n word1! word2,%$?'/word3.word4 \";\n\n[string enumerateSubstringsInRange:NSMakeRange(0, string.length)\n options:NSStringEnumerationByWords\n usingBlock:\n ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {\n NSLog(@\"Substring: '%@'\", substring);\n }];\n\n // Logs:\n // Substring: 'word1'\n // Substring: 'word2'\n // Substring: 'word3'\n // Substring: 'word4' \n</code></pre>\n\n<p>This api works with other languages where spaces are not always the delimiter (e.g. Japanese). Also using <code>NSStringEnumerationByComposedCharacterSequences</code> is the proper way to enumerate over characters, since many non-western characters are more than one byte long.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the best way to tokenize/split a NSString in Objective-C?
Found answer [here](http://borkware.com/quickies/one?topic=NSString): ``` NSString *string = @"oop:ack:bork:greeble:ponies"; NSArray *chunks = [string componentsSeparatedByString: @":"]; ```
259,968
<p>Consider the following file</p> <pre><code>var1 var2 variable3 1 2 3 11 22 33 </code></pre> <p>I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:</p> <pre><code>variable_names = char('var1', 'var2', 'variable3'); </code></pre> <p>I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option. </p> <p>Note that there can be an arbitrary number of variables (columns)</p>
[ { "answer_id": 260016, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 1, "selected": false, "text": "<p>Just use textscan with different format specifiers.</p>\n\n<pre><code>fid = fopen(filename,'r');\nheading = textscan(fid,'%s %s %s',1);\nfgetl(fid); %advance the file pointer one line\ndata = textscan(fid,'%n %n %n');%read the rest of the data\nfclose(fid);\n</code></pre>\n\n<p>In this case 'heading' will be a cell array containing cells with each column heading inside, so you will have to change them into cell array of strings or whatever it is that you want. 'data' will be a cell array containing a numeric array for each column that you read, so you will have to cat them together to make one matrix.</p>\n" }, { "answer_id": 260093, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 2, "selected": false, "text": "<p>If the header is on the first row then </p>\n\n<pre><code>A = dlmread(filename,delimString,2,1);\n</code></pre>\n\n<p>will read the numeric data into the Matrix A.</p>\n\n<p>You can then use </p>\n\n<pre><code>fid = fopen(filename)\nheaderString = fscanf(fid,'%s/n') % reads header data into a string\nfclose(fid)\n</code></pre>\n\n<p>You can then use <em>strtok</em> to split the headerString into a cell array. Is one approach I can think of deal with an unknown number of columns</p>\n\nEdit\n\n<p>fixed fscanf function call</p>\n" }, { "answer_id": 263943, "author": "Adam Holmberg", "author_id": 20688, "author_profile": "https://Stackoverflow.com/users/20688", "pm_score": 4, "selected": true, "text": "<p>I suggest <strong>importdata</strong> for operations like this:</p>\n\n<pre><code>d = importdata('filename.txt');\n</code></pre>\n\n<p>The return is a struct with the numerical fields in a member called 'data', and the column headers in a field called 'colheaders'.</p>\n\n<p>Another useful interface for importing manipulating data like these is the 'dataset' class available in the Statistics Toolbox.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/259968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17523/" ]
Consider the following file ``` var1 var2 variable3 1 2 3 11 22 33 ``` I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to: ``` variable_names = char('var1', 'var2', 'variable3'); ``` I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option. Note that there can be an arbitrary number of variables (columns)
I suggest **importdata** for operations like this: ``` d = importdata('filename.txt'); ``` The return is a struct with the numerical fields in a member called 'data', and the column headers in a field called 'colheaders'. Another useful interface for importing manipulating data like these is the 'dataset' class available in the Statistics Toolbox.
260,010
<p>If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. <code>SELECT * FROM table WHERE column LIKE %news%</code>), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a teaser, if you will.</p>
[ { "answer_id": 260023, "author": "Rockcoder", "author_id": 5290, "author_profile": "https://Stackoverflow.com/users/5290", "pm_score": 2, "selected": false, "text": "<p>You can use substring function in a SELECT part. Something like:</p>\n\n<pre><code>SELECT SUBSTRING(column, 1,20) FROM table WHERE column LIKE %news%\n</code></pre>\n\n<p>This will return the first 20 characters from column <em>column</em></p>\n" }, { "answer_id": 260025, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>If you are using MSSQL you can perform all kinds VB-like of substring functions as part of your query.</p>\n" }, { "answer_id": 260029, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 4, "selected": true, "text": "<pre><code>select substring(column,\n CHARINDEX ('news',lower(column))-10,\n 20)\nFROM table \nWHERE column LIKE %news%\n</code></pre>\n\n<p>basically substring the column starting 10 characters before where the word 'news' is and continuing for 20.</p>\n\n<p>Edit: You'll need to make sure that 'news' isn't in the first 10 characters and adjust the start position accordingly.</p>\n" }, { "answer_id": 260031, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 1, "selected": false, "text": "<p>I had the same problem, I ended up loading the whole field into C#, then re-searched the text for the search string, then selected x characters either side.</p>\n\n<p>This will work fine for LIKE, but not full text queries which use FORMS OF INFLECTION because that may match \"women\" when you search for \"woman\".</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. `SELECT * FROM table WHERE column LIKE %news%`), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a teaser, if you will.
``` select substring(column, CHARINDEX ('news',lower(column))-10, 20) FROM table WHERE column LIKE %news% ``` basically substring the column starting 10 characters before where the word 'news' is and continuing for 20. Edit: You'll need to make sure that 'news' isn't in the first 10 characters and adjust the start position accordingly.
260,040
<p>I want to make a transparent dialog. I capture the OnCtlColor message in a CDialog derived class...this is the code:</p> <pre><code>HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if(bSetBkTransparent_) { pDC-&gt;SetBkMode(TRANSPARENT); hbr = (HBRUSH)GetStockObject(NULL_BRUSH); } return hbr; } </code></pre> <p>It works fine for all the controls but the group-box (CStatic). All the labels (CStatic) are been painted with a transparent text background but the text of the group box it is not transparent.</p> <p>I already googled for this but I didn't find a solutions. Does anybody know how to make a real transparent group-box?</p> <p>By the way, I am working in Windows XP. And I don't want to fully draw the control to avoid having to change the code if the application is migrated to another OS.</p> <p>Thanks,</p> <p>Javier</p> <p>Note: I finally changed the dialog so that I don't need to make it transparent. Anyway, I add this information because maybe someone is still trying to do it. The groupbox isn't a CStatic but a CButton (I know this is not new). I changed the Windows XP theme to Windows classic and then the groupbox backgraund was transparent. The bad new is that in this case the frame line gets visible beneath the text...so if someone is following this approach I think maybe he/she would better follow the Adzm's advice. </p>
[ { "answer_id": 269817, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>You have two options.</p>\n\n<p>You can not use Common Controls v6 (the XP-Styled controls), which will make your app lose the fanciness of newer windows versions. However IIRC the groupbox will respect the CTLCOLOR issue. If you are not using that anyway, and it is still not respecting your color, then you only have one option...</p>\n\n<p>Which is to draw it yourself. I know you said you don't want to, but sometimes you have to. Thankfully a group box is a very simple control to draw. This page has an example for drawing a classic-style group box: <a href=\"http://www.codeguru.com/cpp/controls/controls/groupbox/article.php/c2273/\" rel=\"nofollow noreferrer\">http://www.codeguru.com/cpp/controls/controls/groupbox/article.php/c2273/</a> You can also draw it very simply using the UxTheme libraries that come with XP+.</p>\n\n<p>If the application will be migrated to another OS, you will have plenty to deal with migrating over an MFC application in general. If that is your goal, then you should really look into developing with a cross-platform UI toolkit.</p>\n" }, { "answer_id": 12761919, "author": "Helmut", "author_id": 942715, "author_profile": "https://Stackoverflow.com/users/942715", "pm_score": 0, "selected": false, "text": "<p>Simply set the WS_EX_TRANSPARENT extended window style for the group box.</p>\n" }, { "answer_id": 68690192, "author": "Mecanik", "author_id": 6583298, "author_profile": "https://Stackoverflow.com/users/6583298", "pm_score": 0, "selected": false, "text": "<p>I knows this is a 12 years old question, but it frustrates me that nobody answered it correctly so far.</p>\n<p>All you have to do is handle <a href=\"https://learn.microsoft.com/en-us/windows/win32/controls/wm-ctlcolorstatic\" rel=\"nofollow noreferrer\">WM_CTLCOLORSTATIC</a>:</p>\n<pre><code>case WM_CTLCOLORSTATIC: \n{\n HDC hDC = (HDC)wParam;\n SetTextColor(hDC, RGB(255, 255, 255));\n SetBkMode(hDC, TRANSPARENT);\n return (INT_PTR)GetStockObject(HOLLOW_BRUSH);\n}\nbreak;\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14053/" ]
I want to make a transparent dialog. I capture the OnCtlColor message in a CDialog derived class...this is the code: ``` HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if(bSetBkTransparent_) { pDC->SetBkMode(TRANSPARENT); hbr = (HBRUSH)GetStockObject(NULL_BRUSH); } return hbr; } ``` It works fine for all the controls but the group-box (CStatic). All the labels (CStatic) are been painted with a transparent text background but the text of the group box it is not transparent. I already googled for this but I didn't find a solutions. Does anybody know how to make a real transparent group-box? By the way, I am working in Windows XP. And I don't want to fully draw the control to avoid having to change the code if the application is migrated to another OS. Thanks, Javier Note: I finally changed the dialog so that I don't need to make it transparent. Anyway, I add this information because maybe someone is still trying to do it. The groupbox isn't a CStatic but a CButton (I know this is not new). I changed the Windows XP theme to Windows classic and then the groupbox backgraund was transparent. The bad new is that in this case the frame line gets visible beneath the text...so if someone is following this approach I think maybe he/she would better follow the Adzm's advice.
You have two options. You can not use Common Controls v6 (the XP-Styled controls), which will make your app lose the fanciness of newer windows versions. However IIRC the groupbox will respect the CTLCOLOR issue. If you are not using that anyway, and it is still not respecting your color, then you only have one option... Which is to draw it yourself. I know you said you don't want to, but sometimes you have to. Thankfully a group box is a very simple control to draw. This page has an example for drawing a classic-style group box: <http://www.codeguru.com/cpp/controls/controls/groupbox/article.php/c2273/> You can also draw it very simply using the UxTheme libraries that come with XP+. If the application will be migrated to another OS, you will have plenty to deal with migrating over an MFC application in general. If that is your goal, then you should really look into developing with a cross-platform UI toolkit.
260,056
<p>I'm trying to figure out if there's a reasonably efficient way to perform a lookup in a dictionary (or a hash, or a map, or whatever your favorite language calls it) where the keys are regular expressions and strings are looked up against the set of keys. For example (in Python syntax):</p> <pre><code>&gt;&gt;&gt; regex_dict = { re.compile(r'foo.') : 12, re.compile(r'^FileN.*$') : 35 } &gt;&gt;&gt; regex_dict['food'] 12 &gt;&gt;&gt; regex_dict['foot in my mouth'] 12 &gt;&gt;&gt; regex_dict['FileNotFoundException: file.x does not exist'] 35 </code></pre> <p>(Obviously the above example won't work as written in Python, but that's the sort of thing I'd like to be able to do.)</p> <p>I can think of a naive way to implement this, in which I iterate over all of the keys in the dictionary and try to match the passed in string against them, but then I lose the O(1) lookup time of a hash map and instead have O(n), where n is the number of keys in my dictionary. This is potentially a big deal, as I expect this dictionary to grow very large, and I will need to search it over and over again (actually I'll need to iterate over it for every line I read in a text file, and the files can be hundreds of megabytes in size).</p> <p>Is there a way to accomplish this, without resorting to O(n) efficiency?</p> <p>Alternatively, if you know of a way to accomplish this sort of a lookup in a database, that would be great, too.</p> <p>(Any programming language is fine -- I'm using Python, but I'm more interested in the data structures and algorithms here.)</p> <p>Someone pointed out that more than one match is possible, and that's absolutely correct. Ideally in this situation I'd like to return a list or tuple containing all of the matches. I'd settle for the first match, though.</p> <p>I can't see O(1) being possible in that scenario; I'd settle for anything less than O(n), though. Also, the underlying data structure could be anything, but the basic behavior I'd like is what I've written above: lookup a string, and return the value(s) that match the regular expression keys.</p>
[ { "answer_id": 260075, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "<p>The fundamental assumption is flawed, I think. you can't map hashes to regular expressions. </p>\n" }, { "answer_id": 260077, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>This is not possible to do with a regular hash table in any language. You'll either have to iterate through the entire keyset, attempting to match the key to your regex, or use a different data structure.</p>\n\n<p>You should choose a data structure that is appropriate to the problem you're trying to solve. If you have to match against any arbitrary regular expression, I don't know of a good solution. If the class of regular expressions you'll be using is more restrictive, you might be able to use a data structure such as a <a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">trie</a> or <a href=\"http://en.wikipedia.org/wiki/Suffix_tree\" rel=\"nofollow noreferrer\">suffix tree</a>.</p>\n" }, { "answer_id": 260079, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 0, "selected": false, "text": "<p>I don't think it's even theoretically possible. What happens if someone passes in a string that matches more than 1 regular expression. </p>\n\n<p>For example, what would happen if someone did:</p>\n\n<pre><code>&gt;&gt;&gt; regex_dict['FileNfoo']\n</code></pre>\n\n<p>How can something like that possibly be O(1)?</p>\n" }, { "answer_id": 260085, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "<p>What happens if you have a dictionary such as</p>\n\n<pre><code>regex_dict = { re.compile(\"foo.*\"): 5, re.compile(\"f.*\"): 6 }\n</code></pre>\n\n<p>In this case <code>regex_dict[\"food\"]</code> could legitimately return either 5 or 6.</p>\n\n<p>Even ignoring that problem, there's probably no way to do this efficiently with the regex module. Instead, what you'd need is an internal directed graph or tree structure.</p>\n" }, { "answer_id": 260114, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>In the general case, what you need is a lexer generator. It takes a bunch of regular expressions and compiles them into a recognizer. \"lex\" will work if you are using C. I have never used a lexer generator in Python, but there seem to be a few to choose from. Google shows <a href=\"http://www.dabeaz.com/ply/\" rel=\"nofollow noreferrer\">PLY</a>, <a href=\"http://www.lava.net/~newsham/pyggy/\" rel=\"nofollow noreferrer\">PyGgy</a> and <a href=\"http://margolis-yateley.org.uk/python/various/index.php\" rel=\"nofollow noreferrer\">PyLexer</a>.</p>\n\n<p>If the regular expressions all resemble each other in some way, then you may be able to take some shortcuts. We would need to know more about the ultimate problem that you are trying to solve in order to come up with any suggestions. Can you share some sample regular expressions and some sample data?</p>\n\n<p>Also, how many regular expressions are you dealing with here? Are you sure that the naive approach <em>won't</em> work? As Rob Pike <a href=\"http://www.lysator.liu.se/c/pikestyle.html\" rel=\"nofollow noreferrer\">once said</a>, \"Fancy algorithms are slow when n is small, and n is usually small.\" Unless you have thousands of regular expressions, and thousands of things to match against them, and this is an interactive application where a user is waiting for you, you may be best off just doing it the easy way and looping through the regular expressions.</p>\n" }, { "answer_id": 260120, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "<p>As other respondents have pointed out, it's not possible to do this with a hash table in constant time.</p>\n\n<p>One approximation that might help is to use a technique called <a href=\"http://en.wikipedia.org/wiki/Ngram#n-grams_for_approximate_matching\" rel=\"nofollow noreferrer\">\"n-grams\"</a>. Create an inverted index from n-character chunks of a word to the entire word. When given a pattern, split it into n-character chunks, and use the index to compute a scored list of matching words.</p>\n\n<p>Even if you can't accept an approximation, in most cases this would still provide an accurate filtering mechanism so that you don't have to apply the regex to every key.</p>\n" }, { "answer_id": 260421, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 0, "selected": false, "text": "<p>It <em>may</em> be possible to get the regex compiler to do most of the work for you by concatenating the search expressions into one big regexp, separated by \"|\". A clever regex compiler might search for commonalities in the alternatives in such a case, and devise a more efficient search strategy than simply checking each one in turn. But I have no idea whether there are compilers which will do that.</p>\n" }, { "answer_id": 260591, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 0, "selected": false, "text": "<p>It really depends on what these regexes look like. If you don't have a lot regexes that will match almost anything like '<code>.*</code>' or '<code>\\d+</code>', and instead you have regexes that <em>contains</em> mostly words and phrases or any fixed patterns longer than 4 characters (e.g.'<code>a*b*c</code>' in <code>^\\d+a\\*b\\*c:\\s+\\w+</code>) , as in your examples. You can do this common trick that scales well to millions of regexes:</p>\n\n<p>Build a inverted index for the regexes (rabin-karp-hash('fixed pattern') -> list of regexes containing 'fixed pattern'). Then at matching time, using Rabin-Karp hashing to compute sliding hashes and look up the inverted index, advancing one character at a time. You now have O(1) look-up for inverted-index non-matches and a reasonable O(k) time for matches, k is the average length of the lists of regexes in the inverted index. k can be quite small (less than 10) for many applications. The quality (false positive means bigger k, false negative means missed matches) of the inverted index depends on how well the indexer understands the regex syntax. If the regexes are generated by human experts, they can provide hints for contained fixed patterns as well.</p>\n" }, { "answer_id": 260886, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "<p>There is a Perl module that does just this <a href=\"http://search.cpan.org/~davecross/Tie-Hash-Regex-1.02/lib/Tie/Hash/Regex.pm\" rel=\"nofollow noreferrer\">Tie::Hash::Regex</a>.</p>\n\n<pre><code>use Tie::Hash::Regex;\nmy %h;\n\ntie %h, 'Tie::Hash::Regex';\n\n$h{key} = 'value';\n$h{key2} = 'another value';\n$h{stuff} = 'something else';\n\nprint $h{key}; # prints 'value'\nprint $h{2}; # prints 'another value'\nprint $h{'^s'}; # prints 'something else'\n\nprint tied(%h)-&gt;FETCH(k); # prints 'value' and 'another value'\n\ndelete $h{k}; # deletes $h{key} and $h{key2};\n</code></pre>\n" }, { "answer_id": 260942, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 1, "selected": false, "text": "<p>A special case of this problem came up in the 70s AI languages oriented around deductive databases. The keys in these databases could be patterns with variables -- like regular expressions without the * or | operators. They tended to use fancy extensions of trie structures for indexes. See krep*.lisp in Norvig's <a href=\"http://norvig.com/paip/\" rel=\"nofollow noreferrer\">Paradigms of AI Programming</a> for the general idea.</p>\n" }, { "answer_id": 261070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This is definitely possible, as long as you're using 'real' regular expressions. A textbook regular expression is something that can be recognized by a <a href=\"http://en.wikipedia.org/wiki/Deterministic_finite_state_machine\" rel=\"nofollow noreferrer\">deterministic finite state machine</a>, which primarily means you can't have back-references in there.</p>\n\n<p>There's a property of regular languages that \"the union of two regular languages is regular\", meaning that you can recognize an arbitrary number of regular expressions at once with a single state machine. The state machine runs in O(1) time with respect to the number of expressions (it runs in O(n) time with respect to the length of the input string, but hash tables do too).</p>\n\n<p>Once the state machine completes you'll know which expressions matched, and from there it's easy to look up values in O(1) time.</p>\n" }, { "answer_id": 261755, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 1, "selected": false, "text": "<p>If you have a small set of possible inputs, you can cache the matches as they appear in a second dict and get O(1) for the cached values.</p>\n\n<p>If the set of possible inputs is too big to cache but not infinite, either, you can just keep the last N matches in the cache (check Google for \"LRU maps\" - least recently used).</p>\n\n<p>If you can't do this, you can try to chop down the number of regexps you have to try by checking a prefix or somesuch.</p>\n" }, { "answer_id": 266620, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 3, "selected": true, "text": "<p>What you want to do is very similar to what is supported by xrdb. They only support a fairly minimal notion of globbing however.</p>\n\n<p>Internally you can implement a larger family of regular languages than theirs by storing your regular expressions as a character trie. </p>\n\n<ul>\n<li>single characters just become trie nodes. </li>\n<li>.'s become wildcard insertions covering all children of the current trie node. </li>\n<li>*'s become back links in the trie to node at the start of the previous item. </li>\n<li>[a-z] ranges insert the same subsequent child nodes repeatedly under each of the characters in the range. With care, while inserts/updates may be somewhat expensive the search can be linear in the size of the string. With some placeholder stuff the common combinatorial explosion cases can be kept under control. </li>\n<li>(foo)|(bar) nodes become multiple insertions</li>\n</ul>\n\n<p>This doesn't handle regexes that occur at arbitrary points in the string, but that can be modeled by wrapping your regex with .* on either side.</p>\n\n<p>Perl has a couple of Text::Trie -like modules you can raid for ideas. (Heck I think I even wrote one of them way back when)</p>\n" }, { "answer_id": 267747, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I created this exact data structure for a project once. I implemented it naively, as you suggested. I did make two immensely helpful optimizations, which may or may not be feasible for you, depending on the size of your data:</p>\n\n<ul>\n<li>Memoizing the hash lookups</li>\n<li>Pre-seeding the the memoization table (not sure what to call this... warming up the cache?)</li>\n</ul>\n\n<p>To avoid the problem of multiple keys matching the input, I gave each regex key a priority and the highest priority was used.</p>\n" }, { "answer_id": 816047, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>What about the following:</p>\n\n<pre><code>class redict(dict):\ndef __init__(self, d):\n dict.__init__(self, d)\n\ndef __getitem__(self, regex):\n r = re.compile(regex)\n mkeys = filter(r.match, self.keys())\n for i in mkeys:\n yield dict.__getitem__(self, i)\n</code></pre>\n\n<p>It's basically a subclass of the dict type in Python. With this you can supply a regular expression as a key, and the values of all keys that match this regex are returned in an iterable fashion using yield.</p>\n\n<p>With this you can do the following:</p>\n\n<pre><code>&gt;&gt;&gt; keys = [\"a\", \"b\", \"c\", \"ab\", \"ce\", \"de\"]\n&gt;&gt;&gt; vals = range(0,len(keys))\n&gt;&gt;&gt; red = redict(zip(keys, vals))\n&gt;&gt;&gt; for i in red[r\"^.e$\"]:\n... print i\n... \n5\n4\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 5835497, "author": "TOTEM_MOTORIST", "author_id": 731518, "author_profile": "https://Stackoverflow.com/users/731518", "pm_score": 0, "selected": false, "text": "<p>Ok, I have a very similar requirements, I have a lot of lines of different syntax, basically remark lines and lines with some codes for to use in a process of smart-card format, also, descriptor lines of keys and secret codes, in every case, I think that the \"model\" pattern/action is the beast approach for to recognize and to process a lot of lines.<br>\nI'm using <code>C++/CLI</code> for to develop my assembly named <code>LanguageProcessor.dll</code>, the core of this library is a lex_rule class that basically contains :</p>\n\n<ul>\n<li>a Regex member</li>\n<li>an event member </li>\n</ul>\n\n<p>The constructor loads the regex string and call the necessary codes for to build the event on the fly using <code>DynamicMethod</code>, <code>Emit</code> and <code>Reflexion</code>... also into the assembly exists other class like meta and object that constructs ans instantiates the objects by the simple names of the publisher and the receiver class, receiver class provides the action handlers for each rule matched. </p>\n\n<p>Late, I have a class named <code>fasterlex_engine</code> that build a Dictionary<code>&lt;Regex, action_delegate&gt;</code>\nthat load the definitions from an array for to run.</p>\n\n<p>The project is in advanced point but I'm still building, today. I will try to enhance the performance of running surrounding the sequential access to every pair foreach line input, thru using some mechanism of lookup the dictionary directly using the regexp like:</p>\n\n<pre><code>map_rule[gcnew Regex(\"[a-zA-Z]\")];\n</code></pre>\n\n<p>Here, some of segments of my code:</p>\n\n<pre><code>public ref class lex_rule: ILexRule\n{\nprivate:\n Exception ^m_exception;\n Regex ^m_pattern;\n\n //BACKSTORAGE delegates, esto me lo aprendi asiendo la huella.net de m*e*da JEJE\n yy_lexical_action ^m_yy_lexical_action; \n yy_user_action ^m_yy_user_action;\n\npublic: \n virtual property String ^short_id; \nprivate:\n void init(String ^_short_id, String ^well_formed_regex);\npublic:\n\n lex_rule();\n lex_rule(String ^_short_id,String ^well_formed_regex);\n virtual event yy_lexical_action ^YY_RULE_MATCHED\n {\n virtual void add(yy_lexical_action ^_delegateHandle)\n {\n if(nullptr==m_yy_lexical_action)\n m_yy_lexical_action=_delegateHandle;\n }\n virtual void remove(yy_lexical_action ^)\n {\n m_yy_lexical_action=nullptr;\n }\n\n virtual long raise(String ^id_rule, String ^input_string, String ^match_string, int index) \n {\n long lReturn=-1L;\n if(m_yy_lexical_action)\n lReturn=m_yy_lexical_action(id_rule,input_string, match_string, index);\n return lReturn;\n }\n }\n};\n</code></pre>\n\n<p>Now the fasterlex_engine class that execute a lot of pattern/action pair:</p>\n\n<pre><code>public ref class fasterlex_engine \n{\nprivate: \n Dictionary&lt;String^,ILexRule^&gt; ^m_map_rules;\npublic:\n fasterlex_engine();\n fasterlex_engine(array&lt;String ^,2&gt;^defs);\n Dictionary&lt;String ^,Exception ^&gt; ^load_definitions(array&lt;String ^,2&gt; ^defs);\n void run();\n};\n</code></pre>\n\n<p>AND FOR TO DECORATE THIS TOPIC..some code of my cpp file:</p>\n\n<p>this code creates a constructor invoker by parameter sign</p>\n\n<pre><code>inline Exception ^object::builder(ConstructorInfo ^target, array&lt;Type^&gt; ^args)\n{\ntry\n{\n DynamicMethod ^dm=gcnew DynamicMethod(\n \"dyna_method_by_totem_motorist\",\n Object::typeid,\n args,\n target-&gt;DeclaringType);\n ILGenerator ^il=dm-&gt;GetILGenerator();\n il-&gt;Emit(OpCodes::Ldarg_0);\n il-&gt;Emit(OpCodes::Call,Object::typeid-&gt;GetConstructor(Type::EmptyTypes)); //invoca a constructor base\n il-&gt;Emit(OpCodes::Ldarg_0);\n il-&gt;Emit(OpCodes::Ldarg_1);\n il-&gt;Emit(OpCodes::Newobj, target); //NewObj crea el objeto e invoca al constructor definido en target\n il-&gt;Emit(OpCodes::Ret);\n method_handler=(method_invoker ^) dm-&gt;CreateDelegate(method_invoker::typeid);\n}\ncatch (Exception ^e)\n{\n return e;\n}\nreturn nullptr;\n</code></pre>\n\n<p>}</p>\n\n<p>This code attach an any handler function (static or not) for to deal with a callback raised by matching of a input string</p>\n\n<pre><code>Delegate ^connection_point::hook(String ^receiver_namespace,String ^receiver_class_name, String ^handler_name)\n{\nDelegate ^d=nullptr;\nif(connection_point::waitfor_hook&lt;=m_state) // si es 0,1,2 o mas =&gt; intenta hookear\n{ \n try \n {\n Type ^tmp=meta::_class(receiver_namespace+\".\"+receiver_class_name);\n m_handler=tmp-&gt;GetMethod(handler_name);\n m_receiver_object=Activator::CreateInstance(tmp,false); \n\n d=m_handler-&gt;IsStatic?\n Delegate::CreateDelegate(m_tdelegate,m_handler):\n Delegate::CreateDelegate(m_tdelegate,m_receiver_object,m_handler);\n\n m_add_handler=m_connection_point-&gt;GetAddMethod();\n array&lt;Object^&gt; ^add_handler_args={d};\n m_add_handler-&gt;Invoke(m_publisher_object, add_handler_args);\n ++m_state;\n m_exception_flag=false;\n }\n catch(Exception ^e)\n {\n m_exception_flag=true;\n throw gcnew Exception(e-&gt;ToString()) ;\n }\n}\nreturn d; \n}\n</code></pre>\n\n<p>finally the code that call the lexer engine: </p>\n\n<pre><code>array&lt;String ^,2&gt; ^defs=gcnew array&lt;String^,2&gt; {/* shortID pattern namespc clase fun*/\n {\"LETRAS\", \"[A-Za-z]+\" ,\"prueba\", \"manejador\", \"procesa_directriz\"},\n {\"INTS\", \"[0-9]+\" ,\"prueba\", \"manejador\", \"procesa_comentario\"},\n {\"REM\", \"--[^\\\\n]*\" ,\"prueba\", \"manejador\", \"nullptr\"}\n }; //[3,5]\n\n//USO EL IDENTIFICADOR ESPECIAL \"nullptr\" para que el sistema asigne el proceso del evento a un default que realice nada\nfasterlex_engine ^lex=gcnew fasterlex_engine();\nDictionary&lt;String ^,Exception ^&gt; ^map_error_list=lex-&gt;load_definitions(defs);\nlex-&gt;run();\n</code></pre>\n" }, { "answer_id": 10190682, "author": "DangerMouse", "author_id": 205347, "author_profile": "https://Stackoverflow.com/users/205347", "pm_score": 0, "selected": false, "text": "<p>The problem has nothing to do with regular expressions - you'd have the same problem with a dictionary with keys as functions of lambdas. So the problem you face is figuring is there a way of classifying your functions to figure which will return true or not and that isn't a search problem because f(x) is not known in general before hand.</p>\n\n<p>Distributed programming or caching answer sets assuming there are common values of x may help.</p>\n\n<p>-- DM</p>\n" }, { "answer_id": 16875839, "author": "rptb1", "author_id": 425078, "author_profile": "https://Stackoverflow.com/users/425078", "pm_score": 2, "selected": false, "text": "<p>Here's an efficient way to do it by combining the keys into a single compiled regexp, and so not requiring any looping over key patterns. It abuses the <code>lastindex</code> to find out which key matched. (It's a shame regexp libraries don't let you tag the terminal state of the DFA that a regexp is compiled to, or this would be less of a hack.)</p>\n\n<p>The expression is compiled once, and will produce a fast matcher that doesn't have to search sequentially. Common prefixes are compiled together in the DFA, so each character in the key is matched once, not many times, unlike some of the other suggested solutions. You're effectively compiling a mini lexer for your keyspace.</p>\n\n<p>This map isn't extensible (can't define new keys) without recompiling the regexp, but it can be handy for some situations.</p>\n\n<pre><code># Regular expression map\n# Abuses match.lastindex to figure out which key was matched\n# (i.e. to emulate extracting the terminal state of the DFA of the regexp engine)\n# Mostly for amusement.\n# Richard Brooksby, Ravenbrook Limited, 2013-06-01\n\nimport re\n\nclass ReMap(object):\n\n def __init__(self, items):\n if not items:\n items = [(r'epsilon^', None)] # Match nothing\n key_patterns = []\n self.lookup = {}\n index = 1\n for key, value in items:\n # Ensure there are no capturing parens in the key, because\n # that would mess up match.lastindex\n key_patterns.append('(' + re.sub(r'\\((?!\\?:)', '(?:', key) + ')')\n self.lookup[index] = value\n index += 1\n self.keys_re = re.compile('|'.join(key_patterns))\n\n def __getitem__(self, key):\n m = self.keys_re.match(key)\n if m:\n return self.lookup[m.lastindex]\n raise KeyError(key)\n\nif __name__ == '__main__':\n remap = ReMap([(r'foo.', 12), (r'FileN.*', 35)])\n print remap['food']\n print remap['foot in my mouth']\n print remap['FileNotFoundException: file.x does not exist']\n</code></pre>\n" }, { "answer_id": 16878309, "author": "Nick Barnes", "author_id": 2444191, "author_profile": "https://Stackoverflow.com/users/2444191", "pm_score": 2, "selected": false, "text": "<p>@rptb1 you don't have to avoid capturing groups, because you can use re.groups to count them. Like this:</p>\n\n<pre><code># Regular expression map\n# Abuses match.lastindex to figure out which key was matched\n# (i.e. to emulate extracting the terminal state of the DFA of the regexp engine)\n# Mostly for amusement.\n# Richard Brooksby, Ravenbrook Limited, 2013-06-01\n\nimport re\n\nclass ReMap(object):\n def __init__(self, items):\n if not items:\n items = [(r'epsilon^', None)] # Match nothing\n self.re = re.compile('|'.join('('+k+')' for (k,v) in items))\n self.lookup = {}\n index = 1\n for key, value in items:\n self.lookup[index] = value\n index += re.compile(key).groups + 1\n\n def __getitem__(self, key):\n m = self.re.match(key)\n if m:\n return self.lookup[m.lastindex]\n raise KeyError(key)\n\ndef test():\n remap = ReMap([(r'foo.', 12),\n (r'.*([0-9]+)', 99),\n (r'FileN.*', 35),\n ])\n print remap['food']\n print remap['foot in my mouth']\n print remap['FileNotFoundException: file.x does not exist']\n print remap['there were 99 trombones']\n print remap['food costs $18']\n print remap['bar']\n\nif __name__ == '__main__':\n test()\n</code></pre>\n\n<p>Sadly very few RE engines actually compile the regexps down to machine code, although it's not especially hard to do. I suspect there's an order of magnitude performance improvement waiting for someone to make a really good RE JIT library.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33775/" ]
I'm trying to figure out if there's a reasonably efficient way to perform a lookup in a dictionary (or a hash, or a map, or whatever your favorite language calls it) where the keys are regular expressions and strings are looked up against the set of keys. For example (in Python syntax): ``` >>> regex_dict = { re.compile(r'foo.') : 12, re.compile(r'^FileN.*$') : 35 } >>> regex_dict['food'] 12 >>> regex_dict['foot in my mouth'] 12 >>> regex_dict['FileNotFoundException: file.x does not exist'] 35 ``` (Obviously the above example won't work as written in Python, but that's the sort of thing I'd like to be able to do.) I can think of a naive way to implement this, in which I iterate over all of the keys in the dictionary and try to match the passed in string against them, but then I lose the O(1) lookup time of a hash map and instead have O(n), where n is the number of keys in my dictionary. This is potentially a big deal, as I expect this dictionary to grow very large, and I will need to search it over and over again (actually I'll need to iterate over it for every line I read in a text file, and the files can be hundreds of megabytes in size). Is there a way to accomplish this, without resorting to O(n) efficiency? Alternatively, if you know of a way to accomplish this sort of a lookup in a database, that would be great, too. (Any programming language is fine -- I'm using Python, but I'm more interested in the data structures and algorithms here.) Someone pointed out that more than one match is possible, and that's absolutely correct. Ideally in this situation I'd like to return a list or tuple containing all of the matches. I'd settle for the first match, though. I can't see O(1) being possible in that scenario; I'd settle for anything less than O(n), though. Also, the underlying data structure could be anything, but the basic behavior I'd like is what I've written above: lookup a string, and return the value(s) that match the regular expression keys.
What you want to do is very similar to what is supported by xrdb. They only support a fairly minimal notion of globbing however. Internally you can implement a larger family of regular languages than theirs by storing your regular expressions as a character trie. * single characters just become trie nodes. * .'s become wildcard insertions covering all children of the current trie node. * \*'s become back links in the trie to node at the start of the previous item. * [a-z] ranges insert the same subsequent child nodes repeatedly under each of the characters in the range. With care, while inserts/updates may be somewhat expensive the search can be linear in the size of the string. With some placeholder stuff the common combinatorial explosion cases can be kept under control. * (foo)|(bar) nodes become multiple insertions This doesn't handle regexes that occur at arbitrary points in the string, but that can be modeled by wrapping your regex with .\* on either side. Perl has a couple of Text::Trie -like modules you can raid for ideas. (Heck I think I even wrote one of them way back when)
260,064
<p>Published Date returned from Twitter Search API Atom Feed as 2008-11-03T21:30:06Z which needs to be converted to "X seconds/minutes/hours/days ago" for showing how long ago twitter messages were posted.</p> <p>Think this can be done with php date() function using DATE_ATOM value?</p>
[ { "answer_id": 260092, "author": "Dave Marshall", "author_id": 1248, "author_profile": "https://Stackoverflow.com/users/1248", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://uk3.php.net/strtotime\" rel=\"nofollow noreferrer\">strtotime</a> will handle that date format, giving you a unix timestamp. You can then follow the algorithms on <a href=\"https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time\">How do I calculate relative time?</a> to get your result.</p>\n" }, { "answer_id": 260199, "author": "Jack", "author_id": 24998, "author_profile": "https://Stackoverflow.com/users/24998", "pm_score": 3, "selected": true, "text": "<pre><code>function time_since($your_timestamp) {\n $unix_timestamp = strtotime($your_timestamp);\n $seconds = time() - $unix_timestamp;\n $minutes = 0;\n $hours = 0;\n $days = 0;\n $weeks = 0;\n $months = 0;\n $years = 0;\n if ( $seconds == 0 ) $seconds = 1;\n if ( $seconds&gt; 60 ) {\n $minutes = $seconds/60;\n } else {\n return add_s($seconds,'second');\n }\n\n if ( $minutes &gt;= 60 ) {\n $hours = $minutes/60;\n } else {\n return add_s($minutes,'minute');\n }\n\n if ( $hours &gt;= 24) {\n $days = $hours/24;\n } else {\n return add_s($hours,'hour');\n }\n\n if ( $days &gt;= 7 ) {\n $weeks = $days/7;\n } else {\n return add_s($days,'day');\n }\n\n if ( $weeks &gt;= 4 ) {\n $months = $weeks/4;\n } else {\n return add_s($weeks,'week');\n }\n\n if ( $months&gt;= 12 ) {\n $years = $months/12;\n return add_s($years,'year');\n } else {\n return add_s($months,'month');\n }\n\n}\n\nfunction add_s($num,$word) {\n $num = floor($num);\n if ( $num == 1 ) {\n return $num.' '.$word.' ago';\n } else {\n return $num.' '.$word.'s ago';\n }\n}\n\necho time_since('2008-11-03T21:30:06Z');\n</code></pre>\n" }, { "answer_id": 14595699, "author": "John Conde", "author_id": 250259, "author_profile": "https://Stackoverflow.com/users/250259", "pm_score": 0, "selected": false, "text": "<p>This is easy using the <a href=\"http://www.php.net/manual/en/book.datetime.php\" rel=\"nofollow\">DateTime</a> functionality introduced in PHP 5.2:</p>\n\n<pre><code>$posted = new DateTime('2008-11-03T21:30:06Z');\n$now = new DateTime();\n$interval = $posted-&gt;diff($now);\necho $interval-&gt;format('%a days'); // You can change this to be whatever format you like\n</code></pre>\n\n<p><a href=\"http://codepad.viper-7.com/qFgHZM\" rel=\"nofollow\">Example</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Published Date returned from Twitter Search API Atom Feed as 2008-11-03T21:30:06Z which needs to be converted to "X seconds/minutes/hours/days ago" for showing how long ago twitter messages were posted. Think this can be done with php date() function using DATE\_ATOM value?
``` function time_since($your_timestamp) { $unix_timestamp = strtotime($your_timestamp); $seconds = time() - $unix_timestamp; $minutes = 0; $hours = 0; $days = 0; $weeks = 0; $months = 0; $years = 0; if ( $seconds == 0 ) $seconds = 1; if ( $seconds> 60 ) { $minutes = $seconds/60; } else { return add_s($seconds,'second'); } if ( $minutes >= 60 ) { $hours = $minutes/60; } else { return add_s($minutes,'minute'); } if ( $hours >= 24) { $days = $hours/24; } else { return add_s($hours,'hour'); } if ( $days >= 7 ) { $weeks = $days/7; } else { return add_s($days,'day'); } if ( $weeks >= 4 ) { $months = $weeks/4; } else { return add_s($weeks,'week'); } if ( $months>= 12 ) { $years = $months/12; return add_s($years,'year'); } else { return add_s($months,'month'); } } function add_s($num,$word) { $num = floor($num); if ( $num == 1 ) { return $num.' '.$word.' ago'; } else { return $num.' '.$word.'s ago'; } } echo time_since('2008-11-03T21:30:06Z'); ```
260,094
<p>I've been developing a few JSF applications lately and am disturbed with the inconsistency in the web component APIs. </p> <p>I've noticed that there is extremely unpredictable behavior when calling .getValue() or .getSubmittedValue() on a JSF component object in server side code. Sometimes when I call .getValue() on a drop down list box, I've noticed that I get the value as it was BEFORE I selected my value (so the value from the last page refresh), of which .getSubmittedValue() gets me the correct value, as such:</p> <pre><code>UIInput name = new UIInput(); // This is the control I have in a bean. public void submit(ActionEvent ae) { someMethod(name.getValue().toString()); // Retrieves the "old" value someMethod(name.getSubmittedValue().toString()); // Retrieves the correct value } </code></pre> <p>Also, I've noticed that calling .getSubmittedValue() on a form field sometimes results in a null pointer exception because that value has not been instantiated in the component object, in which case when I call .getValue() in that circumstance I get the correct value, for example:</p> <pre><code>HtmlInputText name = new HtmlInputText(); // This is the control I have in a bean. public void submit(ActionEvent ae) { someMethod(name.getValue().toString()); // Retrieves the correct value someMethod(name.getSubmittedValue().toString()); // Throws NullPointerException } </code></pre> <p>Is this just a "quirk" of the JSF framework, or am I just using the API <strong>COMPLETELY</strong> incorrectly?? Any insight into these two methods would be greatly appreciated. Cheers.</p>
[ { "answer_id": 260438, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 3, "selected": false, "text": "<p>To quote the documentation on <a href=\"http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/EditableValueHolder.html#getSubmittedValue()\" rel=\"noreferrer\">EditableValueHolder.getSubmittedValue</a>:</p>\n\n<blockquote>\n <p>Return the submittedValue value of\n this component. This method should\n only be used by the encodeBegin() \n and/or encodeEnd() methods of this\n component, or its corresponding\n Renderer.</p>\n</blockquote>\n\n<p>Generally, you would not even be calling <em>getValue</em>. Instead, the component's <em>value</em> attribute should be bound to your model (a bean, maybe). Your business logic would interact with the model, not the component.</p>\n\n<p>If the submitted value is not being set as the value, then I'd guess that some validation is failing. The only problem with that is that your event is being fired. Two guesses for the problem here:</p>\n\n<ul>\n<li>You have a stale reference to the component object.</li>\n<li>You've set the <em>immediate</em> attribute on a <em>UICommand</em> which means that the event is fired in a phase where the component will be in an inappropriate state.</li>\n</ul>\n\n<p>It isn't possible to be certain with the information provided.</p>\n" }, { "answer_id": 1145620, "author": "Dr. Nichols", "author_id": 140412, "author_profile": "https://Stackoverflow.com/users/140412", "pm_score": 6, "selected": true, "text": "<p>Since this is the #1 result in Google for searching on getValue vs. getSubmittedValue I'd just like to add that the difference between these is critical in validation (i.e. when writing a custom validator)</p>\n\n<p>To quote the API documentation for getSubmittedValue():</p>\n\n<blockquote>\n <p>This is non-null only between decode\n and validate phases, or when\n validation for the component has not\n succeeded. Once conversion and\n validation has succeeded, the\n (converted) value is stored in the\n local \"value\" property of this\n component, and the submitted value is\n reset to null.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()\" rel=\"noreferrer\"><a href=\"http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()\" rel=\"noreferrer\">http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()</a></a></p>\n\n<p>This means that if the validation/conversion has taken place for the binding you are trying to access, you should call getValue() otherwise you'll have to call getSubmittedValue() and deal with parsing it yourself. The order in which these occur seems to be dictated by the order they appear in the UI, but I don't think that's guaranteed. Even if it is, you shouldn't count on that as changing field in your UI shouldn't break your code.</p>\n\n<p>You can detect if the validation/conversion has been done by just looking at what isLocalValueSet() returns. If it returns true, then the valdation/conversion has been done, so you should call getValue(). Otherwise you'll need to call getSubmittedValue() and that'll give you the raw input the user entered and you'll likely want to parse it into something more meaningful.</p>\n\n<p>For example, a calendar object would return a Date object when getValue() was called, but a String object when getSubmittedValue() was called. It's up to your converter to parse the string into a Date so it can be validated.</p>\n\n<p>It'd be great if the JSF spec had a method which would do this for us, but AFAIK it doesn't. If certain dates need to be before other dates, and some are only required in certain circumstances, one will need to write several validators to handle this. So it can easily become an issue. This is similar to the fact that you can't do any kind of validation on a blank field, which means you can't make that field conditionally required. If validation was run on all fields, even blank ones, a custom validator could be written to throw an exception if it should be required and is not. There are some things with JSF which are just a pain; unless/until they're fixed, we just have to deal with them.</p>\n\n<p><p>To speak to the specifics of the issue in the original post: the difference here is where you're at in the life cycle. The <code>submit</code> method seems like an action listener for a button, which puts it at the end of the life cycle; actions and action listeners are triggered in the \"Invoke Application\" phase which comes prior to the render response, but after validation. If you're going to program in JSF, you should learn and understand the life cycle. It's worth the time.</p>\n" }, { "answer_id": 25189370, "author": "Ermo", "author_id": 3157831, "author_profile": "https://Stackoverflow.com/users/3157831", "pm_score": 0, "selected": false, "text": "<p>I work on xpages which are based on JSF so.. it could be the same...</p>\n\n<p>Anyway, getSubmittedValue(); always returns what you see in firebug/chrome develepers network tab. That is value within sent packet. I have it shown (chrome) in headers tab, in form data section, named $$xspsubmitvalue.</p>\n\n<p>On the other hand, getValue() is component specific. &lt;-- not 100% sure here.</p>\n" }, { "answer_id": 46676231, "author": "Andrew", "author_id": 1599699, "author_profile": "https://Stackoverflow.com/users/1599699", "pm_score": 0, "selected": false, "text": "<p><strong>TL;DR</strong> answer:<s></p>\n\n<pre><code>UIViewRoot viewRoot = context.getViewRoot();\nUIInput input = (UIInput)viewRoot.findComponent(\":form:inputID\");\n\nString inputValueString;\n\nif (input.isLocalValueSet()) {\n inputValueString = (String)input.getValue(); //validated and converted already\n} else {\n inputValueString = (String)input.getSubmittedValue(); //raw input\n}\n</code></pre>\n\n<p>or at least that's what the other answers are saying to do...</s></p>\n\n<p>Just use <code>.getSubmittedValue()</code> and deal with the consequences of having to convert raw input (if necessary, if that raw input needs conversion). <code>.getValue()</code> is broken in this regard, even with the code above. It delays the submitted value if you use it and that's unacceptable.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ]
I've been developing a few JSF applications lately and am disturbed with the inconsistency in the web component APIs. I've noticed that there is extremely unpredictable behavior when calling .getValue() or .getSubmittedValue() on a JSF component object in server side code. Sometimes when I call .getValue() on a drop down list box, I've noticed that I get the value as it was BEFORE I selected my value (so the value from the last page refresh), of which .getSubmittedValue() gets me the correct value, as such: ``` UIInput name = new UIInput(); // This is the control I have in a bean. public void submit(ActionEvent ae) { someMethod(name.getValue().toString()); // Retrieves the "old" value someMethod(name.getSubmittedValue().toString()); // Retrieves the correct value } ``` Also, I've noticed that calling .getSubmittedValue() on a form field sometimes results in a null pointer exception because that value has not been instantiated in the component object, in which case when I call .getValue() in that circumstance I get the correct value, for example: ``` HtmlInputText name = new HtmlInputText(); // This is the control I have in a bean. public void submit(ActionEvent ae) { someMethod(name.getValue().toString()); // Retrieves the correct value someMethod(name.getSubmittedValue().toString()); // Throws NullPointerException } ``` Is this just a "quirk" of the JSF framework, or am I just using the API **COMPLETELY** incorrectly?? Any insight into these two methods would be greatly appreciated. Cheers.
Since this is the #1 result in Google for searching on getValue vs. getSubmittedValue I'd just like to add that the difference between these is critical in validation (i.e. when writing a custom validator) To quote the API documentation for getSubmittedValue(): > > This is non-null only between decode > and validate phases, or when > validation for the component has not > succeeded. Once conversion and > validation has succeeded, the > (converted) value is stored in the > local "value" property of this > component, and the submitted value is > reset to null. > > > Source: [<http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()>](http://myfaces.apache.org/core11/myfaces-api/apidocs/javax/faces/component/UIInput.html#getSubmittedValue()) This means that if the validation/conversion has taken place for the binding you are trying to access, you should call getValue() otherwise you'll have to call getSubmittedValue() and deal with parsing it yourself. The order in which these occur seems to be dictated by the order they appear in the UI, but I don't think that's guaranteed. Even if it is, you shouldn't count on that as changing field in your UI shouldn't break your code. You can detect if the validation/conversion has been done by just looking at what isLocalValueSet() returns. If it returns true, then the valdation/conversion has been done, so you should call getValue(). Otherwise you'll need to call getSubmittedValue() and that'll give you the raw input the user entered and you'll likely want to parse it into something more meaningful. For example, a calendar object would return a Date object when getValue() was called, but a String object when getSubmittedValue() was called. It's up to your converter to parse the string into a Date so it can be validated. It'd be great if the JSF spec had a method which would do this for us, but AFAIK it doesn't. If certain dates need to be before other dates, and some are only required in certain circumstances, one will need to write several validators to handle this. So it can easily become an issue. This is similar to the fact that you can't do any kind of validation on a blank field, which means you can't make that field conditionally required. If validation was run on all fields, even blank ones, a custom validator could be written to throw an exception if it should be required and is not. There are some things with JSF which are just a pain; unless/until they're fixed, we just have to deal with them. To speak to the specifics of the issue in the original post: the difference here is where you're at in the life cycle. The `submit` method seems like an action listener for a button, which puts it at the end of the life cycle; actions and action listeners are triggered in the "Invoke Application" phase which comes prior to the render response, but after validation. If you're going to program in JSF, you should learn and understand the life cycle. It's worth the time.
260,122
<p>I am trying to add a "title" element but am getting a NO_MODIFICATION_ALLOWED_ERR error...</p> <pre><code>private static void saveDoc(String f) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); // create DOMSource for source XML document DOMSource xmlSource = new DOMSource(doc); Node nextNode = xmlSource.getNode().getFirstChild(); while (nextNode != null) { System.out.print("\n node name: " + nextNode.getNodeName() + "\n"); if (nextNode.getNodeName().equals("map")) { nextNode.appendChild(doc.createElement("title")); </code></pre> <p><strong>the line above is throwing error:</strong></p> <blockquote> <p>Exception in thread "main" org.w3c.dom.DOMException: <code>NO_MODIFICATION_ALLOWED_ERR</code>: An attempt is made to modify an object where modifications are not allowed. at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source) at myProject.Main.saveDoc(Main.java:171) at myProject.Main.main(Main.java:48)</p> </blockquote> <pre><code> break; } nextNode = nextNode.getNextSibling(); } } </code></pre> <p>My xml file looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?dctm xml_app="LOPackage"?&gt; &lt;!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "file:C:/Documents%20and%20Settings/joe/Desktop//LOPackage/map.dtd"&gt; &lt;map xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- map/map " ditaarch:DITAArchVersion="1.1" domains="(map mapgroup-d) (topic indexing-d)"&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002504?DMS_OBJECT_SPEC=RELATION_ID" type="Le"/&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002505?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/&gt; &lt;topicref class="- map/topicref " href="dctm://ai/0501869e80002506?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/&gt; &lt;/map&gt; </code></pre>
[ { "answer_id": 260178, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 0, "selected": false, "text": "<p>For some reason, the parent node seems to be read-only.\nClone the document by using:</p>\n\n<pre><code>Document newDoc = doc.cloneNode(true);\n</code></pre>\n\n<p>Set it to read-write by:</p>\n\n<pre><code>newDoc.setReadOnly(false,true);\n// ^^^^ also sets children\n</code></pre>\n\n<p>Then do your stuff.\nI would return the new document after saving it though.</p>\n" }, { "answer_id": 260906, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Where is the original document coming from?</p>\n\n<p>That's the cause of the issue - the code that's reading in the document is constructing a read-only document. Without knowing how you're reading it in, it's pretty hard to work out how to change that.</p>\n\n<p>I just did a quick test on Windows with JDK 1.4.2-11, and I can confirm that using the DocumentBuilderFactory (with the XML content coming from a Reader) does not create a read only Document.</p>\n" }, { "answer_id": 261550, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 3, "selected": true, "text": "<p>Not sure if that's the reason, but check if your DOM implementation validates all the changes to the DOM. Because in you code,</p>\n\n<pre><code>nextNode.appendChild(doc.createTextNode(\"title\"));\n</code></pre>\n\n<p>will attempt to create a text node as the child of <code>map</code> element and DITA Map doesn't allow that. Instead, try</p>\n\n<pre><code>Element title = doc.createElement(\"title\");\ntitle.appendChild(doc.createTextNode(\"title content\"))\nnextNode.appendChild(title);\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
I am trying to add a "title" element but am getting a NO\_MODIFICATION\_ALLOWED\_ERR error... ``` private static void saveDoc(String f) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); // create DOMSource for source XML document DOMSource xmlSource = new DOMSource(doc); Node nextNode = xmlSource.getNode().getFirstChild(); while (nextNode != null) { System.out.print("\n node name: " + nextNode.getNodeName() + "\n"); if (nextNode.getNodeName().equals("map")) { nextNode.appendChild(doc.createElement("title")); ``` **the line above is throwing error:** > > Exception in thread "main" org.w3c.dom.DOMException: `NO_MODIFICATION_ALLOWED_ERR`: An attempt is made to modify an object where modifications are not allowed. > at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(Unknown Source) > at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(Unknown Source) > at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source) > at myProject.Main.saveDoc(Main.java:171) > at myProject.Main.main(Main.java:48) > > > ``` break; } nextNode = nextNode.getNextSibling(); } } ``` My xml file looks like this: ``` <?xml version="1.0" encoding="UTF-8"?> <?dctm xml_app="LOPackage"?> <!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "file:C:/Documents%20and%20Settings/joe/Desktop//LOPackage/map.dtd"> <map xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- map/map " ditaarch:DITAArchVersion="1.1" domains="(map mapgroup-d) (topic indexing-d)"> <topicref class="- map/topicref " href="dctm://ai/0501869e80002504?DMS_OBJECT_SPEC=RELATION_ID" type="Le"/> <topicref class="- map/topicref " href="dctm://ai/0501869e80002505?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/> <topicref class="- map/topicref " href="dctm://ai/0501869e80002506?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/> </map> ```
Not sure if that's the reason, but check if your DOM implementation validates all the changes to the DOM. Because in you code, ``` nextNode.appendChild(doc.createTextNode("title")); ``` will attempt to create a text node as the child of `map` element and DITA Map doesn't allow that. Instead, try ``` Element title = doc.createElement("title"); title.appendChild(doc.createTextNode("title content")) nextNode.appendChild(title); ```
260,150
<p>I am trying to use an XML-RPC server on my Drupal (PHP) backend to make it easier for my Perl backend to talk to it. However, I've run into an issue and I'm not sure which parts, if any, are bugs. Essentially, some of the variables I need to pass to Drupal are strings that sometimes are strings full of numbers and the Drupal XML-RPC server is returning an error that when a string is full of numbers it is not properly formed.</p> <p>My Perl code looks something like this at the moment.</p> <pre><code>use strict; use warnings; use XML::RPC; use Data::Dumper; my $xmlrpc = XML::RPC-&gt;new(URL); my $result = $xmlrpc-&gt;call( FUNCTION, 'hello world', '9876352345'); print Dumper $result; </code></pre> <p>The output is:</p> <pre><code>$VAR1 = { 'faultString' =&gt; 'Server error. Invalid method parameters.', 'faultCode' =&gt; '-32602' }; </code></pre> <p>When I have the Drupal XML-RPC server print out the data it receives, I notice that the second argument is typed as i4:</p> <pre><code>&lt;param&gt; &lt;value&gt; &lt;i4&gt;9876352345&lt;/i4&gt; &lt;/value&gt; </code></pre> <p>I think when Drupal then finishes processing the item, it is typing that variable as an int instead of a string. This means when Drupal later tries to check that the variable value is properly formed for a string, the is_string PHP function returns false.</p> <pre><code>foreach ($signature as $key =&gt; $type) { $arg = $args[$key]; switch ($type) { case 'int': case 'i4': if (is_array($arg) || !is_int($arg)) { $ok = FALSE; } break; case 'base64': case 'string': if (!is_string($arg)) { $ok = FALSE; } break; case 'boolean': if ($arg !== FALSE &amp;&amp; $arg !== TRUE) { $ok = FALSE; } break; case 'float': case 'double': if (!is_float($arg)) { $ok = FALSE; } break; case 'date': case 'dateTime.iso8601': if (!$arg-&gt;is_date) { $ok = FALSE; } break; } if (!$ok) { return xmlrpc_error(-32602, t('Server error. Invalid method parameters.')); } } </code></pre> <p>What I'm not sure about is on which side of the divide the issue lies or if there is something else I should be using. Should the request from the Perl side be typing the content as a string instead of i4 or is the Drupal side of the request too stringent for the string type? My guess is that the issue is the latter, but I don't know enough about how an XML-RPC server is supposed to work to know for sure.</p>
[ { "answer_id": 260283, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "<p>The number <code>9876352345</code> is too big to fit in a 32bit integer. That might cause the problem.</p>\n" }, { "answer_id": 260289, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<p>are you using frontier? perhaps you could declare the string explicitly?</p>\n\n<pre><code>my $result =\n $xmlrpc-&gt;call( FUNCTION, 'hello world', $xmlrpc-&gt;string('9876352345') );\n</code></pre>\n\n<p>info from the <a href=\"http://search.cpan.org/~kmacleod/Frontier-RPC-0.07b4/lib/Frontier/Client.pm\" rel=\"nofollow noreferrer\">client docs</a>:</p>\n\n<blockquote>\n <p>By default, you may pass ordinary Perl values (scalars) to be encoded. RPC2 automatically converts them to XML-RPC types if they look like an integer, float, or as a string. This assumption causes problems when you want to pass a string that looks like \"0096\", RPC2 will convert that to an because it looks like an integer.</p>\n</blockquote>\n" }, { "answer_id": 261574, "author": "rjray", "author_id": 6421, "author_profile": "https://Stackoverflow.com/users/6421", "pm_score": 1, "selected": true, "text": "<p>I don't have any experience with the XML::RPC package, but I'm the author of the <a href=\"http://search.cpan.org/dist/RPC-XML\" rel=\"nofollow noreferrer\">RPC::XML</a> CPAN module. As with the Frontier package, I provide a way to force a value into a specific type when it would otherwise default to something else.</p>\n\n<p>If I had to guess, I would say that the package you're using simple does a regular-expression match on the data to decide how to type it. I had a similar problem with my package, and given the way Perl handles scalar values the only real way around it is to force it with explicit declaration. As a previous answerer pointed out, the value in question is actually outside the range of the &lt;i4&gt; type (which is a signed 32-bit value). So even if you had intended it to be an integer value, it would have been invalid with regards to the XML-RPC spec.</p>\n\n<p>I would recommend switching to one of the other XML-RPC packages, which have clearer ways of explicitly typing data. According to the docs for XML::RPC, it is possible to force the typing of data, but I found it to be unclear and not very well explained.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31240/" ]
I am trying to use an XML-RPC server on my Drupal (PHP) backend to make it easier for my Perl backend to talk to it. However, I've run into an issue and I'm not sure which parts, if any, are bugs. Essentially, some of the variables I need to pass to Drupal are strings that sometimes are strings full of numbers and the Drupal XML-RPC server is returning an error that when a string is full of numbers it is not properly formed. My Perl code looks something like this at the moment. ``` use strict; use warnings; use XML::RPC; use Data::Dumper; my $xmlrpc = XML::RPC->new(URL); my $result = $xmlrpc->call( FUNCTION, 'hello world', '9876352345'); print Dumper $result; ``` The output is: ``` $VAR1 = { 'faultString' => 'Server error. Invalid method parameters.', 'faultCode' => '-32602' }; ``` When I have the Drupal XML-RPC server print out the data it receives, I notice that the second argument is typed as i4: ``` <param> <value> <i4>9876352345</i4> </value> ``` I think when Drupal then finishes processing the item, it is typing that variable as an int instead of a string. This means when Drupal later tries to check that the variable value is properly formed for a string, the is\_string PHP function returns false. ``` foreach ($signature as $key => $type) { $arg = $args[$key]; switch ($type) { case 'int': case 'i4': if (is_array($arg) || !is_int($arg)) { $ok = FALSE; } break; case 'base64': case 'string': if (!is_string($arg)) { $ok = FALSE; } break; case 'boolean': if ($arg !== FALSE && $arg !== TRUE) { $ok = FALSE; } break; case 'float': case 'double': if (!is_float($arg)) { $ok = FALSE; } break; case 'date': case 'dateTime.iso8601': if (!$arg->is_date) { $ok = FALSE; } break; } if (!$ok) { return xmlrpc_error(-32602, t('Server error. Invalid method parameters.')); } } ``` What I'm not sure about is on which side of the divide the issue lies or if there is something else I should be using. Should the request from the Perl side be typing the content as a string instead of i4 or is the Drupal side of the request too stringent for the string type? My guess is that the issue is the latter, but I don't know enough about how an XML-RPC server is supposed to work to know for sure.
I don't have any experience with the XML::RPC package, but I'm the author of the [RPC::XML](http://search.cpan.org/dist/RPC-XML) CPAN module. As with the Frontier package, I provide a way to force a value into a specific type when it would otherwise default to something else. If I had to guess, I would say that the package you're using simple does a regular-expression match on the data to decide how to type it. I had a similar problem with my package, and given the way Perl handles scalar values the only real way around it is to force it with explicit declaration. As a previous answerer pointed out, the value in question is actually outside the range of the <i4> type (which is a signed 32-bit value). So even if you had intended it to be an integer value, it would have been invalid with regards to the XML-RPC spec. I would recommend switching to one of the other XML-RPC packages, which have clearer ways of explicitly typing data. According to the docs for XML::RPC, it is possible to force the typing of data, but I found it to be unclear and not very well explained.
260,165
<p>A colleague is looking to generate UML class diagrams from heaps of Python source code. He's primarily interested in the inheritance relationships, and mildly interested in compositional relationships, and doesn't care much about class attributes that are just Python primitives.</p> <p>The source code is pretty straightforward and not tremendously evil--it doesn't do any fancy metaclass magic, for example. (It's mostly from the days of Python 1.5.2, with some sprinklings of "modern" 2.3ish stuff.) </p> <p>What's the best existing solution to recommend?</p>
[ { "answer_id": 260183, "author": "David Arcos", "author_id": 30300, "author_profile": "https://Stackoverflow.com/users/30300", "pm_score": 3, "selected": false, "text": "<p>If you use Eclipse, maybe <a href=\"http://sourceforge.net/projects/eclipse-pyuml\" rel=\"nofollow noreferrer\">PyUML</a>. Haven't used it, though.</p>\n" }, { "answer_id": 260196, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": false, "text": "<p>Certain classes of well-behaved programs may be diagrammable, but in the general case, it can't be done. Python objects can be extended at run time, and objects of any type can be assigned to any instance variable. Figuring out what classes an object can contain pointers to (composition) would require a full understanding of the runtime behavior of the program.</p>\n\n<p>Python's metaclass capabilities mean that reasoning about the inheritance structure would also require a full understanding of the runtime behavior of the program.</p>\n\n<p>To prove that these are impossible, you argue that if such a UML diagrammer existed, then you could take an arbitrary program, convert \"halt\" statements into statements that would impact the UML diagram, and use the UML diagrammer to solve the halting problem, which as we know is impossible.</p>\n" }, { "answer_id": 260323, "author": "piro", "author_id": 10138, "author_profile": "https://Stackoverflow.com/users/10138", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://epydoc.sourceforge.net/\" rel=\"noreferrer\">Epydoc</a> is a tool to generate API documentation from Python source code. It also generates UML class diagrams, using <a href=\"http://www.graphviz.org/\" rel=\"noreferrer\">Graphviz</a> in fancy ways. Here is <a href=\"http://epydoc.sourceforge.net/api/epydoc.apidoc.VariableDoc-class.html\" rel=\"noreferrer\">an example of diagram</a> generated from the source code of Epydoc itself.</p>\n\n<p>Because Epydoc performs both object introspection and source parsing it can gather more informations respect to static code analysers such as Doxygen: it can inspect a fair amount of dynamically generated classes and functions, but can also use comments or unassigned strings as a documentation source, e.g. for variables and class public attributes.</p>\n" }, { "answer_id": 260649, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://pythonide.blogspot.com\" rel=\"noreferrer\">SPE</a> IDE has built-in UML creator. Just open the files in SPE and click on the UML tab.</p>\n\n<p>I don't know how comprhensive it is for your needs, but it doesn't require any additional downloads or configurations to use.</p>\n" }, { "answer_id": 261844, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 3, "selected": false, "text": "<p>It is worth mentioning <a href=\"https://github.com/gaphor/gaphor\" rel=\"nofollow noreferrer\">Gaphor</a>. A Python modelling/UML tool.</p>\n" }, { "answer_id": 263606, "author": "chimp", "author_id": 18364, "author_profile": "https://Stackoverflow.com/users/18364", "pm_score": 3, "selected": false, "text": "<p>Sparx's <a href=\"http://www.sparxsystems.com\" rel=\"noreferrer\">Enterprise Architect</a> performs round-tripping of Python source. They have a free time-limited trial edition.</p>\n" }, { "answer_id": 6606829, "author": "Hosane", "author_id": 651506, "author_profile": "https://Stackoverflow.com/users/651506", "pm_score": 3, "selected": false, "text": "<p>Umbrello does that too. in the menu go to Code -> import project and then point to the root deirectory of your project. then it reverses the code for ya...</p>\n" }, { "answer_id": 7554457, "author": "Nicolas Chauvat", "author_id": 964956, "author_profile": "https://Stackoverflow.com/users/964956", "pm_score": 8, "selected": false, "text": "<p>You may have heard of <a href=\"http://www.pylint.org/\" rel=\"noreferrer\">Pylint</a> that helps statically checking Python code. Few people know that it comes with a tool named <a href=\"http://www.logilab.org/blogentry/6883\" rel=\"noreferrer\">Pyreverse</a> that draws UML diagrams from the Python code it reads. Pyreverse uses Graphviz as a backend.</p>\n<p>It is used like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>pyreverse -o png -p yourpackage .\n</code></pre>\n<p>where the <code>.</code> can also be a single file.</p>\n" }, { "answer_id": 8445401, "author": "Ángel Luis", "author_id": 1089700, "author_profile": "https://Stackoverflow.com/users/1089700", "pm_score": 3, "selected": false, "text": "<p>vipera is a small application designer, and uml is included. You can see it in:</p>\n\n<p><a href=\"https://sourceforge.net/projects/pythonvipera/\" rel=\"noreferrer\">vipera</a></p>\n\n<p>Best regards.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16056/" ]
A colleague is looking to generate UML class diagrams from heaps of Python source code. He's primarily interested in the inheritance relationships, and mildly interested in compositional relationships, and doesn't care much about class attributes that are just Python primitives. The source code is pretty straightforward and not tremendously evil--it doesn't do any fancy metaclass magic, for example. (It's mostly from the days of Python 1.5.2, with some sprinklings of "modern" 2.3ish stuff.) What's the best existing solution to recommend?
You may have heard of [Pylint](http://www.pylint.org/) that helps statically checking Python code. Few people know that it comes with a tool named [Pyreverse](http://www.logilab.org/blogentry/6883) that draws UML diagrams from the Python code it reads. Pyreverse uses Graphviz as a backend. It is used like this: ```none pyreverse -o png -p yourpackage . ``` where the `.` can also be a single file.
260,192
<p>I'm trying to use <code>mtrace</code> to detect memory leaks in a fortran program. I'm using the gfortran compiler. See the wikipedia entry for a (working) C example of mtrace: <a href="http://en.wikipedia.org/wiki/Mtrace" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Mtrace</a> </p> <p>I tried both ways, i.e. wrapping the mtrace() and muntrace() and call them from the fortran program, as well as create a C program which directly call the mtrace() and muntrace(), besides the leaking fortran code in between. Both approaches will fail to detect the memory leak, but here I'm presenting only the latter.</p> <p>example.c</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;mcheck.h&gt; extern void leaky_(); // this might be different on your system // if it doesn't work, try to run: // 1) gfortran leaky.f90 -c // 2) nm leaky.o // and then change this declaration and its use below void main() { mtrace(); leaky_(); muntrace(); } </code></pre> <p>leaky.f90</p> <pre><code>subroutine leaky() real, allocatable, dimension(:) :: tmp integer :: error allocate (tmp(10), stat=error) if (error /= 0) then print*, "subroutine leaky could not allocate space for array tmp" endif tmp = 1 !of course the actual code makes more... print*, ' subroutine leaky run ' return end subroutine leaky </code></pre> <p>I compile with:</p> <pre><code>gfortran -g example.c leaky.f90 </code></pre> <p>Then I run with:</p> <pre><code>export MALLOC_TRACE=`pwd`/raw.txt; ./a.out </code></pre> <p>Then I parse the <code>raw.txt</code> <code>mtrace</code> output with:</p> <pre><code>mtrace a.out raw.txt </code></pre> <p>and get:</p> <p>No memory leaks.</p> <p>Is there anything I'm doing wrong, or something I can do to let <code>mtrace</code> find the leaky fortran memory allocation? I guess gfortran is using a different <code>malloc</code> call, which <code>mtrace</code> does not trace... In fact, as I wrote above I get the same result if I write a fortran main which would call the (wrapped) <code>mtrace()</code> and <code>muntrace()</code>.</p> <p>EDITED: I considered other options (including some not yet mentioned here), but the actual code being debugged runs on P6/AIX, so Valgrind would be "just" inconvenient (it needs to run on a different machine), whereas Forcheck would be inconvenient (it needs to run on a different machine) and expensive ( ~ 3k$). At present mtrace would be the best solution, if it worked.</p> <p>EDITED again: My guess </p> <blockquote> <p>I guess gfortran is using a different <code>malloc</code> call, which <code>mtrace</code> does not trace...</p> </blockquote> <p>was correct. Looking into the executable (either with <code>nm</code> or <code>readelf</code>) there isn't any <code>malloc()</code> call, but <code>_gfortran_allocate_array</code> ones - which maybe will call malloc). Any other ideas?</p> <p>EDITED again: I posted the answer but I cannot accept it (go to <a href="http://stackoverflow.uservoice.com/pages/general/suggestions/39426" rel="nofollow noreferrer">http://stackoverflow.uservoice.com/pages/general/suggestions/39426</a> and request the feature, it's really needed - no reputation gain wanted)</p>
[ { "answer_id": 260189, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>First find out what is really the problem and that the server is properly tuned for the queries you are running. It's very sad to waste the money on RAM to find out you are I/O bound.</p>\n\n<p>After you gather data about the cause of the timeouts you should be able to convince the pencil wielders easily.</p>\n\n<p>Some tuning/monitoring links:</p>\n\n<p><a href=\"http://www.brentozar.com/archive/2008/03/sql-server-2005-setup-checklist-part-1-before-the-install/\" rel=\"nofollow noreferrer\">http://www.brentozar.com/archive/2008/03/sql-server-2005-setup-checklist-part-1-before-the-install/</a> (check both articles)</p>\n\n<p><a href=\"http://www.sql-server-performance.com/\" rel=\"nofollow noreferrer\">http://www.sql-server-performance.com/</a></p>\n\n<p>About I/O specifically:</p>\n\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/pdpliobp.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/pdpliobp.mspx</a></p>\n\n<p><a href=\"http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1307990,00.html\" rel=\"nofollow noreferrer\">http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1307990,00.html</a></p>\n\n<p><a href=\"http://www.novicksoftware.com/Articles/sql-server-io-statistics.htm\" rel=\"nofollow noreferrer\">http://www.novicksoftware.com/Articles/sql-server-io-statistics.htm</a></p>\n" }, { "answer_id": 260204, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 1, "selected": false, "text": "<p>I would start by profiling and optimizing the queries as much as I could.</p>\n\n<p>I would build a testing system and run the queries using 1GB of RAM, 2GB of RAM, 4 GB of RAM and finally 8GB of RAM.</p>\n\n<p>I would calculate how the queries would behave with 16 or 32 GB of RAM (and show actual time values and percentage increases - they will understand that) and build a nice colorful graph (pencilpushers like that).</p>\n\n<p>They won't understand the technical aspects but they will understand percentage increases and a nice graph.</p>\n\n<p>But I would go through the queries again an try to optimize them first.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25891/" ]
I'm trying to use `mtrace` to detect memory leaks in a fortran program. I'm using the gfortran compiler. See the wikipedia entry for a (working) C example of mtrace: <http://en.wikipedia.org/wiki/Mtrace> I tried both ways, i.e. wrapping the mtrace() and muntrace() and call them from the fortran program, as well as create a C program which directly call the mtrace() and muntrace(), besides the leaking fortran code in between. Both approaches will fail to detect the memory leak, but here I'm presenting only the latter. example.c ``` #include <stdlib.h> #include <mcheck.h> extern void leaky_(); // this might be different on your system // if it doesn't work, try to run: // 1) gfortran leaky.f90 -c // 2) nm leaky.o // and then change this declaration and its use below void main() { mtrace(); leaky_(); muntrace(); } ``` leaky.f90 ``` subroutine leaky() real, allocatable, dimension(:) :: tmp integer :: error allocate (tmp(10), stat=error) if (error /= 0) then print*, "subroutine leaky could not allocate space for array tmp" endif tmp = 1 !of course the actual code makes more... print*, ' subroutine leaky run ' return end subroutine leaky ``` I compile with: ``` gfortran -g example.c leaky.f90 ``` Then I run with: ``` export MALLOC_TRACE=`pwd`/raw.txt; ./a.out ``` Then I parse the `raw.txt` `mtrace` output with: ``` mtrace a.out raw.txt ``` and get: No memory leaks. Is there anything I'm doing wrong, or something I can do to let `mtrace` find the leaky fortran memory allocation? I guess gfortran is using a different `malloc` call, which `mtrace` does not trace... In fact, as I wrote above I get the same result if I write a fortran main which would call the (wrapped) `mtrace()` and `muntrace()`. EDITED: I considered other options (including some not yet mentioned here), but the actual code being debugged runs on P6/AIX, so Valgrind would be "just" inconvenient (it needs to run on a different machine), whereas Forcheck would be inconvenient (it needs to run on a different machine) and expensive ( ~ 3k$). At present mtrace would be the best solution, if it worked. EDITED again: My guess > > I guess gfortran is using a different `malloc` call, which `mtrace` does not trace... > > > was correct. Looking into the executable (either with `nm` or `readelf`) there isn't any `malloc()` call, but `_gfortran_allocate_array` ones - which maybe will call malloc). Any other ideas? EDITED again: I posted the answer but I cannot accept it (go to <http://stackoverflow.uservoice.com/pages/general/suggestions/39426> and request the feature, it's really needed - no reputation gain wanted)
First find out what is really the problem and that the server is properly tuned for the queries you are running. It's very sad to waste the money on RAM to find out you are I/O bound. After you gather data about the cause of the timeouts you should be able to convince the pencil wielders easily. Some tuning/monitoring links: <http://www.brentozar.com/archive/2008/03/sql-server-2005-setup-checklist-part-1-before-the-install/> (check both articles) <http://www.sql-server-performance.com/> About I/O specifically: <http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/pdpliobp.mspx> <http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1307990,00.html> <http://www.novicksoftware.com/Articles/sql-server-io-statistics.htm>
260,195
<p>I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run. So far I have:</p> <pre><code>SELECT startTime, endTime, cast(datediff(hh,starttime,endtime) as varchar) +':' +cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME FROM applog WHERE runID = 33871 ORDER BY startTime DESC </code></pre> <p>When I execute this I get expected values and also some unexpected. For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54. How do I get a quere in MS SQL SMS to return the value 3:06 for this case?</p> <p>Thanks.</p> <p>Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well.</p>
[ { "answer_id": 260209, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.sqlservercurry.com/2008/04/find-hours-minutes-and-seconds-in.html\" rel=\"nofollow noreferrer\">Here's</a> a way to do it:</p>\n\n<pre><code>-- Find Hours, Minutes and Seconds in between two datetime\nDECLARE @First datetime\nDECLARE @Second datetime\nSET @First = '04/02/2008 05:23:22'\nSET @Second = getdate()\n\nSELECT DATEDIFF(day,@First,@Second)*24 as TotalHours,\nDATEDIFF(day,@First,@Second)*24*60 as TotalMinutes,\nDATEDIFF(day,@First,@Second)*24*60*60 as TotalSeconds\n</code></pre>\n" }, { "answer_id": 260220, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>You should separate your calculation and presentation logic:</p>\n\n<pre><code>DECLARE @applog TABLE\n(\n runID int,\n starttime datetime,\n endtime datetime\n)\n\nINSERT INTO @applog (runID, starttime, endtime)\nSELECT 33871, '2008-11-02 15:59:59.790', '2008-11-02 19:05:41.857'\n-------------------\nSELECT\n SUBSTRING(convert(varchar(30), DateAdd(mi, duration, 0), 121),\n 12, 5) as prettyduration\nFROM\n(\nSELECT starttime, DateDiff(mi, starttime, endtime) as duration\nFROM @applog\nWHERE runID = 33871\n) as sub\n</code></pre>\n\n<p>If you need to represent more than 24 hours, you would use a different presentation logic. This is just what I could think of fastest.</p>\n" }, { "answer_id": 260234, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": true, "text": "<p>Try these</p>\n\n<p>Assuming 2 declared dates.</p>\n\n<pre><code>declare @start datetime\nset @start = '2008-11-02 15:59:59.790'\n\ndeclare @end datetime\nset @end = '2008-11-02 19:05:41.857'\n</code></pre>\n\n<p>This will return the hours / mins / seconds</p>\n\n<pre><code>select \n (datediff(ss, @start, @end) / 3600), \n (datediff(ss, @start, @end) / 60) % 60,\n (datediff(ss, @start, @end) % 60) % 60\n\n--returns\n\n----------- ----------- -----------\n3 5 42\n</code></pre>\n\n<p>This is the zero-padded concatenated string version</p>\n\n<pre><code>select\nRIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 3600)), 2) + ':' +\nRIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 60) % 60), 2) + ':' +\nRIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) % 60) % 60), 2)\n\n--------\n03:05:42\n</code></pre>\n" }, { "answer_id": 260255, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 1, "selected": false, "text": "<p>You need to be consistent with your calls to datediff(). They should all use the same datepart argument.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/ms189794.aspx\" rel=\"nofollow noreferrer\">MSDN's DATEDIFF (Transact-SQL) article</a>.</p>\n\n<p>In your example, you're using both \"mi\" and \"hh\" and concatenating.</p>\n\n<p>Choose the least common denominator for your durations (probably ss or s) and do any math based on that (as the other answers are illustrating, but not really describing).</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33727/" ]
I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run. So far I have: ``` SELECT startTime, endTime, cast(datediff(hh,starttime,endtime) as varchar) +':' +cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME FROM applog WHERE runID = 33871 ORDER BY startTime DESC ``` When I execute this I get expected values and also some unexpected. For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54. How do I get a quere in MS SQL SMS to return the value 3:06 for this case? Thanks. Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well.
Try these Assuming 2 declared dates. ``` declare @start datetime set @start = '2008-11-02 15:59:59.790' declare @end datetime set @end = '2008-11-02 19:05:41.857' ``` This will return the hours / mins / seconds ``` select (datediff(ss, @start, @end) / 3600), (datediff(ss, @start, @end) / 60) % 60, (datediff(ss, @start, @end) % 60) % 60 --returns ----------- ----------- ----------- 3 5 42 ``` This is the zero-padded concatenated string version ``` select RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 3600)), 2) + ':' + RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 60) % 60), 2) + ':' + RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) % 60) % 60), 2) -------- 03:05:42 ```
260,210
<p>I'm using jQuery and wanting to target the nth &lt;li&gt; in a list after clicking the nth link.</p> <pre><code>&lt;ul id="targetedArea"&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="clickedItems"&gt; &lt;a&gt;&lt;/a&gt; &lt;a&gt;&lt;/a&gt; &lt;a&gt;&lt;/a&gt; &lt;a&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I can target them individually, but I know there must be a faster way by passing which &lt;a&gt; element I clicked on.</p> <pre><code>$("#clickedItem a:eq(2)").click(function() { $("#targetedArea:eq(2)").addClass('active'); return false; }); </code></pre> <p>Cheers,<br /> Steve </p>
[ { "answer_id": 260242, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "<p>how about something like this:</p>\n\n<pre><code>$('#clickedItems a').click(function() {\n// figure out what position this element is in\n var n = $('#clickedItems a').index($(this) );\n// update the targetedArea\n $('#targetedArea li:eq('+n+')').html('updated!');\n return false;\n});\n</code></pre>\n\n<p>assuming a 1:1 relationship between your <code>&lt;a&gt;</code> and <code>&lt;li&gt;</code> elements it will update the appropriate <code>&lt;li&gt;</code></p>\n" }, { "answer_id": 260244, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>I know this is not directly answering your question, but maybe you're making it more difficult than it is. </p>\n\n<p>Give each of the A and LI elements an ID, and make the IDs so you can infer them from each other. As soon as an A is clicked, you immediately know the LI's ID and can refer to it directly. </p>\n\n<p>As a side effect, this is more efficient than any clever jQuery that might do the same thing.</p>\n" }, { "answer_id": 260278, "author": "ken", "author_id": 20300, "author_profile": "https://Stackoverflow.com/users/20300", "pm_score": 0, "selected": false, "text": "<p>i dont know if jquery has something like this in mootools</p>\n\n<pre><code>$$('a.clickedItems').addEvent('click', function(e){\n e.preventDefault();\n $('targetedArea').getChildren()[this.getAllPrevious().length].addClass('selected');\n});\n</code></pre>\n" }, { "answer_id": 260284, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<pre><code>$('#clickedItems a').click(function() {\n // you probably want to turn off the currently active one\n $('#targetedArea li.active').removeClass(\"active\");\n\n // count the links previous to this one and make the corresponding li active\n $('#targetedArea li:eq(' + $(this).prevAll('a').length + ')').addClass(\"active\");\n\n // prevent the browser from going to the link\n return false;\n});\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16124/" ]
I'm using jQuery and wanting to target the nth <li> in a list after clicking the nth link. ``` <ul id="targetedArea"> <li></li> <li></li> <li></li> <li></li> </ul> <div id="clickedItems"> <a></a> <a></a> <a></a> <a></a> </div> ``` I can target them individually, but I know there must be a faster way by passing which <a> element I clicked on. ``` $("#clickedItem a:eq(2)").click(function() { $("#targetedArea:eq(2)").addClass('active'); return false; }); ``` Cheers, Steve
how about something like this: ``` $('#clickedItems a').click(function() { // figure out what position this element is in var n = $('#clickedItems a').index($(this) ); // update the targetedArea $('#targetedArea li:eq('+n+')').html('updated!'); return false; }); ``` assuming a 1:1 relationship between your `<a>` and `<li>` elements it will update the appropriate `<li>`
260,217
<p>How can i draw a dotted line in .NET/WinForms/GDI+?</p> <pre><code>Pen p = new Pen (Color.Black) </code></pre> <p>gives me only solid line pen. </p> <p>I am trying to have a dotted (or dashed) lines; can't seem to be able to google it up successfully.</p> <p>Will much appreciate any help on this one.</p>
[ { "answer_id": 260221, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 6, "selected": true, "text": "<pre><code>p.DashStyle = DashStyle.Dash;\n</code></pre>\n\n<p>I believe.</p>\n" }, { "answer_id": 260224, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 2, "selected": false, "text": "<p>Set the DashStyle property on your Pen object.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19584/" ]
How can i draw a dotted line in .NET/WinForms/GDI+? ``` Pen p = new Pen (Color.Black) ``` gives me only solid line pen. I am trying to have a dotted (or dashed) lines; can't seem to be able to google it up successfully. Will much appreciate any help on this one.
``` p.DashStyle = DashStyle.Dash; ``` I believe.
260,229
<p>I want to select records that are 1 month old or newer.</p> <p>The query is: SELECT * FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)</p> <p>Using Propel in Symfony, I do:</p> <blockquote> <p>$c = new Criteria<br> $c->add(FoobarPeer::CREATED_AT, "DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::GREATER_THAN); </p> </blockquote> <p>What Propel generates is: SELECT * FROM foobar WHERE created_at > 'DATE_SUB(curdate(), INTERVAL 1 MONTH)' - in other words, it puts the MySQL function in single quotes, which makes it a (meaningless) string and I get no records.</p> <p>What I've done for now is:</p> <blockquote> <p>$c->add(FoobarPeer::CREATED_AT, "created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::CUSTOM); </p> </blockquote> <p>But I don't want to use custom workarounds unless I have to. Any hints besides using Criteria::CUSTOM?</p>
[ { "answer_id": 260263, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "<p>I think there is no option more than using Criteria::CUSTOM or doing a custom SQL query like this:</p>\n\n<pre><code>$con = Propel::getConnection(DATABASE_NAME);\n\n$sql = \"SELECT foobar.* FROM foobar WHERE created_at &gt; DATE_SUB(curdate(), INTERVAL 1 MONTH)\"; \n$stmt = $con-&gt;prepare($sql);\n$stmt-&gt;execute();\n\n$books = FoobarPeer::populateObjects($stmt);\n</code></pre>\n\n<p>That's because Propel tries to be DBMS-agnostic, to help migration by doing a simple configuration value change, so it doesn't have any DBMS specific functions built in.</p>\n" }, { "answer_id": 260354, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 1, "selected": false, "text": "<p>just replace the mysql date code you are using there with a precalculated php variable that has that date in it already.</p>\n\n<p>i.e.</p>\n\n<pre><code>$monthAgo = '2008-10-03';\n$c = new Criteria\n$c-&gt;add(FoobarPeer::CREATED_AT, $monthAgo, Criteria::GREATER_THAN); \n</code></pre>\n\n<p>obviously, you should dynamically calculate the date in php, rather than hard coding it, but you get the picture.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2706/" ]
I want to select records that are 1 month old or newer. The query is: SELECT \* FROM foobar WHERE created\_at > DATE\_SUB(curdate(), INTERVAL 1 MONTH) Using Propel in Symfony, I do: > > $c = new Criteria > > $c->add(FoobarPeer::CREATED\_AT, "DATE\_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::GREATER\_THAN); > > > What Propel generates is: SELECT \* FROM foobar WHERE created\_at > 'DATE\_SUB(curdate(), INTERVAL 1 MONTH)' - in other words, it puts the MySQL function in single quotes, which makes it a (meaningless) string and I get no records. What I've done for now is: > > $c->add(FoobarPeer::CREATED\_AT, "created\_at > DATE\_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::CUSTOM); > > > But I don't want to use custom workarounds unless I have to. Any hints besides using Criteria::CUSTOM?
I think there is no option more than using Criteria::CUSTOM or doing a custom SQL query like this: ``` $con = Propel::getConnection(DATABASE_NAME); $sql = "SELECT foobar.* FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)"; $stmt = $con->prepare($sql); $stmt->execute(); $books = FoobarPeer::populateObjects($stmt); ``` That's because Propel tries to be DBMS-agnostic, to help migration by doing a simple configuration value change, so it doesn't have any DBMS specific functions built in.
260,233
<p>I've created a Visual Basic WPF Application project that contains Toy.edmx, an ADO.NET Entity Data Model generated from a database called Toy.</p> <p>Its <em>Window1.xaml.vb</em> file looks like this:</p> <pre> 1 Class Window1 2 3 Private Sub Window1_Loaded( _ 4 ByVal sender As System.Object, _ 5 ByVal e As System.Windows.RoutedEventArgs) _ 6 Handles MyBase.Loaded 7 8 Dim dc As New ToyEntities1 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Select c).First.FirstName 11 12 End Sub 13 14 End Class </pre> <p>That runs just fine.</p> <p>But, if I add the file <em>Client.vb</em>...</p> <pre> 1 Partial Public Class Client 2 Function IsWashington() As Boolean 3 Return Me.LastName = "Washington" 4 End Function 5 End Class </pre> <p>...and add a WHERE clause to my <em>Window1.xaml.vb</em> query...</p> <pre> 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Where c.IsWashington _ 11 Select c).First.FirstName </pre> <p>...then I get this NotSupportedException:</p> <blockquote> <p>LINQ to Entities does not recognize the method 'Boolean IsWashington()' method, and this method cannot be translated into a store expression.</p> </blockquote> <p>How do I extend ADO.NET Entity Framework objects with partial classes?</p>
[ { "answer_id": 260340, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 1, "selected": false, "text": "<p>What type is Client class?</p>\n\n<p>You might need to add namespace (same as that in which Client \"Entity classs\" is defined) to the file containing \"IsWashington\".</p>\n" }, { "answer_id": 260571, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": true, "text": "<p>The problem is that you're writing code, and expecting the Entity Framework to translate that into SQL... it can't do that. Just like LINQ to SQL can't do that.</p>\n\n<p>Imagine if your property read a file from the \"C:\\\" drive... how do you think it would handle that? - not possible.</p>\n" }, { "answer_id": 260784, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>Is this what you're trying to do - create a method that applies a filter to Client queries.</p>\n\n<p>I don't know vb.net, so don't trust this free-hand code 100%.</p>\n\n<pre><code>Partial Public Class Client\n Public Shared Function IsWashington(query As IQueryable(Of Client)) As IQueryable(Of Client)\n Return query.Where(Function(someClient) someClient.LastName = \"Washington\")\n End Function\nEnd Class\n</code></pre>\n\n<p>later, some calling code.</p>\n\n<pre><code>IQueryable(Of Client) someQuery = dc.ClientSet.AsQueryable\nsomeQuery = Client.IsWashington(someQuery)\n\nLabel1.Content = someQuery.First.FirstName\n</code></pre>\n\n<p>Hope this works!</p>\n" }, { "answer_id": 266291, "author": "Dave Swersky", "author_id": 34796, "author_profile": "https://Stackoverflow.com/users/34796", "pm_score": 1, "selected": false, "text": "<p>You could work around this particular problem by feeding your Client object from a View. Use the SQL CASE statement to set a bit column value:</p>\n\n<p>SELECT col1, col2, col3, LastName\nCASE LastName\n WHEN 'Washington' THEN 1\n ELSE 0 AS IsWashington\nFROM Client</p>\n\n<p>If you use the view as the basis for your Client entity object, the IsWashington column should become a member of the class along with all the other columns.</p>\n" }, { "answer_id": 382978, "author": "RichC", "author_id": 47167, "author_profile": "https://Stackoverflow.com/users/47167", "pm_score": 1, "selected": false, "text": "<p>shahkalpesh is correct, you need to add the namespace around your extended class to match the generated one.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I've created a Visual Basic WPF Application project that contains Toy.edmx, an ADO.NET Entity Data Model generated from a database called Toy. Its *Window1.xaml.vb* file looks like this: ``` 1 Class Window1 2 3 Private Sub Window1_Loaded( _ 4 ByVal sender As System.Object, _ 5 ByVal e As System.Windows.RoutedEventArgs) _ 6 Handles MyBase.Loaded 7 8 Dim dc As New ToyEntities1 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Select c).First.FirstName 11 12 End Sub 13 14 End Class ``` That runs just fine. But, if I add the file *Client.vb*... ``` 1 Partial Public Class Client 2 Function IsWashington() As Boolean 3 Return Me.LastName = "Washington" 4 End Function 5 End Class ``` ...and add a WHERE clause to my *Window1.xaml.vb* query... ``` 9 Label1.Content = (From c As Client In dc.ClientSet _ 10 Where c.IsWashington _ 11 Select c).First.FirstName ``` ...then I get this NotSupportedException: > > LINQ to Entities does not recognize the method 'Boolean IsWashington()' method, and this method cannot be translated into a store expression. > > > How do I extend ADO.NET Entity Framework objects with partial classes?
The problem is that you're writing code, and expecting the Entity Framework to translate that into SQL... it can't do that. Just like LINQ to SQL can't do that. Imagine if your property read a file from the "C:\" drive... how do you think it would handle that? - not possible.
260,235
<p>Consider the following simple C program that read a file into a buffer and displays that buffer to the console:</p> <pre><code>#include&lt;stdio.h&gt; main() { FILE *file; char *buffer; unsigned long fileLen; //Open file file = fopen("HelloWorld.txt", "rb"); if (!file) { fprintf(stderr, "Unable to open file %s", "HelloWorld.txt"); return; } //Get file length fseek(file, 0, SEEK_END); fileLen=ftell(file); fseek(file, 0, SEEK_SET); //Allocate memory buffer=(char *)malloc(fileLen+1); if (!buffer) { fprintf(stderr, "Memory error!"); fclose(file); return; } //Read file contents into buffer fread(buffer, fileLen, 1, file); //Send buffer contents to stdout printf("%s\n",buffer); fclose(file); } </code></pre> <p>The file it will read simply contains: </p> <blockquote> <p>Hello World!</p> </blockquote> <p>The output is:</p> <blockquote> <p>Hello World!²²²²▌▌▌▌▌▌▌↔☺</p> </blockquote> <p>It has been a while since I did anything significant in C/C++, but normally I would assume the buffer was being allocated larger than necessary, but this does not appear to be the case. </p> <p>fileLen ends up being 12, which is accurate.</p> <p>I am thinking now that I must just be displaying the buffer wrong, but I am not sure what I am doing wrong. </p> <p>Can anyone clue me in to what I am doing wrong?</p>
[ { "answer_id": 260243, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 6, "selected": true, "text": "<p>You need to NUL-terminate your string. Add</p>\n\n<pre><code>buffer[fileLen] = 0;\n</code></pre>\n\n<p>before printing it.</p>\n" }, { "answer_id": 260298, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": false, "text": "<p>JesperE is correct regarding the nul-termination issue in your example, I'll just add that if you are processing text files it would be better to use fgets() or something similar as this will properly handle newline sequences across different platforms and will always nul-terminate the string for you. If you are really working with binary data then you don't want to use printf() to output the data as the printf functions expect strings and a nul byte in the data will cause truncation of the output.</p>\n" }, { "answer_id": 260300, "author": "George Eadon", "author_id": 30530, "author_profile": "https://Stackoverflow.com/users/30530", "pm_score": 5, "selected": false, "text": "<p>JesperE's approach will work, but you may be interested to know that there's an alternate way of handling this.</p>\n\n<p>You can always print a string of known length, even when there's no NUL-terminator, by providing the length to <code>printf</code> as the precision for the string field:</p>\n\n<pre><code>printf(\"%.*s\\n\", fileLen, buffer);\n</code></pre>\n\n<p>This allows you print the string without modifying the buffer.</p>\n" }, { "answer_id": 2076025, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 0, "selected": false, "text": "<p>You can use <code>calloc</code> instead of <code>malloc</code> to allocate memory that is already initialised. <code>calloc</code> takes on extra argument. It's useful for allocating arrays; the first parameter of <code>calloc</code> indicates the number of elements in the array that you would like to allocate memory for, and the second argument is the size of each element. Since the size of a <code>char</code> is always 1, we can just pass <code>1</code> as the second argument:</p>\n\n<pre><code> buffer = calloc (fileLen + 1, 1);\n</code></pre>\n\n<p>In C, there is no need to cast the return value of <code>malloc</code> or <code>calloc</code>. The above will ensure that the string will be null terminated even if the reading of file ended prematurely for whatever reason. <code>calloc</code> does take longer than <code>malloc</code> because it has to zero out all the memory you asked for before giving it to you.</p>\n" }, { "answer_id": 2076043, "author": "Alok Singhal", "author_id": 226621, "author_profile": "https://Stackoverflow.com/users/226621", "pm_score": 2, "selected": false, "text": "<p>Your approach to determine file size by seeking to the end of the file and then using <code>ftell()</code> is wrong:</p>\n\n<ul>\n<li>If it is a text file, opened without <code>\"b\"</code> in the second parameter to the <code>fopen()</code> call, then <code>ftell()</code> may not tell you the number of characters that you can read from the file. For example, windows uses two bytes for end of line, but when read, it is one <code>char</code>. In fact, the return value of <code>ftell()</code> for streams opened in text mode is useful only in calls to <code>fseek()</code>, and not to determine file size.</li>\n<li>If it is a binary file, opened with <code>\"b\"</code> in the second parameter to <code>fopen()</code>, then the C standard has this to say:\n\n<blockquote>\n <p>Setting the file position indicator to end-of-file, as with <code>fseek(file, 0, SEEK_END)</code>, has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.</p>\n</blockquote></li>\n</ul>\n\n<p>So, what you are doing isn't necessarily going to work in standard C. Your best bet is to use <code>fread()</code> to read, and if you happen to need more memory, use <code>realloc()</code>. Your system may provide <code>mmap()</code>, or may make guarantees about setting the file position indicator to end-of-file for binary streams&mdash;but relying on those is not portable.</p>\n\n<p>See also this C-FAQ: <a href=\"http://c-faq.com/stdio/textvsbinary.html\" rel=\"nofollow noreferrer\">What's the difference between text and binary I/O?</a>.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5640/" ]
Consider the following simple C program that read a file into a buffer and displays that buffer to the console: ``` #include<stdio.h> main() { FILE *file; char *buffer; unsigned long fileLen; //Open file file = fopen("HelloWorld.txt", "rb"); if (!file) { fprintf(stderr, "Unable to open file %s", "HelloWorld.txt"); return; } //Get file length fseek(file, 0, SEEK_END); fileLen=ftell(file); fseek(file, 0, SEEK_SET); //Allocate memory buffer=(char *)malloc(fileLen+1); if (!buffer) { fprintf(stderr, "Memory error!"); fclose(file); return; } //Read file contents into buffer fread(buffer, fileLen, 1, file); //Send buffer contents to stdout printf("%s\n",buffer); fclose(file); } ``` The file it will read simply contains: > > Hello World! > > > The output is: > > Hello World!²²²²▌▌▌▌▌▌▌↔☺ > > > It has been a while since I did anything significant in C/C++, but normally I would assume the buffer was being allocated larger than necessary, but this does not appear to be the case. fileLen ends up being 12, which is accurate. I am thinking now that I must just be displaying the buffer wrong, but I am not sure what I am doing wrong. Can anyone clue me in to what I am doing wrong?
You need to NUL-terminate your string. Add ``` buffer[fileLen] = 0; ``` before printing it.