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
56,472
<p>I'm trying to send messages to Objective-C objects in gdb.</p> <pre><code>(gdb) p $esi $2 = (void *) 0x1268160 (gdb) po $esi &lt;NSArray: 0x1359c0&gt; (gdb) po [$esi count] Target does not respond to this message selector. </code></pre> <p>I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?</p>
[ { "answer_id": 57279, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 1, "selected": false, "text": "<p>Is it possible that you need to cast <code>$esi</code>?</p>\n\n<pre><code>p (NSUInteger)[(NSArray *)$esi count]\n</code></pre>\n" }, { "answer_id": 58687, "author": "asksol", "author_id": 5577, "author_profile": "https://Stackoverflow.com/users/5577", "pm_score": 0, "selected": false, "text": "<p>@[John Calsbeek]</p>\n\n<p>Then it complains about missing symbols.</p>\n\n<pre><code>(gdb) p (NSUInteger)[(NSObject*)$esi retainCount]\nNo symbol table is loaded. Use the \"file\" command.\n(gdb) p [(NSArray *)$esi count]\nNo symbol \"NSArray\" in current context.\n</code></pre>\n\n<p>I tried to load the symbols for Foundation:</p>\n\n<pre><code>(gdb) add-symbol-file /System/Library/Frameworks/Foundation.framework/Foundation \nadd symbol table from file \"/System/Library/Frameworks/Foundation.framework/Foundation\"? (y or n) y\nReading symbols from /System/Library/Frameworks/Foundation.framework/Foundation...done.\n</code></pre>\n\n<p>but still no luck:</p>\n\n<pre><code>(gdb) p [(NSArray *)$esi count]\nNo symbol \"NSArray\" in current context.\n</code></pre>\n\n<p>Anyway, I don't think casting is the solution to this problem, you shouldn't have to know what kind of object it is, to be able to send messages to it.\nThe weird thing is that I found an NSCFArray I have no problems sending messages to:</p>\n\n<pre><code>(gdb) p $eax\n$11 = 367589056\n(gdb) po $eax\n&lt;NSCFArray 0x15e8f6c0&gt;(\n file://localhost/Users/ask/Documents/composing-fractals.pdf\n)\n\n(gdb) p (int)[$eax retainCount]\n$12 = 1\n</code></pre>\n\n<p>so I guess there was a problem with the object I was investigating... or something.</p>\n\n<p>Thanks for your help!</p>\n" }, { "answer_id": 61947, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 4, "selected": true, "text": "<p>If you must override gdb and send a message to an object when it will not let you, you can use performSelector:</p>\n\n<pre><code>(gdb) print (int)[receivedData count]\nTarget does not respond to this message selector.\n\n(gdb) print (int)[receivedData performSelector:@selector(count) ]\n2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]:\nunrecognized selector sent to instance 0x105f2e0\n</code></pre>\n\n<p>If you need to pass an argument use withObject:</p>\n\n<pre><code>(gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ]\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5577/" ]
I'm trying to send messages to Objective-C objects in gdb. ``` (gdb) p $esi $2 = (void *) 0x1268160 (gdb) po $esi <NSArray: 0x1359c0> (gdb) po [$esi count] Target does not respond to this message selector. ``` I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?
If you must override gdb and send a message to an object when it will not let you, you can use performSelector: ``` (gdb) print (int)[receivedData count] Target does not respond to this message selector. (gdb) print (int)[receivedData performSelector:@selector(count) ] 2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]: unrecognized selector sent to instance 0x105f2e0 ``` If you need to pass an argument use withObject: ``` (gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ] ```
56,500
<p>I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put</p> <pre><code>extern "C" _declspec(dllexport) char* MyNewVariable = 0; </code></pre> <p>which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including</p> <pre><code>_declspec(dllimport) char* MyNewVariable; </code></pre> <p>but that just gives me a linker error:</p> <p>unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA)</p> <pre><code>extern "C" _declspec(dllimport) char* MyNewVariable; </code></pre> <p>as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:</p> <p>unresolved external symbol __imp__MyNewVariable</p> <p>How do I write the declaration so that the C++ DLL variable is accessible from the C app?</p> <hr> <h2>The Answer</h2> <p>As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.</p>
[ { "answer_id": 56513, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 2, "selected": false, "text": "<p>extern \"C\" is how you remove decoration - it should work to use:</p>\n\n<p>extern \"C\" declspec(dllimport) char MyNewVariable;</p>\n\n<p>or if you want a header that can be used by C++ or C (with /TC switch)</p>\n\n<pre><code>#ifdef __cplusplus\nextern \"C\" {\n#endif\ndeclspec(dllimport) char MyNewVariable;\n#ifdef __cplusplus\n}\n#endif\n</code></pre>\n\n<p>And of course, link with the import library generated by the dll doing the export.</p>\n" }, { "answer_id": 56514, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 4, "selected": true, "text": "<p>you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the <code>.lib</code> file. And yes, you should also declare the variable as:</p>\n\n<pre><code>extern \"C\" { declspec(dllimport) char MyNewVariable; }\n</code></pre>\n" }, { "answer_id": 56535, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 2, "selected": false, "text": "<p>I'm not sure who downmodded botismarius, because he's right. The reason is the .lib generated is the import library that makes it easy to simply declare the external variable/function with <code>__declspec(dllimport)</code> and just use it. The import library simply automates the necessary <code>LoadLibrary()</code> and <code>GetProcAddress()</code> calls. Without it, you need to call these manually.</p>\n" }, { "answer_id": 56541, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 1, "selected": false, "text": "<p>They're both right. The fact that the error message describes <code>__imp_?MyNewVariable@@3PADA</code> means that it's looking for the decorated name, so the extern \"C\" is necessary. However, linking with the import library is <strong>also</strong> necessary or you'll just get a different link error.</p>\n" }, { "answer_id": 56550, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 1, "selected": false, "text": "<p>@Graeme: You're right on that, too. I think the \"C\" compiler that the OP is using is not enforcing C99 standard, but compiling as C++, thus mangling the names. A true C compiler wouldn't understand the \"C\" part of the <code>extern \"C\"</code> keyword.</p>\n" }, { "answer_id": 56649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I've never used _declspec(dllimport) when I was programming in Windows. You should be able to simply declare </p>\n\n<pre><code>extern \"C\" char* MyNewVariable;\n</code></pre>\n\n<p>and link to the .libb created when DLL was compiled.</p>\n" }, { "answer_id": 57055, "author": "Bart", "author_id": 4343, "author_profile": "https://Stackoverflow.com/users/4343", "pm_score": 1, "selected": false, "text": "<p>In the <strong>dll source code</strong> you should have this implementation so that the .lib file <em>exports</em> the symbol:</p>\n\n<pre><code>extern \"C\" _declspec(dllexport) char* MyNewVariable = 0;\n</code></pre>\n\n<p>The c client should use a <strong>header</strong> with this declaration so that the client code will <em>import</em> the symbol:</p>\n\n<pre><code>extern \"C\" _declspec(dllimport) char* MyNewVariable;\n</code></pre>\n\n<p>This header will cause a compile error if #include-ed in the dll source code, so it is usually put in an export header that is used only for exported functions and only by clients.</p>\n\n<p>If you need to, you can also create a \"universal\" header that can be included anywhere that looks like this:</p>\n\n<pre><code>#ifdef __cplusplus\nextern \"C\" {\n#endif\n#ifdef dll_source_file\n#define EXPORTED declspec(dllexport) \n#else\n#define EXPORTED declspec(dllimport) \n#endif dll_source_file\n#ifdef __cplusplus\n}\n#endif\n\nEXPORTED char* MyNewVariable;\n</code></pre>\n\n<p>Then the dll source code looks like this:</p>\n\n<pre><code>#define dll_source_code \n#include \"universal_header.h\"\n\nEXPORTED char* MyNewVariable = 0;\n</code></pre>\n\n<p>And the client looks like this:</p>\n\n<pre><code>#include \"universal_header.h\"\n...\nMyNewVariable = \"Hello, world\";\n</code></pre>\n\n<p>If you do this a lot, the monster #ifdef at the top can go in export_magic.h and universal_header.h becomes:</p>\n\n<pre><code>#include \"export_magic.h\"\n\nEXPORTED char *MyNewVariable;\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5816/" ]
I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put ``` extern "C" _declspec(dllexport) char* MyNewVariable = 0; ``` which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including ``` _declspec(dllimport) char* MyNewVariable; ``` but that just gives me a linker error: unresolved external symbol "\_\_declspec(dllimport) char \* MyNewVariable" (\_\_imp\_?MyNewVariable@@3PADA) ``` extern "C" _declspec(dllimport) char* MyNewVariable; ``` as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it: unresolved external symbol \_\_imp\_\_MyNewVariable How do I write the declaration so that the C++ DLL variable is accessible from the C app? --- The Answer ---------- As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.
you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the `.lib` file. And yes, you should also declare the variable as: ``` extern "C" { declspec(dllimport) char MyNewVariable; } ```
56,521
<p>I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type <code>double?</code> (or <code>Nullable&lt;double&gt;</code>). It's nullable to support the case where the user doesn't enter anything.</p> <p>The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():</p> <pre><code>this.numericTextBox1.Value = 1; </code></pre> <p>Remember 'Value' is of type <code>Nullable&lt;double&gt;</code>. This generates the following warning whenever I try to reopen the form in the Designer:</p> <pre><code>Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'. </code></pre> <p>As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.</p> <p>Any suggestions?</p>
[ { "answer_id": 56528, "author": "Alex Duggleby", "author_id": 5790, "author_profile": "https://Stackoverflow.com/users/5790", "pm_score": -1, "selected": false, "text": "<p>Could it help to setting the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(VS.80).aspx\" rel=\"nofollow noreferrer\">DefaultValue attribute</a> on that property to new Nullable(1)?</p>\n\n<pre><code>[DefaultValue(new Nullable&lt;double&gt;(1))] \npublic double? Value ...\n</code></pre>\n" }, { "answer_id": 56533, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 3, "selected": true, "text": "<p>Or, if you don't want the designer adding any code at all... add this to the Property.</p>\n\n<pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n</code></pre>\n" }, { "answer_id": 12729701, "author": "Svetlin Ralchev", "author_id": 538886, "author_profile": "https://Stackoverflow.com/users/538886", "pm_score": 2, "selected": false, "text": "<p>It seems that there is an issue in Visual Studio 2008. You should create custom CodeDomSerializer to work around it:</p>\n\n<pre><code>public class CategoricalDataPointCodeDomSerializer : CodeDomSerializer\n{\n public override object Deserialize(IDesignerSerializationManager manager, object codeObject)\n {\n CodeStatementCollection collection = codeObject as CodeStatementCollection;\n\n if (collection != null)\n {\n foreach (CodeStatement statement in collection)\n {\n CodeAssignStatement codeAssignment = statement as CodeAssignStatement;\n\n if (codeAssignment != null)\n {\n CodePropertyReferenceExpression properyRef = codeAssignment.Left as CodePropertyReferenceExpression;\n CodePrimitiveExpression primitiveExpression = codeAssignment.Right as CodePrimitiveExpression;\n\n if (properyRef != null &amp;&amp; properyRef.PropertyName == \"Value\" &amp;&amp; primitiveExpression != null &amp;&amp; primitiveExpression.Value != null)\n {\n primitiveExpression.Value = Convert.ToDouble(primitiveExpression.Value);\n break;\n }\n }\n }\n }\n\n return base.Deserialize(manager, codeObject);\n }\n}\n</code></pre>\n\n<p>Then you should apply it by using the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.design.serialization.designerserializerattribute.aspx\" rel=\"nofollow\">DesignerSerializer</a> attribute on your class.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type `double?` (or `Nullable<double>`). It's nullable to support the case where the user doesn't enter anything. The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent(): ``` this.numericTextBox1.Value = 1; ``` Remember 'Value' is of type `Nullable<double>`. This generates the following warning whenever I try to reopen the form in the Designer: ``` Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'. ``` As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying. Any suggestions?
Or, if you don't want the designer adding any code at all... add this to the Property. ``` [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] ```
56,547
<p>How do you perform a CROSS JOIN with LINQ to SQL?</p>
[ { "answer_id": 56612, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 8, "selected": true, "text": "<p>A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.</p>\n\n<pre>\nvar combo = from p in people\n from c in cars\n select new\n {\n p.Name,\n c.Make,\n c.Model,\n c.Colour\n };\n</pre>\n" }, { "answer_id": 679174, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": false, "text": "<p>Based on Steve's answer, the simplest expression would be this:</p>\n\n<pre><code>var combo = from Person in people\n from Car in cars\n select new {Person, Car};\n</code></pre>\n" }, { "answer_id": 11395783, "author": "Rzv.im", "author_id": 1474780, "author_profile": "https://Stackoverflow.com/users/1474780", "pm_score": 5, "selected": false, "text": "<p>The same thing with the Linq extension method <code>SelectMany</code> (lambda syntax):</p>\n<pre><code>var names = new string[] { &quot;Ana&quot;, &quot;Raz&quot;, &quot;John&quot; };\nvar numbers = new int[] { 1, 2, 3 };\nvar newList=names.SelectMany(\n x =&gt; numbers,\n (y, z) =&gt; { return y + z + &quot; test &quot;; });\nforeach (var item in newList)\n{\n Console.WriteLine(item);\n}\n</code></pre>\n" }, { "answer_id": 18937903, "author": "amoss", "author_id": 208068, "author_profile": "https://Stackoverflow.com/users/208068", "pm_score": 4, "selected": false, "text": "<p>A <code>Tuple</code> is a good type for Cartesian product:</p>\n\n<pre><code>public static IEnumerable&lt;Tuple&lt;T1, T2&gt;&gt; CrossJoin&lt;T1, T2&gt;(IEnumerable&lt;T1&gt; sequence1, IEnumerable&lt;T2&gt; sequence2)\n{\n return sequence1.SelectMany(t1 =&gt; sequence2.Select(t2 =&gt; Tuple.Create(t1, t2)));\n}\n</code></pre>\n" }, { "answer_id": 36089869, "author": "Denis", "author_id": 400589, "author_profile": "https://Stackoverflow.com/users/400589", "pm_score": 3, "selected": false, "text": "<p>Extension Method:</p>\n\n<pre><code>public static IEnumerable&lt;Tuple&lt;T1, T2&gt;&gt; CrossJoin&lt;T1, T2&gt;(this IEnumerable&lt;T1&gt; sequence1, IEnumerable&lt;T2&gt; sequence2)\n{\n return sequence1.SelectMany(t1 =&gt; sequence2.Select(t2 =&gt; Tuple.Create(t1, t2)));\n}\n</code></pre>\n\n<p>And use like:</p>\n\n<pre><code>vals1.CrossJoin(vals2)\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556/" ]
How do you perform a CROSS JOIN with LINQ to SQL?
A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it. ``` var combo = from p in people from c in cars select new { p.Name, c.Make, c.Model, c.Colour }; ```
56,554
<p>Let's say I want to represent <code>\q</code> (or any other particular "backslash-escaped character"). That is, I want to match <code>\q</code> but not <code>\\q</code>, since the latter is a backslash-escaped backslash followed by a <code>q</code>. Yet <code>\\\q</code> would match, since it's a backslash-escaped backslash followed by a backslash-escaped <code>q</code>. (Well, it would match the <code>\q</code> at the end, not the <code>\\</code> at the beginning.)</p> <p>I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.</p>
[ { "answer_id": 56583, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.codinghorror.com/blog/archives/001016.html\" rel=\"nofollow noreferrer\">Now You Have Two Problems</a>.</p>\n\n<p>Just write a simple parser. If the regex ties your head up in knots now, just wait a month.</p>\n" }, { "answer_id": 56668, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": -1, "selected": false, "text": "<p>The best solution to this is to do your own string parsing as Regular Expressions don't really support what you are trying to do. (rep @Frank Krueger if you go this way, I'm just repeating his advice)</p>\n\n<p>I did however take a shot at a exclusionary regex. This will match all strings that do not fit your criteria of a \"\\\" followed by a character.</p>\n\n<pre><code>(?:[\\\\][\\\\])(?!(([\\\\](?![\\\\])[a-zA-Z])))\n</code></pre>\n" }, { "answer_id": 56671, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": true, "text": "<p>Updated:\nMy new and improved Perl regex, supporting more than 3 backslashes:</p>\n\n<pre>/(?&lt;!\\\\) # Not preceded by a single backslash\n (?>\\\\\\\\)* # an even number of backslashes\n \\\\q # Followed by a \\q\n /x;</pre>\n\n<p>or if your regex library doesn't support extended syntax.</p>\n\n<pre>/(?&lt;!\\\\)(?>\\\\\\\\)*\\\\q/</pre>\n\n<p>Output of my test program:</p>\n\n<pre>q does not match\n\\q does match\n\\\\q does not match\n\\\\\\q does match\n\\\\\\\\q does not match\n\\\\\\\\\\q does match</pre>\n\n<p>Older version</p>\n\n<pre>/(?:(?&lt;!\\\\)|(?&lt;=\\\\\\\\))\\\\q/</pre>\n" }, { "answer_id": 56842, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/56671/6761181\">Leon Timmermans</a> got exactly what I was looking for. I would add one small improvement for those who come here later:</p>\n\n<pre><code>/(?&lt;!\\\\)(?:\\\\\\\\)*\\\\q/\n</code></pre>\n\n<p>The additional <code>?:</code> at the beginning of the <code>(\\\\\\\\)</code> group makes it not saved into any match-data. I can't imagine a scenario where I'd want the text of that saved.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
Let's say I want to represent `\q` (or any other particular "backslash-escaped character"). That is, I want to match `\q` but not `\\q`, since the latter is a backslash-escaped backslash followed by a `q`. Yet `\\\q` would match, since it's a backslash-escaped backslash followed by a backslash-escaped `q`. (Well, it would match the `\q` at the end, not the `\\` at the beginning.) I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.
Updated: My new and improved Perl regex, supporting more than 3 backslashes: ``` /(?<!\\) # Not preceded by a single backslash (?>\\\\)* # an even number of backslashes \\q # Followed by a \q /x; ``` or if your regex library doesn't support extended syntax. ``` /(?<!\\)(?>\\\\)*\\q/ ``` Output of my test program: ``` q does not match \q does match \\q does not match \\\q does match \\\\q does not match \\\\\q does match ``` Older version ``` /(?:(?<!\\)|(?<=\\\\))\\q/ ```
56,568
<p>How do you actually perform datetime operations such as adding date, finding difference, find out how many days excluding weekends in an interval? I personally started to pass some of these operations to my postgresql dbms as typically I would only need to issue one sql statement to obtain an answer, however, to do it in PHP way I would have to write a lot more code that means more chances for errors to occur...</p> <p>Are there any libraries in PHP that does datetime operation in a way that don't require a lot of code? that beats sql in a situation where 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet_lang' that is solved by making this query?</p> <pre class="lang-sql prettyprint-override"><code>SELECT COUNT(*) AS total_days FROM (SELECT date '2008-8-26' + generate_series(0, (date '2008-9-1' - date '2008-8-26')) AS all_days) AS calendar WHERE EXTRACT(isodow FROM all_days) &lt; 6; </code></pre>
[ { "answer_id": 56595, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 3, "selected": false, "text": "<p>While for most datetime operations I would normally convert to Unixtime and perform addition subtraction etc. on the Unixtime integer, you may want to look at the Zend framework Zend_Date class. </p>\n\n<p>This has a lot of the functionality you describe. Although Zend is billed as a \"framework\" it works exceptionally well as a class library to pick and chose elements from. We routinely include it in projects and then just pull in bits as and when we need them. </p>\n" }, { "answer_id": 56606, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 1, "selected": false, "text": "<p>The easiest method is to use a timestamp, representing the number of seconds since January 1, 2008. With a timestamp type, you can do things like...</p>\n\n<pre><code>now = time();\ntomorrow = now + 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds\n</code></pre>\n\n<p>Check out the documentation for <a href=\"http://us2.php.net/manual/en/function.time.php\" rel=\"nofollow noreferrer\">time()</a>, <a href=\"http://us2.php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\">date()</a> and <a href=\"http://us2.php.net/manual/en/function.mktime.php\" rel=\"nofollow noreferrer\">mktime()</a> on the php web pages. Those are the three methods that I tend to use the most frequently.</p>\n" }, { "answer_id": 56900, "author": "Rushi", "author_id": 3983, "author_profile": "https://Stackoverflow.com/users/3983", "pm_score": 0, "selected": false, "text": "<p>You can use a combination of <a href=\"http://php.net/strtotime\" rel=\"nofollow noreferrer\">strtotime</a>, <a href=\"http://php.net/mktime\" rel=\"nofollow noreferrer\">mktime</a> and <a href=\"http://php.net/date\" rel=\"nofollow noreferrer\">date</a> todo the arithmetic</p>\n\n<p>Here is an example which uses a combo todo some arithmetic <a href=\"http://rushi.wordpress.com/2008/04/13/php-print-out-age-of-date-in-words/\" rel=\"nofollow noreferrer\">http://rushi.wordpress.com/2008/04/13/php-print-out-age-of-date-in-words/</a> I'll reproduce the code here for simplicity\n \n\n<pre><code>if ($timestamp_diff &lt; (60*60*24*7)) {\n echo floor($timestamp_diff/60/60/24).\" Days\";\n} elseif ($timestamp_diff &gt; (60*60*24*7*4)) {\n echo floor($timestamp_diff/60/60/24/7).\" Weeks\";\n} else {\n $total_months = $months = floor($timestamp_diff/60/60/24/30);\n if($months &gt;= 12) {\n $months = ($total_months % 12);\n $years&amp;nbsp; = ($total_months - $months)/12;\n echo $years . \" Years \";\n }\n if($months &gt; 0)\n echo $months . \" Months\";\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 56930, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 0, "selected": false, "text": "<p>@Rushi I don't like strtotime() personally.. i don't know why but i discovered this morning that passing a string like this '2008-09-11 9:5 AM' to strtotime returns a false...</p>\n\n<p>I don't think the code you provided solve the example problem 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet_lang' and I haven't consider if I have a list of public holiday...</p>\n" }, { "answer_id": 57039, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://pear.php.net/package/Date\" rel=\"nofollow noreferrer\"><code>PEAR::Date</code></a> looks like it might have some useful functionality.</p>\n\n<p><a href=\"https://pear.php.net/package/Calendar\" rel=\"nofollow noreferrer\"><code>PEAR::Calendar</code></a> might also be useful.</p>\n" }, { "answer_id": 57717, "author": "Laith", "author_id": 5961, "author_profile": "https://Stackoverflow.com/users/5961", "pm_score": 2, "selected": false, "text": "<p>strtotime() is useful but it does have some odd behaviors that can pop-up from time to time if you are not just using it to convert a formatted date/time string.</p>\n\n<p>things like \"+1 month\" or \"-3 days\" can sometimes not give you what you expect it to output.</p>\n" }, { "answer_id": 58545, "author": "ralfe", "author_id": 340241, "author_profile": "https://Stackoverflow.com/users/340241", "pm_score": 0, "selected": false, "text": "<p>If you have a look at <a href=\"http://php.net/date\" rel=\"nofollow noreferrer\">http://php.net/date</a> , you will find some examples of using <code>mktime()</code> to perform operations.</p>\n\n<p>A simple example would be to workout what tomorrows date would be. You can do that by simply adding 1, to the day value in <code>mktime()</code> as follows:</p>\n\n<pre><code>$tomorrow = date(\"Y-m-d\", mktime(0, 0, 0, date(\"m\"), date(\"d\") + 1, date(\"Y\")));\n</code></pre>\n\n<p>So here, you will receive a date in the form of YYYY-MM-DD containing tomorrows date. You can also subtract days by simply replacing '+' with '-'. <code>mktime()</code> makes life a lot easier, and saves you from having to do nested if statements and other such troublesome coding.</p>\n" }, { "answer_id": 58603, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 0, "selected": false, "text": "<p>You can get number of days between two dates like this:</p>\n\n<pre><code>$days = (strtotime(\"2008-09-10\") - strtotime(\"2008-09-12\")) / (60 * 60 * 24);\n</code></pre>\n\n<p>And you can make function something like that (I don't have php installed in my work computer so i can't guarantee syntax is 100% correct)</p>\n\n<pre><code>function isWorkDay($date)\n{\n // check if workday and return true if so\n}\n\nfunction numberOfWorkDays($startdate, $enddate)\n{\n $workdays = 0;\n $tmp = strtotime($startdate);\n $end = strtotime($enddate);\n while($tmp &lt;= $end)\n {\n if ( isWorkDay( date(\"Y-m-d\",$tmp) ) ) $workdays++;\n $tmp += 60*60*24;\n }\n return $workdays;\n}\n</code></pre>\n\n<p>If you don't like strtotime and you always have date in same format you can use explode function like </p>\n\n<pre><code>list($year, $month, day) = explode(\"-\", $date);\n</code></pre>\n" }, { "answer_id": 60699, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 0, "selected": false, "text": "<p>I would strongly recommend using PHP 5.2's <a href=\"http://us2.php.net/datetime\" rel=\"nofollow noreferrer\">DateTime objects</a>, rather than using UNIX timestamps, when doing date calculations. When you use the PHP date functions that return UNIX timestamps, you have a very limited range to work with (e.g. nothing before 1970).</p>\n" }, { "answer_id": 201180, "author": "user13414", "author_id": 13414, "author_profile": "https://Stackoverflow.com/users/13414", "pm_score": 3, "selected": true, "text": "<p>PHP5+'s DateTime object is useful because it is leap time and\ndaylight savings aware, but it needs some extension to really\nsolve the problem. I wrote the following to solve a similar problem.\nThe find_WeekdaysFromThisTo() method is brute-force, but it works reasonably quickly if your time span is less than 2 years.</p>\n\n<pre><code>$tryme = new Extended_DateTime('2007-8-26');\n$newer = new Extended_DateTime('2008-9-1');\n\nprint 'Weekdays From '.$tryme-&gt;format('Y-m-d').' To '.$newer-&gt;format('Y-m-d').': '.$tryme -&gt; find_WeekdaysFromThisTo($newer) .\"\\n\";\n/* Output: Weekdays From 2007-08-26 To 2008-09-01: 265 */\nprint 'All Days From '.$tryme-&gt;format('Y-m-d').' To '.$newer-&gt;format('Y-m-d').': '.$tryme -&gt; find_AllDaysFromThisTo($newer) .\"\\n\";\n/* Output: All Days From 2007-08-26 To 2008-09-01: 371 */\n$timefrom = $tryme-&gt;find_TimeFromThisTo($newer);\nprint 'Between '.$tryme-&gt;format('Y-m-d').' and '.$newer-&gt;format('Y-m-d').' there are '.\n $timefrom['years'].' years, '.$timefrom['months'].' months, and '.$timefrom['days'].\n ' days.'.\"\\n\";\n/* Output: Between 2007-08-26 and 2008-09-01 there are 1 years, 0 months, and 5 days. */\n\nclass Extended_DateTime extends DateTime {\n\n public function find_TimeFromThisTo($newer) {\n $timefrom = array('years'=&gt;0,'months'=&gt;0,'days'=&gt;0);\n\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n\n $timefrom['years'] = $this-&gt;find_YearsFromThisTo($testnewer);\n $mod = '-'.$timefrom['years'].' years';\n $testnewer -&gt; modify($mod);\n\n $timefrom['months'] = $this-&gt;find_MonthsFromThisTo($testnewer);\n $mod = '-'.$timefrom['months'].' months';\n $testnewer -&gt; modify($mod);\n\n $timefrom['days'] = $this-&gt;find_AllDaysFromThisTo($testnewer);\n return $timefrom;\n } // end function find_TimeFromThisTo\n\n\n public function find_YearsFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer-&gt;format('U') &lt; $this-&gt;format('U'))\n return FALSE;\n $count = 0;\n\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n\n $testnewer -&gt; modify ('-1 year');\n while ( $this-&gt;format('U') &lt; $testnewer-&gt;format('U')) {\n $count ++;\n $testnewer -&gt; modify ('-1 year');\n }\n return $count;\n } // end function find_YearsFromThisTo\n\n\n public function find_MonthsFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer-&gt;format('U') &lt; $this-&gt;format('U'))\n return FALSE;\n\n $count = 0;\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n $testnewer -&gt; modify ('-1 month');\n\n while ( $this-&gt;format('U') &lt; $testnewer-&gt;format('U')) {\n $count ++;\n $testnewer -&gt; modify ('-1 month');\n }\n return $count;\n } // end function find_MonthsFromThisTo\n\n\n public function find_AllDaysFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer-&gt;format('U') &lt; $this-&gt;format('U'))\n return FALSE;\n\n $count = 0;\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n $testnewer -&gt; modify ('-1 day');\n\n while ( $this-&gt;format('U') &lt; $testnewer-&gt;format('U')) {\n $count ++;\n $testnewer -&gt; modify ('-1 day');\n }\n return $count;\n } // end function find_AllDaysFromThisTo\n\n\n public function find_WeekdaysFromThisTo($newer) {\n /*\n If the passed is:\n not an object, not of class DateTime or one of its children,\n or not larger (after) $this\n return false\n */\n if (!is_object($newer) || !($newer instanceof DateTime) || $newer-&gt;format('U') &lt; $this-&gt;format('U'))\n return FALSE;\n\n $count = 0;\n\n // Clone because we're using modify(), which will destroy the object that was passed in by reference\n $testnewer = clone $newer;\n $testnewer -&gt; modify ('-1 day');\n\n while ( $this-&gt;format('U') &lt; $testnewer-&gt;format('U')) {\n // If the calculated day is not Sunday or Saturday, count this day\n if ($testnewer-&gt;format('w') != '0' &amp;&amp; $testnewer-&gt;format('w') != '6')\n $count ++;\n $testnewer -&gt; modify ('-1 day');\n }\n return $count;\n } // end function find_WeekdaysFromThisTo\n\n public function set_Day($newday) {\n if (is_int($newday) &amp;&amp; $newday &gt; 0 &amp;&amp; $newday &lt; 32 &amp;&amp; checkdate($this-&gt;format('m'),$newday,$this-&gt;format('Y')))\n $this-&gt;setDate($this-&gt;format('Y'),$this-&gt;format('m'),$newday);\n } // end function set_Day\n\n\n public function set_Month($newmonth) {\n if (is_int($newmonth) &amp;&amp; $newmonth &gt; 0 &amp;&amp; $newmonth &lt; 13)\n $this-&gt;setDate($this-&gt;format('Y'),$newmonth,$this-&gt;format('d'));\n } // end function set_Month\n\n\n public function set_Year($newyear) {\n if (is_int($newyear) &amp;&amp; $newyear &gt; 0)\n $this-&gt;setDate($newyear,$this-&gt;format('m'),$this-&gt;format('d'));\n } // end function set_Year\n} // end class Extended_DateTime\n</code></pre>\n" }, { "answer_id": 2013493, "author": "Vince Bowdren", "author_id": 174843, "author_profile": "https://Stackoverflow.com/users/174843", "pm_score": 2, "selected": false, "text": "<p>For adding a date, you can use the method <strong>DateTime::add</strong> (<em>Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object</em>), available from php 5.3.0 onwards.</p>\n\n<p>To find the difference between two dates, there's the <strong>DateTime::diff</strong> method; but there doesn't seem to be a method for counting the working days between two dates.</p>\n" }, { "answer_id": 6645826, "author": "helmi03", "author_id": 169469, "author_profile": "https://Stackoverflow.com/users/169469", "pm_score": -1, "selected": false, "text": "<p>to get working days/holidays, postgresql CTE ftw -- see <a href=\"http://osssmb.wordpress.com/2009/12/02/business-days-working-days-sql-for-postgres-2/\" rel=\"nofollow\">http://osssmb.wordpress.com/2009/12/02/business-days-working-days-sql-for-postgres-2/</a></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5742/" ]
How do you actually perform datetime operations such as adding date, finding difference, find out how many days excluding weekends in an interval? I personally started to pass some of these operations to my postgresql dbms as typically I would only need to issue one sql statement to obtain an answer, however, to do it in PHP way I would have to write a lot more code that means more chances for errors to occur... Are there any libraries in PHP that does datetime operation in a way that don't require a lot of code? that beats sql in a situation where 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet\_lang' that is solved by making this query? ```sql SELECT COUNT(*) AS total_days FROM (SELECT date '2008-8-26' + generate_series(0, (date '2008-9-1' - date '2008-8-26')) AS all_days) AS calendar WHERE EXTRACT(isodow FROM all_days) < 6; ```
PHP5+'s DateTime object is useful because it is leap time and daylight savings aware, but it needs some extension to really solve the problem. I wrote the following to solve a similar problem. The find\_WeekdaysFromThisTo() method is brute-force, but it works reasonably quickly if your time span is less than 2 years. ``` $tryme = new Extended_DateTime('2007-8-26'); $newer = new Extended_DateTime('2008-9-1'); print 'Weekdays From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_WeekdaysFromThisTo($newer) ."\n"; /* Output: Weekdays From 2007-08-26 To 2008-09-01: 265 */ print 'All Days From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_AllDaysFromThisTo($newer) ."\n"; /* Output: All Days From 2007-08-26 To 2008-09-01: 371 */ $timefrom = $tryme->find_TimeFromThisTo($newer); print 'Between '.$tryme->format('Y-m-d').' and '.$newer->format('Y-m-d').' there are '. $timefrom['years'].' years, '.$timefrom['months'].' months, and '.$timefrom['days']. ' days.'."\n"; /* Output: Between 2007-08-26 and 2008-09-01 there are 1 years, 0 months, and 5 days. */ class Extended_DateTime extends DateTime { public function find_TimeFromThisTo($newer) { $timefrom = array('years'=>0,'months'=>0,'days'=>0); // Clone because we're using modify(), which will destroy the object that was passed in by reference $testnewer = clone $newer; $timefrom['years'] = $this->find_YearsFromThisTo($testnewer); $mod = '-'.$timefrom['years'].' years'; $testnewer -> modify($mod); $timefrom['months'] = $this->find_MonthsFromThisTo($testnewer); $mod = '-'.$timefrom['months'].' months'; $testnewer -> modify($mod); $timefrom['days'] = $this->find_AllDaysFromThisTo($testnewer); return $timefrom; } // end function find_TimeFromThisTo public function find_YearsFromThisTo($newer) { /* If the passed is: not an object, not of class DateTime or one of its children, or not larger (after) $this return false */ if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U')) return FALSE; $count = 0; // Clone because we're using modify(), which will destroy the object that was passed in by reference $testnewer = clone $newer; $testnewer -> modify ('-1 year'); while ( $this->format('U') < $testnewer->format('U')) { $count ++; $testnewer -> modify ('-1 year'); } return $count; } // end function find_YearsFromThisTo public function find_MonthsFromThisTo($newer) { /* If the passed is: not an object, not of class DateTime or one of its children, or not larger (after) $this return false */ if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U')) return FALSE; $count = 0; // Clone because we're using modify(), which will destroy the object that was passed in by reference $testnewer = clone $newer; $testnewer -> modify ('-1 month'); while ( $this->format('U') < $testnewer->format('U')) { $count ++; $testnewer -> modify ('-1 month'); } return $count; } // end function find_MonthsFromThisTo public function find_AllDaysFromThisTo($newer) { /* If the passed is: not an object, not of class DateTime or one of its children, or not larger (after) $this return false */ if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U')) return FALSE; $count = 0; // Clone because we're using modify(), which will destroy the object that was passed in by reference $testnewer = clone $newer; $testnewer -> modify ('-1 day'); while ( $this->format('U') < $testnewer->format('U')) { $count ++; $testnewer -> modify ('-1 day'); } return $count; } // end function find_AllDaysFromThisTo public function find_WeekdaysFromThisTo($newer) { /* If the passed is: not an object, not of class DateTime or one of its children, or not larger (after) $this return false */ if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U')) return FALSE; $count = 0; // Clone because we're using modify(), which will destroy the object that was passed in by reference $testnewer = clone $newer; $testnewer -> modify ('-1 day'); while ( $this->format('U') < $testnewer->format('U')) { // If the calculated day is not Sunday or Saturday, count this day if ($testnewer->format('w') != '0' && $testnewer->format('w') != '6') $count ++; $testnewer -> modify ('-1 day'); } return $count; } // end function find_WeekdaysFromThisTo public function set_Day($newday) { if (is_int($newday) && $newday > 0 && $newday < 32 && checkdate($this->format('m'),$newday,$this->format('Y'))) $this->setDate($this->format('Y'),$this->format('m'),$newday); } // end function set_Day public function set_Month($newmonth) { if (is_int($newmonth) && $newmonth > 0 && $newmonth < 13) $this->setDate($this->format('Y'),$newmonth,$this->format('d')); } // end function set_Month public function set_Year($newyear) { if (is_int($newyear) && $newyear > 0) $this->setDate($newyear,$this->format('m'),$this->format('d')); } // end function set_Year } // end class Extended_DateTime ```
56,574
<p>A while back I was reading the W3C article on '<a href="http://www.w3.org/International/articles/text-reuse/" rel="noreferrer">Re-using Strings in Scripted Content</a>', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code.</p> <p>To take their example, we might have some code like this...</p> <pre><code>print "The printer is "; if (printer.working) { print "on.\n"; } else { print "off.\n"; } print "The stapler is "; if (stapler.working) { print "on.\n"; } else { print "off.\n"; } </code></pre> <p>My instinct would be to eliminate the repetition roughly as follows...</p> <pre><code>report-state(printer, "printer"); report-state(stapler, "stapler"); function report-state(name, object) { print "The "+name+" is "; if (object.working) { print "on\n"; } else { print "off\n"; } } </code></pre> <p>...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases.</p> <p>So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code?</p> <p>Part of me wants to argue that internationalisation is one of those extreme programming “<a href="http://www.extremeprogramming.org/rules/early.html" rel="noreferrer">you arent gonna need it</a>” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here.</p>
[ { "answer_id": 56609, "author": "badbod99", "author_id": 3614, "author_profile": "https://Stackoverflow.com/users/3614", "pm_score": 0, "selected": false, "text": "<p>I would suggest using a CMS rather than hardcoding in your textual values to cover localisation.</p>\n" }, { "answer_id": 56617, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 5, "selected": true, "text": "<p>I'd try to keep complete sentences in the language resource. As you said you might need different words in different contexts. But a bigger problem is that the order of sentences might be different in different languages. So building up strings from words can cause problems.</p>\n\n<p>Just store</p>\n\n<pre><code>The printer is on\nThe printer is off\nThe stapler is on\nThe stapler is off\n</code></pre>\n\n<p>in the language resource for every language. The repetition here is less of a maintenance headache than trying to figure out where all the single words are going to pop up in your application.</p>\n" }, { "answer_id": 56640, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>I agree with Mendelt Siebenga when he says you should keep entire sentences or phrases in your language resource files. Differences in grammar will always prevent you from doing single word replacement across languages. This will still lead to less repetitive code than your first example because you only need to check the object type and its state, then print the appropriate message from the language resource.</p>\n" }, { "answer_id": 56651, "author": "Chris McAtackney", "author_id": 5827, "author_profile": "https://Stackoverflow.com/users/5827", "pm_score": 1, "selected": false, "text": "<p>I suppose it depends on the level of language quality that you are aiming to achieve.</p>\n\n<p>By trying to minimise repetition of code that deals with these real language strings, you are just exposing yourself to a whole other layer of logic in the syntaxes and structures of different languages. There would be a massive amount of work involved in producing code which still retains the original structure of the language whilst minimising repetition.</p>\n\n<p>You'd have to decide which was a more suitable approach to a particular problem; Code that repeats itself, or code that tries to be a Jack of all Trades and accomodates for countless rules of language (no doubt a maintenance nightmare).</p>\n\n<p>Of course, you can strike a middle-ground and minimise your code repitition but give up satisfactory grammatical eloquence. Take the example of Ultima Online - when it was localised, a string that previously read \"A pile of 329 gold coins\" became something like \"A pile of gold coins: 329\". Not great, but a fairly reasonable solution that lends itself easily to localisation.</p>\n" }, { "answer_id": 60925, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 2, "selected": false, "text": "<p>We try not to create message strings by program manipulation because the loc. team can't see them.</p>\n\n<p>The loc. team actually prefer separate but nearly duplicate messages. \nHowever they will accept parameterized messages.</p>\n\n<p>E.g., \"The %(appliance)% is %(on_or_off)%.\"</p>\n\n<p>The parameters can break down but at least it's more obvious to the loc team when it will work and when it won't.</p>\n" }, { "answer_id": 103623, "author": "user19050", "author_id": 19050, "author_profile": "https://Stackoverflow.com/users/19050", "pm_score": 3, "selected": false, "text": "<p>100% agree with Mendelt.</p>\n\n<p>It is not only a maintenance problem, but can also be a linguistic one.\nIn all Latin languages the gender, number, and case of the subject affect other elements.\nExample for Romanian</p>\n\n<pre><code> The printer is on: Imprimanta este pornită // feminine\n The printer is off: Imprimanta este oprită\n The stapler is on: Perforatorul este pornit // masculine\n The stapler is off: Perforatorul este oprit\n</code></pre>\n\n<p>Also see <a href=\"http://www.mihai-nita.net/article.php?artID=20060430a\" rel=\"noreferrer\">http://www.mihai-nita.net/article.php?artID=20060430a</a></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
A while back I was reading the W3C article on '[Re-using Strings in Scripted Content](http://www.w3.org/International/articles/text-reuse/)', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code. To take their example, we might have some code like this... ``` print "The printer is "; if (printer.working) { print "on.\n"; } else { print "off.\n"; } print "The stapler is "; if (stapler.working) { print "on.\n"; } else { print "off.\n"; } ``` My instinct would be to eliminate the repetition roughly as follows... ``` report-state(printer, "printer"); report-state(stapler, "stapler"); function report-state(name, object) { print "The "+name+" is "; if (object.working) { print "on\n"; } else { print "off\n"; } } ``` ...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases. So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code? Part of me wants to argue that internationalisation is one of those extreme programming “[you arent gonna need it](http://www.extremeprogramming.org/rules/early.html)” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here.
I'd try to keep complete sentences in the language resource. As you said you might need different words in different contexts. But a bigger problem is that the order of sentences might be different in different languages. So building up strings from words can cause problems. Just store ``` The printer is on The printer is off The stapler is on The stapler is off ``` in the language resource for every language. The repetition here is less of a maintenance headache than trying to figure out where all the single words are going to pop up in your application.
56,591
<p>Ok, this is bit of an obscure question, but hopefully someone can help me out with it.</p> <p>The system I'm working on builds a dynamic SQL string for execution inside a stored procedure, and part of that dynamic SQL defining column aliases, which themselves are actually values retrieved from another table of user generated data.</p> <p>So, for example, the string might look something like;</p> <pre><code>SELECT table1.Col1 AS "This is an alias" FROM table1 </code></pre> <p>This works fine. However, the value that is used for the alias can potentially contain a double quote character, which breaks the outer quotes. I thought that I could maybe escape double quotes inside the alias somehow, but I've had no luck figuring out how to do so. Backslash doesn't work, and using two double quotes in a row results in this error;</p> <pre><code>SQL Error: ORA-03001: unimplemented feature 03001. 00000 - "unimplemented feature" *Cause: This feature is not implemented. </code></pre> <p>Has anyone had any experience with this issue before? Cheers for any insight anyone has.</p> <p>p.s. the quotes are needed around the aliases because they can contain spaces.</p>
[ { "answer_id": 56636, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "<p>When I run this:</p>\n\n<pre><code>select 'test\"columnname\"' from dual\n</code></pre>\n\n<p>Oracle returns this (notice the Oracle-generated column name):</p>\n\n<pre><code>'TESTCOLUMNNAME'\n--------------------------------\ntest\"columnname\n</code></pre>\n\n<p>The fact that Oracle's column name doesn't include my double-quote tells me that Oracle probably cannot represent that.</p>\n\n<p>Best bet as far as I can see is to strip double-quotes from your data prior to using column names. Sadly, that will also require that you do the same filtering when you <em>select</em> those columns, but I don't see another way.</p>\n" }, { "answer_id": 56711, "author": "ibz", "author_id": 5475, "author_profile": "https://Stackoverflow.com/users/5475", "pm_score": 3, "selected": true, "text": "<p>Can you just put another character instead of double quotes and replace that with double quotes in the code?</p>\n\n<p>Something like this:</p>\n\n<pre><code>SELECT table1.Col1 AS \"This is |not| an alias\" FROM table1\n</code></pre>\n\n<p>Then just replace | with \".</p>\n\n<p>I know it's a hack, but I can't think of any better solution... And what you are doing there is a hack anyway. The \"nice\" way would be to select the values and the column names separately and associate them in your code. That would make things much cleaner.</p>\n" }, { "answer_id": 75473, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>a possibly fruitful area of investigation would be to look into the quote method. <br></p>\n\n<p><strong>my $quotedString = $dbh->quote( $string );</strong> <br></p>\n" }, { "answer_id": 2182542, "author": "swissunix", "author_id": 251361, "author_profile": "https://Stackoverflow.com/users/251361", "pm_score": 2, "selected": false, "text": "<p>use the Oracle quote operator:</p>\n\n<pre><code>select q'#someone's quote#' from dual;\n</code></pre>\n\n<p>the '#' can be replaced by any character</p>\n" }, { "answer_id": 18954073, "author": "Artem", "author_id": 2806242, "author_profile": "https://Stackoverflow.com/users/2806242", "pm_score": 0, "selected": false, "text": "<p>Try this, two single quotes actually look like one double quote in output:<br>\n<code>select 1 as \"University ''John Smith''\" from dual;</code></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827/" ]
Ok, this is bit of an obscure question, but hopefully someone can help me out with it. The system I'm working on builds a dynamic SQL string for execution inside a stored procedure, and part of that dynamic SQL defining column aliases, which themselves are actually values retrieved from another table of user generated data. So, for example, the string might look something like; ``` SELECT table1.Col1 AS "This is an alias" FROM table1 ``` This works fine. However, the value that is used for the alias can potentially contain a double quote character, which breaks the outer quotes. I thought that I could maybe escape double quotes inside the alias somehow, but I've had no luck figuring out how to do so. Backslash doesn't work, and using two double quotes in a row results in this error; ``` SQL Error: ORA-03001: unimplemented feature 03001. 00000 - "unimplemented feature" *Cause: This feature is not implemented. ``` Has anyone had any experience with this issue before? Cheers for any insight anyone has. p.s. the quotes are needed around the aliases because they can contain spaces.
Can you just put another character instead of double quotes and replace that with double quotes in the code? Something like this: ``` SELECT table1.Col1 AS "This is |not| an alias" FROM table1 ``` Then just replace | with ". I know it's a hack, but I can't think of any better solution... And what you are doing there is a hack anyway. The "nice" way would be to select the values and the column names separately and associate them in your code. That would make things much cleaner.
56,628
<p>I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?</p>
[ { "answer_id": 56647, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 5, "selected": false, "text": "<p>Here is a simple and <strong>very inelegant</strong> &amp; <strong>potentially dangerous</strong> way. </p>\n\n<ol>\n<li>Backup DB</li>\n<li>Detach DB</li>\n<li>Rename Log file</li>\n<li>Attach DB</li>\n<li>New log file will be recreated</li>\n<li>Delete Renamed Log file.</li>\n</ol>\n\n<p>I'm guessing that you are not doing log backups. (Which truncate the log). My advice is to change recovery model from <a href=\"http://msdn.microsoft.com/en-us/library/ms190217.aspx\" rel=\"noreferrer\">full</a> to <a href=\"http://msdn.microsoft.com/en-us/library/ms191164.aspx\" rel=\"noreferrer\">simple</a>. This will prevent log bloat.</p>\n" }, { "answer_id": 61544, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 2, "selected": false, "text": "<p><strong>To Truncate the log file:</strong></p>\n\n<ul>\n<li>Backup the database</li>\n<li>Detach the database, either by using Enterprise Manager or by executing : <em>Sp_DetachDB [DBName]</em></li>\n<li>Delete the transaction log file. (or rename the file, just in case)</li>\n<li>Re-attach the database again using: <em>Sp_AttachDB [DBName]</em></li>\n<li>When the database is attached, a new transaction log file is created.</li>\n</ul>\n\n<p><strong>To Shrink the log file:</strong></p>\n\n<ul>\n<li>Backup log [DBName] with No_Log</li>\n<li><p>Shrink the database by either:</p>\n\n<p>Using Enterprise manager :-\nRight click on the database, All tasks, Shrink database, Files, Select log file, OK.</p>\n\n<p>Using T-SQL :-\n<em>Dbcc Shrinkfile ([Log_Logical_Name])</em></p></li>\n</ul>\n\n<p>You can find the logical name of the log file by running sp_helpdb or by looking in the properties of the database in Enterprise Manager.</p>\n" }, { "answer_id": 63423, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 5, "selected": false, "text": "<p>If you do not use the transaction logs for restores (i.e. You only ever do full backups), you can set Recovery Mode to \"Simple\", and the transaction log will very shortly shrink and never fill up again. </p>\n\n<p>If you are using SQL 7 or 2000, you can enable \"truncate log on checkpoint\" in the database options tab. This has the same effect.</p>\n\n<p>This is not recomended in production environments obviously, since you will not be able to restore to a point in time.</p>\n" }, { "answer_id": 122201, "author": "shmia", "author_id": 20573, "author_profile": "https://Stackoverflow.com/users/20573", "pm_score": 2, "selected": false, "text": "<p>To my experience on most SQL Servers there is no backup of the transaction log.\nFull backups or differential backups are common practice, but transaction log backups are really seldom.\nSo the transaction log file grows forever (until the disk is full).\nIn this case the <strong>recovery model</strong> should be set to \"<strong>simple</strong>\".\nDon't forget to modify the system databases \"model\" and \"tempdb\", too.</p>\n\n<p>A backup of the database \"tempdb\" makes no sense, so the recovery model of this db should always be \"simple\".</p>\n" }, { "answer_id": 459055, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 8, "selected": false, "text": "<p><strong>DISCLAIMER:</strong> Please read comments below carefully, and I assume you've already read the accepted answer. As I said nearly 5 years ago:</p>\n\n<blockquote>\n <p>if anyone has any comments to add for situations when this is NOT an\n adequate or optimal solution then please comment below</p>\n</blockquote>\n\n<hr>\n\n<ul>\n<li><p>Right click on the database name.</p></li>\n<li><p>Select Tasks → Shrink → Database</p></li>\n<li><p>Then click <kbd>OK</kbd>!</p></li>\n</ul>\n\n<p>I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.</p>\n\n<p><em>I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17&nbsp;GB in 10 seconds</em></p>\n\n<p>In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]</p>\n\n<p>--</p>\n\n<p>PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!</p>\n" }, { "answer_id": 522481, "author": "mrdenny", "author_id": 4197, "author_profile": "https://Stackoverflow.com/users/4197", "pm_score": 3, "selected": false, "text": "<p>This technique that John recommends is not recommended as there is no guarantee that the database will attach without the log file. Change the database from full to simple, force a checkpoint and wait a few minutes. The SQL Server will clear the log, which you can then shrink using DBCC SHRINKFILE.</p>\n" }, { "answer_id": 985032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>First check the database recovery model. By default, SQL Server Express Edition creates a database for the simple recovery\nmodel (if I am not mistaken).</p>\n\n<p>Backup log DatabaseName With Truncate_Only:</p>\n\n<pre><code>DBCC ShrinkFile(yourLogical_LogFileName, 50)\n</code></pre>\n\n<p>SP_helpfile will give you the logical log file name.</p>\n\n<p>Refer to:</p>\n\n<p><em><a href=\"https://support.microsoft.com/en-us/help/873235/recover-from-a-full-transaction-log-in-a-sql-server-database\" rel=\"nofollow noreferrer\">Recover from a full transaction log in a SQL Server database</a></em></p>\n\n<p>If your database is in Full Recovery Model and if you are not taking TL backup, then change it to SIMPLE.</p>\n" }, { "answer_id": 2898241, "author": "ripvlan", "author_id": 349079, "author_profile": "https://Stackoverflow.com/users/349079", "pm_score": 3, "selected": false, "text": "<p>Use the <code>DBCC ShrinkFile ({logicalLogName}, TRUNCATEONLY)</code> command. If this is a test database and you are trying to save/reclaim space, this will help.</p>\n\n<p>Remember though that TX logs do have a sort of minimum/steady state size that they will grow up to. Depending upon your recovery model you may not be able to shrink the log - if in FULL and you aren't issuing TX log backups the log can't be shrunk - it will grow forever. If you don't need TX log backups, switch your recovery model to <em>Simple</em>.</p>\n\n<p>And remember, never ever under any circumstances delete the log (LDF) file! You will pretty much have instant database corruption. Cooked! Done! Lost data! If left \"unrepaired\" the main MDF file could become corrupt permanently.</p>\n\n<p>Never ever delete the transaction log - you will lose data! Part of your data is in the TX Log (regardless of recovery model)... if you detach and \"rename\" the TX log file that effectively <em>deletes</em> part of your database.</p>\n\n<p>For those that have deleted the TX Log you may want to run a few checkdb commands and fix the corruption before you lose more data.</p>\n\n<p>Check out Paul Randal's blog posts on this very topic, <em><a href=\"http://sqlskills.com/BLOGS/PAUL/category/Bad-Advice.aspx#p4\" rel=\"nofollow noreferrer\">bad advice</a></em>.</p>\n\n<p>Also in general do not use shrinkfile on the MDF files as it can severely fragment your data. Check out his Bad Advice section for more info (\"Why you should not shrink your data files\")</p>\n\n<p>Check out Paul's website - he covers these very questions. Last month he walked through many of these issues in his <em>Myth A Day</em> series.</p>\n" }, { "answer_id": 4322358, "author": "gautam saraswat", "author_id": 526238, "author_profile": "https://Stackoverflow.com/users/526238", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Backup DB</li>\n<li>Detach DB</li>\n<li>Rename Log file</li>\n<li>Attach DB (while attaching remove renamed .ldf (log file).Select it and remove by pressing Remove button)</li>\n<li>New log file will be recreated</li>\n<li>Delete Renamed Log file.</li>\n</ol>\n\n<p>This will work but it is suggested to take backup of your database first.</p>\n" }, { "answer_id": 4584599, "author": "Muhammad Imran", "author_id": 561245, "author_profile": "https://Stackoverflow.com/users/561245", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>USE DatabaseName\n\nGO\n\nDBCC SHRINKFILE( TransactionLogName, 1)\n\nBACKUP LOG DatabaseName WITH TRUNCATE_ONLY\n\nDBCC SHRINKFILE( TransactionLogName, 1)\n\nGO \n</code></pre>\n" }, { "answer_id": 4656532, "author": "Peter Nazarov", "author_id": 479858, "author_profile": "https://Stackoverflow.com/users/479858", "pm_score": -1, "selected": false, "text": "<p>DB Transaction Log <strong>Shrink to min size</strong>:</p>\n\n<ol>\n<li>Backup: Transaction log</li>\n<li>Shrink files: Transaction log</li>\n<li>Backup: Transaction log</li>\n<li>Shrink files: Transaction log</li>\n</ol>\n\n<p>I made tests on several number of DBs: <strong>this sequence works</strong>. </p>\n\n<p>It usually <strong>shrinks to 2MB</strong>.</p>\n\n<p>OR by a script:</p>\n\n<pre><code>DECLARE @DB_Name nvarchar(255);\nDECLARE @DB_LogFileName nvarchar(255);\nSET @DB_Name = '&lt;Database Name&gt;'; --Input Variable\nSET @DB_LogFileName = '&lt;LogFileEntryName&gt;'; --Input Variable\nEXEC \n(\n'USE ['+@DB_Name+']; '+\n'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +\n'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2) ' +\n'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +\n'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2)'\n)\nGO\n</code></pre>\n" }, { "answer_id": 6387629, "author": "Ibrahim", "author_id": 803446, "author_profile": "https://Stackoverflow.com/users/803446", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Take a backup of the MDB file.</li>\n<li>Stop SQL services</li>\n<li>Rename the log file</li>\n<li>Start the service</li>\n</ol>\n\n<p>(The system will create a new log file.)</p>\n\n<p>Delete or move the renamed log file.</p>\n" }, { "answer_id": 7952692, "author": "Rui Lima", "author_id": 565977, "author_profile": "https://Stackoverflow.com/users/565977", "pm_score": 8, "selected": false, "text": "<pre><code>-- DON'T FORGET TO BACKUP THE DB :D (Check [here][1]) \n\n\nUSE AdventureWorks2008R2;\nGO\n-- Truncate the log by changing the database recovery model to SIMPLE.\nALTER DATABASE AdventureWorks2008R2\nSET RECOVERY SIMPLE;\nGO\n-- Shrink the truncated log file to 1 MB.\nDBCC SHRINKFILE (AdventureWorks2008R2_Log, 1);\nGO\n-- Reset the database recovery model.\nALTER DATABASE AdventureWorks2008R2\nSET RECOVERY FULL;\nGO\n</code></pre>\n\n<p>From: <em><a href=\"http://msdn.microsoft.com/en-us/library/ms189493.aspx\" rel=\"noreferrer\">DBCC SHRINKFILE (Transact-SQL)</a></em></p>\n\n<p>You may want to backup first.</p>\n" }, { "answer_id": 14628788, "author": "Rachel", "author_id": 302677, "author_profile": "https://Stackoverflow.com/users/302677", "pm_score": 3, "selected": false, "text": "<p>Most answers here so far are assuming you do not actually need the Transaction Log file, however if your database is using the <code>FULL</code> recovery model, and you want to keep your backups in case you need to restore the database, then <em>do not</em> truncate or delete the log file the way many of these answers suggest.</p>\n\n<p>Eliminating the log file (through truncating it, discarding it, erasing it, etc) will break your backup chain, and will prevent you from restoring to any point in time since your last full, differential, or transaction log backup, until the next full or differential backup is made.</p>\n\n<p>From the <a href=\"http://msdn.microsoft.com/en-us/library/ms186865%28v=sql.90%29.aspx\" rel=\"noreferrer\">Microsoft article on<code>BACKUP</code></a></p>\n\n<blockquote>\n <p>We recommend that you never use NO_LOG or TRUNCATE_ONLY to manually\n truncate the transaction log, because this breaks the log chain. Until\n the next full or differential database backup, the database is not\n protected from media failure. Use manual log truncation in only very\n special circumstances, and create backups of the data immediately.</p>\n</blockquote>\n\n<p>To avoid that, backup your log file <strong>to disk</strong> before shrinking it. The syntax would look something like this:</p>\n\n<pre><code>BACKUP LOG MyDatabaseName \nTO DISK='C:\\DatabaseBackups\\MyDatabaseName_backup_2013_01_31_095212_8797154.trn'\n\nDBCC SHRINKFILE (N'MyDatabaseName_Log', 200)\n</code></pre>\n" }, { "answer_id": 15476656, "author": "Michael Dalton", "author_id": 2182233, "author_profile": "https://Stackoverflow.com/users/2182233", "pm_score": 6, "selected": false, "text": "<p>Below is a script to shrink the transaction log, but I’d definitely recommend backing up the transaction log before shrinking it.</p>\n\n<p>If you just shrink the file you are going to lose a ton of data that may come as a life saver in case of disaster. The transaction log contains a lot of useful data that can be read using a third-party transaction log reader (it can be read manually but with extreme effort though).</p>\n\n<p>The transaction log is also a must when it comes to point in time recovery, so don’t just throw it away, but make sure you back it up beforehand.</p>\n\n<p>Here are several posts where people used data stored in the transaction log to accomplish recovery:</p>\n\n<ul>\n<li><p><em><a href=\"https://stackoverflow.com/questions/4507509\">How to view transaction logs in SQL Server 2008</a></em></p></li>\n<li><p><em><a href=\"https://stackoverflow.com/questions/9767054\">Read the log file (*.LDF) in SQL Server 2008</a></em></p></li>\n</ul>\n\n<p>&nbsp;</p>\n\n<pre><code>USE DATABASE_NAME;\nGO\n\nALTER DATABASE DATABASE_NAME\nSET RECOVERY SIMPLE;\nGO\n--First parameter is log file name and second is size in MB\nDBCC SHRINKFILE (DATABASE_NAME_Log, 1);\n\nALTER DATABASE DATABASE_NAME\nSET RECOVERY FULL;\nGO\n</code></pre>\n\n<p>You may get an error that looks like this when the executing commands above</p>\n\n<blockquote>\n <p>“Cannot shrink log file (log file name) because the logical\n log file located at the end of the file is in use“</p>\n</blockquote>\n\n<p>This means that TLOG is in use. In this case try executing this several times in a row or find a way to reduce database activities.</p>\n" }, { "answer_id": 18292136, "author": "Aaron Bertrand", "author_id": 61305, "author_profile": "https://Stackoverflow.com/users/61305", "pm_score": 11, "selected": true, "text": "<p>Making a log file smaller should really be reserved for scenarios where it encountered unexpected growth which you do not expect to happen again. If the log file will grow to the same size again, not very much is accomplished by shrinking it temporarily. Now, depending on the recovery goals of your database, these are the actions you should take.</p>\n\n<h1>First, take a full backup</h1>\n\n<p>Never make any changes to your database without ensuring you can restore it should something go wrong.</p>\n\n<h1>If you care about point-in-time recovery</h1>\n\n<p>(And by point-in-time recovery, I mean you care about being able to restore to anything other than a full or differential backup.)</p>\n\n<p>Presumably your database is in <code>FULL</code> recovery mode. If not, then make sure it is:</p>\n\n<pre><code>ALTER DATABASE testdb SET RECOVERY FULL;\n</code></pre>\n\n<p>Even if you are taking regular full backups, the log file will grow and grow until you perform a <em>log</em> backup - this is for your protection, not to needlessly eat away at your disk space. You should be performing these log backups quite frequently, according to your recovery objectives. For example, if you have a business rule that states you can afford to lose no more than 15 minutes of data in the event of a disaster, you should have a job that backs up the log every 15 minutes. Here is a script that will generate timestamped file names based on the current time (but you can also do this with maintenance plans etc., just don't choose any of the shrink options in maintenance plans, they're awful).</p>\n\n<pre><code>DECLARE @path NVARCHAR(255) = N'\\\\backup_share\\log\\testdb_' \n + CONVERT(CHAR(8), GETDATE(), 112) + '_'\n + REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','')\n + '.trn';\n\nBACKUP LOG foo TO DISK = @path WITH INIT, COMPRESSION;\n</code></pre>\n\n<p>Note that <code>\\\\backup_share\\</code> should be on a different machine that represents a different underlying storage device. Backing these up to the same machine (or to a different machine that uses the same underlying disks, or a different VM that's on the same physical host) does not really help you, since if the machine blows up, you've lost your database <em>and</em> its backups. Depending on your network infrastructure it may make more sense to backup locally and then transfer them to a different location behind the scenes; in either case, you want to get them off the primary database machine as quickly as possible.</p>\n\n<p>Now, once you have regular log backups running, it should be reasonable to shrink the log file to something more reasonable than whatever it's blown up to now. This does <em>not</em> mean running <code>SHRINKFILE</code> over and over again until the log file is 1 MB - even if you are backing up the log frequently, it still needs to accommodate the sum of any concurrent transactions that can occur. Log file autogrow events are expensive, since SQL Server has to zero out the files (unlike data files when instant file initialization is enabled), and user transactions have to wait while this happens. You want to do this grow-shrink-grow-shrink routine as little as possible, and you certainly don't want to make your users pay for it.</p>\n\n<p>Note that you may need to back up the log twice before a shrink is possible (thanks Robert).</p>\n\n<p>So, you need to come up with a practical size for your log file. Nobody here can tell you what that is without knowing a lot more about your system, but if you've been frequently shrinking the log file and it has been growing again, a good watermark is probably 10-50% higher than the largest it's been. Let's say that comes to 200 MB, and you want any subsequent autogrowth events to be 50 MB, then you can adjust the log file size this way:</p>\n\n<pre><code>USE [master];\nGO\nALTER DATABASE Test1 \n MODIFY FILE\n (NAME = yourdb_log, SIZE = 200MB, FILEGROWTH = 50MB);\nGO\n</code></pre>\n\n<p>Note that if the log file is currently > 200 MB, you may need to run this first:</p>\n\n<pre><code>USE yourdb;\nGO\nDBCC SHRINKFILE(yourdb_log, 200);\nGO\n</code></pre>\n\n<h1>If you don't care about point-in-time recovery</h1>\n\n<p>If this is a test database, and you don't care about point-in-time recovery, then you should make sure that your database is in <code>SIMPLE</code> recovery mode.</p>\n\n<pre><code>ALTER DATABASE testdb SET RECOVERY SIMPLE;\n</code></pre>\n\n<p>Putting the database in <code>SIMPLE</code> recovery mode will make sure that SQL Server re-uses portions of the log file (essentially phasing out inactive transactions) instead of growing to keep a record of <em>all</em> transactions (like <code>FULL</code> recovery does until you back up the log). <code>CHECKPOINT</code> events will help control the log and make sure that it doesn't need to grow unless you generate a lot of t-log activity between <code>CHECKPOINT</code>s.</p>\n\n<p>Next, you should make absolute sure that this log growth was truly due to an abnormal event (say, an annual spring cleaning or rebuilding your biggest indexes), and not due to normal, everyday usage. If you shrink the log file to a ridiculously small size, and SQL Server just has to grow it again to accommodate your normal activity, what did you gain? Were you able to make use of that disk space you freed up only temporarily? If you need an immediate fix, then you can run the following:</p>\n\n<pre><code>USE yourdb;\nGO\nCHECKPOINT;\nGO\nCHECKPOINT; -- run twice to ensure file wrap-around\nGO\nDBCC SHRINKFILE(yourdb_log, 200); -- unit is set in MBs\nGO\n</code></pre>\n\n<p>Otherwise, set an appropriate size and growth rate. As per the example in the point-in-time recovery case, you can use the same code and logic to determine what file size is appropriate and set reasonable autogrowth parameters. </p>\n\n<h1>Some things you don't want to do</h1>\n\n<ul>\n<li><p><strong>Back up the log with <code>TRUNCATE_ONLY</code> option and then <code>SHRINKFILE</code></strong>. For one, this <code>TRUNCATE_ONLY</code> option has been deprecated and is no longer available in current versions of SQL Server. Second, if you are in <code>FULL</code> recovery model, this will destroy your log chain and require a new, full backup.</p></li>\n<li><p><strong>Detach the database, delete the log file, and re-attach</strong>. I can't emphasize how dangerous this can be. Your database may not come back up, it may come up as suspect, you may have to revert to a backup (if you have one), etc. etc.</p></li>\n<li><p><strong>Use the \"shrink database\" option</strong>. <code>DBCC SHRINKDATABASE</code> and the maintenance plan option to do the same are bad ideas, especially if you really only need to resolve a log problem issue. Target the file you want to adjust and adjust it independently, using <code>DBCC SHRINKFILE</code> or <code>ALTER DATABASE ... MODIFY FILE</code> (examples above).</p></li>\n<li><p><strong>Shrink the log file to 1 MB</strong>. This looks tempting because, hey, SQL Server will let me do it in certain scenarios, and look at all the space it frees! Unless your database is read only (and it is, you should mark it as such using <code>ALTER DATABASE</code>), this will absolutely just lead to many unnecessary growth events, as the log has to accommodate current transactions regardless of the recovery model. What is the point of freeing up that space temporarily, just so SQL Server can take it back slowly and painfully?</p></li>\n<li><p><strong>Create a second log file</strong>. This will provide temporarily relief for the drive that has filled your disk, but this is like trying to fix a punctured lung with a band-aid. You should deal with the problematic log file directly instead of just adding another potential problem. Other than redirecting some transaction log activity to a different drive, a second log file really does nothing for you (unlike a second data file), since only one of the files can ever be used at a time. <a href=\"http://www.sqlskills.com/blogs/paul/multiple-log-files-and-why-theyre-bad/\" rel=\"noreferrer\">Paul Randal also explains why multiple log files can bite you later</a>.</p></li>\n</ul>\n\n<h1>Be proactive</h1>\n\n<p>Instead of shrinking your log file to some small amount and letting it constantly autogrow at a small rate on its own, set it to some reasonably large size (one that will accommodate the sum of your largest set of concurrent transactions) and set a reasonable autogrow setting as a fallback, so that it doesn't have to grow multiple times to satisfy single transactions and so that it will be relatively rare for it to ever have to grow during normal business operations.</p>\n\n<p>The worst possible settings here are 1 MB growth or 10% growth. Funny enough, these are the defaults for SQL Server (which I've complained about and <a href=\"https://web.archive.org/web/20140108204835/http://connect.microsoft.com:80/SQLServer/feedback/details/415343\" rel=\"noreferrer\">asked for changes to no avail</a>) - 1 MB for data files, and 10% for log files. The former is much too small in this day and age, and the latter leads to longer and longer events every time (say, your log file is 500 MB, first growth is 50 MB, next growth is 55 MB, next growth is 60.5 MB, etc. etc. - and on slow I/O, believe me, you will really notice this curve).</p>\n\n<h1>Further reading</h1>\n\n<p>Please don't stop here; while much of the advice you see out there about shrinking log files is inherently bad and even potentially disastrous, there are some people who care more about data integrity than freeing up disk space.</p>\n\n<p><a href=\"https://sqlblog.org/2009/07/27/oh-the-horror-please-stop-telling-people-they-should-shrink-their-log-files\" rel=\"noreferrer\">A blog post I wrote in 2009, when I saw a few \"here's how to shrink the log file\" posts spring up</a>.</p>\n\n<p><a href=\"http://www.brentozar.com/archive/2009/08/stop-shrinking-your-database-files-seriously-now/\" rel=\"noreferrer\">A blog post Brent Ozar wrote four years ago, pointing to multiple resources, in response to a SQL Server Magazine article that should <em>not</em> have been published</a>.</p>\n\n<p><a href=\"http://www.sqlskills.com/blogs/paul/importance-of-proper-transaction-log-size-management/\" rel=\"noreferrer\">A blog post by Paul Randal explaining why t-log maintenance is important</a> and <a href=\"http://www.sqlskills.com/blogs/paul/why-you-should-not-shrink-your-data-files/\" rel=\"noreferrer\">why you shouldn't shrink your data files, either</a>.</p>\n\n<p><a href=\"https://dba.stackexchange.com/questions/29829/why-does-the-transaction-log-keep-growing-or-run-out-of-space\">Mike Walsh has a great answer covering some of these aspects too, including reasons why you might not be able to shrink your log file immediately</a>.</p>\n" }, { "answer_id": 27406247, "author": "Shashi3456643", "author_id": 3456643, "author_profile": "https://Stackoverflow.com/users/3456643", "pm_score": 2, "selected": false, "text": "<p>Database → right click <em>Properties</em> → file → add another log file with a different name and set the path the same as the old log file with a different file name.</p>\n\n<p>The database automatically picks up the newly created log file.</p>\n" }, { "answer_id": 30755260, "author": "McRobert", "author_id": 4870511, "author_profile": "https://Stackoverflow.com/users/4870511", "pm_score": 3, "selected": false, "text": "<p>The SQL Server transaction log needs to be properly maintained in order to prevent its unwanted growth. This means running transaction log backups often enough. By not doing that, you risk the transaction log to become full and start to grow.</p>\n<p>Besides the answers for this question I recommend reading and understanding the transaction log common myths. These readings may help understanding the transaction log and deciding what techniques to use to &quot;clear&quot; it:</p>\n<p>From <em><a href=\"http://www.sqlshack.com/10-important-sql-server-transaction-log-myths/\" rel=\"noreferrer\">10 most important SQL Server transaction log myths</a></em>:</p>\n<blockquote>\n<p>Myth: My SQL Server is too busy. I don’t want to make SQL Server transaction log backups</p>\n<p>One of the biggest performance intensive operations in SQL Server is an auto-grow event of the online transaction log file. By not making transaction log backups often enough, the online transaction log will become full and will have to grow. The default growth size is 10%. The busier the database is, the quicker the online transaction log will grow if transaction log backups are not created\nCreating a SQL Server transaction log backup doesn’t block the online transaction log, but an auto-growth event does. It can block all activity in the online transaction log</p>\n</blockquote>\n<p>From <em><a href=\"http://blog.sqlxdetails.com/transaction-log-myths/\" rel=\"noreferrer\">Transaction log myths</a></em>:</p>\n<blockquote>\n<blockquote>\n<p>Myth: Regular log shrinking is a good maintenance practice</p>\n</blockquote>\n<p>FALSE. Log growth is very expensive because the new chunk must be zeroed-out. All write activity stops on that database until zeroing is finished, and if your disk write is slow or autogrowth size is big, that pause can be huge and users will notice. That’s one reason why you want to avoid growth. If you shrink the log, it will grow again and you are just wasting disk operation on needless shrink-and-grow-again game</p>\n</blockquote>\n" }, { "answer_id": 48585660, "author": "Mahendra", "author_id": 1662592, "author_profile": "https://Stackoverflow.com/users/1662592", "pm_score": 2, "selected": false, "text": "<p>It happened with me where the database log file was of 28 GBs. </p>\n\n<p>What can you do to reduce this? \nActually, log files are those file data which the SQL server keeps when an transaction has taken place. For a transaction to process SQL server allocates pages for the same. But after the completion of the transaction, these are not released suddenly hoping that there may be a transaction coming like the same one. This holds up the space. </p>\n\n<p>Step 1: \nFirst Run this command in the database query explored \ncheckpoint</p>\n\n<p>Step 2: \nRight click on the database \nTask> Back up\nSelect back up type as Transaction Log\nAdd a destination address and file name to keep the backup data (.bak)</p>\n\n<p>Repeat this step again and at this time give another file name </p>\n\n<p><a href=\"https://i.stack.imgur.com/ELNLW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ELNLW.png\" alt=\"enter image description here\"></a></p>\n\n<p>Step 3:\nNow go to the database \nRight-click on the database </p>\n\n<p>Tasks> Shrinks> Files \nChoose File type as Log\nShrink action as release unused space</p>\n\n<p><a href=\"https://i.stack.imgur.com/qwPKt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qwPKt.png\" alt=\"enter image description here\"></a></p>\n\n<p>Step 4:</p>\n\n<p>Check your log file \nnormally in SQL 2014 this can be found at </p>\n\n<p>C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQL2014EXPRESS\\MSSQL\\DATA</p>\n\n<p>In my case, its reduced from 28 GB to 1 MB</p>\n" }, { "answer_id": 52846837, "author": "hey", "author_id": 2349661, "author_profile": "https://Stackoverflow.com/users/2349661", "pm_score": 0, "selected": false, "text": "<p>Some of the other answers did not work for me: It was not possible to create the checkpoint while the db was online, because the transaction log was full (how ironic). However, after setting the database to emergency mode, I was able to shrink the log file:</p>\n\n<pre><code>alter database &lt;database_name&gt; set emergency;\nuse &lt;database_name&gt;;\ncheckpoint;\ncheckpoint;\nalter database &lt;database_name&gt; set online;\ndbcc shrinkfile(&lt;database_name&gt;_log, 200);\n</code></pre>\n" }, { "answer_id": 59571949, "author": "George M Reinstate Monica", "author_id": 7577464, "author_profile": "https://Stackoverflow.com/users/7577464", "pm_score": 1, "selected": false, "text": "<p>Slightly updated answer, for MSSQL 2017, and using the SQL server management studio.\nI went mostly from these instructions <a href=\"https://www.sqlshack.com/sql-server-transaction-log-backup-truncate-and-shrink-operations/\" rel=\"nofollow noreferrer\">https://www.sqlshack.com/sql-server-transaction-log-backup-truncate-and-shrink-operations/</a></p>\n\n<p>I had a recent db backup, so I backed up the transaction log. Then I backed it up again for good measure.\nFinally I shrank the log file, and went from 20G to 7MB, much more in line with the size of my data.\nI don't think the transaction logs had ever been backed up since this was installed 2 years ago.. so putting that task on the housekeeping calendar.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?
Making a log file smaller should really be reserved for scenarios where it encountered unexpected growth which you do not expect to happen again. If the log file will grow to the same size again, not very much is accomplished by shrinking it temporarily. Now, depending on the recovery goals of your database, these are the actions you should take. First, take a full backup ========================= Never make any changes to your database without ensuring you can restore it should something go wrong. If you care about point-in-time recovery ======================================== (And by point-in-time recovery, I mean you care about being able to restore to anything other than a full or differential backup.) Presumably your database is in `FULL` recovery mode. If not, then make sure it is: ``` ALTER DATABASE testdb SET RECOVERY FULL; ``` Even if you are taking regular full backups, the log file will grow and grow until you perform a *log* backup - this is for your protection, not to needlessly eat away at your disk space. You should be performing these log backups quite frequently, according to your recovery objectives. For example, if you have a business rule that states you can afford to lose no more than 15 minutes of data in the event of a disaster, you should have a job that backs up the log every 15 minutes. Here is a script that will generate timestamped file names based on the current time (but you can also do this with maintenance plans etc., just don't choose any of the shrink options in maintenance plans, they're awful). ``` DECLARE @path NVARCHAR(255) = N'\\backup_share\log\testdb_' + CONVERT(CHAR(8), GETDATE(), 112) + '_' + REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','') + '.trn'; BACKUP LOG foo TO DISK = @path WITH INIT, COMPRESSION; ``` Note that `\\backup_share\` should be on a different machine that represents a different underlying storage device. Backing these up to the same machine (or to a different machine that uses the same underlying disks, or a different VM that's on the same physical host) does not really help you, since if the machine blows up, you've lost your database *and* its backups. Depending on your network infrastructure it may make more sense to backup locally and then transfer them to a different location behind the scenes; in either case, you want to get them off the primary database machine as quickly as possible. Now, once you have regular log backups running, it should be reasonable to shrink the log file to something more reasonable than whatever it's blown up to now. This does *not* mean running `SHRINKFILE` over and over again until the log file is 1 MB - even if you are backing up the log frequently, it still needs to accommodate the sum of any concurrent transactions that can occur. Log file autogrow events are expensive, since SQL Server has to zero out the files (unlike data files when instant file initialization is enabled), and user transactions have to wait while this happens. You want to do this grow-shrink-grow-shrink routine as little as possible, and you certainly don't want to make your users pay for it. Note that you may need to back up the log twice before a shrink is possible (thanks Robert). So, you need to come up with a practical size for your log file. Nobody here can tell you what that is without knowing a lot more about your system, but if you've been frequently shrinking the log file and it has been growing again, a good watermark is probably 10-50% higher than the largest it's been. Let's say that comes to 200 MB, and you want any subsequent autogrowth events to be 50 MB, then you can adjust the log file size this way: ``` USE [master]; GO ALTER DATABASE Test1 MODIFY FILE (NAME = yourdb_log, SIZE = 200MB, FILEGROWTH = 50MB); GO ``` Note that if the log file is currently > 200 MB, you may need to run this first: ``` USE yourdb; GO DBCC SHRINKFILE(yourdb_log, 200); GO ``` If you don't care about point-in-time recovery ============================================== If this is a test database, and you don't care about point-in-time recovery, then you should make sure that your database is in `SIMPLE` recovery mode. ``` ALTER DATABASE testdb SET RECOVERY SIMPLE; ``` Putting the database in `SIMPLE` recovery mode will make sure that SQL Server re-uses portions of the log file (essentially phasing out inactive transactions) instead of growing to keep a record of *all* transactions (like `FULL` recovery does until you back up the log). `CHECKPOINT` events will help control the log and make sure that it doesn't need to grow unless you generate a lot of t-log activity between `CHECKPOINT`s. Next, you should make absolute sure that this log growth was truly due to an abnormal event (say, an annual spring cleaning or rebuilding your biggest indexes), and not due to normal, everyday usage. If you shrink the log file to a ridiculously small size, and SQL Server just has to grow it again to accommodate your normal activity, what did you gain? Were you able to make use of that disk space you freed up only temporarily? If you need an immediate fix, then you can run the following: ``` USE yourdb; GO CHECKPOINT; GO CHECKPOINT; -- run twice to ensure file wrap-around GO DBCC SHRINKFILE(yourdb_log, 200); -- unit is set in MBs GO ``` Otherwise, set an appropriate size and growth rate. As per the example in the point-in-time recovery case, you can use the same code and logic to determine what file size is appropriate and set reasonable autogrowth parameters. Some things you don't want to do ================================ * **Back up the log with `TRUNCATE_ONLY` option and then `SHRINKFILE`**. For one, this `TRUNCATE_ONLY` option has been deprecated and is no longer available in current versions of SQL Server. Second, if you are in `FULL` recovery model, this will destroy your log chain and require a new, full backup. * **Detach the database, delete the log file, and re-attach**. I can't emphasize how dangerous this can be. Your database may not come back up, it may come up as suspect, you may have to revert to a backup (if you have one), etc. etc. * **Use the "shrink database" option**. `DBCC SHRINKDATABASE` and the maintenance plan option to do the same are bad ideas, especially if you really only need to resolve a log problem issue. Target the file you want to adjust and adjust it independently, using `DBCC SHRINKFILE` or `ALTER DATABASE ... MODIFY FILE` (examples above). * **Shrink the log file to 1 MB**. This looks tempting because, hey, SQL Server will let me do it in certain scenarios, and look at all the space it frees! Unless your database is read only (and it is, you should mark it as such using `ALTER DATABASE`), this will absolutely just lead to many unnecessary growth events, as the log has to accommodate current transactions regardless of the recovery model. What is the point of freeing up that space temporarily, just so SQL Server can take it back slowly and painfully? * **Create a second log file**. This will provide temporarily relief for the drive that has filled your disk, but this is like trying to fix a punctured lung with a band-aid. You should deal with the problematic log file directly instead of just adding another potential problem. Other than redirecting some transaction log activity to a different drive, a second log file really does nothing for you (unlike a second data file), since only one of the files can ever be used at a time. [Paul Randal also explains why multiple log files can bite you later](http://www.sqlskills.com/blogs/paul/multiple-log-files-and-why-theyre-bad/). Be proactive ============ Instead of shrinking your log file to some small amount and letting it constantly autogrow at a small rate on its own, set it to some reasonably large size (one that will accommodate the sum of your largest set of concurrent transactions) and set a reasonable autogrow setting as a fallback, so that it doesn't have to grow multiple times to satisfy single transactions and so that it will be relatively rare for it to ever have to grow during normal business operations. The worst possible settings here are 1 MB growth or 10% growth. Funny enough, these are the defaults for SQL Server (which I've complained about and [asked for changes to no avail](https://web.archive.org/web/20140108204835/http://connect.microsoft.com:80/SQLServer/feedback/details/415343)) - 1 MB for data files, and 10% for log files. The former is much too small in this day and age, and the latter leads to longer and longer events every time (say, your log file is 500 MB, first growth is 50 MB, next growth is 55 MB, next growth is 60.5 MB, etc. etc. - and on slow I/O, believe me, you will really notice this curve). Further reading =============== Please don't stop here; while much of the advice you see out there about shrinking log files is inherently bad and even potentially disastrous, there are some people who care more about data integrity than freeing up disk space. [A blog post I wrote in 2009, when I saw a few "here's how to shrink the log file" posts spring up](https://sqlblog.org/2009/07/27/oh-the-horror-please-stop-telling-people-they-should-shrink-their-log-files). [A blog post Brent Ozar wrote four years ago, pointing to multiple resources, in response to a SQL Server Magazine article that should *not* have been published](http://www.brentozar.com/archive/2009/08/stop-shrinking-your-database-files-seriously-now/). [A blog post by Paul Randal explaining why t-log maintenance is important](http://www.sqlskills.com/blogs/paul/importance-of-proper-transaction-log-size-management/) and [why you shouldn't shrink your data files, either](http://www.sqlskills.com/blogs/paul/why-you-should-not-shrink-your-data-files/). [Mike Walsh has a great answer covering some of these aspects too, including reasons why you might not be able to shrink your log file immediately](https://dba.stackexchange.com/questions/29829/why-does-the-transaction-log-keep-growing-or-run-out-of-space).
56,630
<p>Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click <a href="http://news.slashdot.org/news/08/09/10/2257242.shtml" rel="nofollow noreferrer">here</a>.)</p> <p>My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?</p>
[ { "answer_id": 56759, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": true, "text": "<p>Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.</p>\n\n<pre><code>var MenuManager = Class.create({\n initialize: function initialize(menuElt) {\n this.menu = $(menuElt);\n this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };\n registerEvent(document, 'scroll', this.handleScroll.bind(this));\n this.handleScroll();\n },\n handleScroll: function handleScroll() {\n this.scrollOffset = document.viewport.getScrollOffsets().top;\n if (this.scrollOffset &gt; this.homePosn.y) {\n this.menu.style.position = 'fixed';\n this.menu.style.top = 0;\n this.menu.style.left = this.homePosn.x;\n } else {\n this.menu.style.position = 'absolute';\n this.menu.style.top = null;\n this.menu.style.left = null;\n }\n }\n});\n</code></pre>\n\n<p>Just call the constructor with the id of your menu, and the class will take it from there.</p>\n" }, { "answer_id": 475955, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Thanks for the effort of sharing this code.\nI made some small changes to make it work with the current release of Prototype.</p>\n\n<pre><code>var TableHeaderManager = Class.create({\n initialize: function initialize(headerElt) {\n this.tableHeader = $(headerElt);\n this.homePosn = { x: this.tableHeader.cumulativeOffset()[0], y: this.tableHeader.cumulativeOffset()[1] };\n Event.observe(window, 'scroll', this.handleScroll.bind(this));\n this.handleScroll();\n },\n handleScroll: function handleScroll() {\n this.scrollOffset = document.viewport.getScrollOffsets().top;\n if (this.scrollOffset &gt; this.homePosn.y) {\n this.tableHeader.style.position = 'fixed';\n this.tableHeader.style.top = 0;\n this.tableHeader.style.left = this.homePosn.x;\n } else {\n this.tableHeader.style.position = 'absolute';\n this.tableHeader.style.top = null;\n this.tableHeader.style.left = null;\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 4946851, "author": "IEnumerator", "author_id": 34819, "author_profile": "https://Stackoverflow.com/users/34819", "pm_score": 0, "selected": false, "text": "<p>For a demo but not based on the code above checkout:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2352896/fixing-tabs-to-the-top-of-the-page-but-underneath-the-header\">fixed-floating-elements</a></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click [here](http://news.slashdot.org/news/08/09/10/2257242.shtml).) My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?
Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think. ``` var MenuManager = Class.create({ initialize: function initialize(menuElt) { this.menu = $(menuElt); this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) }; registerEvent(document, 'scroll', this.handleScroll.bind(this)); this.handleScroll(); }, handleScroll: function handleScroll() { this.scrollOffset = document.viewport.getScrollOffsets().top; if (this.scrollOffset > this.homePosn.y) { this.menu.style.position = 'fixed'; this.menu.style.top = 0; this.menu.style.left = this.homePosn.x; } else { this.menu.style.position = 'absolute'; this.menu.style.top = null; this.menu.style.left = null; } } }); ``` Just call the constructor with the id of your menu, and the class will take it from there.
56,638
<p>I want to convert a number that is in <a href="https://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Time" rel="nofollow noreferrer">PRTime</a> format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a <code>DateTime</code>.</p> <p>Note that this is slightly different than the usual &quot;number of milliseconds since 1/1/1970&quot;.</p>
[ { "answer_id": 56674, "author": "Barry", "author_id": 845, "author_profile": "https://Stackoverflow.com/users/845", "pm_score": 3, "selected": true, "text": "<pre><code>Dim prTimeInMillis As UInt64\nprTimeInMillis = prTime/1000\n\nDim prDateTime As New DateTime(1970, 1, 1)\nprDateTime = prDateTime.AddMilliseconds(prTimeInMillis)\n</code></pre>\n" }, { "answer_id": 56753, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>DateTime has a constructor that takes Ticks (which are 100 nanoseconds).</p>\n<p>So take your prTime, multiply it by 10 and add it to the number of ticks representing the Epoch time and you have your conversion.</p>\n<pre><code>private static DateTime epoch = new DateTime(1970, 1, 1);\n\nprivate static DateTime ConvertPrTime(long time)\n{\n return new DateTime(epoch.Ticks + (time*10), DateTimeKind.Utc);\n}\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1842864/" ]
I want to convert a number that is in [PRTime](https://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Time) format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a `DateTime`. Note that this is slightly different than the usual "number of milliseconds since 1/1/1970".
``` Dim prTimeInMillis As UInt64 prTimeInMillis = prTime/1000 Dim prDateTime As New DateTime(1970, 1, 1) prDateTime = prDateTime.AddMilliseconds(prTimeInMillis) ```
56,655
<p>This is the day of weird behavior.</p> <p>We have a Win32 project made with Delphi 2007, which hosts the .NET runtime and calls into .NET to show new forms, as part of a transition period.</p> <p>Recently we've begun experiencing exceptions at seemingly random locations and points of our code: Arithmetic overflow or underflow.</p> <p>The stack trace of one of these looks like this:</p> <pre><code>at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.RunDialog(Form form) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at System.Windows.Forms.Form.ShowDialog() at Gatsoft.Gat.UI.Windows.Forms.Remanaging.RemanageForm.DelphiOpenInNewMode(String employeeCode, String departmentCode, DateTime date) in C:\Dev\VS.NET\Gatsoft\Gatsoft.Gat.UI.Windows\Forms\Remanaging\RemanageForm.Delphi.cs:line 67 </code></pre> <p>In the Visual Studio solution, one of the outmost class libraries (ie. pulls in all the references it can), has set a specific debug program, targetted for the Delphi project output. This allows us to debug .NET code from Visual Studio, even though the main bulk of the program is written in Delphi.</p> <p>The problem only occurs when run from the debugger, not if we just run the exe file directly (either through explorer, shortcuts, or even <kbd>Ctrl</kbd>+<kbd>F5</kbd> inside Visual Studio).</p> <p>There's apparently no spyware on the machine (as hinted by <a href="http://bytes.com/forum/thread106203.html" rel="nofollow noreferrer">this</a>).</p> <p>Any other things we can check?</p> <hr /> <p><strong>Edit:</strong> It looks like the .NET debugger is enabling this SNaN flags, and the Delphi debugger does not. We'll have to investigate this further, but for now I'll accept <a href="https://stackoverflow.com/users/6550/lorenzo-boccaccia">@Lorenzo Boccaccia</a>'s answer.</p> <h2>Apparently Solved</h2> <p>Ok, it looks like we've finally nailed this problem. The problem started occuring without having the debugger attached as well, for our testers, so we had to prioritize the problem way up.</p> <p>Finally we found one common issue with the machines that had the problem, they are Dell Lattitude D620 laptops with an NVIDIA Quadro NVS 110M, with an old driver from a system image used to provision the laptops, from back in 2006.</p> <p>I found one post on the web, though I lost the url when I rebooted to update the display driver, that had a .NET service crashing, mostly when the machine was busy doing something on the screen. One way to reproduce his problem was to open a command prompt to C:\ and doing a <code>DIR /S</code> to just force a massive amount of screen updates, which would trigger the crash.</p> <p>He too had a NVIDIA video card.</p> <p>The problem on my machine occured roughly every 2-4 startups of our program, but after updating the video driver I've had 123 successfull startups without any problems. (BTW I can recommend <a href="http://www.autohotkey.com/" rel="nofollow noreferrer">AutoHotKey</a> for such things).</p> <p>So it looks like we've found the culprit, an old/buggy NVIDIA driver.</p> <p>Updated this question so that perhaps someone in the future can save some time.</p> <p>Now, if you'll excuse me, I'm going to go cry in a corner.</p> <h2>Jinxed!</h2> <p>I must've jinxed it. No sooner had I posted the above update than a colleague laptop failed, after updating the video driver.</p> <p>Still, I'm positive it's a problem outside of our application now, so it just remains to figure out which specific things to update.</p> <hr /> <p><strong>Further updates</strong>: Ok, my machine is now apparently fixed, not so with my colleagues machine. So far we've updated the BIOS, Chipset drivers, and currently SP3 for XP is on its way in.</p> <p>A burn-in test will be done tonight, where the app will be left overnight starting up, as the problem cropped up either during startup, or at the first time some WinForms .NET code was executed. This app is mainly a Delphi Win32 app, but it hosts the .NET runtime, and the problem seems to be related to .NET code. When we &quot;boot&quot; the .NET runtime, the problem can appear, or when we fire the first .NET window from Win32 then it can also appear.</p> <hr /> <p>Statistically I'm ready to release this code now. Over the night the application has been started 3051 times without errors, whereas before I updated the video driver it crashed every 2-4 times.</p> <h2>Prodded and found(!/?)</h2> <p>This bug-fixing ordeal feels like going to the doctor, where the following conversation ensues:</p> <pre><code>Doc: Does this hurt? Me: No... Doc: What about now? </code></pre> <p>I've prodded and poked the application and finally I think I've found something we did that introduced this problem.</p> <p>In our app we host the .NET runtime, from a Delphi 2007 Win32 application, and in our glue-code we have the following line (now):</p> <pre><code> rc := CorBindToRuntimeEx('v2.0.50727', 'wks', STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN or STARTUP_CONCURRENT_GC, @clsid, @iid, UnkRuntimeEngine); </code></pre> <p>The two constants in the middle there was originally just a 0, meaning <em>pick the defaults</em>. This change was introduced a few months ago and the problem has been slowly creeping in on us after this. The change was introduced in order to encourage ANTS profiler to load our Win32 application + hosted .NET runtime in order to do performance profiling and the changes we introduced back then made that work. Additionally, the problem with arithmetic overflow/underflow has slowly been getting worse so I bet the problem didn't appear for a while after the change so it wasn't attributed to any of the changes we did.</p> <p>Also, since we only (originally) saw the problem when running through the debugger, we thought something was wrong with Visual Studio and/or Delphi.</p> <p>Anyway, statistically now, with a browser on one screen doing repeated scrolling up and down triggered by a javascript (apparently needed in order to trigger the bug), then I have been able to successfully start the application 726 times with a 0 in the call, and it crashes 5 out of 17 times with the two constants there.</p> <pre><code>Doc: Does this hurt? </code></pre> <p>And let's not get into who made that change in the first place. I'm sure the culprit wants to be left anonymous... <em>cough</em></p>
[ { "answer_id": 56696, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 1, "selected": false, "text": "<p>Have you added all the WMI components? As far as I know, you need all the WMI components to access the counters!</p>\n\n<blockquote>\n <p>The Performance Counter Windows Management Instrumentation (WMI) Provider component provides a bridge between the performance registry interface and the WMI interface. This component allows WMI clients to access performance counters through WMI scripts, and allows management applications built using WMI to access performance counters. Without this component, applications must directly use the registry interface or the performance data helper interface to access performance counters. </p>\n</blockquote>\n\n<p>Thank you TimK for the link (<a href=\"http://msdn.microsoft.com/en-us/library/aa939695.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa939695.aspx</a>)</p>\n" }, { "answer_id": 58802, "author": "TimK", "author_id": 2348, "author_profile": "https://Stackoverflow.com/users/2348", "pm_score": 1, "selected": true, "text": "<p>It looks like this is what I was missing: <a href=\"http://msdn.microsoft.com/en-us/library/aa939695.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa939695.aspx</a></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
This is the day of weird behavior. We have a Win32 project made with Delphi 2007, which hosts the .NET runtime and calls into .NET to show new forms, as part of a transition period. Recently we've begun experiencing exceptions at seemingly random locations and points of our code: Arithmetic overflow or underflow. The stack trace of one of these looks like this: ``` at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.RunDialog(Form form) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at System.Windows.Forms.Form.ShowDialog() at Gatsoft.Gat.UI.Windows.Forms.Remanaging.RemanageForm.DelphiOpenInNewMode(String employeeCode, String departmentCode, DateTime date) in C:\Dev\VS.NET\Gatsoft\Gatsoft.Gat.UI.Windows\Forms\Remanaging\RemanageForm.Delphi.cs:line 67 ``` In the Visual Studio solution, one of the outmost class libraries (ie. pulls in all the references it can), has set a specific debug program, targetted for the Delphi project output. This allows us to debug .NET code from Visual Studio, even though the main bulk of the program is written in Delphi. The problem only occurs when run from the debugger, not if we just run the exe file directly (either through explorer, shortcuts, or even `Ctrl`+`F5` inside Visual Studio). There's apparently no spyware on the machine (as hinted by [this](http://bytes.com/forum/thread106203.html)). Any other things we can check? --- **Edit:** It looks like the .NET debugger is enabling this SNaN flags, and the Delphi debugger does not. We'll have to investigate this further, but for now I'll accept [@Lorenzo Boccaccia](https://stackoverflow.com/users/6550/lorenzo-boccaccia)'s answer. Apparently Solved ----------------- Ok, it looks like we've finally nailed this problem. The problem started occuring without having the debugger attached as well, for our testers, so we had to prioritize the problem way up. Finally we found one common issue with the machines that had the problem, they are Dell Lattitude D620 laptops with an NVIDIA Quadro NVS 110M, with an old driver from a system image used to provision the laptops, from back in 2006. I found one post on the web, though I lost the url when I rebooted to update the display driver, that had a .NET service crashing, mostly when the machine was busy doing something on the screen. One way to reproduce his problem was to open a command prompt to C:\ and doing a `DIR /S` to just force a massive amount of screen updates, which would trigger the crash. He too had a NVIDIA video card. The problem on my machine occured roughly every 2-4 startups of our program, but after updating the video driver I've had 123 successfull startups without any problems. (BTW I can recommend [AutoHotKey](http://www.autohotkey.com/) for such things). So it looks like we've found the culprit, an old/buggy NVIDIA driver. Updated this question so that perhaps someone in the future can save some time. Now, if you'll excuse me, I'm going to go cry in a corner. Jinxed! ------- I must've jinxed it. No sooner had I posted the above update than a colleague laptop failed, after updating the video driver. Still, I'm positive it's a problem outside of our application now, so it just remains to figure out which specific things to update. --- **Further updates**: Ok, my machine is now apparently fixed, not so with my colleagues machine. So far we've updated the BIOS, Chipset drivers, and currently SP3 for XP is on its way in. A burn-in test will be done tonight, where the app will be left overnight starting up, as the problem cropped up either during startup, or at the first time some WinForms .NET code was executed. This app is mainly a Delphi Win32 app, but it hosts the .NET runtime, and the problem seems to be related to .NET code. When we "boot" the .NET runtime, the problem can appear, or when we fire the first .NET window from Win32 then it can also appear. --- Statistically I'm ready to release this code now. Over the night the application has been started 3051 times without errors, whereas before I updated the video driver it crashed every 2-4 times. Prodded and found(!/?) ---------------------- This bug-fixing ordeal feels like going to the doctor, where the following conversation ensues: ``` Doc: Does this hurt? Me: No... Doc: What about now? ``` I've prodded and poked the application and finally I think I've found something we did that introduced this problem. In our app we host the .NET runtime, from a Delphi 2007 Win32 application, and in our glue-code we have the following line (now): ``` rc := CorBindToRuntimeEx('v2.0.50727', 'wks', STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN or STARTUP_CONCURRENT_GC, @clsid, @iid, UnkRuntimeEngine); ``` The two constants in the middle there was originally just a 0, meaning *pick the defaults*. This change was introduced a few months ago and the problem has been slowly creeping in on us after this. The change was introduced in order to encourage ANTS profiler to load our Win32 application + hosted .NET runtime in order to do performance profiling and the changes we introduced back then made that work. Additionally, the problem with arithmetic overflow/underflow has slowly been getting worse so I bet the problem didn't appear for a while after the change so it wasn't attributed to any of the changes we did. Also, since we only (originally) saw the problem when running through the debugger, we thought something was wrong with Visual Studio and/or Delphi. Anyway, statistically now, with a browser on one screen doing repeated scrolling up and down triggered by a javascript (apparently needed in order to trigger the bug), then I have been able to successfully start the application 726 times with a 0 in the call, and it crashes 5 out of 17 times with the two constants there. ``` Doc: Does this hurt? ``` And let's not get into who made that change in the first place. I'm sure the culprit wants to be left anonymous... *cough*
It looks like this is what I was missing: <http://msdn.microsoft.com/en-us/library/aa939695.aspx>
56,658
<h3>Summary</h3> <p>What's the best way to ensure a table cell cannot be less than a certain minimum width. </p> <h3>Example</h3> <p>I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.</p> <h3>Browser compatibility</h3> <p>I possible I would like to find a solution that works in</p> <ul> <li>IE 6-8</li> <li>FF 2-3</li> <li>Safari</li> </ul> <p>In order of preference.</p>
[ { "answer_id": 56663, "author": "James B", "author_id": 2951, "author_profile": "https://Stackoverflow.com/users/2951", "pm_score": 7, "selected": true, "text": "<p>This CSS should suffice:</p>\n\n<pre><code>td { min-width: 100px; }\n</code></pre>\n\n<p>However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal).</p>\n\n<p><strong>Edit:</strong> As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know. Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width.</p>\n\n<p>However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act <em>like</em> a minimum width and the cell will still expand with the text (due to the nowrap). This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to. (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway).</p>\n" }, { "answer_id": 56667, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 2, "selected": false, "text": "<p>what about this css property</p>\n\n<pre><code>min-width: 100px\n</code></pre>\n\n<p>but it doesn't really work in IE6 if not mistaken</p>\n\n<p>if you don't want to do it in the css way, I suppose you can add this attribute </p>\n\n<pre><code>nowrap=\"nowrap\"\n</code></pre>\n\n<p>in your table data tag</p>\n" }, { "answer_id": 56685, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "<p>Another <strong>hack</strong> is the old 1x1 transparent pixel trick. Insert an 1x1 transparent gif image and set its width in the image tag to the width you want. This will force the cell to be at least as wide as the image.</p>\n" }, { "answer_id": 56738, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>IE6 handles width as min-width:</p>\n\n<pre><code>td {\n min-width: 100px;\n _width: 100px;/* IE6 hack */\n}\n</code></pre>\n\n<p>If you want IE6 to handle width like normal browsers, give it an overflow:visible; (not the case here)</p>\n" }, { "answer_id": 1007998, "author": "Dean Peters", "author_id": 441512, "author_profile": "https://Stackoverflow.com/users/441512", "pm_score": 2, "selected": false, "text": "<p>I had some success with:</p>\n\n<pre><code> min-width: 193px;\n width:auto !important; \n _width: 193px; /* IE6 hack */\n</code></pre>\n\n<p>Based on a combination of Vatos' response and a min-height article here: <a href=\"http://www.dustindiaz.com/min-height-fast-hack/\" rel=\"nofollow noreferrer\">http://www.dustindiaz.com/min-height-fast-hack/</a></p>\n" }, { "answer_id": 5098023, "author": "Prof", "author_id": 629157, "author_profile": "https://Stackoverflow.com/users/629157", "pm_score": 2, "selected": false, "text": "<p>This is a cross-browser way for setting minimum width and/or mimimum height:</p>\n\n<pre><code>{\nwidth (or height): auto !important;\nwidth (or height): 200px;\nmin-width (or min-height): 200px;\n}\n</code></pre>\n\n<p>IE 6 doesn't understand !important<br>\nIE 6 sees width/height:200px (overwriting auto)</p>\n\n<p>Other browsers understand the min- and the !important</p>\n\n<p>I am not 100% familiar with the behaviour of widths in TD elements, but this all works nicely on eg DIV tags</p>\n\n<p>BTW:</p>\n\n<blockquote>\n <p>Based on a combination of Vatos' response and a min-height article here: <a href=\"http://www.dustindiaz.com/min-height-fast-hack/\" rel=\"nofollow\">http://www.dustindiaz.com/min-height-fast-hack/</a></p>\n</blockquote>\n\n<p>This is not working because of the order of the first 2 lines, they need to be in the right order (think about the above) ;)</p>\n" }, { "answer_id": 7225831, "author": "Partack", "author_id": 478222, "author_profile": "https://Stackoverflow.com/users/478222", "pm_score": 3, "selected": false, "text": "<p>I know this is an old question but i thought I'd share something that wasn't mentioned (Although pretty simple in concept..) you can just put a <code>&lt;div&gt;</code> inside the table (in one of the <code>&lt;td&gt;</code>'s or something) and set the <code>&lt;div&gt;</code> to <code>min-width</code>. the table will stop at the <code>&lt;div&gt;</code>'s width. Just thought I'd throw that out there in case somebody comes across this on google. Also, I'm not so sure about how min-width is handled in I.E6. but that has already been covered in another answer.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5182/" ]
### Summary What's the best way to ensure a table cell cannot be less than a certain minimum width. ### Example I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space. ### Browser compatibility I possible I would like to find a solution that works in * IE 6-8 * FF 2-3 * Safari In order of preference.
This CSS should suffice: ``` td { min-width: 100px; } ``` However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal). **Edit:** As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know. Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width. However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act *like* a minimum width and the cell will still expand with the text (due to the nowrap). This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to. (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway).
56,682
<p>In Windows, is there an easy way to tell if a folder has a subfile that has changed?</p> <p>I verified, and the last modified date on the folder does not get updated when a subfile changes.</p> <p>Is there a registry entry I can set that will modify this behavior?</p> <p>If it matters, I am using an NTFS volume. </p> <p>I would ultimately like to have this ability from a C++ program. </p> <p><strong>Scanning an entire directory recursively will not work for me because the folder is much too large.</strong></p> <p><strong>Update: I really need a way to do this without a process running while the change occurs. So installing a file system watcher is not optimal for me.</strong> </p> <p><strong>Update2: The archive bit will also not work because it has the same problem as the last modification date. The file's archive bit will be set, but the folders will not.</strong></p>
[ { "answer_id": 56695, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>If you can't run a process when the change occurs, then there's not much you can do except scan the filesystem, and check the modification date/time. This requires you to store each file's last date/time, though, and compare.</p>\n\n<p>You can speed this up by using the <a href=\"http://en.wikipedia.org/wiki/Archive_bit\" rel=\"nofollow noreferrer\">archive bit</a> (though it may mess up your backup software, so proceed carefully).</p>\n\n<blockquote>\n <p>An archive bit is a file attribute\n present in many computer file systems,\n notably FAT, FAT32, and NTFS. The\n purpose of an archive bit is to track\n incremental changes to files for the\n purpose of backup, also called\n archiving.</p>\n \n <p>As the archive bit is a binary bit, it\n is either 1 or 0, or in this case more\n frequently called set (1) and clear\n (0). The operating system sets the\n archive bit any time a file is\n created, moved, renamed, or otherwise\n modified in any way. The archive bit\n therefore represents one of two\n states: \"changed\" and \"not changed\"\n since the last backup.</p>\n \n <p>Archive bits are not affected by\n simply reading a file. When a file is\n copied, the original file's archive\n bit is unaffected, however the copy's\n archive bit will be set at the time\n the copy is made.</p>\n</blockquote>\n\n<p>So the process would be:</p>\n\n<ol>\n<li>Clear the archive bit on all the files</li>\n<li>Let the file system change over time</li>\n<li>Scan all the files - any with the archive bit set have changed</li>\n</ol>\n\n<p>This will eliminate the need for your program to keep state, and since you're only going over the directory entries (where the bit is stored) and they are clustered, it should be very, very fast.</p>\n\n<p>If you can run a process during the changes, however, then you'll want to look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80).aspx\" rel=\"nofollow noreferrer\">FileSystemWatcher</a> class. Here's an <a href=\"http://msdn.microsoft.com/en-us/library/chzww271(VS.80).aspx\" rel=\"nofollow noreferrer\">example</a> of how you might use it.</p>\n\n<p>It also exists in <a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6165137.html\" rel=\"nofollow noreferrer\">.NET</a> (for future searchers of this type of problem)</p>\n\n<p>Perhaps you can leave a process running on the machine watching for changes and creating a file for you to read later.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 56699, "author": "NotMyself", "author_id": 303, "author_profile": "https://Stackoverflow.com/users/303", "pm_score": 0, "selected": false, "text": "<p>If you are not opposed to using .NET the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx\" rel=\"nofollow noreferrer\">FileSystemWatcher</a> class will handle this for you fairly easily.</p>\n" }, { "answer_id": 56710, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 0, "selected": false, "text": "<p>Nothing easy - if you have a running app you can use the Win32 file change notification apis (FindFirstChangeNotification) as suggested with the other answers. warning: circa 2000 trend micro real-time virus scanner would group the changes together making it necessary to use really large buffers when requesting the file system change lists.</p>\n\n<p>If you don't have a running app, you can turn on ntfs journaling and scan the journal for changes <a href=\"http://msdn.microsoft.com/en-us/library/aa363798(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa363798(VS.85).aspx</a> but this can be slower than scanning the whole directory when the # of changes is larger than the # of files.</p>\n" }, { "answer_id": 56762, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 0, "selected": false, "text": "<p>From the double post someone mentioned: WMI Event Sink</p>\n\n<p>Still looking for a better answer though.</p>\n" }, { "answer_id": 56768, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 4, "selected": true, "text": "<p>This <a href=\"http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx\" rel=\"nofollow noreferrer\">article</a> should help. Basically, you create one or more notification object such as:</p>\n\n<pre>\nHANDLE dwChangeHandles[2]; \ndwChangeHandles[0] = FindFirstChangeNotification( \n lpDir, // directory to watch \n FALSE, // do not watch subtree \n FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes \n\n if (dwChangeHandles[0] == INVALID_HANDLE_VALUE) \n {\n printf(\"\\n ERROR: FindFirstChangeNotification function failed.\\n\");\n ExitProcess(GetLastError()); \n }\n\n// Watch the subtree for directory creation and deletion. \n dwChangeHandles[1] = FindFirstChangeNotification( \n lpDrive, // directory to watch \n TRUE, // watch the subtree \n FILE_NOTIFY_CHANGE_DIR_NAME); // watch dir name changes \n\n if (dwChangeHandles[1] == INVALID_HANDLE_VALUE) \n {\n printf(\"\\n ERROR: FindFirstChangeNotification function failed.\\n\");\n ExitProcess(GetLastError()); \n }\n</pre>\n\n<p>and then you wait for a notification:</p>\n\n<pre>\n while (TRUE) \n { \n // Wait for notification. \n printf(\"\\nWaiting for notification...\\n\");\n\n DWORD dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, \n FALSE, INFINITE); \n\n switch (dwWaitStatus) \n { \n case WAIT_OBJECT_0: \n\n // A file was created, renamed, or deleted in the directory.\n // Restart the notification. \n if ( FindNextChangeNotification(dwChangeHandles[0]) == FALSE )\n {\n printf(\"\\n ERROR: FindNextChangeNotification function failed.\\n\");\n ExitProcess(GetLastError()); \n }\n break; \n\n case WAIT_OBJECT_0 + 1: \n\n // Restart the notification. \n if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE )\n {\n printf(\"\\n ERROR: FindNextChangeNotification function failed.\\n\");\n ExitProcess(GetLastError()); \n }\n break; \n\n case WAIT_TIMEOUT:\n\n // A time-out occurred. This would happen if some value other \n // than INFINITE is used in the Wait call and no changes occur.\n // In a single-threaded environment, you might not want an\n // INFINITE wait.\n\n printf(\"\\nNo changes in the time-out period.\\n\");\n break;\n\n default: \n printf(\"\\n ERROR: Unhandled dwWaitStatus.\\n\");\n ExitProcess(GetLastError());\n break;\n }\n }\n}\n</pre>\n" }, { "answer_id": 57024, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "<p>Perhaps you can use the NTFS 5 Change Journal with DeviceIoControl as explained <a href=\"http://www.microsoft.com/msj/0999/journal/journal.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 168823, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa365465%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">ReadDirectoryChangesW</a></p>\n\n<p>Some excellent sample code in <a href=\"http://www.codeproject.com/KB/files/directorychangewatcher.aspx\" rel=\"nofollow noreferrer\">this CodeProject article</a></p>\n" }, { "answer_id": 335259, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 2, "selected": false, "text": "<p>This is perhaps overkill, but the <a href=\"http://www.microsoft.com/whdc/devtools/ifskit/default.mspx\" rel=\"nofollow noreferrer\">IFS kit</a> from MS or the <a href=\"http://www.osr.com/toolkits_fddk.shtml\" rel=\"nofollow noreferrer\">FDDK</a> from OSR might be an alternative. Create your own filesystem filter driver with simple monitoring of all changes to the filesystem.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
In Windows, is there an easy way to tell if a folder has a subfile that has changed? I verified, and the last modified date on the folder does not get updated when a subfile changes. Is there a registry entry I can set that will modify this behavior? If it matters, I am using an NTFS volume. I would ultimately like to have this ability from a C++ program. **Scanning an entire directory recursively will not work for me because the folder is much too large.** **Update: I really need a way to do this without a process running while the change occurs. So installing a file system watcher is not optimal for me.** **Update2: The archive bit will also not work because it has the same problem as the last modification date. The file's archive bit will be set, but the folders will not.**
This [article](http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx) should help. Basically, you create one or more notification object such as: ``` HANDLE dwChangeHandles[2]; dwChangeHandles[0] = FindFirstChangeNotification( lpDir, // directory to watch FALSE, // do not watch subtree FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes if (dwChangeHandles[0] == INVALID_HANDLE_VALUE) { printf("\n ERROR: FindFirstChangeNotification function failed.\n"); ExitProcess(GetLastError()); } // Watch the subtree for directory creation and deletion. dwChangeHandles[1] = FindFirstChangeNotification( lpDrive, // directory to watch TRUE, // watch the subtree FILE_NOTIFY_CHANGE_DIR_NAME); // watch dir name changes if (dwChangeHandles[1] == INVALID_HANDLE_VALUE) { printf("\n ERROR: FindFirstChangeNotification function failed.\n"); ExitProcess(GetLastError()); } ``` and then you wait for a notification: ``` while (TRUE) { // Wait for notification. printf("\nWaiting for notification...\n"); DWORD dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE, INFINITE); switch (dwWaitStatus) { case WAIT_OBJECT_0: // A file was created, renamed, or deleted in the directory. // Restart the notification. if ( FindNextChangeNotification(dwChangeHandles[0]) == FALSE ) { printf("\n ERROR: FindNextChangeNotification function failed.\n"); ExitProcess(GetLastError()); } break; case WAIT_OBJECT_0 + 1: // Restart the notification. if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE ) { printf("\n ERROR: FindNextChangeNotification function failed.\n"); ExitProcess(GetLastError()); } break; case WAIT_TIMEOUT: // A time-out occurred. This would happen if some value other // than INFINITE is used in the Wait call and no changes occur. // In a single-threaded environment, you might not want an // INFINITE wait. printf("\nNo changes in the time-out period.\n"); break; default: printf("\n ERROR: Unhandled dwWaitStatus.\n"); ExitProcess(GetLastError()); break; } } } ```
56,692
<p>Consider the class below that represents a Broker:</p> <pre><code>public class Broker { public string Name = string.Empty; public int Weight = 0; public Broker(string n, int w) { this.Name = n; this.Weight = w; } } </code></pre> <p>I'd like to randomly select a Broker from an array, taking into account their weights.</p> <p>What do you think of the code below?</p> <pre><code>class Program { private static Random _rnd = new Random(); public static Broker GetBroker(List&lt;Broker&gt; brokers, int totalWeight) { // totalWeight is the sum of all brokers' weight int randomNumber = _rnd.Next(0, totalWeight); Broker selectedBroker = null; foreach (Broker broker in brokers) { if (randomNumber &lt;= broker.Weight) { selectedBroker = broker; break; } randomNumber = randomNumber - broker.Weight; } return selectedBroker; } static void Main(string[] args) { List&lt;Broker&gt; brokers = new List&lt;Broker&gt;(); brokers.Add(new Broker("A", 10)); brokers.Add(new Broker("B", 20)); brokers.Add(new Broker("C", 20)); brokers.Add(new Broker("D", 10)); // total the weigth int totalWeight = 0; foreach (Broker broker in brokers) { totalWeight += broker.Weight; } while (true) { Dictionary&lt;string, int&gt; result = new Dictionary&lt;string, int&gt;(); Broker selectedBroker = null; for (int i = 0; i &lt; 1000; i++) { selectedBroker = GetBroker(brokers, totalWeight); if (selectedBroker != null) { if (result.ContainsKey(selectedBroker.Name)) { result[selectedBroker.Name] = result[selectedBroker.Name] + 1; } else { result.Add(selectedBroker.Name, 1); } } } Console.WriteLine("A\t\t" + result["A"]); Console.WriteLine("B\t\t" + result["B"]); Console.WriteLine("C\t\t" + result["C"]); Console.WriteLine("D\t\t" + result["D"]); result.Clear(); Console.WriteLine(); Console.ReadLine(); } } } </code></pre> <p>I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.</p> <p>Is there a more accurate algorithm?</p> <p>Thanks!</p>
[ { "answer_id": 56735, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "<p>Your algorithm is nearly correct. However, the test should be <code>&lt;</code> instead of <code>&lt;=</code>:</p>\n\n<pre><code>if (randomNumber &lt; broker.Weight)\n</code></pre>\n\n<p>This is because 0 is inclusive in the random number while <code>totalWeight</code> is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what you want. This accounts for broker A having more hits than broker D.</p>\n\n<p>Other than that, your algorithm is fine and in fact the canonical way of solving this problem.</p>\n" }, { "answer_id": 57508, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>An alternative method favours speed when selecting the broker over memory usage. Basically we create the list containing the same number of references to a broker instance as the specified weight.</p>\n\n<pre><code>List&lt;Broker&gt; brokers = new List&lt;Broker&gt;();\nfor (int i=0; i&lt;10; i++)\n brokers.Add(new Broker(\"A\", 10));\nfor (int i=0; i&lt;20; i++)\n brokers.Add(new Broker(\"B\", 20));\nfor (int i=0; i&lt;20; i++)\n brokers.Add(new Broker(\"C\", 20));\nfor (int i=0; i&lt;10; i++)\n brokers.Add(new Broker(\"D\", 10));\n</code></pre>\n\n<p>Then, to select a randomly weighted instance is an O(1) operation:</p>\n\n<pre><code>int randomNumber = _rnd.Next(0, brokers.length);\nselectedBroker = brokers[randomNumber];\n</code></pre>\n" }, { "answer_id": 58113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you want more speed you can either consider weighted reservoir sampling where you don't have to find the total weight ahead of time (but you sample more often from the random number generator). The code might look something like</p>\n\n<pre><code>Broker selected = null;\nint s = 0;\nforeach(Broker broker in brokers) {\n s += broker.Weight;\n if (broker.Weight &lt;= _rnd.Next(0,s)) {\n selected = broker;\n }\n}\n</code></pre>\n\n<p>This requires going once through the list brokers. However if the list of brokers is fixed or doesn't change that often you can keep an array of cumulative sums, i.e. A[i] is the sum of weights of all brokers 0,..,i-1. Then A[n] is the total weight and if you pick a number between 1 and A[n-1], say x you find the broker j s.t. A[j-1] &lt;= x &lt; A[j]. For convenience you let A[0] = 0. You can find this broker number j in log(n) steps using binary search, I'll leave the code as an easy exercise. If your data changes frequently this might not be a good way to go since every time some weight changes you might need to update a large portion of the array.</p>\n" }, { "answer_id": 3899874, "author": "Cagatay", "author_id": 425885, "author_profile": "https://Stackoverflow.com/users/425885", "pm_score": 4, "selected": false, "text": "<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var books = new List&lt;Book&gt; {\n new Book{Isbn=1,Name=\"A\",Weight=1},\n new Book{Isbn=2,Name=\"B\",Weight=100},\n new Book{Isbn=3,Name=\"C\",Weight=1000},\n new Book{Isbn=4,Name=\"D\",Weight=10000},\n new Book{Isbn=5,Name=\"E\",Weight=100000}};\n\n Book randomlySelectedBook = WeightedRandomization.Choose(books);\n }\n}\n\npublic static class WeightedRandomization\n{\n public static T Choose&lt;T&gt;(List&lt;T&gt; list) where T : IWeighted\n {\n if (list.Count == 0)\n {\n return default(T);\n }\n\n int totalweight = list.Sum(c =&gt; c.Weight);\n Random rand = new Random();\n int choice = rand.Next(totalweight);\n int sum = 0;\n\n foreach (var obj in list)\n {\n for (int i = sum; i &lt; obj.Weight + sum; i++)\n {\n if (i &gt;= choice)\n {\n return obj;\n }\n }\n sum += obj.Weight;\n }\n\n return list.First();\n }\n}\n\npublic interface IWeighted\n{\n int Weight { get; set; }\n}\n\npublic class Book : IWeighted\n{\n public int Isbn { get; set; }\n public string Name { get; set; }\n public int Weight { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 8720099, "author": "Jordan", "author_id": 443602, "author_profile": "https://Stackoverflow.com/users/443602", "pm_score": 0, "selected": false, "text": "<p>I've come up with a generic version of this solution:</p>\n\n<pre><code>public static class WeightedEx\n{\n /// &lt;summary&gt;\n /// Select an item from the given sequence according to their respective weights.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TItem\"&gt;Type of item item in the given sequence.&lt;/typeparam&gt;\n /// &lt;param name=\"a_source\"&gt;Given sequence of weighted items.&lt;/param&gt;\n /// &lt;returns&gt;Randomly picked item.&lt;/returns&gt;\n public static TItem PickWeighted&lt;TItem&gt;(this IEnumerable&lt;TItem&gt; a_source)\n where TItem : IWeighted\n {\n if (!a_source.Any())\n return default(TItem);\n\n var source= a_source.OrderBy(i =&gt; i.Weight);\n\n double dTotalWeight = source.Sum(i =&gt; i.Weight);\n\n Random rand = new Random();\n\n while (true)\n {\n double dRandom = rand.NextDouble() * dTotalWeight;\n\n foreach (var item in source)\n {\n if (dRandom &lt; item.Weight)\n return item;\n\n dRandom -= item.Weight;\n }\n }\n }\n}\n\n/// &lt;summary&gt;\n/// IWeighted: Implementation of an item that is weighted.\n/// &lt;/summary&gt;\npublic interface IWeighted\n{\n double Weight { get; }\n}\n</code></pre>\n" }, { "answer_id": 11930875, "author": "necrogt4", "author_id": 1594818, "author_profile": "https://Stackoverflow.com/users/1594818", "pm_score": 5, "selected": false, "text": "<p>How about something a little more generic, that can be used for any data type?</p>\n<pre><code>using System;\nusing System.Linq;\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic static class IEnumerableExtensions {\n \n public static T RandomElementByWeight&lt;T&gt;(this IEnumerable&lt;T&gt; sequence, Func&lt;T, float&gt; weightSelector) {\n float totalWeight = sequence.Sum(weightSelector);\n // The weight we are after...\n float itemWeightIndex = (float)new Random().NextDouble() * totalWeight;\n float currentWeightIndex = 0;\n\n foreach(var item in from weightedItem in sequence select new { Value = weightedItem, Weight = weightSelector(weightedItem) }) {\n currentWeightIndex += item.Weight;\n \n // If we've hit or passed the weight we are after for this item then it's the one we want....\n if(currentWeightIndex &gt;= itemWeightIndex)\n return item.Value;\n \n }\n \n return default(T);\n \n }\n \n}\n</code></pre>\n<p>Simply call by</p>\n<pre><code> Dictionary&lt;string, float&gt; foo = new Dictionary&lt;string, float&gt;();\n foo.Add(&quot;Item 25% 1&quot;, 0.5f);\n foo.Add(&quot;Item 25% 2&quot;, 0.5f);\n foo.Add(&quot;Item 50%&quot;, 1f);\n \n for(int i = 0; i &lt; 10; i++)\n Console.WriteLine(this, &quot;Item Chosen {0}&quot;, foo.RandomElementByWeight(e =&gt; e.Value));\n</code></pre>\n" }, { "answer_id": 30948171, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 3, "selected": false, "text": "<p>Since this is the top result on Google:</p>\n\n<p>I've created <a href=\"https://github.com/BlueRaja/Weighted-Item-Randomizer-for-C-Sharp\" rel=\"noreferrer\">a C# library for randomly selected weighted items</a>.</p>\n\n<ul>\n<li>It implements both the tree-selection and walker alias method algorithms, to give the best performance for all use-cases.</li>\n<li>It is unit-tested and optimized.</li>\n<li>It has LINQ support.</li>\n<li>It's free and open-source, licensed under the MIT license.</li>\n</ul>\n\n<p>Some example code:</p>\n\n<pre><code>IWeightedRandomizer&lt;string&gt; randomizer = new DynamicWeightedRandomizer&lt;string&gt;();\nrandomizer[\"Joe\"] = 1;\nrandomizer[\"Ryan\"] = 2;\nrandomizer[\"Jason\"] = 2;\n\nstring name1 = randomizer.RandomWithReplacement();\n//name1 has a 20% chance of being \"Joe\", 40% of \"Ryan\", 40% of \"Jason\"\n\nstring name2 = randomizer.RandomWithRemoval();\n//Same as above, except whichever one was chosen has been removed from the list.\n</code></pre>\n" }, { "answer_id": 37174530, "author": "Lord of the Goo", "author_id": 277389, "author_profile": "https://Stackoverflow.com/users/277389", "pm_score": 0, "selected": false, "text": "<p>Just to share my own implementation. Hope you'll find it useful.</p>\n\n<pre><code> // Author: Giovanni Costagliola &lt;[email protected]&gt;\n\n using System;\n using System.Collections.Generic;\n using System.Linq;\n\n namespace Utils\n {\n /// &lt;summary&gt;\n /// Represent a Weighted Item.\n /// &lt;/summary&gt;\n public interface IWeighted\n {\n /// &lt;summary&gt;\n /// A positive weight. It's up to the implementer ensure this requirement\n /// &lt;/summary&gt;\n int Weight { get; }\n }\n\n /// &lt;summary&gt;\n /// Pick up an element reflecting its weight.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n public class RandomWeightedPicker&lt;T&gt; where T:IWeighted\n {\n private readonly IEnumerable&lt;T&gt; items;\n private readonly int totalWeight;\n private Random random = new Random();\n\n /// &lt;summary&gt;\n /// Initiliaze the structure. O(1) or O(n) depending by the options, default O(n).\n /// &lt;/summary&gt;\n /// &lt;param name=\"items\"&gt;The items&lt;/param&gt;\n /// &lt;param name=\"checkWeights\"&gt;If &lt;c&gt;true&lt;/c&gt; will check that the weights are positive. O(N)&lt;/param&gt;\n /// &lt;param name=\"shallowCopy\"&gt;If &lt;c&gt;true&lt;/c&gt; will copy the original collection structure (not the items). Keep in mind that items lifecycle is impacted.&lt;/param&gt;\n public RandomWeightedPicker(IEnumerable&lt;T&gt; items, bool checkWeights = true, bool shallowCopy = true)\n {\n if (items == null) throw new ArgumentNullException(\"items\");\n if (!items.Any()) throw new ArgumentException(\"items cannot be empty\");\n if (shallowCopy)\n this.items = new List&lt;T&gt;(items);\n else\n this.items = items;\n if (checkWeights &amp;&amp; this.items.Any(i =&gt; i.Weight &lt;= 0))\n {\n throw new ArgumentException(\"There exists some items with a non positive weight\");\n }\n totalWeight = this.items.Sum(i =&gt; i.Weight);\n }\n /// &lt;summary&gt;\n /// Pick a random item based on its chance. O(n)\n /// &lt;/summary&gt;\n /// &lt;param name=\"defaultValue\"&gt;The value returned in case the element has not been found&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public T PickAnItem()\n {\n int rnd = random.Next(totalWeight);\n return items.First(i =&gt; (rnd -= i.Weight) &lt; 0);\n }\n\n /// &lt;summary&gt;\n /// Resets the internal random generator. O(1)\n /// &lt;/summary&gt;\n /// &lt;param name=\"seed\"&gt;&lt;/param&gt;\n public void ResetRandomGenerator(int? seed)\n {\n random = seed.HasValue ? new Random(seed.Value) : new Random();\n }\n }\n}\n</code></pre>\n\n<p>Gist: <a href=\"https://gist.github.com/MrBogomips/ae6f6c9af8032392e4b93aaa393df447\" rel=\"nofollow\">https://gist.github.com/MrBogomips/ae6f6c9af8032392e4b93aaa393df447</a></p>\n" }, { "answer_id": 55612460, "author": "user2796283", "author_id": 2796283, "author_profile": "https://Stackoverflow.com/users/2796283", "pm_score": 0, "selected": false, "text": "<p>The implementation in the original question seems a little odd to me;</p>\n\n<p>The total weight of the list is 60 so the random number is 0-59.\nIt always checks the random number against the weight and then decrements it.\nIt looks to me that it would favour things in the list based on their order.</p>\n\n<p>Here's a generic implementation I'm using - the crux is in the Random property:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class WeightedList&lt;T&gt;\n{\n private readonly Dictionary&lt;T,int&gt; _items = new Dictionary&lt;T,int&gt;();\n\n // Doesn't allow items with zero weight; to remove an item, set its weight to zero\n public void SetWeight(T item, int weight)\n {\n if (_items.ContainsKey(item))\n {\n if (weight != _items[item])\n {\n if (weight &gt; 0)\n {\n _items[item] = weight;\n }\n else\n {\n _items.Remove(item);\n }\n\n _totalWeight = null; // Will recalculate the total weight later\n }\n }\n else if (weight &gt; 0)\n {\n _items.Add(item, weight);\n\n _totalWeight = null; // Will recalculate the total weight later\n }\n }\n\n public int GetWeight(T item)\n {\n return _items.ContainsKey(item) ? _items[item] : 0;\n }\n\n private int? _totalWeight;\n public int totalWeight\n {\n get\n {\n if (!_totalWeight.HasValue) _totalWeight = _items.Sum(x =&gt; x.Value);\n\n return _totalWeight.Value;\n }\n }\n\n public T Random\n {\n get\n {\n var temp = 0;\n var random = new Random().Next(totalWeight);\n\n foreach (var item in _items)\n {\n temp += item.Value;\n\n if (random &lt; temp) return item.Key;\n }\n\n throw new Exception($\"unable to determine random {typeof(T)} at {random} in {totalWeight}\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 60995361, "author": "zhe", "author_id": 90180, "author_profile": "https://Stackoverflow.com/users/90180", "pm_score": 2, "selected": false, "text": "<p>A little bit too late but here's C#7 example. It's pretty small and gives correct distribution.</p>\n\n<pre><code>public static class RandomTools\n{\n public static T PickRandomItemWeighted&lt;T&gt;(IList&lt;(T Item, int Weight)&gt; items)\n {\n if ((items?.Count ?? 0) == 0)\n {\n return default;\n }\n\n int offset = 0;\n (T Item, int RangeTo)[] rangedItems = items\n .OrderBy(item =&gt; item.Weight)\n .Select(entry =&gt; (entry.Item, RangeTo: offset += entry.Weight))\n .ToArray();\n\n int randomNumber = new Random().Next(items.Sum(item =&gt; item.Weight)) + 1;\n return rangedItems.First(item =&gt; randomNumber &lt;= item.RangeTo).Item;\n }\n}\n</code></pre>\n" }, { "answer_id": 71134909, "author": "RWolfe", "author_id": 3915050, "author_profile": "https://Stackoverflow.com/users/3915050", "pm_score": 0, "selected": false, "text": "<p>Another option is this</p>\n<pre><code>private static Random _Rng = new Random();\npublic static Broker GetBroker(List&lt;Broker&gt; brokers){\n List&lt;Broker&gt; weightedBrokerList = new List&lt;Broker&gt;();\n foreach(Broker broker in brokers) {\n for(int i=0;i&lt;broker.Weight;i++) {\n weightedBrokerList.Add(broker);\n }\n }\n return weightedBrokerList[_Rng.Next(weightedBrokerList.Count)];\n}\n</code></pre>\n" }, { "answer_id": 72568836, "author": "Chris", "author_id": 8291038, "author_profile": "https://Stackoverflow.com/users/8291038", "pm_score": 2, "selected": false, "text": "<p>June 2022: One more implementation (in c#) for the pile:</p>\n<p><a href=\"https://github.com/cdanek/KaimiraWeightedList\" rel=\"nofollow noreferrer\">https://github.com/cdanek/KaimiraWeightedList</a></p>\n<p><code>O(1)</code> gets (!), <code>O(n)</code> memory, <code>O(n)</code> add/removes/edits, robust (nearly all <code>IList</code> methods are implemented) and extremely easy to use (one C# file, one line of code to construct, one line of code to add items, one line of code to get an item):</p>\n<pre class=\"lang-cs prettyprint-override\"><code>WeightedList&lt;string&gt; myList = new();\nmyList.Add(&quot;Hello&quot;, 1);\nmyList.Add(&quot;World&quot;, 2);\nConsole.WriteLine(myList.Next()); // Hello 33%, World 66%\n</code></pre>\n<p>Uses walker-vose alias method.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2868/" ]
Consider the class below that represents a Broker: ``` public class Broker { public string Name = string.Empty; public int Weight = 0; public Broker(string n, int w) { this.Name = n; this.Weight = w; } } ``` I'd like to randomly select a Broker from an array, taking into account their weights. What do you think of the code below? ``` class Program { private static Random _rnd = new Random(); public static Broker GetBroker(List<Broker> brokers, int totalWeight) { // totalWeight is the sum of all brokers' weight int randomNumber = _rnd.Next(0, totalWeight); Broker selectedBroker = null; foreach (Broker broker in brokers) { if (randomNumber <= broker.Weight) { selectedBroker = broker; break; } randomNumber = randomNumber - broker.Weight; } return selectedBroker; } static void Main(string[] args) { List<Broker> brokers = new List<Broker>(); brokers.Add(new Broker("A", 10)); brokers.Add(new Broker("B", 20)); brokers.Add(new Broker("C", 20)); brokers.Add(new Broker("D", 10)); // total the weigth int totalWeight = 0; foreach (Broker broker in brokers) { totalWeight += broker.Weight; } while (true) { Dictionary<string, int> result = new Dictionary<string, int>(); Broker selectedBroker = null; for (int i = 0; i < 1000; i++) { selectedBroker = GetBroker(brokers, totalWeight); if (selectedBroker != null) { if (result.ContainsKey(selectedBroker.Name)) { result[selectedBroker.Name] = result[selectedBroker.Name] + 1; } else { result.Add(selectedBroker.Name, 1); } } } Console.WriteLine("A\t\t" + result["A"]); Console.WriteLine("B\t\t" + result["B"]); Console.WriteLine("C\t\t" + result["C"]); Console.WriteLine("D\t\t" + result["D"]); result.Clear(); Console.WriteLine(); Console.ReadLine(); } } } ``` I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight. Is there a more accurate algorithm? Thanks!
Your algorithm is nearly correct. However, the test should be `<` instead of `<=`: ``` if (randomNumber < broker.Weight) ``` This is because 0 is inclusive in the random number while `totalWeight` is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what you want. This accounts for broker A having more hits than broker D. Other than that, your algorithm is fine and in fact the canonical way of solving this problem.
56,698
<p>I would like to generate a list of differences between 2 instances of the the same object. Object in question:</p> <pre><code>public class Step { [DataMember] public StepInstanceInfo InstanceInfo { get; set; } [DataMember] public Collection&lt;string&gt; AdHocRules { get; set; } [DataMember] public Collection&lt;StepDoc&gt; StepDocs {...} [DataMember] public Collection&lt;StepUsers&gt; StepUsers {...} } </code></pre> <p>What I would like to do is <strong>find an intelligent way to return an object that lists the differences between the two instances</strong> (for example, let me know that 2 specific StepDocs were added, 1 specific StepUser was removed, and one rule was changed from "Go" to "Stop"). I have been looking into using a MD5 hash, but I can't find any good examples of traversing an object like this and returning a <strong>manifest of the specific differences</strong> (not just indicating that they are different).</p> <p><em>Additional Background:</em> the reason that I need to do this is the API that I am supporting allows clients to SaveStep(Step step)...this works great for persisting the Step object to the db using entities and repositories. I need to raise specific events (like this user was added, etc) from this SaveStep method, though, in order to alert another system (workflow engine) that a specific element in the step has changed. Thank you.</p>
[ { "answer_id": 56774, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Implementing the IComparable interface in your object may provide you with the functionality you need. This will provide you a custom way to determine differences between objects without resorting to checksums which really won't help you track what the differences are in usable terms. Otherwise, there's no way to determine equality between two user objects in .NET that I know of. There are some decent examples of the usage of this interface in the help file for Visual Studio, or <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.icomparable\" rel=\"nofollow noreferrer\">here</a>. You might be able to glean some directives from the examples on clean ways to compare the properties and store the values in some usable manner for tracking purposes (perhaps a collection, or dictionary object?). </p>\n\n<p>Hope this helps,\nGreg</p>\n" }, { "answer_id": 57832, "author": "Todd Rowan", "author_id": 3473, "author_profile": "https://Stackoverflow.com/users/3473", "pm_score": 3, "selected": true, "text": "<p>You'll need a separate object, like StepDiff with collections for removed and added items. The easiest way to do something like this is to copy the collections from each of the old and new objects, so that StepDiff has collectionOldStepDocs and collectionNewStepDocs. </p>\n\n<p>Grab the shorter collection and iterate through it and see if each StepDoc exists in the other collection. If so, delete the StepDoc reference from both collections. Then when you're finished iterating, collectionOldStepDocs contains stepDocs that were deleted and collectionNewStepDocs contains the stepDocs that were added. </p>\n\n<p>From there you should be able to build your manifest in whatever way necessary. </p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like to generate a list of differences between 2 instances of the the same object. Object in question: ``` public class Step { [DataMember] public StepInstanceInfo InstanceInfo { get; set; } [DataMember] public Collection<string> AdHocRules { get; set; } [DataMember] public Collection<StepDoc> StepDocs {...} [DataMember] public Collection<StepUsers> StepUsers {...} } ``` What I would like to do is **find an intelligent way to return an object that lists the differences between the two instances** (for example, let me know that 2 specific StepDocs were added, 1 specific StepUser was removed, and one rule was changed from "Go" to "Stop"). I have been looking into using a MD5 hash, but I can't find any good examples of traversing an object like this and returning a **manifest of the specific differences** (not just indicating that they are different). *Additional Background:* the reason that I need to do this is the API that I am supporting allows clients to SaveStep(Step step)...this works great for persisting the Step object to the db using entities and repositories. I need to raise specific events (like this user was added, etc) from this SaveStep method, though, in order to alert another system (workflow engine) that a specific element in the step has changed. Thank you.
You'll need a separate object, like StepDiff with collections for removed and added items. The easiest way to do something like this is to copy the collections from each of the old and new objects, so that StepDiff has collectionOldStepDocs and collectionNewStepDocs. Grab the shorter collection and iterate through it and see if each StepDoc exists in the other collection. If so, delete the StepDoc reference from both collections. Then when you're finished iterating, collectionOldStepDocs contains stepDocs that were deleted and collectionNewStepDocs contains the stepDocs that were added. From there you should be able to build your manifest in whatever way necessary.
56,709
<p>I get the following error message in SQL Server 2005:</p> <pre><code>User '&lt;username&gt;' does not have permission to run DBCC DBREINDEX for object '&lt;table&gt;'. </code></pre> <p>Which minimum role do I have to give to user in order to run the command?</p>
[ { "answer_id": 56720, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": true, "text": "<p>You will need to be a member of the <strong>db_ddladmin</strong> or the <strong>db_owner</strong> role AFAIK</p>\n" }, { "answer_id": 56733, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Caller must own the table, or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms181671(SQL.90).aspx\" rel=\"nofollow noreferrer\">DBCC DBREINDEX (Transact-SQL) @ MSDN</a></p>\n" }, { "answer_id": 29942812, "author": "justintjacob", "author_id": 1374202, "author_profile": "https://Stackoverflow.com/users/1374202", "pm_score": 1, "selected": false, "text": "<p>ALTER AUTHORIZATION ON Tablename TO [domain\\username]</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
I get the following error message in SQL Server 2005: ``` User '<username>' does not have permission to run DBCC DBREINDEX for object '<table>'. ``` Which minimum role do I have to give to user in order to run the command?
You will need to be a member of the **db\_ddladmin** or the **db\_owner** role AFAIK
56,729
<p>Can somebody give me a complete and working example of calling the <code>AllocateAndInitializeSid</code> function from C# code?</p> <p>I found <a href="http://msdn.microsoft.com/en-us/library/aa375213(VS.85).aspx" rel="nofollow noreferrer">this</a>: </p> <pre><code>BOOL WINAPI AllocateAndInitializeSid( __in PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority, __in BYTE nSubAuthorityCount, __in DWORD dwSubAuthority0, __in DWORD dwSubAuthority1, __in DWORD dwSubAuthority2, __in DWORD dwSubAuthority3, __in DWORD dwSubAuthority4, __in DWORD dwSubAuthority5, __in DWORD dwSubAuthority6, __in DWORD dwSubAuthority7, __out PSID *pSid ); </code></pre> <p>and I don't know how to construct the signature of this method - what should I do with <code>PSID_IDENTIFIER_AUTHORITY</code> and <code>PSID</code> types? How should I pass them - using <code>ref</code> or <code>out</code>?</p>
[ { "answer_id": 56745, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 1, "selected": false, "text": "<p>For Platform Invoke www.pinvoke.net is your new best friend!</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/advapi32/AllocateAndInitializeSid.html\" rel=\"nofollow noreferrer\">http://www.pinvoke.net/default.aspx/advapi32/AllocateAndInitializeSid.html</a></p>\n" }, { "answer_id": 58157, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 2, "selected": false, "text": "<p>If you are targeting .NET 2.0 or later, the class System.Security.Principal.SecurityIdentifier wraps a SID and allows you to avoid the error-prone Win32 APIs.</p>\n\n<p>Not exactly an answer to your question, but who knows it may be useful.</p>\n" }, { "answer_id": 58180, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 3, "selected": true, "text": "<p>Using <a href=\"http://www.codeplex.com/clrinterop\" rel=\"nofollow noreferrer\">P/Invoke Interop Assistant</a>:</p>\n\n<pre><code> [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\n public struct SidIdentifierAuthority {\n\n /// BYTE[6]\n [System.Runtime.InteropServices.MarshalAsAttribute(\n System.Runtime.InteropServices.UnmanagedType.ByValArray, \n SizeConst = 6, \n ArraySubType = \n System.Runtime.InteropServices.UnmanagedType.I1)]\n public byte[] Value;\n }\n\n public partial class NativeMethods {\n\n /// Return Type: BOOL-&gt;int\n ///pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY-&gt;_SID_IDENTIFIER_AUTHORITY*\n ///nSubAuthorityCount: BYTE-&gt;unsigned char\n ///nSubAuthority0: DWORD-&gt;unsigned int\n ///nSubAuthority1: DWORD-&gt;unsigned int\n ///nSubAuthority2: DWORD-&gt;unsigned int\n ///nSubAuthority3: DWORD-&gt;unsigned int\n ///nSubAuthority4: DWORD-&gt;unsigned int\n ///nSubAuthority5: DWORD-&gt;unsigned int\n ///nSubAuthority6: DWORD-&gt;unsigned int\n ///nSubAuthority7: DWORD-&gt;unsigned int\n ///pSid: PSID*\n [System.Runtime.InteropServices.DllImportAttribute(\"advapi32.dll\", EntryPoint = \"AllocateAndInitializeSid\")]\n [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]\n public static extern bool AllocateAndInitializeSid(\n [System.Runtime.InteropServices.InAttribute()] \n ref SidIdentifierAuthority pIdentifierAuthority, \n byte nSubAuthorityCount, \n uint nSubAuthority0, \n uint nSubAuthority1, \n uint nSubAuthority2, \n uint nSubAuthority3, \n uint nSubAuthority4, \n uint nSubAuthority5, \n uint nSubAuthority6, \n uint nSubAuthority7, \n out System.IntPtr pSid);\n\n }\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95/" ]
Can somebody give me a complete and working example of calling the `AllocateAndInitializeSid` function from C# code? I found [this](http://msdn.microsoft.com/en-us/library/aa375213(VS.85).aspx): ``` BOOL WINAPI AllocateAndInitializeSid( __in PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority, __in BYTE nSubAuthorityCount, __in DWORD dwSubAuthority0, __in DWORD dwSubAuthority1, __in DWORD dwSubAuthority2, __in DWORD dwSubAuthority3, __in DWORD dwSubAuthority4, __in DWORD dwSubAuthority5, __in DWORD dwSubAuthority6, __in DWORD dwSubAuthority7, __out PSID *pSid ); ``` and I don't know how to construct the signature of this method - what should I do with `PSID_IDENTIFIER_AUTHORITY` and `PSID` types? How should I pass them - using `ref` or `out`?
Using [P/Invoke Interop Assistant](http://www.codeplex.com/clrinterop): ``` [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct SidIdentifierAuthority { /// BYTE[6] [System.Runtime.InteropServices.MarshalAsAttribute( System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = System.Runtime.InteropServices.UnmanagedType.I1)] public byte[] Value; } public partial class NativeMethods { /// Return Type: BOOL->int ///pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY->_SID_IDENTIFIER_AUTHORITY* ///nSubAuthorityCount: BYTE->unsigned char ///nSubAuthority0: DWORD->unsigned int ///nSubAuthority1: DWORD->unsigned int ///nSubAuthority2: DWORD->unsigned int ///nSubAuthority3: DWORD->unsigned int ///nSubAuthority4: DWORD->unsigned int ///nSubAuthority5: DWORD->unsigned int ///nSubAuthority6: DWORD->unsigned int ///nSubAuthority7: DWORD->unsigned int ///pSid: PSID* [System.Runtime.InteropServices.DllImportAttribute("advapi32.dll", EntryPoint = "AllocateAndInitializeSid")] [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)] public static extern bool AllocateAndInitializeSid( [System.Runtime.InteropServices.InAttribute()] ref SidIdentifierAuthority pIdentifierAuthority, byte nSubAuthorityCount, uint nSubAuthority0, uint nSubAuthority1, uint nSubAuthority2, uint nSubAuthority3, uint nSubAuthority4, uint nSubAuthority5, uint nSubAuthority6, uint nSubAuthority7, out System.IntPtr pSid); } ```
56,737
<p>Is the standard Java 1.6 <a href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">javax.xml.parsers.DocumentBuilder</a> class thread safe? Is it safe to call the parse() method from several threads in parallel?</p> <p>The JavaDoc doesn't mention the issue, but the <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">JavaDoc for the same class</a> in Java 1.4 specifically says that it <em>isn't</em> meant to be concurrent; so can I assume that in 1.6 it is?</p> <p>The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.</p>
[ { "answer_id": 56815, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": true, "text": "<p>Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:</p>\n\n<pre><code>private static final ThreadLocal&lt;DocumentBuilder&gt; builderLocal =\n new ThreadLocal&lt;DocumentBuilder&gt;() {\n @Override protected DocumentBuilder initialValue() {\n try {\n return\n DocumentBuilderFactory\n .newInstance(\n \"xx.MyDocumentBuilderFactory\",\n getClass().getClassLoader()\n ).newDocumentBuilder();\n } catch (ParserConfigurationException exc) {\n throw new IllegalArgumentException(exc);\n }\n }\n };\n</code></pre>\n\n<p>(Disclaimer: Not so much as attempted to compile the code.)</p>\n" }, { "answer_id": 231433, "author": "Trenton", "author_id": 2601671, "author_profile": "https://Stackoverflow.com/users/2601671", "pm_score": 5, "selected": false, "text": "<p>There's a reset() method on DocumentBuilder which restores it to the state when it was first created. If you're going the ThreadLocal route, don't forget to call this or you're hosed.</p>\n" }, { "answer_id": 18823295, "author": "Koray Güclü", "author_id": 1242601, "author_profile": "https://Stackoverflow.com/users/1242601", "pm_score": 2, "selected": false, "text": "<p>You can also check this code to make further optimization <a href=\"https://svn.apache.org/repos/asf/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/xml/XmlUtil.java\" rel=\"nofollow\">https://svn.apache.org/repos/asf/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/xml/XmlUtil.java</a></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1605/" ]
Is the standard Java 1.6 [javax.xml.parsers.DocumentBuilder](http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html) class thread safe? Is it safe to call the parse() method from several threads in parallel? The JavaDoc doesn't mention the issue, but the [JavaDoc for the same class](http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html) in Java 1.4 specifically says that it *isn't* meant to be concurrent; so can I assume that in 1.6 it is? The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.
Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal: ``` private static final ThreadLocal<DocumentBuilder> builderLocal = new ThreadLocal<DocumentBuilder>() { @Override protected DocumentBuilder initialValue() { try { return DocumentBuilderFactory .newInstance( "xx.MyDocumentBuilderFactory", getClass().getClassLoader() ).newDocumentBuilder(); } catch (ParserConfigurationException exc) { throw new IllegalArgumentException(exc); } } }; ``` (Disclaimer: Not so much as attempted to compile the code.)
56,767
<p>Is there a difference (performance, overhead) between these two ways of merging data sets?</p> <pre><code>MyTypedDataSet aDataSet = new MyTypedDataSet(); aDataSet .Merge(anotherDataSet); aDataSet .Merge(yetAnotherDataSet); </code></pre> <p>and</p> <pre><code>MyTypedDataSet aDataSet = anotherDataSet; aDataSet .Merge(yetAnotherDataSet); </code></pre> <p>Which do you recommend?</p>
[ { "answer_id": 56772, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "<p>Those two lines do different things.</p>\n\n<p>The first one creates a new set, and then merges a second set into it.</p>\n\n<p>The second one sets the ds reference to point to the second set, so:</p>\n\n<pre><code>MyTypedDataSet ds1 = new MyTypedDataSet();\nds1.Merge(anotherDataSet);\n//ds1 is a copy of anotherDataSet\nds1.Tables.Add(\"test\")\n\n//anotherDataSet does not contain the new table\n\nMyTypedDataSet ds2 = anotherDataSet;\n//ds12 actually points to anotherDataSet\nds2.Tables.Add(\"test\");\n\n//anotherDataSet now contains the new table\n</code></pre>\n\n<hr>\n\n<p>Ok, let's assume that what you meant was:</p>\n\n<pre><code>MyClass o1 = new MyClass();\no1.LoadFrom( /* some data */ );\n\n//vs\n\nMyClass o2 = new MyClass( /* some data */ );\n</code></pre>\n\n<p>Then the latter is better, as the former creates an empty object before populating it.</p>\n\n<p>However unless initialising an empty class has a high cost or is repeated a large number of times the difference is not that important.</p>\n" }, { "answer_id": 56775, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Your second example does <strong>not</strong> create a new dataset. It's just a second <em>reference</em> to an existing dataset.</p>\n" }, { "answer_id": 56781, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": true, "text": "<p>While Keith is right, I suppose the example was simply badly chosen. Generally, it is better to initialize to the “right” object from the beginning and <em>not</em> construct an intermediate, empty object as in your case. Two reasons:</p>\n\n<ol>\n<li>Performance. This should be obvious: Object creation costs time so creating less objects is better.</li>\n<li><em>Much</em> more important however, it better states your <strong>intent</strong>. You do generally <em>not</em> intend to create stateless/empty objects. Rather, you intend to create objects with some state or content. Do it. No need to create a useless (because empty) temporary.</li>\n</ol>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
Is there a difference (performance, overhead) between these two ways of merging data sets? ``` MyTypedDataSet aDataSet = new MyTypedDataSet(); aDataSet .Merge(anotherDataSet); aDataSet .Merge(yetAnotherDataSet); ``` and ``` MyTypedDataSet aDataSet = anotherDataSet; aDataSet .Merge(yetAnotherDataSet); ``` Which do you recommend?
While Keith is right, I suppose the example was simply badly chosen. Generally, it is better to initialize to the “right” object from the beginning and *not* construct an intermediate, empty object as in your case. Two reasons: 1. Performance. This should be obvious: Object creation costs time so creating less objects is better. 2. *Much* more important however, it better states your **intent**. You do generally *not* intend to create stateless/empty objects. Rather, you intend to create objects with some state or content. Do it. No need to create a useless (because empty) temporary.
56,801
<p>I was reviewing some code that a consultant checked in and notice they were using SQLCLR. I don't have any experience with it so thought I would research what it was about. I noticed that they used</p> <pre><code>Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" &amp; sDb) </code></pre> <p>instead of</p> <pre><code>DIM conn As New SqlConnection("context connection=true") </code></pre> <p>I'm wondering what the difference since it's localhost on the first?</p>
[ { "answer_id": 56864, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 4, "selected": true, "text": "<p>The context connection uses the user's already established connection to the server. So you inherit things like their database context, connection options, etc.</p>\n\n<p>Using localhost will connect to the server using a normal shared memory connection. This can be useful if you don't want to use the user's connection (i.e. if you want to connect to a different database, or with different options, etc).</p>\n\n<p>In most cases you should use the context connection, since it doesn't create a separate connection to the server.</p>\n\n<p>Also, be warned that using a separate connection means you are not part of the user's transaction and are subject to normal locking semantics.</p>\n" }, { "answer_id": 56881, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 1, "selected": false, "text": "<p>Consider a big office phone systems:</p>\n\n<p>My office has an internal phone system. But every phone also has an external phone number (virtual numbers that utilize one of a group of real TELCO lines). I can call another office by dialing their phone extension directly and the call will route through our internal phone system (one hop). Alternatively I could dial that phone's public number and the call routes out from the building's system to the TELCO switching office, then back through the building's system then to the office extension (3 hops).</p>\n\n<p>The first SQL connection behaves as any standard SQL connection would when connecting to the server specified in the connection string. A new connection is created using the standard native SQL connectivity. This behaves like dialing the full public phone number of another office phone. Sure, you are connecting to the local machine, but the connection is routed differently.</p>\n\n<p>The context connection has the new SqlConnection instance using the existing connection that is executing the SQLCLR object. It's using the existing/local context. This is like dialing my office mate's extension directly. Local context and more efficient.</p>\n\n<p>Although I'm not positive, I believe that when using the context connection, the calls to the SQLCLR objects also then participate in the context's transaction. Someone please correct me if I'm wrong.</p>\n\n<p>Peter</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
I was reviewing some code that a consultant checked in and notice they were using SQLCLR. I don't have any experience with it so thought I would research what it was about. I noticed that they used ``` Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" & sDb) ``` instead of ``` DIM conn As New SqlConnection("context connection=true") ``` I'm wondering what the difference since it's localhost on the first?
The context connection uses the user's already established connection to the server. So you inherit things like their database context, connection options, etc. Using localhost will connect to the server using a normal shared memory connection. This can be useful if you don't want to use the user's connection (i.e. if you want to connect to a different database, or with different options, etc). In most cases you should use the context connection, since it doesn't create a separate connection to the server. Also, be warned that using a separate connection means you are not part of the user's transaction and are subject to normal locking semantics.
56,810
<p>I have used fork() in C to start another process. How do I start a new thread?</p>
[ { "answer_id": 56818, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 3, "selected": false, "text": "<p>pthreads is a good start, look <a href=\"https://computing.llnl.gov/tutorials/pthreads/\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 56822, "author": "Jay Conrod", "author_id": 1891, "author_profile": "https://Stackoverflow.com/users/1891", "pm_score": 2, "selected": false, "text": "<p>Check out the <a href=\"https://computing.llnl.gov/tutorials/pthreads/\" rel=\"nofollow noreferrer\">pthread</a> (POSIX thread) library.</p>\n" }, { "answer_id": 56825, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 7, "selected": true, "text": "<p>Since you mentioned fork() I assume you're on a Unix-like system, in which case <a href=\"http://en.wikipedia.org/wiki/POSIX_Threads\" rel=\"noreferrer\">POSIX threads</a> (usually referred to as pthreads) are what you want to use.</p>\n\n<p>Specifically, pthread_create() is the function you need to create a new thread. Its arguments are:</p>\n\n<pre><code>int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *\n (*start_routine)(void *), void * arg);\n</code></pre>\n\n<p>The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.</p>\n" }, { "answer_id": 56829, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 4, "selected": false, "text": "<p>AFAIK, ANSI C doesn't define threading, but there are various libraries available.</p>\n\n<p>If you are running on Windows, link to msvcrt and use _beginthread or _beginthreadex.</p>\n\n<p>If you are running on other platforms, check out the pthreads library (I'm sure there are others as well).</p>\n" }, { "answer_id": 56986, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 3, "selected": false, "text": "<p>Threads are not part of the C standard, so the only way to use threads is to use some library (eg: POSIX threads in Unix/Linux, _beginthread/_beginthreadex if you want to use the C-runtime from that thread or just CreateThread Win32 API)</p>\n" }, { "answer_id": 52453291, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 4, "selected": false, "text": "<p><strong>C11 threads + C11 <code>atomic_int</code></strong></p>\n\n<p>Added to glibc 2.28. Tested in Ubuntu 18.10 amd64 (comes with glic 2.28) and Ubuntu 18.04 (comes with glibc 2.27) by compiling glibc 2.28 from source: <a href=\"https://stackoverflow.com/questions/847179/multiple-glibc-libraries-on-a-single-host/52454603#52454603\">Multiple glibc libraries on a single host</a></p>\n\n<p>Example adapted from: <a href=\"https://en.cppreference.com/w/c/language/atomic\" rel=\"noreferrer\">https://en.cppreference.com/w/c/language/atomic</a></p>\n\n<p>main.c</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;threads.h&gt;\n#include &lt;stdatomic.h&gt;\n\natomic_int atomic_counter;\nint non_atomic_counter;\n\nint mythread(void* thr_data) {\n (void)thr_data;\n for(int n = 0; n &lt; 1000; ++n) {\n ++non_atomic_counter;\n ++atomic_counter;\n // for this example, relaxed memory order is sufficient, e.g.\n // atomic_fetch_add_explicit(&amp;atomic_counter, 1, memory_order_relaxed);\n }\n return 0;\n}\n\nint main(void) {\n thrd_t thr[10];\n for(int n = 0; n &lt; 10; ++n)\n thrd_create(&amp;thr[n], mythread, NULL);\n for(int n = 0; n &lt; 10; ++n)\n thrd_join(thr[n], NULL);\n printf(\"atomic %d\\n\", atomic_counter);\n printf(\"non-atomic %d\\n\", non_atomic_counter);\n}\n</code></pre>\n\n<p><a href=\"https://github.com/cirosantilli/linux-kernel-module-cheat/blob/e0fb39c92ae071a444cb92fbb2d0c1977fa7af51/userland/c/atomic.c\" rel=\"noreferrer\">GitHub upstream</a>.</p>\n\n<p>Compile and run:</p>\n\n<pre><code>gcc -ggdb3 -std=c11 -Wall -Wextra -pedantic -o main.out main.c -pthread\n./main.out\n</code></pre>\n\n<p>Possible output:</p>\n\n<pre><code>atomic 10000\nnon-atomic 4341\n</code></pre>\n\n<p>The non-atomic counter is very likely to be smaller than the atomic one due to racy access across threads to the non-atomic variable.</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/2353371/how-to-do-an-atomic-increment-and-fetch-in-c/30878480#30878480\">How to do an atomic increment and fetch in C?</a></p>\n\n<p><strong>Disassembly analysis</strong></p>\n\n<p>Disassemble with:</p>\n\n<pre><code>gdb -batch -ex \"disassemble/rs mythread\" main.out\n</code></pre>\n\n<p>contains:</p>\n\n<pre><code>17 ++non_atomic_counter;\n 0x00000000004007e8 &lt;+8&gt;: 83 05 65 08 20 00 01 addl $0x1,0x200865(%rip) # 0x601054 &lt;non_atomic_counter&gt;\n\n18 __atomic_fetch_add(&amp;atomic_counter, 1, __ATOMIC_SEQ_CST);\n 0x00000000004007ef &lt;+15&gt;: f0 83 05 61 08 20 00 01 lock addl $0x1,0x200861(%rip) # 0x601058 &lt;atomic_counter&gt;\n</code></pre>\n\n<p>so we see that the atomic increment is done at the instruction level with the <a href=\"https://stackoverflow.com/questions/8891067/what-does-the-lock-instruction-mean-in-x86-assembly\"><code>f0</code> lock prefix</a>.</p>\n\n<p>With <code>aarch64-linux-gnu-gcc</code> 8.2.0, we get instead:</p>\n\n<pre><code>11 ++non_atomic_counter;\n 0x0000000000000a28 &lt;+24&gt;: 60 00 40 b9 ldr w0, [x3]\n 0x0000000000000a2c &lt;+28&gt;: 00 04 00 11 add w0, w0, #0x1\n 0x0000000000000a30 &lt;+32&gt;: 60 00 00 b9 str w0, [x3]\n\n12 ++atomic_counter;\n 0x0000000000000a34 &lt;+36&gt;: 40 fc 5f 88 ldaxr w0, [x2]\n 0x0000000000000a38 &lt;+40&gt;: 00 04 00 11 add w0, w0, #0x1\n 0x0000000000000a3c &lt;+44&gt;: 40 fc 04 88 stlxr w4, w0, [x2]\n 0x0000000000000a40 &lt;+48&gt;: a4 ff ff 35 cbnz w4, 0xa34 &lt;mythread+36&gt;\n</code></pre>\n\n<p>so the atomic version actually has a <code>cbnz</code> loop that runs until the <code>stlxr</code> store succeed. Note that ARMv8.1 can do all of that with a single LDADD instruction.</p>\n\n<p>This is analogous to what we get with C++ <code>std::atomic</code>: <a href=\"https://stackoverflow.com/questions/31978324/what-exactly-is-stdatomic/58904448#58904448\">What exactly is std::atomic?</a></p>\n\n<p><strong>Benchmark</strong></p>\n\n<p>TODO. Crate a benchmark to show that atomic is slower.</p>\n\n<p><strong>POSIX threads</strong></p>\n\n<p>main.c</p>\n\n<pre><code>#define _XOPEN_SOURCE 700\n#include &lt;assert.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;pthread.h&gt;\n\nenum CONSTANTS {\n NUM_THREADS = 1000,\n NUM_ITERS = 1000\n};\n\nint global = 0;\nint fail = 0;\npthread_mutex_t main_thread_mutex = PTHREAD_MUTEX_INITIALIZER;\n\nvoid* main_thread(void *arg) {\n int i;\n for (i = 0; i &lt; NUM_ITERS; ++i) {\n if (!fail)\n pthread_mutex_lock(&amp;main_thread_mutex);\n global++;\n if (!fail)\n pthread_mutex_unlock(&amp;main_thread_mutex);\n }\n return NULL;\n}\n\nint main(int argc, char **argv) {\n pthread_t threads[NUM_THREADS];\n int i;\n fail = argc &gt; 1;\n for (i = 0; i &lt; NUM_THREADS; ++i)\n pthread_create(&amp;threads[i], NULL, main_thread, NULL);\n for (i = 0; i &lt; NUM_THREADS; ++i)\n pthread_join(threads[i], NULL);\n assert(global == NUM_THREADS * NUM_ITERS);\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Compile and run:</p>\n\n<pre><code>gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c -pthread\n./main.out\n./main.out 1\n</code></pre>\n\n<p>The first run works fine, the second fails due to missing synchronization.</p>\n\n<p>There don't seem to be POSIX standardized atomic operations: <a href=\"https://stackoverflow.com/questions/1130018/unix-portable-atomic-operations\">UNIX Portable Atomic Operations</a> </p>\n\n<p>Tested on Ubuntu 18.04. <a href=\"https://github.com/cirosantilli/cpp-cheat/blob/1778918f77bc913915386e602ad29f8505e73073/posix/pthread_mutex.c\" rel=\"noreferrer\">GitHub upstream</a>.</p>\n\n<p><strong>GCC <code>__atomic_*</code> built-ins</strong></p>\n\n<p>For those that don't have C11, you can achieve atomic increments with the <code>__atomic_*</code> GCC extensions.</p>\n\n<p>main.c </p>\n\n<pre><code>#define _XOPEN_SOURCE 700\n#include &lt;pthread.h&gt;\n#include &lt;stdatomic.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nenum Constants {\n NUM_THREADS = 1000,\n};\n\nint atomic_counter;\nint non_atomic_counter;\n\nvoid* mythread(void *arg) {\n (void)arg;\n for (int n = 0; n &lt; 1000; ++n) {\n ++non_atomic_counter;\n __atomic_fetch_add(&amp;atomic_counter, 1, __ATOMIC_SEQ_CST);\n }\n return NULL;\n}\n\nint main(void) {\n int i;\n pthread_t threads[NUM_THREADS];\n for (i = 0; i &lt; NUM_THREADS; ++i)\n pthread_create(&amp;threads[i], NULL, mythread, NULL);\n for (i = 0; i &lt; NUM_THREADS; ++i)\n pthread_join(threads[i], NULL);\n printf(\"atomic %d\\n\", atomic_counter);\n printf(\"non-atomic %d\\n\", non_atomic_counter);\n}\n</code></pre>\n\n<p>Compile and run:</p>\n\n<pre><code>gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c -pthread\n./main.out\n</code></pre>\n\n<p>Output and generated assembly: the same as the \"C11 threads\" example.</p>\n\n<p>Tested in Ubuntu 16.04 amd64, GCC 6.4.0.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
I have used fork() in C to start another process. How do I start a new thread?
Since you mentioned fork() I assume you're on a Unix-like system, in which case [POSIX threads](http://en.wikipedia.org/wiki/POSIX_Threads) (usually referred to as pthreads) are what you want to use. Specifically, pthread\_create() is the function you need to create a new thread. Its arguments are: ``` int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg); ``` The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.
56,812
<p>I'm trying to consume a SharePoint webservice from ColdFusion via cfinvoke ('cause I don't want to deal with (read: parse) the SOAP response itself).</p> <p>The SOAP response includes a byte-order-mark character (BOM), which produces the following exception in CF:</p> <pre><code>"Cannot perform web service invocation GetList. The fault returned when invoking the web service operation is: 'AxisFault faultCode: {http://www.w3.org/2003/05/soap-envelope}Server.userException faultSubcode: faultString: org.xml.sax.SAXParseException: Content is not allowed in prolog." </code></pre> <p>The standard for UTF-8 encoding optionally includes the BOM character (<a href="http://unicode.org/faq/utf_bom.html#29" rel="nofollow noreferrer">http://unicode.org/faq/utf_bom.html#29</a>). Microsoft almost universally includes the BOM character with UTF-8 encoded streams . From what I can tell there’s no way to change that in IIS. The XML parser that JRun (ColdFusion) uses by default doesn’t handle the BOM character for UTF-8 encoded XML streams. So, it appears that the way to fix this is to change the XML parser used by JRun (<a href="http://www.bpurcell.org/blog/index.cfm?mode=entry&amp;entry=942" rel="nofollow noreferrer">http://www.bpurcell.org/blog/index.cfm?mode=entry&amp;entry=942</a>).</p> <p>Adobe says that it doesn't handle the BOM character (see comments from anoynomous and halL on May 2nd and 5th).<br /> <a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments" rel="nofollow noreferrer">http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments</a></p>
[ { "answer_id": 56896, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "<p>It sounds like ColdFusion is using Apache Axis under the covers.</p>\n\n<p>This doesn't apply exactly to your solution, but I've had to deal with this issue once before when consuming a .NET web service with Apache Axis/Java. The only solution I was able to find (since the owner of the web service was unwilling to change anything on his end) was to write a Handler class that Axis would plug into the pipeline which would delete the BOM from the message if it existed. </p>\n\n<p>So perhaps it's possible to configure Axis through ColdFusion? If so <a href=\"http://wiki.apache.org/ws/FrontPage/Axis/AxisClientConfiguration\" rel=\"nofollow noreferrer\">you can add additional Handlers to the message handling flow</a>.</p>\n" }, { "answer_id": 56918, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 3, "selected": true, "text": "<p>I'm going to say that the answer to your question (is it possible?) is no. I don't know that definitively, but the poster who commented just above halL (<a href=\"http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_g-h_09.html#comments\" rel=\"nofollow noreferrer\">in the comments on this page</a>) gave a work-around for the problem -- so I assume it is possible to deal with when parsing manually.</p>\n\n<p>You say that you're using CFInvoke because you don't want to deal with the soap response yourself. It looks like you don't have any choice.</p>\n" }, { "answer_id": 73634, "author": "Dan Cramer", "author_id": 3274, "author_profile": "https://Stackoverflow.com/users/3274", "pm_score": 2, "selected": false, "text": "<p>As Adam Tuttle said already, the workaround is on the page that you linked to</p>\n\n<pre><code>&lt;!--- Remove BOM from the start of the string, if it exists ---&gt;\n&lt;cfif Left(responseText, 1) EQ chr(65279)&gt;\n&lt;cfset responseText = mid(xmlText, 2, len(responseText))&gt;\n&lt;/cfif&gt;\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5849/" ]
I'm trying to consume a SharePoint webservice from ColdFusion via cfinvoke ('cause I don't want to deal with (read: parse) the SOAP response itself). The SOAP response includes a byte-order-mark character (BOM), which produces the following exception in CF: ``` "Cannot perform web service invocation GetList. The fault returned when invoking the web service operation is: 'AxisFault faultCode: {http://www.w3.org/2003/05/soap-envelope}Server.userException faultSubcode: faultString: org.xml.sax.SAXParseException: Content is not allowed in prolog." ``` The standard for UTF-8 encoding optionally includes the BOM character (<http://unicode.org/faq/utf_bom.html#29>). Microsoft almost universally includes the BOM character with UTF-8 encoded streams . From what I can tell there’s no way to change that in IIS. The XML parser that JRun (ColdFusion) uses by default doesn’t handle the BOM character for UTF-8 encoded XML streams. So, it appears that the way to fix this is to change the XML parser used by JRun (<http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942>). Adobe says that it doesn't handle the BOM character (see comments from anoynomous and halL on May 2nd and 5th). <http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments>
I'm going to say that the answer to your question (is it possible?) is no. I don't know that definitively, but the poster who commented just above halL ([in the comments on this page](http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_g-h_09.html#comments)) gave a work-around for the problem -- so I assume it is possible to deal with when parsing manually. You say that you're using CFInvoke because you don't want to deal with the soap response yourself. It looks like you don't have any choice.
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="noreferrer">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html" rel="noreferrer">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html" rel="noreferrer">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
[ { "answer_id": 56832, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": -1, "selected": false, "text": "<p>What about:</p>\n\n<pre><code>round(n,1)+epsilon\n</code></pre>\n" }, { "answer_id": 56833, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 8, "selected": true, "text": "<p>I can't help the way it's stored, but at least formatting works correctly: </p>\n\n<pre><code>'%.1f' % round(n, 1) # Gives you '5.6'\n</code></pre>\n" }, { "answer_id": 56840, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 4, "selected": false, "text": "<p>You can switch the data type to an integer:</p>\n\n<pre><code>&gt;&gt;&gt; n = 5.59\n&gt;&gt;&gt; int(n * 10) / 10.0\n5.5\n&gt;&gt;&gt; int(n * 10 + 0.5)\n56\n</code></pre>\n\n<p>And then display the number by inserting the locale's decimal separator.</p>\n\n<p>However, <a href=\"https://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly#56833\">Jimmy's answer</a> is better.</p>\n" }, { "answer_id": 56841, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "<p>You can use the string format operator <code>%</code>, similar to sprintf.</p>\n\n<pre><code>mystring = \"%.2f\" % 5.5999\n</code></pre>\n" }, { "answer_id": 56844, "author": "Tomi Kyöstilä", "author_id": 616, "author_profile": "https://Stackoverflow.com/users/616", "pm_score": 4, "selected": false, "text": "<p>You get '5.6' if you do <code>str(round(n, 1))</code> instead of just <code>round(n, 1)</code>.</p>\n" }, { "answer_id": 56845, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 3, "selected": false, "text": "<p>Floating point math is vulnerable to slight, but annoying, precision inaccuracies. If you can work with integer or fixed point, you will be guaranteed precision.</p>\n" }, { "answer_id": 56849, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 2, "selected": false, "text": "<p><strong>printf</strong> the sucker.</p>\n\n<pre><code>print '%.1f' % 5.59 # returns 5.6\n</code></pre>\n" }, { "answer_id": 56850, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": false, "text": "<p>Formatting works correctly even without having to round:</p>\n\n<pre><code>\"%.1f\" % n\n</code></pre>\n" }, { "answer_id": 57704, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 5, "selected": false, "text": "<p><code>round(5.59, 1)</code> is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.</p>\n\n<pre><code>&gt;&gt;&gt; 5.6\n5.5999999999999996\n&gt;&gt;&gt; \n</code></pre>\n\n<p>As Vinko says, you can use string formatting to do rounding for display.</p>\n\n<p>Python has a <a href=\"http://docs.python.org/lib/module-decimal.html\" rel=\"noreferrer\">module for decimal arithmetic</a> if you need that.</p>\n" }, { "answer_id": 3225829, "author": "Jesse Dhillon", "author_id": 328501, "author_profile": "https://Stackoverflow.com/users/328501", "pm_score": 3, "selected": false, "text": "<p>Take a look at the <a href=\"http://docs.python.org/library/decimal.html\" rel=\"noreferrer\">Decimal module</a></p>\n\n<blockquote>\n <p>Decimal “is based on a floating-point\n model which was designed with people\n in mind, and necessarily has a\n paramount guiding principle –\n computers must provide an arithmetic\n that works in the same way as the\n arithmetic that people learn at\n school.” – excerpt from the decimal\n arithmetic specification.</p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p>Decimal numbers can be represented\n exactly. In contrast, numbers like 1.1\n and 2.2 do not have an exact\n representations in binary floating\n point. End users typically would not\n expect 1.1 + 2.2 to display as\n 3.3000000000000003 as it does with binary floating point.</p>\n</blockquote>\n\n<p>Decimal provides the kind of operations that make it easy to write apps that require floating point operations and <em>also</em> need to present those results in a human readable format, e.g., accounting.</p>\n" }, { "answer_id": 15398691, "author": "Robert Griesmeyer", "author_id": 2070300, "author_profile": "https://Stackoverflow.com/users/2070300", "pm_score": 5, "selected": false, "text": "<p>If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications:</p>\n<pre><code>from decimal import Decimal, ROUND_UP\n\nDecimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)\n</code></pre>\n<p>This will return a Decimal Number which is 16.20.</p>\n" }, { "answer_id": 17296776, "author": "Alexandre Lymberopoulos", "author_id": 2519948, "author_profile": "https://Stackoverflow.com/users/2519948", "pm_score": 3, "selected": false, "text": "<p>It's a big problem indeed. Try out this code:</p>\n\n<pre><code>print \"%.2f\" % (round((2*4.4+3*5.6+3*4.4)/8,2),)\n</code></pre>\n\n<p>It displays 4.85. Then you do: </p>\n\n<pre><code>print \"Media = %.1f\" % (round((2*4.4+3*5.6+3*4.4)/8,1),)\n</code></pre>\n\n<p>and it shows 4.8. Do you calculations by hand the exact answer is 4.85, but if you try: </p>\n\n<pre><code>print \"Media = %.20f\" % (round((2*4.4+3*5.6+3*4.4)/8,20),)\n</code></pre>\n\n<p>you can see the truth: the float point is stored as the nearest finite sum of fractions whose denominators are powers of two.</p>\n" }, { "answer_id": 33771679, "author": "Станислав Повышев", "author_id": 2491847, "author_profile": "https://Stackoverflow.com/users/2491847", "pm_score": 2, "selected": false, "text": "<p>Works Perfect </p>\n\n<pre><code>format(5.59, '.1f') # to display\nfloat(format(5.59, '.1f')) #to round\n</code></pre>\n" }, { "answer_id": 42443001, "author": "Gildas", "author_id": 5318186, "author_profile": "https://Stackoverflow.com/users/5318186", "pm_score": 2, "selected": false, "text": "<p>I am doing:</p>\n\n<pre><code>int(round( x , 0))\n</code></pre>\n\n<p>In this case, we first round properly at the unit level, then we convert to integer to avoid printing a float.</p>\n\n<p>so </p>\n\n<pre><code>&gt;&gt;&gt; int(round(5.59,0))\n6\n</code></pre>\n\n<p>I think this answer works better than formating the string, and it also makes more sens to me to use the round function.</p>\n" }, { "answer_id": 48918096, "author": "Gregory Pittman", "author_id": 9393856, "author_profile": "https://Stackoverflow.com/users/9393856", "pm_score": 0, "selected": false, "text": "<p>Here's where I see round failing. What if you wanted to round these 2 numbers to one decimal place?\n23.45\n23.55\nMy education was that from rounding these you should get:\n23.4\n23.6\nthe \"rule\" being that you should round up if the preceding number was odd, not round up if the preceding number were even.\nThe round function in python simply truncates the 5.</p>\n" }, { "answer_id": 49164892, "author": "Dondon Jie", "author_id": 7866170, "author_profile": "https://Stackoverflow.com/users/7866170", "pm_score": 1, "selected": false, "text": "<p>Code:</p>\n\n<pre><code>x1 = 5.63\nx2 = 5.65\nprint(float('%.2f' % round(x1,1))) # gives you '5.6'\nprint(float('%.2f' % round(x2,1))) # gives you '5.7'\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>5.6\n5.7\n</code></pre>\n" }, { "answer_id": 49777226, "author": "Syed Is Saqlain", "author_id": 5280048, "author_profile": "https://Stackoverflow.com/users/5280048", "pm_score": 1, "selected": false, "text": "<p>The problem is only when last digit is 5. Eg. 0.045 is internally stored as 0.044999999999999... You could simply increment last digit to 6 and round off. This will give you the desired results.</p>\n\n<pre><code>import re\n\n\ndef custom_round(num, precision=0):\n # Get the type of given number\n type_num = type(num)\n # If the given type is not a valid number type, raise TypeError\n if type_num not in [int, float, Decimal]:\n raise TypeError(\"type {} doesn't define __round__ method\".format(type_num.__name__))\n # If passed number is int, there is no rounding off.\n if type_num == int:\n return num\n # Convert number to string.\n str_num = str(num).lower()\n # We will remove negative context from the number and add it back in the end\n negative_number = False\n if num &lt; 0:\n negative_number = True\n str_num = str_num[1:]\n # If number is in format 1e-12 or 2e+13, we have to convert it to\n # to a string in standard decimal notation.\n if 'e-' in str_num:\n # For 1.23e-7, e_power = 7\n e_power = int(re.findall('e-[0-9]+', str_num)[0][2:])\n # For 1.23e-7, number = 123\n number = ''.join(str_num.split('e-')[0].split('.'))\n zeros = ''\n # Number of zeros = e_power - 1 = 6\n for i in range(e_power - 1):\n zeros = zeros + '0'\n # Scientific notation 1.23e-7 in regular decimal = 0.000000123\n str_num = '0.' + zeros + number\n if 'e+' in str_num:\n # For 1.23e+7, e_power = 7\n e_power = int(re.findall('e\\+[0-9]+', str_num)[0][2:])\n # For 1.23e+7, number_characteristic = 1\n # characteristic is number left of decimal point.\n number_characteristic = str_num.split('e+')[0].split('.')[0]\n # For 1.23e+7, number_mantissa = 23\n # mantissa is number right of decimal point.\n number_mantissa = str_num.split('e+')[0].split('.')[1]\n # For 1.23e+7, number = 123\n number = number_characteristic + number_mantissa\n zeros = ''\n # Eg: for this condition = 1.23e+7\n if e_power &gt;= len(number_mantissa):\n # Number of zeros = e_power - mantissa length = 5\n for i in range(e_power - len(number_mantissa)):\n zeros = zeros + '0'\n # Scientific notation 1.23e+7 in regular decimal = 12300000.0\n str_num = number + zeros + '.0'\n # Eg: for this condition = 1.23e+1\n if e_power &lt; len(number_mantissa):\n # In this case, we only need to shift the decimal e_power digits to the right\n # So we just copy the digits from mantissa to characteristic and then remove\n # them from mantissa.\n for i in range(e_power):\n number_characteristic = number_characteristic + number_mantissa[i]\n number_mantissa = number_mantissa[i:]\n # Scientific notation 1.23e+1 in regular decimal = 12.3\n str_num = number_characteristic + '.' + number_mantissa\n # characteristic is number left of decimal point.\n characteristic_part = str_num.split('.')[0]\n # mantissa is number right of decimal point.\n mantissa_part = str_num.split('.')[1]\n # If number is supposed to be rounded to whole number,\n # check first decimal digit. If more than 5, return\n # characteristic + 1 else return characteristic\n if precision == 0:\n if mantissa_part and int(mantissa_part[0]) &gt;= 5:\n return type_num(int(characteristic_part) + 1)\n return type_num(characteristic_part)\n # Get the precision of the given number.\n num_precision = len(mantissa_part)\n # Rounding off is done only if number precision is\n # greater than requested precision\n if num_precision &lt;= precision:\n return num\n # Replace the last '5' with 6 so that rounding off returns desired results\n if str_num[-1] == '5':\n str_num = re.sub('5$', '6', str_num)\n result = round(type_num(str_num), precision)\n # If the number was negative, add negative context back\n if negative_number:\n result = result * -1\n return result\n</code></pre>\n" }, { "answer_id": 60294994, "author": "Tali Oat", "author_id": 4609659, "author_profile": "https://Stackoverflow.com/users/4609659", "pm_score": 2, "selected": false, "text": "<p>I would avoid relying on <code>round()</code> at all in this case. Consider</p>\n\n<pre><code>print(round(61.295, 2))\nprint(round(1.295, 2))\n</code></pre>\n\n<p>will output</p>\n\n<pre><code>61.3\n1.29\n</code></pre>\n\n<p>which is not a desired output if you need solid rounding to the nearest integer. To bypass this behavior go with <code>math.ceil()</code> (or <code>math.floor()</code> if you want to round down):</p>\n\n<pre><code>from math import ceil\ndecimal_count = 2\nprint(ceil(61.295 * 10 ** decimal_count) / 10 ** decimal_count)\nprint(ceil(1.295 * 10 ** decimal_count) / 10 ** decimal_count)\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code>61.3\n1.3\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 61820474, "author": "conmak", "author_id": 12014156, "author_profile": "https://Stackoverflow.com/users/12014156", "pm_score": 2, "selected": false, "text": "<p>Another potential option is:</p>\n\n<pre><code>def hard_round(number, decimal_places=0):\n \"\"\"\n Function:\n - Rounds a float value to a specified number of decimal places\n - Fixes issues with floating point binary approximation rounding in python\n Requires:\n - `number`:\n - Type: int|float\n - What: The number to round\n Optional:\n - `decimal_places`:\n - Type: int \n - What: The number of decimal places to round to\n - Default: 0\n Example:\n ```\n hard_round(5.6,1)\n ```\n \"\"\"\n return int(number*(10**decimal_places)+0.5)/(10**decimal_places)\n</code></pre>\n" }, { "answer_id": 65786552, "author": "Irfan wani", "author_id": 13789135, "author_profile": "https://Stackoverflow.com/users/13789135", "pm_score": 0, "selected": false, "text": "<p>Here is an easy way to round a float number to any number of decimal places, and it still works in 2021!</p>\n<pre><code>float_number = 12.234325335563\nrounded = round(float_number, 3) # 3 is the number of decimal places to be returned.You can pass any number in place of 3 depending on how many decimal places you want to return.\nprint(rounded)\n</code></pre>\n<p>And this will print;</p>\n<pre><code>12.234\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ]
The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this: ``` n = 5.59 round(n, 1) # 5.6 ``` But, in actuality, good old floating point weirdness creeps in and you get: ``` 5.5999999999999996 ``` For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html). Short of creating my own round library, is there any way around this?
I can't help the way it's stored, but at least formatting works correctly: ``` '%.1f' % round(n, 1) # Gives you '5.6' ```
56,837
<p>My problem is that my XML document contains snippets of XHTML within it and while passing it through an XSLT I would like it to render those snippets without mangling them.</p> <p>I've tried wrapping the snippet in a CDATA but it doesn't work since less than and greater than are translated to &lt; and &gt; as opposed to being echoed directly.</p> <p>What's the XSL required for doing this?</p>
[ { "answer_id": 56858, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 0, "selected": false, "text": "<p>xsl:copy-of</p>\n" }, { "answer_id": 58466, "author": "DaveP", "author_id": 3577, "author_profile": "https://Stackoverflow.com/users/3577", "pm_score": 1, "selected": false, "text": "<p>Assuming your xhtml is in an element YYY\n\n\n\n\n</p>\n\n<p><a href=\"http://www.dpawson.co.uk/xsl/sect2/N1930.html\" rel=\"nofollow noreferrer\">http://www.dpawson.co.uk/xsl/sect2/N1930.html</a> explains options</p>\n" }, { "answer_id": 58471, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;xsl:template match=\"@*|node()\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:copy&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>This is referred to as the \"identity transformation\" in the <a href=\"http://www.w3.org/TR/xslt#copying\" rel=\"noreferrer\">XSLT specification</a>.</p>\n" }, { "answer_id": 13282569, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 2, "selected": false, "text": "<p>I ran in that problem and the copy-of is certainly the easiest to use. The identity works, but that's 5 lines of code and you'd need to call such a template, not just define it as is in your XSLT document (otherwise you probably won't get what you expected in your output.)</p>\n\n<p>My main problem actually was to copy the content of a tag, and not the tag itself. It's actually very easy to resolve but it took me a little time to figure it out (maybe because QtXmlPatterns crashes quite a bit!)</p>\n\n<p>So, the following copies the tag named here and all of its children:</p>\n\n<pre><code>&lt;xsl:copy-of select=\"this/tag/here\"/&gt;\n</code></pre>\n\n<p>But most often you do not want to do that because &lt;here&gt; is actually the container, in other words, it should not appear in the output. In that case you can simply do this:</p>\n\n<pre><code>&lt;xsl:copy-of select=\"this/tag/here/*\"/&gt;\n</code></pre>\n\n<p>This copies all the children found in the tag named &lt;here&gt;.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
My problem is that my XML document contains snippets of XHTML within it and while passing it through an XSLT I would like it to render those snippets without mangling them. I've tried wrapping the snippet in a CDATA but it doesn't work since less than and greater than are translated to < and > as opposed to being echoed directly. What's the XSL required for doing this?
``` <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> ``` This is referred to as the "identity transformation" in the [XSLT specification](http://www.w3.org/TR/xslt#copying).
56,843
<p>I'm looking for a builder for <a href="http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html" rel="noreferrer">HQL</a> in Java. I want to get rid of things like:</p> <pre><code>StringBuilder builder = new StringBuilder() .append("select stock from ") .append( Stock.class.getName() ) .append( " as stock where stock.id = ") .append( id ); </code></pre> <p>I'd rather have something like:</p> <pre><code>HqlBuilder builder = new HqlBuilder() .select( "stock" ) .from( Stock.class.getName() ).as( "stock" ) .where( "stock.id" ).equals( id ); </code></pre> <p>I googled a bit, and I couldn't find one.</p> <p>I wrote a quick &amp; dumb <code>HqlBuilder</code> that suits my needs for now, but I'd love to find one that has more users and tests than me alone.</p> <p>Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:</p> <pre><code>select stock from com.something.Stock as stock, com.something.Bonus as bonus where stock.someValue = bonus.id </code></pre> <p>ie. select all stocks whose property <code>someValue</code> points to <em>any</em> bonus from the Bonus table.</p> <p>Thanks!</p>
[ { "answer_id": 56866, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "<p>Doesn't the <a href=\"http://www.hibernate.org/hib_docs/v3/reference/en/html/querycriteria.html\" rel=\"noreferrer\">Criteria API</a> do it for you? It looks almost exactly like what you're asking for. </p>\n" }, { "answer_id": 56883, "author": "Alex Argo", "author_id": 5885, "author_profile": "https://Stackoverflow.com/users/5885", "pm_score": 2, "selected": false, "text": "<p>It looks like you want to use the Criteria query API built into Hibernate. To do your above query it would look like this:</p>\n\n<pre><code>List&lt;Stock&gt; stocks = session.createCriteria(Stock.class)\n .add(Property.forName(\"id\").eq(id))\n .list();\n</code></pre>\n\n<p>If you don't have access to the Hibernate Session yet, you can used 'DetachedCriteria' like so:</p>\n\n<pre><code>DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class) \n .add(Property.forName(\"id\").eq(id));\n</code></pre>\n\n<p>If you wanted to get all Stock that have a Bonus with a specific ID you could do the following:</p>\n\n<pre><code>DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class)\n .createCriteria(\"Stock\")\n .add(Property.forName(\"id\").eq(id)));\n</code></pre>\n\n<p>For more infromation check out <a href=\"http://www.hibernate.org/hib_docs/reference/en/html/querycriteria.html\" rel=\"nofollow noreferrer\" title=\"Criteria Queries from Hibernate Documentation\">Criteria Queries</a> from the Hibernate docs</p>\n" }, { "answer_id": 56937, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/questions/56843/looking-for-an-hql-builder-hibernate-query-language#56889\">Sébastien Rocca-Serra</a> </p>\n\n<pre><code>select stock\nfrom com.something.Stock as stock, com.something.Bonus as bonus\nwhere stock.bonus.id = bonus.id\n</code></pre>\n\n<p>That's just a join. Hibernate does it automatically, if and only if you've got the mapping between <code>Stock</code> and <code>Bonus</code> setup and if <code>bonus</code> is a property of <code>Stock</code>. <code>Criteria.list()</code> will return <code>Stock</code> objects and you just call <code>stock.getBonus()</code>.</p>\n\n<p>Note, if you want to do anything like</p>\n\n<pre><code>select stock\nfrom com.something.Stock as stock\nwhere stock.bonus.value &gt; 1000000\n</code></pre>\n\n<p>You need to use <a href=\"http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Criteria.html#createAlias(java.lang.String,%20java.lang.String)\" rel=\"nofollow noreferrer\"><code>Criteria.createAlias()</code></a>. It'd be something like</p>\n\n<pre><code>session.createCriteria(Stock.class).createAlias(\"bonus\", \"b\")\n .add(Restrictions.gt(\"b.value\", 1000000)).list()\n</code></pre>\n" }, { "answer_id": 57100, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "<p>@<a href=\"https://stackoverflow.com/questions/56843/looking-for-an-hql-builder-hibernate-query-language#57001\">Sébastien Rocca-Serra</a><br>\nNow we're getting somewhere concrete. The sort of join you're trying to do isn't really possible through the Criteria API, but a sub-query should accomplish the same thing. First you create a <code>DetachedCriteria</code> for the bonus table, then use the <code>IN</code> operator for <code>someValue</code>.</p>\n\n<pre><code>DetachedCriteria bonuses = DetachedCriteria.forClass(Bonus.class);\nList stocks = session.createCriteria(Stock.class)\n .add(Property.forName(\"someValue\").in(bonuses)).list();\n</code></pre>\n\n<p>This is equivalent to</p>\n\n<pre><code>select stock\nfrom com.something.Stock as stock\nwhere stock.someValue in (select bonus.id from com.something.Bonus as bonus)\n</code></pre>\n\n<p>The only downside would be if you have references to different tables in <code>someValue</code> and your ID's are not unique across all tables. But your query would suffer from the same flaw.</p>\n" }, { "answer_id": 57141, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 2, "selected": false, "text": "<p>Criteria API does not provide all functionality avaiable in HQL. For example, you cannot do more than one join over the same column.</p>\n\n<p>Why don't you use <strong><a href=\"http://www.javalobby.org/java/forums/t33053.html\" rel=\"nofollow noreferrer\">NAMED QUERIES</a></strong>? The look much more clean:</p>\n\n<pre><code>Person person = session.getNamedQuery(\"Person.findByName\")\n .setString(0, \"Marcio\")\n .list();\n</code></pre>\n" }, { "answer_id": 586392, "author": "Josh", "author_id": 56887, "author_profile": "https://Stackoverflow.com/users/56887", "pm_score": 2, "selected": false, "text": "<p>I wrote a GPL'd solution for OMERO which you could easily build suited to your situation.</p>\n\n<ul>\n<li>Source: <a href=\"http://trac.openmicroscopy.org.uk/omero/browser/trunk/components/server/src/ome/tools/hibernate/QueryBuilder.java\" rel=\"nofollow noreferrer\">QueryBuilder.java</a></li>\n<li>Test: <a href=\"http://trac.openmicroscopy.org.uk/omero/browser/trunk/components/server/test/ome/server/utests/QueryBuilderMockTest.java\" rel=\"nofollow noreferrer\">QueryBuilderMockTest</a></li>\n</ul>\n\n<p>Usage:</p>\n\n<pre><code>QueryBuilder qb = new QueryBuilder();\nqb.select(\"img\");\nqb.from(\"Image\", \"img\");\nqb.join(\"img.pixels\", \"pix\", true, false);\n\n// Can't join anymore after this\nqb.where(); // First\nqb.append(\"(\");\nqb.and(\"pt.details.creationTime &gt; :time\");\nqb.param(\"time\", new Date());\nqb.append(\")\");\nqb.and(\"img.id in (:ids)\");\nqb.paramList(\"ids\", new HashSet());\nqb.order(\"img.id\", true);\nqb.order(\"this.details.creationEvent.time\", false);\n</code></pre>\n\n<p>It functions as a state machine \"select->from->join->where->order\", etc. and keeps up with optional parameters. There were several queries which the Criteria API could not perform (see <a href=\"http://opensource.atlassian.com/projects/hibernate/browse/HHH-879\" rel=\"nofollow noreferrer\">HHH-879</a>), so in the end it was simpler to write this small class to wrap StringBuilder. (Note: there is a ticket <a href=\"http://opensource.atlassian.com/projects/hibernate/browse/HHH-2407\" rel=\"nofollow noreferrer\">HHH-2407</a> describing a Hibernate branch which should unify the two. After that, it would probably make sense to re-visit the Criteria API)</p>\n" }, { "answer_id": 1835464, "author": "Chuck Deal", "author_id": 121475, "author_profile": "https://Stackoverflow.com/users/121475", "pm_score": 2, "selected": false, "text": "<p>Take a look at the search package available from the <a href=\"http://code.google.com/p/hibernate-generic-dao/\" rel=\"nofollow noreferrer\">hibernate-generic-dao</a> project. This is a pretty decent HQL Builder implementation.</p>\n" }, { "answer_id": 1880122, "author": "Guillaume", "author_id": 228689, "author_profile": "https://Stackoverflow.com/users/228689", "pm_score": 2, "selected": false, "text": "<p>I know this thread is pretty old, but I also was looking for a HqlBuilder And I found this <a href=\"http://forge.abcd.harvard.edu/gf/project/screensaver/scmsvn/?action=browse&amp;path=%2Fbranches%2Ficcbl%2Ftrunk%2Fsrc%2Fedu%2Fharvard%2Fmed%2Fscreensaver%2Fdb%2Fhibernate%2FHqlBuilder.java&amp;view=markup\" rel=\"nofollow noreferrer\">\"screensaver\" project</a> <br/>\nIt is NOT a Windows screensaver, it's a \n\"<em>Lab Information Management System (LIMS) for high-throughput screening (HTS) facilities that perform small molecule and RNAi screens.</em>\"</p>\n\n<p>It contains an HQLBuilder that is looking quite good.\n<br/>Here is a sample list of available methods: </p>\n\n<pre><code>...\nHqlBuilder select(String alias);\nHqlBuilder select(String alias, String property);\nHqlBuilder from(Class&lt;?&gt; entityClass, String alias);\nHqlBuilder fromFetch(String joinAlias, String joinRelationship, String alias);\nHqlBuilder where(String alias, String property, Operator operator, Object value);\nHqlBuilder where(String alias, Operator operator, Object value);\nHqlBuilder where(String alias1, Operator operator, String alias2);\nHqlBuilder whereIn(String alias, String property, Set&lt;?&gt; values);\nHqlBuilder whereIn(String alias, Set&lt;?&gt; values);\nHqlBuilder where(Clause clause);\nHqlBuilder orderBy(String alias, String property);\nHqlBuilder orderBy(String alias, SortDirection sortDirection);\nHqlBuilder orderBy(String alias, String property, SortDirection sortDirection);\nString toHql();\n...\n</code></pre>\n" }, { "answer_id": 2044946, "author": "Timo Westkämper", "author_id": 252552, "author_profile": "https://Stackoverflow.com/users/252552", "pm_score": 3, "selected": false, "text": "<p>For a type-safe approach to your problem, consider <a href=\"http://www.querydsl.com\" rel=\"noreferrer\">Querydsl</a>.</p>\n\n<p>The example query becomes</p>\n\n<pre><code>HQLQuery query = new HibernateQuery(session);\nList&lt;Stock&gt; s = query.from(stock, bonus)\n .where(stock.someValue.eq(bonus.id))\n .list(stock);\n</code></pre>\n\n<p>Querydsl uses APT for code generation like JPA2 and supports JPA/Hibernate, JDO, SQL and Java collections.</p>\n\n<p>I am the maintainer of Querydsl, so this answer is biased.</p>\n" }, { "answer_id": 8372768, "author": "ebelanger", "author_id": 1028380, "author_profile": "https://Stackoverflow.com/users/1028380", "pm_score": 3, "selected": false, "text": "<p>For another type-safe query dsl, I recommend <a href=\"http://www.torpedoquery.org\">http://www.torpedoquery.org</a>. The library is still young but it provides type safety by directly using your entity's classes. This means early compiler errors when the query no longer applies before of refactoring or redesign.</p>\n\n<p>I also provided you with an example. I think from your posts that you where trying to do a subquery restriction, so I based the exemple on that:</p>\n\n<pre><code>import static org.torpedoquery.jpa.Torpedo.*;\n\nBonus bonus = from(Bonus.class);\nQuery subQuery = select(bonus.getId());\n\nStock stock = from(Stock.class);\nwhere(stock.getSomeValue()).in(subQuery);\n\nList&lt;Stock&gt; stocks = select(stock).list(entityManager);\n</code></pre>\n" }, { "answer_id": 17545743, "author": "tglman", "author_id": 810633, "author_profile": "https://Stackoverflow.com/users/810633", "pm_score": 1, "selected": false, "text": "<p>Now are also available the standard <a href=\"http://www.ibm.com/developerworks/library/j-typesafejpa/\" rel=\"nofollow\">JPA Type Safe</a> query and an less standard but also good <a href=\"https://www.objectquery.org/\" rel=\"nofollow\">Object Query</a></p>\n\n<p>Examples:</p>\n\n<p>JPA Type Safe</p>\n\n<pre><code>EntityManager em = ...\nCriteriaBuilder qb = em.getCriteriaBuilder();\nCriteriaQuery&lt;Stock&gt; c = qb.createQuery(Stock.class);\nRoot&lt;Stock&gt; = c.from(Stock.class);\nPredicate condition = qb.eq(p.get(Stock_.id), id);\nc.where(condition);\nTypedQuery&lt;Stock&gt; q = em.createQuery(c); \nList&lt;Stock&gt; result = q.getResultList();\n</code></pre>\n\n<p>Object Query</p>\n\n<pre><code>EntityManager em = ...\nObjectQuery&lt;Stock&gt; query = new GenericObjectQuery&lt;Stock&gt;(Stock.class);\nStock toSearch = query.target();\nquery.eq(toSearch.getId(),id);\nList&lt;Stock&gt; res = (List&lt;Stock&gt;)JPAObjectQuery.execute(query, em);\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2797/" ]
I'm looking for a builder for [HQL](http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html) in Java. I want to get rid of things like: ``` StringBuilder builder = new StringBuilder() .append("select stock from ") .append( Stock.class.getName() ) .append( " as stock where stock.id = ") .append( id ); ``` I'd rather have something like: ``` HqlBuilder builder = new HqlBuilder() .select( "stock" ) .from( Stock.class.getName() ).as( "stock" ) .where( "stock.id" ).equals( id ); ``` I googled a bit, and I couldn't find one. I wrote a quick & dumb `HqlBuilder` that suits my needs for now, but I'd love to find one that has more users and tests than me alone. Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API: ``` select stock from com.something.Stock as stock, com.something.Bonus as bonus where stock.someValue = bonus.id ``` ie. select all stocks whose property `someValue` points to *any* bonus from the Bonus table. Thanks!
@[Sébastien Rocca-Serra](https://stackoverflow.com/questions/56843/looking-for-an-hql-builder-hibernate-query-language#57001) Now we're getting somewhere concrete. The sort of join you're trying to do isn't really possible through the Criteria API, but a sub-query should accomplish the same thing. First you create a `DetachedCriteria` for the bonus table, then use the `IN` operator for `someValue`. ``` DetachedCriteria bonuses = DetachedCriteria.forClass(Bonus.class); List stocks = session.createCriteria(Stock.class) .add(Property.forName("someValue").in(bonuses)).list(); ``` This is equivalent to ``` select stock from com.something.Stock as stock where stock.someValue in (select bonus.id from com.something.Bonus as bonus) ``` The only downside would be if you have references to different tables in `someValue` and your ID's are not unique across all tables. But your query would suffer from the same flaw.
56,865
<p>A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?</p> <p>I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like. </p> <p>(Any sample web service can be chosen as an example.)</p>
[ { "answer_id": 57090, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<pre><code>import org.restlet.Client;\nimport org.restlet.data.Protocol;\nimport org.restlet.data.Reference;\nimport org.restlet.data.Response;\nimport org.restlet.resource.DomRepresentation;\nimport org.w3c.dom.Node;\n\n/**\n * Uses YAHOO!'s RESTful web service with XML.\n */\npublic class YahooSearch {\n private static final String BASE_URI = \"http://api.search.yahoo.com/WebSearchService/V1/webSearch\";\n\n public static void main(final String[] args) {\n if (1 != args.length) {\n System.err.println(\"You need to pass a search term!\");\n } else {\n final String term = Reference.encode(args[0]);\n final String uri = BASE_URI + \"?appid=restbook&amp;query=\" + term;\n final Response response = new Client(Protocol.HTTP).get(uri);\n final DomRepresentation document = response.getEntityAsDom();\n\n document.setNamespaceAware(true);\n document.putNamespace(\"y\", \"urn:yahoo:srch\");\n\n final String expr = \"/y:ResultSet/y:Result/y:Title/text()\";\n for (final Node node : document.getNodes(expr)) {\n System.out.println(node.getTextContent());\n }\n }\n }\n}\n</code></pre>\n\n<p>This code uses <a href=\"http://www.restlet.org/\" rel=\"nofollow noreferrer\">Restlet</a> to make a request to Yahoo's RESTful search service. Obviously, the details of the web service you are using will dictate what your client for it looks like.</p>\n" }, { "answer_id": 57163, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>final Response response = new Client(Protocol.HTTP).get(uri);\n</code></pre>\n\n<p>So, if I understand this correctly, the above line is where the actual call to the web service is being made, with the response being converted to an appropriate format and manipulated after this line.</p>\n\n<p>Assuming I were not using Restlet, how would this line differ?<br>\n<em>(Of course, the actual processing code would be significantly different as well, so that's a given.)</em></p>\n" }, { "answer_id": 58591, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": true, "text": "<p>There's roughly a gajillion HTTP client libraries (Restlet is quite a bit more than that, but I already had that code snippet for something else), but they should all provide support for sending GET requests. Here's a rather less featureful snippet that uses <a href=\"http://hc.apache.org/httpclient-3.x/tutorial.html\" rel=\"nofollow noreferrer\">HttpClient</a> from Apache Commons:</p>\n\n<pre><code>HttpClient client = new HttpClient();\nHttpMethod method = new GetMethod(\"http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=restbook&amp;query=HttpClient\");\nclient.executeMethod(method);\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results? I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like. (Any sample web service can be chosen as an example.)
There's roughly a gajillion HTTP client libraries (Restlet is quite a bit more than that, but I already had that code snippet for something else), but they should all provide support for sending GET requests. Here's a rather less featureful snippet that uses [HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.html) from Apache Commons: ``` HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=restbook&query=HttpClient"); client.executeMethod(method); ```
56,867
<p>When should I use an interface and when should I use a base class? </p> <p>Should it always be an interface if I don't want to actually define a base implementation of the methods?</p> <p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.</p>
[ { "answer_id": 56871, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 7, "selected": false, "text": "<p>Modern style is to define IPet <em>and</em> PetBase.</p>\n\n<p>The advantage of the interface is that other code can use it without any ties whatsoever to other executable code. Completely \"clean.\" Also interfaces can be mixed.</p>\n\n<p>But base classes are useful for simple implementations and common utilities. So provide an abstract base class as well to save time and code.</p>\n" }, { "answer_id": 56873, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 6, "selected": false, "text": "<p>In general, you should favor interfaces over abstract classes. One reason to use an abstract class is if you have common implementation among concrete classes. Of course, you should still declare an interface (IPet) and have an abstract class (PetBase) implement that interface.Using small, distinct interfaces, you can use multiples to further improve flexibility. Interfaces allow the maximum amount of flexibility and portability of types across boundaries. When passing references across boundaries, always pass the interface and not the concrete type. This allows the receiving end to determine concrete implementation and provides maximum flexibility. This is absolutely true when programming in a TDD/BDD fashion.</p>\n\n<p>The Gang of Four stated in their book \"Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation\". I believe this to be true.</p>\n" }, { "answer_id": 56878, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>One important difference is that you can only inherit <strong>one</strong> base class, but you can implement <strong>many</strong> interfaces. So you only want to use a base class if you are <em>absolutely certain</em> that you won't need to also inherit a different base class. Additionally, if you find your interface is getting large then you should start looking to break it up into a few logical pieces that define independent functionality, since there's no rule that your class can't implement them all (or that you can define a different interface that just inherits them all to group them).</p>\n" }, { "answer_id": 56887, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 2, "selected": false, "text": "<p>It depends on your requirements. If IPet is simple enough, I would prefer to implement that. Otherwise, if PetBase implements a ton of functionality you don't want to duplicate, then have at it.</p>\n\n<p>The downside to implementing a base class is the requirement to <code>override</code> (or <code>new</code>) existing methods. This makes them virtual methods which means you have to be careful about how you use the object instance.</p>\n\n<p>Lastly, the single inheritance of .NET kills me. A naive example: Say you're making a user control, so you inherit <code>UserControl</code>. But, now you're locked out of also inheriting <code>PetBase</code>. This forces you to reorganize, such as to make a <code>PetBase</code> class member, instead.</p>\n" }, { "answer_id": 56893, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>I usually don't implement either until I need one. I favor interfaces over abstract classes because that gives a little more flexibility. If there's common behavior in some of the inheriting classes I move that up and make an abstract base class. I don't see the need for both, since they essentially server the same purpose, and having both is a bad code smell (imho) that the solution has been over-engineered.</p>\n" }, { "answer_id": 56894, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 7, "selected": false, "text": "<p>Well, Josh Bloch said himself in <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321356683\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java 2d</a>:</p>\n\n<h2>Prefer interfaces over abstract classes</h2>\n\n<p>Some main points:</p>\n\n<blockquote>\n <ul>\n <li><p><strong>Existing classes can be easily retrofitted to implement a new\n interface</strong>. All you have to do is add\n the required methods if they don’t yet\n exist and add an implements clause to\n the class declaration. </p></li>\n <li><p><strong>Interfaces are ideal for defining mixins</strong>. Loosely speaking, a\n mixin is a type that a class can\n implement in addition to its “primary\n type” to declare that it provides\n some optional behavior. For example,\n Comparable is a mixin interface that\n allows a class to declare that its\n instances are ordered with respect to\n other mutually comparable objects.</p></li>\n <li><p><strong>Interfaces allow the construction of nonhierarchical type\n frameworks</strong>. Type hierarchies are\n great for organizing some things, but\n other things don’t fall neatly into a\n rigid hierarchy. </p></li>\n <li><p><strong>Interfaces enable safe, powerful functionality enhancements</strong> via the\n wrap- per class idiom. If you use\n abstract classes to define types, you\n leave the programmer who wants to add\n functionality with no alternative but\n to use inheritance. </p></li>\n </ul>\n \n <p>Moreover, you can combine the virtues\n of interfaces and abstract classes by\n providing an abstract skeletal\n implementation class to go with each\n nontrivial interface that you export.</p>\n</blockquote>\n\n<p>On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.</p>\n\n<p>PS.: Buy the book. It's a lot more detailed.</p>\n" }, { "answer_id": 56901, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 0, "selected": false, "text": "<p>In addition to those comments that mention the IPet/PetBase implementation, there are also cases where providing an accessor helper class can be very valuable.</p>\n\n<p>The IPet/PetBase style assumes that you have multiple implementations thus increasing the value of PetBase since it simplifies implementation. However, if you have the reverse or a blend of the two where you have multiple clients, providing a class help assist in the usage of the interface can reduce cost by making it easier to use an interface.</p>\n" }, { "answer_id": 56902, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 3, "selected": false, "text": "<p>Interfaces should be small. Really small. If you're really breaking down your objects, then your interfaces will probably only contain a few very specific methods and properties.</p>\n\n<p>Abstract classes are shortcuts. Are there things that all derivatives of PetBase share that you can code once and be done with? If yes, then it's time for an abstract class.</p>\n\n<p>Abstract classes are also limiting. While they give you a great shortcut to producing child objects, any given object can only implement one abstract class. Many times, I find this a limitation of Abstract classes, and this is why I use lots of interfaces.</p>\n\n<p>Abstract classes may contain several interfaces. Your PetBase abstract class may implement IPet (pets have owners) and IDigestion (pets eat, or at least they should). However, PetBase will probably not implement IMammal, since not all pets are mammals and not all mammals are pets. You may add a MammalPetBase that extends PetBase and add IMammal. FishBase could have PetBase and add IFish. IFish would have ISwim and IUnderwaterBreather as interfaces.</p>\n\n<p>Yes, my example is extensively over-complicated for the simple example, but that's part of the great thing about how interfaces and abstract classes work together.</p>\n" }, { "answer_id": 56912, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 10, "selected": true, "text": "<p>\nLet's take your example of a Dog and a Cat class, and let's illustrate using C#:</p>\n\n<p>Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public abstract class Mammal\n</code></pre>\n\n<p>This base class will probably have default methods such as:</p>\n\n<ul>\n<li>Feed</li>\n<li>Mate</li>\n</ul>\n\n<p>All of which are behavior that have more or less the same implementation between either species. To define this you will have:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Dog : Mammal\npublic class Cat : Mammal\n</code></pre>\n\n<p>Now let's suppose there are other mammals, which we will usually see in a zoo:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Giraffe : Mammal\npublic class Rhinoceros : Mammal\npublic class Hippopotamus : Mammal\n</code></pre>\n\n<p>This will still be valid because at the core of the functionality <code>Feed()</code> and <code>Mate()</code> will still be the same.</p>\n\n<p>However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public interface IPettable\n{\n IList&lt;Trick&gt; Tricks{get; set;}\n void Bathe();\n void Train(Trick t);\n}\n</code></pre>\n\n<p>The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea. </p>\n\n<p>Your Dog and Cat definitions should now look like:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Dog : Mammal, IPettable\npublic class Cat : Mammal, IPettable\n</code></pre>\n\n<p>Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.</p>\n\n<p>Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly <em>as required</em> basis.</p>\n" }, { "answer_id": 56961, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": false, "text": "<h2>Interfaces</h2>\n<ul>\n<li>Most languages allow you to implement multiple interfaces</li>\n<li>Modifying an interface is a breaking change. All implementations need to be recompiled/modified.</li>\n<li>All members are public. Implementations have to implement all members.</li>\n<li>Interfaces help in Decoupling. You can use mock frameworks to mock out anything behind an interface</li>\n<li>Interfaces normally indicate a kind of behavior</li>\n<li>Interface implementations are decoupled / isolated from each other</li>\n</ul>\n<h2>Base classes</h2>\n<ul>\n<li>Allows you to add some <strong>default</strong> implementation that you get for free by derivation (From C# 8.0 by interface you can have default implementation)</li>\n<li>Except C++, you can only derive from one class. Even if could from multiple classes, it is usually a bad idea.</li>\n<li>Changing the base class is relatively easy. Derivations do not need to do anything special</li>\n<li>Base classes can declare protected and public functions that can be accessed by derivations</li>\n<li>Abstract Base classes can't be mocked easily like interfaces</li>\n<li>Base classes normally indicate type hierarchy (IS A)</li>\n<li>Class derivations may come to depend on some base behavior (have intricate knowledge of parent implementation). Things can be messy if you make a change to the base implementation for one guy and break the others.</li>\n</ul>\n" }, { "answer_id": 57027, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 6, "selected": false, "text": "<p>This is pretty .NET specific, but the Framework Design Guidelines book argues that in general classes give more flexibility in an evolving framework. Once an interface is shipped, you don't get the chance to change it without breaking code that used that interface. With a class however, you can modify it and not break code that links to it. As long you make the right modifications, which includes adding new functionality, you will be able to extend and evolve your code.</p>\n\n<p>Krzysztof Cwalina says on page 81:</p>\n\n<blockquote>\n <p>Over the course of the three versions of the .NET Framework, I have talked about this guideline with quite a few developers on our team. Many of them, including those who initially disagreed with the guidelines, have said that they regret having shipped some API as an interface. I have not heard of even one case in which somebody regretted that they shipped a class.</p>\n</blockquote>\n\n<p>That being said there certainly is a place for interfaces. As a general guideline always provide an abstract base class implementation of an interface if for nothing else as an example of a way to implement the interface. In the best case that base class will save a lot of work.</p>\n" }, { "answer_id": 57271, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 1, "selected": false, "text": "<p>An inheritor of a base class should have an \"is a\" relationship. Interface represents An \"implements a\" relationship.\nSo only use a base class when your inheritors will maintain the is a relationship.</p>\n" }, { "answer_id": 57316, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 0, "selected": false, "text": "<p>Use your own judgement and be smart. Don't always do what others (like me) are saying. You will hear \"prefer interfaces to abstract classes\" but it really depends. It depends what the class is.</p>\n\n<p>In the above mentioned case where we have a hierarchy of objects, interface is a good idea. Interface helps to work with collections of these objects and it also helps when implementing a service working with any object of the hierarchy. You just define a contract for working with objects from the hierarchy.</p>\n\n<p>On the other hand when you implement a bunch of services that share a common functionality you can either separate the common functionality into a complete separate class or you can move it up into a common base class and make it abstract so that nobody can instantiate the base class.</p>\n\n<p>Also consider this how to support your abstractions over time. Interfaces are fixed: You release an interface as a contract for a set of functionality that any type can implement. Base classes can be extended over time. Those extensions become part of every derived class.</p>\n" }, { "answer_id": 57349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I recommend using composition instead of inheritence whenever possible. Use interfaces but use member objects for base implementation. That way, you can define a factory that constructs your objects to behave in a certain way. If you want to change the behavior then you make a new factory method (or abstract factory) that creates different types of sub-objects.</p>\n\n<p>In some cases, you may find that your primary objects don't need interfaces at all, if all of the mutable behavior is defined in helper objects.</p>\n\n<p>So instead of IPet or PetBase, you might end up with a Pet which has an IFurBehavior parameter. The IFurBehavior parameter is set by the CreateDog() method of the PetFactory. It is this parameter which is called for the shed() method.</p>\n\n<p>If you do this you'll find your code is much more flexible and most of your simple objects deal with very basic system-wide behaviors.</p>\n\n<p>I recommend this pattern even in multiple-inheritence languages.</p>\n" }, { "answer_id": 57457, "author": "Mark", "author_id": 5904, "author_profile": "https://Stackoverflow.com/users/5904", "pm_score": 0, "selected": false, "text": "<p>Interfaces have the distinct advantage of being somewhat \"hot swappable\" for classes. Changing a class from one parent to another will often result in a great deal of work, but Interfaces can often be removed and changed without a great deal of effect on the implementation class. This is especially useful in cases where you have several narrow sets of behaviour that you \"may\" want a class to implement.</p>\n\n<p>This works especially well in my field: game programming. Base classes can get bloated with tons of behaviours that \"may\" be needed by inherited objects. With interfaces different behaviours can be added or removed to objects easily and readily. For example, if I create an interface for \"IDamageEffects\" for objects that I want to reflect damage, then I can easily apply that to various game objects, and easily change my mind later. Say I design an initial class that I want to use for \"static\" decorative objects and I initially decide they are non-destructible. Later on, I may decide it would be more fun if they could blow up so I alter the class to implement the \"IDamageEffects\" interface. This is much easier to do than switching base classes or creating a new object hierarchy.</p>\n" }, { "answer_id": 57464, "author": "Keithius", "author_id": 5956, "author_profile": "https://Stackoverflow.com/users/5956", "pm_score": 0, "selected": false, "text": "<p>There are other advantages to inheritance as well - such as the ability for a variable to be able to hold an object of either the parent class or the inherited class (without having to declare it as something generic, like \"Object\"). </p>\n\n<p>For example, in .NET WinForms, most UI components derive from System.Windows.Forms.Control, so a variable declared as that could \"hold\" just about any UI element - be it a button, a ListView, or what have you. Now, granted, you won't have access to all the properties or methods of the item, but you'll have all the basic stuff - and that can be useful.</p>\n" }, { "answer_id": 57714, "author": "Flory", "author_id": 5551, "author_profile": "https://Stackoverflow.com/users/5551", "pm_score": 4, "selected": false, "text": "<p>Juan,</p>\n\n<p>I like to think of interfaces as a way to characterize a class. A particular dog breed class, say a YorkshireTerrier, may be a descended of the parent dog class, but it is also implements IFurry, IStubby, and IYippieDog. So the class defines what the class is but the interface tells us things about it.</p>\n\n<p>The advantage of this is it allows me to, for example, gather all the IYippieDog's and throw them into my Ocean collection. So now I can reach across a particular set of objects and find ones that meet the criteria I am looking at without inspecting the class too closely.</p>\n\n<p>I find that interfaces really should define a sub-set of the public behavior of a class. If it defines all the public behavior for all the classes that implement then it usually does not need to exist. They do not tell me anything useful.</p>\n\n<p>This thought though goes counter to the idea that every class should have an interface and you should code to the interface. That's fine, but you end up with a lot of one to one interfaces to classes and it makes things confusing. I understand that the idea is it does not really cost anything to do and now you can swap things in and out with ease. However, I find that I rarely do that. Most of the time I am just modifying the existing class in place and have the exact same issues I always did if the public interface of that class needs changing, except I now have to change it in two places.</p>\n\n<p>So if you think like me you would definitely say that Cat and Dog are IPettable. It is a characterization that matches them both.</p>\n\n<p>The other piece of this though is should they have the same base class? The question is do they need to be broadly treated as the same thing. Certainly they are both Animals, but does that fit how we are going to use them together. </p>\n\n<p>Say I want to gather all Animal classes and put them in my Ark container.</p>\n\n<p>Or do they need to be Mammals? Perhaps we need some kind of cross animal milking factory?</p>\n\n<p>Do they even need to be linked together at all? Is it enough to just know they are both IPettable?</p>\n\n<p>I often feel the desire to derive a whole class hierarchy when I really just need one class. I do it in anticipation someday I might need it and usually I never do. Even when I do, I usually find I have to do a lot to fix it. That’s because the first class I am creating is not the Dog, I am not that lucky, it is instead the Platypus. Now my entire class hierarchy is based on the bizarre case and I have a lot of wasted code. </p>\n\n<p>You might also find at some point that not all Cats are IPettable (like that hairless one). Now you can move that Interface to all the derivative classes that fit. You will find that a much less breaking change that all of a sudden Cats are no longer derived from PettableBase.</p>\n" }, { "answer_id": 57763, "author": "Scott Lawrence", "author_id": 3475, "author_profile": "https://Stackoverflow.com/users/3475", "pm_score": 2, "selected": false, "text": "<p>Previous comments about using abstract classes for common implementation is definitely on the mark. One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing. Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).</p>\n" }, { "answer_id": 59999, "author": "theschmitzer", "author_id": 2167252, "author_profile": "https://Stackoverflow.com/users/2167252", "pm_score": 2, "selected": false, "text": "<p>Don't use a base class unless you know what it means, and that it applies in this case. If it applies, use it, otherwise, use interfaces. But note the answer about small interfaces.</p>\n\n<p>Public Inheritance is overused in OOD and expresses a lot more than most developers realize or are willing to live up to. See the <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov Substitutablity Principle</a></p>\n\n<p>In short, if A \"is a\" B then A requires no more than B and delivers no less than B, for every method it exposes.</p>\n" }, { "answer_id": 60013, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>You should use a base class if there really isn't any reason for other developers to desire using their own base class in addition to your type's members <strong>and</strong> you foresee versioning issues (see <a href=\"http://haacked.com/archive/2008/02/21/versioning-issues-with-abstract-base-classes-and-interfaces.aspx\" rel=\"nofollow noreferrer\">http://haacked.com/archive/2008/02/21/versioning-issues-with-abstract-base-classes-and-interfaces.aspx</a>).</p>\n\n<p>If inheriting developers have any reason to use their own base class to implement your type's interface and you don't see the interface changing, then go with an interface. In this case, you can still throw in a default base class that implements the interface for sake of convenience.</p>\n" }, { "answer_id": 65660, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 4, "selected": false, "text": "<p>Also keep in mind not to get swept away in OO (<a href=\"http://www.indiangeek.net/2006/10/25/do-not-start-with-an-interface\" rel=\"noreferrer\">see blog</a>) and always model objects based on behavior required, if you were designing an app where the only behavior you required was a generic name and species for an animal then you would only need one class Animal with a property for the name, instead of millions of classes for every possible animal in the world.</p>\n" }, { "answer_id": 65939, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 7, "selected": false, "text": "<p>Interfaces and base classes represent two different forms of relationships.</p>\n\n<p><strong>Inheritance</strong> (base classes) represent an \"is-a\" relationship. E.g. a dog or a cat \"is-a\" pet. This relationship always represents the (single) <strong>purpose</strong> of the class (in conjunction with the <a href=\"http://codebetter.com/blogs/glenn.block/archive/2008/09/11/the-alt-net-criterion.aspx\" rel=\"noreferrer\" title=\"References of the most important principles of software engineering\">\"single responsibility principle\"</a>).</p>\n\n<p><strong>Interfaces</strong>, on the other hand, represent <strong>additional features</strong> of a class. I'd call it an \"is\" relationship, like in \"<code>Foo</code> is disposable\", hence the <code>IDisposable</code> interface in C#.</p>\n" }, { "answer_id": 67653, "author": "Wheat", "author_id": 70142, "author_profile": "https://Stackoverflow.com/users/70142", "pm_score": 2, "selected": false, "text": "<p>Conceptually, an <em>interface</em> is used to formally and semi-formally define a set of methods that an object will provide. Formally means a set of method names and signatures, and semi-formally means human readable documentation associated with those methods.</p>\n\n<p>Interfaces are only descriptions of an API (after all, <a href=\"https://en.wikipedia.org/wiki/Application_programming_interface\" rel=\"nofollow noreferrer\">API</a> stands for application programming <strong>interface</strong>), they can't contain any implementation, and it's not possible to use or run an interface. They only make explicit the contract of how you should interact with an object.</p>\n\n<p>Classes provide an implementation, and they can declare that they implement zero, one or more Interfaces. If a <em>class</em> is intended to be inherited, the convention is to prefix the class name with \"Base\".</p>\n\n<p>There is a distinction between a <em>base class</em> and an <em>abstract base classes</em> (ABC). ABCs mix interface and implementation together. Abstract outside of computer programming means \"summary\", that is \"abstract == interface\". An <em>abstract base class</em> can then describe both an interface, as well as an empty, partial or complete implementation that is intended to be inherited.</p>\n\n<p>Opinions on when to use <em>interfaces</em> versus <em>abstract base classes</em> versus just <em>classes</em> is going to vary wildly based on both what you are developing, and which language you are developing in. Interfaces are often associated only with statically typed languages such as Java or C#, but dynamically typed languages can also have <em>interfaces</em> and <em>abstract base classes</em>. In Python for example, the distinction is made clear between a Class, which declares that it <strong>implements</strong> an <em>interface</em>, and an object, which is an instance of a <em>class</em>, and is said to <strong>provide</strong> that <em>interface</em>. It's possible in a dynamic language that two objects that are both instances of the same <em>class</em>, can declare that they provide completely <strong>different</strong> interfaces. In Python this is only possible for object attributes, while methods are shared state between all objects of a <em>class</em>. However, in Ruby, objects can have per-instance methods, so it's possible that the <em>interface</em> between two objects of the same <em>class</em> can vary as much as the programmer desires (however, Ruby doesn't have any explicit way of declaring Interfaces).</p>\n\n<p>In dynamic languages the interface to an object is often implicitly assumed, either by introspecting an object and asking it what methods it provides (<em>look before you leap</em>) or preferably by simply attempting to use the desired <em>interface</em> on an object and catching exceptions if the object doesn't provide that <em>interface</em> (<em>easier to ask forgiveness than permission</em>). This can lead to \"false positives\" where two <em>interfaces</em> have the same method name, but are semantically different. However, the trade-off is that your code is more flexible since you don't need to over specify up-front to anticipate all possible uses of your code.</p>\n" }, { "answer_id": 203853, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 4, "selected": false, "text": "<p>Here is the basic and simple definiton of interface and base class:</p>\n\n<ul>\n<li>Base class = object inheritance.</li>\n<li>Interface = functional inheritance.</li>\n</ul>\n\n<p>cheers</p>\n" }, { "answer_id": 210208, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 4, "selected": false, "text": "<p>It is explained well in this <a href=\"http://www.javaworld.com/javaworld/javaqa/2001-04/03-qa-0420-abstract.html\" rel=\"nofollow noreferrer\">Java World article</a>.</p>\n\n<p>Personally, I tend to use interfaces to define interfaces - i.e. parts of the system design that specify how something should be accessed.</p>\n\n<p>It's not uncommon that I will have a class implementing one or more interfaces.</p>\n\n<p>Abstract classes I use as a basis for something else.</p>\n\n<p>The following is an extract from the above mentioned article <a href=\"http://www.javaworld.com/javaworld/javaqa/2001-04/03-qa-0420-abstract.html\" rel=\"nofollow noreferrer\">JavaWorld.com article, author Tony Sintes, 04/20/01</a></p>\n\n<hr/>\n\n<blockquote>\n <h2>Interface vs. abstract class</h2>\n \n <p>Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.</p>\n \n <p>Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.</p>\n \n <p>Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.</p>\n \n <h2>Class vs. interface</h2>\n</blockquote>\n\n<p>Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.</p>\n\n<blockquote>\n <p>For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.</p>\n \n <p>With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.</p>\n \n <p>This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.</p>\n</blockquote>\n" }, { "answer_id": 260213, "author": "Parappa", "author_id": 9974, "author_profile": "https://Stackoverflow.com/users/9974", "pm_score": 2, "selected": false, "text": "<p>Another option to keep in mind is using the \"has-a\" relationship, aka \"is implemented in terms of\" or \"composition.\" Sometimes this is a cleaner, more flexible way to structure things than using \"is-a\" inheritance.</p>\n\n<p>It may not make as much sense logically to say that Dog and Cat both \"have\" a Pet, but it avoids common multiple inheritance pitfalls:</p>\n\n<pre><code>public class Pet\n{\n void Bathe();\n void Train(Trick t);\n}\n\npublic class Dog\n{\n private Pet pet;\n\n public void Bathe() { pet.Bathe(); }\n public void Train(Trick t) { pet.Train(t); }\n}\n\npublic class Cat\n{\n private Pet pet;\n\n public void Bathe() { pet.Bathe(); }\n public void Train(Trick t) { pet.Train(t); }\n}\n</code></pre>\n\n<p>Yes, this example shows that there is a lot of code duplication and lack of elegance involved in doing things this way. But one should also appreciate that this helps to keep Dog and Cat decoupled from the Pet class (in that Dog and Cat do not have access to the private members of Pet), and it leaves room for Dog and Cat to inherit from something else--possibly the Mammal class.</p>\n\n<p>Composition is preferable when no private access is required and you don't need to refer to Dog and Cat using generic Pet references/pointers. Interfaces give you that generic reference capability and can help cut down on the verbosity of your code, but they can also obfuscate things when they are poorly organized. Inheritance is useful when you need private member access, and in using it you are committing yourself to highly coupling your Dog and Cat classes to your Pet class, which is a steep cost to pay.</p>\n\n<p>Between inheritance, composition, and interfaces there is no one way that is always right, and it helps to consider how all three options can be used in harmony. Of the three, inheritance is typically the option that should be used the least often.</p>\n" }, { "answer_id": 300019, "author": "YeahStu", "author_id": 1300, "author_profile": "https://Stackoverflow.com/users/1300", "pm_score": 3, "selected": false, "text": "<p>The case for Base Classes over Interfaces was explained well in the Submain .NET Coding Guidelines:</p>\n\n<blockquote>\n <p><strong>Base Classes vs. Interfaces</strong> \n An interface type is a partial\n description of a value, potentially\n supported by many object types. Use\n base classes instead of interfaces\n whenever possible. From a versioning\n perspective, classes are more flexible\n than interfaces. With a class, you can\n ship Version 1.0 and then in Version\n 2.0 add a new method to the class. As long as the method is not abstract,\n any existing derived classes continue\n to function unchanged.</p>\n \n <p>Because interfaces do not support\n implementation inheritance, the\n pattern that applies to classes does\n not apply to interfaces. Adding a\n method to an interface is equivalent\n to adding an abstract method to a base\n class; any class that implements the\n interface will break because the class\n does not implement the new method.\n Interfaces are appropriate in the\n following situations:</p>\n \n <ol>\n <li>Several unrelated classes want to support the protocol.</li>\n <li>These classes already have established base classes (for\n example,\n some are user interface (UI) controls,\n and some are XML Web services).</li>\n <li>Aggregation is not appropriate or practicable. In all other\n situations,\n class inheritance is a better model.</li>\n </ol>\n</blockquote>\n" }, { "answer_id": 361188, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>When I first started learning about object-oriented programming, I made the easy and probably common mistake of using inheritance to share common behavior - even where that behavior was not essential to the nature of the object.</p>\n\n<p>To further build on an example much used in this particular question, there are <em>lots</em> of things that are petable - girlfriends, cars, fuzzy blankets... - so I might have had a Petable class that provided this common behavior, and various classes inheriting from it.</p>\n\n<p>However, being petable is not part of the nature of any of these objects. There are vastly more important concepts that <em>are</em> essential to their nature - the girlfriend is a person, the car is a land vehicle, the cat is a mammal...</p>\n\n<p>Behaviors should be assigned first to interfaces (including the default interface of the class), and promoted to a base class only if they are (a) common to a large group of classes that are subsets of a larger class - in the same sense that \"cat\" and \"person\" are subsets of \"mammal\".</p>\n\n<p>The catch is, after you understand object-oriented design sufficiently better than I did at first, you'll normally do this automatically without even thinking about it. So the bare truth of the statement \"code to an interface, not an abstract class\" becomes so obvious you have a hard time believing anyone would bother to say it - and start trying to read other meanings into it.</p>\n\n<p>Another thing I'd add is that if a class is <em>purely</em> abstract - with no non-abstract, non-inherited members or methods exposed to child, parent, or client - then why is it a class? It could be replaced, in some cases by an interface and in other cases by Null.</p>\n" }, { "answer_id": 5090489, "author": "Phil C", "author_id": 388267, "author_profile": "https://Stackoverflow.com/users/388267", "pm_score": 2, "selected": false, "text": "<p>Regarding C#, in some senses interfaces and abstract classes can be interchangeable. However, the differences are: i) interfaces cannot implement code; ii) because of this, interfaces cannot call further up the stack to subclass; and iii) only can abstract class may be inherited on a class, whereas multiple interfaces may be implemented on a class.</p>\n" }, { "answer_id": 5304755, "author": "sunwukung", "author_id": 124192, "author_profile": "https://Stackoverflow.com/users/124192", "pm_score": 1, "selected": false, "text": "<p>Use Interfaces to enforce a contract ACROSS families of unrelated classes. For example, you might have common access methods for classes that represent collections, but contain radically different data i.e. one class might represent a result set from a query, while the other might represent the images in a gallery. Also, you can implement multiple interfaces, thus allowing you to blend (and signify) the capabilities of the class.</p>\n\n<p>Use Inheritance when the classes bear a common relationship and therefore have a similair structural and behavioural signature, i.e. Car, Motorbike, Truck and SUV are all types of road vehicle that might contain a number of wheels, a top speed</p>\n" }, { "answer_id": 12880702, "author": "Akhil Jain", "author_id": 1225413, "author_profile": "https://Stackoverflow.com/users/1225413", "pm_score": 3, "selected": false, "text": "<p>I have a rough rule-of-thumb</p>\n\n<p><strong>Functionality:</strong> likely to be different in all parts: Interface.</p>\n\n<p><strong>Data, and functionality, parts will be mostly the same, parts different:</strong> abstract class.</p>\n\n<p><strong>Data, and functionality, actually working, if extended only with slight changes:</strong> ordinary (concrete) class</p>\n\n<p><strong>Data and functionality, no changes planned:</strong> ordinary (concrete) class with final modifier.</p>\n\n<p><strong>Data, and maybe functionality: read-only:</strong> enum members.</p>\n\n<p>This is very rough and ready and not at all strictly defined, but there is a spectrum from interfaces where everything is intended to be changed to enums where everything is fixed a bit like a read-only file.</p>\n" }, { "answer_id": 25577574, "author": "x19", "author_id": 1817640, "author_profile": "https://Stackoverflow.com/users/1817640", "pm_score": 0, "selected": false, "text": "<p>Thanks for <a href=\"https://stackoverflow.com/a/56912/1817640\">answering</a> by <a href=\"https://stackoverflow.com/users/372/jon-limjap\">Jon Limjap</a> but I want to add some explanation for concept of Interface and Abstract Base Classes</p>\n\n<p><strong>Interface Types vs. Abstract Base Classes</strong></p>\n\n<p>Adapted from the <a href=\"http://www.apress.com/9781430242338\" rel=\"nofollow noreferrer\">Pro C# 5.0 and the .NET 4.5 Framework</a> book.</p>\n\n<p>The interface type might seem very similar to an abstract base class. Recall\nthat when a class is marked as abstract, it may define any number of abstract members to provide a\npolymorphic interface to all derived types. However, even when a class does define a set of abstract\nmembers, it is also free to define any number of constructors, field data, nonabstract members (with\nimplementation), and so on. Interfaces, on the other hand, contain only abstract member definitions.\nThe polymorphic interface established by an abstract parent class suffers from one major limitation\nin that only derived types support the members defined by the abstract parent. However, in larger\nsoftware systems, it is very common to develop multiple class hierarchies that have no common parent\nbeyond System.Object. Given that abstract members in an abstract base class apply only to derived\ntypes, we have no way to configure types in different hierarchies to support the same polymorphic\ninterface. By way of example, assume you have defined the following abstract class:</p>\n\n<pre><code>public abstract class CloneableType\n{\n// Only derived types can support this\n// \"polymorphic interface.\" Classes in other\n// hierarchies have no access to this abstract\n// member.\n public abstract object Clone();\n}\n</code></pre>\n\n<p>Given this definition, only members that extend CloneableType are able to support the Clone()\nmethod. If you create a new set of classes that do not extend this base class, you can’t gain this\npolymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes.\nTherefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:</p>\n\n<pre><code>// Nope! Multiple inheritance is not possible in C#\n// for classes.\npublic class MiniVan : Car, CloneableType\n{\n}\n</code></pre>\n\n<p>As you would guess, interface types come to the rescue. After an interface has been defined, it can\nbe implemented by any class or structure, in any hierarchy, within any namespace or any assembly\n(written in any .NET programming language). As you can see, interfaces are highly polymorphic.\nConsider the standard .NET interface named ICloneable, defined in the System namespace. This\ninterface defines a single method named Clone():</p>\n\n<pre><code>public interface ICloneable\n{\nobject Clone();\n}\n</code></pre>\n" }, { "answer_id": 25996970, "author": "Ganesh Kodiganti", "author_id": 3452366, "author_profile": "https://Stackoverflow.com/users/3452366", "pm_score": 2, "selected": false, "text": "<p>By def, interface provides a layer to communicate with other code. All the public properties and methods of a class are by default implementing implicit interface. We can also define an interface as a role, when ever any class needs to play that role, it has to implement it giving it different forms of implementation depending on the class implementing it. Hence when you talk about interface, you are talking about polymorphism and when you are talking about base class, you are talking about inheritance. Two concepts of oops !!!</p>\n" }, { "answer_id": 27388452, "author": "Jason Roell", "author_id": 1253072, "author_profile": "https://Stackoverflow.com/users/1253072", "pm_score": 3, "selected": false, "text": "<p><strong>Source</strong>: <a href=\"http://jasonroell.com/2014/12/09/interfaces-vs-abstract-classes-what-should-you-use/\" rel=\"noreferrer\">http://jasonroell.com/2014/12/09/interfaces-vs-abstract-classes-what-should-you-use/</a></p>\n\n<p>C# is a wonderful language that has matured and evolved over the last 14 years. This is great for us developers because a mature language provides us with a plethora of language features that are at our disposal.</p>\n\n<p>However, with much power becomes much responsibility. Some of these features can be misused, or sometimes it is hard to understand why you would choose to use one feature over another. Over the years, a feature that I have seen many developers struggle with is when to choose to use an interface or to choose to use an abstract class. Both have there advantages and disadvantages and the correct time and place to use each. But how to we decide???</p>\n\n<p>Both provide for reuse of common functionality between types. The most obvious difference right away is that interfaces provide no implementation for their functionality whereas abstract classes allow you to implement some “base” or “default” behavior and then have the ability to “override” this default behavior with the classes derived types if necessary.</p>\n\n<p>This is all well and good and provides for great reuse of code and adheres to the DRY (Don’t Repeat Yourself) principle of software development. Abstract classes are great to use when you have an “is a” relationship.</p>\n\n<p>For example: A golden retriever “is a” type of dog. So is a poodle. They both can bark, as all dogs can. However, you might want to state that the poodle park is significantly different than the “default” dog bark. Therefor, it could make sense for you to implement something as follows:</p>\n\n<pre><code>public abstract class Dog\n{\n public virtual void Bark()\n {\n Console.WriteLine(\"Base Class implementation of Bark\");\n }\n}\n\npublic class GoldenRetriever : Dog\n{\n // the Bark method is inherited from the Dog class\n}\n\npublic class Poodle : Dog\n{\n // here we are overriding the base functionality of Bark with our new implementation\n // specific to the Poodle class\n public override void Bark()\n {\n Console.WriteLine(\"Poodle's implementation of Bark\");\n }\n}\n\n// Add a list of dogs to a collection and call the bark method.\n\nvoid Main()\n{\n var poodle = new Poodle();\n var goldenRetriever = new GoldenRetriever();\n\n var dogs = new List&lt;Dog&gt;();\n dogs.Add(poodle);\n dogs.Add(goldenRetriever);\n\n foreach (var dog in dogs)\n {\n dog.Bark();\n }\n}\n\n// Output will be:\n// Poodle's implementation of Bark\n// Base Class implementation of Bark\n\n// \n</code></pre>\n\n<p>As you can see, this would be a great way to keep your code DRY and allow for the base class implementation be called when any of the types can just rely on the default Bark instead of a special case implementation. The classes like GoldenRetriever, Boxer, Lab could all could inherit the “default” (bass class) Bark at no charge just because they implement the Dog abstract class.</p>\n\n<p>But I’m sure you already knew that.</p>\n\n<p>You are here because you want to understand why you might want to choose an interface over an abstract class or vice versa. Well one reason you may want to choose an interface over an abstract class is when you don’t have or want to prevent a default implementation. This is usually because the types that are implementing the interface not related in an “is a” relationship. Actually, they don’t have to be related at all except for the fact that each type “is able” or has “the ablity” to do something or have something.</p>\n\n<p>Now what the heck does that mean? Well, for example: A human is not a duck…and a duck is not a human. Pretty obvious. However, both a duck and a human have “the ability” to swim (given that the human passed his swimming lessons in 1st grade :) ). Also, since a duck is not a human or vice versa, this is not an “is a” realationship, but instead an “is able” relationship and we can use an interface to illustrate that:</p>\n\n<pre><code>// Create ISwimable interface\npublic interface ISwimable\n{\n public void Swim();\n}\n\n// Have Human implement ISwimable Interface\npublic class Human : ISwimable\n\n public void Swim()\n {\n //Human's implementation of Swim\n Console.WriteLine(\"I'm a human swimming!\");\n }\n\n// Have Duck implement ISwimable interface\npublic class Duck: ISwimable\n{\n public void Swim()\n {\n // Duck's implementation of Swim\n Console.WriteLine(\"Quack! Quack! I'm a Duck swimming!\")\n }\n}\n\n//Now they can both be used in places where you just need an object that has the ability \"to swim\"\n\npublic void ShowHowYouSwim(ISwimable somethingThatCanSwim)\n{\n somethingThatCanSwim.Swim();\n}\n\npublic void Main()\n{\n var human = new Human();\n var duck = new Duck();\n\n var listOfThingsThatCanSwim = new List&lt;ISwimable&gt;();\n\n listOfThingsThatCanSwim.Add(duck);\n listOfThingsThatCanSwim.Add(human);\n\n foreach (var something in listOfThingsThatCanSwim)\n {\n ShowHowYouSwim(something);\n }\n}\n\n // So at runtime the correct implementation of something.Swim() will be called\n // Output:\n // Quack! Quack! I'm a Duck swimming!\n // I'm a human swimming!\n</code></pre>\n\n<p>Using interfaces like the code above will allow you to pass an object into a method that “is able” to do something. The code doesn’t care how it does it…All it knows is that it can call the Swim method on that object and that object will know which behavior take at run-time based on its type.</p>\n\n<p>Once again, this helps your code stay DRY so that you would not have to write multiple methods that are calling the object to preform the same core function (ShowHowHumanSwims(human), ShowHowDuckSwims(duck), etc.)</p>\n\n<p>Using an interface here allows the calling methods to not have to worry about what type is which or how the behavior is implemented. It just knows that given the interface, each object will have to have implemented the Swim method so it is safe to call it in its own code and allow the behavior of the Swim method be handled within its own class.</p>\n\n<p>Summary:</p>\n\n<p>So my main rule of thumb is use an abstract class when you want to implement a “default” functionality for a class hierarchy or/and the classes or types you are working with share a “is a” relationship (ex. poodle “is a” type of dog).</p>\n\n<p>On the other hand use an interface when you do not have an “is a” relationship but have types that share “the ability” to do something or have something (ex. Duck “is not” a human. However, duck and human share “the ability” to swim).</p>\n\n<p>Another difference to note between abstract classes and interfaces is that a class can implement one to many interfaces but a class can only inherit from ONE abstract class (or any class for that matter). Yes, you can nest classes and have an inheritance hierarchy (which many programs do and should have) but you cannot inherit two classes in one derived class definition (this rule applies to C#. In some other languages you are able to do this, usually only because of the lack of interfaces in these languages).</p>\n\n<p>Also remember when using interfaces to adhere to the Interface Segregation Principle (ISP). ISP states that no client should be forced to depend on methods it does not use. For this reason interfaces should be focused on specific tasks and are usually very small (ex. IDisposable, IComparable ).</p>\n\n<p>Another tip is if you are developing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.</p>\n\n<p>Hope this clears things up for some people!</p>\n\n<p>Also if you can think of any better examples or want to point something out, please do so in the comments below!</p>\n" }, { "answer_id": 28104375, "author": "dSerk", "author_id": 2158635, "author_profile": "https://Stackoverflow.com/users/2158635", "pm_score": 1, "selected": false, "text": "<p>Make a list of the things your objects <em>must</em> be, have, or do and the things your objects <em>can</em> (or <em>might</em>) be, have, or do. <em>Must</em> indicates your base types and <em>can</em> indicates your interfaces. </p>\n\n<p>E.g., your PetBase <em>must</em> Breathe, and your IPet <em>might</em> DoTricks.</p>\n\n<p>Analysis of your problem domain will help you define the precise hierarchy structure.</p>\n" }, { "answer_id": 34608857, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>When should I use an interface and when should I use a base class?</p>\n</blockquote>\n\n<p>You should use interface if </p>\n\n<ol>\n<li>You have pure <code>abstract</code> methods and don't have non-abstract methods</li>\n<li>You don't have default implementation of <code>non abstract</code> methods (except for Java 8 language, where interface methods provides default implementation)</li>\n<li>If you are using Java 8, now interface will provide default implementation for some non-abstract methods. This will make <code>interface</code> more usable compared to <code>abstract</code> classes.</li>\n</ol>\n\n<p>Have a look at this SE <a href=\"https://stackoverflow.com/questions/479142/when-to-use-an-interface-instead-of-an-abstract-class-and-vice-versa/33963465#33963465\">question</a> for more details. </p>\n\n<blockquote>\n <p>Should it always be an interface if I don't want to actually define a base implementation of the methods?</p>\n</blockquote>\n\n<p>Yes. It's better and cleaner. Even if you have a base class with some abstract methods, let's base class extends <code>abstract</code> methods through interface. You can change interface in future without changing the base class.</p>\n\n<p>Example in java: </p>\n\n<pre><code>abstract class PetBase implements IPet {\n// Add all abstract methods in IPet interface and keep base class clean. \n Base class will contain only non abstract methods and static methods.\n}\n</code></pre>\n\n<blockquote>\n <p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.</p>\n</blockquote>\n\n<p>I prefer to have base class implement the interface.</p>\n\n<pre><code> abstract class PetBase implements IPet {\n // Add all abstract methods in IPet\n }\n\n /*If ISheds,IBarks is common for Pets, your PetBase can implement ISheds,IBarks. \n Respective implementations of PetBase can change the behaviour in their concrete classes*/\n\n abstract class PetBase implements IPet,ISheds,IBarks {\n // Add all abstract methods in respective interfaces\n }\n</code></pre>\n\n<p><strong>Advantages:</strong></p>\n\n<ol>\n<li><p>If I want to add one more abstract method in existing interfaces, I simple change interface without touching the abstract base class. If I want to change the contract, I will change interface &amp; implementation classes without touching base class. </p></li>\n<li><p>You can provide immutability to base class through interface. Have a look at this <a href=\"http://www.andygibson.net/blog/programming/immutability-through-interfaces/\" rel=\"nofollow noreferrer\">article</a></p></li>\n</ol>\n\n<p>Refer to this related SE question for more details:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/18777989/how-should-i-have-explained-the-difference-between-an-interface-and-an-abstract/34978606#34978606\">How should I have explained the difference between an Interface and an Abstract class?</a></p>\n" }, { "answer_id": 35669282, "author": "Jaimin Patel", "author_id": 3396808, "author_profile": "https://Stackoverflow.com/users/3396808", "pm_score": 2, "selected": false, "text": "<p><strong>Prefer interfaces over abstract classes</strong></p>\n\n<p>Rationale,\nthe main points to consider [two already mentioned here] are :</p>\n\n<ul>\n<li>Interfaces are more flexible, because a class can implement multiple\ninterfaces. Since Java does not have multiple inheritance, using\nabstract classes prevents your users from using any other class\nhierarchy. <strong>In general, prefer interfaces when there are no default\nimplementations or state.</strong> Java collections offer good examples of\nthis (Map, Set, etc.).</li>\n<li>Abstract classes have the advantage of allowing better forward\ncompatibility. Once clients use an interface, you cannot change it;\nif they use an abstract class, you can still add behavior without\nbreaking existing code. <strong>If compatibility is a concern, consider using\nabstract classes.</strong></li>\n<li>Even if you do have default implementations or internal state,\n<strong>consider offering an interface and an abstract implementation of it</strong>.\nThis will assist clients, but still allow them greater freedom if\ndesired [1].<br>\nOf course, the subject has been discussed at length\nelsewhere [2,3].</li>\n</ul>\n\n<p>[1] It adds more code, of course, but if brevity is your primary concern, you probably should have avoided Java in the first place!</p>\n\n<p>[2] Joshua Bloch, Effective Java, items 16-18.</p>\n\n<p>[3] <a href=\"http://www.codeproject.com/KB/ar\" rel=\"nofollow\">http://www.codeproject.com/KB/ar</a>...</p>\n" }, { "answer_id": 35803354, "author": "Adam Hughes", "author_id": 4076764, "author_profile": "https://Stackoverflow.com/users/4076764", "pm_score": 2, "selected": false, "text": "<p>I've found that a pattern of Interface > Abstract > Concrete works in the following use-case:</p>\n\n<pre><code>1. You have a general interface (eg IPet)\n2. You have a implementation that is less general (eg Mammal)\n3. You have many concrete members (eg Cat, Dog, Ape)\n</code></pre>\n\n<p>The abstract class defines default shared attributes of the concrete classes, yet enforces the interface. For example:</p>\n\n<pre><code>public interface IPet{\n\n public boolean hasHair();\n\n public boolean walksUprights();\n\n public boolean hasNipples();\n}\n</code></pre>\n\n<p>Now, since all mammals have hair and nipples (AFAIK, I'm not a zoologist), we can roll this into the abstract base class</p>\n\n<pre><code>public abstract class Mammal() implements IPet{\n\n @override\n public walksUpright(){\n throw new NotSupportedException(\"Walks Upright not implemented\");\n }\n\n @override\n public hasNipples(){return true}\n\n @override\n public hasHair(){return true}\n</code></pre>\n\n<p>And then the concrete classes merely define that they walk upright.</p>\n\n<pre><code>public class Ape extends Mammal(){\n\n @override\n public walksUpright(return true)\n}\n\npublic class Catextends Mammal(){\n\n @override\n public walksUpright(return false)\n}\n</code></pre>\n\n<p>This design is nice when there are lots of concrete classes, and you don't want to maintain boilerplate just to program to an interface. If new methods were added to the interface, it would break all of the resulting classes, so you are still getting the advantages of the interface approach.</p>\n\n<p><strong>In this case, the abstract could just as well be concrete; however, the abstract designation helps to emphasize that this pattern is being employed.</strong></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2871/" ]
When should I use an interface and when should I use a base class? Should it always be an interface if I don't want to actually define a base implementation of the methods? If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.
Let's take your example of a Dog and a Cat class, and let's illustrate using C#: Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them: ```cs public abstract class Mammal ``` This base class will probably have default methods such as: * Feed * Mate All of which are behavior that have more or less the same implementation between either species. To define this you will have: ```cs public class Dog : Mammal public class Cat : Mammal ``` Now let's suppose there are other mammals, which we will usually see in a zoo: ```cs public class Giraffe : Mammal public class Rhinoceros : Mammal public class Hippopotamus : Mammal ``` This will still be valid because at the core of the functionality `Feed()` and `Mate()` will still be the same. However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful: ```cs public interface IPettable { IList<Trick> Tricks{get; set;} void Bathe(); void Train(Trick t); } ``` The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea. Your Dog and Cat definitions should now look like: ```cs public class Dog : Mammal, IPettable public class Cat : Mammal, IPettable ``` Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance. Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly *as required* basis.
56,895
<p>How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set.</p> <hr> <p>As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results.</p>
[ { "answer_id": 56931, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 3, "selected": false, "text": "<p>This sounds to me like a an NP complete problem. I'm not sure there is a sure fire way to prove this kind of thing</p>\n" }, { "answer_id": 57313, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 1, "selected": false, "text": "<p>The DBMS vendors have been working on this for a very, very long time. As Rik said, it's <em>probably</em> an intractable problem, but I don't think any formal analysis on the NP-completeness of the problem space has been done.</p>\n\n<p>However, your best bet is to leverage your DBMS as much as possible. All DBMS systems translate SQL into some sort of query plan. You can use this query plan, which is an abstracted version of the query, as a good starting point (the DBMS will do LOTS of optimization, flattening queries into more workable models). </p>\n\n<p><em>NOTE: modern DBMS use a \"cost-based\" analyzer which is non-deterministic across statistics updates, so the query planner, over time, may change the query plan for identical queries.</em></p>\n\n<p>In Oracle (depending on your version), you can tell the optimizer to switch from the cost based analyzer to the deterministic rule based analyzer (this will simplify plan analysis) with a SQL hint, e.g.</p>\n\n<pre><code>SELECT /*+RULE*/ FROM yourtable\n</code></pre>\n\n<p>The rule-based optimizer has been deprecated since 8i but it still hangs around even thru 10g (I don't know 'bout 11). However, the rule-based analyzer is much less sophisticated: the error rate potentially is much higher.</p>\n\n<p>For further reading of a more generic nature, IBM has been fairly prolific with their query-optimization patents. This one here on a method for converting SQL to an \"abstract plan\" is a good starting point:\n<a href=\"http://www.patentstorm.us/patents/7333981.html\" rel=\"nofollow noreferrer\">http://www.patentstorm.us/patents/7333981.html</a></p>\n" }, { "answer_id": 75328, "author": "Michael OShea", "author_id": 13178, "author_profile": "https://Stackoverflow.com/users/13178", "pm_score": 0, "selected": false, "text": "<p>You don't.</p>\n\n<p>If you need a high level of confidence that a performance change, for example, hasn't changed the output of a query then test the hell out it.</p>\n\n<p>If you need a really high level of confidence .. then errrm, test it even more.</p>\n\n<p>Massive level's of testing aren't that hard to cobble together for a SQL query. Write a proc which will iterate around a large/complete set of possible paramenters, and call each query with each set of params, and write the outputs to respective tables. Compare the two tables and there you have it.</p>\n\n<p>It's not exactly scientific, which I guess was the OP's question, but I'm not aware of a formal method to prove equivalency.</p>\n" }, { "answer_id": 93489, "author": "Doug Porter", "author_id": 4311, "author_profile": "https://Stackoverflow.com/users/4311", "pm_score": 5, "selected": true, "text": "<p>The best you can do is compare the 2 query outputs based on a given set of inputs looking for any differences. To say that they will always return the same results for all inputs really depends on the data.</p>\n\n<p>For Oracle one of the better if not best approaches (very efficient) is here (<kbd>Ctrl</kbd>+<kbd>F</kbd> Comparing the Contents of Two Tables):<br>\n<a href=\"http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html\" rel=\"noreferrer\"><a href=\"http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html\" rel=\"noreferrer\">http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html</a></a></p>\n\n<p>Which boils down to:</p>\n\n<pre><code>select c1,c2,c3, \n count(src1) CNT1, \n count(src2) CNT2\n from (select a.*, \n 1 src1, \n to_number(null) src2 \n from a\n union all\n select b.*, \n to_number(null) src1, \n 2 src2 \n from b\n )\ngroup by c1,c2,c3\nhaving count(src1) &lt;&gt; count(src2);\n</code></pre>\n" }, { "answer_id": 93527, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 1, "selected": false, "text": "<p>Perhaps you could draw (by hand) out your query and the results using <a href=\"http://en.wikipedia.org/wiki/Venn_diagram\" rel=\"nofollow noreferrer\">Venn Diagrams</a>, and see if they produce the same diagram. Venn diagrams are good for representing sets of data, and SQL queries work on sets of data. Drawing out a Venn Diagram might help you to visualize if 2 queries are functionally equivalent.</p>\n" }, { "answer_id": 98609, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "<p>This is pretty easy to do.</p>\n\n<p>Lets assume your queries are named a and b</p>\n\n<p><strong>a\nminus \nb</strong></p>\n\n<p>should give you an empty set. If it does not. then the queries return different sets, and the result set shows you the rows that are different.</p>\n\n<p>then do</p>\n\n<p><strong>b \nminus \na</strong></p>\n\n<p>that should give you an empty set. If it does, then the queries do return the same sets.\nif it is not empty, then the queries are different in some respect, and the result set shows you the rows that are different.</p>\n" }, { "answer_id": 2122095, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 1, "selected": false, "text": "<p>This will do the trick. If this query returns zero rows the two queries are returning the same results. As a bonus, it runs as a single query, so you don't have to worry about setting the isolation level so that the data doesn't change between two queries.</p>\n\n<pre><code>select * from ((&lt;query 1&gt; MINUS &lt;query 2&gt;) UNION ALL (&lt;query 2&gt; MINUS &lt;query 1&gt;))\n</code></pre>\n\n<p>Here's a handy shell script to do this:</p>\n\n<pre><code>#!/bin/sh\n\nCONNSTR=$1\necho query 1, no semicolon, eof to end:; Q1=`cat` \necho query 2, no semicolon, eof to end:; Q2=`cat`\n\nT=\"(($Q1 MINUS $Q2) UNION ALL ($Q2 MINUS $Q1));\"\n\necho select 'count(*)' from $T | sqlplus -S -L $CONNSTR\n</code></pre>\n" }, { "answer_id": 5730066, "author": "tbone", "author_id": 534120, "author_profile": "https://Stackoverflow.com/users/534120", "pm_score": 1, "selected": false, "text": "<p>CAREFUL! Functional \"equivalence\" is often based on the data, and you may \"prove\" equivalence of 2 queries by comparing results for many cases <strong><em>and still be wrong once the data changes in a certain way</em></strong>.</p>\n\n<p>For example:</p>\n\n<pre><code>SQL&gt; create table test_tabA\n(\ncol1 number\n)\n\nTable created.\n\nSQL&gt; create table test_tabB\n(\ncol1 number\n)\n\nTable created.\n\nSQL&gt; -- insert 1 row\n\nSQL&gt; insert into test_tabA values (1)\n\n1 row created.\n\nSQL&gt; commit\n\nCommit complete.\n\nSQL&gt; -- Not exists query:\n\nSQL&gt; select * from test_tabA a\nwhere not exists\n(select 'x' from test_tabB b\nwhere b.col1 = a.col1)\n\n COL1\n\n----------\n\n 1\n\n1 row selected.\n\nSQL&gt; -- Not IN query:\n\nSQL&gt; select * from test_tabA a\nwhere col1 not in\n(select col1\nfrom test_tabB b)\n\n COL1\n\n----------\n\n 1\n\n1 row selected.\n\n\n-- THEY MUST BE THE SAME!!! (or maybe not...)\n\n\nSQL&gt; -- insert a NULL to test_tabB\n\nSQL&gt; insert into test_tabB values (null)\n\n1 row created.\n\nSQL&gt; commit\n\nCommit complete.\n\nSQL&gt; -- Not exists query:\n\nSQL&gt; select * from test_tabA a\nwhere not exists\n(select 'x' from test_tabB b\nwhere b.col1 = a.col1)\n\n\n COL1\n\n----------\n\n 1\n\n1 row selected.\n\nSQL&gt; -- Not IN query:\n\nSQL&gt; select * from test_tabA a\nwhere col1 not in\n(select col1\nfrom test_tabB b)\n\n**no rows selected.**\n</code></pre>\n" }, { "answer_id": 45584198, "author": "Sander van den Oord", "author_id": 3489155, "author_profile": "https://Stackoverflow.com/users/3489155", "pm_score": 4, "selected": false, "text": "<p><strong>1) Real equivalency proof with Cosette:</strong><br>\nCosette checks (with a proof) if 2 SQL query's are equivalent and counter examples when not equivalent. It's the only way to be absolutely sure, well almost ;) You can even throw in 2 query's on their website and check (formal) equivalence right away.</p>\n<p>Link to Cosette:\n<a href=\"https://cosette.cs.washington.edu/\" rel=\"nofollow noreferrer\">https://cosette.cs.washington.edu/</a></p>\n<p>Link to article that gives a good explanation of how Cosette works: <a href=\"https://medium.com/@uwdb/introducing-cosette-527898504bd6\" rel=\"nofollow noreferrer\">https://medium.com/@uwdb/introducing-cosette-527898504bd6</a><br>\n<br>\n<br>\n<strong>2) Or if you're just looking for a quick practical fix:</strong><br>\nTry this stackoverflow answer: <a href=\"https://stackoverflow.com/questions/5727882/check-if-two-selects-are-equivalent\">[sql - check if two select's are equal]</a><br>\nWhich comes down to:</p>\n<pre><code>(select * from query1 MINUS select * from query2) \nUNION ALL\n(select * from query2 MINUS select * from query1)\n</code></pre>\n<p>This query gives you all rows that are returned by only one of the queries.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set. --- As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results.
The best you can do is compare the 2 query outputs based on a given set of inputs looking for any differences. To say that they will always return the same results for all inputs really depends on the data. For Oracle one of the better if not best approaches (very efficient) is here (`Ctrl`+`F` Comparing the Contents of Two Tables): [<http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html>](http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html) Which boils down to: ``` select c1,c2,c3, count(src1) CNT1, count(src2) CNT2 from (select a.*, 1 src1, to_number(null) src2 from a union all select b.*, to_number(null) src1, 2 src2 from b ) group by c1,c2,c3 having count(src1) <> count(src2); ```
56,905
<p>Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object. </p> <p>Here is the scenario with simplified code:</p> <ol> <li><p><code>Default.aspx</code></p></li> <li><p><code>MainScript.js</code></p> <pre><code>function getObject(){ return new Array(); } function function1(obj){ var s=Sys.Serialization.JavaScriptSerializer.serialize(obj); alert(s); } function function2(){ var obj=getObject(); var s=Sys.Serialization.JavaScriptSerializer.serialize(obj); alert(s); } </code></pre></li> <li><p><code>Content.aspx</code></p></li> <li><p><code>ContentScript.js</code></p> <pre><code>function serializeObject(){ var obj=window.top.getObject(); window.top.function1(obj); // &lt;– This works fine obj=new Array(); window.top.function1(obj); // &lt;– this causes an Out of Stack Space error } </code></pre></li> </ol> <p>The code for the sample pages and JavaScript is <a href="http://braincells2pixels.wordpress.com/2008/02/14/aspnet-ajax-javascript-serialization-error/" rel="nofollow noreferrer">here</a>.</p> <p>Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages.</p> <p>A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx). </p> <p>Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error.</p> <p>Any ideas?</p>
[ { "answer_id": 57433, "author": "d91-jal", "author_id": 5085, "author_profile": "https://Stackoverflow.com/users/5085", "pm_score": 0, "selected": false, "text": "<p>I have no way of testing your code right now, but it looks like a bug in JavaScriptSerializer.serialize to me. My guess is that it tries to do some kind of type checking on the array via the CLR and that it doesn't handle an empty array properly. </p>\n\n<p>Have you tried to add an item of a serializable type to the array in your code? If so, what happens?</p>\n" }, { "answer_id": 194249, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 1, "selected": false, "text": "<p>I converted your example to a set of static html files, and dowloaded the standalone <a href=\"http://msdn.microsoft.com/en-us/asp.net/bb944808.aspx\" rel=\"nofollow noreferrer\">Microsoft Ajax Library 3.5</a> to test with. It didn't have issue on either Firefox 3 or IE 7, but I did notice the first alert box displayed [] (an array) and the second {} (an object).</p>\n\n<p>Then, I converted your new Array() code to:</p>\n\n<pre><code> var obj = [];\n obj.push(1);\n</code></pre>\n\n<p>and after that, I got [1] and {\"0\", 1} is the alert boxes. I don't think the bug is with JavaScriptSerializer, but something to do with passing objects across frames.</p>\n" }, { "answer_id": 2561528, "author": "GotDotCom", "author_id": 307026, "author_profile": "https://Stackoverflow.com/users/307026", "pm_score": 3, "selected": true, "text": "<p>This problem happens because Sys.Serialization.JavaScriptSerializer can't serialize objects from others frames, but only those objects which where instantiated in the current window (which calls serialize() method). The only workaround which is known for me it's making clone of the object from other frame before calling serialize() method.</p>\n\n<p>Example of the clone() methode you can find here (comments in Russian):\n<a href=\"http://snowcore.net/clone-javascript-object\" rel=\"nofollow noreferrer\">link text</a></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3635/" ]
Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object. Here is the scenario with simplified code: 1. `Default.aspx` 2. `MainScript.js` ``` function getObject(){ return new Array(); } function function1(obj){ var s=Sys.Serialization.JavaScriptSerializer.serialize(obj); alert(s); } function function2(){ var obj=getObject(); var s=Sys.Serialization.JavaScriptSerializer.serialize(obj); alert(s); } ``` 3. `Content.aspx` 4. `ContentScript.js` ``` function serializeObject(){ var obj=window.top.getObject(); window.top.function1(obj); // <– This works fine obj=new Array(); window.top.function1(obj); // <– this causes an Out of Stack Space error } ``` The code for the sample pages and JavaScript is [here](http://braincells2pixels.wordpress.com/2008/02/14/aspnet-ajax-javascript-serialization-error/). Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages. A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx). Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error. Any ideas?
This problem happens because Sys.Serialization.JavaScriptSerializer can't serialize objects from others frames, but only those objects which where instantiated in the current window (which calls serialize() method). The only workaround which is known for me it's making clone of the object from other frame before calling serialize() method. Example of the clone() methode you can find here (comments in Russian): [link text](http://snowcore.net/clone-javascript-object)
56,908
<p>Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it?</p> <p>It probably does something like:</p> <pre><code>override OnRead(object sender, Event e) { ShowFilesFromAmazon(); } </code></pre> <p>Are there any API:s for this? Maybe to write to an XML-file or a database, instead of a real drive.</p> <hr> <p>The <a href="http://dokan-dev.net/en/" rel="noreferrer">Dokan Library</a> seems to be the answer that mostly corresponds with my question, even though <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx" rel="noreferrer">System.IO.IsolatedStorage</a> seems to be the most standardized and most Microsoft-environment adapted.</p>
[ { "answer_id": 56919, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 2, "selected": false, "text": "<p>Yes, use the classes in <a href=\"http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx\" rel=\"nofollow noreferrer\">System.IO.IsolatedStorage</a></p>\n" }, { "answer_id": 57079, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 4, "selected": true, "text": "<p>You can use the <a href=\"https://dokan-dev.github.io/\" rel=\"nofollow noreferrer\">Dokan library</a> to create a virtual drive. There is a .Net wrapper for interfacing with C#.</p>\n" }, { "answer_id": 268935, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>The contents of My Computer can include Shell Namespace Extensions. These COM objects run inside the main Explorer process, as do many other shell extensions. Using C# for such extensions is a bad idea, since your extension cannot control which CLR version Explorer.exe can use. And Microsoft allows only one CLR per process.</p>\n" }, { "answer_id": 66696796, "author": "Coder", "author_id": 14187101, "author_profile": "https://Stackoverflow.com/users/14187101", "pm_score": 4, "selected": false, "text": "<p>Depending on what type of virtual drive you wish to build, here are some new OS API recently introduced in Windows, macOS and iOS.</p>\n<p>Some of the below API is available as managed .NET code on Windows but many are a native Windows / macOS / iOS API. Even though, I was able to consume many of the below API in .NET and Xamarin applications and build entire Virtual Drive in C# for Windows, macOS and iOS.</p>\n<h2>For Remote Cloud Storage</h2>\n<p><strong>On Windows.</strong> Windows 10 provides <a href=\"https://learn.microsoft.com/en-us/windows/win32/cfapi/build-a-cloud-file-sync-engine\" rel=\"noreferrer\">Cloud Sync Engine API</a> for creating virtual drives that publish data from a remote location. It is also known under the “Cloud Filter API” name or “Windows Cloud Provider”. Here are its major features:</p>\n<ul>\n<li>On-demand folders listing. Folder listing is made only when the first requested by the client application to the file system is made. File content is not downloaded, but all file properties including file size are available on the client via regular files API.</li>\n<li>On-demand file content loading. File content can be downloaded in several modes (progressive, streaming mode, allow background download, etc) and made available to OS when application makes first file content reading request.</li>\n<li>Offline files support. Files can be edited in the offline mode, pinned/unpinned and synched to/from the server.</li>\n<li>Windows shell integration. Windows File Manager shows file status (modified, in-sync, conflict) and file download progress.</li>\n<li>Metadata and properties support. Custom columns can be displayed in Windows File Manager as well as some binary metadata can be associated with each file and folder.</li>\n</ul>\n<p><strong>On macOS and iOS.</strong> MacOS Big Sur and iOS 11+ provides similar API called <a href=\"https://developer.apple.com/documentation/fileprovider\" rel=\"noreferrer\">File Provider API</a>. Its features are similar to what Windows API provides:</p>\n<ul>\n<li>On-demand folders listing.</li>\n<li>On-demand files content loading.</li>\n<li>Offline files support.</li>\n<li>File Manager Integration. In macOS Finder and iOS Files application you can can show file status (in the cloud, local).</li>\n</ul>\n<p>I am not sure currently if files/folders and can show custom columns in macOS Finder and store any metadata.</p>\n<h2>For High-Speed Local Storage</h2>\n<p><strong>On Windows.</strong> Windows provides <a href=\"https://learn.microsoft.com/en-us/windows/win32/projfs/projected-file-system\" rel=\"noreferrer\">ProjFS API</a>. Its main difference from the Cloud Sync Engine API and macOS/iOS File Provider API is that it hides the fact that it is a remote storage. It does not provide any indication of the file status, download progress, ets. The documentation says it is intended for “projecting” hierarchical data in the form of file system.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429/" ]
Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it? It probably does something like: ``` override OnRead(object sender, Event e) { ShowFilesFromAmazon(); } ``` Are there any API:s for this? Maybe to write to an XML-file or a database, instead of a real drive. --- The [Dokan Library](http://dokan-dev.net/en/) seems to be the answer that mostly corresponds with my question, even though [System.IO.IsolatedStorage](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx) seems to be the most standardized and most Microsoft-environment adapted.
You can use the [Dokan library](https://dokan-dev.github.io/) to create a virtual drive. There is a .Net wrapper for interfacing with C#.
56,913
<p>I have a whole bunch of files with filenames using our lovely Swedish letters <strong>å å</strong> and <strong>ö</strong>. For various reasons I now need to convert these to an [a-zA-Z] range. Just removing anything outside this range is fairly easy. The thing that's causing me trouble is that I'd like to replace <strong>å</strong> with <strong>a</strong>, <strong>ö</strong> with <strong>o</strong> and so on. </p> <p>This is charset troubles at their worst.</p> <p>I have a set of test files:</p> <pre><code>files\Copy of New Text Documen åäö t.txt files\fofo.txt files\New Text Document.txt files\worstcase åäöÅÄÖéÉ.txt </code></pre> <p>I'm basing my script on this line, piping it's results into various commands</p> <pre><code>for %%X in (files\*.txt) do (echo %%X) </code></pre> <p>The wierd thing is that if I print the results of this (the plain for-loop that is) into a file I get this output:</p> <pre><code>files\Copy of New Text Documen †„” t.txt files\fofo.txt files\New Text Document.txt files\worstcase †„”Ž™‚.txt </code></pre> <p>So something wierd is happening to my filenames before they even reach the other tools (I've been trying to do this using a sed port for Windows from something called GnuWin32 but no luck so far) and doing the replace on these characters doesn't help either.</p> <p>How would you solve this problem? I'm open to any type of tools, commandline or otherwise…</p> <p><strong>EDIT:</strong> This is a one time problem, so I'm looking for a quick 'n ugly fix</p>
[ { "answer_id": 56924, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 0, "selected": false, "text": "<p>I would write this in C++, C#, or Java -- environments where I know for certain that you can get the Unicode characters out of a path properly. It's always uncertain with command-line tools, especially out of Cygwin.</p>\n\n<p>Then the code is a simple find/replace or regex/replace. If you can name a language it would be easy to write the code.</p>\n" }, { "answer_id": 56938, "author": "busse", "author_id": 5702, "author_profile": "https://Stackoverflow.com/users/5702", "pm_score": 0, "selected": false, "text": "<p>I'd write a vbscript (WSH) to scan the directories, then send the filenames to a function that breaks up the filenames into their individual letters, then does a SELECT CASE on the Swedish ones and replaces them with the ones you want. Or, instead of doing that the function could just drop it thru a bunch of REPLACE() functions, reassigning the output to the input string. At the end it then renames the file with the new value.</p>\n" }, { "answer_id": 57049, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 1, "selected": false, "text": "<p>You might have more luck in cmd.exe if you opened it in UNICODE mode. Use \"cmd /U\".</p>\n\n<p>Others have proposed using a real programming language. That's fine, especially if you have a language you are very comfortable with. My friend on the C# team says that C# 3.0 (with Linq) is well-suited to whipping up quick, small programs like this. He has stopped writing batch files most of the time.</p>\n\n<p>Personally, I would choose PowerShell. This problem can be solved right on the command line, and in a single line. I'll</p>\n\n<p>EDIT: it's not one line, but it's not a lot of code, either. Also, it looks like StackOverflow doesn't like the syntax \"$_.Name\", and renders the _ as &amp;#95.</p>\n\n<pre><code>$mapping = @{ \n \"å\" = \"a\"\n \"ä\" = \"a\"\n \"ö\" = \"o\"\n}\n\nGet-ChildItem -Recurse . *.txt | Foreach-Object { \n $newname = $_.Name \n foreach ($l in $mapping.Keys) {\n $newname = $newname.Replace( $l, $mapping[$l] )\n $newname = $newname.Replace( $l.ToUpper(), $mapping[$l].ToUpper() )\n }\n Rename-Item -WhatIf $_.FullName $newname # remove the -WhatIf when you're ready to do it for real.\n}\n</code></pre>\n" }, { "answer_id": 57359, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": true, "text": "<p>You can use this code (Python)</p>\n\n<h1>Rename international files</h1>\n\n<pre><code># -*- coding: cp1252 -*-\n\nimport os, shutil\n\nbase_dir = \"g:\\\\awk\\\\\" # Base Directory (includes subdirectories)\nchar_table_1 = \"áéíóúñ\"\nchar_table_2 = \"aeioun\"\n\nadirs = os.walk (base_dir)\n\nfor adir in adirs:\n dir = adir[0] + \"\\\\\" # Directory\n # print \"\\nDir : \" + dir\n\n for file in adir[2]: # List of files\n if os.access(dir + file, os.R_OK):\n file2 = file\n for i in range (0, len(char_table_1)):\n file2 = file2.replace (char_table_1[i], char_table_2[i])\n\n if file2 &lt;&gt; file:\n # Different, rename\n print dir + file, \" =&gt; \", file2\n shutil.move (dir + file, dir + file2)\n\n###\n</code></pre>\n\n<p>You have to change your encoding and your char tables (I tested this script with Spanish files and works fine). You can comment the \"move\" line to check if it's working ok, and remove the comment later to do the renaming.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914/" ]
I have a whole bunch of files with filenames using our lovely Swedish letters **å å** and **ö**. For various reasons I now need to convert these to an [a-zA-Z] range. Just removing anything outside this range is fairly easy. The thing that's causing me trouble is that I'd like to replace **å** with **a**, **ö** with **o** and so on. This is charset troubles at their worst. I have a set of test files: ``` files\Copy of New Text Documen åäö t.txt files\fofo.txt files\New Text Document.txt files\worstcase åäöÅÄÖéÉ.txt ``` I'm basing my script on this line, piping it's results into various commands ``` for %%X in (files\*.txt) do (echo %%X) ``` The wierd thing is that if I print the results of this (the plain for-loop that is) into a file I get this output: ``` files\Copy of New Text Documen †„” t.txt files\fofo.txt files\New Text Document.txt files\worstcase †„”Ž™‚.txt ``` So something wierd is happening to my filenames before they even reach the other tools (I've been trying to do this using a sed port for Windows from something called GnuWin32 but no luck so far) and doing the replace on these characters doesn't help either. How would you solve this problem? I'm open to any type of tools, commandline or otherwise… **EDIT:** This is a one time problem, so I'm looking for a quick 'n ugly fix
You can use this code (Python) Rename international files ========================== ``` # -*- coding: cp1252 -*- import os, shutil base_dir = "g:\\awk\\" # Base Directory (includes subdirectories) char_table_1 = "áéíóúñ" char_table_2 = "aeioun" adirs = os.walk (base_dir) for adir in adirs: dir = adir[0] + "\\" # Directory # print "\nDir : " + dir for file in adir[2]: # List of files if os.access(dir + file, os.R_OK): file2 = file for i in range (0, len(char_table_1)): file2 = file2.replace (char_table_1[i], char_table_2[i]) if file2 <> file: # Different, rename print dir + file, " => ", file2 shutil.move (dir + file, dir + file2) ### ``` You have to change your encoding and your char tables (I tested this script with Spanish files and works fine). You can comment the "move" line to check if it's working ok, and remove the comment later to do the renaming.
56,943
<p>I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.</p> <pre><code>if (YesNoDialog.ask("Are you sure?") == true) { // yes was chosen } else { // no was chosen } </code></pre>
[ { "answer_id": 56970, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": -1, "selected": false, "text": "<p>I dont have programed in Java ME, but i found in it's reference for optional packages the\n<a href=\"http://java.sun.com/javame/reference/apis/jsr209/\" rel=\"nofollow noreferrer\">Advanced Graphics and User Interface API</a>, and it's used like the Java SE API to create these dialogs with the <a href=\"http://java.sun.com/javame/reference/apis/jsr209/javax/swing/JOptionPane.html\" rel=\"nofollow noreferrer\">JOptionPane Class</a></p>\n\n<blockquote>\n <p><code>int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object &gt;message, java.lang.String title, int optionType)</code></p>\n</blockquote>\n\n<p>Return could be\n<code>JOptionPane.YES_OPTION</code>, <code>JOptionPane.NO_OPTION</code>, <code>JOptionPane.CANCEL_OPTION</code>...</p>\n" }, { "answer_id": 63063, "author": "Carlos Carrasco", "author_id": 7027, "author_profile": "https://Stackoverflow.com/users/7027", "pm_score": 4, "selected": true, "text": "<p>You need an <a href=\"http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Alert.html\" rel=\"nofollow noreferrer\">Alert</a>:</p>\n\n<blockquote>\n <p>An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions.</p>\n</blockquote>\n\n<p>With 2 <a href=\"http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Command.html\" rel=\"nofollow noreferrer\">commands</a> (\"Yes\"/\"No\" in your case):</p>\n\n<blockquote>\n <p>If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked.</p>\n</blockquote>\n\n<p>These are built-in classes supported in MIDP 1.0 and higher. Also your code snippet will never work. Such an API would need to block the calling thread awaiting for the user to select and answer. This goes exactly in the opposite direction of the UI interaction model of MIDP, which is based in callbacks and delegation. You need to provide your own class, implementing <a href=\"http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/CommandListener.html\" rel=\"nofollow noreferrer\">CommandListener</a>, and prepare your code for asynchronous execution.</p>\n\n<p>Here is an (untested!) example class based on Alert:</p>\n\n<pre><code>public class MyPrompter implements CommandListener {\n\n private Alert yesNoAlert;\n\n private Command softKey1;\n private Command softKey2;\n\n private boolean status;\n\n public MyPrompter() {\n yesNoAlert = new Alert(\"Attention\");\n yesNoAlert.setString(\"Are you sure?\");\n softKey1 = new Command(\"No\", Command.BACK, 1);\n softKey2 = new Command(\"Yes\", Command.OK, 1);\n yesNoAlert.addCommand(softKey1);\n yesNoAlert.addCommand(softKey2);\n yesNoAlert.setCommandListener(this);\n status = false;\n }\n\n public Displayable getDisplayable() {\n return yesNoAlert;\n }\n\n public boolean getStatus() {\n return status;\n }\n\n public void commandAction(Command c, Displayable d) {\n status = c.getCommandType() == Command.OK;\n // maybe do other stuff here. remember this is asynchronous\n }\n\n};\n</code></pre>\n\n<p>To use it (again, untested and on top of my head):</p>\n\n<pre><code>MyPrompter prompt = new MyPrompter();\nDisplay.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());\n</code></pre>\n\n<p>This code will make the prompt the current displayed form in your app, but it <em>won't block your thread</em> like in the example you posted. You need to continue running and wait for a commandAction invocation.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5896/" ]
I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey. ``` if (YesNoDialog.ask("Are you sure?") == true) { // yes was chosen } else { // no was chosen } ```
You need an [Alert](http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Alert.html): > > An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions. > > > With 2 [commands](http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Command.html) ("Yes"/"No" in your case): > > If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked. > > > These are built-in classes supported in MIDP 1.0 and higher. Also your code snippet will never work. Such an API would need to block the calling thread awaiting for the user to select and answer. This goes exactly in the opposite direction of the UI interaction model of MIDP, which is based in callbacks and delegation. You need to provide your own class, implementing [CommandListener](http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/CommandListener.html), and prepare your code for asynchronous execution. Here is an (untested!) example class based on Alert: ``` public class MyPrompter implements CommandListener { private Alert yesNoAlert; private Command softKey1; private Command softKey2; private boolean status; public MyPrompter() { yesNoAlert = new Alert("Attention"); yesNoAlert.setString("Are you sure?"); softKey1 = new Command("No", Command.BACK, 1); softKey2 = new Command("Yes", Command.OK, 1); yesNoAlert.addCommand(softKey1); yesNoAlert.addCommand(softKey2); yesNoAlert.setCommandListener(this); status = false; } public Displayable getDisplayable() { return yesNoAlert; } public boolean getStatus() { return status; } public void commandAction(Command c, Displayable d) { status = c.getCommandType() == Command.OK; // maybe do other stuff here. remember this is asynchronous } }; ``` To use it (again, untested and on top of my head): ``` MyPrompter prompt = new MyPrompter(); Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable()); ``` This code will make the prompt the current displayed form in your app, but it *won't block your thread* like in the example you posted. You need to continue running and wait for a commandAction invocation.
56,946
<p>Say I have:</p> <pre><code>&lt;ul&gt; &lt;li id="x"&gt; &lt;a href="x"&gt;x&lt;/a&gt; &lt;/li&gt; &lt;li id="y"&gt; &lt;a href="y"&gt;y&lt;/a&gt; &lt;ul&gt; &lt;li id="z"&gt; &lt;a href="z"&gt;z&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x.</p> <p>Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)?</p> <p>Thanks!</p>
[ { "answer_id": 56958, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 0, "selected": false, "text": "<p>I suggest you parse it into a DOM and recurse backwards like you were thinking. Regular expressions don't work very well for nested structures with arbitrary nesting levels.</p>\n" }, { "answer_id": 56960, "author": "Simon Keep", "author_id": 1127460, "author_profile": "https://Stackoverflow.com/users/1127460", "pm_score": 2, "selected": false, "text": "<p>I would use XSLT. You can specify to search for nodes that are ancestors of z .</p>\n" }, { "answer_id": 57076, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 2, "selected": false, "text": "<p>xpath has an ancestor-axis which includes all ancestors of the current context node.</p>\n\n<p>//*[@id=\"z\"]/ancestor::li</p>\n\n<p><strong>*</strong> any element<br />\n<strong>[@id=\"z\"]</strong> that has an attribute <i>id</i> with the value <i>z</i> (since the attribute is id there can(/should be) only be one such element)<br />\n<strong>/ancestor::li</strong> all <i>li</i> elements that are ancestors of that</p>\n\n<p>see also: <a href=\"https://www.w3schools.com/xml/xpath_axes.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/xml/xpath_axes.asp</a></p>\n" }, { "answer_id": 57118, "author": "DaveP", "author_id": 3577, "author_profile": "https://Stackoverflow.com/users/3577", "pm_score": 0, "selected": false, "text": "<p>\n\n\n\n\n</p>\n\n<p>Will add the attribute only to elements with a descendent element of 'z'. </p>\n" }, { "answer_id": 57210, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks for the input. I figured it was impossible without parsing (or using xsl, etc)... Oh well.</p>\n" }, { "answer_id": 58329, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 1, "selected": false, "text": "<p>Example of the whole XSLT:</p>\n\n<pre><code>&lt;xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\"&gt;\n\n &lt;xsl:variable name=\"ancestors\" select=\"descendant::li[@id = 'z']/ancestor::li\"/&gt;\n\n &lt;xsl:template match=\"li\"&gt;\n &lt;xsl:copy&gt;\n &lt;!-- test if current li is in the $ancestors node-list --&gt;\n &lt;xsl:if test=\"count($ancestors | .) = count($ancestors)\"&gt;\n &lt;xsl:attribute name=\"class\"&gt;ancestor&lt;/xsl:attribute&gt;\n &lt;/xsl:if&gt;\n &lt;xsl:apply-templates select=\"node() | @*\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"node() | @*\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"node() | @*\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 58365, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "<p>This is a good fit for jQuery if that's available to you.</p>\n\n<pre><code>$(\"#z\").parent().parent().addClass(\"foo\");\n</code></pre>\n" }, { "answer_id": 59496, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 0, "selected": false, "text": "<p>In addition to John Sheehan's anwser:<br />\nWith JQuery I'd rather use\n<br/><code>$('#z').parents('li').addClass('myClass');</code><br/>\nthan relying on the actual structure.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Say I have: ``` <ul> <li id="x"> <a href="x">x</a> </li> <li id="y"> <a href="y">y</a> <ul> <li id="z"> <a href="z">z</a> </li> </ul> </li> </ul> ``` I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x. Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)? Thanks!
I would use XSLT. You can specify to search for nodes that are ancestors of z .
56,950
<p>We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...</p> <p>I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:</p> <pre><code>Value ---------- 143.55 3532.13 1.75 </code></pre> <p>How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".</p> <p>I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.</p> <p>Thank you.</p>
[ { "answer_id": 56972, "author": "d91-jal", "author_id": 5085, "author_profile": "https://Stackoverflow.com/users/5085", "pm_score": 5, "selected": true, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms189527.aspx\" rel=\"noreferrer\">STR function</a> has an optional length argument as well as a number-of-decimals one.</p>\n\n<pre><code>SELECT STR(123.45, 6, 1)\n\n------\n 123.5\n\n(1 row(s) affected)\n</code></pre>\n" }, { "answer_id": 56973, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "<p>If you MUST do this in SQL you can use the folowing code (This code assumes that you have no numerics that are bigger than 40 chars):</p>\n\n<pre><code>SELECT REPLICATE(' ', 40 - LEN(CAST(numColumn as varchar(40)))) + \nCAST(numColumn AS varchar(40)) FROM YourTable\n</code></pre>\n" }, { "answer_id": 56977, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 1, "selected": false, "text": "<p>The easiest way is to pad left:</p>\n\n<pre><code>CREATE FUNCTION PadLeft(@PadString nvarchar(100), @PadLength int)\nRETURNS nvarchar(200)\nAS\nbegin\nreturn replicate(' ',@padlength-len(@PadString)) + @PadString\nend\ngo\nprint dbo.PadLeft('123.456', 20)\nprint dbo.PadLeft('1.23', 20)\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2230/" ]
We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired... I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example: ``` Value ---------- 143.55 3532.13 1.75 ``` How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever". I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control. Thank you.
The [STR function](http://msdn.microsoft.com/en-us/library/ms189527.aspx) has an optional length argument as well as a number-of-decimals one. ``` SELECT STR(123.45, 6, 1) ------ 123.5 (1 row(s) affected) ```
56,954
<p>The code</p> <pre><code>private SomeClass&lt;Integer&gt; someClass; someClass = EasyMock.createMock(SomeClass.class); </code></pre> <p>gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass&lt;Integer&gt;".</p>
[ { "answer_id": 56996, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>The two obvious routes are to suppress the warning or mock a subclass.</p>\n\n<pre><code>private static class SomeClass_Integer extends SomeClass&lt;Integer&gt;();\nprivate SomeClass&lt;Integer&gt; someClass;\n...\n someClass = EasyMock.createMock(SomeClass_Integer.class);\n</code></pre>\n\n<p>(Disclaimer: Not even attempted to compile this code, nor have I used EasyMock.)</p>\n" }, { "answer_id": 57247, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 2, "selected": false, "text": "<p>You can annotate the test method with <code>@SuppressWarnings(\"unchecked\")</code>. I agree this is some what of a hack but in my opinion it's acceptable on test code. </p>\n\n<pre><code>@Test\n@SuppressWarnings(\"unchecked\")\npublic void someTest() {\n SomeClass&lt;Integer&gt; someClass = EasyMock.createMock(SomeClass.class);\n}\n</code></pre>\n" }, { "answer_id": 396122, "author": "Barend", "author_id": 49489, "author_profile": "https://Stackoverflow.com/users/49489", "pm_score": 5, "selected": false, "text": "<p>AFAIK, you can't avoid the unchecked warning when a class name literal is involved, and the <code>SuppressWarnings</code> annotation is the only way to handle this.</p>\n\n<p>Note that it is good form to narrow the scope of the <code>SuppressWarnings</code> annotation as much as possible. You can apply this annotation to a single local variable assignment:</p>\n\n<pre><code>public void testSomething() {\n\n @SuppressWarnings(\"unchecked\")\n Foo&lt;Integer&gt; foo = EasyMock.createMock(Foo.class);\n\n // Rest of test method may still expose other warnings\n}\n</code></pre>\n\n<p>or use a helper method:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\nprivate static &lt;T&gt; Foo&lt;T&gt; createFooMock() {\n return (Foo&lt;T&gt;)EasyMock.createMock(Foo.class);\n}\n\npublic void testSomething() {\n Foo&lt;String&gt; foo = createFooMock();\n\n // Rest of test method may still expose other warnings\n}\n</code></pre>\n" }, { "answer_id": 8897152, "author": "Barry John Williams", "author_id": 1154244, "author_profile": "https://Stackoverflow.com/users/1154244", "pm_score": 4, "selected": false, "text": "<p>I worked around this problem by introducing a subclass, e.g.</p>\n\n<pre><code>private abstract class MySpecialString implements MySpecial&lt;String&gt;{};\n</code></pre>\n\n<p>Then create a mock of that abstract class:</p>\n\n<pre><code>MySpecial&lt;String&gt; myMock = createControl().createMock(MySpecialString.class);\n</code></pre>\n" }, { "answer_id": 20427511, "author": "chim", "author_id": 673282, "author_profile": "https://Stackoverflow.com/users/673282", "pm_score": 1, "selected": false, "text": "<p>I know this goes against the question, but why not create a List rather than a Mock List?</p>\n\n<p>It's less code and easier to work with, for instance if you want to add items to the list.</p>\n\n<pre><code>MyItem myItem = createMock(myItem.class);\nList&lt;MyItem&gt; myItemList = new ArrayList&lt;MyItem&gt;();\nmyItemList.add(myItem);\n</code></pre>\n\n<p>Instead of </p>\n\n<pre><code>MyItem myItem = createMock(myItem.class);\n@SuppressWarnings(\"unchecked\")\nList&lt;MyItem&gt; myItemList = createMock(ArrayList.class);\nexpect(myItemList.get(0)).andReturn(myItem);\nreplay(myItemList);\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ]
The code ``` private SomeClass<Integer> someClass; someClass = EasyMock.createMock(SomeClass.class); ``` gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".
AFAIK, you can't avoid the unchecked warning when a class name literal is involved, and the `SuppressWarnings` annotation is the only way to handle this. Note that it is good form to narrow the scope of the `SuppressWarnings` annotation as much as possible. You can apply this annotation to a single local variable assignment: ``` public void testSomething() { @SuppressWarnings("unchecked") Foo<Integer> foo = EasyMock.createMock(Foo.class); // Rest of test method may still expose other warnings } ``` or use a helper method: ``` @SuppressWarnings("unchecked") private static <T> Foo<T> createFooMock() { return (Foo<T>)EasyMock.createMock(Foo.class); } public void testSomething() { Foo<String> foo = createFooMock(); // Rest of test method may still expose other warnings } ```
56,968
<p>I'm trying to attach an instance of UIScrollbar component to a dynamic text field inside of an instance of a class that is being made after some XML is loaded. The scroll bar component is getting properly attached, as the size of the slider varies depending on the amount of content in the text field, however, it won't scroll.</p> <p>Here's the code:</p> <pre><code>function xmlLoaded(evt:Event):void { //do some stuff for(var i:int = 0; i &lt; numProfiles; i++) { var thisProfile:profile = new profile(); thisProfile.alpha = 0; thisProfile.x = 0; thisProfile.y = 0; thisProfile.name = "profile" + i; profilecontainer.addChild(thisProfile); thisProfile.profiletextholder.profilename.htmlText = profiles[i].attribute("name"); thisProfile.profiletextholder.profiletext.htmlText = profiles[i].profiletext; //add scroll bar var vScrollBar:UIScrollBar = new UIScrollBar(); vScrollBar.direction = ScrollBarDirection.VERTICAL; vScrollBar.move(thisProfile.profiletextholder.profiletext.x + thisProfile.profiletextholder.profiletext.width, thisProfile.profiletextholder.profiletext.y); vScrollBar.height = thisProfile.profiletextholder.profiletext.height; vScrollBar.scrollTarget = thisProfile.profiletextholder.profiletext; vScrollBar.name = "scrollbar"; vScrollBar.update(); vScrollBar.visible = (thisProfile.profiletextholder.profiletext.maxScrollV &gt; 1); thisProfile.profiletextholder.addChild(vScrollBar); //do some more stuff } } </code></pre> <p>I've also tried it with a UIScrollBar component within the movieclip/class itself, and it still doesn't work. Any ideas?</p>
[ { "answer_id": 57197, "author": "Jeff Winkworth", "author_id": 1306, "author_profile": "https://Stackoverflow.com/users/1306", "pm_score": 0, "selected": false, "text": "<p>Have you tried putting the UI scrollbar onto the stage, binding it to the textfield at design time, and then calling update() during the loaded event?</p>\n\n<p>I have had some <em>interesting</em> experiences in the past with dynamically creating UIScrollbars at runtime.</p>\n" }, { "answer_id": 74302, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 0, "selected": false, "text": "<p>In your first example have you tried putting the \n<code>vScrollBar.update();</code> \nstatement <strong>after</strong> the \n<code>addChild(vScollbar);</code> \n?</p>\n" }, { "answer_id": 74342, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 2, "selected": false, "text": "<p>You might try adding the scrollbar once your textfield is initialized from a separate function similar to this:</p>\n\n<pre><code>private function assignScrollBar(tf:TextField, sb:UIScrollBar):void {\n trace(\"assigning scrollbar\");\n sb.move(tf.x + tf.width, tf.y);\n sb.setSize(15, tf.height);\n sb.direction = ScrollBarDirection.VERTICAL;\n sb.scrollTarget = tf;\n addChild(sb);\n sb.update(); \n}\n</code></pre>\n\n<p>That is how I currently doing it.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to attach an instance of UIScrollbar component to a dynamic text field inside of an instance of a class that is being made after some XML is loaded. The scroll bar component is getting properly attached, as the size of the slider varies depending on the amount of content in the text field, however, it won't scroll. Here's the code: ``` function xmlLoaded(evt:Event):void { //do some stuff for(var i:int = 0; i < numProfiles; i++) { var thisProfile:profile = new profile(); thisProfile.alpha = 0; thisProfile.x = 0; thisProfile.y = 0; thisProfile.name = "profile" + i; profilecontainer.addChild(thisProfile); thisProfile.profiletextholder.profilename.htmlText = profiles[i].attribute("name"); thisProfile.profiletextholder.profiletext.htmlText = profiles[i].profiletext; //add scroll bar var vScrollBar:UIScrollBar = new UIScrollBar(); vScrollBar.direction = ScrollBarDirection.VERTICAL; vScrollBar.move(thisProfile.profiletextholder.profiletext.x + thisProfile.profiletextholder.profiletext.width, thisProfile.profiletextholder.profiletext.y); vScrollBar.height = thisProfile.profiletextholder.profiletext.height; vScrollBar.scrollTarget = thisProfile.profiletextholder.profiletext; vScrollBar.name = "scrollbar"; vScrollBar.update(); vScrollBar.visible = (thisProfile.profiletextholder.profiletext.maxScrollV > 1); thisProfile.profiletextholder.addChild(vScrollBar); //do some more stuff } } ``` I've also tried it with a UIScrollBar component within the movieclip/class itself, and it still doesn't work. Any ideas?
You might try adding the scrollbar once your textfield is initialized from a separate function similar to this: ``` private function assignScrollBar(tf:TextField, sb:UIScrollBar):void { trace("assigning scrollbar"); sb.move(tf.x + tf.width, tf.y); sb.setSize(15, tf.height); sb.direction = ScrollBarDirection.VERTICAL; sb.scrollTarget = tf; addChild(sb); sb.update(); } ``` That is how I currently doing it.
56,974
<p>In the following snippet:</p> <pre><code>public class a { public void otherMethod(){} public void doStuff(String str, InnerClass b){} public void method(a){ doStuff("asd", new InnerClass(){ public void innerMethod(){ otherMethod(); } } ); } } </code></pre> <p>Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is <code>outer.otherMethod()</code>, or something of the like, but can't seem to find anything.</p>
[ { "answer_id": 56987, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 9, "selected": true, "text": "<p>In general you use <code>OuterClassName.this</code> to refer to the enclosing instance of the outer class.</p>\n\n<p>In your example that would be <code>a.this.otherMethod()</code></p>\n" }, { "answer_id": 56992, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 6, "selected": false, "text": "<pre><code>OuterClassName.this.outerClassMethod();\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
In the following snippet: ``` public class a { public void otherMethod(){} public void doStuff(String str, InnerClass b){} public void method(a){ doStuff("asd", new InnerClass(){ public void innerMethod(){ otherMethod(); } } ); } } ``` Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is `outer.otherMethod()`, or something of the like, but can't seem to find anything.
In general you use `OuterClassName.this` to refer to the enclosing instance of the outer class. In your example that would be `a.this.otherMethod()`
56,975
<p>I'm currently looping through a datareader and calling the System.Net.Mail.SmtpClient's Send() method. The problem with this is that it's slow. Each email takes about 5-10 seconds to send (it's possible this is just an issue with my host). I had to override the executionTimeout default in my web.config file (it defaults to 90 seconds) like this:</p> <pre><code> &lt;httpRuntime executionTimeout="3000" /&gt; </code></pre> <p>One caveat: I'm on a shared host, so I don't think it is possible for me to send using the PickupDirectoryFromIis option (at least, it gave me errors when I turned it on).</p>
[ { "answer_id": 56988, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 4, "selected": true, "text": "<p>You could send the mail asynchronous. That way the timeout should not interrupt your sending.</p>\n\n<p>This article should help you get started with that: <a href=\"http://www.eggheadcafe.com/articles/20030720.asp\" rel=\"nofollow noreferrer\">Sending Emails Asynchronously in C#</a>.</p>\n\n<p>There is another approach here: <a href=\"http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx\" rel=\"nofollow noreferrer\">http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx</a></p>\n\n<p>And off course there are several commercial clients available, but the only one that i have tried and can recommend is <a href=\"http://www.aspnetemail.com/\" rel=\"nofollow noreferrer\">http://www.aspnetemail.com/</a></p>\n" }, { "answer_id": 57009, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 0, "selected": false, "text": "<p>Definitely spawn it off on a background worker process so they go out asynchronously. </p>\n\n<p>BTW, 5-10 seconds per e-mail seems way slow to me. On my server it takes just fractions of a second per e-mail. </p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965/" ]
I'm currently looping through a datareader and calling the System.Net.Mail.SmtpClient's Send() method. The problem with this is that it's slow. Each email takes about 5-10 seconds to send (it's possible this is just an issue with my host). I had to override the executionTimeout default in my web.config file (it defaults to 90 seconds) like this: ``` <httpRuntime executionTimeout="3000" /> ``` One caveat: I'm on a shared host, so I don't think it is possible for me to send using the PickupDirectoryFromIis option (at least, it gave me errors when I turned it on).
You could send the mail asynchronous. That way the timeout should not interrupt your sending. This article should help you get started with that: [Sending Emails Asynchronously in C#](http://www.eggheadcafe.com/articles/20030720.asp). There is another approach here: <http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx> And off course there are several commercial clients available, but the only one that i have tried and can recommend is <http://www.aspnetemail.com/>
57,010
<p>Please, now that I've re-written the question, and before it suffers from further <a href="https://stackoverflow.com/questions/56103/fastest-gun-in-the-west-problem">fast-gun answers</a> or premature closure by <a href="https://stackoverflow.com/users/905/keith">eager editors</a> let me point out that this is not a duplicate of <a href="https://stackoverflow.com/questions/9673/remove-duplicates-from-array">this question</a>. I know how to remove duplicates from an array.</p> <p>This question is about removing <strong>sequences</strong> from an array, not duplicates in the strict sense.</p> <p>Consider this sequence of elements in an array;</p> <pre><code>[0] a [1] a [2] b [3] c [4] c [5] a [6] c [7] d [8] c [9] d </code></pre> <p>In this example I want to obtain the following...</p> <pre><code>[0] a [1] b [2] c [3] a [4] c [5] d </code></pre> <p>Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element.</p> <p>Further, notice that when two lines repeat they should be reduced to one set (of two lines).</p> <pre><code>[0] c [1] d [2] c [3] d </code></pre> <p>...reduces to...</p> <pre><code>[0] c [1] d </code></pre> <p>I'm coding in C# but algorithms in any language appreciated.</p>
[ { "answer_id": 57013, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>I would dump them all into your favorite Set implementation.</p>\n\n<p>EDIT: Now that I understand the question, your original solution looks like the best way to do this. Just loop through the array once, keeping an array of flags to mark which elements to keep, plus a counter to keep track to the size of the new array. Then loop through again to copy all the keepers to a new array.</p>\n" }, { "answer_id": 57022, "author": "Terry", "author_id": 2171, "author_profile": "https://Stackoverflow.com/users/2171", "pm_score": 0, "selected": false, "text": "<p>I agree that if you can just dump the strings into a Set, then that might be the easiest solution. </p>\n\n<p>If you don't have access to a Set implementation for some reason, I would just sort the strings alphabetically and then go through once and remove the duplicates. How to sort them and remove duplicates from the list will depend on what language and environment you are running your code. </p>\n\n<p>EDIT: Oh, ick.... I see based on your clarification that you expect that patterns might occur even over separate lines. My approach won't solve your problem. Sorry. Here is a question for you. If I had the following file.</p>\n\n<p>a</p>\n\n<p>a</p>\n\n<p>b</p>\n\n<p>c</p>\n\n<p>c</p>\n\n<p>a</p>\n\n<p>a</p>\n\n<p>b</p>\n\n<p>c</p>\n\n<p>c</p>\n\n<p>Would you expect it to simplify to </p>\n\n<p>a</p>\n\n<p>b</p>\n\n<p>c</p>\n" }, { "answer_id": 57181, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "<p><strong>EDIT: made some changes and new suggestions</strong></p>\n\n<p>What about a sliding window...</p>\n\n<pre><code>REMOVE LENGTH 2: (no other length has other matches)\n//the lower case letters are the matches\nABCBAbabaBBCbcbcbVbvBCbcbcAB \n__ABCBABABABBCBCBCBVBVBCBCBCAB\n\nREMOVE LENGTH 1 (duplicate characters):\n//* denote that a string was removed to prevent continual contraction\n//of the string, unless this is what you want.\nABCBA*BbC*V*BC*AB\n_ABCBA*BBC*V*BC*AB\n\nRESULT:\nABCBA*B*C*V*BC*AB == ABCBABCVBCAB\n</code></pre>\n\n<p>This is of course starting with length=2, increase it to L/2 and iterate down. </p>\n\n<p>I'm also thinking of two other approaches:</p>\n\n<ol>\n<li><strong>digraph</strong> - Set a stateful digraph with the data and iterate over it with the string, if a cycle is found you'll have a duplication. I'm not sure how easy it is check check for these cycles... possibly some dynamic programming, so it could be equivlent to method 2 below. I'm going to have to think about this one as well longer.</li>\n<li><strong>distance matrix</strong> - using a levenstein distance matrix you might be able to detect duplication from diagonal movement (off the diagonal) with cost 0. This could indicate duplication of data. I will have to think about this more.</li>\n</ol>\n" }, { "answer_id": 57410, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 3, "selected": true, "text": "<p>Here's C# app i wrote that solves this problem.</p>\n\n<p><strong>takes</strong><br>\naabccacdcd </p>\n\n<p><strong>outputs</strong><br>\nabcacd </p>\n\n<p>Probably looks pretty messy, took me a bit to get my head around the dynamic pattern length bit.</p>\n\n<pre><code>class Program\n{\n private static List&lt;string&gt; values;\n private const int MAX_PATTERN_LENGTH = 4;\n\n static void Main(string[] args)\n {\n values = new List&lt;string&gt;();\n values.AddRange(new string[] { \"a\", \"b\", \"c\", \"c\", \"a\", \"c\", \"d\", \"c\", \"d\" });\n\n\n for (int i = MAX_PATTERN_LENGTH; i &gt; 0; i--)\n {\n RemoveDuplicatesOfLength(i);\n }\n\n foreach (string s in values)\n {\n Console.WriteLine(s);\n }\n }\n\n private static void RemoveDuplicatesOfLength(int dupeLength)\n {\n for (int i = 0; i &lt; values.Count; i++)\n {\n if (i + dupeLength &gt; values.Count)\n break;\n\n if (i + dupeLength + dupeLength &gt; values.Count)\n break;\n\n var patternA = values.GetRange(i, dupeLength);\n var patternB = values.GetRange(i + dupeLength, dupeLength);\n\n bool isPattern = ComparePatterns(patternA, patternB);\n\n if (isPattern)\n {\n values.RemoveRange(i, dupeLength);\n }\n }\n }\n\n private static bool ComparePatterns(List&lt;string&gt; pattern, List&lt;string&gt; candidate)\n {\n for (int i = 0; i &lt; pattern.Count; i++)\n {\n if (pattern[i] != candidate[i])\n return false;\n }\n\n return true;\n }\n}\n</code></pre>\n\n<p><em>fixed the initial values to match the questions values</em></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200/" ]
Please, now that I've re-written the question, and before it suffers from further [fast-gun answers](https://stackoverflow.com/questions/56103/fastest-gun-in-the-west-problem) or premature closure by [eager editors](https://stackoverflow.com/users/905/keith) let me point out that this is not a duplicate of [this question](https://stackoverflow.com/questions/9673/remove-duplicates-from-array). I know how to remove duplicates from an array. This question is about removing **sequences** from an array, not duplicates in the strict sense. Consider this sequence of elements in an array; ``` [0] a [1] a [2] b [3] c [4] c [5] a [6] c [7] d [8] c [9] d ``` In this example I want to obtain the following... ``` [0] a [1] b [2] c [3] a [4] c [5] d ``` Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element. Further, notice that when two lines repeat they should be reduced to one set (of two lines). ``` [0] c [1] d [2] c [3] d ``` ...reduces to... ``` [0] c [1] d ``` I'm coding in C# but algorithms in any language appreciated.
Here's C# app i wrote that solves this problem. **takes** aabccacdcd **outputs** abcacd Probably looks pretty messy, took me a bit to get my head around the dynamic pattern length bit. ``` class Program { private static List<string> values; private const int MAX_PATTERN_LENGTH = 4; static void Main(string[] args) { values = new List<string>(); values.AddRange(new string[] { "a", "b", "c", "c", "a", "c", "d", "c", "d" }); for (int i = MAX_PATTERN_LENGTH; i > 0; i--) { RemoveDuplicatesOfLength(i); } foreach (string s in values) { Console.WriteLine(s); } } private static void RemoveDuplicatesOfLength(int dupeLength) { for (int i = 0; i < values.Count; i++) { if (i + dupeLength > values.Count) break; if (i + dupeLength + dupeLength > values.Count) break; var patternA = values.GetRange(i, dupeLength); var patternB = values.GetRange(i + dupeLength, dupeLength); bool isPattern = ComparePatterns(patternA, patternB); if (isPattern) { values.RemoveRange(i, dupeLength); } } } private static bool ComparePatterns(List<string> pattern, List<string> candidate) { for (int i = 0; i < pattern.Count; i++) { if (pattern[i] != candidate[i]) return false; } return true; } } ``` *fixed the initial values to match the questions values*
57,020
<p>Was considering the <code>System.Collections.ObjectModel ObservableCollection&lt;T&gt;</code> class. This one is strange because </p> <ul> <li>it has an Add Method which takes <strong>one</strong> item only. No AddRange or equivalent. </li> <li>the Notification event arguments has a NewItems property, which is a <strong>IList</strong> (of objects.. not T)</li> </ul> <p>My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?</p> <p><em>Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.</em></p> <hr> <p>Related Q:<br> <a href="https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579">https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each</a></p>
[ { "answer_id": 57029, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Inherit from List&lt;T> and override the Add() and AddRange() methods to raise an event?</p>\n" }, { "answer_id": 57036, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 2, "selected": false, "text": "<p>If you're wanting to inherit from a collection of some sort, you're probably better off inheriting from System.Collections.ObjectModel.Collection because it provides virtual methods for override. You'll have to shadow methods off of List if you go that route.</p>\n\n<p>I'm not aware of any built-in collections that provide this functionality, though I'd welcome being corrected :)</p>\n" }, { "answer_id": 57069, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 4, "selected": false, "text": "<p>It seems that the <code>INotifyCollectionChanged</code> interface allows for updating when multiple items were added, so I'm not sure why <code>ObservableCollection&lt;T&gt;</code> doesn't have an <code>AddRange</code>. You could make an extension method for <code>AddRange</code>, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from <code>ObservableCollection&lt;T&gt;</code> as follows:</p>\n\n<pre><code>public class MyObservableCollection&lt;T&gt; : ObservableCollection&lt;T&gt;\n{\n // matching constructors ...\n\n bool isInAddRange = false;\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n // intercept this when it gets called inside the AddRange method.\n if (!isInAddRange) \n base.OnCollectionChanged(e);\n }\n\n\n public void AddRange(IEnumerable&lt;T&gt; items)\n {\n isInAddRange = true;\n foreach (T item in items)\n Add(item);\n isInAddRange = false;\n\n var e = new NotifyCollectionChangedEventArgs(\n NotifyCollectionChangedAction.Add,\n items.ToList());\n base.OnCollectionChanged(e);\n }\n}\n</code></pre>\n" }, { "answer_id": 58255, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": false, "text": "<p>Not only is <code>System.Collections.ObjectModel.Collection&lt;T&gt;</code> a good bet, but in the help docs there's <a href=\"http://msdn.microsoft.com/en-us/library/ms132397.aspx\" rel=\"nofollow noreferrer\">an example</a> of how to override its various protected methods in order to get notification. (Scroll down to Example 2.)</p>\n" }, { "answer_id": 61564, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "<p>Well the idea is same as that of fryguybob - kinda weird that ObservableCollection is kinda half-done. The event args for this thing do not even use Generics.. making me use an IList (that's so.. yesterday :)\nTested Snippet follows...</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\n\nnamespace MyNamespace\n{\n public class ObservableCollectionWithBatchUpdates&lt;T&gt; : ObservableCollection&lt;T&gt;\n {\n public void AddRange(ICollection&lt;T&gt; obNewItems)\n {\n IList&lt;T&gt; obAddedItems = new List&lt;T&gt;();\n foreach (T obItem in obNewItems)\n {\n Items.Add(obItem);\n obAddedItems.Add(obItem);\n }\n NotifyCollectionChangedEventArgs obEvtArgs = new NotifyCollectionChangedEventArgs(\n NotifyCollectionChangedAction.Add, \n obAddedItems as System.Collections.IList);\n base.OnCollectionChanged(obEvtArgs);\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 851197, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "<p>If you use any of the above implementations that send an add range command and bind the observablecolletion to a listview you will get this nasty error. </p>\n\n<pre>\nNotSupportedException\n at System.Windows.Data.ListCollectionView.ValidateCollectionChangedEventArgs(NotifyCollectionChangedEventArgs e)\n at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)\n at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)\n at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n</pre> \n\n<p>The implementation I have gone with uses the Reset event that is more evenly implemented around the WPF framework: </p>\n\n<pre><code> public void AddRange(IEnumerable&lt;T&gt; collection)\n {\n foreach (var i in collection) Items.Add(i);\n OnPropertyChanged(\"Count\");\n OnPropertyChanged(\"Item[]\");\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n</code></pre>\n" }, { "answer_id": 1123307, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 0, "selected": false, "text": "<p>Take a look at <a href=\"https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579\">Observable collection with AddRange, RemoveRange and Replace range methods</a> in both C# and VB.</p>\n\n<p>In VB: INotifyCollectionChanging implementation.</p>\n" }, { "answer_id": 1790438, "author": "Boris", "author_id": 217845, "author_profile": "https://Stackoverflow.com/users/217845", "pm_score": 0, "selected": false, "text": "<p>For fast adding you could use:</p>\n\n<pre><code>((List&lt;Person&gt;)this.Items).AddRange(NewItems);\n</code></pre>\n" }, { "answer_id": 3829525, "author": "Akash Kava", "author_id": 85597, "author_profile": "https://Stackoverflow.com/users/85597", "pm_score": 2, "selected": false, "text": "<p>I have seen this kind of question many times, and I wonder why even Microsoft is promoting ObservableCollection everywhere where else there is a better collection already available thats.. </p>\n\n<blockquote>\n <p><code>BindingList&lt;T&gt;</code></p>\n</blockquote>\n\n<p>Which allows you to turn off notifications and do bulk operations and then turn on the notifications. </p>\n" }, { "answer_id": 8837627, "author": "Mo0gles", "author_id": 283512, "author_profile": "https://Stackoverflow.com/users/283512", "pm_score": 2, "selected": false, "text": "<p>Another solution that is similar to the CollectionView pattern:</p>\n\n<pre><code>public class DeferableObservableCollection&lt;T&gt; : ObservableCollection&lt;T&gt;\n{\n private int deferLevel;\n\n private class DeferHelper&lt;T&gt; : IDisposable\n {\n private DeferableObservableCollection&lt;T&gt; owningCollection;\n public DeferHelper(DeferableObservableCollection&lt;T&gt; owningCollection)\n {\n this.owningCollection = owningCollection;\n }\n\n public void Dispose()\n {\n owningCollection.EndDefer();\n }\n }\n\n private void EndDefer()\n {\n if (--deferLevel &lt;= 0)\n {\n deferLevel = 0;\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n }\n\n public IDisposable DeferNotifications()\n {\n deferLevel++;\n return new DeferHelper&lt;T&gt;(this);\n }\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (deferLevel == 0) // Not in a defer just send events as normally\n {\n base.OnCollectionChanged(e);\n } // Else notify on EndDefer\n }\n}\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
Was considering the `System.Collections.ObjectModel ObservableCollection<T>` class. This one is strange because * it has an Add Method which takes **one** item only. No AddRange or equivalent. * the Notification event arguments has a NewItems property, which is a **IList** (of objects.. not T) My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec? *Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.* --- Related Q: [https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each](https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579)
It seems that the `INotifyCollectionChanged` interface allows for updating when multiple items were added, so I'm not sure why `ObservableCollection<T>` doesn't have an `AddRange`. You could make an extension method for `AddRange`, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from `ObservableCollection<T>` as follows: ``` public class MyObservableCollection<T> : ObservableCollection<T> { // matching constructors ... bool isInAddRange = false; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { // intercept this when it gets called inside the AddRange method. if (!isInAddRange) base.OnCollectionChanged(e); } public void AddRange(IEnumerable<T> items) { isInAddRange = true; foreach (T item in items) Add(item); isInAddRange = false; var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, items.ToList()); base.OnCollectionChanged(e); } } ```
57,054
<p>I've got a collection that implements an interface that extends both IList&lt;T> and List. </p> <pre><code>public Interface IMySpecialCollection : IList&lt;MyObject&gt;, IList { ... } </code></pre> <p>That means I have two versions of the indexer. </p> <p>I wish the generic implementation to be used, so I implement that one normally:</p> <pre><code>public MyObject this[int index] { .... } </code></pre> <p>I only need the IList version for serialization, so I implement it explicitly, to keep it hidden:</p> <pre><code>object IList.this[int index] { ... } </code></pre> <p>However, in my unit tests, the following</p> <pre><code>MyObject foo = target[0]; </code></pre> <p>results in a compiler error</p> <blockquote> <p>The call is ambiguous between the following methods or properties</p> </blockquote> <p>I'm a bit surprised at this; I believe I've done it before and it works fine. What am I missing here? How can I get IList&lt;T> and IList to coexist within the same interface?</p> <p><strong>Edit</strong> IList&lt;T> does <em>not</em> implement IList, and I <strong>must</strong> implement IList for serialization. I'm not interested in workarounds, I want to know what I'm missing.</p> <p><strong>Edit again</strong>: I've had to drop IList from the interface and move it on my class. I don't want to do this, as classes that implement the interface are eventually going to be serialized to Xaml, which requires collections to implement IDictionary or IList...</p>
[ { "answer_id": 57072, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>List&lt;T> implies IList, so it's a bad idea to use both in the same class.</p>\n" }, { "answer_id": 57084, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 1, "selected": false, "text": "<p>Unfortunately you can't declare two indexers with the same parameter list. The following paragraph is taken from here <a href=\"http://msdn.microsoft.com/en-us/library/2549tw02.aspx#languageReferenceRemarksToggle\" rel=\"nofollow noreferrer\" title=\"C# Programming Guide - Using Indexers\">C# Programming Guide - Using Indexers \"Remarks\" section</a>:</p>\n\n<blockquote>\n <p>The signature of an indexer consists of the number and types of its formal parameters. It does not include the indexer type or the names of the formal parameters. If you declare more than one indexer in the same class, they must have different signatures.</p>\n</blockquote>\n\n<p>You will have to declare a different set of parameters if you wish to use the second indexer.</p>\n" }, { "answer_id": 57093, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": -1, "selected": false, "text": "<p>Change your generic implementation to...</p>\n\n<pre><code>T IList&lt;T&gt;.this[int index] { get; set; }\n</code></pre>\n\n<p>This explicitly says which 'this' is which.</p>\n" }, { "answer_id": 57166, "author": "Darryl Braaten", "author_id": 1834, "author_profile": "https://Stackoverflow.com/users/1834", "pm_score": 3, "selected": true, "text": "<p>You can't do this with </p>\n\n<p><code>public interface IMySpecialCollection : IList&lt;MyObject&gt;, IList { ... }</code></p>\n\n<p>But you can do what you want with a class, you will need to make the implementations for one of the interfaces explicit. In my example I made IList explicit.</p>\n\n<p><code>public class MySpecialCollection : IList&lt;MyObject&gt;, IList { ... }</code></p>\n\n<p><code>IList&lt;object&gt; myspecialcollection = new MySpecialCollection();\n IList list = (IList)myspecialcollection;</code></p>\n\n<p>Have you considered having IMySpecialCollection implement ISerializable for serialization?\nSupporting multiple collection types seems a bit wrong to me. You may also want to look at casting yout IList to IEnumerable for serialization since IList just wraps IEnumerable and ICollection. </p>\n" }, { "answer_id": 1669935, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>This is a dupe of <a href=\"https://stackoverflow.com/questions/1552456/icollection-vs-icollectiont-ambiguity-between-icollectiont-count-and-icollec\">my question here</a></p>\n\n<p>To summarise, if you do this, it solves the problem:</p>\n\n<pre><code>public Interface IMySpecialCollection : IList&lt;MyObject&gt;, IList\n{\n new MyObject this[int index];\n ... \n}\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a collection that implements an interface that extends both IList<T> and List. ``` public Interface IMySpecialCollection : IList<MyObject>, IList { ... } ``` That means I have two versions of the indexer. I wish the generic implementation to be used, so I implement that one normally: ``` public MyObject this[int index] { .... } ``` I only need the IList version for serialization, so I implement it explicitly, to keep it hidden: ``` object IList.this[int index] { ... } ``` However, in my unit tests, the following ``` MyObject foo = target[0]; ``` results in a compiler error > > The call is ambiguous between the > following methods or properties > > > I'm a bit surprised at this; I believe I've done it before and it works fine. What am I missing here? How can I get IList<T> and IList to coexist within the same interface? **Edit** IList<T> does *not* implement IList, and I **must** implement IList for serialization. I'm not interested in workarounds, I want to know what I'm missing. **Edit again**: I've had to drop IList from the interface and move it on my class. I don't want to do this, as classes that implement the interface are eventually going to be serialized to Xaml, which requires collections to implement IDictionary or IList...
You can't do this with `public interface IMySpecialCollection : IList<MyObject>, IList { ... }` But you can do what you want with a class, you will need to make the implementations for one of the interfaces explicit. In my example I made IList explicit. `public class MySpecialCollection : IList<MyObject>, IList { ... }` `IList<object> myspecialcollection = new MySpecialCollection(); IList list = (IList)myspecialcollection;` Have you considered having IMySpecialCollection implement ISerializable for serialization? Supporting multiple collection types seems a bit wrong to me. You may also want to look at casting yout IList to IEnumerable for serialization since IList just wraps IEnumerable and ICollection.
57,091
<p>Let's say I have a parent DIV. Inside, there are three child DIVs: header, content and footer. Header is attached to the top of the parent and fills it horizontally. Footer is attached to the bottom of the parent and fills it horizontally too. Content is supposed to fill all the space between header and footer.</p> <p>The parent has to have a fixed width and height. The content DIV has to fill all available space between header and footer. When the content size of the content DIV exceeds the space between header and footer, <strong><em>the content DIV should display scrollbars and allow appropriate scrolling</em></strong> so that the footer contents should never be obscured nor the footer obscure content.</p> <p>Now comes the hard part: <strong><em>you don't know the height of the header nor footer beforehand</em></strong> (eg. header and footer are filled dynamically). How can content be positioned <strong><em>without using JavaScript</em></strong>?</p> <p>Example:</p> <pre><code>&lt;div style="position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;"&gt; &lt;div style="background-color: #80ff80; position : absolute; left : 0; right : 0; top : 0;"&gt; header &lt;/div&gt; &lt;div style="background-color: #8080ff; overflow : auto; position : absolute;"&gt; content (how to position it?) &lt;/div&gt; &lt;div style="background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;"&gt; footer &lt;/div&gt; &lt;/div&gt; </code></pre> <hr> <p><strong>To clarify this event further</strong> - the target layout that I'm trying to achieve will be used in a business web application. <strong><em>The parent DIV will have a fixed, but unknown size</em></strong> (for instance, it will be exactly the size of the browser viewport, sizing itself along with sizing the browser window by the user). Let's call the parent DIV a "screen".</p> <p>The header will contain a set of filtering controls (like textboxes, drop down lists and a "filter" button) that should wrap to the next line if there is insufficient horizontal space (so its height can change any time to accomodate line breaking). <strong><em>The header should always be visible and attached to the top</em></strong> of the "screen".</p> <p>The footer will contain a set of buttons, like on a dialog window. These too can wrap to next line if there is not enough space horizontally. <strong><em>The footer must be attached to the bottom</em></strong> of the "screen" to be accessible and visible at all times.</p> <p>The content will contain "screen" contents, like dialog fields etc. If there are too few fields, the rest of the content will be "blank" (in this case the footer should not begin right after the content, but still be attached to the bottom of the "screen" which is fixed size). If there are too many fields, <strong><em>the content DIV will provide scrollbar(s)</em></strong> to access the hidden controls (in this case the content DIV must not extend itself below the footer, as the scrollbar would be partially hidden). </p> <p>I hope this clarifies the question a little bit further, as I have too low rep to enter comments to your repsonses.</p>
[ { "answer_id": 57119, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 0, "selected": false, "text": "<p>Absolute positioning is messing you up. Try something like this:</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div id=\"wrapper\"&gt;\n &lt;div id=\"header\"&gt;\n header\n &lt;/div&gt;\n &lt;div id=\"content\"&gt;\n content\n &lt;/div&gt;\n &lt;div id=\"footer\"&gt;\n footer\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#wrapper {\n width: 200px;\n height: 200px;\n overflow: visible;\n background: #e0e0ff;\n}\n#header {\n background: #80ff80;\n}\n#content {\n background: #8080ff;\n}\n#footer {\n background: #ff8080;\n}\n</code></pre>\n\n<p>edit: perhaps I misunderstood, do you want everything to fit into the 200x200px box or do you want the box to increase its height to fit the content?</p>\n" }, { "answer_id": 57121, "author": "busse", "author_id": 5702, "author_profile": "https://Stackoverflow.com/users/5702", "pm_score": 0, "selected": false, "text": "<p>Does the parent need to stay at a fixed height?</p>\n\n<pre><code>&lt;div style=\"position : relative; width : 200px; background-color : #e0e0ff; overflow : hidden;\"&gt;\n&lt;div style=\"float: left; clear: left; background-color: #80ff80;\"&gt;\nheader \n&lt;/div&gt;\n&lt;div style=\"float: left; clear: left; background-color: #8080ff; overflow : auto; \"&gt;\ncontent (how to position it?)\n&lt;BR /&gt;taller\n&lt;BR /&gt;taller\n&lt;BR /&gt;taller\n&lt;BR /&gt;taller\n&lt;BR /&gt;taller\n&lt;BR /&gt;taller\n&lt;BR /&gt;taller\n&lt;BR /&gt;taller\n&lt;/div&gt;\n&lt;div style=\"float: left; clear: left; background-color: #ff8080;\"&gt;\nfooter \n&lt;BR /&gt;taller\n&lt;/div&gt; \n</code></pre>\n\n<p></p>\n\n<p>if the height of the parent is fixed, this is the closest I'd know how to get to it offhand -- still not exactly right if those color blocks (as opposed to just text) are truly important and weren't just for illustrating the boundaries of the DIVs:</p>\n\n<pre><code>&lt;div style=\"position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;\"&gt;\n&lt;div style=\"float: left; clear: left; background-color: #80ff80; \"&gt;\nheader &lt;BR .&gt; taller\n&lt;/div&gt;\n&lt;div style=\"float: left; clear: left; background-color: #8080ff; overflow : auto; \"&gt;\ncontent (how to position it?)&lt;BR /&gt; and another line\n&lt;/div&gt;\n&lt;div style=\"background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;\"&gt;\nfooter &lt;BR /&gt; taller\n&lt;/div&gt; \n</code></pre>\n\n<p></p>\n" }, { "answer_id": 57149, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 2, "selected": false, "text": "<p>I'm going to get downmodded for this, but this sounds like a job for a table.</p>\n\n<p>What you're trying to do is to set the total height of three contiguous divs as a unit, and a 1x3 table with height 100% is actually a cleaner solution.</p>\n" }, { "answer_id": 57635, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 0, "selected": false, "text": "<p>Do you need to have the center div change size? If you're just trying to make sure that it appears that its background (#8080ff) appears between the header and the footer, why not just have the containing div's background be #8080ff. The header and footer background would override that, and the rest of the div's background would be correct.</p>\n" }, { "answer_id": 58800, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 1, "selected": false, "text": "<p>If you can get away with not having the main content scrollable, you might be better using the <a href=\"http://www.themaninblue.com/writing/perspective/2005/08/29/\" rel=\"nofollow noreferrer\">footerStickAlt</a> method to make sure your footer stays at the bottom of the screen or the bottom of the content (if the content extends beyond the bottom of the screen).</p>\n" }, { "answer_id": 21977077, "author": "pschueller", "author_id": 2126792, "author_profile": "https://Stackoverflow.com/users/2126792", "pm_score": 2, "selected": false, "text": "<h2>Pure CSS Solution 1 - Flexbox:</h2>\n\n<p>You can create a column of divs that behave in this way by using the CSS3 <code>display: flex;</code> property (<a href=\"http://www.w3.org/TR/css3-flexbox/\" rel=\"nofollow\">see W3 Specs</a>)</p>\n\n<p>Using a wrapper, you can align everything in a column with the <code>flex-direction: column;</code> declaration and then fill the vertical space with <code>justify content: space-between;</code> and <code>height: 100vh;</code>. Then all you need to do is make your content element expand with <code>flex: 1 0 0;</code> and give it a scrollbar with <code>overflow-y: auto;</code>.</p>\n\n<p><strong><em>Note on browser support</em></strong> - While flexbox is supported by most modern browsers, there are still a few limitations (see: <a href=\"http://caniuse.com/#feat=flexbox\" rel=\"nofollow\">http://caniuse.com/#feat=flexbox</a>). I would recommend using the <code>-webkit-</code> and <code>-ms-</code> prefixes.</p>\n\n<hr>\n\n<p><strong>Working example</strong>: See the following snippet and this <a href=\"http://jsfiddle.net/4LxaP/18/\" rel=\"nofollow\">jsfiddle</a>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\r\n display: -webkit-flex; /* Safari 6.1+ */\r\n display: -ms-flex; /* IE 10 */ \r\n display: flex;\r\n -webkit-flex-direction: column; /* Safari 6.1+ */\r\n -ms-flex-direction: column; /* IE 10 */\r\n flex-direction: column;\r\n -webkit-justify-content: space-between; /* Safari 6.1+ */\r\n -ms-justify-content: space-between; /* IE 10 */\r\n justify-content: space-between; /* Header top, footer bottom */\r\n height: 100vh; /* Fill viewport height */\r\n}\r\nmain {\r\n -webkit-flex: 1 0 0; /* Safari 6.1+ */\r\n -ms-flex: 1 0 0; /* IE 10 */\r\n flex: 1 0 0; /* Grow to fill space */\r\n overflow-y: auto; /* Add scrollbar */\r\n height: 100%; /* Needed to fill space in IE */\r\n}\r\nheader, footer {\r\n -webkit-flex: 0 0 auto; /* Safari 6.1+ */\r\n -ms-flex: 0 0 auto; /* IE 10 */\r\n flex: 0 0 auto;\r\n}\r\n\r\n\r\n\r\n/* Make it look a little nicer */\r\nbody {\r\n margin: 0;\r\n background-color: #8080ff;\r\n}\r\nheader {\r\n background-color: #80ff80; \r\n}\r\nfooter {\r\n background-color: #ff8080;\r\n}\r\np {\r\n margin: 1.25rem;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;body&gt;\r\n &lt;header&gt;\r\n &lt;p&gt;header&lt;/p&gt; \r\n &lt;/header&gt;\r\n &lt;main&gt;\r\n &lt;article&gt;\r\n &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pellentesque lobortis augue, in porta arcu dapibus dapibus. Suspendisse vulputate tempus venenatis. Pellentesque ac euismod urna. Donec dui odio, ullamcorper in posuere eu, laoreet sed nisl. Sed vitae vestibulum leo. Maecenas mattis lacus eget nisl malesuada, quis semper urna ornare. Praesent id mauris nec neque aliquet dignissim.&lt;/p&gt;\r\n &lt;p&gt;Morbi varius dolor at lorem aliquet lacinia. Aliquam id lacinia quam. Sed vel libero felis. Etiam et pellentesque sem. Aenean bibendum, ante quis luctus tincidunt, elit mauris volutpat nisi, et tempus lectus sapien in mauris. Aliquam condimentum nisl ut elit accumsan hendrerit. Morbi mollis turpis est, id tincidunt ipsum rhoncus eget. Fusce in feugiat lacus. Quisque vel massa magna. Mauris varius congue nisl, vitae pellentesque diam ultricies at. Sed ac nibh ac diam tristique venenatis non nec nisl. Vivamus enim eros, pretium at iaculis nec, pharetra non sem. Aenean ac imperdiet odio.&lt;/p&gt;\r\n &lt;p&gt;Morbi varius dolor at lorem aliquet lacinia. Aliquam id lacinia quam. Sed vel libero felis. Etiam et pellentesque sem. Aenean bibendum, ante quis luctus tincidunt, elit mauris volutpat nisi, et tempus lectus sapien in mauris. Aliquam condimentum nisl ut elit accumsan hendrerit. Morbi mollis turpis est, id tincidunt ipsum rhoncus eget. Fusce in feugiat lacus. Quisque vel massa magna. Mauris varius congue nisl, vitae pellentesque diam ultricies at. Sed ac nibh ac diam tristique venenatis non nec nisl. Vivamus enim eros, pretium at iaculis nec, pharetra non sem. Aenean ac imperdiet odio.&lt;/p&gt;\r\n &lt;/article&gt;\r\n &lt;/main&gt;\r\n &lt;footer&gt;\r\n &lt;p&gt;footer&lt;/p&gt; \r\n &lt;/footer&gt;\r\n&lt;/body&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><strong>For more information on how to use flexbox see these guides:</strong></p>\n\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes</a></li>\n<li><a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"nofollow\">https://css-tricks.com/snippets/css/a-guide-to-flexbox/</a></li>\n</ul>\n\n<hr>\n\n<hr>\n\n<h2>Pure CSS Solution 2 - Display Table [Old solution]:</h2>\n\n<p>This can also be done by using the CSS <code>display: table;</code> property (<a href=\"http://www.w3schools.com/cssref/pr_class_display.asp\" rel=\"nofollow\">see W3 Specs</a>).</p>\n\n<p><strong>The HTML:</strong></p>\n\n<pre><code>&lt;div id=\"screen\"&gt;\n &lt;div id=\"header\"&gt;&lt;/div&gt;\n &lt;div id=\"content\"&gt;\n &lt;div id=\"content_frame\"&gt;\n &lt;div id=\"content_wrap\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"footer\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>The CSS:</strong></p>\n\n<pre><code>html, body, #screen, #content, #content_frame {\n height: 100%; /* Make #screen viewport height and #content fill space */\n}\n#screen {\n display: table;\n}\n#header, #content, #footer {\n display: table-row;\n}\n#content_frame {\n overflow-y: auto; /* Add scrollbar */\n position: relative;\n}\n#content_wrap {\n position: absolute; /* Fix problem with overflow in FF */\n}\n</code></pre>\n\n<p>The overflow property is unreliable on css table elements and their children, so I had to nest the content. In this case I was forced to nest twice and use <code>position: absolute;</code> in order to make it work in Firefox. Maybe someone else can come up with a more elegant solution to avoid this 'divitis'.</p>\n\n<p>Here is a functioning <strong><a href=\"http://jsfiddle.net/4LxaP/3/\" rel=\"nofollow\">jsfiddle</a></strong>.</p>\n\n<p><strong><em>Warning:</em></strong> This does not appear to work in Opera 12! The content div takes up 100% of the parent's height which causes the rows to overflow the table (as they did in firefox).</p>\n" }, { "answer_id": 63935260, "author": "JKD", "author_id": 14152908, "author_profile": "https://Stackoverflow.com/users/14152908", "pm_score": 0, "selected": false, "text": "<p>This can be solved by using different techniques. The first one is using media queries. Using them, you can define what your page should look like for each screen size. Secondly, there are several techniques for positioning your footer correctly (sticky footer). Thirdly, you can use different table styles or the flexbox approach to position your content correctly.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5348/" ]
Let's say I have a parent DIV. Inside, there are three child DIVs: header, content and footer. Header is attached to the top of the parent and fills it horizontally. Footer is attached to the bottom of the parent and fills it horizontally too. Content is supposed to fill all the space between header and footer. The parent has to have a fixed width and height. The content DIV has to fill all available space between header and footer. When the content size of the content DIV exceeds the space between header and footer, ***the content DIV should display scrollbars and allow appropriate scrolling*** so that the footer contents should never be obscured nor the footer obscure content. Now comes the hard part: ***you don't know the height of the header nor footer beforehand*** (eg. header and footer are filled dynamically). How can content be positioned ***without using JavaScript***? Example: ``` <div style="position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;"> <div style="background-color: #80ff80; position : absolute; left : 0; right : 0; top : 0;"> header </div> <div style="background-color: #8080ff; overflow : auto; position : absolute;"> content (how to position it?) </div> <div style="background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;"> footer </div> </div> ``` --- **To clarify this event further** - the target layout that I'm trying to achieve will be used in a business web application. ***The parent DIV will have a fixed, but unknown size*** (for instance, it will be exactly the size of the browser viewport, sizing itself along with sizing the browser window by the user). Let's call the parent DIV a "screen". The header will contain a set of filtering controls (like textboxes, drop down lists and a "filter" button) that should wrap to the next line if there is insufficient horizontal space (so its height can change any time to accomodate line breaking). ***The header should always be visible and attached to the top*** of the "screen". The footer will contain a set of buttons, like on a dialog window. These too can wrap to next line if there is not enough space horizontally. ***The footer must be attached to the bottom*** of the "screen" to be accessible and visible at all times. The content will contain "screen" contents, like dialog fields etc. If there are too few fields, the rest of the content will be "blank" (in this case the footer should not begin right after the content, but still be attached to the bottom of the "screen" which is fixed size). If there are too many fields, ***the content DIV will provide scrollbar(s)*** to access the hidden controls (in this case the content DIV must not extend itself below the footer, as the scrollbar would be partially hidden). I hope this clarifies the question a little bit further, as I have too low rep to enter comments to your repsonses.
I'm going to get downmodded for this, but this sounds like a job for a table. What you're trying to do is to set the total height of three contiguous divs as a unit, and a 1x3 table with height 100% is actually a cleaner solution.
57,094
<p>I have ASP.NET web pages for which I want to build automated tests (using WatiN &amp; MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS.</p>
[ { "answer_id": 57105, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": true, "text": "<p>From what I know, you can fire up the dev server from the command prompt with the following path/syntax:</p>\n\n<pre><code>C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]\n</code></pre>\n\n<p>...so I could imagine you could easily use Process.Start() to launch the particulars you need through some code.</p>\n\n<p>Naturally you'll want to adjust that version number to whatever is most recent/desired for you.</p>\n" }, { "answer_id": 57890, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 3, "selected": false, "text": "<p>This is what I used that worked:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing System.Web;\n...\n\n// settings\nstring PortNumber = \"1162\"; // arbitrary unused port #\nstring LocalHostUrl = string.Format(\"http://localhost:{0}\", PortNumber);\nstring PhysicalPath = Environment.CurrentDirectory // the path of compiled web app\nstring VirtualPath = \"\";\nstring RootUrl = LocalHostUrl + VirtualPath; \n\n// create a new process to start the ASP.NET Development Server\nProcess process = new Process();\n\n/// configure the web server\nprocess.StartInfo.FileName = HttpRuntime.ClrInstallDirectory + \"WebDev.WebServer.exe\";\nprocess.StartInfo.Arguments = string.Format(\"/port:{0} /path:\\\"{1}\\\" /virtual:\\\"{2}\\\"\", PortNumber, PhysicalPath, VirtualPath);\nprocess.StartInfo.CreateNoWindow = true;\nprocess.StartInfo.UseShellExecute = false;\n\n// start the web server\nprocess.Start();\n\n// rest of code...\n</code></pre>\n" }, { "answer_id": 19845812, "author": "Michael Sorens", "author_id": 115690, "author_profile": "https://Stackoverflow.com/users/115690", "pm_score": 1, "selected": false, "text": "<p>Building upon @Ray Vega's useful answer, and @James McLachlan's important update for VS2010, here is my implementation to cover VS2012 and fallback to VS2010 if necessary. I also chose not to select only on Environment.Is64BitOperatingSystem because it went awry on my system. That is, I have a 64-bit system but the web server was in the 32-bit folder. My code therefore looks first for the 64-bit folder and falls back to the 32-bit one if necessary.</p>\n\n<pre><code>public void LaunchWebServer(string appWebDir)\n{\n var PortNumber = \"1162\"; // arbitrary unused port #\n var LocalHostUrl = string.Format(\"http://localhost:{0}\", PortNumber);\n var VirtualPath = \"/\";\n\n var exePath = FindLatestWebServer();\n\n var process = new Process\n {\n StartInfo =\n {\n FileName = exePath,\n Arguments = string.Format(\n \"/port:{0} /nodirlist /path:\\\"{1}\\\" /virtual:\\\"{2}\\\"\",\n PortNumber, appWebDir, VirtualPath),\n CreateNoWindow = true,\n UseShellExecute = false\n }\n };\n process.Start();\n}\n\nprivate string FindLatestWebServer()\n{\n var exeCandidates = new List&lt;string&gt;\n {\n BuildCandidatePaths(11, true), // vs2012\n BuildCandidatePaths(11, false),\n BuildCandidatePaths(10, true), // vs2010\n BuildCandidatePaths(10, false)\n };\n return exeCandidates.Where(f =&gt; File.Exists(f)).FirstOrDefault();\n}\n\nprivate string BuildCandidatePaths(int versionNumber, bool isX64)\n{\n return Path.Combine(\n Environment.GetFolderPath(isX64\n ? Environment.SpecialFolder.CommonProgramFiles\n : Environment.SpecialFolder.CommonProgramFilesX86),\n string.Format(\n @\"microsoft shared\\DevServer\\{0}.0\\WebDev.WebServer40.EXE\",\n versionNumber));\n}\n</code></pre>\n\n<p>I am hoping that an informed reader might be able to supply the appropriate incantation for VS2013, as it apparently uses yet a different scheme...</p>\n" }, { "answer_id": 24969218, "author": "Behzad", "author_id": 809974, "author_profile": "https://Stackoverflow.com/users/809974", "pm_score": 0, "selected": false, "text": "<p>You can easily use <strong>Process Explorer</strong> to find complete command line options needed for manually start it.\nStart Process Explorer while debugging your website. For VS2012, expand 'devenv.exe' node. Right-click on 'WebDev.WebServer20.exe' and from there you can see Path and Command Line values.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS.
From what I know, you can fire up the dev server from the command prompt with the following path/syntax: ``` C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT] ``` ...so I could imagine you could easily use Process.Start() to launch the particulars you need through some code. Naturally you'll want to adjust that version number to whatever is most recent/desired for you.
57,104
<p>I'm going to be starting a project soon that requires support for large-ish binary files. I'd like to use Ruby on Rails for the webapp, but I'm concerned with the BLOB support. In my experience with other languages, frameworks, and databases, BLOBs are often overlooked and thus have poor, difficult, and/or buggy functionality.</p> <p>Does RoR spport BLOBs adequately? Are there any gotchas that creep up once you're already committed to Rails?</p> <p>BTW: I want to be using PostgreSQL and/or MySQL as the backend database. Obviously, BLOB support in the underlying database is important. For the moment, I want to avoid focusing on the DB's BLOB capabilities; I'm more interested in how Rails itself reacts. Ideally, Rails should be hiding the details of the database from me, and so I should be able to switch from one to the other. If this is <em>not</em> the case (ie: there's some problem with using Rails with a particular DB) then please do mention it. </p> <p>UPDATE: Also, I'm not just talking about ActiveRecord here. I'll need to handle binary files on the HTTP side (file upload effectively). That means getting access to the appropriate HTTP headers and streams via Rails. I've updated the question title and description to reflect this.</p>
[ { "answer_id": 57112, "author": "Teflon Ted", "author_id": 4061, "author_profile": "https://Stackoverflow.com/users/4061", "pm_score": 2, "selected": false, "text": "<p>I think your best bet is the attachment_fu plug-in:\n<a href=\"http://github.com/technoweenie/attachment_fu/tree/master\" rel=\"nofollow noreferrer\">http://github.com/technoweenie/attachment_fu/tree/master</a></p>\n\n<p>UPDATE: Found some more info here <a href=\"http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a81beffb93708bb3\" rel=\"nofollow noreferrer\">http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a81beffb93708bb3</a></p>\n" }, { "answer_id": 57201, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>:binary</code> type in your ActiveRecord migration and also constrain the maximum size:</p>\n\n<pre><code>class BlobTest &lt; ActiveRecord::Migration\n def self.up\n create_table :files do |t|\n t.column :file_data, :binary, :limit =&gt; 1.megabyte\n end\n end\nend\n</code></pre>\n\n<p>ActiveRecord exposes the BLOB (or CLOB) contents as a Ruby String.</p>\n" }, { "answer_id": 57608, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 4, "selected": true, "text": "<p>+1 for attachment_fu</p>\n\n<p>I use attachment_fu in one of my apps and MUST store files in the DB (for annoying reasons which are outside the scope of this convo).</p>\n\n<p>The (one?) tricky thing dealing w/BLOB's I've found is that you need a separate code path to send the data to the user -- you can't simply in-line a path on the filesystem like you would if it was a plain-Jane file.</p>\n\n<p>e.g. if you're storing avatar information, you can't simply do:</p>\n\n<pre><code>&lt;%= image_tag @youruser.avatar.path %&gt;\n</code></pre>\n\n<p>you have to write some wrapper logic and use send_data, e.g. (below is JUST an example w/attachment_fu, in practice you'd need to DRY this up)</p>\n\n<pre><code>send_data(@youruser.avatar.current_data, :type =&gt; @youruser.avatar.content_type, :filename =&gt; @youruser.avatar.filename, :disposition =&gt; 'inline' )\n</code></pre>\n\n<p>Unfortunately, as far as I know attachment_fu (I don't have the latest version) does not do clever wrapping for you -- you've gotta write it yourself.</p>\n\n<p>P.S.\nSeeing your question edit - Attachment_fu handles all that annoying stuff that you mention -- about needing to know file paths and all that crap -- EXCEPT the one little issue when storing in the DB. Give it a try; it's the standard for rails apps. IF you insist on re-inventing the wheel, the source code for attachment_fu should document most of the gotchas, too!</p>\n" }, { "answer_id": 58208, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Look into the plugin, <a href=\"http://john.guen.in/rdoc/x_send_file/\" rel=\"nofollow noreferrer\">x_send_file</a> too. </p>\n\n<p>\"The XSendFile plugin provides a simple interface for sending files via the X-Sendfile HTTP header. This enables your web server to serve the file directly from disk, instead of streaming it through your Rails process. This is faster and saves a lot of memory if you‘re using Mongrel. Not every web server supports this header. YMMV.\"</p>\n\n<p>I'm not sure if it's usable with Blobs, it may just be for files on the file system. But you probably need something that doesn't tie up the web server streaming large chunks of data.</p>\n" }, { "answer_id": 58377, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 4, "selected": false, "text": "<p>As for streaming, you can do it all in an (at least memory-) efficient way. On the upload side, file parameters in forms are abstracted as IO objects that you can read from; on the download side, look in to the form of <code>render :text =&gt;</code> that takes a Proc argument:</p>\n\n<pre><code>render :content_type =&gt; 'application/octet-stream', :text =&gt; Proc.new {\n |response, output|\n # do something that reads data and writes it to output\n}\n</code></pre>\n\n<p>If your stuff is in files on disk, though, the aforementioned solutions will certainly work better.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
I'm going to be starting a project soon that requires support for large-ish binary files. I'd like to use Ruby on Rails for the webapp, but I'm concerned with the BLOB support. In my experience with other languages, frameworks, and databases, BLOBs are often overlooked and thus have poor, difficult, and/or buggy functionality. Does RoR spport BLOBs adequately? Are there any gotchas that creep up once you're already committed to Rails? BTW: I want to be using PostgreSQL and/or MySQL as the backend database. Obviously, BLOB support in the underlying database is important. For the moment, I want to avoid focusing on the DB's BLOB capabilities; I'm more interested in how Rails itself reacts. Ideally, Rails should be hiding the details of the database from me, and so I should be able to switch from one to the other. If this is *not* the case (ie: there's some problem with using Rails with a particular DB) then please do mention it. UPDATE: Also, I'm not just talking about ActiveRecord here. I'll need to handle binary files on the HTTP side (file upload effectively). That means getting access to the appropriate HTTP headers and streams via Rails. I've updated the question title and description to reflect this.
+1 for attachment\_fu I use attachment\_fu in one of my apps and MUST store files in the DB (for annoying reasons which are outside the scope of this convo). The (one?) tricky thing dealing w/BLOB's I've found is that you need a separate code path to send the data to the user -- you can't simply in-line a path on the filesystem like you would if it was a plain-Jane file. e.g. if you're storing avatar information, you can't simply do: ``` <%= image_tag @youruser.avatar.path %> ``` you have to write some wrapper logic and use send\_data, e.g. (below is JUST an example w/attachment\_fu, in practice you'd need to DRY this up) ``` send_data(@youruser.avatar.current_data, :type => @youruser.avatar.content_type, :filename => @youruser.avatar.filename, :disposition => 'inline' ) ``` Unfortunately, as far as I know attachment\_fu (I don't have the latest version) does not do clever wrapping for you -- you've gotta write it yourself. P.S. Seeing your question edit - Attachment\_fu handles all that annoying stuff that you mention -- about needing to know file paths and all that crap -- EXCEPT the one little issue when storing in the DB. Give it a try; it's the standard for rails apps. IF you insist on re-inventing the wheel, the source code for attachment\_fu should document most of the gotchas, too!
57,124
<p>I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so.</p> <p>If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0.</p> <p>Is there a way to bypass this behaviour and get true Windows version?</p>
[ { "answer_id": 57128, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "<p>WMI QUery:</p>\n\n<pre><code>\"Select * from Win32_OperatingSystem\"\n</code></pre>\n\n<p>EDIT: Actually better would be:</p>\n\n<pre><code>\"Select Version from Win32_OperatingSystem\"\n</code></pre>\n\n<p>You could implement this in Delphi like so:</p>\n\n<pre><code>function OperatingSystemDisplayName: string;\n\n function GetWMIObject(const objectName: string): IDispatch;\n var\n chEaten: Integer;\n BindCtx: IBindCtx;\n Moniker: IMoniker;\n begin\n OleCheck(CreateBindCtx(0, bindCtx));\n OleCheck(MkParseDisplayName(BindCtx, PChar(objectName), chEaten, Moniker));\n OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result));\n end;\n\n function VarToString(const Value: OleVariant): string;\n begin\n if VarIsStr(Value) then begin\n Result := Trim(Value);\n end else begin\n Result := '';\n end;\n end;\n\n function FullVersionString(const Item: OleVariant): string;\n var\n Caption, ServicePack, Version, Architecture: string;\n begin\n Caption := VarToString(Item.Caption);\n ServicePack := VarToString(Item.CSDVersion);\n Version := VarToString(Item.Version);\n Architecture := ArchitectureDisplayName(SystemArchitecture);\n Result := Caption;\n if ServicePack &lt;&gt; '' then begin\n Result := Result + ' ' + ServicePack;\n end;\n Result := Result + ', version ' + Version + ', ' + Architecture;\n end;\n\nvar\n objWMIService: OleVariant;\n colItems: OleVariant;\n Item: OleVariant;\n oEnum: IEnumvariant;\n iValue: LongWord;\n\nbegin\n Try\n objWMIService := GetWMIObject('winmgmts:\\\\localhost\\root\\cimv2');\n colItems := objWMIService.ExecQuery('SELECT Caption, CSDVersion, Version FROM Win32_OperatingSystem', 'WQL', 0);\n oEnum := IUnknown(colItems._NewEnum) as IEnumVariant;\n if oEnum.Next(1, Item, iValue)=0 then begin\n Result := FullVersionString(Item);\n exit;\n end;\n Except\n // yes, I know this is nasty, but come what may I want to use the fallback code below should the WMI code fail\n End;\n\n (* Fallback, relies on the deprecated function GetVersionEx, reports erroneous values\n when manifest does not contain supportedOS matching the executing system *)\n Result := TOSVersion.ToString;\nend;\n</code></pre>\n" }, { "answer_id": 57130, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 6, "selected": true, "text": "<p>The best approach I know is to check if specific API is exported from some DLL. Each new Windows version adds new functions and by checking the existance of those functions one can tell which OS the application is running on. For example, Vista exports <a href=\"http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx\" rel=\"noreferrer\">GetLocaleInfoEx</a> from kernel32.dll while previous Windowses didn't.</p>\n\n<p>To cut the long story short, here is one such list containing only exports from kernel32.dll.</p>\n\n<pre>\n> *function: implemented in* \n> GetLocaleInfoEx: Vista \n> GetLargePageMinimum: Vista, Server 2003 \nGetDLLDirectory: Vista, Server 2003, XP SP1 \nGetNativeSystemInfo: Vista, Server 2003, XP SP1, XP \nReplaceFile: Vista, Server 2003, XP SP1, XP, 2000 \nOpenThread: Vista, Server 2003, XP SP1, XP, 2000, ME \nGetThreadPriorityBoost: Vista, Server 2003, XP SP1, XP, 2000, NT 4 \nIsDebuggerPresent: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98 \nGetDiskFreeSpaceEx: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98, 95 OSR2 \nConnectNamedPipe: Vista, Server 2003, XP SP1, XP, 2000, NT 4, NT 3 \nBeep: Vista, Server 2003, XP SP1, XP, 2000, ME, 98, 95 OSR2, 95 \n</pre>\n\n<p>Writing the function to determine the real OS version is simple; just proceed from newest OS to oldest and use <a href=\"http://msdn.microsoft.com/en-us/library/ms683212.aspx\" rel=\"noreferrer\">GetProcAddress</a> to check exported APIs. Implementing this in any language should be trivial.</p>\n\n<p>The following code in Delphi was extracted from the free <a href=\"http://gp.17slon.com/gp/dsiwin32.htm\" rel=\"noreferrer\">DSiWin32</a> library):</p>\n\n<pre><code>TDSiWindowsVersion = (wvUnknown, wvWin31, wvWin95, wvWin95OSR2, wvWin98,\n wvWin98SE, wvWinME, wvWin9x, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP,\n wvWinNT, wvWinServer2003, wvWinVista);\n\nfunction DSiGetWindowsVersion: TDSiWindowsVersion;\nvar\n versionInfo: TOSVersionInfo;\nbegin\n versionInfo.dwOSVersionInfoSize := SizeOf(versionInfo);\n GetVersionEx(versionInfo);\n Result := wvUnknown;\n case versionInfo.dwPlatformID of\n VER_PLATFORM_WIN32s: Result := wvWin31;\n VER_PLATFORM_WIN32_WINDOWS:\n case versionInfo.dwMinorVersion of\n 0:\n if Trim(versionInfo.szCSDVersion[1]) = 'B' then\n Result := wvWin95OSR2\n else\n Result := wvWin95;\n 10:\n if Trim(versionInfo.szCSDVersion[1]) = 'A' then\n Result := wvWin98SE\n else\n Result := wvWin98;\n 90:\n if (versionInfo.dwBuildNumber = 73010104) then\n Result := wvWinME;\n else\n Result := wvWin9x;\n end; //case versionInfo.dwMinorVersion\n VER_PLATFORM_WIN32_NT:\n case versionInfo.dwMajorVersion of\n 3: Result := wvWinNT3;\n 4: Result := wvWinNT4;\n 5:\n case versionInfo.dwMinorVersion of\n 0: Result := wvWin2000;\n 1: Result := wvWinXP;\n 2: Result := wvWinServer2003;\n else Result := wvWinNT\n end; //case versionInfo.dwMinorVersion\n 6: Result := wvWinVista;\n end; //case versionInfo.dwMajorVersion\n end; //versionInfo.dwPlatformID\nend; { DSiGetWindowsVersion }\n\nfunction DSiGetTrueWindowsVersion: TDSiWindowsVersion;\n\n function ExportsAPI(module: HMODULE; const apiName: string): boolean;\n begin\n Result := GetProcAddress(module, PChar(apiName)) &lt;&gt; nil;\n end; { ExportsAPI }\n\nvar\n hKernel32: HMODULE;\n\nbegin { DSiGetTrueWindowsVersion }\n hKernel32 := GetModuleHandle('kernel32');\n Win32Check(hKernel32 &lt;&gt; 0);\n if ExportsAPI(hKernel32, 'GetLocaleInfoEx') then\n Result := wvWinVista\n else if ExportsAPI(hKernel32, 'GetLargePageMinimum') then\n Result := wvWinServer2003\n else if ExportsAPI(hKernel32, 'GetNativeSystemInfo') then\n Result := wvWinXP\n else if ExportsAPI(hKernel32, 'ReplaceFile') then\n Result := wvWin2000\n else if ExportsAPI(hKernel32, 'OpenThread') then\n Result := wvWinME\n else if ExportsAPI(hKernel32, 'GetThreadPriorityBoost') then\n Result := wvWinNT4\n else if ExportsAPI(hKernel32, 'IsDebuggerPresent') then //is also in NT4!\n Result := wvWin98\n else if ExportsAPI(hKernel32, 'GetDiskFreeSpaceEx') then //is also in NT4!\n Result := wvWin95OSR2\n else if ExportsAPI(hKernel32, 'ConnectNamedPipe') then\n Result := wvWinNT3\n else if ExportsAPI(hKernel32, 'Beep') then\n Result := wvWin95\n else // we have no idea\n Result := DSiGetWindowsVersion;\nend; { DSiGetTrueWindowsVersion }\n</code></pre>\n\n<p>--- updated 2009-10-09</p>\n\n<p>It turns out that it gets very hard to do an \"undocumented\" OS detection on Vista SP1 and higher. A look at the <a href=\"http://msdn.microsoft.com/en-us/library/aa383687(VS.85).aspx\" rel=\"noreferrer\">API changes</a> shows that all Windows 2008 functions are also implemented in Vista SP1 and that all Windows 7 functions are also implemented in Windows 2008 R2. Too bad :(</p>\n\n<p>--- end of update</p>\n\n<p>FWIW, this is a problem I encountered in practice. We (the company I work for) have a program that was not really Vista-ready when Vista was released (and some weeks after that ...). It was not working under the compatibility layer either. (Some DirectX problems. Don't ask.)</p>\n\n<p>We didn't want too-smart-for-their-own-good users to run this app on Vista at all - compatibility mode or not - so I had to find a solution (a guy smarter than me pointed me into right direction; the stuff above is not my brainchild). Now I'm posting it for your pleasure and to help all poor souls that will have to solve this problem in the future. Google, please index this article!</p>\n\n<p>If you have a better solution (or an upgrade and/or fix for mine), please post an answer here ...</p>\n" }, { "answer_id": 57156, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 4, "selected": false, "text": "<p>How about obtaining the version of a system file?</p>\n\n<p>The best file would be kernel32.dll, located in %WINDIR%\\System32\\kernel32.dll.</p>\n\n<p>There are APIs to obtain the file version. eg: I'm using Windows XP -> \"5.1.2600.5512 (xpsp.080413-2111)\"</p>\n" }, { "answer_id": 57326, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 3, "selected": false, "text": "<p>Another solution:</p>\n\n<p>read the following registry entry:</p>\n\n<pre><code>HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProductName\n</code></pre>\n\n<p>or other keys from</p>\n\n<pre><code>HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\n</code></pre>\n" }, { "answer_id": 8123929, "author": "Warren P", "author_id": 84704, "author_profile": "https://Stackoverflow.com/users/84704", "pm_score": 1, "selected": false, "text": "<p><strong>Note:</strong> Gabr is asking about an approach that can bypass the limitations of <code>GetVersionEx</code>. JCL code uses GetVersionEx, and is thus subject to compatibility layer. This information is for people who don't need to bypass the compatibility layer, only.</p>\n\n<p>Using the Jedi JCL, you can add unit JclSysInfo, and call function <code>GetWindowsVersion</code>. It returns an enumerated type TWindowsVersion.</p>\n\n<p>Currently JCL contains all shipped windows versions, and gets changed each time Microsoft ships a new version of Windows in a box:</p>\n\n<pre><code> TWindowsVersion =\n (wvUnknown, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME,\n wvWinNT31, wvWinNT35, wvWinNT351, wvWinNT4, wvWin2000, wvWinXP,\n wvWin2003, wvWinXP64, wvWin2003R2, wvWinVista, wvWinServer2008,\n wvWin7, wvWinServer2008R2);\n</code></pre>\n\n<p>If you want to know if you're running 64-bit windows 7 instead of 32-bit, then call <code>JclSysInfo.IsWindows64</code>.</p>\n\n<p>Note that JCL allso handles Editions, like Pro, Ultimate, etc. For that call GetWindowsEdition, and it returns one of these:</p>\n\n<pre><code>TWindowsEdition =\n (weUnknown, weWinXPHome, weWinXPPro, weWinXPHomeN, weWinXPProN, weWinXPHomeK,\n weWinXPProK, weWinXPHomeKN, weWinXPProKN, weWinXPStarter, weWinXPMediaCenter,\n weWinXPTablet, weWinVistaStarter, weWinVistaHomeBasic, weWinVistaHomeBasicN,\n weWinVistaHomePremium, weWinVistaBusiness, weWinVistaBusinessN,\n weWinVistaEnterprise, weWinVistaUltimate, weWin7Starter, weWin7HomeBasic,\n weWin7HomePremium, weWin7Professional, weWin7Enterprise, weWin7Ultimate);\n</code></pre>\n\n<p>For historical interest, you can check the NT-level edition too with the NtProductType function, it returns:</p>\n\n<pre><code> TNtProductType =       (ptUnknown, ptWorkStation, ptServer, ptAdvancedServer,        \n ptPersonal, ptProfessional, ptDatacenterServer, \n ptEnterprise, ptWebEdition);\n</code></pre>\n\n<p>Note that \"N editions\" are detected above. That's an EU (Europe) version of Windows, created due to EU anti-trust regulations. That's a pretty fine gradation of detection inside the JCL.</p>\n\n<p>Here's a sample function that will help you detect Vista, and do something special when on Vista.</p>\n\n<pre><code>function IsSupported:Boolean;\nbegin\n case GetWindowsVersion of\n wvVista: result := false; \n else\n result := true;\n end;\nend;\n</code></pre>\n\n<p>Note that if you want to do \"greater than\" checking, then you should just use other techniques. Also note that version checking can often be a source of future breakage. I have usually chosen to warn users and continue, so that my binary code doesn't become the actual source of breakage in the future.</p>\n\n<p>Recently I tried to install an app, and the installer checked my drive free space, and would not install, because I had more than 2 gigabytes of free space. The 32 bit integer signed value in the installer became negative, breaking the installer. I had to install it into a VM to get it to work. Adding \"smart code\" often makes your app \"stupider\". Be wary.</p>\n\n<p>Incidentally, I found that from the command line, you can run WMIC.exe, and type <code>path Win32_OperatingSystem</code> (The \"Select * from Win32_OperatingSystem\" didn't work for me). In future perhaps JCL could be extended to use the WMI information.</p>\n" }, { "answer_id": 24345510, "author": "Victor Fedorenkov", "author_id": 3763602, "author_profile": "https://Stackoverflow.com/users/3763602", "pm_score": 3, "selected": false, "text": "<p>real version store on PEB block of process information.</p>\n\n<p>Sample for Win32 app (Delphi Code)</p>\n\n<p></p>\n\n<pre><code>unit RealWindowsVerUnit;\n\ninterface\n\nuses\n Windows;\n\nvar\n //Real version Windows\n Win32MajorVersionReal: Integer;\n Win32MinorVersionReal: Integer;\n\nimplementation\n\ntype\n PPEB=^PEB;\n PEB = record\n InheritedAddressSpace: Boolean;\n ReadImageFileExecOptions: Boolean;\n BeingDebugged: Boolean;\n Spare: Boolean;\n Mutant: Cardinal;\n ImageBaseAddress: Pointer;\n LoaderData: Pointer;\n ProcessParameters: Pointer; //PRTL_USER_PROCESS_PARAMETERS;\n SubSystemData: Pointer;\n ProcessHeap: Pointer;\n FastPebLock: Pointer;\n FastPebLockRoutine: Pointer;\n FastPebUnlockRoutine: Pointer;\n EnvironmentUpdateCount: Cardinal;\n KernelCallbackTable: PPointer;\n EventLogSection: Pointer;\n EventLog: Pointer;\n FreeList: Pointer; //PPEB_FREE_BLOCK;\n TlsExpansionCounter: Cardinal;\n TlsBitmap: Pointer;\n TlsBitmapBits: array[0..1] of Cardinal;\n ReadOnlySharedMemoryBase: Pointer;\n ReadOnlySharedMemoryHeap: Pointer;\n ReadOnlyStaticServerData: PPointer;\n AnsiCodePageData: Pointer;\n OemCodePageData: Pointer;\n UnicodeCaseTableData: Pointer;\n NumberOfProcessors: Cardinal;\n NtGlobalFlag: Cardinal;\n Spare2: array[0..3] of Byte;\n CriticalSectionTimeout: LARGE_INTEGER;\n HeapSegmentReserve: Cardinal;\n HeapSegmentCommit: Cardinal;\n HeapDeCommitTotalFreeThreshold: Cardinal;\n HeapDeCommitFreeBlockThreshold: Cardinal;\n NumberOfHeaps: Cardinal;\n MaximumNumberOfHeaps: Cardinal;\n ProcessHeaps: Pointer;\n GdiSharedHandleTable: Pointer;\n ProcessStarterHelper: Pointer;\n GdiDCAttributeList: Pointer;\n LoaderLock: Pointer;\n OSMajorVersion: Cardinal;\n OSMinorVersion: Cardinal;\n OSBuildNumber: Cardinal;\n OSPlatformId: Cardinal;\n ImageSubSystem: Cardinal;\n ImageSubSystemMajorVersion: Cardinal;\n ImageSubSystemMinorVersion: Cardinal;\n GdiHandleBuffer: array [0..33] of Cardinal;\n PostProcessInitRoutine: Cardinal;\n TlsExpansionBitmap: Cardinal;\n TlsExpansionBitmapBits: array [0..127] of Byte;\n SessionId: Cardinal;\n end;\n\n//Get PEB block current win32 process\nfunction GetPDB: PPEB; stdcall;\nasm\n MOV EAX, DWORD PTR FS:[30h]\nend;\n\ninitialization\n //Detect true windows wersion\n Win32MajorVersionReal := GetPDB^.OSMajorVersion;\n Win32MinorVersionReal := GetPDB^.OSMinorVersion;\nend.\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 31755501, "author": "FredS", "author_id": 5042682, "author_profile": "https://Stackoverflow.com/users/5042682", "pm_score": 1, "selected": false, "text": "<p>Essentially to answer duplicate Q: <a href=\"https://stackoverflow.com/questions/31753092/getting-os-major-minor-and-build-versions-for-windows-8-1-and-up-in-delphi-200\">Getting OS major, minor, and build versions for Windows 8.1 and up in Delphi 2007</a></p>\n\n<p>Starting with W2K you can use <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa370624%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">NetServerGetInfo</a>. NetServerGetInfo returns the correct info on W7 and W8.1, unable to test on W10..</p>\n\n<pre><code>function GetWinVersion: string;\nvar\n Buffer: PServerInfo101;\nbegin\n Buffer := nil;\n if NetServerGetInfo(nil, 101, Pointer(Buffer)) = NO_ERROR then\n try\n Result := &lt;Build You Version String here&gt;(\n Buffer.sv101_version_major,\n Buffer.sv101_version_minor,\n VER_PLATFORM_WIN32_NT // Save since minimum support begins in W2K\n );\n finally\n NetApiBufferFree(Buffer);\n end;\nend;\n</code></pre>\n" }, { "answer_id": 31756711, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 3, "selected": false, "text": "<p>The following works for me in Windows 10 without the Windows 10 GUID listed in the application manifest:</p>\n\n<pre><code>uses\n System.SysUtils, Winapi.Windows;\n\ntype\n NET_API_STATUS = DWORD;\n\n _SERVER_INFO_101 = record\n sv101_platform_id: DWORD;\n sv101_name: LPWSTR;\n sv101_version_major: DWORD;\n sv101_version_minor: DWORD;\n sv101_type: DWORD;\n sv101_comment: LPWSTR;\n end;\n SERVER_INFO_101 = _SERVER_INFO_101;\n PSERVER_INFO_101 = ^SERVER_INFO_101;\n LPSERVER_INFO_101 = PSERVER_INFO_101;\n\nconst\n MAJOR_VERSION_MASK = $0F;\n\nfunction NetServerGetInfo(servername: LPWSTR; level: DWORD; var bufptr): NET_API_STATUS; stdcall; external 'Netapi32.dll';\nfunction NetApiBufferFree(Buffer: LPVOID): NET_API_STATUS; stdcall; external 'Netapi32.dll';\n\ntype\n pfnRtlGetVersion = function(var RTL_OSVERSIONINFOEXW): LONG; stdcall;\nvar\n Buffer: PSERVER_INFO_101;\n ver: RTL_OSVERSIONINFOEXW;\n RtlGetVersion: pfnRtlGetVersion;\nbegin\n Buffer := nil;\n\n // Win32MajorVersion and Win32MinorVersion are populated from GetVersionEx()...\n ShowMessage(Format('GetVersionEx: %d.%d', [Win32MajorVersion, Win32MinorVersion])); // shows 6.2, as expected per GetVersionEx() documentation\n\n @RtlGetVersion := GetProcAddress(GetModuleHandle('ntdll.dll'), 'RtlGetVersion');\n if Assigned(RtlGetVersion) then\n begin\n ZeroMemory(@ver, SizeOf(ver));\n ver.dwOSVersionInfoSize := SizeOf(ver);\n\n if RtlGetVersion(ver) = 0 then\n ShowMessage(Format('RtlGetVersion: %d.%d', [ver.dwMajorVersion, ver.dwMinorVersion])); // shows 10.0\n end;\n\n if NetServerGetInfo(nil, 101, Buffer) = NO_ERROR then\n try\n ShowMessage(Format('NetServerGetInfo: %d.%d', [Buffer.sv101_version_major and MAJOR_VERSION_MASK, Buffer.sv101_version_minor])); // shows 10.0\n finally\n NetApiBufferFree(Buffer);\n end;\nend.\n</code></pre>\n\n<p><strong>Update</strong>: <code>NetWkstaGetInfo()</code> would probably also work, similar to 'NetServerGetInfo()`, but I have not try it yet.</p>\n" }, { "answer_id": 31764902, "author": "Ivry Gates", "author_id": 5181214, "author_profile": "https://Stackoverflow.com/users/5181214", "pm_score": 1, "selected": false, "text": "<p>One note about using NetServerGetInfo(), which does work still on Windows 10 (10240.th1_st1)...</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa370903%28v=vs.85%29.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/windows/desktop/aa370903%28v=vs.85%29.aspx</a></p>\n\n<blockquote>\n <p>sv101_version_major</p>\n \n <p>The major version number and the server type.</p>\n \n <p>The major release version number of the operating system is specified\n in the least significant 4 bits. The server type is specified in the\n most significant 4 bits. The MAJOR_VERSION_MASK bitmask defined in the\n Lmserver.h header {0x0F} should be used by an application to obtain\n the major version number from this member.</p>\n</blockquote>\n\n<p>In other words, (sv101_version_major &amp; MAJOR_VERSION_MASK).</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4997/" ]
I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so. If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0. Is there a way to bypass this behaviour and get true Windows version?
The best approach I know is to check if specific API is exported from some DLL. Each new Windows version adds new functions and by checking the existance of those functions one can tell which OS the application is running on. For example, Vista exports [GetLocaleInfoEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) from kernel32.dll while previous Windowses didn't. To cut the long story short, here is one such list containing only exports from kernel32.dll. ``` > *function: implemented in* > GetLocaleInfoEx: Vista > GetLargePageMinimum: Vista, Server 2003 GetDLLDirectory: Vista, Server 2003, XP SP1 GetNativeSystemInfo: Vista, Server 2003, XP SP1, XP ReplaceFile: Vista, Server 2003, XP SP1, XP, 2000 OpenThread: Vista, Server 2003, XP SP1, XP, 2000, ME GetThreadPriorityBoost: Vista, Server 2003, XP SP1, XP, 2000, NT 4 IsDebuggerPresent: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98 GetDiskFreeSpaceEx: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98, 95 OSR2 ConnectNamedPipe: Vista, Server 2003, XP SP1, XP, 2000, NT 4, NT 3 Beep: Vista, Server 2003, XP SP1, XP, 2000, ME, 98, 95 OSR2, 95 ``` Writing the function to determine the real OS version is simple; just proceed from newest OS to oldest and use [GetProcAddress](http://msdn.microsoft.com/en-us/library/ms683212.aspx) to check exported APIs. Implementing this in any language should be trivial. The following code in Delphi was extracted from the free [DSiWin32](http://gp.17slon.com/gp/dsiwin32.htm) library): ``` TDSiWindowsVersion = (wvUnknown, wvWin31, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME, wvWin9x, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP, wvWinNT, wvWinServer2003, wvWinVista); function DSiGetWindowsVersion: TDSiWindowsVersion; var versionInfo: TOSVersionInfo; begin versionInfo.dwOSVersionInfoSize := SizeOf(versionInfo); GetVersionEx(versionInfo); Result := wvUnknown; case versionInfo.dwPlatformID of VER_PLATFORM_WIN32s: Result := wvWin31; VER_PLATFORM_WIN32_WINDOWS: case versionInfo.dwMinorVersion of 0: if Trim(versionInfo.szCSDVersion[1]) = 'B' then Result := wvWin95OSR2 else Result := wvWin95; 10: if Trim(versionInfo.szCSDVersion[1]) = 'A' then Result := wvWin98SE else Result := wvWin98; 90: if (versionInfo.dwBuildNumber = 73010104) then Result := wvWinME; else Result := wvWin9x; end; //case versionInfo.dwMinorVersion VER_PLATFORM_WIN32_NT: case versionInfo.dwMajorVersion of 3: Result := wvWinNT3; 4: Result := wvWinNT4; 5: case versionInfo.dwMinorVersion of 0: Result := wvWin2000; 1: Result := wvWinXP; 2: Result := wvWinServer2003; else Result := wvWinNT end; //case versionInfo.dwMinorVersion 6: Result := wvWinVista; end; //case versionInfo.dwMajorVersion end; //versionInfo.dwPlatformID end; { DSiGetWindowsVersion } function DSiGetTrueWindowsVersion: TDSiWindowsVersion; function ExportsAPI(module: HMODULE; const apiName: string): boolean; begin Result := GetProcAddress(module, PChar(apiName)) <> nil; end; { ExportsAPI } var hKernel32: HMODULE; begin { DSiGetTrueWindowsVersion } hKernel32 := GetModuleHandle('kernel32'); Win32Check(hKernel32 <> 0); if ExportsAPI(hKernel32, 'GetLocaleInfoEx') then Result := wvWinVista else if ExportsAPI(hKernel32, 'GetLargePageMinimum') then Result := wvWinServer2003 else if ExportsAPI(hKernel32, 'GetNativeSystemInfo') then Result := wvWinXP else if ExportsAPI(hKernel32, 'ReplaceFile') then Result := wvWin2000 else if ExportsAPI(hKernel32, 'OpenThread') then Result := wvWinME else if ExportsAPI(hKernel32, 'GetThreadPriorityBoost') then Result := wvWinNT4 else if ExportsAPI(hKernel32, 'IsDebuggerPresent') then //is also in NT4! Result := wvWin98 else if ExportsAPI(hKernel32, 'GetDiskFreeSpaceEx') then //is also in NT4! Result := wvWin95OSR2 else if ExportsAPI(hKernel32, 'ConnectNamedPipe') then Result := wvWinNT3 else if ExportsAPI(hKernel32, 'Beep') then Result := wvWin95 else // we have no idea Result := DSiGetWindowsVersion; end; { DSiGetTrueWindowsVersion } ``` --- updated 2009-10-09 It turns out that it gets very hard to do an "undocumented" OS detection on Vista SP1 and higher. A look at the [API changes](http://msdn.microsoft.com/en-us/library/aa383687(VS.85).aspx) shows that all Windows 2008 functions are also implemented in Vista SP1 and that all Windows 7 functions are also implemented in Windows 2008 R2. Too bad :( --- end of update FWIW, this is a problem I encountered in practice. We (the company I work for) have a program that was not really Vista-ready when Vista was released (and some weeks after that ...). It was not working under the compatibility layer either. (Some DirectX problems. Don't ask.) We didn't want too-smart-for-their-own-good users to run this app on Vista at all - compatibility mode or not - so I had to find a solution (a guy smarter than me pointed me into right direction; the stuff above is not my brainchild). Now I'm posting it for your pleasure and to help all poor souls that will have to solve this problem in the future. Google, please index this article! If you have a better solution (or an upgrade and/or fix for mine), please post an answer here ...
57,140
<p>Say instead of returning void a method you returned a reference to the class even if it didn't make any particular semantic sense. It seems to me like it would give you more options on how the methods are called, allowing you to use it in a fluent-interface-like style and I can't really think of any disadvantages since you don't have to do anything with the return value (even store it).</p> <p>So suppose you're in a situation where you want to update an object and then return its current value. instead of saying </p> <pre><code>myObj.Update(); var val = myObj.GetCurrentValue(); </code></pre> <p>you will be able to combine the two lines to say</p> <pre><code>var val = myObj.Update().GetCurrentValue(); </code></pre> <hr> <p><strong>EDIT:</strong> I asked the below on a whim, in retrospect, I agree that its likely to be unnecessary and complicating, however my question regarding returning this rather than void stands.</p> <p>On a related note, what do you guys think of having the language include a new bit of syntactic sugar:</p> <pre><code>var val = myObj.Update()&lt;.GetCurrentValue(); </code></pre> <p>This operator would have a low order of precedence so myObj.Update() would execute first and then call GetCurrentValue() on myObj instead of the void return of Update.</p> <p>Essentially I'm imagining an operator that will say "call the method on the right-hand side of the operator on the first valid object on the left". Any thoughts?</p>
[ { "answer_id": 57165, "author": "argv0", "author_id": 5595, "author_profile": "https://Stackoverflow.com/users/5595", "pm_score": 2, "selected": false, "text": "<p>Returning \"self\" or \"this\" is a common pattern, sometimes referred to as <a href=\"http://www.martinfowler.com/dslwip/MethodChaining.html\" rel=\"nofollow noreferrer\">\"method chaining\"</a>. As for your proposed syntax sugar, I'm not so sure. I'm not a .NET guy, but it doesn't seem terribly useful to me. </p>\n" }, { "answer_id": 57176, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 2, "selected": false, "text": "<p>The NeXTSTEP Objective-C framework used to use this pattern. It was discontinued in that framework once distributed objects (remote procedure calls, basically) were added to the language—a function that returned <code>self</code> had to be a synchronous invocation, since the distributed object system saw the return type and assumed that the caller would need to know the result of the function.</p>\n" }, { "answer_id": 57178, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 4, "selected": false, "text": "<p>I think as a general policy, it simply doesn't make sense. Method chaining in this manner works with a properly defined interface but it's only appropriate if it makes semantic sense. </p>\n\n<p>Your example is a prime one where it's not appropriate, because it makes no semantic sense.</p>\n\n<p>Similarly, your syntactic sugar is unnecessary with a properly designed fluent interface.</p>\n\n<p>Fluent interfaces or method chaining <b>can</b> work very well, but need to be designed carefully.</p>\n" }, { "answer_id": 57203, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 4, "selected": true, "text": "<p>I know in Java they're actually thinking about making this standard behaviour for void methods. If you do that you don't need the extra syntactic sugar.</p>\n\n<p>The only downside I can think of is performance. But that's easilly measured. I'll get back to you with the results in a few minutes :-)</p>\n\n<p>Edit:</p>\n\n<p>Returning a reference is a bit slower than returning void .. what a surprise. So that's the only downside. A few more ticks when calling your function.</p>\n" }, { "answer_id": 57212, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 2, "selected": false, "text": "<p>The only disadvantage I can see is that it makes the API slightly more confusing. Let's say you have some collection object with a remove() method that would normally return void. Now you want to return a reference to the collection itself. The new signature would look like:</p>\n\n<pre><code>public MyCollection remove(Object someElement)\n</code></pre>\n\n<p>Just looking at the signature, it's not clear that you're returning a reference to the same instance. Maybe MyCollection is immutable and you're returning a new instance. In some cases, like here, you would need some external documentation to clarify this.</p>\n\n<p>I actually like this idea, and I believe that there was some talk in retrofitting all void methods in Java7 to return a reference to 'this', but it ultimately fell through. </p>\n" }, { "answer_id": 57227, "author": "Pete", "author_id": 76, "author_profile": "https://Stackoverflow.com/users/76", "pm_score": 2, "selected": false, "text": "<p>Isn't this how \"fluent interfaces\" - like those that JQuery utilizes - are built? One benefit is supposed to be code readability (though the wikipedia entry at <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Fluent_interface</a> mentions that some find it <em>NOT</em> readable). Another benefit is in code terseness, you lose the need to set properties in 7 lines of code and then call a method on that object in the 8th line.</p>\n\n<p>Martin Fowler (who coined the term here - <a href=\"http://martinfowler.com/bliki/FluentInterface.html\" rel=\"nofollow noreferrer\">http://martinfowler.com/bliki/FluentInterface.html</a>) says that there is more to fluent interfaces than method chaining, however method chaining is a common technique to use with fluent interfaces.</p>\n\n<p>EDIT:\nI was actually coming back here to edit my answer and add that there is no disadvantage to returning this instead of void in any measurable way, when I saw George's comment pointing out that I did forget to discuss the <em>point</em> of the question. Sorry for the initial \"pointless\" rambling.</p>\n" }, { "answer_id": 57792, "author": "Ismael", "author_id": 5999, "author_profile": "https://Stackoverflow.com/users/5999", "pm_score": 0, "selected": false, "text": "<p>At first sight it may look good, but for a consistent interface you will need that all methods return a reference to this (which has it own problems).</p>\n\n<p>Let say you have a class with two methods GetA which return this and GetB which return another object:</p>\n\n<p>Then you can call obj.GetA().GetB(), but not obj.GetB().GetA(), which at least doesn't seems consistent.</p>\n\n<p>With Pascal (and Visual Basic) you can call several methods of the same object.</p>\n\n<blockquote>\n<pre><code>with obj\n .GetA();\n .GetB();\nend with;\n</code></pre>\n</blockquote>\n\n<p>The problem with this feature is that you easily can write code that is harder to understand than it should be. Also adding a new operator probably make it ever harder.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Say instead of returning void a method you returned a reference to the class even if it didn't make any particular semantic sense. It seems to me like it would give you more options on how the methods are called, allowing you to use it in a fluent-interface-like style and I can't really think of any disadvantages since you don't have to do anything with the return value (even store it). So suppose you're in a situation where you want to update an object and then return its current value. instead of saying ``` myObj.Update(); var val = myObj.GetCurrentValue(); ``` you will be able to combine the two lines to say ``` var val = myObj.Update().GetCurrentValue(); ``` --- **EDIT:** I asked the below on a whim, in retrospect, I agree that its likely to be unnecessary and complicating, however my question regarding returning this rather than void stands. On a related note, what do you guys think of having the language include a new bit of syntactic sugar: ``` var val = myObj.Update()<.GetCurrentValue(); ``` This operator would have a low order of precedence so myObj.Update() would execute first and then call GetCurrentValue() on myObj instead of the void return of Update. Essentially I'm imagining an operator that will say "call the method on the right-hand side of the operator on the first valid object on the left". Any thoughts?
I know in Java they're actually thinking about making this standard behaviour for void methods. If you do that you don't need the extra syntactic sugar. The only downside I can think of is performance. But that's easilly measured. I'll get back to you with the results in a few minutes :-) Edit: Returning a reference is a bit slower than returning void .. what a surprise. So that's the only downside. A few more ticks when calling your function.
57,145
<p>While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).</p> <pre><code>class Foo { ArrayList&lt;Bar&gt; bars = new ArrayList&lt;Bar&gt;(10); } </code></pre> <p>A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm?</p> <p>Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things.</p>
[ { "answer_id": 57177, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "<p>The overhead is very small. It is possible to write a hybrid array list that has fields for the first few items, and then falls back to using an array for longer list.</p>\n\n<p>You can avoid the overhead of the list object entirely by using an array. To go even further hardcore, you can declare the field as Object, and avoid the array altogether for a single item.</p>\n\n<p>If memory really is a problem, you might want to forget about using object instances at the low-level. Instead use a larger data structure at a larger level of granularity.</p>\n" }, { "answer_id": 57185, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 4, "selected": true, "text": "<p>The <code>ArrayList</code> class in Java has only two data members, a reference to an <code>Object[]</code> array and a size—which you need anyway if you don't use an <code>ArrayList</code>. So the only advantage to not using an <code>ArrayList</code> is saving one object allocation, which is unlikely ever to be a big deal.</p>\n\n<p>If you're creating and disposing of many, many instances of your container class (and by extension your <code>ArrayList</code> instance) every second, you <em>might</em> have a slight problem with garbage collection churn—but that's something to worry about if it ever occurs. Garbage collection is typically the least of your worries.</p>\n" }, { "answer_id": 57226, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 2, "selected": false, "text": "<p>For the sake of keeping things simple, I think this is pretty much a non-issue. Your implementation is flexible enough that if the requirements change in the future, you aren't forced into a refactoring. Also, adding more logic to your code for a hybrid solution just isn't worth it taking into account your small data set and the high-quality of Java's Collection API.</p>\n" }, { "answer_id": 57341, "author": "Cagatay", "author_id": 3071, "author_profile": "https://Stackoverflow.com/users/3071", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://web.archive.org/web/20081018003459/http://google-collections.googlecode.com:80/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html\" rel=\"nofollow noreferrer\">Google Collections</a> has collections optimized for immutable/small number of elements. See <code>Lists.asList</code> API as an example.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881/" ]
While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc). ``` class Foo { ArrayList<Bar> bars = new ArrayList<Bar>(10); } ``` A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm? Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things.
The `ArrayList` class in Java has only two data members, a reference to an `Object[]` array and a size—which you need anyway if you don't use an `ArrayList`. So the only advantage to not using an `ArrayList` is saving one object allocation, which is unlikely ever to be a big deal. If you're creating and disposing of many, many instances of your container class (and by extension your `ArrayList` instance) every second, you *might* have a slight problem with garbage collection churn—but that's something to worry about if it ever occurs. Garbage collection is typically the least of your worries.
57,152
<p>Let's say I've got Alpha things that may or may not <em>be</em> or be <em>related to</em> Bravo or Charlie things.</p> <p>These are one-to-one relationships: No Alpha will relate to more than one Bravo. And no Bravo will relate to more than one Alpha.</p> <p>I've got a few goals:</p> <ul> <li>a system that's easy to learn and maintain.</li> <li>data integrity enforced within my database.</li> <li>a schema that matches the real-world, logical organization of my data.</li> <li>classes/objects within my programming that map well to database tables (à la Linq to SQL)</li> <li>speedy read and write operations</li> <li>effective use of space (few null fields)</li> </ul> <p>I've got three ideas&hellip;</p> <pre><code>PK = primary key FK = foreign key NU = nullable </code></pre> <p>One table with many nullalbe fields (flat file)&hellip;</p> <pre><code> Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU BravoOne NU BravoTwo NU BravoThree NU CharlieOne NU CharlieTwo NU CharlieThree </code></pre> <p>Many tables with zero nullalbe fields&hellip;</p> <pre><code> Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree Bravos -------- FK PK AlphaId BravoOne BravoTwo BravoThree Charlies -------- FK PK AlphaId CharlieOne CharlieTwo CharlieThree </code></pre> <p>Best (or worst) of both: Lots of nullalbe foreign keys to many tables&hellip;</p> <pre><code> Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU FK BravoId NU FK CharlieId Bravos -------- PK BravoId BravoOne BravoTwo BravoThree Charlies -------- PK CharlieId CharlieOne CharlieTwo CharlieThree </code></pre> <p>What if an Alpha must be either Bravo or Charlie, but not both?</p> <p>What if instead of just Bravos and Charlies, Alphas could also be any of Deltas, Echos, Foxtrots, or Golfs, etc&hellip;?</p> <hr> <p><strong>EDIT:</strong> This is a portion of the question: <a href="https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation#57056">Which is the best database schema for my navigation?</a></p>
[ { "answer_id": 57164, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 1, "selected": false, "text": "<p>One more approach is having 3 tables for storing the 3 entities and having a separate table for storing the relations.</p>\n" }, { "answer_id": 57167, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 2, "selected": false, "text": "<p>Personally, I've had lots of success with your second model, using a PK/FK on a single column.</p>\n\n<p>I have never had a situation where all Alphas were required to have a record in a Bravo or Charlie table. I've always dealt with 1 &lt;-> 0..1, never 1 &lt;-> 1.</p>\n\n<p>As for your last question, that's just that many more tables.</p>\n" }, { "answer_id": 57169, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 1, "selected": false, "text": "<p>You could have a join table that specifies an Alpha and a related ID. You can then add another column specifing if it is an ID for Bravo, Charlie or whatever. Keeps the column creep down on Alpha but does add some complexity to joining queries.</p>\n" }, { "answer_id": 57184, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 0, "selected": false, "text": "<p>I'd go with option 1 unless I had a significant reason not to. It might not cost you as much space as you think, esp. if you are using varchars in Bravo. Don't forget that splitting it will cost you for foreign keys, secondary identity and needed indexes.\n<p>A place where you might run into trouble is if Bravo is unlikely to be needed (&lt;%10) AND you need to quickly query by one of its fields so you index it.</p>\n" }, { "answer_id": 57209, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 3, "selected": false, "text": "<p>If you want each Alpha to be related to by only one Bravo I would vote for the possibility with using a combined FK/PK:</p>\n\n<pre><code> Bravos\n --------\nFK PK AlphaId\n BravoOne\n BravoTwo\n BravoThree\n</code></pre>\n\n<p>This way one and only one Bravo may refer to your Alphas.</p>\n\n<p>If the Bravos and Charlies have to be mutually exclusive, the simplest method would probably to create a discriminator field:</p>\n\n<pre><code> Alpha\n --------\n PK AlphaId\n PK AlphaType NOT NULL IN (\"Bravo\", \"Charlie\")\n AlphaOne\n AlphaTwo\n AlphaThree\n\n Bravos\n --------\nFK PK AlphaId\nFK PK AlphaType == \"Bravo\"\n BravoOne\n BravoTwo\n BravoThree\n\n Charlies\n --------\nFK PK AlphaId\nFK PK AlphaType == \"Charlie\"\n CharlieOne\n CharlieTwo\n CharlieThree\n</code></pre>\n\n<p>This way the AlphaType field forces the records to always belong to exactly one subtype.</p>\n" }, { "answer_id": 57772, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 1, "selected": false, "text": "<p>I have an example working pretty well so far that fits your model:</p>\n\n<p>I Have Charlie and Bravo Tables Having the Foreign Key alpha_id from Alpha. Like your first example, except alpha is not the Primary Key, bravo_id and charlie_id are.</p>\n\n<p>I use alpha_id on every table I need to address to those entities, so, to avoid a SQL that may cause some delay researching both Bravo and Charlie to find which one Alpha is, I created a AlphaType table and on Alpha table I have its id (alpha_type_id) as foreign key. That way I can know in a programmatic way which AlphaType I am dealing with without Joining tables that may have zillions of records. in tSQL:</p>\n\n<pre><code>// For example sake lets think Id as a CHAR.\n// and pardon me on any mistake, I dont have the exact code here,\n// but you can get the idea\n\nSELECT \n (CASE alpha_type_id\n WHEN 'B' THEN '[Bravo].[Name]'\n WHEN 'C' THEN '[Charlie].[Name]'\n ELSE Null\n END)\nFROM ...\n</code></pre>\n" }, { "answer_id": 86025, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "<p>I would create a supertype / subtype relationship.</p>\n\n<pre><code> THINGS\n ------\nPK ThingId \n\n ALPHAS\n ------\nFK ThingId (not null, identifying, exported from THINGS)\n AlphaCol1\n AlphaCol2\n AlphaCol3 \n\n BRAVOS\n ------\nFK ThingId (not null, identifying, exported from THINGS)\n BravoCol1\n BravoCol2\n BravoCol3 \n\n CHARLIES\n --------\nFK ThingId (not null, identifying, exported from THINGS)\n CharlieCol1\n CharlieCol2\n CharlieCol3\n</code></pre>\n\n<p>So, for example, an alpha that has a charlie but not a bravo:-</p>\n\n<pre><code>insert into things values (1);\ninsert into alphas values (1,'alpha col 1',5,'blue');\ninsert into charlies values (1,'charlie col 1',17,'Y');\n</code></pre>\n\n<p>Note, you can't create more than one charlie for the alpha, as if you tried to create a two charlies with a ThingId of 1 the second insert would get a unique index/constraint violation.</p>\n" }, { "answer_id": 86467, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 1, "selected": false, "text": "<p>You raise a lot of questions that make it hard to select any of your proposed solutions without a lot more clarification on the exact problem you are trying to solve. Consider not just my clarification questions, but the criteria that you will use to evaluate my questions, as an indication of the amount of detail required to solve your problem:</p>\n\n<ul>\n<li>a system that's easy to learn and maintain. </li>\n</ul>\n\n<p>What \"System\" will it be easy to learn and maintain? The source code of your app, or the app's data via it's end-user interface? </p>\n\n<ul>\n<li>data integrity enforced within my database.</li>\n</ul>\n\n<p>What do you mean by \"enforced within my database\"? Does this mean you cannot by any means control data integrity any other way, i.e. the project requires only DB-based data integrity rules?</p>\n\n<ul>\n<li>a schema that matches the real-world, logical organization of my data.</li>\n</ul>\n\n<p>Can you provide us the real world, logical organization to which you are referring? It's impossible to infer it from your three examples of the data you are trying to store -- i.e. suppose all three of your structures are completely wrong. How would we know that unless we know the real-world spec?</p>\n\n<ul>\n<li>classes/objects within my programming that map well to database tables (à la Linq to SQL)</li>\n</ul>\n\n<p>This requirement sounds like your hand is being forced to create this with linq to SQL, is that the case?</p>\n\n<ul>\n<li>speedy read and write operations</li>\n</ul>\n\n<p>What is \"speedy\"? .03 seconds? 3 seconds? 30 minutes? It's unclear because you're not specifying the data size and type of operations to which you are referring.</p>\n\n<ul>\n<li>effective use of space (few null fields)</li>\n</ul>\n\n<p>Effective use of space has nothing to do with the number of null fields. If you mean a normalized database structure, that will depend again on the real-world spec's and other design elements of the application that have not been provided in the question. </p>\n" }, { "answer_id": 113304, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I'm assuming you will be using SQL Server 2000 / 2005. I have a standard pattern for 1-to-1 relationships which I use, which is not too dissimilar to your 2nd idea, but here are the differences:</p>\n\n<ul>\n<li><p>Every entity must have its own primary key first, so your Bravo, Charlie, etc tables should define their own surrogate key, in addition to the foreign key column for the Alpha table. You are making your domain model quite inflexible by specifying that the primary key of one table must be exactly the same as the primary key of another table. The entities therefore become very tightly coupled, and one entity cannot exist without another, which is not a business rule that needs to be enforced within database design.</p></li>\n<li><p>Add a foreign key constraint between the AlphaID columns in the Bravo and Charlie tables to the primary key column on the Alpha table. This gives you 1-to-many, and also allows you to specify whether the relationship is mandatory simply by setting the nullability of the FK column (something that isn't possible in your current design).</p></li>\n<li><p>Add a unique key constraint to tables Bravo, Charlie, etc on the AlphaID column. This creates a 1-to-1 relationship, with the added benefit that the unique key also acts as an index which can help to speed up queries that retrieve rows based on the foreign key value.</p></li>\n</ul>\n\n<p>The major benefit of this approach is that change is easier:</p>\n\n<ul>\n<li>Want 1-to-many back? Drop the relevant unique key, or just change it to a normal index</li>\n<li>Want Bravo to exist independently of Alpha? You've already got the surrogate key, all you do is set the AlphaID FK column to allow NULLs</li>\n</ul>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
Let's say I've got Alpha things that may or may not *be* or be *related to* Bravo or Charlie things. These are one-to-one relationships: No Alpha will relate to more than one Bravo. And no Bravo will relate to more than one Alpha. I've got a few goals: * a system that's easy to learn and maintain. * data integrity enforced within my database. * a schema that matches the real-world, logical organization of my data. * classes/objects within my programming that map well to database tables (à la Linq to SQL) * speedy read and write operations * effective use of space (few null fields) I've got three ideas… ``` PK = primary key FK = foreign key NU = nullable ``` One table with many nullalbe fields (flat file)… ``` Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU BravoOne NU BravoTwo NU BravoThree NU CharlieOne NU CharlieTwo NU CharlieThree ``` Many tables with zero nullalbe fields… ``` Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree Bravos -------- FK PK AlphaId BravoOne BravoTwo BravoThree Charlies -------- FK PK AlphaId CharlieOne CharlieTwo CharlieThree ``` Best (or worst) of both: Lots of nullalbe foreign keys to many tables… ``` Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU FK BravoId NU FK CharlieId Bravos -------- PK BravoId BravoOne BravoTwo BravoThree Charlies -------- PK CharlieId CharlieOne CharlieTwo CharlieThree ``` What if an Alpha must be either Bravo or Charlie, but not both? What if instead of just Bravos and Charlies, Alphas could also be any of Deltas, Echos, Foxtrots, or Golfs, etc…? --- **EDIT:** This is a portion of the question: [Which is the best database schema for my navigation?](https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation#57056)
If you want each Alpha to be related to by only one Bravo I would vote for the possibility with using a combined FK/PK: ``` Bravos -------- FK PK AlphaId BravoOne BravoTwo BravoThree ``` This way one and only one Bravo may refer to your Alphas. If the Bravos and Charlies have to be mutually exclusive, the simplest method would probably to create a discriminator field: ``` Alpha -------- PK AlphaId PK AlphaType NOT NULL IN ("Bravo", "Charlie") AlphaOne AlphaTwo AlphaThree Bravos -------- FK PK AlphaId FK PK AlphaType == "Bravo" BravoOne BravoTwo BravoThree Charlies -------- FK PK AlphaId FK PK AlphaType == "Charlie" CharlieOne CharlieTwo CharlieThree ``` This way the AlphaType field forces the records to always belong to exactly one subtype.
57,168
<p>I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).</p>
[ { "answer_id": 57172, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT * INTO &lt; new_table &gt; FROM &lt; existing_table &gt; WHERE &lt; clause &gt;\n</code></pre>\n" }, { "answer_id": 57188, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 8, "selected": true, "text": "<p>As long as there are no identity columns you can just </p>\n\n<pre><code>INSERT INTO TableNew\nSELECT * FROM TableOld\nWHERE [Conditions]\n</code></pre>\n" }, { "answer_id": 57189, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 6, "selected": false, "text": "<p>Alternative syntax:</p>\n\n<pre><code>INSERT tbl (Col1, Col2, ..., ColN)\n SELECT Col1, Col2, ..., ColN\n FROM Tbl2\n WHERE ...\n</code></pre>\n\n<p>The select query can (of course) include expressions, case statements, constants/literals, etc.</p>\n" }, { "answer_id": 57190, "author": "Kaniu", "author_id": 3236, "author_profile": "https://Stackoverflow.com/users/3236", "pm_score": 3, "selected": false, "text": "<pre><code>INSERT INTO DestTable\nSELECT * FROM SourceTable\nWHERE ... \n</code></pre>\n\n<p>works in SQL Server</p>\n" }, { "answer_id": 57198, "author": "ScottStonehouse", "author_id": 2342, "author_profile": "https://Stackoverflow.com/users/2342", "pm_score": 5, "selected": false, "text": "<p>Jarrett's answer creates a new table.</p>\n\n<p>Scott's answer inserts into an existing table with the same structure.</p>\n\n<p>You can also insert into a table with different structure:</p>\n\n<pre><code>INSERT Table2\n(columnX, columnY)\nSELECT column1, column2 FROM Table1\nWHERE [Conditions]\n</code></pre>\n" }, { "answer_id": 69256412, "author": "Shravya Mutyapu", "author_id": 12065837, "author_profile": "https://Stackoverflow.com/users/12065837", "pm_score": 0, "selected": false, "text": "<p>To select only few rows..This will work like charm..</p>\n<pre><code>SELECT TOP 10 *\nINTO db2.dbo.new_table\nFROM db1.dbo.old_table;\n</code></pre>\n<p>Note : Just create a new table in the required db..We need not define its structure.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536/" ]
I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).
As long as there are no identity columns you can just ``` INSERT INTO TableNew SELECT * FROM TableOld WHERE [Conditions] ```
57,183
<p>How do I get the history of commits that have been made to the repository for a particular user? </p> <p>I am able to access CVS either through the command line or TortioseCVS, so a solution using either method is sufficient.</p>
[ { "answer_id": 57218, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": true, "text": "<pre><code>cvs history -u username\n</code></pre>\n\n<p>gives a history of changes the user has made</p>\n" }, { "answer_id": 115301, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "<p>As a coder, I am mostly interested in commit changes, (as opposed to tagging, branching, etc), so I usually include the <code>-c</code> commit option as well:</p>\n\n<pre>cvs history -c -u username</pre>\n" }, { "answer_id": 5150036, "author": "Brain90", "author_id": 341959, "author_profile": "https://Stackoverflow.com/users/341959", "pm_score": 0, "selected": false, "text": "<p>Or try this one:</p>\n\n<pre><code>cvs history -x AMR -D \"your-desired-date\"\n</code></pre>\n\n<p>Example </p>\n\n<pre><code>cvs history -x AMR -D \"2012-04-12\"\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3498/" ]
How do I get the history of commits that have been made to the repository for a particular user? I am able to access CVS either through the command line or TortioseCVS, so a solution using either method is sufficient.
``` cvs history -u username ``` gives a history of changes the user has made
57,202
<p>I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created. </p> <p>How can I make the dialog box show something like this:</p> <pre><code>There was an error. Go to this page to fix it. wwww.TheWebPageToFix.com </code></pre> <p>Thanks.</p>
[ { "answer_id": 57204, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 3, "selected": false, "text": "<p>You can't. Alert boxes don't support html. You should display the error as part of the page, it's nicer than JS alerts anyway.</p>\n" }, { "answer_id": 57213, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>Or use window.open and put the <a href=\"http://qa.techinterviews.com/q/20060809080754AAs7gKM\" rel=\"nofollow noreferrer\">link there</a>.</p>\n" }, { "answer_id": 57214, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "<p>Even if you could, <code>alert()</code> boxes are generally modal - so any page opened from one would have to open in a new window. Annoying! </p>\n" }, { "answer_id": 57215, "author": "DrFloyd5", "author_id": 1736623, "author_profile": "https://Stackoverflow.com/users/1736623", "pm_score": 2, "selected": false, "text": "<pre><code>alert(\"There was an error. Got to this page to fix it.\\nwww.TheWebPageToFix.com\");\n</code></pre>\n\n<p>That's the best you can do from a JavaScript <code>alert()</code>. Your alternative option is to try and open a new tiny window that looks like a dialog. With IE you can open it modal.</p>\n" }, { "answer_id": 57233, "author": "jessegavin", "author_id": 5651, "author_profile": "https://Stackoverflow.com/users/5651", "pm_score": 3, "selected": false, "text": "<p>If you <strong><em>really</em></strong> wanted to, you could override the default behavior of the <code>alert()</code> function. Not saying you <strong><em>should</em></strong> do this.</p>\n\n<p>Here's an example that uses the YUI library, but you don't have to use YUI to do it: </p>\n\n<p><a href=\"http://htmlblog.net/yui-based-alert-box-replace-your-ugly-javascript-alert-box/\" rel=\"nofollow noreferrer\">YUI-based alert box - replace your ugly JavaScript alert box</a></p>\n" }, { "answer_id": 57236, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 3, "selected": false, "text": "<p>You can't - but here are some options:</p>\n\n<ul>\n<li><code>window.open()</code> - make your own dialog</li>\n<li>Use <code>prompt()</code> and instruct the user to copy the url</li>\n<li>Use JavaScript to just navigate them to the url directly (maybe after using <code>confirm()</code> to ask them)</li>\n<li>Include a <code>div</code> on your page with a [FIX IT] button and unhide it</li>\n<li>Use JavaScript to put a fix it URL into the user's clipboard (not recommended)</li>\n</ul>\n" }, { "answer_id": 57306, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 4, "selected": true, "text": "<p>You could try asking them if they wish to visit via window.prompt:</p>\n\n<pre><code>if(window.prompt('Do you wish to visit the following website?','http://www.google.ca'))\n location.href='http://www.google.ca/';\n</code></pre>\n\n<p>Also, Internet Explorer supports modal dialogs so you could try showing one of those:</p>\n\n<pre><code>if (window.showModalDialog)\n window.showModalDialog(\"mypage.html\",\"popup\",\"dialogWidth:255px;dialogHeight:250px\");\nelse\n window.open(\"mypage.html\",\"name\",\"height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes\");\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created. How can I make the dialog box show something like this: ``` There was an error. Go to this page to fix it. wwww.TheWebPageToFix.com ``` Thanks.
You could try asking them if they wish to visit via window.prompt: ``` if(window.prompt('Do you wish to visit the following website?','http://www.google.ca')) location.href='http://www.google.ca/'; ``` Also, Internet Explorer supports modal dialogs so you could try showing one of those: ``` if (window.showModalDialog) window.showModalDialog("mypage.html","popup","dialogWidth:255px;dialogHeight:250px"); else window.open("mypage.html","name","height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes"); ```
57,238
<p>Say I have several JavaScript includes in a page:</p> <pre><code>&lt;script type="text/javascript" src="/js/script0.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script1.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script2.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script3.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script4.js"&gt;&lt;/script&gt; </code></pre> <p>Is there a way i can tell if any of those weren't found (404) without having to manually check each one? I guess i'm looking for an online tool or something similar. Any ideas?</p>
[ { "answer_id": 57246, "author": "Alex Argo", "author_id": 5885, "author_profile": "https://Stackoverflow.com/users/5885", "pm_score": 4, "selected": true, "text": "<p>If you get the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"noreferrer\" title=\"Firebug\">Firebug</a> firefox plugin and enable the consoles it should tell you when there are errors retrieving resources in the console.</p>\n" }, { "answer_id": 57248, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 2, "selected": false, "text": "<p>I don't use other browsers enough to know where to find a similar feature in them, but Safari has an <em>Activity</em> window that displays all of the included files for a given web page and which ones were unable to be retrieved.</p>\n" }, { "answer_id": 57255, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Log your 404's.</p>\n" }, { "answer_id": 57297, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you want to monitor on the fly without actually checking if it exists, then I suggest placing dynamic variables inside the files. Then just do something like this:</p>\n\n<pre><code>var script0Exists = true; // inside script0.js\nvar script1Exists = true; // inside script1.js\n</code></pre>\n\n<p>Then in your other files, just use:</p>\n\n<pre><code>if ( script0Exists ) {\n // not a 404 - it exists\n}\n</code></pre>\n" }, { "answer_id": 57323, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you don't want to check it manually on the client you will need to do this server-side. You need to make sure whichever webserver you are using is configured to log 404s and then check that log to see which HTTP requests have failed.</p>\n" }, { "answer_id": 1531355, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 0, "selected": false, "text": "<p>If your webhost always returns the HTTP result \"200 OK\", whether the file exists or not (the latter should give a \"404 Not Found\"), the browser has no way of telling if it received a script or not.</p>\n\n<p>You might try retrieving the files via XMLHttpRequest, examine the data, and if they look like JS, either eval() them, or create a script tag pointing to the exact same URL you downloaded (if the script is cacheable, it won't be transferred again, as the browser already has it).</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
Say I have several JavaScript includes in a page: ``` <script type="text/javascript" src="/js/script0.js"></script> <script type="text/javascript" src="/js/script1.js"></script> <script type="text/javascript" src="/js/script2.js"></script> <script type="text/javascript" src="/js/script3.js"></script> <script type="text/javascript" src="/js/script4.js"></script> ``` Is there a way i can tell if any of those weren't found (404) without having to manually check each one? I guess i'm looking for an online tool or something similar. Any ideas?
If you get the [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843 "Firebug") firefox plugin and enable the consoles it should tell you when there are errors retrieving resources in the console.
57,243
<p>I am trying to do something I've done a million times and it's not working, can anyone tell me why?</p> <p>I have a table for people who sent in resumes, and it has their email address in it...</p> <p>I want to find out if any of these people have NOT signed up on the web site. The aspnet_Membership table has all the people who ARE signed up on the web site.</p> <p>There are 9472 job seekers, with unique email addresses.</p> <p>This query produces 1793 results:</p> <pre><code>select j.email from jobseeker j join aspnet_Membership m on j.email = m.email </code></pre> <p>This suggests that there should be 7679 (9472-1793) emails of people who are not signed up on the web site. Since 1793 of them DID match, I would expect the rest of them DON'T match... but when I do the query for that, I get nothing!</p> <p>Why is this query giving me nothing???</p> <pre><code>select j.email from jobseeker j where j.email not in (select email from aspnet_Membership) </code></pre> <p>I don't know how that could be not working - it basically says "show me all the emails which are IN the jobseeker table, but NOT IN the aspnet_Membership table... </p>
[ { "answer_id": 57251, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You could have a lot of duplicates out there. I'm not seeing the query error off the top of my head, but you might try writing it this way:</p>\n\n<pre><code>SELECT j.email\nFROM jobseeker j\nLEFT JOIN aspnet_Membership m ON m.email = j.email\nWHERE m.email IS NULL\n</code></pre>\n\n<p>You might also throw a GROUP BY or DISTINCT in there to get rid of duplicates.</p>\n" }, { "answer_id": 57264, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": true, "text": "<p>We had a very similar problem recently where the subquery was returning null values sometimes. Then, the in statement treats null in a weird way, I think always matching the value, so if you change your query to:</p>\n\n<pre><code>select j.email \nfrom jobseeker j\nwhere j.email not in (select email from aspnet_Membership\n where email is not null)\n</code></pre>\n\n<p>it may work....</p>\n" }, { "answer_id": 57716, "author": "Martynnw", "author_id": 5466, "author_profile": "https://Stackoverflow.com/users/5466", "pm_score": 0, "selected": false, "text": "<p>You could use <code>exists</code> instead of <code>in</code> like this:</p>\n\n<pre><code>Select J.Email\nFrom Jobseeker j\nWhere not exists (Select * From aspnetMembership a where j.email = a.email)\n</code></pre>\n\n<p>You should get better performance and avoid the 'weird' behaviour (which I suspect is to do with null values/results) when using <code>in</code>. </p>\n" }, { "answer_id": 57816, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 1, "selected": false, "text": "<p>Also see <a href=\"http://wiki.lessthandot.com/index.php/5_ways_to_return_rows_from_one_table_not_in_another_table\" rel=\"nofollow noreferrer\">Five ways to return all rows from one table which are not in another table</a> </p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5255/" ]
I am trying to do something I've done a million times and it's not working, can anyone tell me why? I have a table for people who sent in resumes, and it has their email address in it... I want to find out if any of these people have NOT signed up on the web site. The aspnet\_Membership table has all the people who ARE signed up on the web site. There are 9472 job seekers, with unique email addresses. This query produces 1793 results: ``` select j.email from jobseeker j join aspnet_Membership m on j.email = m.email ``` This suggests that there should be 7679 (9472-1793) emails of people who are not signed up on the web site. Since 1793 of them DID match, I would expect the rest of them DON'T match... but when I do the query for that, I get nothing! Why is this query giving me nothing??? ``` select j.email from jobseeker j where j.email not in (select email from aspnet_Membership) ``` I don't know how that could be not working - it basically says "show me all the emails which are IN the jobseeker table, but NOT IN the aspnet\_Membership table...
We had a very similar problem recently where the subquery was returning null values sometimes. Then, the in statement treats null in a weird way, I think always matching the value, so if you change your query to: ``` select j.email from jobseeker j where j.email not in (select email from aspnet_Membership where email is not null) ``` it may work....
57,350
<p>I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?</p>
[ { "answer_id": 57361, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>Environment.GetFolderPath( Environment.SpecialFolders.LocalApplicationData);?</p>\n\n<p>I can't remember if there is a \"Local Settings\" folder on Windows XP anymore, it seems vaguely familiar.</p>\n" }, { "answer_id": 57363, "author": "Matthew Maravillas", "author_id": 2186, "author_profile": "https://Stackoverflow.com/users/2186", "pm_score": 6, "selected": true, "text": "<p>How about this, for example:</p>\n\n<pre><code>String appData = \n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n</code></pre>\n\n<p>I don't see an enum for just the Local Settings folder.</p>\n\n<p><a href=\"http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx\" rel=\"noreferrer\">http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx</a> has a list with examples.</p>\n" }, { "answer_id": 6971240, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 2, "selected": false, "text": "<pre><code>string localPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)).FullName;\n</code></pre>\n\n<p>is the simple answer.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?
How about this, for example: ``` String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); ``` I don't see an enum for just the Local Settings folder. <http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx> has a list with examples.
57,355
<p>I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have:</p> <pre><code>struct Widget { Widget():x(0), y(0), z(0){} int x, y, z; }; struct WidgetHolder //Just a simple struct to hold four Widgets. { WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} Widget&amp; A; Widget&amp; B; Widget&amp; C; Widget&amp; D; }; class Test //This class uses four widgets internally, and must provide access to them externally. { public: const WidgetHolder AccessWidgets() const { //This should return our four widgets, but I don't want anyone messing with them. return WidgetHolder(A, B, C, D); } WidgetHolder AccessWidgets() { //This should return our four widgets, I don't care if they get changed. return WidgetHolder(A, B, C, D); } private: Widget A, B, C, D; }; int main() { const Test unchangeable; unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget&amp; be const? } </code></pre> <p>Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also.</p> <p>Can someone explain to me why the code in main() compiles?</p> <p>Thank you very much.</p>
[ { "answer_id": 57364, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "<p>unchangeable.AccessWidgets():</p>\n\n<p>At this point, you are creating a new object of type WidgetHolder. \nThis object is not protected by const. </p>\n\n<p>You are also creating new widgets in the WidgetHolder and not references to the Wdiget. </p>\n" }, { "answer_id": 57370, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<p>Your <code>WidgetHolder</code> is going to hold invalid references (pointers). You are passing objects on the stack to the constructor and then holding references to their (temporary) addresses. This is guaranteed to break.</p>\n\n<p><strong>You should only assign references to objects with the same (or greater) lifetime as the reference itself.</strong></p>\n\n<p>Pass references to the constructor if you must hold references. Even better, don't hold the references at all and just make the copies.</p>\n" }, { "answer_id": 57376, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "<p>This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to by the WidgetHolder.</p>\n\n<p>The problem appears to lie in this line:</p>\n\n<pre><code>WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){}\n</code></pre>\n\n<p>As Frank mentioned, your references inside the WidgetHolder class are going to hold invalid references after the constructor returns. Therefore, you should change this to:</p>\n\n<pre><code>WidgetHolder(Widget &amp;a, Widget &amp;b, Widget &amp;c, Widget &amp;d): A(a), B(b), C(c), D(d){}\n</code></pre>\n\n<p>After you do that, it won't compile, and I leave it as an exercise for the reader to work out the rest of the solution.</p>\n" }, { "answer_id": 57431, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "<p>You need to create a new type specifically for holding const Widget&amp; objects. Ie:</p>\n\n<pre>\n<code>\nstruct ConstWidgetHolder\n{\n ConstWidgetHolder(const Widget &a, const Widget &b, const Widget &c, const Widget &d): A(a), B(b), C(c), D(d){}\n\n const Widget& A;\n const Widget& B;\n const Widget& C;\n const Widget& D;\n};\n\nclass Test\n{\npublic:\n ConstWidgetHolder AccessWidgets() const\n {\n return ConstWidgetHolder(A, B, C, D);\n }\n</code>\n</pre>\n\n<p>You will now get the following error (in gcc 4.3):</p>\n\n<pre>\nwidget.cc: In function 'int main()':\nwidget.cc:51: error: assignment of data-member 'Widget::x' in read-only structure\n</pre>\n\n<p>A similar idiom is used in the standard library with iterators ie:</p>\n\n<pre>\n<code>\nclass vector {\n iterator begin();\n const_iterator begin() const;\n</code>\n</pre>\n" }, { "answer_id": 58537, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 0, "selected": false, "text": "<p>EDIT: he deleted his answer, making me look a bit foolish :)</p>\n\n<p>The answer by Flame is dangerously wrong. His WidgetHolder takes a reference to a value object in the constructor. As soon as the constructor returns, that passed-by-value object will be destroyed and so you'll hold a reference to a destroyed object.</p>\n\n<p>A very simple sample app using his code clearly shows this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nclass Widget\n{\n int x;\npublic:\n Widget(int inX) : x(inX){}\n ~Widget() {\n std::cout &lt;&lt; \"widget \" &lt;&lt; static_cast&lt; void*&gt;(this) &lt;&lt; \" destroyed\" &lt;&lt; std::endl;\n }\n};\n\nstruct WidgetHolder\n{\n Widget&amp; A;\n\npublic:\n WidgetHolder(Widget a): A(a) {}\n\n const Widget&amp; a() const {\n std::cout &lt;&lt; \"widget \" &lt;&lt; static_cast&lt; void*&gt;(&amp;A) &lt;&lt; \" used\" &lt;&lt; std::endl;\n return A;\n}\n\n};\n\nint main(char** argv, int argc)\n{\nWidget test(7);\nWidgetHolder holder(test);\nWidget const &amp; test2 = holder.a();\n\nreturn 0;\n} \n</code></pre>\n\n<p>The output would be something like </p>\n\n<pre>\nwidget 0xbffff7f8 destroyed\nwidget 0xbffff7f8 used\nwidget 0xbffff7f4 destroyed\n</pre>\n\n<p>To avoid this the WidgetHolder constructor should take references to the variables it wants to store as references.</p>\n\n<pre>\nstruct WidgetHolder\n{\n Widget& A;\n\npublic:\n WidgetHolder(Widget & a): A(a) {}\n\n /* ... */\n\n};\n</pre>\n" }, { "answer_id": 62608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The original query was how to return the WidgetHolder as const if the containing class was const. C++ uses const as part of the function signature and therefore you can have const and none const versions of the same function. The none const one is called when the instance is none const, and the const one is called when the instance is const. Therefore a solution is to access the widgets in the widget holder by functions, rather than directly. I have create a more simple example below which I believe answers the original question. </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nclass Test\n{\npublic:\n Test(int v){m_v = v;}\n ~Test(){printf(\"Destruct value = %d\\n\",m_v);}\n\n int&amp; GetV(){printf (\"None Const returning %d\\n\",m_v); return m_v; }\n\n const int&amp; GetV() const { printf(\"Const returning %d\\n\",m_v); return m_v;}\nprivate:\n int m_v;\n};\n\nvoid main()\n{\n // A none const object (or reference) calls the none const functions\n // in preference to the const\n Test one(10);\n int&amp; x = one.GetV();\n // We can change the member variable via the reference\n x = 12;\n\n const Test two(20);\n // This will call the const version \n two.GetV();\n\n // So the below line will not compile\n // int&amp; xx = two.GetV();\n\n // Where as this will compile\n const int&amp; xx = two.GetV();\n\n // And then the below line will not compile\n // xx = 3;\n\n}\n</code></pre>\n\n<p>In terms of the original code, I think it would be easier to have a WidgetHolder as a member of the class Test and then return either a const or none const reference to it, and make the Widgets private members of the holder, and provide a const and none const accessor for each Widget.</p>\n\n<pre><code>class WidgetHolder {\n...\n\nWidget&amp; GetA();\nconst Widget&amp; GetA() const;\n...\n};\n</code></pre>\n\n<p>And then on the main class</p>\n\n<pre><code>class Test {\n...\nWigetHolder&amp; AccessWidgets() { return m_Widgets;}\nconst WidgetHolder&amp;AcessWidgets() const { return m_Widgets;}\n\nprivate:\n WidgetHolder m_Widgets;\n...\n};\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have: ``` struct Widget { Widget():x(0), y(0), z(0){} int x, y, z; }; struct WidgetHolder //Just a simple struct to hold four Widgets. { WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} Widget& A; Widget& B; Widget& C; Widget& D; }; class Test //This class uses four widgets internally, and must provide access to them externally. { public: const WidgetHolder AccessWidgets() const { //This should return our four widgets, but I don't want anyone messing with them. return WidgetHolder(A, B, C, D); } WidgetHolder AccessWidgets() { //This should return our four widgets, I don't care if they get changed. return WidgetHolder(A, B, C, D); } private: Widget A, B, C, D; }; int main() { const Test unchangeable; unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget& be const? } ``` Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also. Can someone explain to me why the code in main() compiles? Thank you very much.
This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to by the WidgetHolder. The problem appears to lie in this line: ``` WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} ``` As Frank mentioned, your references inside the WidgetHolder class are going to hold invalid references after the constructor returns. Therefore, you should change this to: ``` WidgetHolder(Widget &a, Widget &b, Widget &c, Widget &d): A(a), B(b), C(c), D(d){} ``` After you do that, it won't compile, and I leave it as an exercise for the reader to work out the rest of the solution.
57,380
<p>Will the code below work if the clock on the server is ahead of the clock on the client?</p> <pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1)) </code></pre> <p>EDIT: the reason I ask is on one of our web apps some users are claiming they are seeing the pages ( account numbers, etc ) from a user that previously used that machine. Yet we use the line above and others to 'prevent' this from happening.</p>
[ { "answer_id": 57407, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/questions/49547/making-sure-a-webpage-is-not-cached-across-all-browsers\">This question</a> covers making sure a webpage is not cached. It seems you have to set several properties to ensure a web page is not cached across all browsers.</p>\n" }, { "answer_id": 57413, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 0, "selected": false, "text": "<p>Your problem could be caused by the browser remembering data entered into form fields. You can turn this off like this:</p>\n\n<pre><code>&lt;input autocomplete=\"off\"&gt;\n</code></pre>\n" }, { "answer_id": 57715, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 0, "selected": false, "text": "<p>As far as I can tell, the browser will check the expiry date against the local clock (although it will account for the time zone), so the code in your question may not work as you expect if the client's clock is inaccurate. Most commonly, this happens when their time looks right but is set to the wrong timezone, meaning the UTC timestamps are actually out by several hours.</p>\n\n<p>You could try setting a much older timestamp, say: 0000 1st Jan 1970 GMT (epoch)</p>\n\n<p>I think the code you have should work with the server side caching, but you can more explicitly disable it with:</p>\n\n<pre><code>Response.Cache.SetNoServerCaching();\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
Will the code below work if the clock on the server is ahead of the clock on the client? ``` Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1)) ``` EDIT: the reason I ask is on one of our web apps some users are claiming they are seeing the pages ( account numbers, etc ) from a user that previously used that machine. Yet we use the line above and others to 'prevent' this from happening.
[This question](https://stackoverflow.com/questions/49547/making-sure-a-webpage-is-not-cached-across-all-browsers) covers making sure a webpage is not cached. It seems you have to set several properties to ensure a web page is not cached across all browsers.
57,383
<p>I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it?<br> I am rethrowing the InnerException, but this destroys the stack trace.<br> Example code:</p> <pre><code>public void test1() { // Throw an exception for testing purposes throw new ArgumentException("test1"); } void test2() { try { MethodInfo mi = typeof(Program).GetMethod("test1"); mi.Invoke(this, null); } catch (TargetInvocationException tiex) { // Throw the new exception throw tiex.InnerException; } } </code></pre>
[ { "answer_id": 57387, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 5, "selected": false, "text": "<p>I think your best bet would be to just put this in your catch block:</p>\n\n<pre><code>throw;\n</code></pre>\n\n<p>And then extract the innerexception later.</p>\n" }, { "answer_id": 57389, "author": "skolima", "author_id": 3205, "author_profile": "https://Stackoverflow.com/users/3205", "pm_score": 4, "selected": false, "text": "<p>Even more reflection...</p>\n\n<pre><code>catch (TargetInvocationException tiex)\n{\n // Get the _remoteStackTraceString of the Exception class\n FieldInfo remoteStackTraceString = typeof(Exception)\n .GetField(\"_remoteStackTraceString\",\n BindingFlags.Instance | BindingFlags.NonPublic); // MS.Net\n\n if (remoteStackTraceString == null)\n remoteStackTraceString = typeof(Exception)\n .GetField(\"remote_stack_trace\",\n BindingFlags.Instance | BindingFlags.NonPublic); // Mono\n\n // Set the InnerException._remoteStackTraceString\n // to the current InnerException.StackTrace\n remoteStackTraceString.SetValue(tiex.InnerException,\n tiex.InnerException.StackTrace + Environment.NewLine);\n\n // Throw the new exception\n throw tiex.InnerException;\n}\n</code></pre>\n\n<p>Keep in mind that this may break at any time, as private fields are not part of API. See further discussion on <a href=\"https://bugzilla.novell.com/show_bug.cgi?id=425512\" rel=\"nofollow noreferrer\">Mono bugzilla</a>.</p>\n" }, { "answer_id": 57394, "author": "kokos", "author_id": 1065, "author_profile": "https://Stackoverflow.com/users/1065", "pm_score": 4, "selected": false, "text": "<p>First: don't lose the TargetInvocationException - it's valuable information when you will want to debug things.<br>\nSecond: Wrap the TIE as InnerException in your own exception type and put an OriginalException property that links to what you need (and keep the entire callstack intact).<br>\nThird: Let the TIE bubble out of your method.</p>\n" }, { "answer_id": 1663549, "author": "Eric", "author_id": 201208, "author_profile": "https://Stackoverflow.com/users/201208", "pm_score": 4, "selected": false, "text": "<pre><code>public static class ExceptionHelper\n{\n private static Action&lt;Exception&gt; _preserveInternalException;\n\n static ExceptionHelper()\n {\n MethodInfo preserveStackTrace = typeof( Exception ).GetMethod( \"InternalPreserveStackTrace\", BindingFlags.Instance | BindingFlags.NonPublic );\n _preserveInternalException = (Action&lt;Exception&gt;)Delegate.CreateDelegate( typeof( Action&lt;Exception&gt; ), preserveStackTrace ); \n }\n\n public static void PreserveStackTrace( this Exception ex )\n {\n _preserveInternalException( ex );\n }\n}\n</code></pre>\n\n<p>Call the extension method on your exception before you throw it, it will preserve the original stack trace.</p>\n" }, { "answer_id": 1992235, "author": "Boris Treukhov", "author_id": 241986, "author_profile": "https://Stackoverflow.com/users/241986", "pm_score": 3, "selected": false, "text": "<p>Guys, you are cool.. I'm gonna be a necromancer soon.</p>\n\n<pre><code> public void test1()\n {\n // Throw an exception for testing purposes\n throw new ArgumentException(\"test1\");\n }\n\n void test2()\n {\n MethodInfo mi = typeof(Program).GetMethod(\"test1\");\n ((Action)Delegate.CreateDelegate(typeof(Action), mi))();\n\n }\n</code></pre>\n" }, { "answer_id": 2085377, "author": "Anton Tykhyy", "author_id": 77724, "author_profile": "https://Stackoverflow.com/users/77724", "pm_score": 6, "selected": false, "text": "<p>It <strong>is</strong> possible to preserve the stack trace before rethrowing without reflection:</p>\n\n<pre><code>static void PreserveStackTrace (Exception e)\n{\n var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ;\n var mgr = new ObjectManager (null, ctx) ;\n var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ;\n\n e.GetObjectData (si, ctx) ;\n mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData\n mgr.DoFixups () ; // ObjectManager calls SetObjectData\n\n // voila, e is unmodified save for _remoteStackTraceString\n}\n</code></pre>\n\n<p>This wastes a lot of cycles compared to calling <code>InternalPreserveStackTrace</code> via cached delegate, but has the advantage of relying only on public functionality. Here are a couple of common usage patterns for stack-trace preserving functions:</p>\n\n<pre><code>// usage (A): cross-thread invoke, messaging, custom task schedulers etc.\ncatch (Exception e)\n{\n PreserveStackTrace (e) ;\n\n // store exception to be re-thrown later,\n // possibly in a different thread\n operationResult.Exception = e ;\n}\n\n// usage (B): after calling MethodInfo.Invoke() and the like\ncatch (TargetInvocationException tiex)\n{\n PreserveStackTrace (tiex.InnerException) ;\n\n // unwrap TargetInvocationException, so that typed catch clauses \n // in library/3rd-party code can work correctly;\n // new stack trace is appended to existing one\n throw tiex.InnerException ;\n}\n</code></pre>\n" }, { "answer_id": 9989557, "author": "chickenbyproduct", "author_id": 1309889, "author_profile": "https://Stackoverflow.com/users/1309889", "pm_score": 2, "selected": false, "text": "<p>Anpother sample code which uses exception serialization/deserialization.\nIt does not require the actual exception type to be serializable.\nAlso it uses only public/protected methods.</p>\n\n<pre><code> static void PreserveStackTrace(Exception e)\n {\n var ctx = new StreamingContext(StreamingContextStates.CrossAppDomain);\n var si = new SerializationInfo(typeof(Exception), new FormatterConverter());\n var ctor = typeof(Exception).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);\n\n e.GetObjectData(si, ctx);\n ctor.Invoke(e, new object[] { si, ctx });\n }\n</code></pre>\n" }, { "answer_id": 17091351, "author": "Paul Turner", "author_id": 138578, "author_profile": "https://Stackoverflow.com/users/138578", "pm_score": 10, "selected": true, "text": "<p>In <strong>.NET 4.5</strong> there is now the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo\" rel=\"noreferrer\"><code>ExceptionDispatchInfo</code></a> class.</p>\n<p>This lets you capture an exception and re-throw it without changing the stack-trace:</p>\n<pre><code>using ExceptionDispatchInfo = \n System.Runtime.ExceptionServices.ExceptionDispatchInfo;\n\ntry\n{\n task.Wait();\n}\ncatch(AggregateException ex)\n{\n ExceptionDispatchInfo.Capture(ex.InnerException).Throw();\n}\n</code></pre>\n<p>This works on any exception, not just <code>AggregateException</code>.</p>\n<p>It was introduced due to the <code>await</code> C# language feature, which unwraps the inner exceptions from <code>AggregateException</code> instances in order to make the asynchronous language features more like the synchronous language features.</p>\n" }, { "answer_id": 40586566, "author": "Mark", "author_id": 6192931, "author_profile": "https://Stackoverflow.com/users/6192931", "pm_score": 5, "selected": false, "text": "<p>Nobody has explained the difference between <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> and a plain <code>throw</code>, so here it is.</p>\n\n<p>The complete way to rethrow a caught exception is to use <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> (only available from .Net 4.5).</p>\n\n<p>Below there are the cases necessary to test this:</p>\n\n<p>1.</p>\n\n<pre><code>void CallingMethod()\n{\n //try\n {\n throw new Exception( \"TEST\" );\n }\n //catch\n {\n // throw;\n }\n}\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n ExceptionDispatchInfo.Capture( ex ).Throw();\n throw; // So the compiler doesn't complain about methods which don't either return or throw.\n }\n}\n</code></pre>\n\n<p>3.</p>\n\n<pre><code>void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch\n {\n throw;\n }\n}\n</code></pre>\n\n<p>4.</p>\n\n<pre><code>void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n throw new Exception( \"RETHROW\", ex );\n }\n}\n</code></pre>\n\n<p>Case 1 and case 2 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw new Exception( \"TEST\" )</code> line.</p>\n\n<p>However, case 3 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw</code> call. This means that if the <code>throw new Exception( \"TEST\" )</code> line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.</p>\n\n<p>Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.</p>\n" }, { "answer_id": 57052791, "author": "Jürgen Steinblock", "author_id": 98491, "author_profile": "https://Stackoverflow.com/users/98491", "pm_score": 4, "selected": false, "text": "<p>Based on Paul Turners answer I made an extension method</p>\n\n<pre><code> public static Exception Capture(this Exception ex)\n {\n ExceptionDispatchInfo.Capture(ex).Throw();\n return ex;\n }\n</code></pre>\n\n<p>the <code>return ex</code> ist never reached but the advantage is that I can use <code>throw ex.Capture()</code> as a one liner so the compiler won't raise an <code>not all code paths return a value</code> error.</p>\n\n<pre><code> public static object InvokeEx(this MethodInfo method, object obj, object[] parameters)\n {\n {\n return method.Invoke(obj, parameters);\n }\n catch (TargetInvocationException ex) when (ex.InnerException != null)\n {\n throw ex.InnerException.Capture();\n }\n }\n</code></pre>\n" }, { "answer_id": 73625170, "author": "Ben", "author_id": 723645, "author_profile": "https://Stackoverflow.com/users/723645", "pm_score": 1, "selected": false, "text": "<p>This is just a nice clean, modern implementation of some of the other ideas here, tested in .NET 6:</p>\n<pre><code>public static class ExceptionExtensions\n{\n [DoesNotReturn]\n public static void Rethrow(this Exception ex) \n =&gt; ExceptionDispatchInfo.Capture(ex).Throw();\n}\n</code></pre>\n<p>I wanted the value of the <code>PropertyName</code> property on <code>myObject</code> but this will work just as well when using reflection to call methods (as per OP's problem) or anything else that results in you wanting to re-throw an inner exception.</p>\n<pre><code>try\n{\n object? value = myObject.GetType().GetProperty(&quot;PropertyName&quot;)?.GetValue(myObject);\n}\ncatch (TargetInvocationException ex)\n{\n (ex.InnerException ?? ex).Rethrow();\n}\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205/" ]
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code: ``` public void test1() { // Throw an exception for testing purposes throw new ArgumentException("test1"); } void test2() { try { MethodInfo mi = typeof(Program).GetMethod("test1"); mi.Invoke(this, null); } catch (TargetInvocationException tiex) { // Throw the new exception throw tiex.InnerException; } } ```
In **.NET 4.5** there is now the [`ExceptionDispatchInfo`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo) class. This lets you capture an exception and re-throw it without changing the stack-trace: ``` using ExceptionDispatchInfo = System.Runtime.ExceptionServices.ExceptionDispatchInfo; try { task.Wait(); } catch(AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); } ``` This works on any exception, not just `AggregateException`. It was introduced due to the `await` C# language feature, which unwraps the inner exceptions from `AggregateException` instances in order to make the asynchronous language features more like the synchronous language features.
57,421
<p>I would like to make an ajax call to a different server (same domain and box, just a different port.) e.g.</p> <p>My page is</p> <pre> http://localhost/index.html </pre> <p>I would like to make a ajax get request to:</p> <pre> http://localhost:7076/?word=foo </pre> <p>I am getting this error:</p> <pre> Access to restricted URI denied (NS_ERROR_DOM_BAD_URI) </pre> <p>I know that you can not make an ajax request to a different domain, but it seem this also included different ports? are there any workarounds?</p>
[ { "answer_id": 57435, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 3, "selected": true, "text": "<p>Have a certain page on your port 80 server proxy requests to the other port. For example:</p>\n\n<pre><code>http://localhost/proxy?port=7076&amp;url=%2f%3fword%3dfoo\n</code></pre>\n\n<p>Note the url encoding on the last query string argument value.</p>\n" }, { "answer_id": 57441, "author": "Luke Smith", "author_id": 5556, "author_profile": "https://Stackoverflow.com/users/5556", "pm_score": 1, "selected": false, "text": "<p>You could use JSONP. This is where you specify a callback with the request, the response from your ajax request gets wrapped with the callback function name. Rather than using XmlHttpRequest you insert a tag into the HTML document with the URL. Then when the response is retrieved the callback function is called, passing the data as a parameter.</p>\n\n<p>Check this <a href=\"http://www.west-wind.com/Weblog/posts/107136.aspx\" rel=\"nofollow noreferrer\">blog post</a> out for an example</p>\n" }, { "answer_id": 57442, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>This is a browser restriction. All javascript calls must be to the same server and port of the home of the script. This will require something server-side to get around. I.E. have the process at <code>localhost</code> forward the request to <code>localhost:7076</code>.</p>\n" }, { "answer_id": 57444, "author": "matt", "author_id": 2646, "author_profile": "https://Stackoverflow.com/users/2646", "pm_score": 0, "selected": false, "text": "<p>It sucks, but it's necessary... Basically what you're going to need to do is proxy your AJAX request through a local proxy - some server side script / page / whatever on the same domain you're on - receive the call and forward it on to the other resource server-side. There might be some IFRAME tricks you could do but I don't think they work very well...could be wrong though, been awhile.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I would like to make an ajax call to a different server (same domain and box, just a different port.) e.g. My page is ``` http://localhost/index.html ``` I would like to make a ajax get request to: ``` http://localhost:7076/?word=foo ``` I am getting this error: ``` Access to restricted URI denied (NS_ERROR_DOM_BAD_URI) ``` I know that you can not make an ajax request to a different domain, but it seem this also included different ports? are there any workarounds?
Have a certain page on your port 80 server proxy requests to the other port. For example: ``` http://localhost/proxy?port=7076&url=%2f%3fword%3dfoo ``` Note the url encoding on the last query string argument value.
57,439
<p>No, this is not a question about generics.</p> <p>I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory).</p> <p>My problem is that <code>CreateInstance</code> fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.</p> <p>Example</p> <pre><code>// Fails Activator.CreateInstance(type); // Works Activator.CreateInstance(type, true); </code></pre> <p>I wanted to make the factory generic to make it a little simpler, like this:</p> <pre><code>public class GenericFactory&lt;T&gt; where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance&lt;T&gt;(); } } </code></pre> <p>However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal).</p> <p>Did I miss something or it isn't possible?</p>
[ { "answer_id": 57450, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 5, "selected": true, "text": "<p>To get around this, couldnt you just alter your usage as such:</p>\n\n<pre><code>public class GenericFactory&lt;T&gt; where T : MyAbstractType\n{\n public static T GetInstance()\n {\n return Activator.CreateInstance(typeof(T), true);\n }\n}\n</code></pre>\n\n<p>Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.</p>\n" }, { "answer_id": 57463, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 2, "selected": false, "text": "<p>If you absolutely require that the constructor be private you can try something like this:</p>\n\n<pre><code>public abstract class GenericFactory&lt;T&gt; where T : MyAbstractType\n{\n public static T GetInstance()\n {\n return (T)Activator.CreateInstance(typeof(T), true);\n }\n}\n</code></pre>\n\n<p>Otherwise you're best off adding the new constraint and going that route:</p>\n\n<pre><code>public abstract class GenericFactory&lt;T&gt; where T : MyAbstractType, new()\n{\n public static T GetInstance()\n {\n return new T;\n }\n}\n</code></pre>\n\n<p>You're trying to use GenericFactory as a base class for all of your factories rather than writing each from scratch right?</p>\n" }, { "answer_id": 3032285, "author": "mpastern", "author_id": 365684, "author_profile": "https://Stackoverflow.com/users/365684", "pm_score": 0, "selected": false, "text": "<p>besides Activator.CreateInstance(typeof(T), true) to work, T should have default constructor</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
No, this is not a question about generics. I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory). My problem is that `CreateInstance` fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter. Example ``` // Fails Activator.CreateInstance(type); // Works Activator.CreateInstance(type, true); ``` I wanted to make the factory generic to make it a little simpler, like this: ``` public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance<T>(); } } ``` However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal). Did I miss something or it isn't possible?
To get around this, couldnt you just alter your usage as such: ``` public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance(typeof(T), true); } } ``` Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.
57,479
<p>Help! I am using jQuery to make an AJAX call to fill in a drop-down dynamically given the user's previous input (from another drop-down, that is filled server-side). In all other browsers aside from Firefox (IE6/7, Opera, Safari), my append call actually appends the information below my existing option - "Select An ". But in Firefox, it automatically selects the last item given to the select control, regardless of whether I specify the JQuery action to .append or to replace (.html()). </p> <pre><code>&lt;select name="Products" id="Products" onchange="getHeadings(this.value);"&gt; &lt;option value=""&gt;Select Product&lt;/option&gt; &lt;/select&gt; function getProducts(Category) { $.ajax({ type: "GET", url: "getInfo.cfm", data: "Action=getProducts&amp;Category=" + Category, success: function(result){ $("#Products").html(result); } }); }; </code></pre> <p>Any thoughts? I have tried in the past to also transmit another blank first option, and then trigger a JavaScript option to re-select the first index, but this triggers the onChange event in my code, rather annoying for the user.</p> <hr> <p>Update:</p> <p>Here's an example of what the script would return</p> <pre><code>&lt;option value="3"&gt;Option 1&lt;/option&gt; &lt;option value="4"&gt;Option 2&lt;/option&gt; &lt;option value="6"&gt;Option 3&lt;/option&gt; </code></pre> <p>Optionally, if using the .html() method instead of the .append(), I would put another</p> <pre><code>&lt;option value=""&gt;Select a Product&lt;/option&gt; </code></pre> <p>at the top of the result.</p> <hr> <p>@Darryl Hein</p> <p>Here's an example of what the script would return</p> <pre><code>&lt;option value="3"&gt;Option 1&lt;/option&gt; &lt;option value="4"&gt;Option 2&lt;/option&gt; &lt;option value="6"&gt;Option 3&lt;/option&gt; </code></pre> <p>Optionally, if using the .html() method instead of the .append(), I would put another</p> <pre><code>&lt;option value=""&gt;Select a Product&lt;/option&gt; </code></pre> <p>at the top of the result.</p>
[ { "answer_id": 57514, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>I just did the following and it worked fine:</p>\n\n<pre><code>&lt;select name=\"Products\" id=\"Products\"&gt;\n&lt;option value=\"\"&gt;Select Product&lt;/option&gt;\n&lt;/select&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n$('#Products').append('&lt;option value=\"1\"&gt;test 1&lt;/option&gt;&lt;option value=\"3\"&gt;test 3&lt;/option&gt;&lt;option value=\"3\"&gt;test 3&lt;/option&gt;');\n&lt;/script&gt;\n</code></pre>\n\n<p>What is your script returning?</p>\n" }, { "answer_id": 57905, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 3, "selected": true, "text": "<p>Can you just change your success function to reset the selected item to the first option?</p>\n\n<pre><code>$(\"#Products\").append(result).selectedIndex = 0;\n</code></pre>\n\n<p>or to set it to the previous selection?</p>\n\n<pre><code>var tmpIdx = $(\"#Products\").selectedIndex;\n$(\"#Products\").append(result).selectedIndex = tmpIdx;\n</code></pre>\n\n<p>If the onChange event should not fire then you can always set a flag to indicate that the form is updating and change events can check for that flag and exit if it is set.</p>\n" }, { "answer_id": 490513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>$('#field').find('option:first').attr('selected', 'selected').parent('select');\n</code></pre>\n\n<p>see this will work</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5405/" ]
Help! I am using jQuery to make an AJAX call to fill in a drop-down dynamically given the user's previous input (from another drop-down, that is filled server-side). In all other browsers aside from Firefox (IE6/7, Opera, Safari), my append call actually appends the information below my existing option - "Select An ". But in Firefox, it automatically selects the last item given to the select control, regardless of whether I specify the JQuery action to .append or to replace (.html()). ``` <select name="Products" id="Products" onchange="getHeadings(this.value);"> <option value="">Select Product</option> </select> function getProducts(Category) { $.ajax({ type: "GET", url: "getInfo.cfm", data: "Action=getProducts&Category=" + Category, success: function(result){ $("#Products").html(result); } }); }; ``` Any thoughts? I have tried in the past to also transmit another blank first option, and then trigger a JavaScript option to re-select the first index, but this triggers the onChange event in my code, rather annoying for the user. --- Update: Here's an example of what the script would return ``` <option value="3">Option 1</option> <option value="4">Option 2</option> <option value="6">Option 3</option> ``` Optionally, if using the .html() method instead of the .append(), I would put another ``` <option value="">Select a Product</option> ``` at the top of the result. --- @Darryl Hein Here's an example of what the script would return ``` <option value="3">Option 1</option> <option value="4">Option 2</option> <option value="6">Option 3</option> ``` Optionally, if using the .html() method instead of the .append(), I would put another ``` <option value="">Select a Product</option> ``` at the top of the result.
Can you just change your success function to reset the selected item to the first option? ``` $("#Products").append(result).selectedIndex = 0; ``` or to set it to the previous selection? ``` var tmpIdx = $("#Products").selectedIndex; $("#Products").append(result).selectedIndex = tmpIdx; ``` If the onChange event should not fire then you can always set a flag to indicate that the form is updating and change events can check for that flag and exit if it is set.
57,483
<p>What is the difference between a pointer variable and a reference variable?</p>
[ { "answer_id": 57490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>Apart from syntactic sugar, a reference is a <code>const</code> pointer (<em>not</em> pointer to a <code>const</code>). You must establish what it refers to when you declare the reference variable, and you cannot change it later.</p>\n\n<p>Update: now that I think about it some more, there is an important difference.</p>\n\n<p>A const pointer's target can be replaced by taking its address and using a const cast.</p>\n\n<p>A reference's target cannot be replaced in any way short of UB.</p>\n\n<p>This should permit the compiler to do more optimization on a reference.</p>\n" }, { "answer_id": 57492, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 11, "selected": false, "text": "<ol>\n<li><p>A pointer can be re-assigned:</p>\n<pre><code>int x = 5;\nint y = 6;\nint *p;\np = &amp;x;\np = &amp;y;\n*p = 10;\nassert(x == 5);\nassert(y == 10);\n</code></pre>\n<p>A reference cannot be re-bound, and must be bound at initialization:</p>\n<pre><code>int x = 5;\nint y = 6;\nint &amp;q; // error\nint &amp;r = x;\n</code></pre>\n</li>\n<li><p>A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary <code>&amp;</code> operator and a certain amount of space that can be measured with the <code>sizeof</code> operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.</p>\n<pre><code>int x = 0;\nint &amp;r = x;\nint *p = &amp;x;\nint *p2 = &amp;r;\n\nassert(p == p2); // &amp;x == &amp;r\nassert(&amp;p != &amp;p2);\n</code></pre>\n</li>\n<li><p>You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection.</p>\n<pre><code>int x = 0;\nint y = 0;\nint *p = &amp;x;\nint *q = &amp;y;\nint **pp = &amp;p;\n\n**pp = 2;\npp = &amp;q; // *pp is now q\n**pp = 4;\n\nassert(y == 4);\nassert(x == 2);\n</code></pre>\n</li>\n<li><p>A pointer can be assigned <code>nullptr</code>, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to <code>nullptr</code>, but this is <a href=\"https://stackoverflow.com/questions/2397984/\">undefined</a> and will not behave consistently.</p>\n<pre><code>/* the code below is undefined; your compiler may optimise it\n * differently, emit warnings, or outright refuse to compile it */\n\nint &amp;r = *static_cast&lt;int *&gt;(nullptr);\n\n// prints &quot;null&quot; under GCC 10\nstd::cout\n &lt;&lt; (&amp;r != nullptr\n ? &quot;not null&quot; : &quot;null&quot;)\n &lt;&lt; std::endl;\n\nbool f(int &amp;r) { return &amp;r != nullptr; }\n\n// prints &quot;not null&quot; under GCC 10\nstd::cout\n &lt;&lt; (f(*static_cast&lt;int *&gt;(nullptr))\n ? &quot;not null&quot; : &quot;null&quot;)\n &lt;&lt; std::endl;\n</code></pre>\n<p>You can, however, have a reference to a pointer whose value is <code>nullptr</code>.</p>\n</li>\n<li><p>Pointers can iterate over an array; you can use <code>++</code> to go to the next item that a pointer is pointing to, and <code>+ 4</code> to go to the 5th element. This is no matter what size the object is that the pointer points to.</p>\n</li>\n<li><p>A pointer needs to be dereferenced with <code>*</code> to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses <code>-&gt;</code> to access its members whereas a reference uses a <code>.</code>.</p>\n</li>\n<li><p>References cannot be put into an array, whereas pointers can be (Mentioned by user @litb)</p>\n</li>\n<li><p>Const references can be bound to temporaries. Pointers cannot (not without some indirection):</p>\n<pre><code>const int &amp;x = int(12); // legal C++\nint *y = &amp;int(12); // illegal to take the address of a temporary.\n</code></pre>\n<p>This makes <code>const &amp;</code> more convenient to use in argument lists and so forth.</p>\n</li>\n</ol>\n" }, { "answer_id": 57502, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>A reference can never be <code>NULL</code>.</p>\n" }, { "answer_id": 57656, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 7, "selected": false, "text": "<p>Contrary to popular opinion, it is possible to have a reference that is NULL.</p>\n\n<pre><code>int * p = NULL;\nint &amp; r = *p;\nr = 1; // crash! (if you're lucky)\n</code></pre>\n\n<p>Granted, it is much harder to do with a reference - but if you manage it, you'll tear your hair out trying to find it. References are <em>not</em> inherently safe in C++!</p>\n\n<p>Technically this is an <strong>invalid reference</strong>, not a null reference. C++ doesn't support null references as a concept as you might find in other languages. There are other kinds of invalid references as well. <em>Any</em> invalid reference raises the spectre of <strong>undefined behavior</strong>, just as using an invalid pointer would.</p>\n\n<p>The actual error is in the dereferencing of the NULL pointer, prior to the assignment to a reference. But I'm not aware of any compilers that will generate any errors on that condition - the error propagates to a point further along in the code. That's what makes this problem so insidious. Most of the time, if you dereference a NULL pointer, you crash right at that spot and it doesn't take much debugging to figure it out.</p>\n\n<p>My example above is short and contrived. Here's a more real-world example.</p>\n\n<pre><code>class MyClass\n{\n ...\n virtual void DoSomething(int,int,int,int,int);\n};\n\nvoid Foo(const MyClass &amp; bar)\n{\n ...\n bar.DoSomething(i1,i2,i3,i4,i5); // crash occurs here due to memory access violation - obvious why?\n}\n\nMyClass * GetInstance()\n{\n if (somecondition)\n return NULL;\n ...\n}\n\nMyClass * p = GetInstance();\nFoo(*p);\n</code></pre>\n\n<p>I want to reiterate that the only way to get a null reference is through malformed code, and once you have it you're getting undefined behavior. It <strong>never</strong> makes sense to check for a null reference; for example you can try <code>if(&amp;bar==NULL)...</code> but the compiler might optimize the statement out of existence! A valid reference can never be NULL so from the compiler's view the comparison is always false, and it is free to eliminate the <code>if</code> clause as dead code - this is the essence of undefined behavior.</p>\n\n<p>The proper way to stay out of trouble is to avoid dereferencing a NULL pointer to create a reference. Here's an automated way to accomplish this.</p>\n\n<pre><code>template&lt;typename T&gt;\nT&amp; deref(T* p)\n{\n if (p == NULL)\n throw std::invalid_argument(std::string(\"NULL reference\"));\n return *p;\n}\n\nMyClass * p = GetInstance();\nFoo(deref(p));\n</code></pre>\n\n<p>For an older look at this problem from someone with better writing skills, see <a href=\"http://www.gotw.ca/conv/002.htm\" rel=\"noreferrer\">Null References</a> from Jim Hyslop and Herb Sutter.</p>\n\n<p>For another example of the dangers of dereferencing a null pointer see <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20171222-00/?p=97635\" rel=\"noreferrer\">Exposing undefined behavior when trying to port code to another platform</a> by Raymond Chen.</p>\n" }, { "answer_id": 57734, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 8, "selected": false, "text": "<p>If you want to be really pedantic, there is one thing you can do with a reference that you can't do with a pointer: extend the lifetime of a temporary object. In C++ if you bind a const reference to a temporary object, the lifetime of that object becomes the lifetime of the reference.</p>\n\n<pre><code>std::string s1 = \"123\";\nstd::string s2 = \"456\";\n\nstd::string s3_copy = s1 + s2;\nconst std::string&amp; s3_reference = s1 + s2;\n</code></pre>\n\n<p>In this example s3_copy copies the temporary object that is a result of the concatenation. Whereas s3_reference in essence becomes the temporary object. It's really a reference to a temporary object that now has the same lifetime as the reference. </p>\n\n<p>If you try this without the <code>const</code> it should fail to compile. You cannot bind a non-const reference to a temporary object, nor can you take its address for that matter.</p>\n" }, { "answer_id": 57780, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": false, "text": "<p>You forgot the most important part:</p>\n\n<p>member-access with pointers uses <code>-&gt;</code> <br/>\nmember-access with references uses <code>.</code></p>\n\n<p><code>foo.bar</code> is <em>clearly</em> superior to <code>foo-&gt;bar</code> in the same way that <a href=\"http://en.wikipedia.org/wiki/Vi\" rel=\"noreferrer\">vi</a> is <em>clearly</em> superior to <a href=\"http://en.wikipedia.org/wiki/Emacs\" rel=\"noreferrer\">Emacs</a> :-)</p>\n" }, { "answer_id": 58996, "author": "Aardvark", "author_id": 3655, "author_profile": "https://Stackoverflow.com/users/3655", "pm_score": 4, "selected": false, "text": "<p>I use references unless I need either of these:</p>\n\n<ul>\n<li><p>Null pointers can be used as a\nsentinel value, often a cheap way to\navoid function overloading or use of\na bool.</p></li>\n<li><p>You can do arithmetic on a pointer.\nFor example, <code>p += offset;</code></p></li>\n</ul>\n" }, { "answer_id": 59636, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 4, "selected": false, "text": "<p>Another interesting use of references is to supply a default argument of a user-defined type:</p>\n\n<pre><code>class UDT\n{\npublic:\n UDT() : val_d(33) {};\n UDT(int val) : val_d(val) {};\n virtual ~UDT() {};\nprivate:\n int val_d;\n};\n\nclass UDT_Derived : public UDT\n{\npublic:\n UDT_Derived() : UDT() {};\n virtual ~UDT_Derived() {};\n};\n\nclass Behavior\n{\npublic:\n Behavior(\n const UDT &amp;udt = UDT()\n ) {};\n};\n\nint main()\n{\n Behavior b; // take default\n\n UDT u(88);\n Behavior c(u);\n\n UDT_Derived ud;\n Behavior d(ud);\n\n return 1;\n}\n</code></pre>\n\n<p>The default flavor uses the 'bind const reference to a temporary' aspect of references.</p>\n" }, { "answer_id": 60148, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 5, "selected": false, "text": "<p>It doesn't matter how much space it takes up since you can't actually see any side effect (without executing code) of whatever space it would take up.</p>\n\n<p>On the other hand, one major difference between references and pointers is that temporaries assigned to const references live until the const reference goes out of scope.</p>\n\n<p>For example:</p>\n\n<pre><code>class scope_test\n{\npublic:\n ~scope_test() { printf(\"scope_test done!\\n\"); }\n};\n\n...\n\n{\n const scope_test &amp;test= scope_test();\n printf(\"in scope\\n\");\n}\n</code></pre>\n\n<p>will print:</p>\n\n<pre><code>in scope\nscope_test done!\n</code></pre>\n\n<p>This is the language mechanism that allows ScopeGuard to work.</p>\n" }, { "answer_id": 101406, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 6, "selected": false, "text": "<p>Actually, a reference is not really like a pointer.</p>\n\n<p>A compiler keeps \"references\" to variables, associating a name with a memory address; that's its job to translate any variable name to a memory address when compiling.</p>\n\n<p>When you create a reference, you only tell the compiler that you assign another name to the pointer variable; that's why references cannot \"point to null\", because a variable cannot be, and not be.</p>\n\n<p>Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.</p>\n\n<p>Now some explanation of real code:</p>\n\n<pre><code>int a = 0;\nint&amp; b = a;\n</code></pre>\n\n<p>Here you are not creating another variable that points to <code>a</code>; you are just adding another name to the memory content holding the value of <code>a</code>. This memory now has two names, <code>a</code> and <code>b</code>, and it can be addressed using either name.</p>\n\n<pre><code>void increment(int&amp; n)\n{\n n = n + 1;\n}\n\nint a;\nincrement(a);\n</code></pre>\n\n<p>When calling a function, the compiler usually generates memory spaces for the arguments to be copied to. The function signature defines the spaces that should be created and gives the name that should be used for these spaces. Declaring a parameter as a reference just tells the compiler to use the input variable memory space instead of allocating a new memory space during the method call. It may seem strange to say that your function will be directly manipulating a variable declared in the calling scope, but remember that when executing compiled code, there is no more scope; there is just plain flat memory, and your function code could manipulate any variables.</p>\n\n<p>Now there may be some cases where your compiler may not be able to know the reference when compiling, like when using an extern variable. So a reference may or may not be implemented as a pointer in the underlying code. But in the examples I gave you, it will most likely not be implemented with a pointer.</p>\n" }, { "answer_id": 596750, "author": "Christoph", "author_id": 48015, "author_profile": "https://Stackoverflow.com/users/48015", "pm_score": 9, "selected": false, "text": "<h1>What's a C++ reference (<em>for C programmers</em>)</h1>\n\n<p>A <em>reference</em> can be thought of as a <em>constant pointer</em> (not to be confused with a pointer to a constant value!) with automatic indirection, ie the compiler will apply the <code>*</code> operator for you.</p>\n\n<p>All references must be initialized with a non-null value or compilation will fail. It's neither possible to get the address of a reference - the address operator will return the address of the referenced value instead - nor is it possible to do arithmetics on references.</p>\n\n<p>C programmers might dislike C++ references as it will no longer be obvious when indirection happens or if an argument gets passed by value or by pointer without looking at function signatures.</p>\n\n<p>C++ programmers might dislike using pointers as they are considered unsafe - although references aren't really any safer than constant pointers except in the most trivial cases - lack the convenience of automatic indirection and carry a different semantic connotation.</p>\n\n<p>Consider the following statement from the <a href=\"https://isocpp.org/wiki/faq/references#overview-refs\" rel=\"noreferrer\"><em>C++ FAQ</em></a>:</p>\n\n<blockquote>\n <p>Even though a reference is often implemented using an address in the\n underlying assembly language, please do <em>not</em> think of a reference as a\n funny looking pointer to an object. A reference <em>is</em> the object. It is\n not a pointer to the object, nor a copy of the object. It <em>is</em> the\n object.</p>\n</blockquote>\n\n<p>But if a reference <em>really</em> were the object, how could there be dangling references? In unmanaged languages, it's impossible for references to be any 'safer' than pointers - there generally just isn't a way to reliably alias values across scope boundaries!</p>\n\n<h1>Why I consider C++ references useful</h1>\n\n<p>Coming from a C background, C++ references may look like a somewhat silly concept, but one should still use them instead of pointers where possible: Automatic indirection <em>is</em> convenient, and references become especially useful when dealing with <a href=\"https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"noreferrer\">RAII</a> - but not because of any perceived safety advantage, but rather because they make writing idiomatic code less awkward.</p>\n\n<p>RAII is one of the central concepts of C++, but it interacts non-trivially with copying semantics. Passing objects by reference avoids these issues as no copying is involved. If references were not present in the language, you'd have to use pointers instead, which are more cumbersome to use, thus violating the language design principle that the best-practice solution should be easier than the alternatives.</p>\n" }, { "answer_id": 1569931, "author": "Adisak", "author_id": 14904, "author_profile": "https://Stackoverflow.com/users/14904", "pm_score": 4, "selected": false, "text": "<p>Also, a reference that is a parameter to a function that is inlined may be handled differently than a pointer.</p>\n\n<pre><code>void increment(int *ptrint) { (*ptrint)++; }\nvoid increment(int &amp;refint) { refint++; }\nvoid incptrtest()\n{\n int testptr=0;\n increment(&amp;testptr);\n}\nvoid increftest()\n{\n int testref=0;\n increment(testref);\n}\n</code></pre>\n\n<p>Many compilers when inlining the pointer version one will actually force a write to memory (we are taking the address explicitly). However, they will leave the reference in a register which is more optimal.</p>\n\n<p>Of course, for functions that are not inlined the pointer and reference generate the same code and it's always better to pass intrinsics by value than by reference if they are not modified and returned by the function.</p>\n" }, { "answer_id": 2162825, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 4, "selected": false, "text": "<p>Another difference is that you can have pointers to a void type (and it means pointer to anything) but references to void are forbidden.</p>\n\n<pre><code>int a;\nvoid * p = &amp;a; // ok\nvoid &amp; p = a; // forbidden\n</code></pre>\n\n<p>I can't say I'm really happy with this particular difference. I would much prefer it would be allowed with the meaning reference to anything with an address and otherwise the same behavior for references. It would allow to define some equivalents of C library functions like memcpy using references.</p>\n" }, { "answer_id": 6076707, "author": "Kunal Vyas", "author_id": 731433, "author_profile": "https://Stackoverflow.com/users/731433", "pm_score": 5, "selected": false, "text": "<p>While both references and pointers are used to indirectly access another value, there are two important differences between references and pointers. The first is that a reference always refers to an object: It is an error to define a reference without initializing it. The behavior of assignment is the second important difference: Assigning to a reference changes the object to which the reference is bound; it does not rebind the reference to another object. Once initialized, a reference always refers to the same underlying object.</p>\n\n<p>Consider these two program fragments. In the first, we assign one pointer to another:</p>\n\n<pre><code>int ival = 1024, ival2 = 2048;\nint *pi = &amp;ival, *pi2 = &amp;ival2;\npi = pi2; // pi now points to ival2\n</code></pre>\n\n<p>After the assignment, ival, the object addressed by pi remains unchanged. The assignment changes the value of pi, making it point to a different object. Now consider a similar program that assigns two references:</p>\n\n<pre><code>int &amp;ri = ival, &amp;ri2 = ival2;\nri = ri2; // assigns ival2 to ival\n</code></pre>\n\n<p>This assignment changes ival, the value referenced by ri, and not the reference itself. After the assignment, the two references still refer to their original objects, and the value of those objects is now the same as well.</p>\n" }, { "answer_id": 9157689, "author": "Andrzej", "author_id": 838509, "author_profile": "https://Stackoverflow.com/users/838509", "pm_score": 4, "selected": false, "text": "<p>There is one fundamental difference between pointers and references that I didn't see anyone had mentioned: references enable pass-by-reference semantics in function arguments. Pointers, although it is not visible at first do not: they only provide pass-by-value semantics. This has been very nicely described in <a href=\"http://javadude.com/articles/passbyvalue.htm\">this article</a>.</p>\n\n<p>Regards,\n&amp;rzej</p>\n" }, { "answer_id": 14112711, "author": "fatma.ekici", "author_id": 1678760, "author_profile": "https://Stackoverflow.com/users/1678760", "pm_score": 5, "selected": false, "text": "<p>A reference is an alias for another variable whereas a pointer holds the memory address of a variable. References are generally used as function parameters so that the passed object is not the copy but the object itself. </p>\n\n<pre><code> void fun(int &amp;a, int &amp;b); // A common usage of references.\n int a = 0;\n int &amp;b = a; // b is an alias for a. Not so common to use. \n</code></pre>\n" }, { "answer_id": 15081923, "author": "tanweer alam", "author_id": 2002964, "author_profile": "https://Stackoverflow.com/users/2002964", "pm_score": 4, "selected": false, "text": "<p>A reference is not another name given to some memory. It's a immutable pointer that is automatically de-referenced on usage. Basically it boils down to:</p>\n\n<pre><code>int&amp; j = i;\n</code></pre>\n\n<p>It internally becomes</p>\n\n<pre><code>int* const j = &amp;i;\n</code></pre>\n" }, { "answer_id": 15423961, "author": "Arlene Batada", "author_id": 2172349, "author_profile": "https://Stackoverflow.com/users/2172349", "pm_score": 4, "selected": false, "text": "<p>This program might help in comprehending the answer of the question. This is a simple program of a reference \"j\" and a pointer \"ptr\" pointing to variable \"x\".</p>\n\n<pre><code>#include&lt;iostream&gt;\n\nusing namespace std;\n\nint main()\n{\nint *ptr=0, x=9; // pointer and variable declaration\nptr=&amp;x; // pointer to variable \"x\"\nint &amp; j=x; // reference declaration; reference to variable \"x\"\n\ncout &lt;&lt; \"x=\" &lt;&lt; x &lt;&lt; endl;\n\ncout &lt;&lt; \"&amp;x=\" &lt;&lt; &amp;x &lt;&lt; endl;\n\ncout &lt;&lt; \"j=\" &lt;&lt; j &lt;&lt; endl;\n\ncout &lt;&lt; \"&amp;j=\" &lt;&lt; &amp;j &lt;&lt; endl;\n\ncout &lt;&lt; \"*ptr=\" &lt;&lt; *ptr &lt;&lt; endl;\n\ncout &lt;&lt; \"ptr=\" &lt;&lt; ptr &lt;&lt; endl;\n\ncout &lt;&lt; \"&amp;ptr=\" &lt;&lt; &amp;ptr &lt;&lt; endl;\n getch();\n}\n</code></pre>\n\n<p>Run the program and have a look at the output and you'll understand.</p>\n\n<p>Also, spare 10 minutes and watch this video: <a href=\"https://www.youtube.com/watch?v=rlJrrGV0iOg\">https://www.youtube.com/watch?v=rlJrrGV0iOg</a></p>\n" }, { "answer_id": 18555015, "author": "Cort Ammon", "author_id": 2728148, "author_profile": "https://Stackoverflow.com/users/2728148", "pm_score": 6, "selected": false, "text": "<p>References are very similar to pointers, but they are specifically crafted to be helpful to optimizing compilers.</p>\n\n<ul>\n<li>References are designed such that it is substantially easier for the compiler to trace which reference aliases which variables. Two major features are very important: no \"reference arithmetic\" and no reassigning of references. These allow the compiler to figure out which references alias which variables at compile time.</li>\n<li>References are allowed to refer to variables which do not have memory addresses, such as those the compiler chooses to put into registers. If you take the address of a local variable, it is very hard for the compiler to put it in a register.</li>\n</ul>\n\n<p>As an example:</p>\n\n<pre><code>void maybeModify(int&amp; x); // may modify x in some way\n\nvoid hurtTheCompilersOptimizer(short size, int array[])\n{\n // This function is designed to do something particularly troublesome\n // for optimizers. It will constantly call maybeModify on array[0] while\n // adding array[1] to array[2]..array[size-1]. There's no real reason to\n // do this, other than to demonstrate the power of references.\n for (int i = 2; i &lt; (int)size; i++) {\n maybeModify(array[0]);\n array[i] += array[1];\n }\n}\n</code></pre>\n\n<p>An optimizing compiler may realize that we are accessing a[0] and a[1] quite a bunch. It would love to optimize the algorithm to:</p>\n\n<pre><code>void hurtTheCompilersOptimizer(short size, int array[])\n{\n // Do the same thing as above, but instead of accessing array[1]\n // all the time, access it once and store the result in a register,\n // which is much faster to do arithmetic with.\n register int a0 = a[0];\n register int a1 = a[1]; // access a[1] once\n for (int i = 2; i &lt; (int)size; i++) {\n maybeModify(a0); // Give maybeModify a reference to a register\n array[i] += a1; // Use the saved register value over and over\n }\n a[0] = a0; // Store the modified a[0] back into the array\n}\n</code></pre>\n\n<p>To make such an optimization, it needs to prove that nothing can change array[1] during the call. This is rather easy to do. i is never less than 2, so array[i] can never refer to array[1]. maybeModify() is given a0 as a reference (aliasing array[0]). Because there is no \"reference\" arithmetic, the compiler just has to prove that maybeModify never gets the address of x, and it has proven that nothing changes array[1].</p>\n\n<p>It also has to prove that there are no ways a future call could read/write a[0] while we have a temporary register copy of it in a0. This is often trivial to prove, because in many cases it is obvious that the reference is never stored in a permanent structure like a class instance.</p>\n\n<p>Now do the same thing with pointers</p>\n\n<pre><code>void maybeModify(int* x); // May modify x in some way\n\nvoid hurtTheCompilersOptimizer(short size, int array[])\n{\n // Same operation, only now with pointers, making the\n // optimization trickier.\n for (int i = 2; i &lt; (int)size; i++) {\n maybeModify(&amp;(array[0]));\n array[i] += array[1];\n }\n}\n</code></pre>\n\n<p>The behavior is the same; only now it is much harder to prove that maybeModify does not ever modify array[1], because we already gave it a pointer; the cat is out of the bag. Now it has to do the much more difficult proof: a static analysis of maybeModify to prove it never writes to &amp;x + 1. It also has to prove that it never saves off a pointer that can refer to array[0], which is just as tricky.</p>\n\n<p>Modern compilers are getting better and better at static analysis, but it is always nice to help them out and use references.</p>\n\n<p>Of course, barring such clever optimizations, compilers will indeed turn references into pointers when needed.</p>\n\n<p>EDIT: Five years after posting this answer, I found an actual technical difference where references are different than just a different way of looking at the same addressing concept. References can modify the lifespan of temporary objects in a way that pointers cannot.</p>\n\n<pre><code>F createF(int argument);\n\nvoid extending()\n{\n const F&amp; ref = createF(5);\n std::cout &lt;&lt; ref.getArgument() &lt;&lt; std::endl;\n};\n</code></pre>\n\n<p>Normally temporary objects such as the one created by the call to <code>createF(5)</code> are destroyed at the end of the expression. However, by binding that object to a reference, <code>ref</code>, C++ will extend the lifespan of that temporary object until <code>ref</code> goes out of scope.</p>\n" }, { "answer_id": 21092239, "author": "Life", "author_id": 2143209, "author_profile": "https://Stackoverflow.com/users/2143209", "pm_score": 5, "selected": false, "text": "<p>This is based on the <a href=\"http://www.cplusplus.com/files/tutorial.pdf\">tutorial</a>. What is written makes it more clear:</p>\n\n<pre><code>&gt;&gt;&gt; The address that locates a variable within memory is\n what we call a reference to that variable. (5th paragraph at page 63)\n\n&gt;&gt;&gt; The variable that stores the reference to another\n variable is what we call a pointer. (3rd paragraph at page 64)\n</code></pre>\n\n<p>Simply to remember that,</p>\n\n<pre><code>&gt;&gt;&gt; reference stands for memory location\n&gt;&gt;&gt; pointer is a reference container (Maybe because we will use it for\nseveral times, it is better to remember that reference.)\n</code></pre>\n\n<p>What's more, as we can refer to almost any pointer tutorial, a pointer is an object that is supported by pointer arithmetic which makes pointer similar to an array.</p>\n\n<p>Look at the following statement,</p>\n\n<pre><code>int Tom(0);\nint &amp; alias_Tom = Tom;\n</code></pre>\n\n<p><code>alias_Tom</code> can be understood as an <code>alias of a variable</code> (different with <code>typedef</code>, which is <code>alias of a type</code>) <code>Tom</code>. It is also OK to forget the terminology of such statement is to create a reference of <code>Tom</code>.</p>\n" }, { "answer_id": 26370807, "author": "Tory", "author_id": 3093272, "author_profile": "https://Stackoverflow.com/users/3093272", "pm_score": 4, "selected": false, "text": "<p>At the risk of adding to confusion, I want to throw in some input, I'm sure it mostly depends on how the compiler implements references, but in the case of gcc the idea that a reference can only point to a variable on the stack is not actually correct, take this for example:</p>\n\n<pre><code>#include &lt;iostream&gt;\nint main(int argc, char** argv) {\n // Create a string on the heap\n std::string *str_ptr = new std::string(\"THIS IS A STRING\");\n // Dereference the string on the heap, and assign it to the reference\n std::string &amp;str_ref = *str_ptr;\n // Not even a compiler warning! At least with gcc\n // Now lets try to print it's value!\n std::cout &lt;&lt; str_ref &lt;&lt; std::endl;\n // It works! Now lets print and compare actual memory addresses\n std::cout &lt;&lt; str_ptr &lt;&lt; \" : \" &lt;&lt; &amp;str_ref &lt;&lt; std::endl;\n // Exactly the same, now remember to free the memory on the heap\n delete str_ptr;\n}\n</code></pre>\n\n<p>Which outputs this:</p>\n\n<pre><code>THIS IS A STRING\n0xbb2070 : 0xbb2070\n</code></pre>\n\n<p>If you notice even the memory addresses are exactly the same, meaning the reference is successfully pointing to a variable on the heap! Now if you really want to get freaky, this also works:</p>\n\n<pre><code>int main(int argc, char** argv) {\n // In the actual new declaration let immediately de-reference and assign it to the reference\n std::string &amp;str_ref = *(new std::string(\"THIS IS A STRING\"));\n // Once again, it works! (at least in gcc)\n std::cout &lt;&lt; str_ref;\n // Once again it prints fine, however we have no pointer to the heap allocation, right? So how do we free the space we just ignorantly created?\n delete &amp;str_ref;\n /*And, it works, because we are taking the memory address that the reference is\n storing, and deleting it, which is all a pointer is doing, just we have to specify\n the address with '&amp;' whereas a pointer does that implicitly, this is sort of like\n calling delete &amp;(*str_ptr); (which also compiles and runs fine).*/\n}\n</code></pre>\n\n<p>Which outputs this:</p>\n\n<pre><code>THIS IS A STRING\n</code></pre>\n\n<p>Therefore a reference IS a pointer under the hood, they both are just storing a memory address, where the address is pointing to is irrelevant, what do you think would happen if I called std::cout &lt;&lt; str_ref; AFTER calling delete &amp;str_ref? Well, obviously it compiles fine, but causes a segmentation fault at runtime because it's no longer pointing at a valid variable, we essentially have a broken reference that still exists (until it falls out of scope), but is useless.</p>\n\n<p>In other words, a reference is nothing but a pointer that has the pointer mechanics abstracted away, making it safer and easier to use (no accidental pointer math, no mixing up '.' and '->', etc.), assuming you don't try any nonsense like my examples above ;)</p>\n\n<p>Now <strong>regardless</strong> of how a compiler handles references, it will <strong>always</strong> have some kind of pointer under the hood, because a reference <strong>must</strong> refer to a specific variable at a specific memory address for it to work as expected, there is no getting around this (hence the term 'reference').</p>\n\n<p>The only major rule that's important to remember with references is that they must be defined at the time of declaration (with the exception of a reference in a header, in that case it must be defined in the constructor, after the object it's contained in is constructed it's too late to define it).</p>\n\n<p><strong>Remember, my examples above are just that, examples demonstrating what a reference is, you would never want to use a reference in those ways! For proper usage of a reference there are plenty of answers on here already that hit the nail on the head</strong></p>\n" }, { "answer_id": 26636769, "author": "Lightness Races in Orbit", "author_id": 560648, "author_profile": "https://Stackoverflow.com/users/560648", "pm_score": 5, "selected": false, "text": "<p>There is a semantic difference that may appear esoteric if you are not familiar with studying computer languages in an abstract or even academic fashion.</p>\n\n<p>At the highest-level, the idea of references is that they are transparent \"aliases\". Your computer may use an address to make them work, but you're not supposed to worry about that: you're supposed to think of them as \"just another name\" for an existing object and the syntax reflects that. They are stricter than pointers so your compiler can more reliably warn you when you about to create a dangling reference, than when you are about to create a dangling pointer.</p>\n\n<p>Beyond that, there are of course some practical differences between pointers and references. The syntax to use them is obviously different, and you cannot \"re-seat\" references, have references to nothingness, or have pointers to references.</p>\n" }, { "answer_id": 27667467, "author": "George R", "author_id": 289442, "author_profile": "https://Stackoverflow.com/users/289442", "pm_score": 4, "selected": false, "text": "<p>Maybe some metaphors will help; \nIn the context of your desktop screenspace - </p>\n\n<ul>\n<li>A reference requires you to specify an actual window.</li>\n<li>A pointer requires the location of a piece of space on screen that you assure it will contain zero or more instances of that window type.</li>\n</ul>\n" }, { "answer_id": 28410732, "author": "Destructor", "author_id": 3777958, "author_profile": "https://Stackoverflow.com/users/3777958", "pm_score": 4, "selected": false, "text": "<p>A reference to a pointer is possible in C++, but the reverse is not possible means a pointer to a reference isn't possible. A reference to a pointer provides a cleaner syntax to modify the pointer.\nLook at this example:</p>\n\n<pre><code>#include&lt;iostream&gt;\nusing namespace std;\n\nvoid swap(char * &amp;str1, char * &amp;str2)\n{\n char *temp = str1;\n str1 = str2;\n str2 = temp;\n}\n\nint main()\n{\n char *str1 = \"Hi\";\n char *str2 = \"Hello\";\n swap(str1, str2);\n cout&lt;&lt;\"str1 is \"&lt;&lt;str1&lt;&lt;endl;\n cout&lt;&lt;\"str2 is \"&lt;&lt;str2&lt;&lt;endl;\n return 0;\n}\n</code></pre>\n\n<p>And consider the C version of the above program. In C you have to use pointer to pointer (multiple indirection), and it leads to confusion and the program may look complicated.</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n/* Swaps strings by swapping pointers */\nvoid swap1(char **str1_ptr, char **str2_ptr)\n{\n char *temp = *str1_ptr;\n *str1_ptr = *str2_ptr;\n *str2_ptr = temp;\n}\n\nint main()\n{\n char *str1 = \"Hi\";\n char *str2 = \"Hello\";\n swap1(&amp;str1, &amp;str2);\n printf(\"str1 is %s, str2 is %s\", str1, str2);\n return 0;\n}\n</code></pre>\n\n<p>Visit the following for more information about reference to pointer:</p>\n\n<ul>\n<li><em><a href=\"http://markgodwin.blogspot.in/2009/08/c-reference-to-pointer.html\">C++: Reference to Pointer</a></em></li>\n<li><em><a href=\"http://www.codeguru.com/cpp/cpp/cpp_mfc/pointers/article.php/c4089/PointertoPointer-and-ReferencetoPointer.htm\">Pointer-to-Pointer and Reference-to-Pointer</a></em></li>\n</ul>\n\n<p>As I said, a pointer to a reference isn't possible. Try the following program:</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint main()\n{\n int x = 10;\n int *ptr = &amp;x;\n int &amp;*ptr1 = ptr;\n}\n</code></pre>\n" }, { "answer_id": 36823688, "author": "Zorgiev", "author_id": 1466198, "author_profile": "https://Stackoverflow.com/users/1466198", "pm_score": 3, "selected": false, "text": "<p>The difference is that non-constant pointer variable(not to be confused with a pointer to constant) may be changed at some time during program execution, requires pointer semantics to be used(&amp;,*) operators, while references can be set upon initialization only(that's why you can set them in constructor initializer list only, but not somehow else) and use ordinary value accessing semantics. Basically references were introduced to allow support for operators overloading as I had read in some very old book. As somebody stated in this thread - pointer can be set to 0 or whatever value you want. 0(NULL, nullptr) means that the pointer is initialized with nothing. It is an error to dereference null pointer. But actually the pointer may contain a value that doesn't point to some correct memory location. References in their turn try not to allow a user to initialize a reference to something that cannot be referenced due to the fact that you always provide rvalue of correct type to it. Although there are a lot of ways to make reference variable be initialized to a wrong memory location - it is better for you not to dig this deep into details. On machine level both pointer and reference work uniformly - via pointers. Let's say in essential references are syntactic sugar. rvalue references are different to this - they are naturally stack/heap objects.</p>\n" }, { "answer_id": 41507371, "author": "dhokar.w", "author_id": 7383437, "author_profile": "https://Stackoverflow.com/users/7383437", "pm_score": 3, "selected": false, "text": "<h3>Difference between pointer and reference</h3>\n<p>A pointer can be initialized to 0 and a reference not. In fact, a reference must also refer to an object, but a pointer can be the null pointer:</p>\n<pre><code>int* p = 0;\n</code></pre>\n<p>But we can’t have <code>int&amp; p = 0;</code> and also <code>int&amp; p=5 ;</code>.</p>\n<p>In fact to do it properly, we must have declared and defined an object at the first then we can make a reference to that object, so the correct implementation of the previous code will be:</p>\n<pre><code>Int x = 0;\nInt y = 5;\nInt&amp; p = x;\nInt&amp; p1 = y;\n</code></pre>\n<p>Another important point is that is we can make the declaration of the pointer without initialization however no such thing can be done in case of reference which must make a reference always to variable or object. However such use of a pointer is risky so generally we check if the pointer is actually is pointing to something or not. In case of a reference no such check is necessary, because we know already that referencing to an object during declaration is mandatory.</p>\n<p>Another difference is that pointer can point to another object however reference is always referencing to the same object, let’s take this example:</p>\n<pre><code>Int a = 6, b = 5;\nInt&amp; rf = a;\n\nCout &lt;&lt; rf &lt;&lt; endl; // The result we will get is 6, because rf is referencing to the value of a.\n\nrf = b;\ncout &lt;&lt; a &lt;&lt; endl; // The result will be 5 because the value of b now will be stored into the address of a so the former value of a will be erased\n</code></pre>\n<p>Another point: When we have a template like an STL template such kind of a class template will always return a reference, not a pointer, to make easy reading or assigning new value using operator []:</p>\n<pre><code>Std ::vector&lt;int&gt;v(10); // Initialize a vector with 10 elements\nV[5] = 5; // Writing the value 5 into the 6 element of our vector, so if the returned type of operator [] was a pointer and not a reference we should write this *v[5]=5, by making a reference we overwrite the element by using the assignment &quot;=&quot;\n</code></pre>\n" }, { "answer_id": 44957687, "author": "Ap31", "author_id": 6350858, "author_profile": "https://Stackoverflow.com/users/6350858", "pm_score": 4, "selected": false, "text": "<p>I feel like there is yet another point that hasn't been covered here. </p>\n\n<p>Unlike the pointers, references are <strong>syntactically equivalent</strong> to the object they refer to, i.e. any operation that can be applied to an object works for a reference, and with the exact same syntax (the exception is of course the initialization). </p>\n\n<p>While this may appear superficial, I believe this property is crucial for a number of C++ features, for example: </p>\n\n<ul>\n<li><p><em>Templates</em>. Since template parameters are duck-typed, syntactic properties of a type is all that matters, so often the same template can be used with both <code>T</code> and <code>T&amp;</code>.<br>\n(or <code>std::reference_wrapper&lt;T&gt;</code> which still relies on an implicit cast\nto <code>T&amp;</code>)<br>\nTemplates that cover both <code>T&amp;</code> and <code>T&amp;&amp;</code> are even more common. </p></li>\n<li><p><em>Lvalues</em>. Consider the statement <code>str[0] = 'X';</code> Without references it would only work for c-strings (<code>char* str</code>). Returning the character by reference allows user-defined classes to have the same notation. </p></li>\n<li><p><em>Copy constructors</em>. Syntactically it makes sense to pass objects to copy constructors, and not pointers to objects. But there is just no way for a copy constructor to take an object by value - it would result in a recursive call to the same copy constructor. This leaves references as the only option here. </p></li>\n<li><p><em>Operator overloads</em>. With references it is possible to introduce indirection to an operator call - say, <code>operator+(const T&amp; a, const T&amp; b)</code> while retaining the same infix notation. This also works for regular overloaded functions. </p></li>\n</ul>\n\n<p>These points empower a considerable part of C++ and the standard library so this is quite a major property of references.</p>\n" }, { "answer_id": 46829217, "author": "Hitokage", "author_id": 3027604, "author_profile": "https://Stackoverflow.com/users/3027604", "pm_score": 2, "selected": false, "text": "<p>I always decide by <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f60-prefer-t-over-t-when-no-argument-is-a-valid-option\" rel=\"nofollow noreferrer\">this</a> rule from C++ Core Guidelines:</p>\n\n<blockquote>\n <p>Prefer T* over T&amp; when \"no argument\" is a valid option</p>\n</blockquote>\n" }, { "answer_id": 47073963, "author": "Arthur Tacca", "author_id": 7008416, "author_profile": "https://Stackoverflow.com/users/7008416", "pm_score": 4, "selected": false, "text": "<p>There is a very important non-technical difference between pointers and references: An argument passed to a function by pointer is much more visible than an argument passed to a function by non-const reference. For example:</p>\n\n<pre><code>void fn1(std::string s);\nvoid fn2(const std::string&amp; s);\nvoid fn3(std::string&amp; s);\nvoid fn4(std::string* s);\n\nvoid bar() {\n std::string x;\n fn1(x); // Cannot modify x\n fn2(x); // Cannot modify x (without const_cast)\n fn3(x); // CAN modify x!\n fn4(&amp;x); // Can modify x (but is obvious about it)\n}\n</code></pre>\n\n<p>Back in C, a call that looks like <code>fn(x)</code> can only be passed by value, so it definitely cannot modify <code>x</code>; to modify an argument you would need to pass a pointer <code>fn(&amp;x)</code>. So if an argument wasn't preceded by an <code>&amp;</code> you knew it would not be modified. (The converse, <code>&amp;</code> means modified, was not true because you would sometimes have to pass large read-only structures by <code>const</code> pointer.)</p>\n\n<p>Some argue that this is such a useful feature when reading code, that pointer parameters should always be used for modifiable parameters rather than non-<code>const</code> references, even if the function never expects a <code>nullptr</code>. That is, those people argue that function signatures like <code>fn3()</code> above should not be allowed. <a href=\"http://google.github.io/styleguide/cppguide.html#Reference_Arguments\" rel=\"noreferrer\">Google's C++ style guidelines</a> are an example of this.</p>\n" }, { "answer_id": 47243714, "author": "Immac", "author_id": 3203817, "author_profile": "https://Stackoverflow.com/users/3203817", "pm_score": 2, "selected": false, "text": "<p>I have an analogy for references and pointers, think of references as another name for an object and pointers as the address of an object.</p>\n\n<pre><code>// receives an alias of an int, an address of an int and an int value\npublic void my_function(int&amp; a,int* b,int c){\n int d = 1; // declares an integer named d\n int &amp;e = d; // declares that e is an alias of d\n // using either d or e will yield the same result as d and e name the same object\n int *f = e; // invalid, you are trying to place an object in an address\n // imagine writting your name in an address field \n int *g = f; // writes an address to an address\n g = &amp;d; // &amp;d means get me the address of the object named d you could also\n // use &amp;e as it is an alias of d and write it on g, which is an address so it's ok\n}\n</code></pre>\n" }, { "answer_id": 50058587, "author": "Michael Zheng", "author_id": 1673396, "author_profile": "https://Stackoverflow.com/users/1673396", "pm_score": 2, "selected": false, "text": "<p>Taryn♦ said:</p>\n\n<blockquote>\n <p>You can't take the address of a reference like you can with pointers.</p>\n</blockquote>\n\n<p>Actually you can.</p>\n\n<p>I'm quoting from <a href=\"https://stackoverflow.com/a/1950826\">an answer on another question</a>:</p>\n\n<blockquote>\n <p><a href=\"https://isocpp.org/wiki/faq/references\" rel=\"nofollow noreferrer\">The C++ FAQ</a> says it best:</p>\n \n <p>Unlike a pointer, once a reference is bound to an object, it can not be \"reseated\" to another object. The reference itself isn't an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent).</p>\n</blockquote>\n" }, { "answer_id": 51658995, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 2, "selected": false, "text": "<p>You can use the difference between references and pointers if you follow a convention for arguments passed to a function. Const references are for data passed into a function, and pointers are for data passed out of a function. In other languages, you can explicit notate this with keywords such as <code>in</code> and <code>out</code>. In C++, you can declare (by convention) the equivalent. For example,</p>\n\n<pre><code>void DoSomething(const Foo&amp; thisIsAnInput, Foo* thisIsAnOutput)\n{\n if (thisIsAnOuput)\n *thisIsAnOutput = thisIsAnInput;\n}\n</code></pre>\n\n<p>The use of references as inputs and pointers as outputs is part of the <a href=\"https://google.github.io/styleguide/cppguide.html#Output_Parameters\" rel=\"noreferrer\">Google style guide</a>.</p>\n" }, { "answer_id": 54222315, "author": "ebasconp", "author_id": 1680261, "author_profile": "https://Stackoverflow.com/users/1680261", "pm_score": 2, "selected": false, "text": "<p>Beside all the answers here,</p>\n\n<p>you can implement operator overloading using references:</p>\n\n<pre><code>my_point operator+(const my_point&amp; a, const my_point&amp; b)\n{\n return { a.x + b.x, a.y + b.y };\n}\n</code></pre>\n\n<p>Using parameters as value would create temporary copies of the original arguments and using pointers would not invoke this function because of pointers arithmetics.</p>\n" }, { "answer_id": 54731129, "author": "FrankHB", "author_id": 2307646, "author_profile": "https://Stackoverflow.com/users/2307646", "pm_score": 5, "selected": false, "text": "<h2>The direct answer</h2>\n\n<p>What is a reference in C++? Some specific instance of type that <strong>is not an object type</strong>.</p>\n\n<p>What is a pointer in C++? Some specific instance of type that <strong>is an object type</strong>.</p>\n\n<p>From <a href=\"http://eel.is/c++draft/basic.types#8\" rel=\"noreferrer\">the ISO C++ definition of object type</a>:</p>\n\n<blockquote>\n <p>An <em>object</em> type is a (possibly <em>cv</em>-qualified) type that is not a function type, not a reference type, and not <em>cv</em> void.</p>\n</blockquote>\n\n<p>It may be important to know, object type is a top-level category of the type universe in C++. Reference is also a top-level category. <strong>But pointer is not.</strong></p>\n\n<p>Pointers and references are mentioned together <a href=\"http://eel.is/c++draft/basic.compound#1\" rel=\"noreferrer\">in the context of <em>compound type</em></a>. This is basically due to the nature of the declarator syntax inherited from (and extended) C, which has no references. (Besides, there are more than one kind of declarator of references since C++ 11, while pointers are still \"unityped\": <code>&amp;</code>+<code>&amp;&amp;</code> vs. <code>*</code>.) So drafting a language specific by \"extension\" with similar style of C in this context is somewhat reasonable. (I will still argue that the syntax of declarators wastes the syntactic expressiveness <em>a lot</em>, makes both human users and implementations frustrating. Thus, all of them are not qualified to be <em>built-in</em> in a new language design. This is a totally different topic about PL design, though.)</p>\n\n<p>Otherwise, it is insignificant that pointers can be qualified as a specific sorts of types with references together. They simply share too few common properties besides the syntax similarity, so there is no need to put them together in most cases.</p>\n\n<p>Note the statements above only mentions \"pointers\" and \"references\" as types. There are some interested questions about their instances (like variables). There also come too many misconceptions.</p>\n\n<p>The differences of the top-level categories can already reveal many concrete differences not tied to pointers directly:</p>\n\n<ul>\n<li>Object types can have top-level <code>cv</code> qualifiers. References cannot.</li>\n<li>Variable of object types do occupy storage as per <a href=\"http://eel.is/c++draft/intro.abstract\" rel=\"noreferrer\">the abstract machine</a> semantics. Reference do not necessary occupy storage (see the section about misconceptions below for details).</li>\n<li>...</li>\n</ul>\n\n<p>A few more special rules on references:</p>\n\n<ul>\n<li><a href=\"http://eel.is/c++draft/dcl.ref#5\" rel=\"noreferrer\">Compound declarators are more restrictive on references.</a></li>\n<li>References can <a href=\"http://eel.is/c++draft/dcl.ref#6\" rel=\"noreferrer\">collapse</a>.\n\n<ul>\n<li>Special rules on <code>&amp;&amp;</code> parameters (as the \"forwarding references\") based on reference collapsing during template parameter deduction allow <a href=\"https://stackoverflow.com/questions/3582001\">\"perfect forwarding\"</a> of parameters.</li>\n</ul></li>\n<li>References have special rules in initialization. The lifetime of variable declared as a reference type can be different to ordinary objects via extension.\n\n<ul>\n<li>BTW, a few other contexts like initialization involving <code>std::initializer_list</code> follows some similar rules of reference lifetime extension. It is another can of worms.</li>\n</ul></li>\n<li>...</li>\n</ul>\n\n<h2>The misconceptions</h2>\n\n<h3><a href=\"https://en.wikipedia.org/wiki/Syntactic_sugar\" rel=\"noreferrer\">Syntactic sugar</a></h3>\n\n<blockquote>\n <p>I know references are syntactic sugar, so code is easier to read and write.</p>\n</blockquote>\n\n<p>Technically, this is plain wrong. References are not syntactic sugar of any other features in C++, because they cannot be exactly replaced by other features without any semantic differences.</p>\n\n<p>(Similarly, <em>lambda-expression</em>s are <em>not</em> syntactic sugar of any other features in C++ because it cannot be precisely simulated with \"unspecified\" properties like <a href=\"http://eel.is/c++draft/expr.prim.lambda#capture-9\" rel=\"noreferrer\">the declaration order of the captured variables</a>, which may be important because the initialization order of such variables can be significant.)</p>\n\n<p>C++ only has a few kinds of syntactic sugars in this strict sense. One instance is (inherited from C) the built-in (non-overloaded) operator <code>[]</code>, which <a href=\"http://eel.is/c++draft/expr.sub#1\" rel=\"noreferrer\">is defined exactly having same semantic properties of specific forms of combination over built-in operator unary <code>*</code> and binary <code>+</code></a>.</p>\n\n<h3>Storage</h3>\n\n<blockquote>\n <p><strong><em>So, a pointer and a reference both use the same amount of memory.</em></strong></p>\n</blockquote>\n\n<p>The statement above is simply wrong. To avoid such misconceptions, look at the ISO C++ rules instead:</p>\n\n<p>From <a href=\"http://eel.is/c++draft/intro.object#1\" rel=\"noreferrer\">[intro.object]/1</a>:</p>\n\n<blockquote>\n <p>... An object occupies a region of storage in its period of construction, throughout its lifetime, and in its period of destruction. ...</p>\n</blockquote>\n\n<p>From <a href=\"http://eel.is/c++draft/dcl.ref#4\" rel=\"noreferrer\">[dcl.ref]/4</a>:</p>\n\n<blockquote>\n <p>It is unspecified whether or not a reference requires storage.</p>\n</blockquote>\n\n<p>Note these are <em>semantic</em> properties.</p>\n\n<h3>Pragmatics</h3>\n\n<p>Even that pointers are not qualified enough to be put together with references in the sense of the language design, there are still some arguments making it debatable to make choice between them in some other contexts, for example, when making choices on parameter types.</p>\n\n<p>But this is not the whole story. I mean, there are more things than pointers vs references you have to consider.</p>\n\n<p>If you don't have to stick on such over-specific choices, in most cases the answer is short: <strong>you do not have the necessity to use pointers, so you don't</strong>. Pointers are usually bad enough because they imply too many things you don't expect and they will rely on too many implicit assumptions undermining the maintainability and (even) portability of the code. <strong>Unnecessarily relying on pointers is definitely a bad style and it should be avoided in the sense of modern C++.</strong> Reconsider your purpose and you will finally find that <strong>pointer is the feature of last sorts</strong> in most cases.</p>\n\n<ul>\n<li>Sometimes the language rules explicitly require specific types to be used. If you want to use these features, obey the rules.\n\n<ul>\n<li>Copy constructors require specific types of <em>cv</em>-<code>&amp;</code> reference type as the 1st parameter type. (And usually it should be <code>const</code> qualified.)</li>\n<li>Move constructors require specific types of <em>cv</em>-<code>&amp;&amp;</code> reference type as the 1st parameter type. (And usually there should be no qualifiers.)</li>\n<li>Specific overloads of operators require reference or non reference types. For example:\n\n<ul>\n<li>Overloaded <code>operator=</code> as special member functions requires reference types similar to 1st parameter of copy/move constructors.</li>\n<li>Postfix <code>++</code> requires dummy <code>int</code>.</li>\n<li>...</li>\n</ul></li>\n</ul></li>\n<li>If you know pass-by-value (i.e. using non-reference types) is sufficient, use it directly, particularly when using an implementation supporting C++17 mandated copy elision. (<strong>Warning</strong>: However, to <strong>exhaustively</strong> reason about the necessity can be <a href=\"https://stackoverflow.com/a/53825424\">very complicated</a>.)</li>\n<li>If you want to operate some handles with ownership, use smart pointers like <code>unique_ptr</code> and <code>shared_ptr</code> (or even with homebrew ones by yourself if you require them to be <em>opaque</em>), rather than raw pointers.</li>\n<li>If you are doing some iterations over a range, use iterators (or some ranges which are not provided by the standard library yet), rather than raw pointers unless you are convinced raw pointers will do better (e.g. for less header dependencies) in very specific cases.</li>\n<li>If you know pass-by-value is sufficient and you want some explicit nullable semantics, use wrapper like <code>std::optional</code>, rather than raw pointers.</li>\n<li>If you know pass-by-value is not ideal for the reasons above, and you don't want nullable semantics, use {lvalue, rvalue, forwarding}-references.</li>\n<li>Even when you do want semantics like traditional pointer, there are often something more appropriate, like <code>observer_ptr</code> in Library Fundamental TS.</li>\n</ul>\n\n<p>The only exceptions cannot be worked around in the current language:</p>\n\n<ul>\n<li>When you are implementing smart pointers above, you may have to deal with raw pointers.</li>\n<li>Specific language-interoperation routines require pointers, like <code>operator new</code>. (However, <em>cv</em>-<code>void*</code> is still quite different and safer compared to the ordinary object pointers because it rules out unexpected pointer arithmetics unless you are relying on some non conforming extension on <code>void*</code> like GNU's.)</li>\n<li>Function pointers can be converted from lambda expressions without captures, while function references cannot. You have to use function pointers in non-generic code for such cases, even you deliberately do not want nullable values.</li>\n</ul>\n\n<p>So, in practice, the answer is so obvious: <strong>when in doubt, avoid pointers</strong>. You have to use pointers only when there are very explicit reasons that nothing else is more appropriate. Except a few exceptional cases mentioned above, such choices are almost always not purely C++-specific (but likely to be language-implementation-specific). Such instances can be:</p>\n\n<ul>\n<li>You have to serve to old-style (C) APIs.</li>\n<li>You have to meet the ABI requirements of specific C++ implementations.</li>\n<li>You have to interoperate at runtime with different language implementations (including various assemblies, language runtime and FFI of some high-level client languages) based on assumptions of specific implementations.</li>\n<li>You have to improve efficiency of the translation (compilation &amp; linking) in some extreme cases.</li>\n<li>You have to avoid symbol bloat in some extreme cases.</li>\n</ul>\n\n<h3>Language neutrality caveats</h3>\n\n<p>If you come to see the question via <a href=\"https://www.google.com/search?q=pointer+vs+reference&amp;hl=en\" rel=\"noreferrer\">some Google search result (not specific to C++)</a>, this is very likely to be the wrong place.</p>\n\n<p>References in C++ is quite \"odd\", as it is essentially not first-class: <a href=\"http://eel.is/c++draft/expr#type-1\" rel=\"noreferrer\">they will be treated as the objects or the functions being referred to</a> so they have no chance to support some first-class operations like being the left operand of <a href=\"http://eel.is/c++draft/expr.ref\" rel=\"noreferrer\">the member access operator</a> independently to the type of the referred object. Other languages may or may not have similar restrictions on their references.</p>\n\n<p>References in C++ will likely not preserve the meaning across different languages. For example, references in general do not imply nonnull properties on values like they in C++, so such assumptions may not work in some other languages (and you will find counterexamples quite easily, e.g. Java, C#, ...). </p>\n\n<p>There can still be some common properties among references in different programming languages in general, but let's leave it for some other questions in SO.</p>\n\n<p>(A side note: the question may be significant earlier than any \"C-like\" languages are involved, like <a href=\"https://academic.oup.com/comjnl/article-pdf/17/4/325/1215152/17-4-325.pdf\" rel=\"noreferrer\">ALGOL 68 vs. PL/I</a>.)</p>\n" }, { "answer_id": 57304404, "author": "Xitalogy", "author_id": 1691559, "author_profile": "https://Stackoverflow.com/users/1691559", "pm_score": 3, "selected": false, "text": "<h2>Some key pertinent details about references and pointers</h2>\n<h3>Pointers</h3>\n<ul>\n<li>Pointer variables are declared using the <em>unary suffix declarator operator</em> *</li>\n<li>Pointer objects are assigned an address value, for example, by assignment to an array object, the address of an object using the &amp; <em>unary prefix operator</em>, or assignment to the value of another pointer object</li>\n<li>A pointer can be reassigned any number of times, pointing to different objects</li>\n<li>A pointer is a variable that holds the assigned address. It takes up storage in memory equal to the size of the address for the target machine architecture</li>\n<li>A pointer can be mathematically manipulated, for instance, by the increment or addition operators. Hence, one can iterate with a pointer, etc.</li>\n<li>To get or set the contents of the object referred to by a pointer, one must use the <em>unary prefix operator</em> * to <em>dereference</em> it</li>\n</ul>\n<h3>References</h3>\n<ul>\n<li>References must be initialized when they are declared.</li>\n<li>References are declared using the <em>unary suffix declarator operator</em> &amp;.</li>\n<li>When initializing a reference, one uses the name of the object to which they will refer directly, without the need for the <em>unary prefix operator</em> &amp;</li>\n<li>Once initialized, references cannot be pointed to something else by assignment or arithmetical manipulation</li>\n<li>There is no need to dereference the reference to get or set the contents of the object it refers to</li>\n<li>Assignment operations on the reference manipulate the contents of the object it points to (after initialization), not the reference itself (does not change where it points to)</li>\n<li>Arithmetic operations on the reference manipulate the contents of the object it points to, not the reference itself (does not change where it points to)</li>\n<li>In pretty much all implementations, the reference is actually stored as an address in memory of the referred to object. Hence, it takes up storage in memory equal to the size of the address for the target machine architecture just like a pointer object</li>\n</ul>\n<p>Even though pointers and references are implemented in much the same way &quot;under-the-hood,&quot; the compiler treats them differently, resulting in all the differences described above.</p>\n<h3>Article</h3>\n<p>A recent article I wrote that goes into much greater detail than I can show here and should be very helpful for this question, especially about how things happen in memory:</p>\n<p><a href=\"https://www.xitalogy.com/programming/2019/08/15/a-tour-of-cpp-arrays-pointers-and-references-under-the-hood.html\" rel=\"nofollow noreferrer\">Arrays, Pointers and References Under the Hood In-Depth Article</a></p>\n" }, { "answer_id": 57363123, "author": "Gerard ONeill", "author_id": 1331672, "author_profile": "https://Stackoverflow.com/users/1331672", "pm_score": 1, "selected": false, "text": "<p>\"I know references are syntactic sugar, so code is easier to read and write\"</p>\n\n<p>This. A reference is not another way to implement a pointer, although it covers a huge pointer use case. A pointer is a datatype -- an address that in general points to a actual value. However it can be set to zero, or a couple of places after the address using address arithmetic, etc. A reference is 'syntactic sugar' for a variable which has its own value.</p>\n\n<p>C only had pass by value semantics. Getting the address of the data a variable was referring to and sending that to a function was a way to pass by 'reference'. A reference shortcuts this semantically by 'referring' to the original data location itself. So:</p>\n\n<pre><code>int x = 1;\nint *y = &amp;x;\nint &amp;z = x;\n</code></pre>\n\n<p>Y is an int pointer, pointing to the location where x is stored.\nX and Z refer to the same storage place (the stack or the heap).</p>\n\n<p>Alot of people have talked about the difference between the two (pointers and references) as if they are the same thing with different usages. They are not the same at all. </p>\n\n<p>1) \"A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding.\" -- a pointer is an address data type which points to data. A reference is another name for the data. So you <em>can</em> 'reassign' a reference. You just can't reassign the data location it refers to. Just like you can't change the data location that 'x' refers to, you can't do that to 'z'. </p>\n\n<pre><code>x = 2;\n*y = 2;\nz = 2;\n</code></pre>\n\n<p>The same. It is a reassignment. </p>\n\n<p>2) \"Pointers can point nowhere (NULL), whereas a reference always refers to an object\" -- again with the confusion. The reference is just another name for the object. A null pointer means (semantically) that it isn't referring to anything, whereas the reference was created by saying it was another name for 'x'. Since</p>\n\n<p>3) \"You can't take the address of a reference like you can with pointers\" -- Yes you can. Again with the confusion. If you are trying to find the address of the pointer that is being used as a reference, that is a problem -- cause references are not pointers to the object. They are the object. So you can get the address of the object, and you can get the address of the pointer. Cause they are both getting the address of data (one the object's location in memory, the other the pointer to the objects location in memory).</p>\n\n<pre><code>int *yz = &amp;z; -- legal\nint **yy = &amp;y; -- legal\n\nint *yx = &amp;x; -- legal; notice how this looks like the z example. x and z are equivalent.\n</code></pre>\n\n<p>4) \"There's no \"reference arithmetic\"\" -- again with the confusion -- since the example above has z being a reference to x and both are therefore integers, 'reference' arithmetic means for example adding 1 to the value referred to by x.</p>\n\n<pre><code>x++;\nz++;\n\n*y++; // what people assume is happening behind the scenes, but isn't. it would produce the same results in this example.\n*(y++); // this one adds to the pointer, and then dereferences it. It makes sense that a pointer datatype (an address) can be incremented. Just like an int can be incremented. \n</code></pre>\n" }, { "answer_id": 57728134, "author": "Hitesh Jangid", "author_id": 9473321, "author_profile": "https://Stackoverflow.com/users/9473321", "pm_score": 1, "selected": false, "text": "<p>Basic meaning of pointer(*) is \"Value at address of\" which means whatever address you provide it will give value at that address. Once you change the address it will give the new value, while reference variable used to reference any particular variable and which can't be change to reference any other variable in future. </p>\n" }, { "answer_id": 59591539, "author": "S.S. Anne", "author_id": 10795151, "author_profile": "https://Stackoverflow.com/users/10795151", "pm_score": 3, "selected": false, "text": "<p>Summary from answers and links below:</p>\n\n<ol>\n<li>A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding.</li>\n<li>Pointers can point nowhere (<code>NULL</code>), whereas a reference always refers to an object.</li>\n<li>You can't take the address of a reference like you can with pointers.</li>\n<li>There's no \"reference arithmetic\" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in <code>&amp;obj + 5</code>).</li>\n</ol>\n\n<p>To clarify a misconception:</p>\n\n<blockquote>\n <p><em>The C++ standard is very careful to avoid dictating how a compiler may\n implement references, but every C++ compiler implements\n references as pointers. That is, a declaration such as:</em></p>\n\n<pre><code>int &amp;ri = i;\n</code></pre>\n \n <p><strong><em>if it's not optimized away entirely</em></strong>, <em>allocates the same amount of storage\n as a pointer, and places the address\n of <code>i</code> into that storage.</em></p>\n</blockquote>\n\n<p><strong><em>So, a pointer and a reference both use the same amount of memory.</em></strong></p>\n\n<p>As a general rule,</p>\n\n<ul>\n<li>Use references in function parameters and return types to provide useful and self-documenting interfaces.</li>\n<li>Use pointers for implementing algorithms and data structures.</li>\n</ul>\n\n<p>Interesting read:</p>\n\n<ul>\n<li>My all-time favorite <a href=\"https://yosefk.com/c++fqa/ref.html\" rel=\"noreferrer\">C++ FAQ lite</a>.</li>\n<li><a href=\"https://www.embedded.com/references-vs-pointers\" rel=\"noreferrer\">References vs. Pointers</a>.</li>\n<li><a href=\"https://www.embedded.com/an-introduction-to-references\" rel=\"noreferrer\">An Introduction to References</a>.</li>\n<li><a href=\"https://www.embedded.com/references-and-const\" rel=\"noreferrer\">References and const</a>.</li>\n</ul>\n" }, { "answer_id": 59748316, "author": "Sadhana Singh", "author_id": 9011579, "author_profile": "https://Stackoverflow.com/users/9011579", "pm_score": 3, "selected": false, "text": "<p>in simple words, we can say a reference is an alternative name for a variable whereas,\na pointer is a variable that holds the address of another variable.\ne.g.</p>\n\n<pre><code>int a = 20;\nint &amp;r = a;\nr = 40; /* now the value of a is changed to 40 */\n\nint b =20;\nint *ptr;\nptr = &amp;b; /*assigns address of b to ptr not the value */\n</code></pre>\n" }, { "answer_id": 62199065, "author": "Lewis Kelsey", "author_id": 7194773, "author_profile": "https://Stackoverflow.com/users/7194773", "pm_score": 4, "selected": false, "text": "<p>A reference is a const pointer. <code>int * const a = &amp;b</code> is the same as <code>int&amp; a = b</code>. This is why there's is no such thing as a const reference, because it is already const, whereas a reference to const is <code>const int * const a</code>. When you compile using -O0, the compiler will place the address of b on the stack in both situations, and as a member of a class, it will also be present in the object on the stack/heap identically to if you had declared a const pointer. With -Ofast, it is free to optimise this out. A const pointer and reference are both optimised away.</p>\n<p>Unlike a const pointer, there is no way to take the address of the reference itself, as it will be interpreted as the address of the variable it references. Because of this, on -Ofast, the const pointer representing the reference (the address of the variable being referenced) will always be optimised off the stack, but if the program absolutely needs the address of an actual const pointer (the address of the pointer itself, not the address it points to) i.e. you print the address of the const pointer, then the const pointer will be placed on the stack so that it has an address.</p>\n<p>Otherwise it is identical i.e. when you print the that address it points to:</p>\n<pre><code>#include &lt;iostream&gt;\n\nint main() {\n int a =1;\n int* b = &amp;a;\n std::cout &lt;&lt; b ;\n}\n\nint main() {\n int a =1;\n int&amp; b = a;\n std::cout &lt;&lt; &amp;b ;\n}\n</code></pre>\n<pre><code>they both have the same assembly output\n-Ofast:\nmain:\n sub rsp, 24\n mov edi, OFFSET FLAT:_ZSt4cout\n lea rsi, [rsp+12]\n mov DWORD PTR [rsp+12], 1\n call std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp; std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;::_M_insert&lt;void const*&gt;(void const*)\n xor eax, eax\n add rsp, 24\n ret\n--------------------------------------------------------------------\n-O0:\nmain:\n push rbp\n mov rbp, rsp\n sub rsp, 16\n mov DWORD PTR [rbp-12], 1\n lea rax, [rbp-12]\n mov QWORD PTR [rbp-8], rax\n mov rax, QWORD PTR [rbp-8]\n mov rsi, rax\n mov edi, OFFSET FLAT:_ZSt4cout\n call std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;::operator&lt;&lt;(void const*)\n mov eax, 0\n leave\n ret\n</code></pre>\n<p>The pointer has been optimised off the stack, and the pointer isn't even dereferenced on -Ofast in both cases, instead it uses a compile time value.</p>\n<p>As members of an object they are identical on -O0 through -Ofast.</p>\n<pre><code>#include &lt;iostream&gt;\nint b=1;\nstruct A {int* i=&amp;b; int&amp; j=b;};\nA a;\nint main() {\n std::cout &lt;&lt; &amp;a.j &lt;&lt; &amp;a.i;\n}\n\nThe address of b is stored twice in the object. \n\na:\n .quad b\n .quad b\n</code></pre>\n<pre><code> mov rax, QWORD PTR a[rip+8] //&amp;a.j\n mov esi, OFFSET FLAT:a //&amp;a.i\n</code></pre>\n<p>When you pass by reference, on -O0, you pass the address of the variable referenced, so it is identical to passing by pointer i.e. the address the const pointer contains. On -Ofast this is optimised out by the compiler in an inline call if the function can be inlined, as the dynamic scope is known, but in the function definition, the parameter is always dereferenced as a pointer (expecting the address of the variable being referenced by the reference) where it may be used by another translation unit and the dynamic scope is unknown to the compiler, unless of course the function is declared as a static function, then it can't be used outside of the translation unit and then it passes by value so long as it isn't modified in the function by reference, then it will pass the address of the variable being referenced by the reference that you're passing, and on -Ofast this will be passed in a register and kept off of the stack if there are enough volatile registers in the calling convention.</p>\n" }, { "answer_id": 68188598, "author": "Sarath Govind", "author_id": 12284466, "author_profile": "https://Stackoverflow.com/users/12284466", "pm_score": 2, "selected": false, "text": "<p>A pointer is a variable that holds the memory address of another variable , where as a reference is an alias to an existing variable. (another name of the already existing variable)</p>\n<p>1.\nA pointer can be initialised as:</p>\n<pre><code>int b = 15;\nint *q = &amp;b;\n</code></pre>\n<p>OR</p>\n<pre><code>int *q;\nq = &amp;b;\n</code></pre>\n<p>where as reference,</p>\n<pre><code>int b=15;\nint &amp;c=b;\n</code></pre>\n<p>(declare and initialize in a single step)</p>\n<ol start=\"2\">\n<li>A pointer can be assigned to null, but reference cannot</li>\n<li>Various arithmetic operations can be performed on pointers whereas there is no such thing called Reference Arithmetic.</li>\n<li>A pointer can be reassigned , but reference cannot</li>\n<li>A pointer has its own memory address and size on the stack whereas a reference shares the same memory address</li>\n</ol>\n" }, { "answer_id": 69281608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>you can not dereference a reference like a pointer, which when dereferenced gives values at that location,</p>\n<p>both reference and pointer work by the address though...</p>\n<p>so</p>\n<p>you can do this</p>\n<p>int* val = 0xDEADBEEF;\n*val is something at 0xDEADBEEF.</p>\n<p>you can not do this\nint&amp; val = 1;</p>\n<p>*val is not allowed.</p>\n" }, { "answer_id": 73017343, "author": "CPP_is_no_STANDARD", "author_id": 18032104, "author_profile": "https://Stackoverflow.com/users/18032104", "pm_score": 0, "selected": false, "text": "<p>In short,</p>\n<blockquote>\n<p>Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. - Extracted from Geeks for Geeks</p>\n</blockquote>\n<blockquote>\n<p>References: A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer, is also implemented by storing the address of an object. - Extracted from Geeks for Geeks</p>\n</blockquote>\n<p>Another picture for more details:</p>\n<p><a href=\"https://i.stack.imgur.com/PBfzi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PBfzi.png\" alt=\"From the web.\" /></a></p>\n" }, { "answer_id": 73859509, "author": "Ezh", "author_id": 589119, "author_profile": "https://Stackoverflow.com/users/589119", "pm_score": 2, "selected": false, "text": "<p>Think about a pointer as about a business card:</p>\n<ul>\n<li>It gives you a chance to contact someone</li>\n<li>It can be empy</li>\n<li>It can contain wrong or outdated information</li>\n<li>You are not sure someone, mentioned on it, is even still alive</li>\n<li>You can't talk directly to the card, you only can use it to call someone</li>\n<li>Maybe there are many such cards exist</li>\n</ul>\n<p>Think about a reference as about an active call with someone:</p>\n<ul>\n<li>You are pretty sure someone, you contacted, is alive</li>\n<li>You can talk directly, no extra calls are needed</li>\n<li>You are pretty sure you talk not to an empty place or a piece of garbage</li>\n<li>You can't be sure you are the only one, who is currently talking with this object</li>\n</ul>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ]
What is the difference between a pointer variable and a reference variable?
1. A pointer can be re-assigned: ``` int x = 5; int y = 6; int *p; p = &x; p = &y; *p = 10; assert(x == 5); assert(y == 10); ``` A reference cannot be re-bound, and must be bound at initialization: ``` int x = 5; int y = 6; int &q; // error int &r = x; ``` 2. A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary `&` operator and a certain amount of space that can be measured with the `sizeof` operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable. ``` int x = 0; int &r = x; int *p = &x; int *p2 = &r; assert(p == p2); // &x == &r assert(&p != &p2); ``` 3. You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection. ``` int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p; **pp = 2; pp = &q; // *pp is now q **pp = 4; assert(y == 4); assert(x == 2); ``` 4. A pointer can be assigned `nullptr`, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to `nullptr`, but this is [undefined](https://stackoverflow.com/questions/2397984/) and will not behave consistently. ``` /* the code below is undefined; your compiler may optimise it * differently, emit warnings, or outright refuse to compile it */ int &r = *static_cast<int *>(nullptr); // prints "null" under GCC 10 std::cout << (&r != nullptr ? "not null" : "null") << std::endl; bool f(int &r) { return &r != nullptr; } // prints "not null" under GCC 10 std::cout << (f(*static_cast<int *>(nullptr)) ? "not null" : "null") << std::endl; ``` You can, however, have a reference to a pointer whose value is `nullptr`. 5. Pointers can iterate over an array; you can use `++` to go to the next item that a pointer is pointing to, and `+ 4` to go to the 5th element. This is no matter what size the object is that the pointer points to. 6. A pointer needs to be dereferenced with `*` to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses `->` to access its members whereas a reference uses a `.`. 7. References cannot be put into an array, whereas pointers can be (Mentioned by user @litb) 8. Const references can be bound to temporaries. Pointers cannot (not without some indirection): ``` const int &x = int(12); // legal C++ int *y = &int(12); // illegal to take the address of a temporary. ``` This makes `const &` more convenient to use in argument lists and so forth.
57,484
<p>I'm trying to do a basic "OR" on three fields using a hibernate criteria query.</p> <p>Example</p> <pre><code>class Whatever{ string name; string address; string phoneNumber; } </code></pre> <p>I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".</p>
[ { "answer_id": 57526, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 8, "selected": true, "text": "<p>You want to use <code>Restrictions.disjuntion()</code>. Like so</p>\n\n<pre><code>session.createCriteria(Whatever.class)\n .add(Restrictions.disjunction()\n .add(Restrictions.eq(\"name\", queryString))\n .add(Restrictions.eq(\"address\", queryString))\n .add(Restrictions.eq(\"phoneNumber\", queryString))\n );\n</code></pre>\n\n<p>See the Hibernate doc <a href=\"http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-narrowing\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 57541, "author": "Rob Oxspring", "author_id": 1867, "author_profile": "https://Stackoverflow.com/users/1867", "pm_score": 6, "selected": false, "text": "<p>Assuming you have a hibernate session to hand then something like the following should work:</p>\n\n<pre><code>Criteria c = session.createCriteria(Whatever.class);\nDisjunction or = Restrictions.disjunction();\nor.add(Restrictions.eq(\"name\",searchString));\nor.add(Restrictions.eq(\"address\",searchString));\nor.add(Restrictions.eq(\"phoneNumber\",searchString));\nc.add(or);\n</code></pre>\n" }, { "answer_id": 58643, "author": "Geir-Tore Lindsve", "author_id": 4582, "author_profile": "https://Stackoverflow.com/users/4582", "pm_score": 2, "selected": false, "text": "<p>Just in case anyone should stumble upon this with the same question for NHibernate:</p>\n\n<pre><code>ICriteria c = session.CreateCriteria(typeof (Whatever))\n .Add(Expression.Disjunction()\n .Add(Expression.Eq(\"name\", searchString))\n .Add(Expression.Eq(\"address\", searchString))\n .Add(Expression.Eq(\"phoneNumber\", searchString)));\n</code></pre>\n" }, { "answer_id": 25283984, "author": "Dharmender Rawat", "author_id": 3936966, "author_profile": "https://Stackoverflow.com/users/3936966", "pm_score": 4, "selected": false, "text": "<pre><code> //Expression : (c1 AND c2) OR (c3) \n\n\n Criteria criteria = session.createCriteria(Employee.class);\n\n Criterion c1 = Restrictions.like(\"name\", \"%e%\");\n Criterion c2 = Restrictions.ge(\"salary\", 10000.00);\n Criterion c3 = Restrictions.like(\"name\", \"%YYY%\");\n Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3);\n criteria.add(c4);\n</code></pre>\n\n<p>//Same thing can be done for (c1 OR c2) AND c3, or any complex expression.</p>\n" }, { "answer_id": 25294252, "author": "Dharmender Rawat", "author_id": 3936975, "author_profile": "https://Stackoverflow.com/users/3936975", "pm_score": 3, "selected": false, "text": "<pre><code>//Expression : (c1 AND c2) OR (c3) \n\n\n Criteria criteria = session.createCriteria(Employee.class);\n\n Criterion c1 = Restrictions.like(\"name\", \"%e%\");\n Criterion c2 = Restrictions.ge(\"salary\", 10000.00);\n Criterion c3 = Restrictions.like(\"name\", \"%YYY%\");\n Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3);\n criteria.add(c4);\n\n //Same thing can be done for (c1 OR c2) AND c3, or any complex expression.\n</code></pre>\n" }, { "answer_id": 36494224, "author": "Tiago Medici", "author_id": 6117311, "author_profile": "https://Stackoverflow.com/users/6117311", "pm_score": 1, "selected": false, "text": "<p>The conditions can be applied using the or / and in different levels of the query\nusing disjunction</p>\n\n<pre><code>Criteria query = getCriteria(\"ENTITY_NAME\");\nquery.add(Restrictions.ne(\"column Name\", current _value));\n\nDisjunction disjunction = Restrictions.disjunction();\n\nif (param_1 != null)\n disjunction.add(Restrictions.or(Restrictions.eq(\"column Name\", param1)));\n\nif (param_2 != null)\n disjunction.add(Restrictions.or(Restrictions.eq(\"column Name\", param_2)));\n\nif (param_3 != null)\n disjunction.add(Restrictions.or(Restrictions.eq(\"column Name\", param_3)));\nif (param_4 != null &amp;&amp; param_5 != null)\n disjunction.add(Restrictions.or(Restrictions.and(Restrictions.eq(\"column Name\", param_4 ), Restrictions.eq(\"column Name\", param_5 ))));\n\nif (disjunction.conditions() != null &amp;&amp; disjunction.conditions().iterator().hasNext())\n query.add(Restrictions.and(disjunction));\n\nreturn query.list();\n</code></pre>\n" }, { "answer_id": 56698228, "author": "ronak", "author_id": 6673843, "author_profile": "https://Stackoverflow.com/users/6673843", "pm_score": 1, "selected": false, "text": "<p>This is what worked for me for an OR condition, that too with an IN condition and not the answer up-voted most on this discussion:</p>\n\n<pre><code>criteria.add( Restrictions.or(\n Restrictions.eq(ch.getPath(ch.propertyResolver().getXXXX()), \"OR_STRING\"),\n Restrictions.in(ch.getPath(ch.propertyResolver().getYYYY()), new String[]{\"AA\",\"BB\",\"CC\"})\n ));\n</code></pre>\n\n<p><strong>Resulting Query:</strong></p>\n\n<pre><code> and (\n this_.XXXX=? \n or this_.YYYY in (\n ?, ?, ?\n )\n ) \n</code></pre>\n" }, { "answer_id": 63181989, "author": "Gaspar", "author_id": 3681565, "author_profile": "https://Stackoverflow.com/users/3681565", "pm_score": 1, "selected": false, "text": "<p>If someone is using CriteriaQuery instead of Criteria, you can put all your expressions in a <code>Predicate</code> list and put a OR by predicates size like this:</p>\n<pre><code>List&lt;Predicate&gt; predicates = new ArrayList&lt;&gt;();\nif (...) {\n predicates.add(...);\n}\n\ncriteriaQuery.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
I'm trying to do a basic "OR" on three fields using a hibernate criteria query. Example ``` class Whatever{ string name; string address; string phoneNumber; } ``` I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".
You want to use `Restrictions.disjuntion()`. Like so ``` session.createCriteria(Whatever.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", queryString)) .add(Restrictions.eq("address", queryString)) .add(Restrictions.eq("phoneNumber", queryString)) ); ``` See the Hibernate doc [here](http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-narrowing).
57,488
<p>Does anyone know of a way to declare a date constant that is compatible with international dates?</p> <p>I've tried:</p> <pre><code>' not international compatible public const ADate as Date = #12/31/04# ' breaking change if you have an optional parameter that defaults to this value ' because it isnt constant. public shared readonly ADate As New Date(12, 31, 04) </code></pre>
[ { "answer_id": 57511, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>OK, I am unsure what you are trying to do here:</p>\n\n<ul>\n<li>The code you are posting is <strong>NOT</strong> .NET, are you trying to port?</li>\n<li>DateTime's cannot be declared as constants.</li>\n<li>DateTime's are a data type, so once init'ed, the format that they were init'ed from is irrelevant.</li>\n<li>If you need a constant value, then just create a method to always return the same DateTime.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>public static DateTime SadDayForAll()\n{\n return new DateTime(2001, 09, 11);\n}\n</code></pre>\n\n<h3>Update</h3>\n\n<p>Where the hell are you getting all that from?!</p>\n\n<ul>\n<li>There <strong>are</strong> differences between C# and VB.NET, and this highlights one of them.</li>\n<li><strong>Date</strong> is not a <a href=\"http://www.ondotnet.com/pub/a/dotnet/2001/07/30/vb7.html\" rel=\"nofollow noreferrer\">.NET data type</a> - <strong>DateTime</strong> is.</li>\n<li>It looks like you can create DateTime constants in VB.NET but there are limitations</li>\n<li>The method was there to try and help you, since you cannot create a const from a <strong>variable</strong> (i.e. optional param). That doesn't even make sense.</li>\n</ul>\n" }, { "answer_id": 57604, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": false, "text": "<p>According to the Microsoft documentation,</p>\n\n<p>\"You must enclose a Date literal within number signs (# #). You must specify the date value in the format M/d/yyyy, for example #5/31/1993#. This requirement is independent of your locale and your computer's date and time format settings.\"</p>\n\n<p>Are you saying that this is not correct and the parsing is affected by the current locale?</p>\n\n<p><strong>Edit:</strong> Did you try with a 4-digit year?</p>\n" }, { "answer_id": 57644, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>Ok right, I understand more where you are coming from..</p>\n\n<p>How about:</p>\n\n<ul>\n<li>Create a static method that returns the date constant. This overcomes the international issue since it is returned as the specific DateTime value.</li>\n<li>Now I remember optional params from my VB6 days, but can you not just overload the method? If you are using the overloaded method without the date, just pull it from the static?</li>\n</ul>\n\n<p><strong>EDIT:</strong> If you are unsure what I mean and would like a code sample, just comment this post and I will chuck one on.</p>\n" }, { "answer_id": 57695, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "<p>Once you have data into Date objects in VB, you don't have to worry about globalization until you compare something to it or try to export it.</p>\n\n<p>This is fine:</p>\n\n<pre><code>Dim FirstDate as Date = Date.UtcNow() 'or this: = NewDate (2008,09,10)'\nDim SecondDate as Date\n\nSecondDate = FirstDate.AddDays(1)\n</code></pre>\n\n<p>This pulls in the globalization rules and prints in the current thread's culture format:</p>\n\n<pre><code>HeaderLabel.Text = SecondDate.ToString()\n</code></pre>\n\n<p>This is bad: </p>\n\n<pre><code>Dim BadDate as Date = CDate(\"2/20/2000\")\n</code></pre>\n\n<p>Actually--even that is OK if you force CDate in that case to use the right culture (InvariantCulture):</p>\n\n<pre><code>Dim OkButBadPracticeDate as Date = CDate(\"2/20/2000\", CultureInfo.InvariantCulture)\n</code></pre>\n\n<p>If you want to force everything to a particular culture, you need to set the executing thread culture and UI culture to the desired culture (en-US, invariant, etc.).</p>\n\n<p>Make sure you aren't doing any work with dates as strings--make sure they are actual Date objects!</p>\n" }, { "answer_id": 59626, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 4, "selected": true, "text": "<p>If you look at the IL generated by the statement</p>\n\n<pre><code>public const ADate as Date = #12/31/04#\n</code></pre>\n\n<p>You'll see this:</p>\n\n<pre><code>.field public static initonly valuetype [mscorlib]System.DateTime ADate\n.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 2F CE E2 BC C6 08 00 00 )\n</code></pre>\n\n<p>Notice that the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.datetimeconstantattribute.aspx\" rel=\"noreferrer\">DateTimeConstantAttribute</a> is being initialized with a constructor that takes an int64 tick count. Since this tick count is being determined at complile time, it seems unlikely that any localization is coming into play when this value is initialized at runtime. My guess is that the error is with some other date handling in your code, not the const initialization.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5966/" ]
Does anyone know of a way to declare a date constant that is compatible with international dates? I've tried: ``` ' not international compatible public const ADate as Date = #12/31/04# ' breaking change if you have an optional parameter that defaults to this value ' because it isnt constant. public shared readonly ADate As New Date(12, 31, 04) ```
If you look at the IL generated by the statement ``` public const ADate as Date = #12/31/04# ``` You'll see this: ``` .field public static initonly valuetype [mscorlib]System.DateTime ADate .custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 2F CE E2 BC C6 08 00 00 ) ``` Notice that the [DateTimeConstantAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.datetimeconstantattribute.aspx) is being initialized with a constructor that takes an int64 tick count. Since this tick count is being determined at complile time, it seems unlikely that any localization is coming into play when this value is initialized at runtime. My guess is that the error is with some other date handling in your code, not the const initialization.
57,493
<p>In my WPF application, I have a number of databound TextBoxes. The <code>UpdateSourceTrigger</code> for these bindings is <code>LostFocus</code>. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind?</p> <p><em>@palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want.</em></p> <p><em>@dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself.</em></p> <p><em>@Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem:</em></p> <pre class="lang-xml prettyprint-override"><code>&lt;Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;ObjectDataProvider x:Key="MyItemProvider" /&gt; &lt;/Window.Resources&gt; &lt;DockPanel LastChildFill="True"&gt; &lt;Menu DockPanel.Dock="Top"&gt; &lt;MenuItem Header="File"&gt; &lt;MenuItem Header="Save" Click="MenuItem_Click" /&gt; &lt;/MenuItem&gt; &lt;/Menu&gt; &lt;StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"&gt; &lt;Label Content="Enter some text and then File &gt; Save:" /&gt; &lt;TextBox Text="{Binding ValueA}" /&gt; &lt;TextBox Text="{Binding ValueB}" /&gt; &lt;/StackPanel&gt; &lt;/DockPanel&gt; &lt;/Window&gt; </code></pre> <pre><code>using System; using System.Text; using System.Windows; using System.Windows.Data; namespace WpfApplication2 { public partial class Window1 : Window { public MyItem Item { get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; } set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; } } public Window1() { InitializeComponent(); Item = new MyItem(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB)); } } public class MyItem { public string ValueA { get; set; } public string ValueB { get; set; } } } </code></pre>
[ { "answer_id": 57506, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 2, "selected": false, "text": "<p>Have you tried setting the UpdateSourceTrigger to PropertyChanged? Alternatively, you could call the UpdateSOurce() method, but that seems like a bit overkill and defeats the purpose of TwoWay databinding.</p>\n" }, { "answer_id": 57662, "author": "dmo", "author_id": 1807, "author_profile": "https://Stackoverflow.com/users/1807", "pm_score": 1, "selected": false, "text": "<p>Could you set the focus somewhere else just before saving?</p>\n\n<p>You can do this by calling focus() on a UI element.</p>\n\n<p>You could focus on whatever element invokes the \"save\". If your trigger is LostFocus then you have to move the focus somewhere. Save has the advantage that it isn't modified and would make sense to the user.</p>\n" }, { "answer_id": 58443, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 4, "selected": true, "text": "<blockquote>\n<p>Suppose you have a TextBox in a window, and a ToolBar with a Save button in it. Assume the TextBox’s Text property is bound to a property on a business object, and the binding’s UpdateSourceTrigger property is set to the default value of LostFocus, meaning that the bound value is pushed back to the business object property when the TextBox loses input focus. Also, assume that the ToolBar’s Save button has its Command property set to ApplicationCommands.Save command.</p>\n<p>In that situation, if you edit the TextBox and click the Save button with the mouse, there is a problem. When clicking on a Button in a ToolBar, the TextBox does not lose focus. Since the TextBox’s LostFocus event does not fire, the Text property binding does not update the source property of the business object.</p>\n<p>Obviously you should not validate and save an object if the most recently edited value in the UI has not yet been pushed into the object. This is the exact problem Karl had worked around, by writing code in his window that manually looked for a TextBox with focus and updated the source of the data binding. His solution worked fine, but it got me thinking about a generic solution that would also be useful outside of this particular scenario. Enter CommandGroup…</p>\n</blockquote>\n<p>Taken from Josh Smith’s CodeProject article about <a href=\"http://www.codeproject.com/KB/WPF/commandgroup.aspx\" rel=\"noreferrer\">CommandGroup</a></p>\n" }, { "answer_id": 58451, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 3, "selected": false, "text": "<p>This is a UGLY hack but should also work</p>\n\n<pre><code>TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;\nif (focusedTextBox != null)\n{\n focusedTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();\n}\n</code></pre>\n\n<p>This code checks if a TextBox has focus... If 1 is found... update the binding source!</p>\n" }, { "answer_id": 229738, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 0, "selected": false, "text": "<p>The easiest way is to <em>set the focus somewhere</em>.<br>\nYou can set the focus back immediately, but setting the focus anywhere will trigger the LostFocus-Event on <strong>any type of control</strong> and make it update its stuff:</p>\n\n<pre><code>IInputElement x = System.Windows.Input.Keyboard.FocusedElement;\nDummyField.Focus();\nx.Focus();\n</code></pre>\n\n<p>Another way would be to get the focused element, get the binding element from the focused element, and trigger the update manually. An example for TextBox and ComboBox (you would need to add any control type you need to support):</p>\n\n<pre><code>TextBox t = Keyboard.FocusedElement as TextBox;\nif ((t != null) &amp;&amp; (t.GetBindingExpression(TextBox.TextProperty) != null))\n t.GetBindingExpression(TextBox.TextProperty).UpdateSource();\n\nComboBox c = Keyboard.FocusedElement as ComboBox;\nif ((c != null) &amp;&amp; (c.GetBindingExpression(ComboBox.TextProperty) != null))\n c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();\n</code></pre>\n" }, { "answer_id": 1764845, "author": "BigBlondeViking", "author_id": 119910, "author_profile": "https://Stackoverflow.com/users/119910", "pm_score": 5, "selected": false, "text": "<p>I found that removing the menu items that are scope depended from the FocusScope of the menu causes the textbox to lose focus correctly. I wouldn't think this applies to ALL items in Menu, but certainly for a save or validate action.</p>\n\n<pre><code>&lt;Menu FocusManager.IsFocusScope=\"False\" &gt;\n</code></pre>\n" }, { "answer_id": 4724766, "author": "Dave the Rave", "author_id": 580011, "author_profile": "https://Stackoverflow.com/users/580011", "pm_score": 4, "selected": false, "text": "<p>Assuming that there is more than one control in the tab sequence, the following solution appears to be complete and general (just cut-and-paste)...</p>\n\n<pre><code>Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control;\n\nif (currentControl != null)\n{\n // Force focus away from the current control to update its binding source.\n currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n currentControl.Focus();\n}\n</code></pre>\n" }, { "answer_id": 6195116, "author": "Shawn Nelson", "author_id": 437254, "author_profile": "https://Stackoverflow.com/users/437254", "pm_score": 0, "selected": false, "text": "<p>What do you think about this? I believe I've figured out a way to make it a bit more generic using reflection. I really didn't like the idea of maintaining a list like some of the other examples.</p>\n\n<pre><code>var currentControl = System.Windows.Input.Keyboard.FocusedElement;\nif (currentControl != null)\n{\n Type type = currentControl.GetType();\n if (type.GetMethod(\"MoveFocus\") != null &amp;&amp; type.GetMethod(\"Focus\") != null)\n {\n try\n {\n type.GetMethod(\"MoveFocus\").Invoke(currentControl, new object[] { new TraversalRequest(FocusNavigationDirection.Next) });\n type.GetMethod(\"Focus\").Invoke(currentControl, null);\n }\n catch (Exception ex)\n {\n throw new Exception(\"Unable to handle unknown type: \" + type.Name, ex);\n }\n }\n}\n</code></pre>\n\n<p>See any problems with that?</p>\n" }, { "answer_id": 7518908, "author": "Ram", "author_id": 959677, "author_profile": "https://Stackoverflow.com/users/959677", "pm_score": 2, "selected": false, "text": "<p>Simple solution is update the Xaml code as shown below</p>\n\n<pre><code> &lt;StackPanel DataContext=\"{Binding Source={StaticResource MyItemProvider}}\"&gt; \n &lt;Label Content=\"Enter some text and then File &gt; Save:\" /&gt; \n &lt;TextBox Text=\"{Binding ValueA, UpdateSourceTrigger=PropertyChanged}\" /&gt; \n &lt;TextBox Text=\"{Binding ValueB, UpdateSourceTrigger=PropertyChanged}\" /&gt; \n &lt;/StackPanel&gt; \n</code></pre>\n" }, { "answer_id": 8680327, "author": "Nathan Swannet", "author_id": 983690, "author_profile": "https://Stackoverflow.com/users/983690", "pm_score": 1, "selected": false, "text": "<p>Since I noticed this issue is still a pain in the ass to solve on a very generic way, I tried various solutions.</p>\n\n<p>Eventually one that worked out for me:\nWhenever the need is there that UI changes must be validated and updated to its sources (Check for changes upon closeing a window, performing Save operations, ...), I call a validation function which does various things:\n- make sure a focused element (like textbox, combobox, ...) loses its focus which will trigger default updatesource behavior\n- validate any controls within the tree of the DependencyObject which is given to the validation function\n- set focus back to the original focused element</p>\n\n<p>The function itself returns true if everything is in order (validation is succesful) -> your original action (closeing with optional asking confirmation, saveing, ...) can continue. Otherwise the function will return false and your action cannot continue because there are validation errors on one or more elements (with the help of a generic ErrorTemplate on the elements).</p>\n\n<p>The code (validation functionality is based on the article <a href=\"https://stackoverflow.com/questions/127477/detecting-wpf-validation-errors\">Detecting WPF Validation Errors</a>):</p>\n\n<pre><code>public static class Validator\n{\n private static Dictionary&lt;String, List&lt;DependencyProperty&gt;&gt; gdicCachedDependencyProperties = new Dictionary&lt;String, List&lt;DependencyProperty&gt;&gt;();\n\n public static Boolean IsValid(DependencyObject Parent)\n {\n // Move focus and reset it to update bindings which or otherwise not processed until losefocus\n IInputElement lfocusedElement = Keyboard.FocusedElement;\n if (lfocusedElement != null &amp;&amp; lfocusedElement is UIElement)\n {\n // Move to previous AND to next InputElement (if your next InputElement is a menu, focus will not be lost -&gt; therefor move in both directions)\n (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));\n (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n Keyboard.ClearFocus();\n }\n\n if (Parent as UIElement == null || (Parent as UIElement).Visibility != Visibility.Visible)\n return true;\n\n // Validate all the bindings on the parent \n Boolean lblnIsValid = true;\n foreach (DependencyProperty aDependencyProperty in GetAllDependencyProperties(Parent))\n {\n if (BindingOperations.IsDataBound(Parent, aDependencyProperty))\n {\n // Get the binding expression base. This way all kinds of bindings (MultiBinding, PropertyBinding, ...) can be updated\n BindingExpressionBase lbindingExpressionBase = BindingOperations.GetBindingExpressionBase(Parent, aDependencyProperty);\n if (lbindingExpressionBase != null)\n {\n lbindingExpressionBase.ValidateWithoutUpdate();\n if (lbindingExpressionBase.HasError)\n lblnIsValid = false;\n }\n }\n }\n\n if (Parent is Visual || Parent is Visual3D)\n {\n // Fetch the visual children (in case of templated content, the LogicalTreeHelper will return no childs)\n Int32 lintVisualChildCount = VisualTreeHelper.GetChildrenCount(Parent);\n for (Int32 lintVisualChildIndex = 0; lintVisualChildIndex &lt; lintVisualChildCount; lintVisualChildIndex++)\n if (!IsValid(VisualTreeHelper.GetChild(Parent, lintVisualChildIndex)))\n lblnIsValid = false;\n }\n\n if (lfocusedElement != null)\n lfocusedElement.Focus();\n\n return lblnIsValid;\n }\n\n public static List&lt;DependencyProperty&gt; GetAllDependencyProperties(DependencyObject DependencyObject)\n {\n Type ltype = DependencyObject.GetType();\n if (gdicCachedDependencyProperties.ContainsKey(ltype.FullName))\n return gdicCachedDependencyProperties[ltype.FullName];\n\n List&lt;DependencyProperty&gt; llstDependencyProperties = new List&lt;DependencyProperty&gt;();\n List&lt;FieldInfo&gt; llstFieldInfos = ltype.GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static).Where(Field =&gt; Field.FieldType == typeof(DependencyProperty)).ToList();\n foreach (FieldInfo aFieldInfo in llstFieldInfos)\n llstDependencyProperties.Add(aFieldInfo.GetValue(null) as DependencyProperty);\n gdicCachedDependencyProperties.Add(ltype.FullName, llstDependencyProperties);\n\n return llstDependencyProperties;\n }\n}\n</code></pre>\n" }, { "answer_id": 9840108, "author": "Tomer", "author_id": 805138, "author_profile": "https://Stackoverflow.com/users/805138", "pm_score": 2, "selected": false, "text": "<p>I've run into this issue and the best solution I've found was to change the focusable value of the button (or any other component such as MenuItem) to true:</p>\n\n<pre><code>&lt;Button Focusable=\"True\" Command=\"{Binding CustomSaveCommand}\"/&gt;\n</code></pre>\n\n<p>The reason it works, is because it forces the button to get focused before it invokes the command and therefore makes the TextBox <strong>or any other UIElement for that matter</strong> to loose their focus and raise lost focus event which invokes the binding to be changed.</p>\n\n<p><em>In case you are using bounded command (as I was pointing to in my example), John Smith's great solution won't fit very well since you can't bind StaticExtension into bounded property (nor DP).</em></p>\n" }, { "answer_id": 26902637, "author": "kenjiuno", "author_id": 974413, "author_profile": "https://Stackoverflow.com/users/974413", "pm_score": 0, "selected": false, "text": "<p>I'm using BindingGroup.</p>\n\n<p>XAML:</p>\n\n<pre><code>&lt;R:RibbonWindow Closing=\"RibbonWindow_Closing\" ...&gt;\n\n &lt;FrameworkElement.BindingGroup&gt;\n &lt;BindingGroup /&gt;\n &lt;/FrameworkElement.BindingGroup&gt;\n\n ...\n&lt;/R:RibbonWindow&gt;\n</code></pre>\n\n<p>C#</p>\n\n<pre><code>private void RibbonWindow_Closing(object sender, CancelEventArgs e) {\n e.Cancel = !NeedSave();\n}\n\nbool NeedSave() {\n BindingGroup.CommitEdit();\n\n // Insert your business code to check modifications.\n\n // return true; if Saved/DontSave/NotChanged\n // return false; if Cancel\n}\n</code></pre>\n\n<p>It should work.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
In my WPF application, I have a number of databound TextBoxes. The `UpdateSourceTrigger` for these bindings is `LostFocus`. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind? *@palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want.* *@dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself.* *@Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem:* ```xml <Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Window.Resources> <ObjectDataProvider x:Key="MyItemProvider" /> </Window.Resources> <DockPanel LastChildFill="True"> <Menu DockPanel.Dock="Top"> <MenuItem Header="File"> <MenuItem Header="Save" Click="MenuItem_Click" /> </MenuItem> </Menu> <StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"> <Label Content="Enter some text and then File > Save:" /> <TextBox Text="{Binding ValueA}" /> <TextBox Text="{Binding ValueB}" /> </StackPanel> </DockPanel> </Window> ``` ``` using System; using System.Text; using System.Windows; using System.Windows.Data; namespace WpfApplication2 { public partial class Window1 : Window { public MyItem Item { get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; } set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; } } public Window1() { InitializeComponent(); Item = new MyItem(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB)); } } public class MyItem { public string ValueA { get; set; } public string ValueB { get; set; } } } ```
> > Suppose you have a TextBox in a window, and a ToolBar with a Save button in it. Assume the TextBox’s Text property is bound to a property on a business object, and the binding’s UpdateSourceTrigger property is set to the default value of LostFocus, meaning that the bound value is pushed back to the business object property when the TextBox loses input focus. Also, assume that the ToolBar’s Save button has its Command property set to ApplicationCommands.Save command. > > > In that situation, if you edit the TextBox and click the Save button with the mouse, there is a problem. When clicking on a Button in a ToolBar, the TextBox does not lose focus. Since the TextBox’s LostFocus event does not fire, the Text property binding does not update the source property of the business object. > > > Obviously you should not validate and save an object if the most recently edited value in the UI has not yet been pushed into the object. This is the exact problem Karl had worked around, by writing code in his window that manually looked for a TextBox with focus and updated the source of the data binding. His solution worked fine, but it got me thinking about a generic solution that would also be useful outside of this particular scenario. Enter CommandGroup… > > > Taken from Josh Smith’s CodeProject article about [CommandGroup](http://www.codeproject.com/KB/WPF/commandgroup.aspx)
57,522
<p>I can create the following and reference it using</p> <pre><code>area[0].states[0] area[0].cities[0] var area = [ { "State" : "Texas", "Cities" : ['Austin','Dallas','San Antonio'] }, { "State" :"Arkansas", "Cities" : ['Little Rock','Texarkana','Hot Springs'] } ] ; </code></pre> <p>How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities?</p> <p>Thanks</p> <p><strong>EDIT</strong> Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads.</p>
[ { "answer_id": 57531, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": true, "text": "<p>If you want to just create it that way to begin with, just say</p>\n\n<pre><code>area = {\n \"Texas\": ['Austin','Dallas','San Antonio']\n}\n</code></pre>\n\n<p>and so on. If you're asking how to take an existing object and convert it into this, just say</p>\n\n<pre><code>states = {}\nfor(var j=0; j&lt;area.length; j++)\n states[ area[0].State ] = area[0].Cities\n</code></pre>\n\n<p>After running the above code, you could say</p>\n\n<pre><code>states[\"Texas\"]\n</code></pre>\n\n<p>which would return</p>\n\n<pre><code>['Austin','Dallas','San Antonio']\n</code></pre>\n" }, { "answer_id": 57535, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 2, "selected": false, "text": "<pre><code>var area = \n{\n \"Texas\" : { \"Cities\" : ['Austin','Dallas','San Antonio'] },\n \"Arkansas\" : { \"Cities\" : ['Little Rock','Texarkana','Hot Springs'] }\n};\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>area[\"Texas\"].Cities[0];\n</code></pre>\n" }, { "answer_id": 57536, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 1, "selected": false, "text": "<p>This would give you the array of cities based on knowing the state's name:</p>\n\n<pre><code>var area = {\n \"Texas\" : [\"Austin\",\"Dallas\",\"San Antonio\"], \n \"Arkansas\" : [\"Little Rock\",\"Texarkana\",\"Hot Springs\"]\n};\n\n// area[\"Texas\"] would return [\"Austin\",\"Dallas\",\"San Antonio\"]\n</code></pre>\n" }, { "answer_id": 58062, "author": "Jay Corbett", "author_id": 2755, "author_profile": "https://Stackoverflow.com/users/2755", "pm_score": 2, "selected": false, "text": "<p>(With help from the answers, I got this to work like I wanted. I fixed the syntax in selected answer, in the below code)</p>\n\n<p>With the following select boxes</p>\n\n<pre><code>&lt;select id=\"states\" size=\"2\"&gt;&lt;/select&gt;\n&lt;select id=\"cities\" size=\"3\"&gt;&lt;/select&gt;\n</code></pre>\n\n<p>and data in this format (either in .js file or received as JSON)</p>\n\n<pre><code>var area = [\n {\n \"states\" : \"Texas\",\n \"cities\" : ['Austin','Dallas','San Antonio']\n },\n {\n \"states\" :\"Arkansas\",\n \"cities\" : ['Little Rock','Texarkana','Hot Springs']\n }\n ] ;\n</code></pre>\n\n<p>These JQuery functions will populate the city select box based on the state select box selection</p>\n\n<pre><code>$(function() { // create an array to be referenced by state name\n state = [] ;\n for(var i=0; i&lt;area.length; i++) {\n state[area[i].states] = area[i].cities ;\n }\n});\n\n$(function() {\n // populate states select box\n var options = '' ;\n for (var i = 0; i &lt; area.length; i++) {\n options += '&lt;option value=\"' + area[i].states + '\"&gt;' + area[i].states + '&lt;/option&gt;'; \n }\n $(\"#states\").html(options); // populate select box with array\n\n // selecting state (change) will populate cities select box\n $(\"#states\").bind(\"change\",\n function() {\n $(\"#cities\").children().remove() ; // clear select box\n var options = '' ;\n for (var i = 0; i &lt; state[this.value].length; i++) { \n options += '&lt;option value=\"' + state[this.value][i] + '\"&gt;' + state[this.value][i] + '&lt;/option&gt;'; \n }\n $(\"#cities\").html(options); // populate select box with array\n } // bind function end\n ); // bind end \n});\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
I can create the following and reference it using ``` area[0].states[0] area[0].cities[0] var area = [ { "State" : "Texas", "Cities" : ['Austin','Dallas','San Antonio'] }, { "State" :"Arkansas", "Cities" : ['Little Rock','Texarkana','Hot Springs'] } ] ; ``` How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities? Thanks **EDIT** Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads.
If you want to just create it that way to begin with, just say ``` area = { "Texas": ['Austin','Dallas','San Antonio'] } ``` and so on. If you're asking how to take an existing object and convert it into this, just say ``` states = {} for(var j=0; j<area.length; j++) states[ area[0].State ] = area[0].Cities ``` After running the above code, you could say ``` states["Texas"] ``` which would return ``` ['Austin','Dallas','San Antonio'] ```
57,537
<p>In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.</p> <p>It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.</p> <p>Does anyone know of a method for getting the context directory so that I can load and write files to disk?</p>
[ { "answer_id": 57563, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": -1, "selected": false, "text": "<p>Do you mean:</p>\n\n<pre><code>public class MyServlet extends HttpServlet {\n\n public void init(final ServletConfig config) {\n final String context = config.getServletContext();\n ...\n }\n\n ...\n}\n</code></pre>\n\n<p>Or something more complex?</p>\n" }, { "answer_id": 57595, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 5, "selected": true, "text": "<p>This should give you the real path that you can use to extract / edit files.</p>\n\n<p><a href=\"http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)\" rel=\"noreferrer\">Javadoc Link</a></p>\n\n<p>We're doing something similar in a context listener.</p>\n\n<pre><code>public class MyServlet extends HttpServlet {\n\n public void init(final ServletConfig config) {\n final String context = config.getServletContext().getRealPath(\"/\");\n ...\n }\n\n ...\n}\n</code></pre>\n" }, { "answer_id": 1807990, "author": "diätpillen", "author_id": 219965, "author_profile": "https://Stackoverflow.com/users/219965", "pm_score": 0, "selected": false, "text": "<p>I was googling the result and getting no where. In JSP pages that need to use Java Script to access the current <em>contextPath</em> it is actually quite easy. </p>\n\n<p>Just put the following lines into your <em>html head</em> inside a <code>script</code> block.</p>\n\n<pre><code>// set up a global java script variable to access the context path\nvar contextPath = \"${request.contextPath}\" \n</code></pre>\n" }, { "answer_id": 1808295, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p><em>In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying</em></p>\n</blockquote>\n\n<p>You can also access the files in the WebContent by <a href=\"http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html#getResource%28java.lang.String%29\" rel=\"nofollow noreferrer\"><code>ServletContext#getResource()</code></a>. So if your JS file is for example located at <code>WebContent/js/file.js</code> then you can use the following in your <code>Servlet</code> to get a <code>File</code> handle of it:</p>\n\n<pre><code>File file = new File(getServletContext().getResource(\"/js/file.js\").getFile());\n</code></pre>\n\n<p>or to get an <code>InputStream</code>:</p>\n\n<pre><code>InputStream input = getServletContext().getResourceAsStream(\"/js/file.js\");\n</code></pre>\n\n<p>That said, how often do you need to minify JS files? I have never seen the need for request-based minifying, it would only unnecessarily add much overhead. You probably want to do it only once during application's startup. If so, then using a <code>Servlet</code> for this is a bad idea. Better use <a href=\"http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContextListener.html\" rel=\"nofollow noreferrer\"><code>ServletContextListener</code></a> and do your thing on <code>contextInitialized()</code>.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ]
In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying. It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost. Does anyone know of a method for getting the context directory so that I can load and write files to disk?
This should give you the real path that you can use to extract / edit files. [Javadoc Link](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)) We're doing something similar in a context listener. ``` public class MyServlet extends HttpServlet { public void init(final ServletConfig config) { final String context = config.getServletContext().getRealPath("/"); ... } ... } ```
57,560
<p>What's the best way in c# to determine is a given QFE/patch has been installed?</p>
[ { "answer_id": 57626, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 1, "selected": false, "text": "<p>The most reliable way is to determine which files are impacted by the QFE and use <code>System.Diagnostics.FileVersionInfo.GetVersionInfo(path)</code> on each file and compare the version numbers.</p>\n\n<p>edit: I think there's a way to check the uninstall information in the registry as well, but if the QFE ever becomes part of a Service Pack or rollup package that might report false negatives</p>\n" }, { "answer_id": 205258, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 3, "selected": true, "text": "<p>Use WMI and inspect the <a href=\"http://msdn.microsoft.com/en-us/library/aa394391.aspx\" rel=\"nofollow noreferrer\">Win32_QuickFixEngineering</a> enumeration.</p>\n\n<p>From TechNet:</p>\n\n<pre><code>strComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\" _\n &amp; \"{impersonationLevel=impersonate}!\\\\\" &amp; strComputer &amp; \"\\root\\cimv2\")\nSet colQuickFixes = objWMIService.ExecQuery _\n (\"Select * from Win32_QuickFixEngineering\")\nFor Each objQuickFix in colQuickFixes\n Wscript.Echo \"Computer: \" &amp; objQuickFix.CSName\n Wscript.Echo \"Description: \" &amp; objQuickFix.Description\n Wscript.Echo \"Hot Fix ID: \" &amp; objQuickFix.HotFixID\n Wscript.Echo \"Installation Date: \" &amp; objQuickFix.InstallDate\n Wscript.Echo \"Installed By: \" &amp; objQuickFix.InstalledBy\nNext\n</code></pre>\n\n<p><strong>The HotFixID is what you want to examine.</strong></p>\n\n<p>Here's the output on my system:</p>\n\n<pre>\n Hot Fix ID: KB941569\n Description: Security Update for Windows XP (KB941569)\n Hot Fix ID: KB937143-IE7\n Description: Security Update for Windows Internet Explorer 7 (KB937143)\n Hot Fix ID: KB938127-IE7\n Description: Security Update for Windows Internet Explorer 7 (KB938127)\n Hot Fix ID: KB939653-IE7\n Description: Security Update for Windows Internet Explorer 7 (KB939653)\n Hot Fix ID: KB942615-IE7\n Description: Security Update for Windows Internet Explorer 7 (KB942615)\n Hot Fix ID: KB944533-IE7\n Description: Security Update for Windows Internet Explorer 7 (KB944533)\n Hot Fix ID: KB947864-IE7\n Description: Hotfix for Windows Internet Explorer 7 (KB947864)\n Hot Fix ID: KB950759-IE7\n Description: Security Update for Windows Internet Explorer 7 (KB950759)\n Hot Fix ID: KB953838-IE7\n Description: Security Update for Windows Internet Explorer 7 (KB953838)\n Hot Fix ID: MSCompPackV1\n Description: Microsoft Compression Client Pack 1.0 for Windows XP\n Hot Fix ID: KB873339\n Description: Windows XP Hotfix - KB873339\n Hot Fix ID: KB885835\n Description: Windows XP Hotfix - KB885835\n Hot Fix ID: KB885836\n Description: Windows XP Hotfix - KB885836\n Hot Fix ID: KB886185\n Description: Windows XP Hotfix - KB886185\n Hot Fix ID: KB887472\n Description: Windows XP Hotfix - KB887472\n Hot Fix ID: KB888302\n Description: Windows XP Hotfix - KB888302\n Hot Fix ID: KB890046\n Description: Security Update for Windows XP (KB890046)\n</pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2564/" ]
What's the best way in c# to determine is a given QFE/patch has been installed?
Use WMI and inspect the [Win32\_QuickFixEngineering](http://msdn.microsoft.com/en-us/library/aa394391.aspx) enumeration. From TechNet: ``` strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colQuickFixes = objWMIService.ExecQuery _ ("Select * from Win32_QuickFixEngineering") For Each objQuickFix in colQuickFixes Wscript.Echo "Computer: " & objQuickFix.CSName Wscript.Echo "Description: " & objQuickFix.Description Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID Wscript.Echo "Installation Date: " & objQuickFix.InstallDate Wscript.Echo "Installed By: " & objQuickFix.InstalledBy Next ``` **The HotFixID is what you want to examine.** Here's the output on my system: ``` Hot Fix ID: KB941569 Description: Security Update for Windows XP (KB941569) Hot Fix ID: KB937143-IE7 Description: Security Update for Windows Internet Explorer 7 (KB937143) Hot Fix ID: KB938127-IE7 Description: Security Update for Windows Internet Explorer 7 (KB938127) Hot Fix ID: KB939653-IE7 Description: Security Update for Windows Internet Explorer 7 (KB939653) Hot Fix ID: KB942615-IE7 Description: Security Update for Windows Internet Explorer 7 (KB942615) Hot Fix ID: KB944533-IE7 Description: Security Update for Windows Internet Explorer 7 (KB944533) Hot Fix ID: KB947864-IE7 Description: Hotfix for Windows Internet Explorer 7 (KB947864) Hot Fix ID: KB950759-IE7 Description: Security Update for Windows Internet Explorer 7 (KB950759) Hot Fix ID: KB953838-IE7 Description: Security Update for Windows Internet Explorer 7 (KB953838) Hot Fix ID: MSCompPackV1 Description: Microsoft Compression Client Pack 1.0 for Windows XP Hot Fix ID: KB873339 Description: Windows XP Hotfix - KB873339 Hot Fix ID: KB885835 Description: Windows XP Hotfix - KB885835 Hot Fix ID: KB885836 Description: Windows XP Hotfix - KB885836 Hot Fix ID: KB886185 Description: Windows XP Hotfix - KB886185 Hot Fix ID: KB887472 Description: Windows XP Hotfix - KB887472 Hot Fix ID: KB888302 Description: Windows XP Hotfix - KB888302 Hot Fix ID: KB890046 Description: Security Update for Windows XP (KB890046) ```
57,577
<p>What is the easiest way to merge XML from two distinct DOM Documents? Is there a way other than using the Canonical <a href="http://support.microsoft.com/kb/311530" rel="nofollow noreferrer">DataReader</a> approach and then messing with the outputted DOM. What I basically want is to AppendChild to XmlElements without getting: <code>The node to be inserted is from a different document context.</code> Here is C# code that I want to work, that obviously won't (what I am doing is merging two documents which have bunch of nodes that I am interested in parts of):</p> <pre><code>XmlDocument doc1 = new XmlDocument(); doc1.LoadXml("&lt;a&gt;&lt;items&gt;&lt;item1/&gt;&lt;item2/&gt;&lt;item3/&gt;&lt;/items&gt;&lt;/a&gt;"); XmlDocument doc2 = new XmlDocument(); doc2.LoadXml("&lt;b&gt;&lt;items&gt;&lt;item4/&gt;&lt;item5/&gt;&lt;item6/&gt;&lt;/items&gt;&lt;/b&gt;"); XmlNode doc2Node = doc2.SelectSingleNode("/b/items"); XmlNodeList doc1Nodes = doc1.SelectNodes("/a/items/*"); foreach (XmlNode doc1Node in doc1Nodes) { doc2Node.AppendChild(doc1Node); } </code></pre>
[ { "answer_id": 57593, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 4, "selected": true, "text": "<p>You can use the XmlDocument.ImportNode method to copy a node from a XmlDocument to another.</p>\n" }, { "answer_id": 57602, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 1, "selected": false, "text": "<p>You might be interested in <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.importnode.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.importnode.aspx</a>. But take a close look at the \"The following table describes the specific behavior for each XmlNodeType.\"-part of that document.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
What is the easiest way to merge XML from two distinct DOM Documents? Is there a way other than using the Canonical [DataReader](http://support.microsoft.com/kb/311530) approach and then messing with the outputted DOM. What I basically want is to AppendChild to XmlElements without getting: `The node to be inserted is from a different document context.` Here is C# code that I want to work, that obviously won't (what I am doing is merging two documents which have bunch of nodes that I am interested in parts of): ``` XmlDocument doc1 = new XmlDocument(); doc1.LoadXml("<a><items><item1/><item2/><item3/></items></a>"); XmlDocument doc2 = new XmlDocument(); doc2.LoadXml("<b><items><item4/><item5/><item6/></items></b>"); XmlNode doc2Node = doc2.SelectSingleNode("/b/items"); XmlNodeList doc1Nodes = doc1.SelectNodes("/a/items/*"); foreach (XmlNode doc1Node in doc1Nodes) { doc2Node.AppendChild(doc1Node); } ```
You can use the XmlDocument.ImportNode method to copy a node from a XmlDocument to another.
57,599
<p>What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?</p> <p>The <code>datediff</code> function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedure</a>.</p>
[ { "answer_id": 57642, "author": "Michael Runyon", "author_id": 5405, "author_profile": "https://Stackoverflow.com/users/5405", "pm_score": 0, "selected": false, "text": "<p>Are you trying to calculate the total days/months/years of an age? do you have a starting date? Or are you trying to dissect it (ex: 24 years, 1 month, 29 days)?</p>\n\n<p>If you have a start date that you're working with, datediff will output the total days/months/years with the following commands:</p>\n\n<pre><code>Select DateDiff(d,'1984-07-12','2008-09-11')\n\nSelect DateDiff(m,'1984-07-12','2008-09-11')\n\nSelect DateDiff(yyyy,'1984-07-12','2008-09-11')\n</code></pre>\n\n<p>with the respective outputs being (8827/290/24).</p>\n\n<p>Now, if you wanted to do the dissection method, you'd have to subtract the number of years in days (days - 365*years), and then do further math on that to get the months, etc.</p>\n" }, { "answer_id": 57720, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 7, "selected": true, "text": "<p>Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate.</p>\n\n<pre><code>DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int\nSELECT @date = '2/29/04'\n\nSELECT @tmpdate = @date\n\nSELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) &gt; MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) &gt; DAY(GETDATE())) THEN 1 ELSE 0 END\nSELECT @tmpdate = DATEADD(yy, @years, @tmpdate)\nSELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) &gt; DAY(GETDATE()) THEN 1 ELSE 0 END\nSELECT @tmpdate = DATEADD(m, @months, @tmpdate)\nSELECT @days = DATEDIFF(d, @tmpdate, GETDATE())\n\nSELECT @years, @months, @days\n</code></pre>\n" }, { "answer_id": 57748, "author": "Leonardo", "author_id": 1014, "author_profile": "https://Stackoverflow.com/users/1014", "pm_score": 2, "selected": false, "text": "<p>Here is a (slightly) simpler version:</p>\n\n<pre><code>CREATE PROCEDURE dbo.CalculateAge \n @dayOfBirth datetime\nAS\n\nDECLARE @today datetime, @thisYearBirthDay datetime\nDECLARE @years int, @months int, @days int\n\nSELECT @today = GETDATE()\n\nSELECT @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)\n\nSELECT @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay &gt; @today THEN 1 ELSE 0 END)\n\nSELECT @months = MONTH(@today - @thisYearBirthDay) - 1\n\nSELECT @days = DAY(@today - @thisYearBirthDay) - 1\n\nSELECT @years, @months, @days\nGO\n</code></pre>\n" }, { "answer_id": 2809382, "author": "simon831", "author_id": 107062, "author_profile": "https://Stackoverflow.com/users/107062", "pm_score": 2, "selected": false, "text": "<p>The same sort of thing as a function.</p>\n\n<pre><code>create function [dbo].[Age](@dayOfBirth datetime, @today datetime)\n RETURNS varchar(100)\nAS\n\nBegin\nDECLARE @thisYearBirthDay datetime\nDECLARE @years int, @months int, @days int\n\nset @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)\nset @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay &gt; @today THEN 1 ELSE 0 END)\nset @months = MONTH(@today - @thisYearBirthDay) - 1\nset @days = DAY(@today - @thisYearBirthDay) - 1\n\nreturn cast(@years as varchar(2)) + ' years,' + cast(@months as varchar(2)) + ' months,' + cast(@days as varchar(3)) + ' days'\nend\n</code></pre>\n" }, { "answer_id": 3324468, "author": "sumesh", "author_id": 400953, "author_profile": "https://Stackoverflow.com/users/400953", "pm_score": 2, "selected": false, "text": "<pre><code>create procedure getDatedifference\n\n(\n @startdate datetime,\n @enddate datetime\n)\nas\nbegin\n declare @monthToShow int\n declare @dayToShow int\n\n --set @startdate='01/21/1934'\n --set @enddate=getdate()\n\n if (DAY(@startdate) &gt; DAY(@enddate))\n begin\n set @dayToShow=0\n\n if (month(@startdate) &gt; month(@enddate))\n begin\n set @monthToShow= (12-month(@startdate)+ month(@enddate)-1)\n end\n else if (month(@startdate) &lt; month(@enddate))\n begin\n set @monthToShow= ((month(@enddate)-month(@startdate))-1)\n end\n else\n begin\n set @monthToShow= 11\n end\n -- set @monthToShow= convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12))-1\n if(@monthToShow&lt;0)\n begin\n set @monthToShow=0\n end\n\n declare @amonthbefore integer\n set @amonthbefore=Month(@enddate)-1\n if(@amonthbefore=0)\n begin\n set @amonthbefore=12\n end\n\n\n if (@amonthbefore in(1,3,5,7,8,10,12))\n begin\n set @dayToShow=31-DAY(@startdate)+DAY(@enddate)\n end\n if (@amonthbefore=2)\n begin\n IF (YEAR( @enddate ) % 4 = 0 AND YEAR( @enddate ) % 100 != 0) OR YEAR( @enddate ) % 400 = 0\n begin\n set @dayToShow=29-DAY(@startdate)+DAY(@enddate)\n end\n else\n begin\n set @dayToShow=28-DAY(@startdate)+DAY(@enddate)\n end\n end\n if (@amonthbefore in (4,6,9,11))\n begin\n set @dayToShow=30-DAY(@startdate)+DAY(@enddate)\n end\n end\n else\n begin\n --set @monthToShow=convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12))\n if (month(@enddate)&lt; month(@startdate))\n begin\n set @monthToShow=12+(month(@enddate)-month(@startdate))\n end\n else\n begin\n set @monthToShow= (month(@enddate)-month(@startdate))\n end\n set @dayToShow=DAY(@enddate)-DAY(@startdate)\n end\n\n SELECT\n FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25) as [yearToShow],\n @monthToShow as monthToShow ,@dayToShow as dayToShow ,\n convert(varchar,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25)) +' Year ' + convert(varchar,@monthToShow) +' months '+convert(varchar,@dayToShow)+' days ' as age\n\n return\nend\n</code></pre>\n" }, { "answer_id": 6618627, "author": "tkerwood", "author_id": 463425, "author_profile": "https://Stackoverflow.com/users/463425", "pm_score": 4, "selected": false, "text": "<p>Try this...</p>\n\n<pre><code>SELECT CASE WHEN\n (DATEADD(year,DATEDIFF(year, @datestart ,@dateend) , @datestart) &gt; @dateend)\nTHEN DATEDIFF(year, @datestart ,@dateend) -1\nELSE DATEDIFF(year, @datestart ,@dateend)\nEND\n</code></pre>\n\n<p>Basically the \"DateDiff( year...\", gives you the age the person will turn this year, so i have just add a case statement to say, if they have not had a birthday yet this year, then subtract 1 year, else return the value. </p>\n" }, { "answer_id": 8312825, "author": "Keith", "author_id": 1071528, "author_profile": "https://Stackoverflow.com/users/1071528", "pm_score": 1, "selected": false, "text": "<p>I've seen the question several times with results outputting Years, Month, Days but never a numeric / decimal result. (At least not one that doesn't round incorrectly).\nI welcome feedback on this function. Might not still need a little adjusting.</p>\n\n<p>-- Input to the function is two dates.\n-- Output is the numeric number of years between the two dates in Decimal(7,4) format.\n-- Output is always always a possitive number. </p>\n\n<h2>-- NOTE:Output does not handle if difference is greater than 999.9999</h2>\n\n<p>-- Logic is based on three steps.\n-- 1) Is the difference less than 1 year (0.5000, 0.3333, 0.6667, ect.)\n-- 2) Is the difference exactly a whole number of years (1,2,3, ect.)</p>\n\n<h2>-- 3) (Else)...The difference is years and some number of days. (1.5000, 2.3333, 7.6667, ect.)</h2>\n\n<hr>\n\n<hr>\n\n<pre><code>CREATE Function [dbo].[F_Get_Actual_Age](@pi_date1 datetime,@pi_date2 datetime)\nRETURNS Numeric(7,4)\nAS\nBEGIN\n\nDeclare \n @l_tmp_date DATETIME\n,@l_days1 DECIMAL(9,6)\n,@l_days2 DECIMAL(9,6)\n,@l_result DECIMAL(10,6)\n,@l_years DECIMAL(7,4)\n\n\n --Check to make sure there is a date for both inputs\n IF @pi_date1 IS NOT NULL and @pi_date2 IS NOT NULL \n BEGIN\n\n IF @pi_date1 &gt; @pi_date2 --Make sure the \"older\" date is in @pi_date1\n BEGIN\n SET @l_tmp_date = @pi_date2\n SET @pi_date2 = @Pi_date1\n SET @pi_date1 = @l_tmp_date\n END\n\n --Check #1 If date1 + 1 year is greater than date2, difference must be less than 1 year\n IF DATEADD(YYYY,1,@pi_date1) &gt; @pi_date2 \n BEGIN\n --How many days between the two dates (numerator)\n SET @l_days1 = DATEDIFF(dd,@pi_date1, @pi_date2) \n --subtract 1 year from date2 and calculate days bewteen it and date2\n --This is to get the denominator and accounts for leap year (365 or 366 days)\n SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) \n SET @l_years = @l_days1 / @l_days2 -- Do the math\n END\n ELSE\n --Check #2 Are the dates an exact number of years apart.\n --Calculate years bewteen date1 and date2, then add the years to date1, compare dates to see if exactly the same.\n IF DATEADD(YYYY,DATEDIFF(YYYY,@pi_date1,@pi_date2),@pi_date1) = @pi_date2 \n SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2) --AS Years, 'Exactly even Years' AS Msg\n ELSE\n BEGIN\n --Check #3 The rest of the cases.\n --Check if datediff, returning years, over or under states the years difference\n SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2)\n IF DATEADD(YYYY,@l_years,@pi_date1) &gt; @pi_date2\n SET @l_years = @l_years -1\n --use basicly same logic as in check #1 \n SET @l_days1 = DATEDIFF(dd,DATEADD(YYYY,@l_years,@pi_date1), @pi_date2) \n SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) \n SET @l_years = @l_years + @l_days1 / @l_days2\n --SELECT @l_years AS Years, 'Years Plus' AS Msg\n END\n END\n ELSE\n SET @l_years = 0 --If either date was null\n\nRETURN @l_Years --Return the result as decimal(7,4)\nEND \n</code></pre>\n\n<p>`</p>\n" }, { "answer_id": 9986532, "author": "Will", "author_id": 377058, "author_profile": "https://Stackoverflow.com/users/377058", "pm_score": 0, "selected": false, "text": "<p><code>DateTime</code> values in T-SQL are stored as floats. You can just subtract the dates from each other and you now have a new date that is the timespan between them.</p>\n\n<pre><code>declare @birthdate datetime\nset @birthdate = '6/15/1974'\n\n--age in years - short version\nprint year(getdate() - @birthdate) - year(0)\n\n--age in years - visualization\ndeclare @mindate datetime\ndeclare @span datetime\n\nset @mindate = 0\nset @span = getdate() - @birthdate\n\nprint @mindate\nprint @birthdate\nprint getdate()\nprint @span\n--substract minyear from spanyear to get age in years\nprint year(@span) - year(@mindate)\nprint month(@span)\nprint day(@span)\n</code></pre>\n" }, { "answer_id": 11169287, "author": "Md. Munir Hussain", "author_id": 1476734, "author_profile": "https://Stackoverflow.com/users/1476734", "pm_score": 0, "selected": false, "text": "<p>Here is SQL code that gives you the number of years, months, and days since the sysdate. \nEnter value for input_birth_date this format(dd_mon_yy). note: input same value(birth date) for years, months &amp; days such as 01-mar-85</p>\n\n<pre><code>select trunc((sysdate -to_date('&amp;input_birth_date_dd_mon_yy'))/365) years,\ntrunc(mod(( sysdate -to_date('&amp;input_birth_date_dd_mon_yy'))/365,1)*12) months,\ntrunc((mod((mod((sysdate -to_date('&amp;input_birth_date_dd_mon_yy'))/365,1)*12),1)*30)+1) days \n from dual\n</code></pre>\n" }, { "answer_id": 15061160, "author": "Junaid", "author_id": 2106258, "author_profile": "https://Stackoverflow.com/users/2106258", "pm_score": 0, "selected": false, "text": "<pre><code>CREATE FUNCTION DBO.GET_AGE\n(\n@DATE AS DATETIME\n)\nRETURNS VARCHAR(MAX)\nAS\nBEGIN\n\nDECLARE @YEAR AS VARCHAR(50) = ''\nDECLARE @MONTH AS VARCHAR(50) = ''\nDECLARE @DAYS AS VARCHAR(50) = ''\nDECLARE @RESULT AS VARCHAR(MAX) = ''\n\nSET @YEAR = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) &gt; DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) / 12 ))\nSET @MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) &gt; DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) % 12 ))\nSET @DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,@YEAR)*12 + CONVERT(INT,@MONTH)),@DATE),GETDATE())\n\nSET @RESULT = (RIGHT('00' + @YEAR, 2) + ' YEARS ' + RIGHT('00' + @MONTH, 2) + ' MONTHS ' + RIGHT('00' + @DAYS, 2) + ' DAYS')\n\nRETURN @RESULT\nEND\n\nSELECT DBO.GET_AGE('04/12/1986')\n</code></pre>\n" }, { "answer_id": 17064482, "author": "ZafarYousafi", "author_id": 134164, "author_profile": "https://Stackoverflow.com/users/134164", "pm_score": 1, "selected": false, "text": "<p>Quite Old question, but I want to share what I have done to calculate age</p>\n\n<pre><code> Declare @BirthDate As DateTime\nSet @BirthDate = '1994-11-02'\n\nSELECT DATEDIFF(YEAR,@BirthDate,GETDATE()) - (CASE \nWHEN MONTH(@BirthDate)&gt; MONTH(GETDATE()) THEN 1 \nWHEN MONTH(@BirthDate)= MONTH(GETDATE()) AND DAY(@BirthDate) &gt; DAY(GETDATE()) THEN 1 \nElse 0 END)\n</code></pre>\n" }, { "answer_id": 18517263, "author": "user2730262", "author_id": 2730262, "author_profile": "https://Stackoverflow.com/users/2730262", "pm_score": 0, "selected": false, "text": "<pre><code>DECLARE @BirthDate datetime, @AgeInMonths int\nSET @BirthDate = '10/5/1971'\nSET @AgeInMonths -- Determine the age in \"months old\":\n = DATEDIFF(MONTH, @BirthDate, GETDATE()) -- .Get the difference in months\n - CASE WHEN DATEPART(DAY,GETDATE()) -- .If today was the 1st to 4th,\n &lt; DATEPART(DAY,@BirthDate) -- (or before the birth day of month)\n THEN 1 ELSE 0 END -- ... don't count the month.\nSELECT @AgeInMonths / 12 as AgeYrs -- Divide by 12 months to get the age in years\n ,@AgeInMonths % 12 as AgeXtraMonths -- Get the remainder of dividing by 12 months = extra months\n ,DATEDIFF(DAY -- For the extra days, find the difference between, \n ,DATEADD(MONTH, @AgeInMonths -- 1. Last Monthly Birthday \n , @BirthDate) -- (if birthdays were celebrated monthly)\n ,GETDATE()) as AgeXtraDays -- 2. Today's date.\n</code></pre>\n" }, { "answer_id": 19204768, "author": "Ajit Bhgayanathan", "author_id": 2850876, "author_profile": "https://Stackoverflow.com/users/2850876", "pm_score": 4, "selected": false, "text": "<p>Simple way to get age as text is as below:</p>\n\n<pre><code>Select cast((DATEDIFF(m, date_of_birth, GETDATE())/12) as varchar) + ' Y &amp; ' + \n cast((DATEDIFF(m, date_of_birth, GETDATE())%12) as varchar) + ' M' as Age\n</code></pre>\n\n<p>Results Format will be:</p>\n\n<pre><code>**63 Y &amp; 2 M**\n</code></pre>\n" }, { "answer_id": 25912864, "author": "Jaugar Chang", "author_id": 3630826, "author_profile": "https://Stackoverflow.com/users/3630826", "pm_score": 3, "selected": false, "text": "<h2>Implemented by arithmetic with ISO formatted date.</h2>\n\n<pre><code>declare @now date,@dob date, @now_i int,@dob_i int, @days_in_birth_month int\ndeclare @years int, @months int, @days int\nset @now = '2013-02-28' \nset @dob = '2012-02-29' -- Date of Birth\n\nset @now_i = convert(varchar(8),@now,112) -- iso formatted: 20130228\nset @dob_i = convert(varchar(8),@dob,112) -- iso formatted: 20120229\nset @years = ( @now_i - @dob_i)/10000\n-- (20130228 - 20120229)/10000 = 0 years\n\nset @months =(1200 + (month(@now)- month(@dob))*100 + day(@now) - day(@dob))/100 %12\n-- (1200 + 0228 - 0229)/100 % 12 = 11 months\n\nset @days_in_birth_month = day(dateadd(d,-1,left(convert(varchar(8),dateadd(m,1,@dob),112),6)+'01'))\nset @days = (sign(day(@now) - day(@dob))+1)/2 * (day(@now) - day(@dob))\n + (sign(day(@dob) - day(@now))+1)/2 * (@days_in_birth_month - day(@dob) + day(@now))\n-- ( (-1+1)/2*(28 - 29) + (1+1)/2*(29 - 29 + 28))\n-- Explain: if the days of now is bigger than the days of birth, then diff the two days\n-- else add the days of now and the distance from the date of birth to the end of the birth month \nselect @years,@months,@days -- 0, 11, 28 \n</code></pre>\n\n<h2>Test Cases</h2>\n\n<p><em>The approach of days is different from the accepted answer, the differences shown in the comments below:</em></p>\n\n<pre><code> dob now years months days \n2012-02-29 2013-02-28 0 11 28 --Days will be 30 if calculated by the approach in accepted answer. \n2012-02-29 2016-02-28 3 11 28 --Days will be 31 if calculated by the approach in accepted answer, since the day of birth will be changed to 28 from 29 after dateadd by years. \n2012-02-29 2016-03-31 4 1 2\n2012-01-30 2016-02-29 4 0 30\n2012-01-30 2016-03-01 4 1 2 --Days will be 1 if calculated by the approach in accepted answer, since the day of birth will be changed to 30 from 29 after dateadd by years.\n2011-12-30 2016-02-29 4 1 30\n</code></pre>\n\n<h2>An short version of Days by case statement:</h2>\n\n<pre><code>set @days = CASE WHEN day(@now) &gt;= day(@dob) THEN day(@now) - day(@dob)\n ELSE @days_in_birth_month - day(@dob) + day(@now) END\n</code></pre>\n\n<p><strong>If you want the age of years and months only, it could be simpler</strong></p>\n\n<pre><code>set @years = ( @now_i/100 - @dob_i/100)/100\nset @months =(12 + month(@now) - month(@dob))%12 \nselect @years,@months -- 1, 0\n</code></pre>\n\n<p><strong>NOTE:</strong> A very useful link of <a href=\"http://www.sql-server-helper.com/tips/date-formats.aspx\" rel=\"noreferrer\">SQL Server Date Formats</a></p>\n" }, { "answer_id": 27064788, "author": "miguelbgouveia", "author_id": 2486661, "author_profile": "https://Stackoverflow.com/users/2486661", "pm_score": 0, "selected": false, "text": "<p>For the ones that want to create a calculated column in a table to store the age:</p>\n\n<pre><code>CASE WHEN DateOfBirth&lt; DATEADD(YEAR, (DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth))*-1, GETDATE()) \n THEN DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth)\n ELSE DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth) -1 END\n</code></pre>\n" }, { "answer_id": 35181398, "author": "Komengem", "author_id": 619010, "author_profile": "https://Stackoverflow.com/users/619010", "pm_score": 0, "selected": false, "text": "<p>Here is how I calculate the age given a birth date and the current date.</p>\n\n<pre><code>select case \n when cast(getdate() as date) = cast(dateadd(year, (datediff(year, '1996-09-09', getdate())), '1996-09-09') as date)\n then dateDiff(yyyy,'1996-09-09',dateadd(year, 0, getdate()))\n else dateDiff(yyyy,'1996-09-09',dateadd(year, -1, getdate()))\n end as MemberAge\ngo\n</code></pre>\n" }, { "answer_id": 35902737, "author": "Mark Brittingham", "author_id": 15592, "author_profile": "https://Stackoverflow.com/users/15592", "pm_score": 0, "selected": false, "text": "<p>There is an easy way, based on the hours between the two days BUT with the end date truncated. </p>\n\n<pre><code>SELECT CAST(DATEDIFF(hour,Birthdate,CAST(GETDATE() as Date))/8766.0 as INT) AS Age FROM &lt;YourTable&gt;\n</code></pre>\n\n<p>This one has proven to be extremely accurate and reliable. If it weren't for the inner CAST on the GETDATE() it might flip the birthday a few hours before midnight but, with the CAST, it is dead on with the age changing over at <strong>exactly</strong> midnight.</p>\n" }, { "answer_id": 36428043, "author": "Harry Steinmeyer", "author_id": 6157545, "author_profile": "https://Stackoverflow.com/users/6157545", "pm_score": -1, "selected": false, "text": "<pre><code>DECLARE @DoB AS DATE = '1968-10-24'\nDECLARE @cDate AS DATE = CAST('2000-10-23' AS DATE)\n\nSELECT \n--Get Year difference\nDATEDIFF(YEAR,@DoB,@cDate) -\n--Cases where year difference will be augmented\nCASE \n --If Date of Birth greater than date passed return 0\n WHEN YEAR(@DoB) - YEAR(@cDate) &gt;= 0 THEN DATEDIFF(YEAR,@DoB,@cDate)\n\n --If date of birth month less than date passed subtract one year\n WHEN MONTH(@DoB) - MONTH(@cDate) &gt; 0 THEN 1 \n\n --If date of birth day less than date passed subtract one year\n WHEN MONTH(@DoB) - MONTH(@cDate) = 0 AND DAY(@DoB) - DAY(@cDate) &gt; 0 THEN 1 \n\n --All cases passed subtract zero\n ELSE 0\nEND\n</code></pre>\n" }, { "answer_id": 37345569, "author": "user6360847", "author_id": 6360847, "author_profile": "https://Stackoverflow.com/users/6360847", "pm_score": -1, "selected": false, "text": "<pre><code>declare @StartDate datetime = '2016-01-31'\ndeclare @EndDate datetime = '2016-02-01'\nSELECT @StartDate AS [StartDate]\n ,@EndDate AS [EndDate]\n ,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END AS [Years]\n ,DATEDIFF(Month,(DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) &gt; @EndDate THEN 1 ELSE 0 END AS [Months]\n ,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) &gt; @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate) - CASE WHEN DATEADD(Day,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) &gt; @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate),DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) &gt; @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) &gt; @EndDate THEN 1 ELSE 0 END,@StartDate))) &gt; @EndDate THEN 1 ELSE 0 END AS [Days]\n</code></pre>\n" }, { "answer_id": 37915012, "author": "Prince Jain", "author_id": 6487482, "author_profile": "https://Stackoverflow.com/users/6487482", "pm_score": -1, "selected": false, "text": "<pre><code>select DOB as Birthdate,\n YEAR(GETDATE()) as ThisYear, \n YEAR(getdate()) - EAR(date1) as Age \nfrom TableName\n</code></pre>\n" }, { "answer_id": 37915082, "author": "Prince Jain", "author_id": 6487482, "author_profile": "https://Stackoverflow.com/users/6487482", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT DOB AS Birthdate ,\n YEAR(GETDATE()) AS ThisYear,\n YEAR(getdate()) - YEAR(DOB) AS Age\nFROM tableprincejain\n</code></pre>\n" }, { "answer_id": 51813114, "author": "Adal H. Vega", "author_id": 2097023, "author_profile": "https://Stackoverflow.com/users/2097023", "pm_score": 2, "selected": false, "text": "<p>I use this Function I modified (the Days part) From @Dane answer: <a href=\"https://stackoverflow.com/a/57720/2097023\">https://stackoverflow.com/a/57720/2097023</a></p>\n\n<pre><code>CREATE FUNCTION dbo.EdadAMD\n (\n @FECHA DATETIME\n )\n RETURNS NVARCHAR(10)\n AS\n BEGIN\n DECLARE\n @tmpdate DATETIME\n , @years INT\n , @months INT\n , @days INT\n , @EdadAMD NVARCHAR(10);\n\n SELECT @tmpdate = @FECHA;\n\n SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE\n WHEN (MONTH(@FECHA) &gt; MONTH(GETDATE()))\n OR (\n MONTH(@FECHA) = MONTH(GETDATE())\n AND DAY(@FECHA) &gt; DAY(GETDATE())\n ) THEN\n 1\n ELSE\n 0\n END;\n SELECT @tmpdate = DATEADD(yy, @years, @tmpdate);\n SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE\n WHEN DAY(@FECHA) &gt; DAY(GETDATE()) THEN\n 1\n ELSE\n 0\n END;\n SELECT @tmpdate = DATEADD(m, @months, @tmpdate);\n\n IF MONTH(@FECHA) = MONTH(GETDATE())\n AND DAY(@FECHA) &gt; DAY(GETDATE())\n SELECT @days = \n DAY(EOMONTH(GETDATE(), -1)) - (DAY(@FECHA) - DAY(GETDATE()));\n ELSE\n SELECT @days = DATEDIFF(d, @tmpdate, GETDATE());\n\n SELECT @EdadAMD = CONCAT(@years, 'a', @months, 'm', @days, 'd');\n\n RETURN @EdadAMD;\n\nEND; \nGO\n</code></pre>\n\n<p>It works pretty well.</p>\n" }, { "answer_id": 54178003, "author": "Sai Krishnan Harish", "author_id": 7906457, "author_profile": "https://Stackoverflow.com/users/7906457", "pm_score": 0, "selected": false, "text": "<p>There is another method for calculate age is</p>\n\n<p>See below table</p>\n\n<pre><code> FirstName LastName DOB\n sai krishnan 1991-11-04\n Harish S A 1998-10-11\n</code></pre>\n\n<p>For finding age,you can calculate through month</p>\n\n<pre><code> Select datediff(MONTH,DOB,getdate())/12 as dates from [Organization].[Employee]\n</code></pre>\n\n<p>Result will be </p>\n\n<pre><code>firstname dates\nsai 27\nHarish 20\n</code></pre>\n" }, { "answer_id": 59627199, "author": "Sanket Doshi", "author_id": 5934456, "author_profile": "https://Stackoverflow.com/users/5934456", "pm_score": -1, "selected": false, "text": "<pre><code>declare @BirthDate datetime\ndeclare @TotalYear int\ndeclare @TotalMonths int\ndeclare @TotalDays int\ndeclare @TotalWeeks int\ndeclare @TotalHours int\ndeclare @TotalMinute int\ndeclare @TotalSecond int\ndeclare @CurrentDtTime datetime\nset @BirthDate='1998/01/05 05:04:00' -- Set Your date here\nset @TotalYear= FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / 365.25)\nset @TotalMonths= FLOOR(DATEDIFF(DAY,DATEADD(year, @TotalYear,@BirthDate),GetDate()) / 30.436875E)\nset @TotalDays= FLOOR(DATEDIFF(DAY, DATEADD(month, @TotalMonths,DATEADD(year, \n @TotalYear,@BirthDate)), GETDATE()))\nset @CurrentDtTime=CONVERT(datetime,CONVERT(varchar(50), DATEPART(year, \n GetDate()))+'/' +CONVERT(varchar(50), DATEPART(MONTH, GetDate()))\n +'/'+ CONVERT(varchar(50),DATEPART(DAY, GetDate()))+' '\n + CONVERT(varchar(50),DATEPART(HOUR, @BirthDate))+':'+ \n CONVERT(varchar(50),DATEPART(MINUTE, @BirthDate))+\n ':'+ CONVERT(varchar(50),DATEPART(Second, @BirthDate)))\nset @TotalHours = DATEDIFF(hour, @CurrentDtTime, GETDATE())\nif(@TotalHours &lt; 0)\nbegin\n set @TotalHours = DATEDIFF(hour,DATEADD(Day,-1, @CurrentDtTime), GETDATE())\n set @TotalDays= @TotalDays -1 \n end\nset @TotalMinute= DATEPART(MINUTE, GETDATE())-DATEPART(MINUTE, @BirthDate)\n if(@TotalMinute &lt; 0)\nset @TotalMinute = DATEPART(MINUTE, DATEADD(hour,-1,GETDATE()))+(60-DATEPART(MINUTE, \n @BirthDate))\n\nset @TotalSecond= DATEPART(Second, GETDATE())-DATEPART(Second, @BirthDate)\n\n Print 'Your age are'+ CHAR(13)\n + CONVERT(varchar(50), @TotalYear)+' Years, ' +\n CONVERT(varchar(50),@TotalMonths) +' Months, ' +\n CONVERT(varchar(50),@TotalDays)+' Days, ' +\n CONVERT(varchar(50),@TotalHours)+' Hours, ' +\n CONVERT(varchar(50),@TotalMinute)+' Minutes, ' + \n CONVERT(varchar(50),@TotalSecond)+' Seconds. ' +char(13)+\n 'Your are born at day of week was - ' + CONVERT(varchar(50),DATENAME(dw , \n @BirthDate ))\n +char(13)+char(13)+\n+'Your Birthdate to till date your '+ CHAR(13)\n+'Years - ' + CONVERT(varchar(50), FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / \n 365.25))\n+' , Months - ' + CONVERT(varchar(50),DATEDIFF(MM,@BirthDate,getdate())) \n+' , Weeks - ' + CONVERT(varchar(50),DATEDIFF(wk,@BirthDate,getdate()))\n+' , Days - ' + CONVERT(varchar(50),DATEDIFF(dd,@BirthDate,getdate()))+char(13)+\n+'Hours - ' + CONVERT(varchar(50),DATEDIFF(HH,@BirthDate,getdate()))\n+' , Minutes - ' + CONVERT(varchar(50),DATEDIFF(mi,@BirthDate,getdate()))\n+' , Seconds - ' + CONVERT(varchar(50),DATEDIFF(ss,@BirthDate,getdate()))\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>Your age are\n22 Years, 0 Months, 2 Days, 11 Hours, 30 Minutes, 16 Seconds. \nYour are born at day of week was - Monday\n\nYour Birthdate to till date your \nYears - 22 , Months - 264 , Weeks - 1148 , Days - 8037\nHours - 192899 , Minutes - 11573970 , Seconds - 694438216\n</code></pre>\n" }, { "answer_id": 73035178, "author": "Mohan Kethireddigari", "author_id": 19533588, "author_profile": "https://Stackoverflow.com/users/19533588", "pm_score": 0, "selected": false, "text": "<p>I have created a function <code>calculateAge</code> that takes parameter <code>dateOfBirth</code> from outside and then it calculates the age in years, months and days and finally it returns in string format.</p>\n<pre><code>CREATE FUNCTION calculateAge(dateOfBirth datetime) RETURNS varchar(40)\nBEGIN\n set @currentdatetime = CURRENT_TIMESTAMP;\n set @years = TIMESTAMPDIFF(YEAR,dateOfBirth,@currentdatetime);\n set @months = TIMESTAMPDIFF(MONTH,dateOfBirth,@currentdatetime) - @years*12 ;\n set @dayOfBirth = EXTRACT(DAY FROM dateOfBirth);\n set @today = EXTRACT(DAY FROM @currentdatetime);\n set @days = 0;\n if (@today &gt; @dayOfBirth) then\n set @days = @today - @dayOfBirth;\n else\n set @decreaseMonth = DATE_SUB(@currentdatetime, INTERVAL 1 MONTH);\n set @days = DATEDIFF(dateOfBirth, @decreaseMonth);\n end if;\n RETURN concat(concat( concat(@years , &quot;years\\n&quot;) , concat(@months , &quot;months\\n&quot;)), concat(@days , &quot;days&quot;));\nEND\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845/" ]
What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)? The `datediff` function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my [stored procedure](http://en.wikipedia.org/wiki/Stored_procedure).
Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate. ``` DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int SELECT @date = '2/29/04' SELECT @tmpdate = @date SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(yy, @years, @tmpdate) SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(m, @months, @tmpdate) SELECT @days = DATEDIFF(d, @tmpdate, GETDATE()) SELECT @years, @months, @days ```
57,600
<p>Should developers avoid using <a href="http://msdn.microsoft.com/en-us/library/923ahwt1.aspx" rel="nofollow noreferrer">continue</a> in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about <a href="https://stackoverflow.com/questions/46586/goto-still-considered-harmful">Goto</a>? </p>
[ { "answer_id": 57606, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": false, "text": "<p>I don't think continue could ever be as difficult as goto since continue never moves execution out of the code block that it is in.</p>\n" }, { "answer_id": 57611, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 7, "selected": true, "text": "<p>I think there should be more use of continue!</p>\n\n<p>Too often I come across code like:</p>\n\n<pre><code>for (...)\n{\n if (!cond1)\n {\n if (!cond2)\n {\n ... highly indented lines ...\n }\n }\n}\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>for (...)\n{\n if (cond1 || cond2)\n {\n continue;\n }\n\n ...\n}\n</code></pre>\n\n<p>Use it to make the code more readable!</p>\n" }, { "answer_id": 57616, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 5, "selected": false, "text": "<p>Is <strong><code>continue</code></strong> any more harmful than, say, <strong><code>break</code></strong>?</p>\n\n<p>If anything, in the majority of cases where I encounter/use it, I find it makes code clearer and less spaghetti-like.</p>\n" }, { "answer_id": 57619, "author": "Patman", "author_id": 5729, "author_profile": "https://Stackoverflow.com/users/5729", "pm_score": 4, "selected": false, "text": "<p>You can write good code with or without continue and you can write bad code with or without continue.</p>\n\n<p>There probably is some overlap with arguments about goto, but as far as I'm concerned the use of continue is equivalent to using break statements (in loops) or return statement from anywhere in a method body - if used correctly it can simplify the code (less likely to contain bugs, easier to maintain).</p>\n" }, { "answer_id": 57632, "author": "stukelly", "author_id": 5891, "author_profile": "https://Stackoverflow.com/users/5891", "pm_score": 0, "selected": false, "text": "<p>Continue is a really useful function in most languages, because it allows blocks of code to be skipped for certain conditions.</p>\n\n<p>One alternative would be to uses boolean variables in if statements, but these would need to be reset after every use.</p>\n" }, { "answer_id": 57657, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": -1, "selected": false, "text": "<p><code>continue</code> feels wrong to me. <code>break</code> gets you out of there, but <code>continue</code> seems just to be spaghetti.</p>\n\n<p>On the other hand, you can emulate <code>continue</code> with <code>break</code> (at least in Java).</p>\n\n<pre><code>for (String str : strs) contLp: {\n ...\n break contLp;\n ...\n}\n</code></pre>\n\n<p>(This posting had an obvious bug in the above code for over a decade. That doesn't look good for <code>break</code>/<code>continue</code>.)</p>\n\n<p><code>continue</code> can be useful in some circumstances, but it still feels dirty to me. It might be time to introduce a new method.</p>\n\n<pre><code>for (char c : cs) {\n final int i;\n if ('0' &lt;= c &amp;&amp; c &lt;= '9') {\n i = c - '0';\n } else if ('a' &lt;= c &amp;&amp; c &lt;= 'z') {\n i = c - 'a' + 10;\n } else {\n continue;\n }\n ... use i ...\n}\n</code></pre>\n\n<p>These uses should be very rare.</p>\n" }, { "answer_id": 57668, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": "<p>goto can be used as a continue, but not the reverse.</p>\n\n<p>You can \"goto\" anywhere, thus break flow control arbitrarily.</p>\n\n<p>Thus continue, not nearly as harmful.</p>\n" }, { "answer_id": 57681, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 3, "selected": false, "text": "<p>If continue is causing a problem with readability, then chances are you have other problems. For example, massive amounts of code inside a for loop. If you have to write large for loops, I would try to stick to using continue close to the top of the for loop. Otherwise, a continue buried deep in the middle of a for loop can easily be missed.</p>\n" }, { "answer_id": 57765, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 3, "selected": false, "text": "<p>There are not harmful keywords. There's only harmful uses of them.</p>\n\n<p>Goto is not harmful per se, neither is continue. They need to be used carefully, that's all.</p>\n" }, { "answer_id": 57786, "author": "Jack Bolding", "author_id": 5882, "author_profile": "https://Stackoverflow.com/users/5882", "pm_score": 3, "selected": false, "text": "<p>I like to use continue at the beginning of loops for handling simple if conditions.</p>\n\n<p>To me it makes the code more readable since there is not extra nesting and you can see that I have explicitly dealt with these cases.</p>\n\n<p>Is this the same reason that I would use a goto? Perhaps. I do use them for readability at times and to stop the nesting of code but I usually use them more for cleanup/error handling. </p>\n" }, { "answer_id": 57806, "author": "Nij", "author_id": 6004, "author_profile": "https://Stackoverflow.com/users/6004", "pm_score": 1, "selected": false, "text": "<p>Others have hinted at it... but continue and break are enforced by the <strong>compiler</strong> and have their own associated rules. Goto has no such limitations, though the net effect <em>might</em> almost be the same, in some circumstances.</p>\n\n<p>I do not consider continue or break to be harmful per se, though I'm sure either can be used poorly in a way that would make any sane programmer gag.</p>\n" }, { "answer_id": 58320, "author": "Christopher Elliott", "author_id": 5072, "author_profile": "https://Stackoverflow.com/users/5072", "pm_score": -1, "selected": false, "text": "<p>I believe the bottom line argument against continue is that it makes it harder to PROVE that the code is correct. This is prove in the mathematical sense. But it probably doesn't matter to you because no one has the resources to 'prove' a computer program that is significantly complex. </p>\n\n<p>Enter the static-analysis tools. You may make things harder on them...</p>\n\n<p>And the goto, that sounds like a nightmare for the same reasons but at any random place in code. </p>\n" }, { "answer_id": 58923, "author": "Peter Bernier", "author_id": 6112, "author_profile": "https://Stackoverflow.com/users/6112", "pm_score": 0, "selected": false, "text": "<p>I'd say yes. To me, it just breaks the 'flow' of a fluidly-written piece of code.</p>\n\n<p>Another argument could also be that if you stick to the basic keywords supported by most modern languages, then your program flow (if not the logic or code) could be ported to any other language. Having an unsupported keyword (ie, continue or goto) would break that.</p>\n\n<p>It's really more of a personal preference, but I've never had to use it and don't really consider it an option when I'm writing new code. (same as goto.)</p>\n" }, { "answer_id": 63187, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 2, "selected": false, "text": "<p>If you are iterating through any kind of a result set, and performing operations on said results, for e.g within a for each, and if one particular result caused a problem, its rather useful in capturing an expected error (via try-catch), logging it, and moving on to the next result via continue. Continue is especially useful, imo, for unattended services that do jobs at odd hours, and one exception shouldn't affect the other x number of records.</p>\n" }, { "answer_id": 436952, "author": "blabla999", "author_id": 48469, "author_profile": "https://Stackoverflow.com/users/48469", "pm_score": 2, "selected": false, "text": "<p>I'd say: \"it depends\".</p>\n\n<p>If you have reasonably small loop code (where you can see the whole loop-code without scrolling) its usually ok to use a continue.</p>\n\n<p>However, if the loops body is large (for example due to a big switch), and there is some followup code (say below the switch), you may easily introduce bugs by adding a continue and thus skipping over that code sometimes. I have encountered this in the heart of a bytecode interpreter, where some instrumentation code was sometimes not executed due to a continue in some case-branches.</p>\n\n<p>This might be a somewhat artificially constructed case, but I generally try to avoid continue and use an if (but not nesting too deep as in the Rob's sample code).</p>\n" }, { "answer_id": 436963, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 2, "selected": false, "text": "<p>As far as this programmer is concerned, <strong>Nested if/else</strong> considered harmful.</p>\n" }, { "answer_id": 619943, "author": "Victor Rodrigues", "author_id": 21668, "author_profile": "https://Stackoverflow.com/users/21668", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>Using continue at the beginning of a loop to avoid iteration over unnecessary elements is not harmful and can be very useful, but using it in the middle of nested ifs and elses can turn the loop code into a complex maze, to understand and validate.</p></li>\n<li><p>I think its usage avoidance is also the result of a semantic misunderstanding. People who does never see/write 'continue' keyword on their code, when seeing a code with continue can interpret it as \"the continuation of the natural flow\". If instead of continue we had <strong>next</strong>, for instance, I think more people would appreciate this valuable cursor feature.</p></li>\n</ol>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ]
Should developers avoid using [continue](http://msdn.microsoft.com/en-us/library/923ahwt1.aspx) in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about [Goto](https://stackoverflow.com/questions/46586/goto-still-considered-harmful)?
I think there should be more use of continue! Too often I come across code like: ``` for (...) { if (!cond1) { if (!cond2) { ... highly indented lines ... } } } ``` instead of ``` for (...) { if (cond1 || cond2) { continue; } ... } ``` Use it to make the code more readable!
57,615
<p>I have a console app in which I want to give the user <em>x</em> seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response.</p> <p>What is the most straightforward way of approaching this?</p>
[ { "answer_id": 57639, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 3, "selected": false, "text": "<p>I think you will need to make a secondary thread and poll for a key on the console. I know of no built in way to accomplish this.</p>\n" }, { "answer_id": 57655, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": false, "text": "<p>Will this approach using <a href=\"http://msdn.microsoft.com/en-us/library/system.console.keyavailable.aspx\" rel=\"noreferrer\">Console.KeyAvailable</a> help?</p>\n\n<pre><code>class Sample \n{\n public static void Main() \n {\n ConsoleKeyInfo cki = new ConsoleKeyInfo();\n\n do {\n Console.WriteLine(\"\\nPress a key to display; press the 'x' key to quit.\");\n\n// Your code could perform some useful task in the following loop. However, \n// for the sake of this example we'll merely pause for a quarter second.\n\n while (Console.KeyAvailable == false)\n Thread.Sleep(250); // Loop until input is entered.\n cki = Console.ReadKey(true);\n Console.WriteLine(\"You pressed the '{0}' key.\", cki.Key);\n } while(cki.Key != ConsoleKey.X);\n }\n}\n</code></pre>\n" }, { "answer_id": 57686, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 3, "selected": false, "text": "<p>One way or another you do need a second thread. You could use asynchronous IO to avoid declaring your own:</p>\n\n<ul>\n<li>declare a ManualResetEvent, call it \"evt\"</li>\n<li>call System.Console.OpenStandardInput to get the input stream. Specify a callback method that will store its data and set evt.</li>\n<li>call that stream's BeginRead method to start an asynchronous read operation</li>\n<li>then enter a timed wait on a ManualResetEvent</li>\n<li>if the wait times out, then cancel the read</li>\n</ul>\n\n<p>If the read returns data, set the event and your main thread will continue, otherwise you'll continue after the timeout.</p>\n" }, { "answer_id": 57692, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Another cheap way to get a 2nd thread is to wrap it in a delegate.</p>\n" }, { "answer_id": 57711, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 2, "selected": false, "text": "<p><strong>EDIT</strong>: fixed the problem by having the actual work be done in a separate process and killing that process if it times out. See below for details. Whew!</p>\n\n<p>Just gave this a run and it seemed to work nicely. My coworker had a version which used a Thread object, but I find the BeginInvoke() method of delegate types to be a bit more elegant.</p>\n\n<pre><code>namespace TimedReadLine\n{\n public static class Console\n {\n private delegate string ReadLineInvoker();\n\n public static string ReadLine(int timeout)\n {\n return ReadLine(timeout, null);\n }\n\n public static string ReadLine(int timeout, string @default)\n {\n using (var process = new System.Diagnostics.Process\n {\n StartInfo =\n {\n FileName = \"ReadLine.exe\",\n RedirectStandardOutput = true,\n UseShellExecute = false\n }\n })\n {\n process.Start();\n\n var rli = new ReadLineInvoker(process.StandardOutput.ReadLine);\n var iar = rli.BeginInvoke(null, null);\n\n if (!iar.AsyncWaitHandle.WaitOne(new System.TimeSpan(0, 0, timeout)))\n {\n process.Kill();\n return @default;\n }\n\n return rli.EndInvoke(iar);\n }\n }\n }\n}\n</code></pre>\n\n<p>The ReadLine.exe project is a very simple one which has one class which looks like so:</p>\n\n<pre><code>namespace ReadLine\n{\n internal static class Program\n {\n private static void Main()\n {\n System.Console.WriteLine(System.Console.ReadLine());\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 57775, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": false, "text": "<p>Calling Console.ReadLine() in the delegate is bad because if the user doesn't hit 'enter' then that call will never return. The thread executing the delegate will be blocked until the user hits 'enter', with no way to cancel it.</p>\n\n<p>Issuing a sequence of these calls will not behave as you would expect. Consider the following (using the example Console class from above):</p>\n\n<pre><code>System.Console.WriteLine(\"Enter your first name [John]:\");\n\nstring firstName = Console.ReadLine(5, \"John\");\n\nSystem.Console.WriteLine(\"Enter your last name [Doe]:\");\n\nstring lastName = Console.ReadLine(5, \"Doe\");\n</code></pre>\n\n<p>The user lets the timeout expire for the first prompt, then enters a value for the second prompt. Both firstName and lastName will contain the default values. When the user hits 'enter', the <strong>first</strong> ReadLine call will complete, but the code has abandonded that call and essentially discarded the result. The <strong>second</strong> ReadLine call will continue to block, the timeout will eventually expire and the value returned will again be the default.</p>\n\n<p>BTW- There is a bug in the code above. By calling waitHandle.Close() you close the event out from under the worker thread. If the user hits 'enter' after the timeout expires, the worker thread will attempt to signal the event which throws an ObjectDisposedException. The exception is thrown from the worker thread, and if you haven't setup an unhandled exception handler your process will terminate.</p>\n" }, { "answer_id": 231333, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 2, "selected": false, "text": "<p>I may be reading too much into the question, but I am assuming the wait would be similar to the boot menu where it waits 15 seconds unless you press a key. You could either use (1) a blocking function or (2) you could use a thread, an event, and a timer. The event would act as a 'continue' and would block until either the timer expired or a key was pressed.</p>\n\n<p>Pseudo-code for (1) would be:</p>\n\n<pre><code>// Get configurable wait time\nTimeSpan waitTime = TimeSpan.FromSeconds(15.0);\nint configWaitTimeSec;\nif (int.TryParse(ConfigManager.AppSetting[\"DefaultWaitTime\"], out configWaitTimeSec))\n waitTime = TimeSpan.FromSeconds(configWaitTimeSec);\n\nbool keyPressed = false;\nDateTime expireTime = DateTime.Now + waitTime;\n\n// Timer and key processor\nConsoleKeyInfo cki;\n// EDIT: adding a missing ! below\nwhile (!keyPressed &amp;&amp; (DateTime.Now &lt; expireTime))\n{\n if (Console.KeyAvailable)\n {\n cki = Console.ReadKey(true);\n // TODO: Process key\n keyPressed = true;\n }\n Thread.Sleep(10);\n}\n</code></pre>\n" }, { "answer_id": 885542, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Example implementation of Eric's post above. This particular example was used to read information that was passed to a console app via pipe:</p>\n\n<pre><code> using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading;\n\nnamespace PipedInfo\n{\n class Program\n {\n static void Main(string[] args)\n {\n StreamReader buffer = ReadPipedInfo();\n\n Console.WriteLine(buffer.ReadToEnd());\n }\n\n #region ReadPipedInfo\n public static StreamReader ReadPipedInfo()\n {\n //call with a default value of 5 milliseconds\n return ReadPipedInfo(5);\n }\n\n public static StreamReader ReadPipedInfo(int waitTimeInMilliseconds)\n {\n //allocate the class we're going to callback to\n ReadPipedInfoCallback callbackClass = new ReadPipedInfoCallback();\n\n //to indicate read complete or timeout\n AutoResetEvent readCompleteEvent = new AutoResetEvent(false);\n\n //open the StdIn so that we can read against it asynchronously\n Stream stdIn = Console.OpenStandardInput();\n\n //allocate a one-byte buffer, we're going to read off the stream one byte at a time\n byte[] singleByteBuffer = new byte[1];\n\n //allocate a list of an arbitary size to store the read bytes\n List&lt;byte&gt; byteStorage = new List&lt;byte&gt;(4096);\n\n IAsyncResult asyncRead = null;\n int readLength = 0; //the bytes we have successfully read\n\n do\n {\n //perform the read and wait until it finishes, unless it's already finished\n asyncRead = stdIn.BeginRead(singleByteBuffer, 0, singleByteBuffer.Length, new AsyncCallback(callbackClass.ReadCallback), readCompleteEvent);\n if (!asyncRead.CompletedSynchronously)\n readCompleteEvent.WaitOne(waitTimeInMilliseconds);\n\n //end the async call, one way or another\n\n //if our read succeeded we store the byte we read\n if (asyncRead.IsCompleted)\n {\n readLength = stdIn.EndRead(asyncRead);\n if (readLength &gt; 0)\n byteStorage.Add(singleByteBuffer[0]);\n }\n\n } while (asyncRead.IsCompleted &amp;&amp; readLength &gt; 0);\n //we keep reading until we fail or read nothing\n\n //return results, if we read zero bytes the buffer will return empty\n return new StreamReader(new MemoryStream(byteStorage.ToArray(), 0, byteStorage.Count));\n }\n\n private class ReadPipedInfoCallback\n {\n public void ReadCallback(IAsyncResult asyncResult)\n {\n //pull the user-defined variable and strobe the event, the read finished successfully\n AutoResetEvent readCompleteEvent = asyncResult.AsyncState as AutoResetEvent;\n readCompleteEvent.Set();\n }\n }\n #endregion ReadPipedInfo\n }\n}\n</code></pre>\n" }, { "answer_id": 2041489, "author": "gp.", "author_id": 247843, "author_profile": "https://Stackoverflow.com/users/247843", "pm_score": 5, "selected": false, "text": "<pre><code>string ReadLine(int timeoutms)\n{\n ReadLineDelegate d = Console.ReadLine;\n IAsyncResult result = d.BeginInvoke(null, null);\n result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs\n if (result.IsCompleted)\n {\n string resultstr = d.EndInvoke(result);\n Console.WriteLine(\"Read: \" + resultstr);\n return resultstr;\n }\n else\n {\n Console.WriteLine(\"Timed out!\");\n throw new TimedoutException(\"Timed Out!\");\n }\n}\n\ndelegate string ReadLineDelegate();\n</code></pre>\n" }, { "answer_id": 2282672, "author": "mphair", "author_id": 191299, "author_profile": "https://Stackoverflow.com/users/191299", "pm_score": 1, "selected": false, "text": "<p>Simple threading example to solve this</p>\n\n<pre><code>Thread readKeyThread = new Thread(ReadKeyMethod);\nstatic ConsoleKeyInfo cki = null;\n\nvoid Main()\n{\n readKeyThread.Start();\n bool keyEntered = false;\n for(int ii = 0; ii &lt; 10; ii++)\n {\n Thread.Sleep(1000);\n if(readKeyThread.ThreadState == ThreadState.Stopped)\n keyEntered = true;\n }\n if(keyEntered)\n { //do your stuff for a key entered\n }\n}\n\nvoid ReadKeyMethod()\n{\n cki = Console.ReadKey();\n}\n</code></pre>\n\n<p>or a static string up top for getting an entire line.</p>\n" }, { "answer_id": 2967469, "author": "Jamie Kitson", "author_id": 139560, "author_profile": "https://Stackoverflow.com/users/139560", "pm_score": 2, "selected": false, "text": "<p>I can't comment on Gulzar's post unfortunately, but here's a fuller example:</p>\n\n<pre><code> while (Console.KeyAvailable == false)\n {\n Thread.Sleep(250);\n i++;\n if (i &gt; 3)\n throw new Exception(\"Timedout waiting for input.\");\n }\n input = Console.ReadLine();\n</code></pre>\n" }, { "answer_id": 2974065, "author": "Sasha", "author_id": 197897, "author_profile": "https://Stackoverflow.com/users/197897", "pm_score": 1, "selected": false, "text": "<p>Im my case this work fine:</p>\n\n<pre><code>public static ManualResetEvent evtToWait = new ManualResetEvent(false);\n\nprivate static void ReadDataFromConsole( object state )\n{\n Console.WriteLine(\"Enter \\\"x\\\" to exit or wait for 5 seconds.\");\n\n while (Console.ReadKey().KeyChar != 'x')\n {\n Console.Out.WriteLine(\"\");\n Console.Out.WriteLine(\"Enter again!\");\n }\n\n evtToWait.Set();\n}\n\nstatic void Main(string[] args)\n{\n Thread status = new Thread(ReadDataFromConsole);\n status.Start();\n\n evtToWait = new ManualResetEvent(false);\n\n evtToWait.WaitOne(5000); // wait for evtToWait.Set() or timeOut\n\n status.Abort(); // exit anyway\n return;\n}\n</code></pre>\n" }, { "answer_id": 3591551, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 3, "selected": false, "text": "<pre><code>// Wait for 'Enter' to be pressed or 5 seconds to elapse\nusing (Stream s = Console.OpenStandardInput())\n{\n ManualResetEvent stop_waiting = new ManualResetEvent(false);\n s.BeginRead(new Byte[1], 0, 1, ar =&gt; stop_waiting.Set(), null);\n\n // ...do anything else, or simply...\n\n stop_waiting.WaitOne(5000);\n // If desired, other threads could also set 'stop_waiting' \n // Disposing the stream cancels the async read operation. It can be\n // re-opened if needed.\n}\n</code></pre>\n" }, { "answer_id": 7318974, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 0, "selected": false, "text": "<pre><code>string readline = \"?\";\nThreadPool.QueueUserWorkItem(\n delegate\n {\n readline = Console.ReadLine();\n }\n);\ndo\n{\n Thread.Sleep(100);\n} while (readline == \"?\");\n</code></pre>\n\n<p>Note that if you go down the \"Console.ReadKey\" route, you lose some of the cool features of ReadLine, namely:</p>\n\n<ul>\n<li>Support for delete, backspace, arrow keys, etc.</li>\n<li>The ability to press the \"up\" key and repeat the last command (this comes in very handy if you implement a background debugging console that gets a lot of use).</li>\n</ul>\n\n<p>To add a timeout, alter the while loop to suit.</p>\n" }, { "answer_id": 7664463, "author": "user980750", "author_id": 980750, "author_profile": "https://Stackoverflow.com/users/980750", "pm_score": 4, "selected": false, "text": "<p>This worked for me.</p>\n<pre><code>ConsoleKeyInfo k = new ConsoleKeyInfo();\nConsole.WriteLine(&quot;Press any key in the next 5 seconds.&quot;);\nfor (int cnt = 5; cnt &gt; 0; cnt--)\n {\n if (Console.KeyAvailable)\n {\n k = Console.ReadKey();\n break;\n }\n else\n {\n Console.WriteLine(cnt.ToString());\n System.Threading.Thread.Sleep(1000);\n }\n }\nConsole.WriteLine(&quot;The key pressed was &quot; + k.Key);\n</code></pre>\n" }, { "answer_id": 9016896, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 3, "selected": false, "text": "<p>I struggled with this problem for 5 months before I found an solution that works perfectly in an enterprise setting.</p>\n\n<p>The problem with most of the solutions so far is that they rely on something other than Console.ReadLine(), and Console.ReadLine() has a lot of advantages:</p>\n\n<ul>\n<li>Support for delete, backspace, arrow keys, etc.</li>\n<li>The ability to press the \"up\" key and repeat the last command (this comes in very handy if you implement a background debugging console that gets a lot of use).</li>\n</ul>\n\n<p>My solution is as follows:</p>\n\n<ol>\n<li>Spawn a <strong>separate thread</strong> to handle the user input using Console.ReadLine().</li>\n<li>After the timeout period, unblock Console.ReadLine() by sending an [enter] key into the current console window, using <a href=\"http://inputsimulator.codeplex.com/\" rel=\"nofollow noreferrer\">http://inputsimulator.codeplex.com/</a>.</li>\n</ol>\n\n<p>Sample code:</p>\n\n<pre><code> InputSimulator.SimulateKeyPress(VirtualKeyCode.RETURN);\n</code></pre>\n\n<p>More information on this technique, including the correct technique to abort a thread that uses Console.ReadLine:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/9016087/net-call-to-send-enter-keystroke-into-the-current-process-which-is-a-console\">.NET call to send [enter] keystroke into the current process, which is a console app?</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/8984838/how-to-abort-another-thread-in-net-when-said-thread-is-executing-console-readl\">How to abort another thread in .NET, when said thread is executing Console.ReadLine?</a></p>\n" }, { "answer_id": 16503766, "author": "John Atac", "author_id": 2374141, "author_profile": "https://Stackoverflow.com/users/2374141", "pm_score": 1, "selected": false, "text": "<p>Isn't this nice and short?</p>\n\n<pre><code>if (SpinWait.SpinUntil(() =&gt; Console.KeyAvailable, millisecondsTimeout))\n{\n ConsoleKeyInfo keyInfo = Console.ReadKey();\n\n // Handle keyInfo value here...\n}\n</code></pre>\n" }, { "answer_id": 17627972, "author": "mikemay", "author_id": 96167, "author_profile": "https://Stackoverflow.com/users/96167", "pm_score": 1, "selected": false, "text": "<p>This is a fuller example of Glen Slayden's solution. I happended to make this when building a test case for another problem. It uses asynchronous I/O and a manual reset event.</p>\n\n<pre><code>public static void Main() {\n bool readInProgress = false;\n System.IAsyncResult result = null;\n var stop_waiting = new System.Threading.ManualResetEvent(false);\n byte[] buffer = new byte[256];\n var s = System.Console.OpenStandardInput();\n while (true) {\n if (!readInProgress) {\n readInProgress = true;\n result = s.BeginRead(buffer, 0, buffer.Length\n , ar =&gt; stop_waiting.Set(), null);\n\n }\n bool signaled = true;\n if (!result.IsCompleted) {\n stop_waiting.Reset();\n signaled = stop_waiting.WaitOne(5000);\n }\n else {\n signaled = true;\n }\n if (signaled) {\n readInProgress = false;\n int numBytes = s.EndRead(result);\n string text = System.Text.Encoding.UTF8.GetString(buffer\n , 0, numBytes);\n System.Console.Out.Write(string.Format(\n \"Thank you for typing: {0}\", text));\n }\n else {\n System.Console.Out.WriteLine(\"oy, type something!\");\n }\n }\n</code></pre>\n" }, { "answer_id": 17946497, "author": "David Kirkland", "author_id": 41621, "author_profile": "https://Stackoverflow.com/users/41621", "pm_score": 0, "selected": false, "text": "<p>Please don't hate me for adding another solution to the plethora of existing answers! This works for Console.ReadKey(), but could easily be modified to work with ReadLine(), etc.</p>\n\n<p>As the \"Console.Read\" methods are blocking, it's necessary to \"<a href=\"https://stackoverflow.com/questions/9479573/interrupt-console-readline\">nudge</a>\" the StdIn stream to cancel the read.</p>\n\n<p>Calling syntax:<br></p>\n\n<pre><code>ConsoleKeyInfo keyInfo;\nbool keyPressed = AsyncConsole.ReadKey(500, out keyInfo);\n// where 500 is the timeout\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>public class AsyncConsole // not thread safe\n{\n private static readonly Lazy&lt;AsyncConsole&gt; Instance =\n new Lazy&lt;AsyncConsole&gt;();\n\n private bool _keyPressed;\n private ConsoleKeyInfo _keyInfo;\n\n private bool DoReadKey(\n int millisecondsTimeout,\n out ConsoleKeyInfo keyInfo)\n {\n _keyPressed = false;\n _keyInfo = new ConsoleKeyInfo();\n\n Thread readKeyThread = new Thread(ReadKeyThread);\n readKeyThread.IsBackground = false;\n readKeyThread.Start();\n\n Thread.Sleep(millisecondsTimeout);\n\n if (readKeyThread.IsAlive)\n {\n try\n {\n IntPtr stdin = GetStdHandle(StdHandle.StdIn);\n CloseHandle(stdin);\n readKeyThread.Join();\n }\n catch { }\n }\n\n readKeyThread = null;\n\n keyInfo = _keyInfo;\n return _keyPressed;\n }\n\n private void ReadKeyThread()\n {\n try\n {\n _keyInfo = Console.ReadKey();\n _keyPressed = true;\n }\n catch (InvalidOperationException) { }\n }\n\n public static bool ReadKey(\n int millisecondsTimeout,\n out ConsoleKeyInfo keyInfo)\n {\n return Instance.Value.DoReadKey(millisecondsTimeout, out keyInfo);\n }\n\n private enum StdHandle { StdIn = -10, StdOut = -11, StdErr = -12 };\n\n [DllImport(\"kernel32.dll\")]\n private static extern IntPtr GetStdHandle(StdHandle std);\n\n [DllImport(\"kernel32.dll\")]\n private static extern bool CloseHandle(IntPtr hdl);\n}\n</code></pre>\n" }, { "answer_id": 18342182, "author": "JSQuareD", "author_id": 1370541, "author_profile": "https://Stackoverflow.com/users/1370541", "pm_score": 8, "selected": true, "text": "<p>I'm surprised to learn that after 5 years, all of the answers still suffer from one or more of the following problems:</p>\n\n<ul>\n<li>A function other than ReadLine is used, causing loss of functionality. (Delete/backspace/up-key for previous input).</li>\n<li>Function behaves badly when invoked multiple times (spawning multiple threads, many hanging ReadLine's, or otherwise unexpected behavior).</li>\n<li>Function relies on a busy-wait. Which is a horrible waste since the wait is expected to run anywhere from a number of seconds up to the timeout, which might be multiple minutes. A busy-wait which runs for such an ammount of time is a horrible suck of resources, which is especially bad in a multithreading scenario. If the busy-wait is modified with a sleep this has a negative effect on responsiveness, although I admit that this is probably not a huge problem.</li>\n</ul>\n\n<p>I believe my solution will solve the original problem without suffering from any of the above problems:</p>\n\n<pre><code>class Reader {\n private static Thread inputThread;\n private static AutoResetEvent getInput, gotInput;\n private static string input;\n\n static Reader() {\n getInput = new AutoResetEvent(false);\n gotInput = new AutoResetEvent(false);\n inputThread = new Thread(reader);\n inputThread.IsBackground = true;\n inputThread.Start();\n }\n\n private static void reader() {\n while (true) {\n getInput.WaitOne();\n input = Console.ReadLine();\n gotInput.Set();\n }\n }\n\n // omit the parameter to read a line without a timeout\n public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) {\n getInput.Set();\n bool success = gotInput.WaitOne(timeOutMillisecs);\n if (success)\n return input;\n else\n throw new TimeoutException(\"User did not provide input within the timelimit.\");\n }\n}\n</code></pre>\n\n<p>Calling is, of course, very easy:</p>\n\n<pre><code>try {\n Console.WriteLine(\"Please enter your name within the next 5 seconds.\");\n string name = Reader.ReadLine(5000);\n Console.WriteLine(\"Hello, {0}!\", name);\n} catch (TimeoutException) {\n Console.WriteLine(\"Sorry, you waited too long.\");\n}\n</code></pre>\n\n<p>Alternatively, you can use the <code>TryXX(out)</code> convention, as shmueli suggested:</p>\n\n<pre><code> public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) {\n getInput.Set();\n bool success = gotInput.WaitOne(timeOutMillisecs);\n if (success)\n line = input;\n else\n line = null;\n return success;\n }\n</code></pre>\n\n<p>Which is called as follows:</p>\n\n<pre><code>Console.WriteLine(\"Please enter your name within the next 5 seconds.\");\nstring name;\nbool success = Reader.TryReadLine(out name, 5000);\nif (!success)\n Console.WriteLine(\"Sorry, you waited too long.\");\nelse\n Console.WriteLine(\"Hello, {0}!\", name);\n</code></pre>\n\n<p>In both cases, you cannot mix calls to <code>Reader</code> with normal <code>Console.ReadLine</code> calls: if the <code>Reader</code> times out, there will be a hanging <code>ReadLine</code> call. Instead, if you want to have a normal (non-timed) <code>ReadLine</code> call, just use the <code>Reader</code> and omit the timeout, so that it defaults to an infinite timeout.</p>\n\n<p>So how about those problems of the other solutions I mentioned?</p>\n\n<ul>\n<li>As you can see, ReadLine is used, avoiding the first problem.</li>\n<li>The function behaves properly when invoked multiple times. Regardless of whether a timeout occurs or not, only one background thread will ever be running and only at most one call to ReadLine will ever be active. Calling the function will always result in the latest input, or in a timeout, and the user won't have to hit enter more than once to submit his input.</li>\n<li>And, obviously, the function does not rely on a busy-wait. Instead it uses proper multithreading techniques to prevent wasting resources.</li>\n</ul>\n\n<p>The only problem that I foresee with this solution is that it is not thread-safe. However, multiple threads can't really ask the user for input at the same time, so synchronization should be happening before making a call to <code>Reader.ReadLine</code> anyway.</p>\n" }, { "answer_id": 19321114, "author": "Brian Gideon", "author_id": 158779, "author_profile": "https://Stackoverflow.com/users/158779", "pm_score": 0, "selected": false, "text": "<p>Here is a solution that uses <code>Console.KeyAvailable</code>. These are blocking calls, but it should be fairly trivial to call them asynchronously via the TPL if desired. I used the standard cancellation mechanisms to make it easy to wire in with the Task Asynchronous Pattern and all that good stuff.</p>\n\n<pre><code>public static class ConsoleEx\n{\n public static string ReadLine(TimeSpan timeout)\n {\n var cts = new CancellationTokenSource();\n return ReadLine(timeout, cts.Token);\n }\n\n public static string ReadLine(TimeSpan timeout, CancellationToken cancellation)\n {\n string line = \"\";\n DateTime latest = DateTime.UtcNow.Add(timeout);\n do\n {\n cancellation.ThrowIfCancellationRequested();\n if (Console.KeyAvailable)\n {\n ConsoleKeyInfo cki = Console.ReadKey();\n if (cki.Key == ConsoleKey.Enter)\n {\n return line;\n }\n else\n {\n line += cki.KeyChar;\n }\n }\n Thread.Sleep(1);\n }\n while (DateTime.UtcNow &lt; latest);\n return null;\n }\n}\n</code></pre>\n\n<p>There are some disadvantages with this. </p>\n\n<ul>\n<li>You do not get the standard navigation features that <code>ReadLine</code> provides (up/down arrow scrolling, etc.).</li>\n<li>This injects '\\0' characters into input if a special key is press (F1, PrtScn, etc.). You could easily filter them out by modifying the code though.</li>\n</ul>\n" }, { "answer_id": 20631955, "author": "Frank Rem", "author_id": 450467, "author_profile": "https://Stackoverflow.com/users/450467", "pm_score": 0, "selected": false, "text": "<p>Ended up here because a duplicate question was asked. I came up with the following solution which looks straightforward. I am sure it has some drawbacks I missed. </p>\n\n<pre><code>static void Main(string[] args)\n{\n Console.WriteLine(\"Hit q to continue or wait 10 seconds.\");\n\n Task task = Task.Factory.StartNew(() =&gt; loop());\n\n Console.WriteLine(\"Started waiting\");\n task.Wait(10000);\n Console.WriteLine(\"Stopped waiting\");\n}\n\nstatic void loop()\n{\n while (true)\n {\n if ('q' == Console.ReadKey().KeyChar) break;\n }\n}\n</code></pre>\n" }, { "answer_id": 26184541, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 0, "selected": false, "text": "<p>I came to this answer and end up doing:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Reads Line from console with timeout. \n /// &lt;/summary&gt;\n /// &lt;exception cref=\"System.TimeoutException\"&gt;If user does not enter line in the specified time.&lt;/exception&gt;\n /// &lt;param name=\"timeout\"&gt;Time to wait in milliseconds. Negative value will wait forever.&lt;/param&gt; \n /// &lt;returns&gt;&lt;/returns&gt; \n public static string ReadLine(int timeout = -1)\n {\n ConsoleKeyInfo cki = new ConsoleKeyInfo();\n StringBuilder sb = new StringBuilder();\n\n // if user does not want to spesify a timeout\n if (timeout &lt; 0)\n return Console.ReadLine();\n\n int counter = 0;\n\n while (true)\n {\n while (Console.KeyAvailable == false)\n {\n counter++;\n Thread.Sleep(1);\n if (counter &gt; timeout)\n throw new System.TimeoutException(\"Line was not entered in timeout specified\");\n }\n\n cki = Console.ReadKey(false);\n\n if (cki.Key == ConsoleKey.Enter)\n {\n Console.WriteLine();\n return sb.ToString();\n }\n else\n sb.Append(cki.KeyChar); \n } \n }\n</code></pre>\n" }, { "answer_id": 31089330, "author": "cprcrack", "author_id": 423171, "author_profile": "https://Stackoverflow.com/users/423171", "pm_score": 0, "selected": false, "text": "<p>A simple example using <code>Console.KeyAvailable</code>:</p>\n\n<pre><code>Console.WriteLine(\"Press any key during the next 2 seconds...\");\nThread.Sleep(2000);\nif (Console.KeyAvailable)\n{\n Console.WriteLine(\"Key pressed\");\n}\nelse\n{\n Console.WriteLine(\"You were too slow\");\n}\n</code></pre>\n" }, { "answer_id": 34749067, "author": "StevoInco", "author_id": 1812688, "author_profile": "https://Stackoverflow.com/users/1812688", "pm_score": 2, "selected": false, "text": "<p>.NET 4 makes this incredibly simple using Tasks. </p>\n\n<p>First, build your helper:</p>\n\n<pre><code> Private Function AskUser() As String\n Console.Write(\"Answer my question: \")\n Return Console.ReadLine()\n End Function\n</code></pre>\n\n<p>Second, execute with a task and wait:</p>\n\n<pre><code> Dim askTask As Task(Of String) = New TaskFactory().StartNew(Function() AskUser())\n askTask.Wait(TimeSpan.FromSeconds(30))\n If Not askTask.IsCompleted Then\n Console.WriteLine(\"User failed to respond.\")\n Else\n Console.WriteLine(String.Format(\"You responded, '{0}'.\", askTask.Result))\n End If\n</code></pre>\n\n<p>There's no trying to recreate ReadLine functionality or performing other perilous hacks to get this working. Tasks let us solve the question in a very natural way.</p>\n" }, { "answer_id": 37907735, "author": "Shonn Lyga", "author_id": 1951795, "author_profile": "https://Stackoverflow.com/users/1951795", "pm_score": 0, "selected": false, "text": "<p>Much more contemporary and Task based code would look something like this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public string ReadLine(int timeOutMillisecs)\n{\n var inputBuilder = new StringBuilder();\n\n var task = Task.Factory.StartNew(() =&gt;\n {\n while (true)\n {\n var consoleKey = Console.ReadKey(true);\n if (consoleKey.Key == ConsoleKey.Enter)\n {\n return inputBuilder.ToString();\n }\n\n inputBuilder.Append(consoleKey.KeyChar);\n }\n });\n\n\n var success = task.Wait(timeOutMillisecs);\n if (!success)\n {\n throw new TimeoutException(\"User did not provide input within the timelimit.\");\n }\n\n return inputBuilder.ToString();\n}\n</code></pre>\n" }, { "answer_id": 39154725, "author": "JJS", "author_id": 26877, "author_profile": "https://Stackoverflow.com/users/26877", "pm_score": 0, "selected": false, "text": "<p>I had a unique situation of having a Windows Application (Windows Service). When running the program interactively <code>Environment.IsInteractive</code> (VS Debugger or from cmd.exe), I used AttachConsole/AllocConsole to get my stdin/stdout. \nTo keep the process from ending while the work was being done, the UI Thread calls <code>Console.ReadKey(false)</code>. I wanted to cancel the waiting the UI thread was doing from another thread, so I came up with a modification to the solution by @JSquaredD.</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\ninternal class PressAnyKey\n{\n private static Thread inputThread;\n private static AutoResetEvent getInput;\n private static AutoResetEvent gotInput;\n private static CancellationTokenSource cancellationtoken;\n\n static PressAnyKey()\n {\n // Static Constructor called when WaitOne is called (technically Cancel too, but who cares)\n getInput = new AutoResetEvent(false);\n gotInput = new AutoResetEvent(false);\n inputThread = new Thread(ReaderThread);\n inputThread.IsBackground = true;\n inputThread.Name = \"PressAnyKey\";\n inputThread.Start();\n }\n\n private static void ReaderThread()\n {\n while (true)\n {\n // ReaderThread waits until PressAnyKey is called\n getInput.WaitOne();\n // Get here \n // Inner loop used when a caller uses PressAnyKey\n while (!Console.KeyAvailable &amp;&amp; !cancellationtoken.IsCancellationRequested)\n {\n Thread.Sleep(50);\n }\n // Release the thread that called PressAnyKey\n gotInput.Set();\n }\n }\n\n /// &lt;summary&gt;\n /// Signals the thread that called WaitOne should be allowed to continue\n /// &lt;/summary&gt;\n public static void Cancel()\n {\n // Trigger the alternate ending condition to the inner loop in ReaderThread\n if(cancellationtoken== null) throw new InvalidOperationException(\"Must call WaitOne before Cancelling\");\n cancellationtoken.Cancel();\n }\n\n /// &lt;summary&gt;\n /// Wait until a key is pressed or &lt;see cref=\"Cancel\"/&gt; is called by another thread\n /// &lt;/summary&gt;\n public static void WaitOne()\n {\n if(cancellationtoken==null || cancellationtoken.IsCancellationRequested) throw new InvalidOperationException(\"Must cancel a pending wait\");\n cancellationtoken = new CancellationTokenSource();\n // Release the reader thread\n getInput.Set();\n // Calling thread will wait here indefiniately \n // until a key is pressed, or Cancel is called\n gotInput.WaitOne();\n } \n}\n</code></pre>\n" }, { "answer_id": 42940552, "author": "Igorium", "author_id": 6268624, "author_profile": "https://Stackoverflow.com/users/6268624", "pm_score": 1, "selected": false, "text": "<p>Here is safe solution which fakes console input to unblock thread after timeout.\n<a href=\"https://github.com/Igorium/ConsoleReader\" rel=\"nofollow noreferrer\">https://github.com/Igorium/ConsoleReader</a> project provides a sample user dialog implementation.</p>\n\n<pre><code>var inputLine = ReadLine(5);\n\npublic static string ReadLine(uint timeoutSeconds, Func&lt;uint, string&gt; countDownMessage, uint samplingFrequencyMilliseconds)\n{\n if (timeoutSeconds == 0)\n return null;\n\n var timeoutMilliseconds = timeoutSeconds * 1000;\n\n if (samplingFrequencyMilliseconds &gt; timeoutMilliseconds)\n throw new ArgumentException(\"Sampling frequency must not be greater then timeout!\", \"samplingFrequencyMilliseconds\");\n\n CancellationTokenSource cts = new CancellationTokenSource();\n\n Task.Factory\n .StartNew(() =&gt; SpinUserDialog(timeoutMilliseconds, countDownMessage, samplingFrequencyMilliseconds, cts.Token), cts.Token)\n .ContinueWith(t =&gt; {\n var hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;\n PostMessage(hWnd, 0x100, 0x0D, 9);\n }, TaskContinuationOptions.NotOnCanceled);\n\n\n var inputLine = Console.ReadLine();\n cts.Cancel();\n\n return inputLine;\n}\n\n\nprivate static void SpinUserDialog(uint countDownMilliseconds, Func&lt;uint, string&gt; countDownMessage, uint samplingFrequencyMilliseconds,\n CancellationToken token)\n{\n while (countDownMilliseconds &gt; 0)\n {\n token.ThrowIfCancellationRequested();\n\n Thread.Sleep((int)samplingFrequencyMilliseconds);\n\n countDownMilliseconds -= countDownMilliseconds &gt; samplingFrequencyMilliseconds\n ? samplingFrequencyMilliseconds\n : countDownMilliseconds;\n }\n}\n\n\n[DllImport(\"User32.Dll\", EntryPoint = \"PostMessageA\")]\nprivate static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);\n</code></pre>\n" }, { "answer_id": 43651242, "author": "georgiosd", "author_id": 165656, "author_profile": "https://Stackoverflow.com/users/165656", "pm_score": 0, "selected": false, "text": "<p>This seems to be the simplest, working solution, that doesn't use any native APIs:</p>\n\n<pre><code> static Task&lt;string&gt; ReadLineAsync(CancellationToken cancellation)\n {\n return Task.Run(() =&gt;\n {\n while (!Console.KeyAvailable)\n {\n if (cancellation.IsCancellationRequested)\n return null;\n\n Thread.Sleep(100);\n }\n return Console.ReadLine();\n });\n }\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code> static void Main(string[] args)\n {\n AsyncContext.Run(async () =&gt;\n {\n CancellationTokenSource cancelSource = new CancellationTokenSource();\n cancelSource.CancelAfter(1000);\n Console.WriteLine(await ReadLineAsync(cancelSource.Token) ?? \"null\");\n });\n }\n</code></pre>\n" }, { "answer_id": 44760134, "author": "kwl", "author_id": 2846791, "author_profile": "https://Stackoverflow.com/users/2846791", "pm_score": 3, "selected": false, "text": "<p>If you're in the <code>Main()</code> method, you can't use <code>await</code>, so you'll have to use <code>Task.WaitAny()</code>:</p>\n\n<pre><code>var task = Task.Factory.StartNew(Console.ReadLine);\nvar result = Task.WaitAny(new Task[] { task }, TimeSpan.FromSeconds(5)) == 0\n ? task.Result : string.Empty;\n</code></pre>\n\n<p>However, C# 7.1 introduces the possiblity to create an async <code>Main()</code> method, so it's better to use the <code>Task.WhenAny()</code> version whenever you have that option:</p>\n\n<pre><code>var task = Task.Factory.StartNew(Console.ReadLine);\nvar completedTask = await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(5)));\nvar result = object.ReferenceEquals(task, completedTask) ? task.Result : string.Empty;\n</code></pre>\n" }, { "answer_id": 46226327, "author": "Nicholas Petersen", "author_id": 264031, "author_profile": "https://Stackoverflow.com/users/264031", "pm_score": 2, "selected": false, "text": "<p>As if there weren't already enough answers here :0), the following encapsulates into a static method @kwl's solution above (the first one). </p>\n\n<pre><code> public static string ConsoleReadLineWithTimeout(TimeSpan timeout)\n {\n Task&lt;string&gt; task = Task.Factory.StartNew(Console.ReadLine);\n\n string result = Task.WaitAny(new Task[] { task }, timeout) == 0\n ? task.Result \n : string.Empty;\n return result;\n }\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code> static void Main()\n {\n Console.WriteLine(\"howdy\");\n string result = ConsoleReadLineWithTimeout(TimeSpan.FromSeconds(8.5));\n Console.WriteLine(\"bye\");\n }\n</code></pre>\n" }, { "answer_id": 55320462, "author": "Sergio Cabral", "author_id": 1396511, "author_profile": "https://Stackoverflow.com/users/1396511", "pm_score": 2, "selected": false, "text": "<p><em>My code is based entirely on the friend's answer @JSQuareD</em></p>\n\n<p>But I needed to use <code>Stopwatch</code> to timer because when I finished the program with <code>Console.ReadKey()</code> it was still waiting for <code>Console.ReadLine()</code> and it generated unexpected behavior.</p>\n\n<p><strong>It WORKED PERFECTLY for me. Maintains the original Console.ReadLine ()</strong></p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(\"What is the answer? (5 secs.)\");\n try\n {\n var answer = ConsoleReadLine.ReadLine(5000);\n Console.WriteLine(\"Answer is: {0}\", answer);\n }\n catch\n {\n Console.WriteLine(\"No answer\");\n }\n Console.ReadKey();\n }\n}\n\nclass ConsoleReadLine\n{\n private static string inputLast;\n private static Thread inputThread = new Thread(inputThreadAction) { IsBackground = true };\n private static AutoResetEvent inputGet = new AutoResetEvent(false);\n private static AutoResetEvent inputGot = new AutoResetEvent(false);\n\n static ConsoleReadLine()\n {\n inputThread.Start();\n }\n\n private static void inputThreadAction()\n {\n while (true)\n {\n inputGet.WaitOne();\n inputLast = Console.ReadLine();\n inputGot.Set();\n }\n }\n\n // omit the parameter to read a line without a timeout\n public static string ReadLine(int timeout = Timeout.Infinite)\n {\n if (timeout == Timeout.Infinite)\n {\n return Console.ReadLine();\n }\n else\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n\n while (stopwatch.ElapsedMilliseconds &lt; timeout &amp;&amp; !Console.KeyAvailable) ;\n\n if (Console.KeyAvailable)\n {\n inputGet.Set();\n inputGot.WaitOne();\n return inputLast;\n }\n else\n {\n throw new TimeoutException(\"User did not provide input within the timelimit.\");\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 66821954, "author": "scott", "author_id": 1769757, "author_profile": "https://Stackoverflow.com/users/1769757", "pm_score": 1, "selected": false, "text": "<p>I've got a solution to this using the Windows API that has some benefits over many of the solutions here:</p>\n<ul>\n<li>Uses Console.ReadLine to retrieve the input, so you get all of the niceties associated with that (input history, etc)</li>\n<li>Forces the Console.ReadLine call to complete after the timeout, so you don't accumulate a new thread for every call that times out.</li>\n<li>Doesn't abort a thread unsafely.</li>\n<li>Doesn't have issues with focus like the input faking approach does.</li>\n</ul>\n<p>The two main downsides:</p>\n<ul>\n<li>Only works on Windows.</li>\n<li>It's pretty complicated.</li>\n</ul>\n<p>The basic idea is that the Windows API has a function to cancel outstanding I/O requests: <a href=\"https://learn.microsoft.com/en-us/windows/win32/fileio/cancelioex-func\" rel=\"nofollow noreferrer\">CancelIoEx</a>. When you use it to cancel operations on STDIN, Console.ReadLine throws an OperationCanceledException.</p>\n<p>So here's how you do it:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ConsoleHelper\n{\n public static class ConsoleHelper\n {\n public static string ReadLine(TimeSpan timeout)\n {\n return ReadLine(Task.Delay(timeout));\n }\n\n public static string ReadLine(Task cancel_trigger)\n {\n var status = new Status();\n\n var cancel_task = Task.Run(async () =&gt;\n {\n await cancel_trigger;\n\n status.Mutex.WaitOne();\n bool io_done = status.IODone;\n if (!io_done)\n status.CancellationStarted = true;\n status.Mutex.ReleaseMutex();\n\n while (!status.IODone)\n {\n var success = CancelStdIn(out int error_code);\n\n if (!success &amp;&amp; error_code != 0x490) // 0x490 is what happens when you call cancel and there is not a pending I/O request\n throw new Exception($&quot;Canceling IO operation on StdIn failed with error {error_code} ({error_code:x})&quot;);\n }\n });\n\n ReadLineWithStatus(out string input, out bool read_canceled);\n \n if (!read_canceled)\n {\n status.Mutex.WaitOne();\n bool must_wait = status.CancellationStarted;\n status.IODone = true;\n status.Mutex.ReleaseMutex();\n\n if (must_wait)\n cancel_task.Wait();\n\n return input;\n }\n else // read_canceled == true\n {\n status.Mutex.WaitOne();\n bool cancel_started = status.CancellationStarted;\n status.IODone = true;\n status.Mutex.ReleaseMutex();\n\n if (!cancel_started)\n throw new Exception(&quot;Received cancelation not triggered by this method.&quot;);\n else\n cancel_task.Wait();\n\n return null;\n }\n }\n\n private const int STD_INPUT_HANDLE = -10;\n\n [DllImport(&quot;kernel32.dll&quot;, SetLastError = true)]\n private static extern IntPtr GetStdHandle(int nStdHandle);\n\n [DllImport(&quot;kernel32.dll&quot;, SetLastError = true)]\n private static extern bool CancelIoEx(IntPtr handle, IntPtr lpOverlapped);\n\n\n private static bool CancelStdIn(out int error_code)\n {\n var handle = GetStdHandle(STD_INPUT_HANDLE);\n bool success = CancelIoEx(handle, IntPtr.Zero);\n\n if (success)\n {\n error_code = 0;\n return true;\n }\n else\n {\n var rc = Marshal.GetLastWin32Error();\n error_code = rc;\n return false;\n }\n }\n\n private class Status\n {\n public Mutex Mutex = new Mutex(false);\n public volatile bool IODone;\n public volatile bool CancellationStarted;\n }\n\n private static void ReadLineWithStatus(out string result, out bool operation_canceled)\n {\n try\n {\n result = Console.ReadLine();\n operation_canceled = false;\n }\n catch (OperationCanceledException)\n {\n result = null;\n operation_canceled = true;\n }\n }\n }\n}\n\n</code></pre>\n<p>Avoid the temptation to simplify this, getting the threading right is pretty tricky. You need to handle all of these cases:</p>\n<ul>\n<li>Cancel is triggered and <code>CancelStdIn</code> is called before <code>Console.ReadLine</code> starts (this is why you need the loop in the <code>cancel_trigger</code>).</li>\n<li>Console.ReadLine returns before cancel is triggered (possibly long before).</li>\n<li>Console.ReadLine returns after the cancel is triggered but before <code>CancelStdIn</code> is called.</li>\n<li>Console.ReadLine throws an exception due to the call to <code>CancelStdIn</code> in response to the cancel trigger.</li>\n</ul>\n<p>Credits:\nGot the idea for CancelIoEx from a <a href=\"https://stackoverflow.com/a/58475263/1769757\">SO answer</a> who got it from <a href=\"https://www.meziantou.net/cancelling-console-read.htm\" rel=\"nofollow noreferrer\">Gérald Barré's blog</a>. However those solutions have subtle concurrency bugs.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
I have a console app in which I want to give the user *x* seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response. What is the most straightforward way of approaching this?
I'm surprised to learn that after 5 years, all of the answers still suffer from one or more of the following problems: * A function other than ReadLine is used, causing loss of functionality. (Delete/backspace/up-key for previous input). * Function behaves badly when invoked multiple times (spawning multiple threads, many hanging ReadLine's, or otherwise unexpected behavior). * Function relies on a busy-wait. Which is a horrible waste since the wait is expected to run anywhere from a number of seconds up to the timeout, which might be multiple minutes. A busy-wait which runs for such an ammount of time is a horrible suck of resources, which is especially bad in a multithreading scenario. If the busy-wait is modified with a sleep this has a negative effect on responsiveness, although I admit that this is probably not a huge problem. I believe my solution will solve the original problem without suffering from any of the above problems: ``` class Reader { private static Thread inputThread; private static AutoResetEvent getInput, gotInput; private static string input; static Reader() { getInput = new AutoResetEvent(false); gotInput = new AutoResetEvent(false); inputThread = new Thread(reader); inputThread.IsBackground = true; inputThread.Start(); } private static void reader() { while (true) { getInput.WaitOne(); input = Console.ReadLine(); gotInput.Set(); } } // omit the parameter to read a line without a timeout public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) return input; else throw new TimeoutException("User did not provide input within the timelimit."); } } ``` Calling is, of course, very easy: ``` try { Console.WriteLine("Please enter your name within the next 5 seconds."); string name = Reader.ReadLine(5000); Console.WriteLine("Hello, {0}!", name); } catch (TimeoutException) { Console.WriteLine("Sorry, you waited too long."); } ``` Alternatively, you can use the `TryXX(out)` convention, as shmueli suggested: ``` public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) line = input; else line = null; return success; } ``` Which is called as follows: ``` Console.WriteLine("Please enter your name within the next 5 seconds."); string name; bool success = Reader.TryReadLine(out name, 5000); if (!success) Console.WriteLine("Sorry, you waited too long."); else Console.WriteLine("Hello, {0}!", name); ``` In both cases, you cannot mix calls to `Reader` with normal `Console.ReadLine` calls: if the `Reader` times out, there will be a hanging `ReadLine` call. Instead, if you want to have a normal (non-timed) `ReadLine` call, just use the `Reader` and omit the timeout, so that it defaults to an infinite timeout. So how about those problems of the other solutions I mentioned? * As you can see, ReadLine is used, avoiding the first problem. * The function behaves properly when invoked multiple times. Regardless of whether a timeout occurs or not, only one background thread will ever be running and only at most one call to ReadLine will ever be active. Calling the function will always result in the latest input, or in a timeout, and the user won't have to hit enter more than once to submit his input. * And, obviously, the function does not rely on a busy-wait. Instead it uses proper multithreading techniques to prevent wasting resources. The only problem that I foresee with this solution is that it is not thread-safe. However, multiple threads can't really ask the user for input at the same time, so synchronization should be happening before making a call to `Reader.ReadLine` anyway.
57,625
<p>This one will take some explaining. What I've done is create a specific custom message queue in SQL Server 2005. I have a table with messages that contain timestamps for both acknowledgment and completion. The stored procedure that callers execute to obtain the next message in their queue also acknowledges the message. So far so good. Well, if the system is experiencing a massive amount of transactions (thousands per minute), isn't it possible for a message to be acknowledged by another execution of the stored procedure while another is prepared to so itself? Let me help by showing my SQL code in the stored proc:</p> <pre><code>--Grab the next message id declare @MessageId uniqueidentifier set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands); --Acknowledge the message update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId --Select the entire message ... ... </code></pre> <p>In the above code, couldn't another stored procedure running at the same time obtain the same id and attempt to acknowledge it at the same time? Could I (or should I) implement some sort of locking to prevent another stored proc from acknowledging messages that another stored proc is querying? </p> <p>Wow, did any of this even make sense? It's a bit difficult to put to words...</p>
[ { "answer_id": 57637, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": -1, "selected": false, "text": "<p>You want to wrap your code in a transaction, then SQL server will handle locking the appropriate rows or tables.</p>\n\n<pre><code>begin transaction\n\n--Grab the next message id\ndeclare @MessageId uniqueidentifier\nset @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands);\n\n--Acknowledge the message\nupdate ActionMessages\nset AcknowledgedTime = getdate()\nwhere ActionMessageId = @MessageId\n\ncommit transaction\n\n--Select the entire message\n...\n</code></pre>\n" }, { "answer_id": 57649, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 0, "selected": false, "text": "<p>Should you really be processing things one-by-one? Shouldn't you just have SQL Server acknowledge all unacknowledged messages with todays date and return them? (all also in a transaction of course)</p>\n" }, { "answer_id": 57653, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": false, "text": "<p>@Kilhoffer:</p>\n\n<p>The whole SQL batch is parsed before execution, so SQL knows that you're going to do an update to the table as well as select from it.</p>\n\n<p>Edit: Also, SQL will not necessarily lock the whole table - it could just lock the necessary rows. See <a href=\"http://msdn.microsoft.com/en-us/library/aa213039(SQL.80).aspx\" rel=\"nofollow noreferrer\">here</a> for an overview of locking in SQL server.</p>\n" }, { "answer_id": 57664, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 4, "selected": true, "text": "<p>Something like this</p>\n\n<pre><code>--Grab the next message id\nbegin tran\ndeclare @MessageId uniqueidentifier\nselect top 1 @MessageId = ActionMessageId from UnacknowledgedDemands with(holdlock, updlock);\n\n--Acknowledge the message\nupdate ActionMessages\nset AcknowledgedTime = getdate()\nwhere ActionMessageId = @MessageId\n\n-- some error checking\ncommit tran\n\n--Select the entire message\n...\n...\n</code></pre>\n" }, { "answer_id": 57671, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 0, "selected": false, "text": "<p>Read more about SQL Server Select Locking <a href=\"http://www.quest-pipelines.com/newsletter-v3/0202_F.htm\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/library/aa213039(SQL.80).aspx\" rel=\"nofollow noreferrer\">here</a>. SQL Server has the ability to invoke a table lock on a select. Nothing will happen to the table during the transaction. When the transaction completes, any inserts or updates will then resolve themselves.</p>\n" }, { "answer_id": 126970, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "<p>Instead of explicit locking, which is often escalated by SQL Server to higher granularity than desired, why not just try this approach:</p>\n\n<pre><code>declare @MessageId uniqueidentifier\nselect top 1 @MessageId = ActionMessageId from UnacknowledgedDemands\n\nupdate ActionMessages\n set AcknowledgedTime = getdate()\n where ActionMessageId = @MessageId and AcknowledgedTime is null\n\nif @@rowcount &gt; 0\n /* acknoweldge succeeded */\nelse\n /* concurrent query acknowledged message before us,\n go back and try another one */\n</code></pre>\n\n<p>The less you lock - the higher concurrency you have.</p>\n" }, { "answer_id": 6746381, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 2, "selected": false, "text": "<p>This seems like the kind of situation where <a href=\"http://msdn.microsoft.com/en-us/library/ms177564.aspx\" rel=\"nofollow\"><code>OUTPUT</code></a> can be useful:</p>\n\n<pre><code>-- Acknowledge and grab the next message\ndeclare @message table (\n -- ...your `ActionMessages` columns here...\n)\nupdate ActionMessages\nset AcknowledgedTime = getdate()\noutput INSERTED.* into @message\nwhere ActionMessageId in (select top(1) ActionMessageId from UnacknowledgedDemands)\n and AcknowledgedTime is null\n\n-- Use the data in @message, which will have zero or one rows assuming\n-- `ActionMessageId` uniquely identifies a row (strongly implied in your question)\n...\n...\n</code></pre>\n\n<p>There, we update and grab the row in the same operation, which tells the query optimizer <strong>exactly</strong> what we're doing, allowing it to choose the most granular lock it can and maintain it for the briefest possible time. (Although the column prefix is <code>INSERTED</code>, <code>OUTPUT</code> is like triggers, expressed in terms of the <code>UPDATE</code> being like deleting the row and inserting the new one.)</p>\n\n<p>I'd need more information about your <code>ActionMessages</code> and <code>UnacknowledgedDemands</code> tables (views/TVFs/whatever), not to mention a greater knowledge of SQL Server's automatic locking, to say whether that <code>and AcknowledgedTime is null</code> clause is necessary. It's there to defend against a race condition between the sub-select and the update. I'm certain it wouldn't be necessary if we were selecting from <code>ActionMessages</code> itself (e.g., <code>where AcknowledgedTime is null</code> with a <code>top</code> on the <code>update</code>, instead of the sub-select on <code>UnacknowledgedDemands</code>). I expect even if it's unnecessary, it's harmless.</p>\n\n<p>Note that <code>OUTPUT</code> is in SQL Server 2005 and above. That's what you said you were using, but if compatibility with geriatric SQL Server 2000 installs were required, you'd want to go another way.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
This one will take some explaining. What I've done is create a specific custom message queue in SQL Server 2005. I have a table with messages that contain timestamps for both acknowledgment and completion. The stored procedure that callers execute to obtain the next message in their queue also acknowledges the message. So far so good. Well, if the system is experiencing a massive amount of transactions (thousands per minute), isn't it possible for a message to be acknowledged by another execution of the stored procedure while another is prepared to so itself? Let me help by showing my SQL code in the stored proc: ``` --Grab the next message id declare @MessageId uniqueidentifier set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands); --Acknowledge the message update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId --Select the entire message ... ... ``` In the above code, couldn't another stored procedure running at the same time obtain the same id and attempt to acknowledge it at the same time? Could I (or should I) implement some sort of locking to prevent another stored proc from acknowledging messages that another stored proc is querying? Wow, did any of this even make sense? It's a bit difficult to put to words...
Something like this ``` --Grab the next message id begin tran declare @MessageId uniqueidentifier select top 1 @MessageId = ActionMessageId from UnacknowledgedDemands with(holdlock, updlock); --Acknowledge the message update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId -- some error checking commit tran --Select the entire message ... ... ```
57,652
<p>Scenario:</p> <ol> <li>The user has two monitors.</li> <li>Their browser is open on the secondary monitor.</li> <li>They click a link in the browser which calls window.open() with a specific top and left window offset.</li> <li>The popup window always opens on their primary monitor.</li> </ol> <p>Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)?</p>
[ { "answer_id": 57680, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": -1, "selected": false, "text": "<p>as long as you know the x and y position that falls on the particular monitor you can do:</p>\n\n<pre><code>var x = 0;\nvar y = 0;\nvar myWin = window.open(''+self.location,'mywin','left='+x+',top='+y+',width=500,height=500,toolbar=1,resizable=0');\n</code></pre>\n" }, { "answer_id": 57684, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 5, "selected": false, "text": "<p>You can't specify the monitor, but you can specify the position of the popup window as being relative to the where the click caused the window to popup. </p>\n\n<p>Use the getMouseXY() function to get values to pass as the left and top args to the window.open() method. (the left and top args only work with V3 and up browsers).</p>\n\n<p>window.open docs:\n<a href=\"http://www.javascripter.net/faq/openinga.htm\" rel=\"noreferrer\">http://www.javascripter.net/faq/openinga.htm</a></p>\n\n<pre><code>function getMouseXY( e ) {\n if ( event.clientX ) { // Grab the x-y pos.s if browser is IE.\n CurrentLeft = event.clientX + document.body.scrollLeft;\n CurrentTop = event.clientY + document.body.scrollTop;\n }\n else { // Grab the x-y pos.s if browser isn't IE.\n CurrentLeft = e.pageX;\n CurrentTop = e.pageY;\n } \n if ( CurrentLeft &lt; 0 ) { CurrentLeft = 0; };\n if ( CurrentTop &lt; 0 ) { CurrentTop = 0; }; \n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 993724, "author": "WhyNotHugo", "author_id": 107510, "author_profile": "https://Stackoverflow.com/users/107510", "pm_score": 0, "selected": false, "text": "<p><em>If</em> you know the resolution of each monitor, you could estimate this.\nA bad idea for a public website, but might be useful if you know (for some odd reason) that this scenario will always apply.</p>\n\n<p>Relative position to the mouse (as said above) or to the original browser window could also be useful, Though you'd have to suppose the user uses the browser maximized (which is not necessarily true).</p>\n" }, { "answer_id": 4682246, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 4, "selected": false, "text": "<p>Here is something I shamelessly reverse engineered from the Facebook oauth API. Tested on a primary and secondary monitor in Firefox/Chrome.</p>\n\n<pre><code>function popup_params(width, height) {\n var a = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft;\n var i = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop;\n var g = typeof window.outerWidth!='undefined' ? window.outerWidth : document.documentElement.clientWidth;\n var f = typeof window.outerHeight != 'undefined' ? window.outerHeight: (document.documentElement.clientHeight - 22);\n var h = (a &lt; 0) ? window.screen.width + a : a;\n var left = parseInt(h + ((g - width) / 2), 10);\n var top = parseInt(i + ((f-height) / 2.5), 10);\n return 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',scrollbars=1';\n} \n\nwindow.open(url, \"window name\", \"location=1,toolbar=0,\" + popup_params(modal_width, modal_height));\n</code></pre>\n" }, { "answer_id": 4786990, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 3, "selected": false, "text": "<pre><code>// Pops a window relative to the current window position\nfunction popup(url, winName, xOffset, yOffset) {\n var x = (window.screenX || window.screenLeft || 0) + (xOffset || 0);\n var y = (window.screenY || window.screenTop || 0) + (yOffset || 0);\n return window.open(url, winName, 'top=' +y+ ',left=' +x))\n}\n</code></pre>\n\n<p>Call it like the following and it will open on top of the current window</p>\n\n<pre><code>popup('http://www.google.com', 'my-win');\n</code></pre>\n\n<p>Or make it slightly offset</p>\n\n<pre><code>popup('http://www.google.com', 'my-win', 30, 30);\n</code></pre>\n\n<p>The point is that window.screenX/screenLeft give you the position in relationship to the entire desktop, not just the monitor.</p>\n\n<p>window.screen.left would be the ideal candidate to give you the information you need. The problem is that it's set when the page is loaded and the user could move the window to the other monitor.</p>\n\n<p><strong>More research</strong> </p>\n\n<p>A final solution to this problem (beyond just offsetting from the current window position) requires knowing the dimensions of the screen that the window is in. Since the screen object doesn't update as the user moves a window around, we need to craft our own way of detecting the current screen resolution. Here's what I came up with</p>\n\n<pre><code>/**\n * Finds the screen element for the monitor that the browser window is currently in.\n * This is required because window.screen is the screen that the page was originally\n * loaded in. This method works even after the window has been moved across monitors.\n * \n * @param {function} cb The function that will be called (asynchronously) once the screen \n * object has been discovered. It will be passed a single argument, the screen object.\n */\nfunction getScreenProps (cb) {\n if (!window.frames.testiframe) {\n var iframeEl = document.createElement('iframe');\n iframeEl.name = 'testiframe';\n iframeEl.src = \"about:blank\";\n iframeEl.id = 'iframe-test'\n document.body.appendChild(iframeEl);\n }\n\n // Callback when the iframe finishes reloading, it will have the \n // correct screen object\n document.getElementById('iframe-test').onload = function() {\n cb( window.frames.testiframe.screen );\n delete document.getElementById('iframe-test').onload;\n };\n // reload the iframe so that the screen object is reloaded\n window.frames.testiframe.location.reload();\n};\n</code></pre>\n\n<p>So if you wanted to always open the window at the top left of whatever monitor the window is in, you could use the following:</p>\n\n<pre><code>function openAtTopLeftOfSameMonitor(url, winName) {\n getScreenProps(function(scr){\n window.open(url, winName, 'top=0,left=' + scr.left);\n })\n}\n</code></pre>\n" }, { "answer_id": 14290277, "author": "Suvi Vignarajah", "author_id": 1417588, "author_profile": "https://Stackoverflow.com/users/1417588", "pm_score": 0, "selected": false, "text": "<p>I ran into this issue recently and finally found a way to position the pop up window on the screen that it's triggered from. Take a look at my solution on my github page here: <a href=\"https://github.com/svignara/windowPopUp\" rel=\"nofollow\">https://github.com/svignara/windowPopUp</a></p>\n\n<p>The trick is in using the <code>window.screen</code> object, which returns <code>availWidth</code>, <code>availHeight</code>, <code>availLeft</code> and <code>availTop</code> values (as well as <code>width</code> and <code>height</code>). For a complete list of the variables in the object and what these variables represent look at <a href=\"https://developer.mozilla.org/en-US/docs/DOM/window.screen\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/DOM/window.screen</a>.</p>\n\n<p>Essentially, my solution finds the values of the <code>window.screen</code> whenever the trigger for the popup is clicked. This way I know for sure which monitor screen it's being clicked from. The <code>availLeft</code> value takes care of the rest. Here's how:</p>\n\n<blockquote>\n <blockquote>\n <p>Basically if the first available pixel from the left (<code>availLeft</code>) is negative, that's telling us there is a monitor to the left of the \"main\" monitor. Likewise, if the first available pixel from left is greater than 0, this means one of 2 things:</p>\n \n <ol>\n <li>The monitor is to the right of the \"main\" monitor, OR</li>\n <li>There is some \"junk\" on the left side of the screen (possibly the application dock or windows start menu)</li>\n </ol>\n </blockquote>\n</blockquote>\n\n<p>In either case you want the offset of your popup to start from after the available pixel from the left.</p>\n\n<pre><code>offsetLeft = availableLeft + ( (availableWidth - modalWidth) / 2 )\n</code></pre>\n" }, { "answer_id": 26549914, "author": "user11153", "author_id": 1795426, "author_profile": "https://Stackoverflow.com/users/1795426", "pm_score": 2, "selected": false, "text": "<p>Open centered window on current monitor, working also with Chrome:</p>\n\n<pre><code>function popupOnCurrentScreenCenter(url, title, w, h) {\n var dualScreenLeft = typeof window.screenLeft !== \"undefined\" ? window.screenLeft : screen.left;\n var dualScreenTop = typeof window.screenTop !== \"undefined\" ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth :\n document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight :\n document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (w / 2)) + dualScreenLeft;\n var top = ((height / 2) - (h / 2)) + dualScreenTop;\n var newWindow =\n window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);\n\n // Puts focus on the newWindow\n if (window.focus) {\n newWindow.focus();\n }\n}\n</code></pre>\n" }, { "answer_id": 52249716, "author": "hirano", "author_id": 5113353, "author_profile": "https://Stackoverflow.com/users/5113353", "pm_score": 0, "selected": false, "text": "<p>Only user11153's version works with Chrome and dual screen. Here is its TypeScript version.</p>\n\n<pre><code>popupOnCurrentScreenCenter(url: string, title: string, w: number, h: number): Window|null {\n var dualScreenLeft = typeof window.screenLeft !== \"undefined\" ? window.screenLeft : (&lt;any&gt;screen).left;\n var dualScreenTop = typeof window.screenTop !== \"undefined\" ? window.screenTop : (&lt;any&gt;screen).top;\n\n var width = window.innerWidth ? window.innerWidth :\n document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight :\n document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (w / 2)) + dualScreenLeft;\n var top = ((height / 2) - (h / 2)) + dualScreenTop;\n var newWindow =\n window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);\n\n // Puts focus on the newWindow\n if (window.focus &amp;&amp; newWindow) {\n newWindow.focus();\n }\n return newWindow;\n}\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436/" ]
Scenario: 1. The user has two monitors. 2. Their browser is open on the secondary monitor. 3. They click a link in the browser which calls window.open() with a specific top and left window offset. 4. The popup window always opens on their primary monitor. Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)?
You can't specify the monitor, but you can specify the position of the popup window as being relative to the where the click caused the window to popup. Use the getMouseXY() function to get values to pass as the left and top args to the window.open() method. (the left and top args only work with V3 and up browsers). window.open docs: <http://www.javascripter.net/faq/openinga.htm> ``` function getMouseXY( e ) { if ( event.clientX ) { // Grab the x-y pos.s if browser is IE. CurrentLeft = event.clientX + document.body.scrollLeft; CurrentTop = event.clientY + document.body.scrollTop; } else { // Grab the x-y pos.s if browser isn't IE. CurrentLeft = e.pageX; CurrentTop = e.pageY; } if ( CurrentLeft < 0 ) { CurrentLeft = 0; }; if ( CurrentTop < 0 ) { CurrentTop = 0; }; return true; } ```
57,665
<p>Is there an easy way to return data to web service clients in JSON using Rails?</p>
[ { "answer_id": 57706, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON\" rel=\"nofollow noreferrer\">http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON</a></p>\n" }, { "answer_id": 57761, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>Rails monkeypatches most things you'd care about to have a <code>#to_json</code> method.</p>\n\n<p>Off the top of my head, you can do it for hashes, arrays, and ActiveRecord objects, which should cover about 95% of the use cases you might want. If you have your own custom objects, it's trivial to write your own <code>to_json</code> method for them, which can just jam data into a hash and then return the jsonized hash.</p>\n" }, { "answer_id": 70660, "author": "Evgeny", "author_id": 11414, "author_profile": "https://Stackoverflow.com/users/11414", "pm_score": 1, "selected": false, "text": "<p>There is a plugin that does just this,\n<a href=\"http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/\" rel=\"nofollow noreferrer\">http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/</a></p>\n\n<p>And from what I understand this functionality is already in Rails. But go see that blog post, there are code examples and explanations.</p>\n" }, { "answer_id": 245486, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 5, "selected": true, "text": "<p>Rails resource gives a RESTful interface for your model. Let's see.</p>\n\n<h1>Model</h1>\n\n<pre><code>class Contact &lt; ActiveRecord::Base\n ...\nend\n</code></pre>\n\n<h1>Routes</h1>\n\n<pre><code>map.resources :contacts\n</code></pre>\n\n<h1>Controller</h1>\n\n<pre><code>class ContactsController &lt; ApplicationController\n ...\n def show\n @contact = Contact.find(params[:id]\n\n respond_to do |format|\n format.html \n format.xml {render :xml =&gt; @contact}\n format.js {render :json =&gt; @contact.json}\n end\n end\n ...\nend\n</code></pre>\n\n<p>So this gives you an API interfaces without the need to define special methods to get the type of respond required</p>\n\n<p>Eg.</p>\n\n<pre><code>/contacts/1 # Responds with regular html page\n\n/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes\n\n/contacts/1.js # Responds with json output of Contact.find(1) and its attributes\n</code></pre>\n" }, { "answer_id": 353525, "author": "Nils", "author_id": 44232, "author_profile": "https://Stackoverflow.com/users/44232", "pm_score": 0, "selected": false, "text": "<p>ActiveRecord also provides methods to interact with JSON. To create JSON out of an AR object, just call object.to_json. TO create an AR object out of JSON you should be able to create a new AR object and then call object.from_json.. as far as I understood, but this did not work for me.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5988/" ]
Is there an easy way to return data to web service clients in JSON using Rails?
Rails resource gives a RESTful interface for your model. Let's see. Model ===== ``` class Contact < ActiveRecord::Base ... end ``` Routes ====== ``` map.resources :contacts ``` Controller ========== ``` class ContactsController < ApplicationController ... def show @contact = Contact.find(params[:id] respond_to do |format| format.html format.xml {render :xml => @contact} format.js {render :json => @contact.json} end end ... end ``` So this gives you an API interfaces without the need to define special methods to get the type of respond required Eg. ``` /contacts/1 # Responds with regular html page /contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes /contacts/1.js # Responds with json output of Contact.find(1) and its attributes ```
57,679
<p>I'm trying to determine, based on the result of this call, if it was successful. The <code>successFunction</code> doesn't get called, so I'm assuming it was not. How do I know what went wrong?</p> <pre><code>xmlRequest = $.post("/url/file/", { 'id' : object.id }, successFunction, 'json'); </code></pre> <p>Do I use the xmlRequest object?</p>
[ { "answer_id": 57688, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 3, "selected": false, "text": "<p>You could use the $.ajaxComplete() and/or $.ajaxError() methods to attach function to those events. I would also recommend using the Firefox browser with the Firebug pluging, you can get a lot of information about the requests and responses.</p>\n" }, { "answer_id": 57997, "author": "defrex", "author_id": 6007, "author_profile": "https://Stackoverflow.com/users/6007", "pm_score": 4, "selected": true, "text": "<p>You can use:</p>\n\n<pre><code>$.ajax({\n url:\"/url/file/\",\n dataType:\"json\"\n data:{ 'id' : object.id }\n error:function(request){alert(request.statusText)}\n success:successFunction\n})\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
I'm trying to determine, based on the result of this call, if it was successful. The `successFunction` doesn't get called, so I'm assuming it was not. How do I know what went wrong? ``` xmlRequest = $.post("/url/file/", { 'id' : object.id }, successFunction, 'json'); ``` Do I use the xmlRequest object?
You can use: ``` $.ajax({ url:"/url/file/", dataType:"json" data:{ 'id' : object.id } error:function(request){alert(request.statusText)} success:successFunction }) ```
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
[ { "answer_id": 57745, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "<p>You could find an answer here -- <a href=\"https://stackoverflow.com/questions/53224/getting-international-characters-from-a-web-page#53246\">Getting international characters from a web page?</a></p>\n\n<p><strong>EDIT</strong>: It seems like <code>BeautifulSoup</code> doesn't convert entities written in hexadecimal form. It can be fixed:</p>\n\n<pre><code>import copy, re\nfrom BeautifulSoup import BeautifulSoup\n\nhexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)\n# replace hexadecimal character reference by decimal one\nhexentityMassage += [(re.compile('&amp;#x([^;]+);'), \n lambda m: '&amp;#%d;' % int(m.group(1), 16))]\n\ndef convert(html):\n return BeautifulSoup(html,\n convertEntities=BeautifulSoup.HTML_ENTITIES,\n markupMassage=hexentityMassage).contents[0].string\n\nhtml = '&lt;html&gt;&amp;#x01ce;&amp;#462;&lt;/html&gt;'\nprint repr(convert(html))\n# u'\\u01ce\\u01ce'\n</code></pre>\n\n<p><strong>EDIT</strong>: </p>\n\n<p><a href=\"http://effbot.org/zone/re-sub.htm#unescape-html\" rel=\"nofollow noreferrer\"><code>unescape()</code></a> function mentioned by <a href=\"https://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python/58125#58125\">@dF</a> which uses <code>htmlentitydefs</code> standard module and <code>unichr()</code> might be more appropriate in this case.</p>\n" }, { "answer_id": 57877, "author": "chryss", "author_id": 5169, "author_profile": "https://Stackoverflow.com/users/5169", "pm_score": 4, "selected": false, "text": "<p>Use the builtin <code>unichr</code> -- BeautifulSoup isn't necessary:</p>\n\n<pre><code>&gt;&gt;&gt; entity = '&amp;#x01ce'\n&gt;&gt;&gt; unichr(int(entity[3:],16))\nu'\\u01ce'\n</code></pre>\n" }, { "answer_id": 58125, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 6, "selected": false, "text": "<p>Python has the <a href=\"https://docs.python.org/2/library/htmllib.html#module-htmlentitydefs\" rel=\"noreferrer\">htmlentitydefs</a> module, but this doesn't include a function to unescape HTML entities.</p>\n\n<p>Python developer Fredrik Lundh (author of elementtree, among other things) has such a function <a href=\"http://effbot.org/zone/re-sub.htm#unescape-html\" rel=\"noreferrer\">on his website</a>, which works with decimal, hex and named entities:</p>\n\n<pre><code>import re, htmlentitydefs\n\n##\n# Removes HTML or XML character references and entities from a text string.\n#\n# @param text The HTML (or XML) source text.\n# @return The plain text, as a Unicode string, if necessary.\n\ndef unescape(text):\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&amp;#\":\n # character reference\n try:\n if text[:3] == \"&amp;#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n pass\n else:\n # named entity\n try:\n text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return re.sub(\"&amp;#?\\w+;\", fixup, text)\n</code></pre>\n" }, { "answer_id": 573629, "author": "karlcow", "author_id": 62262, "author_profile": "https://Stackoverflow.com/users/62262", "pm_score": 3, "selected": false, "text": "<p>This is a function which should help you to get it right and convert entities back to utf-8 characters.</p>\n\n<pre><code>def unescape(text):\n \"\"\"Removes HTML or XML character references \n and entities from a text string.\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n from Fredrik Lundh\n 2008-01-03: input only unicode characters string.\n http://effbot.org/zone/re-sub.htm#unescape-html\n \"\"\"\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&amp;#\":\n # character reference\n try:\n if text[:3] == \"&amp;#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n print \"Value Error\"\n pass\n else:\n # named entity\n # reescape the reserved characters.\n try:\n if text[1:-1] == \"amp\":\n text = \"&amp;amp;amp;\"\n elif text[1:-1] == \"gt\":\n text = \"&amp;amp;gt;\"\n elif text[1:-1] == \"lt\":\n text = \"&amp;amp;lt;\"\n else:\n print text[1:-1]\n text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])\n except KeyError:\n print \"keyerror\"\n pass\n return text # leave as is\n return re.sub(\"&amp;#?\\w+;\", fixup, text)\n</code></pre>\n" }, { "answer_id": 4438857, "author": "rogerhu", "author_id": 541895, "author_profile": "https://Stackoverflow.com/users/541895", "pm_score": 2, "selected": false, "text": "<p>Not sure why the Stack Overflow thread does not include the ';' in the search/replace (i.e. lambda m: '&amp;#%d*<em>;</em>*') If you don't, BeautifulSoup can barf because the adjacent character can be interpreted as part of the HTML code (i.e. &amp;#39B for &amp;#39Blackout). </p>\n\n<p>This worked better for me:</p>\n\n<pre><code>import re\nfrom BeautifulSoup import BeautifulSoup\n\nhtml_string='&lt;a href=\"/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL\"title=\"\"&gt;&amp;#x27;Blackout in a can; on some shelves despite ban&lt;/a&gt;'\n\nhexentityMassage = [(re.compile('&amp;#x([^;]+);'), \nlambda m: '&amp;#%d;' % int(m.group(1), 16))]\n\nsoup = BeautifulSoup(html_string, \nconvertEntities=BeautifulSoup.HTML_ENTITIES, \nmarkupMassage=hexentityMassage)\n</code></pre>\n\n<ol>\n<li>The int(m.group(1), 16) converts the number (specified in base-16) format back to an integer. </li>\n<li>m.group(0) returns the entire match, m.group(1) returns the regexp capturing group </li>\n<li>Basically using markupMessage is the same as:<br>\nhtml_string = re.sub('&amp;#x([^;]+);', lambda m: '&amp;#%d;' % int(m.group(1), 16), html_string) </li>\n</ol>\n" }, { "answer_id": 9216990, "author": "pragmar", "author_id": 1196188, "author_profile": "https://Stackoverflow.com/users/1196188", "pm_score": 4, "selected": false, "text": "<p>An alternative, if you have lxml:</p>\n\n<pre><code>&gt;&gt;&gt; import lxml.html\n&gt;&gt;&gt; lxml.html.fromstring('&amp;#x01ce').text\nu'\\u01ce'\n</code></pre>\n" }, { "answer_id": 12614706, "author": "Vladislav", "author_id": 1164730, "author_profile": "https://Stackoverflow.com/users/1164730", "pm_score": 7, "selected": true, "text": "<p>The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does:</p>\n\n<p>up to Python 3.4:\n</p>\n\n<pre><code>import HTMLParser\nh = HTMLParser.HTMLParser()\nh.unescape('&amp;copy; 2010') # u'\\xa9 2010'\nh.unescape('&amp;#169; 2010') # u'\\xa9 2010'\n</code></pre>\n\n<p>Python 3.4+:</p>\n\n<pre><code>import html\nhtml.unescape('&amp;copy; 2010') # u'\\xa9 2010'\nhtml.unescape('&amp;#169; 2010') # u'\\xa9 2010'\n</code></pre>\n" }, { "answer_id": 27424874, "author": "Markus Amalthea Magnuson", "author_id": 11403, "author_profile": "https://Stackoverflow.com/users/11403", "pm_score": 4, "selected": false, "text": "<p>If you are on Python 3.4 or newer, you can simply use the <a href=\"https://docs.python.org/3.4/library/html.html#html.unescape\" rel=\"noreferrer\"><code>html.unescape</code></a>:</p>\n\n<pre><code>import html\n\ns = html.unescape(s)\n</code></pre>\n" }, { "answer_id": 33486253, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Another solution is the builtin library xml.sax.saxutils (both for html and xml). However, it will convert only &amp;gt, &amp;amp and &amp;lt.</p>\n\n<pre><code>from xml.sax.saxutils import unescape\n\nescaped_text = unescape(text_to_escape)\n</code></pre>\n" }, { "answer_id": 34463462, "author": "Victor", "author_id": 2086547, "author_profile": "https://Stackoverflow.com/users/2086547", "pm_score": 0, "selected": false, "text": "<p>Here is the Python 3 version of <a href=\"https://stackoverflow.com/a/58125/2086547\">dF's answer</a>:</p>\n\n<pre><code>import re\nimport html.entities\n\ndef unescape(text):\n \"\"\"\n Removes HTML or XML character references and entities from a text string.\n\n :param text: The HTML (or XML) source text.\n :return: The plain text, as a Unicode string, if necessary.\n \"\"\"\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&amp;#\":\n # character reference\n try:\n if text[:3] == \"&amp;#x\":\n return chr(int(text[3:-1], 16))\n else:\n return chr(int(text[2:-1]))\n except ValueError:\n pass\n else:\n # named entity\n try:\n text = chr(html.entities.name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return re.sub(\"&amp;#?\\w+;\", fixup, text)\n</code></pre>\n\n<p>The main changes concern <code>htmlentitydefs</code> that is now <code>html.entities</code> and <code>unichr</code> that is now <code>chr</code>. See this <a href=\"http://docs.pythonsprints.com/python3_porting/py-porting.html#reorganization\" rel=\"nofollow noreferrer\">Python 3 porting guide</a>.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type? For example: I get back: ``` &#x01ce; ``` which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'`
The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does: up to Python 3.4: ``` import HTMLParser h = HTMLParser.HTMLParser() h.unescape('&copy; 2010') # u'\xa9 2010' h.unescape('&#169; 2010') # u'\xa9 2010' ``` Python 3.4+: ``` import html html.unescape('&copy; 2010') # u'\xa9 2010' html.unescape('&#169; 2010') # u'\xa9 2010' ```
57,731
<p>I have a table in SQL Server that I inherited from a legacy system thats still in production that is structured according to the code below. I created a SP to query the table as described in the code below the table create statement. My issue is that, sporadically, calls from .NET to this SP both through the Enterprise Library 4 and through a DataReader object are slow. The SP is called through a loop structure in the Data Layer that specifies the params that go into the SP for the purpose of populating user objects. It's also important to mention that a slow call will not take place on every pass the loop structure. It will generally be fine for most of a day or more, and then start presenting which makes it extremely hard to debug.</p> <p>The table in question contains about 5 million rows. The calls that are slow, for instance, will take as long as 10 seconds, while the calls that are fast will take 0 to 10 milliseconds on average. I checked for locking/blocking transactions during the slow calls, none were found. I created some custom performance counters in the data layer to monitor call times. Essentially, when performance is bad, it's really bad for that one call. But when it's good, it's really good. I've been able to recreate the issue on a few different developer machines, but not on our development and staging database servers, which of course have beefier hardware. Generally, the problem is resolved through restarting the SQL server services, but not always. There are indexes on the table for the fields I'm querying, but there are more indexes than I would like. However, I'm hesitant to remove any or toy with the indexes due to the impact it may have on the legacy system. Has anyone experienced a problem like this before, or do you have a recommendation to remedy it? </p> <pre><code>CREATE TABLE [dbo].[product_performance_quarterly]( [performance_id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [product_id] [int] NULL, [month] [int] NULL, [year] [int] NULL, [performance] [decimal](18, 6) NULL, [gross_or_net] [char](15) NULL, [vehicle_type] [char](30) NULL, [quarterly_or_monthly] [char](1) NULL, [stamp] [datetime] NULL CONSTRAINT [DF_product_performance_quarterly_stamp] DEFAULT (getdate()), [eA_loaded] [nchar](10) NULL, [vehicle_type_id] [int] NULL, [yearmonth] [char](6) NULL, [gross_or_net_id] [tinyint] NULL, CONSTRAINT [PK_product_performance_quarterly_4_19_04] PRIMARY KEY CLUSTERED ( [performance_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[product_performance_quarterly] WITH NOCHECK ADD CONSTRAINT [FK_product_performance_quarterlyProduct_id] FOREIGN KEY([product_id]) REFERENCES [dbo].[products] ([product_id]) GO ALTER TABLE [dbo].[product_performance_quarterly] CHECK CONSTRAINT [FK_product_performance_quarterlyProduct_id] CREATE PROCEDURE [eA.Analytics.Calculations].[USP.GetCalculationData] ( @PRODUCTID INT, --products.product_id @BEGINYEAR INT, --year to begin retrieving performance data @BEGINMONTH INT, --month to begin retrieving performance data @ENDYEAR INT, --year to end retrieving performance data @ENDMONTH INT, --month to end retrieving performance data @QUARTERLYORMONTHLY VARCHAR(1), --do you want quarterly or monthly data? @VEHICLETYPEID INT, --what product vehicle type are you looking for? @GROSSORNETID INT --are your looking gross of fees data or net of fees data? ) AS BEGIN SET NOCOUNT ON DECLARE @STARTDATE VARCHAR(6), @ENDDATE VARCHAR(6), @vBEGINMONTH VARCHAR(2), @vENDMONTH VARCHAR(2) IF LEN(@BEGINMONTH) = 1 SET @vBEGINMONTH = '0' + CAST(@BEGINMONTH AS VARCHAR(1)) ELSE SET @vBEGINMONTH = @BEGINMONTH IF LEN(@ENDMONTH) = 1 SET @vENDMONTH = '0' + CAST(@ENDMONTH AS VARCHAR(1)) ELSE SET @vENDMONTH = @ENDMONTH SET @STARTDATE = CAST(@BEGINYEAR AS VARCHAR(4)) + @vBEGINMONTH SET @ENDDATE = CAST(@ENDYEAR AS VARCHAR(4)) + @vENDMONTH --because null values for gross_or_net_id and vehicle_type_id are represented in --multiple ways (true null, empty string, or 0) in the PPQ table, need to account for all possible variations if --a -1 is passed in from the .NET code, which represents an enumerated value that --indicates that the value(s) should be true null. IF @VEHICLETYPEID = '-1' AND @GROSSORNETID = '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '') AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '') ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID &lt;&gt; '-1' AND @GROSSORNETID &lt;&gt; '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID ) AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID) ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID = '-1' AND @GROSSORNETID &lt;&gt; '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '') AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID) ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID &lt;&gt; '-1' AND @GROSSORNETID = '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID) AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '') ORDER BY PPQ.YEARMONTH ASC END </code></pre>
[ { "answer_id": 57741, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 0, "selected": false, "text": "<p>Sounds like another query is running in the background that has locked the table and your innocent query is simply waiting for it to finish</p>\n" }, { "answer_id": 57749, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>I have seen this happen with indexes that were out of date. It could also be a parameter sniffing problem, where a different query plan is being used for different parameters that come in to the stored procedure.</p>\n\n<p>You should capture the parameters of the slow calls and see if they are the same ones each time it runs slow.</p>\n\n<p>You might also try running the tuning wizard and see if it recommends any indexes.</p>\n\n<p>You don't want to worry about having too many indexes until you can prove that updates and inserts are happening too slow (time needed to modify the index plus locking/contention), or you are running out of disk space for them.</p>\n" }, { "answer_id": 57753, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 0, "selected": false, "text": "<p>A strange, edge case but I encountered it recently. </p>\n\n<p>If the queries run longer in the application than they do when run from within Management Studio, you may want to check to make sure that Arithabort is set off. The connection parameters used by Management Studio are different from the ones used by .NET.</p>\n" }, { "answer_id": 224507, "author": "SqlRyan", "author_id": 8114, "author_profile": "https://Stackoverflow.com/users/8114", "pm_score": 0, "selected": false, "text": "<p>It seems like it's one of two things - either the parameters on the slow calls are different in some way than on the fast calls, and they're not able to use the indexes as well, or there's some type of locking contention that's holding you up. You say you've checked for blocking locks while a particular process is hung, and saw none - that would suggest that it's the first one. However - are you sure that your staging server (that you can't reproduce this error on) and the development servers (that you can reproduce it on) have the same database configuration? For example, maybe \"READ COMMITTED SNAPSHOT\" is enabled in production, but not in development, which would cause read contention issues to disappear in production.</p>\n\n<p>If it's a difference in parameters, I'd suggest using SQL Profiler to watch the transactions and capture a few - some slow ones and some faster ones, and then, in a Management Studio window, replace the variables in that SP above with the parameter values and then get an execution plan by pressing \"Control-L\". This will tell you exactly how SQL Server expects to process your query, and you can compare the execution plan for different parameter combination to see if there's a difference with one set, and work from there to optimize it.</p>\n\n<p>Good luck!</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a table in SQL Server that I inherited from a legacy system thats still in production that is structured according to the code below. I created a SP to query the table as described in the code below the table create statement. My issue is that, sporadically, calls from .NET to this SP both through the Enterprise Library 4 and through a DataReader object are slow. The SP is called through a loop structure in the Data Layer that specifies the params that go into the SP for the purpose of populating user objects. It's also important to mention that a slow call will not take place on every pass the loop structure. It will generally be fine for most of a day or more, and then start presenting which makes it extremely hard to debug. The table in question contains about 5 million rows. The calls that are slow, for instance, will take as long as 10 seconds, while the calls that are fast will take 0 to 10 milliseconds on average. I checked for locking/blocking transactions during the slow calls, none were found. I created some custom performance counters in the data layer to monitor call times. Essentially, when performance is bad, it's really bad for that one call. But when it's good, it's really good. I've been able to recreate the issue on a few different developer machines, but not on our development and staging database servers, which of course have beefier hardware. Generally, the problem is resolved through restarting the SQL server services, but not always. There are indexes on the table for the fields I'm querying, but there are more indexes than I would like. However, I'm hesitant to remove any or toy with the indexes due to the impact it may have on the legacy system. Has anyone experienced a problem like this before, or do you have a recommendation to remedy it? ``` CREATE TABLE [dbo].[product_performance_quarterly]( [performance_id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [product_id] [int] NULL, [month] [int] NULL, [year] [int] NULL, [performance] [decimal](18, 6) NULL, [gross_or_net] [char](15) NULL, [vehicle_type] [char](30) NULL, [quarterly_or_monthly] [char](1) NULL, [stamp] [datetime] NULL CONSTRAINT [DF_product_performance_quarterly_stamp] DEFAULT (getdate()), [eA_loaded] [nchar](10) NULL, [vehicle_type_id] [int] NULL, [yearmonth] [char](6) NULL, [gross_or_net_id] [tinyint] NULL, CONSTRAINT [PK_product_performance_quarterly_4_19_04] PRIMARY KEY CLUSTERED ( [performance_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[product_performance_quarterly] WITH NOCHECK ADD CONSTRAINT [FK_product_performance_quarterlyProduct_id] FOREIGN KEY([product_id]) REFERENCES [dbo].[products] ([product_id]) GO ALTER TABLE [dbo].[product_performance_quarterly] CHECK CONSTRAINT [FK_product_performance_quarterlyProduct_id] CREATE PROCEDURE [eA.Analytics.Calculations].[USP.GetCalculationData] ( @PRODUCTID INT, --products.product_id @BEGINYEAR INT, --year to begin retrieving performance data @BEGINMONTH INT, --month to begin retrieving performance data @ENDYEAR INT, --year to end retrieving performance data @ENDMONTH INT, --month to end retrieving performance data @QUARTERLYORMONTHLY VARCHAR(1), --do you want quarterly or monthly data? @VEHICLETYPEID INT, --what product vehicle type are you looking for? @GROSSORNETID INT --are your looking gross of fees data or net of fees data? ) AS BEGIN SET NOCOUNT ON DECLARE @STARTDATE VARCHAR(6), @ENDDATE VARCHAR(6), @vBEGINMONTH VARCHAR(2), @vENDMONTH VARCHAR(2) IF LEN(@BEGINMONTH) = 1 SET @vBEGINMONTH = '0' + CAST(@BEGINMONTH AS VARCHAR(1)) ELSE SET @vBEGINMONTH = @BEGINMONTH IF LEN(@ENDMONTH) = 1 SET @vENDMONTH = '0' + CAST(@ENDMONTH AS VARCHAR(1)) ELSE SET @vENDMONTH = @ENDMONTH SET @STARTDATE = CAST(@BEGINYEAR AS VARCHAR(4)) + @vBEGINMONTH SET @ENDDATE = CAST(@ENDYEAR AS VARCHAR(4)) + @vENDMONTH --because null values for gross_or_net_id and vehicle_type_id are represented in --multiple ways (true null, empty string, or 0) in the PPQ table, need to account for all possible variations if --a -1 is passed in from the .NET code, which represents an enumerated value that --indicates that the value(s) should be true null. IF @VEHICLETYPEID = '-1' AND @GROSSORNETID = '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '') AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '') ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID <> '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID ) AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID) ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID = '-1' AND @GROSSORNETID <> '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '') AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID) ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID = '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID) AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '') ORDER BY PPQ.YEARMONTH ASC END ```
I have seen this happen with indexes that were out of date. It could also be a parameter sniffing problem, where a different query plan is being used for different parameters that come in to the stored procedure. You should capture the parameters of the slow calls and see if they are the same ones each time it runs slow. You might also try running the tuning wizard and see if it recommends any indexes. You don't want to worry about having too many indexes until you can prove that updates and inserts are happening too slow (time needed to modify the index plus locking/contention), or you are running out of disk space for them.
57,751
<p>I want to find any text in a file that matches a regexp of the form <em>t</em><code>[A-Z]</code><em>u</em> (i.e., a match <em>t</em> followed by a capital letter and another match <em>u</em>, and transform the matched text so that the capital letter is lowercase. For example, for the regexp <code>x[A-Z]y</code></p> <pre><code>xAy </code></pre> <p>becomes</p> <pre><code>xay </code></pre> <p>and</p> <pre><code>xZy </code></pre> <p>becomes</p> <pre><code>xzy </code></pre> <p>Emacs' <code>query-replace</code> function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use?</p> <p><strong>UPDATE</strong></p> <p>@Marcel Levy has it: <code>\,</code> in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is</p> <pre><code>M-x replace-regexp &lt;RET&gt; x\([A-Z]\)z &lt;RET&gt; x\,(downcase \1)z </code></pre>
[ { "answer_id": 57794, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 5, "selected": true, "text": "<p>It looks like <a href=\"http://steve-yegge.blogspot.com/\" rel=\"noreferrer\">Steve Yegge</a> actually already posted the answer to this a few years back: <a href=\"http://steve-yegge.blogspot.com/2006/06/shiny-and-new-emacs-22.html\" rel=\"noreferrer\">\"Shiny and New: Emacs 22.\"</a> Scroll down to \"Changing Case in Replacement Strings\" and you'll see his example code using the <code>replace-regexp</code> function.</p>\n\n<p>The general answer is that you use \"\\,\" to call any lisp expression as part of the replacement string, as in <code>\\,(capitalize \\1)</code>. Reading the help text, it looks like it's only in interactive mode, but that seems like the one place where this would be most necessary.</p>\n" }, { "answer_id": 67756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>An alternative to qrr in this case is recording a macro and replaying it. (isearch-forward-regexp, select the character, downcase-region.) I find on the fly macros easier, since you get immediate feedback if your regexp is wrong.</p>\n" }, { "answer_id": 69754, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 0, "selected": false, "text": "<p>I'd do this with a macro as well, but only because executing code from within a replacement string for a regular expression is very unintuitive to me. If you're writing a batch script or something that needs to go very fast, \\, is certainly the way to go.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
I want to find any text in a file that matches a regexp of the form *t*`[A-Z]`*u* (i.e., a match *t* followed by a capital letter and another match *u*, and transform the matched text so that the capital letter is lowercase. For example, for the regexp `x[A-Z]y` ``` xAy ``` becomes ``` xay ``` and ``` xZy ``` becomes ``` xzy ``` Emacs' `query-replace` function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use? **UPDATE** @Marcel Levy has it: `\,` in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is ``` M-x replace-regexp <RET> x\([A-Z]\)z <RET> x\,(downcase \1)z ```
It looks like [Steve Yegge](http://steve-yegge.blogspot.com/) actually already posted the answer to this a few years back: ["Shiny and New: Emacs 22."](http://steve-yegge.blogspot.com/2006/06/shiny-and-new-emacs-22.html) Scroll down to "Changing Case in Replacement Strings" and you'll see his example code using the `replace-regexp` function. The general answer is that you use "\," to call any lisp expression as part of the replacement string, as in `\,(capitalize \1)`. Reading the help text, it looks like it's only in interactive mode, but that seems like the one place where this would be most necessary.
57,766
<p>I am getting the below error and call stack at the same time everyday after several hours of application use. Can anyone shed some light on what is happening?</p> <pre><code>System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress. at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing) at System.Drawing.BufferedGraphicsContext.Dispose() at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle) at System.Windows.Forms.Control.WmPaint(Message&amp; m) at System.Windows.Forms.Control.WndProc(Message&amp; m) at System.Windows.Forms.ScrollableControl.WndProc(Message&amp; m) at System.Windows.Forms.ToolStrip.WndProc(Message&amp; m) at System.Windows.Forms.MenuStrip.WndProc(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) </code></pre>
[ { "answer_id": 57820, "author": "qbeuek", "author_id": 5348, "author_profile": "https://Stackoverflow.com/users/5348", "pm_score": 0, "selected": false, "text": "<p>a shot in the dark - are you painting from multiple threads? If you are doing painting related work, do it on the GUI thread or synchronize your code carefully.</p>\n" }, { "answer_id": 58132, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 3, "selected": true, "text": "<p>There is a very long MSDN forums discussion of this error <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=200483&amp;SiteID=1\" rel=\"nofollow noreferrer\">here</a>. In most cases the error is apparently associated with either:</p>\n\n<ol>\n<li>An underlying OutOfMemory problem, which manifests as the BufferedGraphicsContext exception, possibly due to a framework bug.</li>\n<li>A GDI object leak (creating GDI objects and not disposing them).</li>\n</ol>\n\n<p>I recall seeing this error myself a year or so ago, and it was definitely associated with a memory problem that made our app fill up all available VM after a long run, so #1 agrees with what I have observed.</p>\n" }, { "answer_id": 21282876, "author": "TheQaa", "author_id": 2028568, "author_profile": "https://Stackoverflow.com/users/2028568", "pm_score": 0, "selected": false, "text": "<p>I know this question is old, but i had the same problem and found out, that it only showed up, when i used multiple controls which implemented manual double buffering.</p>\n\n<p>For me, i found the problem at this point:</p>\n\n<pre><code>BufferedGraphicsContext _BackbufferContext = BufferedGraphicsManager.Current;\n</code></pre>\n\n<p>So all my controls used the <em>Current</em> context, which i assume is always the same.\nAfter i replaced it by</p>\n\n<pre><code>BufferedGraphicsContext _BackbufferContext = new BufferedGraphicsContext();\n</code></pre>\n\n<p>everything works like wanted.</p>\n\n<p>I hope this is a little bit helpfull.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
I am getting the below error and call stack at the same time everyday after several hours of application use. Can anyone shed some light on what is happening? ``` System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress. at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing) at System.Drawing.BufferedGraphicsContext.Dispose() at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ToolStrip.WndProc(Message& m) at System.Windows.Forms.MenuStrip.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ```
There is a very long MSDN forums discussion of this error [here](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=200483&SiteID=1). In most cases the error is apparently associated with either: 1. An underlying OutOfMemory problem, which manifests as the BufferedGraphicsContext exception, possibly due to a framework bug. 2. A GDI object leak (creating GDI objects and not disposing them). I recall seeing this error myself a year or so ago, and it was definitely associated with a memory problem that made our app fill up all available VM after a long run, so #1 agrees with what I have observed.
57,791
<p>I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.</p> <p>Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads. </p> <p>The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?</p>
[ { "answer_id": 57798, "author": "Tom Kidd", "author_id": 2577, "author_profile": "https://Stackoverflow.com/users/2577", "pm_score": 2, "selected": false, "text": "<p><strong>EDIT:</strong> My \"workaround\" below is complete overkill, based on my lack of understanding. Go with Shog9's answer above.</p>\n\n<p>OK so while I was writing the question, I came up with a workaround which will work for now.</p>\n\n<p>I put a global JavaScript variable in act as a boolean on whether or not the icon is being hovered over. Then, I attach events to the image's onmouseover and onmouseout events and write functions that will set this value. Finally, I just code in the function that handles onbeforeunload that will check this value before setting event.returnValue.</p>\n\n<p>Probably not a flawless workaround but it will work for now.</p>\n" }, { "answer_id": 57827, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "<p>Let me guess: the help \"icon\" is actually a link with a <code>javascript:</code> url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.</p>\n\n<pre><code>&lt;!-- clicking this link will do nothing. No onbeforeunload handler triggered. \nNothing. \nAnd you could put something in before the return false bit...\n...and the onunload handler would still not get called... --&gt;\n&lt;a href=\"http://www.google.com/\" onclick=\"return false;\"&gt;blah1&lt;/a&gt;\n&lt;!-- this should also do nothing, but IE will trigger the onbeforeunload \nhandler --&gt;\n&lt;a href=\"javascript:void(0)\"&gt;blah2&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 221423, "author": "Kevin Dark", "author_id": 26151, "author_profile": "https://Stackoverflow.com/users/26151", "pm_score": -1, "selected": false, "text": "<p>I have a method that is a bit clunky but it will work in most instances.</p>\n\n<p>Create a \"Holding\" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script language=\"Javascript\" type=\"text/javascript\"&gt;\n window.onbeforeunload = exitCheck;\n window.onunload = onCloseDoSomething;\n\n function onCloseDoSomething()\n {\n alert(\"This is executed at unload\");\n }\n\n function exitCheck(evt)\n {\n return \"Any string here.\"}\n &lt;/script&gt;\n &lt;/head&gt;\n\n &lt;frameset rows=\"100%\"&gt;\n &lt;FRAME name=\"main\" src=\"http://www.yourDomain.com/yourActualPage.aspx\"&gt;\n &lt;/frameset&gt;\n&lt;body&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.</p>\n\n<p>If the outer frame is refreshed or actually closed the events will fire.</p>\n\n<p>Like i said, not full-proof but will get round the firing of the event on every click or postback.</p>\n" }, { "answer_id": 415369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>on the internet you will find many people suggesting you use something like</p>\n\n<p>window.onbeforeunload = null</p>\n\n<p>but this does not work for me in IE6. reading up in the MSDN docs for the event object i found a reference to the event.cancelBubble property, which i thought was the solution. but thanks to Orso who pointed out that setting \"event.cancelBubble=true\" is useless, the way to get rid of the confirm prompt is to exclude the return statement altogether, i chose to use a boolean variable as a flag to decide whether to return something or not. in the example below i add the javascript code programattically in the code behind:</p>\n\n<pre><code>Page.ClientScript.RegisterStartupScript(typeof(String), \"ConfirmClose\", @\" &lt;script&gt; window.onbeforeunload = confirmExit; function confirmExit() { if(postback == false) return \"\"Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons.\"\"; } &lt;/script&gt;\");\n</code></pre>\n\n<p>then the help button contains the following aspx markup:</p>\n\n<pre><code>OnClientClick=\"postback=true;return true;\n</code></pre>\n\n<p>this sets the 'postback' variable to true, which gets picked up in the confirmExit() function, having the effect of cancelling the event. </p>\n\n<p>hope you find this useful. it is tested and works in IE6 and FF 1.5.0.2.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great. Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads. The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?
Let me guess: the help "icon" is actually a link with a `javascript:` url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved. ``` <!-- clicking this link will do nothing. No onbeforeunload handler triggered. Nothing. And you could put something in before the return false bit... ...and the onunload handler would still not get called... --> <a href="http://www.google.com/" onclick="return false;">blah1</a> <!-- this should also do nothing, but IE will trigger the onbeforeunload handler --> <a href="javascript:void(0)">blah2</a> ```
57,803
<p>How do you convert decimal values to their hexadecimal equivalent in JavaScript?</p>
[ { "answer_id": 57805, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 13, "selected": true, "text": "<p>Convert a number to a hexadecimal string with:</p>\n<pre><code>hexString = yourNumber.toString(16);\n</code></pre>\n<p>And reverse the process with:</p>\n<pre><code>yourNumber = parseInt(hexString, 16);\n</code></pre>\n" }, { "answer_id": 57807, "author": "Luke Smith", "author_id": 5556, "author_profile": "https://Stackoverflow.com/users/5556", "pm_score": 7, "selected": false, "text": "<p>The code below will convert the decimal value d to hexadecimal. It also allows you to add padding to the hexadecimal result. So 0 will become 00 by default.</p>\n\n<pre><code>function decimalToHex(d, padding) {\n var hex = Number(d).toString(16);\n padding = typeof (padding) === \"undefined\" || padding === null ? padding = 2 : padding;\n\n while (hex.length &lt; padding) {\n hex = \"0\" + hex;\n }\n\n return hex;\n}\n</code></pre>\n" }, { "answer_id": 57814, "author": "Danny Wilson", "author_id": 5364, "author_profile": "https://Stackoverflow.com/users/5364", "pm_score": 4, "selected": false, "text": "<pre><code>var number = 3200;\nvar hexString = number.toString(16);\n</code></pre>\n\n<p>The 16 is the radix and there are 16 values in a hexadecimal number :-)</p>\n" }, { "answer_id": 697841, "author": "Tod", "author_id": 16679, "author_profile": "https://Stackoverflow.com/users/16679", "pm_score": 7, "selected": false, "text": "<p>If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function <code>toString(16)</code> will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function decimalToHexString(number)\r\n{\r\n if (number &lt; 0)\r\n {\r\n number = 0xFFFFFFFF + number + 1;\r\n }\r\n\r\n return number.toString(16).toUpperCase();\r\n}\r\n\r\nconsole.log(decimalToHexString(27));\r\nconsole.log(decimalToHexString(48.6));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 930315, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>function dec2hex(i)\n{\n var result = \"0000\";\n if (i &gt;= 0 &amp;&amp; i &lt;= 15) { result = \"000\" + i.toString(16); }\n else if (i &gt;= 16 &amp;&amp; i &lt;= 255) { result = \"00\" + i.toString(16); }\n else if (i &gt;= 256 &amp;&amp; i &lt;= 4095) { result = \"0\" + i.toString(16); }\n else if (i &gt;= 4096 &amp;&amp; i &lt;= 65535) { result = i.toString(16); }\n return result\n}\n</code></pre>\n" }, { "answer_id": 1446578, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>AFAIK <a href=\"https://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript/57807#57807\">comment 57807</a> is wrong and should be something like:\n<strong>var hex = Number(d).toString(16);</strong>\ninstead of\n<strong>var hex = parseInt(d, 16);</strong></p>\n\n<pre><code>function decimalToHex(d, padding) {\n var hex = Number(d).toString(16);\n padding = typeof (padding) === \"undefined\" || padding === null ? padding = 2 : padding;\n\n while (hex.length &lt; padding) {\n hex = \"0\" + hex;\n }\n\n return hex;\n}\n</code></pre>\n" }, { "answer_id": 3689638, "author": "mystifeid", "author_id": 444910, "author_profile": "https://Stackoverflow.com/users/444910", "pm_score": 4, "selected": false, "text": "<p>Without the loop:</p>\n\n<pre><code>function decimalToHex(d) {\n var hex = Number(d).toString(16);\n hex = \"000000\".substr(0, 6 - hex.length) + hex;\n return hex;\n}\n\n// Or \"#000000\".substr(0, 7 - hex.length) + hex;\n// Or whatever\n// *Thanks to MSDN\n</code></pre>\n\n<p>Also isn't it better not to use loop tests that have to be evaluated?</p>\n\n<p>For example, instead of:</p>\n\n<pre><code>for (var i = 0; i &lt; hex.length; i++){}\n</code></pre>\n\n<p>have</p>\n\n<pre><code>for (var i = 0, var j = hex.length; i &lt; j; i++){}\n</code></pre>\n" }, { "answer_id": 6680530, "author": "Fabio Ferrari", "author_id": 87648, "author_profile": "https://Stackoverflow.com/users/87648", "pm_score": 5, "selected": false, "text": "<p>With padding:</p>\n\n<pre><code>function dec2hex(i) {\n return (i+0x10000).toString(16).substr(-4).toUpperCase();\n}\n</code></pre>\n" }, { "answer_id": 9034019, "author": "Adamarla", "author_id": 1167359, "author_profile": "https://Stackoverflow.com/users/1167359", "pm_score": 4, "selected": false, "text": "<p>Constrained/padded to a set number of characters:</p>\n\n<pre><code>function decimalToHex(decimal, chars) {\n return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();\n}\n</code></pre>\n" }, { "answer_id": 11012314, "author": "korona", "author_id": 25731, "author_profile": "https://Stackoverflow.com/users/25731", "pm_score": 3, "selected": false, "text": "<p>If you want to convert a number to a hexadecimal representation of an RGBA color value, I've found this to be the most useful combination of several tips from here:</p>\n\n<pre><code>function toHexString(n) {\n if(n &lt; 0) {\n n = 0xFFFFFFFF + n + 1;\n }\n return \"0x\" + (\"00000000\" + n.toString(16).toUpperCase()).substr(-8);\n}\n</code></pre>\n" }, { "answer_id": 12995874, "author": "Eliarh", "author_id": 1762728, "author_profile": "https://Stackoverflow.com/users/1762728", "pm_score": 3, "selected": false, "text": "<p>And if the number is negative?</p>\n\n<p>Here is my version.</p>\n\n<pre><code>function hexdec (hex_string) {\n hex_string=((hex_string.charAt(1)!='X' &amp;&amp; hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);\n hex_string=(hex_string.charAt(2)&lt;8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);\n return parseInt(hex_string, 10);\n}\n</code></pre>\n" }, { "answer_id": 13240395, "author": "Baznr", "author_id": 1801365, "author_profile": "https://Stackoverflow.com/users/1801365", "pm_score": 6, "selected": false, "text": "<pre><code>function toHex(d) {\n return (\"0\"+(Number(d).toString(16))).slice(-2).toUpperCase()\n}\n</code></pre>\n" }, { "answer_id": 13397771, "author": "Keith Mashinter", "author_id": 1826649, "author_profile": "https://Stackoverflow.com/users/1826649", "pm_score": 4, "selected": false, "text": "<p>Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the <code>#</code> elsewhere for HTML/CSS):</p>\n\n<pre><code>function rgb2hex(r,g,b) {\n if (g !== undefined)\n return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);\n else\n return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);\n}\n</code></pre>\n" }, { "answer_id": 13865336, "author": "almaz", "author_id": 460477, "author_profile": "https://Stackoverflow.com/users/460477", "pm_score": 3, "selected": false, "text": "<p>I'm doing conversion to hex string in a pretty large loop, so I tried several techniques in order to find the fastest one. My requirements were to have a fixed-length string as a result, and encode negative values properly (-1 => ff..f).</p>\n\n<p>Simple <code>.toString(16)</code> didn't work for me since I needed negative values to be properly encoded. The following code is the quickest I've tested so far on 1-2 byte values (note that <code>symbols</code> defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):</p>\n\n<pre><code>var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction getHexRepresentation(num, symbols) {\n var result = '';\n while (symbols--) {\n result = hex[num &amp; 0xF] + result;\n num &gt;&gt;= 4;\n }\n return result;\n}\n</code></pre>\n\n<p>It performs faster than <code>.toString(16)</code> on 1-2 byte numbers and slower on larger numbers (when <code>symbols</code> >= 6), but still should outperform methods that encode negative values properly.</p>\n" }, { "answer_id": 17023332, "author": "R D", "author_id": 2448914, "author_profile": "https://Stackoverflow.com/users/2448914", "pm_score": 3, "selected": false, "text": "<p>As the accepted answer states, the easiest way to convert from decimal to hexadecimal is <code>var hex = dec.toString(16)</code>. However, you may prefer to add a string conversion, as it ensures that string representations like <code>\"12\".toString(16)</code> work correctly.</p>\n\n<pre><code>// Avoids a hard-to-track-down bug by returning `c` instead of `12`\n(+\"12\").toString(16);\n</code></pre>\n\n<p>To reverse the process you may also use the solution below, as it is even shorter.</p>\n\n<pre><code>var dec = +(\"0x\" + hex);\n</code></pre>\n\n<p>It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See <a href=\"http://jsperf.com/hex-to-dec\" rel=\"nofollow noreferrer\">http://jsperf.com/hex-to-dec</a>.</p>\n" }, { "answer_id": 17106974, "author": "Alberto", "author_id": 413020, "author_profile": "https://Stackoverflow.com/users/413020", "pm_score": 6, "selected": false, "text": "<p>For completeness, if you want the <a href=\"http://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"noreferrer\" title=\"Two&#39;s complement [Wikipedia]\">two's-complement</a> hexadecimal representation of a negative number, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#%3E%3E%3E_%28Zero-fill_right_shift%29\" rel=\"noreferrer\" title=\"Zero-fill right shift [MDN]\">zero-fill-right shift <code>&gt;&gt;&gt;</code> operator</a>. For instance:</p>\n\n\n\n<pre><code>&gt; (-1).toString(16)\n\"-1\"\n\n&gt; ((-2)&gt;&gt;&gt;0).toString(16)\n\"fffffffe\"\n</code></pre>\n\n<p>There is however one limitation: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Summary\" rel=\"noreferrer\" title=\"Bitwise Operators [MDN]\">JavaScript bitwise operators treat their operands as a sequence of 32 bits</a>, that is, you get the 32-bits two's complement.</p>\n" }, { "answer_id": 20483568, "author": "realkstrawn93", "author_id": 1118706, "author_profile": "https://Stackoverflow.com/users/1118706", "pm_score": 2, "selected": false, "text": "<p>To sum it all up;</p>\n\n<pre><code>function toHex(i, pad) {\n\n if (typeof(pad) === 'undefined' || pad === null) {\n pad = 2;\n } \n\n var strToParse = i.toString(16);\n\n while (strToParse.length &lt; pad) {\n strToParse = \"0\" + strToParse;\n }\n\n var finalVal = parseInt(strToParse, 16);\n\n if ( finalVal &lt; 0 ) {\n finalVal = 0xFFFFFFFF + finalVal + 1;\n }\n\n return finalVal;\n}\n</code></pre>\n\n<p>However, if you don't need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren't negative should suffice.</p>\n" }, { "answer_id": 26784300, "author": "Mark Manning", "author_id": 928121, "author_profile": "https://Stackoverflow.com/users/928121", "pm_score": 5, "selected": false, "text": "<p>The accepted answer did not take into account single digit returned hexadecimal codes. This is easily adjusted by:</p>\n\n<pre><code>function numHex(s)\n{\n var a = s.toString(16);\n if ((a.length % 2) &gt; 0) {\n a = \"0\" + a;\n }\n return a;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>function strHex(s)\n{\n var a = \"\";\n for (var i=0; i&lt;s.length; i++) {\n a = a + numHex(s.charCodeAt(i));\n }\n\n return a;\n}\n</code></pre>\n\n<p>I believe the above answers have been posted numerous times by others in one form or another. I wrap these in a toHex() function like so:</p>\n\n<pre><code>function toHex(s)\n{\n var re = new RegExp(/^\\s*(\\+|-)?((\\d+(\\.\\d+)?)|(\\.\\d+))\\s*$/);\n\n if (re.test(s)) {\n return '#' + strHex( s.toString());\n }\n else {\n return 'A' + strHex(s);\n }\n}\n</code></pre>\n\n<p>Note that the numeric regular expression came from <a href=\"http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html\" rel=\"noreferrer\">10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency</a>.</p>\n\n<p>Update: After testing this thing several times I found an error (double quotes in the RegExp), so I fixed that. HOWEVER! After quite a bit of testing and having read the post by almaz - I realized I could not get negative numbers to work. </p>\n\n<p>Further - I did some reading up on this and since all JavaScript numbers are stored as 64 bit words no matter what - I tried modifying the numHex code to get the 64 bit word. But it turns out you can not do that. If you put \"3.14159265\" AS A NUMBER into a variable - all you will be able to get is the \"3\", because the fractional portion is only accessible by multiplying the number by ten(IE:10.0) repeatedly. Or to put that another way - the <em>hexadecimal</em> value of 0xF causes the <em>floating point</em> value to be translated into an <em>integer</em> before it is ANDed which removes everything behind the period. Rather than taking the value as a whole (i.e.: 3.14159265) and ANDing the <em>floating point</em> value against the 0xF value.</p>\n\n<p>So the best thing to do, in this case, is to convert the 3.14159265 into a <em>string</em> and then just convert the string. Because of the above, it also makes it easy to convert negative numbers because the minus sign just becomes 0x26 on the front of the value.</p>\n\n<p>So what I did was on determining that the variable contains a number - just convert it to a string and convert the string. This means to everyone that on the server side you will need to unhex the incoming string and then to determine the incoming information is numeric. You can do that easily by just adding a \"#\" to the front of numbers and \"A\" to the front of a character string coming back. See the toHex() function.</p>\n\n<p>Have fun!</p>\n\n<p>After another year and a lot of thinking, I decided that the \"toHex\" function (and I also have a \"fromHex\" function) really needed to be revamped. The whole question was \"How can I do this more efficiently?\" I decided that a to/from hexadecimal function should not care if something is a fractional part but at the same time it should ensure that fractional parts are included in the string.</p>\n\n<p>So then the question became, \"How do you know you are working with a hexadecimal string?\". The answer is simple. Use the standard pre-string information that is already recognized around the world.</p>\n\n<p>In other words - use \"0x\". So now my toHex function looks to see if that is already there and if it is - it just returns the string that was sent to it. Otherwise, it converts the string, number, whatever. Here is the revised toHex function:</p>\n\n<pre><code>/////////////////////////////////////////////////////////////////////////////\n// toHex(). Convert an ASCII string to hexadecimal.\n/////////////////////////////////////////////////////////////////////////////\ntoHex(s)\n{\n if (s.substr(0,2).toLowerCase() == \"0x\") {\n return s;\n }\n\n var l = \"0123456789ABCDEF\";\n var o = \"\";\n\n if (typeof s != \"string\") {\n s = s.toString();\n }\n for (var i=0; i&lt;s.length; i++) {\n var c = s.charCodeAt(i);\n\n o = o + l.substr((c&gt;&gt;4),1) + l.substr((c &amp; 0x0f),1);\n }\n\n return \"0x\" + o;\n}\n</code></pre>\n\n<p>This is a very fast function that takes into account single digits, floating point numbers, and even checks to see if the person is sending a hex value over to be hexed again. It only uses four function calls and only two of those are in the loop. To un-hex the values you use:</p>\n\n<pre><code>/////////////////////////////////////////////////////////////////////////////\n// fromHex(). Convert a hex string to ASCII text.\n/////////////////////////////////////////////////////////////////////////////\nfromHex(s)\n{\n var start = 0;\n var o = \"\";\n\n if (s.substr(0,2).toLowerCase() == \"0x\") {\n start = 2;\n }\n\n if (typeof s != \"string\") {\n s = s.toString();\n }\n for (var i=start; i&lt;s.length; i+=2) {\n var c = s.substr(i, 2);\n\n o = o + String.fromCharCode(parseInt(c, 16));\n }\n\n return o;\n}\n</code></pre>\n\n<p>Like the toHex() function, the fromHex() function first looks for the \"0x\" and then it translates the incoming information into a string if it isn't already a string. I don't know how it wouldn't be a string - but just in case - I check. The function then goes through, grabbing two characters and translating those in to ASCII characters. If you want it to translate Unicode, you will need to change the loop to going by four(4) characters at a time. But then you also need to ensure that the string is NOT divisible by four. If it is - then it is a standard hexadecimal string. (Remember the string has \"0x\" on the front of it.)</p>\n\n<p>A simple test script to show that -3.14159265, when converted to a string, is still -3.14159265.</p>\n\n<pre><code>&lt;?php\n\n echo &lt;&lt;&lt;EOD\n&lt;html&gt;\n &lt;head&gt;&lt;title&gt;Test&lt;/title&gt;\n &lt;script&gt;\n var a = -3.14159265;\n alert( \"A = \" + a );\n var b = a.toString();\n alert( \"B = \" + b );\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;/body&gt;\n&lt;/html&gt;\nEOD;\n\n?&gt;\n</code></pre>\n\n<p>Because of how JavaScript works in respect to the toString() function, all of those problems can be eliminated which before were causing problems. Now all strings and numbers can be converted easily. Further, such things as objects will cause an error to be generated by JavaScript itself. I believe this is about as good as it gets. The only improvement left is for W3C to just include a toHex() and fromHex() function in JavaScript.</p>\n" }, { "answer_id": 33622834, "author": "Hat", "author_id": 2203482, "author_profile": "https://Stackoverflow.com/users/2203482", "pm_score": 4, "selected": false, "text": "<p>For anyone interested, <a href=\"http://jsfiddle.net/t3z4tqy5/\" rel=\"noreferrer\">here's a JSFiddle comparing most of the answers given to this question</a>.</p>\n\n<p>And here's the method I ended up going with:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function decToHex(dec) {\n return (dec + Math.pow(16, 6)).toString(16).substr(-6)\n}\n</code></pre>\n\n<hr>\n\n<p>Also, bear in mind that if you're looking to convert from decimal to hex for use in CSS as a <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/color_value\" rel=\"noreferrer\">color data type</a>, you might instead prefer to extract the RGB values from the decimal and use <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/color_value#rgb()\" rel=\"noreferrer\">rgb()</a>.</p>\n\n<p>For example (<a href=\"http://jsfiddle.net/6wzckyn9/\" rel=\"noreferrer\">JSFiddle</a>):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let c = 4210330 // your color in decimal format\nlet rgb = [(c &amp; 0xff0000) &gt;&gt; 16, (c &amp; 0x00ff00) &gt;&gt; 8, (c &amp; 0x0000ff)]\n\n// Vanilla JS:\ndocument..getElementById('some-element').style.color = 'rgb(' + rgb + ')'\n// jQuery:\n$('#some-element').css('color', 'rgb(' + rgb + ')')\n</code></pre>\n\n<p>This sets <code>#some-element</code>'s CSS <code>color</code> property to <code>rgb(64, 62, 154)</code>.</p>\n" }, { "answer_id": 35251679, "author": "JonLikeSquirrel", "author_id": 5763792, "author_profile": "https://Stackoverflow.com/users/5763792", "pm_score": 2, "selected": false, "text": "<p><strong>How to convert decimal to hexadecimal in JavaScript</strong></p>\n\n<p>I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.</p>\n\n<pre><code>function DecToHex(decimal) { // Data (decimal)\n\n length = -1; // Base string length\n string = ''; // Source 'string'\n\n characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array\n\n do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift\n\n string += characters[decimal &amp; 0xF]; // Mask byte, get that character\n ++length; // Increment to length of string\n\n } while (decimal &gt;&gt;&gt;= 4); // For next character shift right 4 bits, or break on 0\n\n decimal += 'x'; // Convert that 0 into a hex prefix string -&gt; '0x'\n\n do\n decimal += string[length];\n while (length--); // Flip string forwards, with the prefixed '0x'\n\n return (decimal); // return (hexadecimal);\n}\n\n/* Original: */\n\nD = 3678; // Data (decimal)\nC = 0xF; // Check\nA = D; // Accumulate\nB = -1; // Base string length\nS = ''; // Source 'string'\nH = '0x'; // Destination 'string'\n\ndo {\n ++B;\n A&amp; = C;\n\n switch(A) {\n case 0xA: A='A'\n break;\n\n case 0xB: A='B'\n break;\n\n case 0xC: A='C'\n break;\n\n case 0xD: A='D'\n break;\n\n case 0xE: A='E'\n break;\n\n case 0xF: A='F'\n break;\n\n A = (A);\n }\n S += A;\n\n D &gt;&gt;&gt;= 0x04;\n A = D;\n} while(D)\n\ndo\n H += S[B];\nwhile (B--)\n\nS = B = A = C = D; // Zero out variables\nalert(H); // H: holds hexadecimal equivalent\n</code></pre>\n" }, { "answer_id": 47125022, "author": "Francisco Manuel Garca Botella", "author_id": 4285108, "author_profile": "https://Stackoverflow.com/users/4285108", "pm_score": 2, "selected": false, "text": "<p>I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:</p>\n\n<pre><code>((0xFF + number +1) &amp; 0x0FF).toString(16);\n</code></pre>\n\n<p>You can use this instruction to any number bytes, only you add <code>FF</code> in respective places. For example, to two bytes:</p>\n\n<pre><code>((0xFFFF + number +1) &amp; 0x0FFFF).toString(16);\n</code></pre>\n\n<p>If you want cast an array integer to string hexadecimal:</p>\n\n<pre><code>s = \"\";\nfor(var i = 0; i &lt; arrayNumber.length; ++i) {\n s += ((0xFF + arrayNumber[i] +1) &amp; 0x0FF).toString(16);\n}\n</code></pre>\n" }, { "answer_id": 49264490, "author": "dhc", "author_id": 2868394, "author_profile": "https://Stackoverflow.com/users/2868394", "pm_score": 2, "selected": false, "text": "<p>In case you're looking to convert to a 'full' JavaScript or CSS representation, you can use something like:</p>\n\n<pre><code> numToHex = function(num) {\n var r=((0xff0000&amp;num)&gt;&gt;16).toString(16),\n g=((0x00ff00&amp;num)&gt;&gt;8).toString(16),\n b=(0x0000ff&amp;num).toString(16);\n if (r.length==1) { r = '0'+r; }\n if (g.length==1) { g = '0'+g; }\n if (b.length==1) { b = '0'+b; }\n return '0x'+r+g+b; // ('#' instead of'0x' for CSS)\n };\n\n var dec = 5974678;\n console.log( numToHex(dec) ); // 0x5b2a96\n</code></pre>\n" }, { "answer_id": 53389207, "author": "Hypersoft Systems", "author_id": 3370790, "author_profile": "https://Stackoverflow.com/users/3370790", "pm_score": -1, "selected": false, "text": "<p>Here's my solution:</p>\n\n<pre><code>hex = function(number) {\n return '0x' + Math.abs(number).toString(16);\n}\n</code></pre>\n\n<p>The question says: <em>\"How to convert decimal to hexadecimal in JavaScript\"</em>. While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish <em>hexadecimal codes</em> from <em>programmatic identifiers</em> and <em>other numbers</em> (1234 could be hexadecimal, decimal, or even octal).</p>\n\n<p>Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.</p>\n\n<p>The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.</p>\n\n<p>The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.</p>\n" }, { "answer_id": 54441205, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 2, "selected": false, "text": "<p>You can do something like this in <a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-_ECMAScript_2015\" rel=\"nofollow noreferrer\">ECMAScript&nbsp;6</a>:</p>\n\n<pre><code>const toHex = num =&gt; (num).toString(16).toUpperCase();\n</code></pre>\n" }, { "answer_id": 56180356, "author": "Abhilash Nayak", "author_id": 5950470, "author_profile": "https://Stackoverflow.com/users/5950470", "pm_score": 2, "selected": false, "text": "<p>If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const hugeNumber = \"9007199254740991873839\" // Make sure its in String\r\nconst hexOfHugeNumber = BigInt(hugeNumber).toString(16);\r\nconsole.log(hexOfHugeNumber)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 57551796, "author": "Brian", "author_id": 2850957, "author_profile": "https://Stackoverflow.com/users/2850957", "pm_score": 2, "selected": false, "text": "<p>This is based on Prestaul and Tod's solutions. However, this is a generalisation that accounts for varying size of a variable (e.g. Parsing signed value from a microcontroller serial log). </p>\n\n<pre><code>function decimalToPaddedHexString(number, bitsize)\n{ \n let byteCount = Math.ceil(bitsize/8);\n let maxBinValue = Math.pow(2, bitsize)-1;\n\n /* In node.js this function fails for bitsize above 32bits */\n if (bitsize &gt; 32)\n throw \"number above maximum value\";\n\n /* Conversion to unsigned form based on */\n if (number &lt; 0)\n number = maxBinValue + number + 1;\n\n return \"0x\"+(number &gt;&gt;&gt; 0).toString(16).toUpperCase().padStart(byteCount*2, '0');\n}\n</code></pre>\n\n<p>Test script:</p>\n\n<pre><code>for (let n = 0 ; n &lt; 64 ; n++ ) { \n let s=decimalToPaddedHexString(-1, n); \n console.log(`decimalToPaddedHexString(-1,${(n+\"\").padStart(2)}) = ${s.padStart(10)} = ${(\"0b\"+parseInt(s).toString(2)).padStart(34)}`);\n }\n</code></pre>\n\n<p>Test results:</p>\n\n<pre><code>decimalToPaddedHexString(-1, 0) = 0x0 = 0b0\ndecimalToPaddedHexString(-1, 1) = 0x01 = 0b1\ndecimalToPaddedHexString(-1, 2) = 0x03 = 0b11\ndecimalToPaddedHexString(-1, 3) = 0x07 = 0b111\ndecimalToPaddedHexString(-1, 4) = 0x0F = 0b1111\ndecimalToPaddedHexString(-1, 5) = 0x1F = 0b11111\ndecimalToPaddedHexString(-1, 6) = 0x3F = 0b111111\ndecimalToPaddedHexString(-1, 7) = 0x7F = 0b1111111\ndecimalToPaddedHexString(-1, 8) = 0xFF = 0b11111111\ndecimalToPaddedHexString(-1, 9) = 0x01FF = 0b111111111\ndecimalToPaddedHexString(-1,10) = 0x03FF = 0b1111111111\ndecimalToPaddedHexString(-1,11) = 0x07FF = 0b11111111111\ndecimalToPaddedHexString(-1,12) = 0x0FFF = 0b111111111111\ndecimalToPaddedHexString(-1,13) = 0x1FFF = 0b1111111111111\ndecimalToPaddedHexString(-1,14) = 0x3FFF = 0b11111111111111\ndecimalToPaddedHexString(-1,15) = 0x7FFF = 0b111111111111111\ndecimalToPaddedHexString(-1,16) = 0xFFFF = 0b1111111111111111\ndecimalToPaddedHexString(-1,17) = 0x01FFFF = 0b11111111111111111\ndecimalToPaddedHexString(-1,18) = 0x03FFFF = 0b111111111111111111\ndecimalToPaddedHexString(-1,19) = 0x07FFFF = 0b1111111111111111111\ndecimalToPaddedHexString(-1,20) = 0x0FFFFF = 0b11111111111111111111\ndecimalToPaddedHexString(-1,21) = 0x1FFFFF = 0b111111111111111111111\ndecimalToPaddedHexString(-1,22) = 0x3FFFFF = 0b1111111111111111111111\ndecimalToPaddedHexString(-1,23) = 0x7FFFFF = 0b11111111111111111111111\ndecimalToPaddedHexString(-1,24) = 0xFFFFFF = 0b111111111111111111111111\ndecimalToPaddedHexString(-1,25) = 0x01FFFFFF = 0b1111111111111111111111111\ndecimalToPaddedHexString(-1,26) = 0x03FFFFFF = 0b11111111111111111111111111\ndecimalToPaddedHexString(-1,27) = 0x07FFFFFF = 0b111111111111111111111111111\ndecimalToPaddedHexString(-1,28) = 0x0FFFFFFF = 0b1111111111111111111111111111\ndecimalToPaddedHexString(-1,29) = 0x1FFFFFFF = 0b11111111111111111111111111111\ndecimalToPaddedHexString(-1,30) = 0x3FFFFFFF = 0b111111111111111111111111111111\ndecimalToPaddedHexString(-1,31) = 0x7FFFFFFF = 0b1111111111111111111111111111111\ndecimalToPaddedHexString(-1,32) = 0xFFFFFFFF = 0b11111111111111111111111111111111\nThrown: 'number above maximum value'\n</code></pre>\n\n<p>Note: Not too sure why it fails above 32 bitsize</p>\n" }, { "answer_id": 65859562, "author": "Bohdan Sych", "author_id": 4768564, "author_profile": "https://Stackoverflow.com/users/4768564", "pm_score": 2, "selected": false, "text": "<ul>\n<li><p>rgb(255, 255, 255) // returns FFFFFF</p>\n</li>\n<li><p>rgb(255, 255, 300) // returns FFFFFF</p>\n</li>\n<li><p>rgb(0,0,0) // returns 000000</p>\n</li>\n<li><p>rgb(148, 0, 211) // returns 9400D3</p>\n<pre><code> function rgb(...values){\n return values.reduce((acc, cur) =&gt; {\n let val = cur &gt;= 255 ? 'ff' : cur &lt;= 0 ? '00' : Number(cur).toString(16);\n return acc + (val.length === 1 ? '0'+val : val);\n }, '').toUpperCase();\n }\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 66126345, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "<h1>Arbitrary precision</h1>\n<p>This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm</p>\n<ul>\n<li>split number to sign (<code>s</code>), integer part (<code>i</code>) and fractional part (<code>f</code>) e.g for <code>-123.75</code> we have <code>s=true</code>, <code>i=123</code>, <code>f=75</code></li>\n<li>integer part to hex:\n<ul>\n<li>if <code>i='0'</code> stop</li>\n<li>get modulo: <code>m=i%16</code> (in arbitrary precision)</li>\n<li>convert <code>m</code> to hex digit and put to result string</li>\n<li>for next step calc integer part <code>i=i/16</code> (in arbitrary precision)</li>\n</ul>\n</li>\n<li>fractional part\n<ul>\n<li>count fractional digits <code>n</code></li>\n<li>multiply <code>k=f*16</code> (in arbitrary precision)</li>\n<li>split <code>k</code> to right part with <code>n</code> digits and put them to <code>f</code>, and left part with rest of digits and put them to <code>d</code></li>\n<li>convert <code>d</code> to hex and add to result.</li>\n<li>finish when number of result fractional digits is enough</li>\n</ul>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// @param decStr - string with non-negative integer\n// @param divisor - positive integer\nfunction dec2HexArbitrary(decStr, fracDigits=0) { \n // Helper: divide arbitrary precision number by js number\n // @param decStr - string with non-negative integer\n // @param divisor - positive integer\n function arbDivision(decStr, divisor) \n { \n // algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/\n let ans=''; \n let idx = 0; \n let temp = +decStr[idx]; \n while (temp &lt; divisor) temp = temp * 10 + +decStr[++idx]; \n\n while (decStr.length &gt; idx) { \n ans += (temp / divisor)|0 ; \n temp = (temp % divisor) * 10 + +decStr[++idx]; \n } \n\n if (ans.length == 0) return \"0\"; \n\n return ans; \n } \n\n // Helper: calc module of arbitrary precision number\n // @param decStr - string with non-negative integer\n // @param mod - positive integer\n function arbMod(decStr, mod) { \n // algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/\n let res = 0; \n\n for (let i = 0; i &lt; decStr.length; i++) \n res = (res * 10 + +decStr[i]) % mod; \n\n return res; \n } \n\n // Helper: multiply arbitrary precision integer by js number\n // @param decStr - string with non-negative integer\n // @param mult - positive integer\n function arbMultiply(decStr, mult) {\n let r='';\n let m=0;\n for (let i = decStr.length-1; i &gt;=0 ; i--) {\n let n = m+mult*(+decStr[i]);\n r= (i ? n%10 : n) + r \n m= n/10|0;\n }\n return r;\n }\n \n \n // dec2hex algorithm starts here\n \n let h= '0123456789abcdef'; // hex 'alphabet'\n let m= decStr.match(/-?(.*?)\\.(.*)?/) || decStr.match(/-?(.*)/); // separate sign,integer,ractional\n let i= m[1].replace(/^0+/,'').replace(/^$/,'0'); // integer part (without sign and leading zeros)\n let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0'); // fractional part (without last zeros)\n let s= decStr[0]=='-'; // sign\n\n let r=''; // result\n \n if(i=='0') r='0';\n \n while(i!='0') { // integer part\n r=h[arbMod(i,16)]+r; \n i=arbDivision(i,16);\n }\n \n if(fracDigits) r+=\".\";\n \n let n = f.length;\n \n for(let j=0; j&lt;fracDigits; j++) { // frac part\n let k= arbMultiply(f,16);\n f = k.slice(-n);\n let d= k.slice(0,k.length-n); \n r+= d.length ? h[+d] : '0';\n }\n \n return (s?'-':'')+r;\n}\n\n\n\n\n\n\n\n\n// -----------\n// TESTS\n// -----------\n\n\n\nlet tests = [\n [\"0\",2],\n [\"000\",2], \n [\"123\",0],\n [\"-123\",0], \n [\"00.000\",2],\n \n [\"255.75\",5],\n [\"-255.75\",5], \n [\"127.999\",32], \n];\n\nconsole.log('Input Standard Abitrary');\ntests.forEach(t=&gt; {\n let nonArb = (+t[0]).toString(16).padEnd(17,' ');\n let arb = dec2HexArbitrary(t[0],t[1]);\n console.log(t[0].padEnd(10,' '), nonArb, arb); \n});\n\n\n// Long Example (40 digits after dot)\nlet example = \"123456789012345678901234567890.09876543210987654321\"\nconsole.log(`\\nLong Example:`);\nconsole.log('dec:',example);\nconsole.log('hex: ',dec2HexArbitrary(example,40));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 71171818, "author": "Wilt", "author_id": 1697459, "author_profile": "https://Stackoverflow.com/users/1697459", "pm_score": 2, "selected": false, "text": "<h2>Converting hex color numbers to hex color strings:</h2>\n<p>A simple solution with <code>toString</code> and ES6 <code>padStart</code> for converting hex color numbers to hex color strings.</p>\n<pre><code>const string = `#${color.toString(16).padStart(6, '0')}`;\n</code></pre>\n<p>For example:</p>\n<p><code>0x000000</code> will become <code>#000000</code><br>\n<code>0xFFFFFF</code> will become <code>#FFFFFF</code></p>\n<p><a href=\"https://jsfiddle.net/wilt/zg1vcbu3/\" rel=\"nofollow noreferrer\">Check this example in a fiddle here</a></p>\n" }, { "answer_id": 71523192, "author": "aGuegu", "author_id": 1764290, "author_profile": "https://Stackoverflow.com/users/1764290", "pm_score": 0, "selected": false, "text": "<p>The problem basically how many padding zeros to expect.</p>\n<p>If you expect string <code>01</code> and <code>11</code> from Number 1 and 17. it's better to use <a href=\"https://nodejs.org/docs/latest-v16.x/api/buffer.html\" rel=\"nofollow noreferrer\">Buffer</a> as a bridge, with which number is turn into bytes, and then the hex is just an output format of it. And the bytes organization is well controlled by Buffer functions, like <a href=\"https://nodejs.org/docs/latest-v16.x/api/buffer.html#bufwriteuint32bevalue-offset\" rel=\"nofollow noreferrer\">writeUInt32BE</a>, <a href=\"https://nodejs.org/docs/latest-v16.x/api/buffer.html#bufwriteint16levalue-offset\" rel=\"nofollow noreferrer\">writeInt16LE</a>, etc.</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { Buffer } from 'buffer';\n\nfunction toHex(n) { // 4byte\n const buff = Buffer.alloc(4);\n buff.writeInt32BE(n);\n return buff.toString('hex');\n}\n\n</code></pre>\n<pre class=\"lang-sh prettyprint-override\"><code>&gt; toHex(1)\n'00000001'\n&gt; toHex(17)\n'00000011'\n&gt; toHex(-1)\n'ffffffff'\n&gt; toHex(-1212)\n'fffffb44'\n&gt; toHex(1212)\n'000004bc'\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556/" ]
How do you convert decimal values to their hexadecimal equivalent in JavaScript?
Convert a number to a hexadecimal string with: ``` hexString = yourNumber.toString(16); ``` And reverse the process with: ``` yourNumber = parseInt(hexString, 16); ```
57,804
<p>Now, before you say it: I <strong>did</strong> Google and my <code>hbm.xml</code> file <strong>is</strong> an Embedded Resource. </p> <p>Here is the code I am calling:</p> <pre><code>ISession session = GetCurrentSession(); var returnObject = session.Get&lt;T&gt;(Id); </code></pre> <p>Here is my mapping file for the class:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"&gt; &lt;class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true"&gt; &lt;id name="ID" column="ID" unsaved-value="0"&gt; &lt;generator class="identity" /&gt; &lt;/id&gt; &lt;property name="Name" column="Name" /&gt; &lt;property name="NumberOfBuckets" column="NumberOfBuckets" /&gt; &lt;property name="SearchCriteriaOne" column="SearchCriteriaOne" /&gt; &lt;bag name="_Businesses" cascade="all"&gt; &lt;key column="SubCategoryId"/&gt; &lt;one-to-many class="HQData.Objects.Business, HQData"/&gt; &lt;/bag&gt; &lt;bag name="_Buckets" cascade="all"&gt; &lt;key column="SubCategoryId"/&gt; &lt;one-to-many class="HQData.Objects.Bucket, HQData"/&gt; &lt;/bag&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>Has anyone run to this issue before?</p> <p>Here is the full error message:</p> <blockquote> <pre>MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory() in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436</pre> </blockquote> <p><strong>Update</strong>, here's what the solution for <em>my</em> scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime. </p>
[ { "answer_id": 57860, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 2, "selected": false, "text": "<p>Should it be <code>name=\"Id\"</code>? Typos are a likely cause.</p>\n\n<p>Next would be to try it out with a non-generic test to make sure you're passing in the proper type parameter.</p>\n\n<p>Can you post the entire error message?</p>\n" }, { "answer_id": 57995, "author": "Andy S", "author_id": 3759, "author_profile": "https://Stackoverflow.com/users/3759", "pm_score": 8, "selected": true, "text": "<p>Sounds like you forgot to add a mapping assembly to the session factory configuration..</p>\n\n<p>If you're using app.config...</p>\n\n<pre><code>.\n.\n &lt;property name=\"show_sql\"&gt;true&lt;/property&gt;\n &lt;property name=\"query.substitutions\"&gt;true 1, false 0, yes 'Y', no 'N'&lt;/property&gt;\n &lt;mapping assembly=\"Project.DomainModel\"/&gt; &lt;!-- Here --&gt;\n&lt;/session-factory&gt;\n.\n.\n</code></pre>\n" }, { "answer_id": 615156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If running tests on the repository from a seperate assembly, then make sure your Hibernate.cfg.xml is set to output always in the bin directory of said assembly. This wasn't happening for us and we got the above error in certain circumstances.</p>\n\n<p>Disclaimer: This might be a slightly esoteric bit of advice, given that it's a direct result of how we structure our repository integration test assemblies (i.e. we have a symbolic link from each test assembly to a single Hibernate.xfg.xml)</p>\n" }, { "answer_id": 660099, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Had a similar problem when find an object by id...\nAll i did was to use the fully qualified name in the class name. That is \nBefore it was :</p>\n\n<pre><code>find(\"Class\",id)\n</code></pre>\n\n<p>Object so it became like this : </p>\n\n<pre><code>find(\"assemblyName.Class\",id)\n</code></pre>\n" }, { "answer_id": 1795914, "author": "Chris Vosnidis", "author_id": 166576, "author_profile": "https://Stackoverflow.com/users/166576", "pm_score": 7, "selected": false, "text": "<p>Something obvious, yet quite useful for someone new to NHibernate.</p>\n\n<p>All XML Mapping files should be treated as <em>Embedded Resources</em> rather than the default <em>Content</em>. This option is set by editing the Build Action attribute in the file's properties.</p>\n\n<p>XML files are then embedded into the assembly, and parsed at project startup during NHibernate's configuration phase.</p>\n" }, { "answer_id": 2421598, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Don't forget to specify mapping information in .config file</p>\n\n<p>e.g. </p>\n\n<p>where MyApp.Data is assembly that contains your mappings</p>\n" }, { "answer_id": 3203836, "author": "David", "author_id": 386675, "author_profile": "https://Stackoverflow.com/users/386675", "pm_score": 2, "selected": false, "text": "<p>I had similar problem, and I solved it as folows:</p>\n\n<p>I working on MS SQL 2008, but in the NH configuration I had bad dialect:\nNHibernate.Dialect.<strong>MsSql2005Dialect</strong>\nif I correct it to:\nNHibernate.Dialect.<strong>MsSql2008Dialect</strong>\nthen everything's working fine without a exception \"No persister for: ...\"\nDavid.</p>\n" }, { "answer_id": 3512745, "author": "nHibernate User", "author_id": 424070, "author_profile": "https://Stackoverflow.com/users/424070", "pm_score": 6, "selected": false, "text": "<p>My issue was that I forgot to put the .hbm in the name of the mapping xml. Also make sure you make it an embedded resource!</p>\n" }, { "answer_id": 3542235, "author": "basarat", "author_id": 390330, "author_profile": "https://Stackoverflow.com/users/390330", "pm_score": 6, "selected": false, "text": "<p>I got this off of <a href=\"http://www.mail-archive.com/[email protected]/msg03276.html\" rel=\"noreferrer\">here</a>:</p>\n\n<p>In my case the mapping class was not public. In other words, instead of:</p>\n\n<pre><code>public class UserMap : ClassMap&lt;user&gt; // note the public!\n</code></pre>\n\n<p>I just had:</p>\n\n<pre><code>class UserMap : ClassMap&lt;user&gt;\n</code></pre>\n" }, { "answer_id": 4538190, "author": "IdontCareAboutReputationPoints", "author_id": 554893, "author_profile": "https://Stackoverflow.com/users/554893", "pm_score": 2, "selected": false, "text": "<p>I had the same problem because I was adding the wrong assembly in Configuration.AddAssembly() method.</p>\n" }, { "answer_id": 6112707, "author": "Seth", "author_id": 521662, "author_profile": "https://Stackoverflow.com/users/521662", "pm_score": 2, "selected": false, "text": "<p>I was also adding the wrong assembly during initialization. The class I'm persisting is in assembly #1, and my .hbm.xml file is embedded in assembly #2. I changed <code>cfg.AddAssembly(...</code> to add assembly #2 (instead of assembly #1) and everything worked. Thanks!</p>\n" }, { "answer_id": 7360026, "author": "Amol", "author_id": 189654, "author_profile": "https://Stackoverflow.com/users/189654", "pm_score": 0, "selected": false, "text": "<p>Make sure you have called the <code>CreateCriteria(typeof(DomainObjectType))</code> method on Session for the domain object which you intent to fetch from DB.</p>\n" }, { "answer_id": 11252936, "author": "goku_da_master", "author_id": 151325, "author_profile": "https://Stackoverflow.com/users/151325", "pm_score": 2, "selected": false, "text": "<p>To add to Amol's answer, don't make the mistake of specifying the Interface class type. <b>Make sure you specify the implementation class</b>. (Ie. don't use IDomainObjectType). Not that I made this mistake... :)</p>\n" }, { "answer_id": 11758228, "author": "Nickmaovich", "author_id": 565157, "author_profile": "https://Stackoverflow.com/users/565157", "pm_score": 5, "selected": false, "text": "<p>Spending about 4 hours on <strong>googling</strong> and <strong>stackoverflowing</strong>, trying all of stuff around there, i've found my error:</p>\n\n<p><strong>My mapping file was called <em>.nbm.xml</em> instead of <em>.hbm.xml</em></strong>. That was insane.</p>\n" }, { "answer_id": 23153675, "author": "Arkadas Kilic", "author_id": 3276913, "author_profile": "https://Stackoverflow.com/users/3276913", "pm_score": 2, "selected": false, "text": "<p>This error occurs because of invalid mapping configuration. You should check where you set .Mappings for your session factory. Basically search for \".Mappings(\" in your project and make sure you specified correct entity class in below line.</p>\n\n<pre><code>.Mappings(m =&gt; m.FluentMappings.AddFromAssemblyOf&lt;YourEntityClassName&gt;())\n</code></pre>\n" }, { "answer_id": 60490552, "author": "Robetto", "author_id": 3631770, "author_profile": "https://Stackoverflow.com/users/3631770", "pm_score": 0, "selected": false, "text": "<p>I have a similar problem but all mentioned <em>requirements</em> are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.</p>\n\n<p>My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why. </p>\n\n<pre><code> OBJEKTE t = _mapper.Map&lt;OBJEKTE&gt;(inparam);\n OBJEKTE res = await _objRepo.UpdateAsync(t);\n</code></pre>\n\n<p>If inparam would go straight to UpdateAsync() it cannot find a matching persistor.</p>\n\n<p>It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:</p>\n\n<pre><code>t.GetType()\n{Name = \"OBJEKTE\" FullName = \"MyComp.Persistence.OBJEKTE\"}\n\ninparam.GetType()\n{Name = \"OBJEKTEProxyForFieldInterceptor\" FullName = \"OBJEKTEProxyForFieldInterceptor\"}\n</code></pre>\n\n<p>The fun thing though is that the source of <code>inparam</code> is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.</p>\n" }, { "answer_id": 65218643, "author": "xhafan", "author_id": 379279, "author_profile": "https://Stackoverflow.com/users/379279", "pm_score": 0, "selected": false, "text": "<p>I my case I fetched an entity without <code>await</code>:</p>\n<pre><code>var company = _unitOfWork.Session.GetAsync&lt;Company&gt;(id);\n</code></pre>\n<p>and then I tried to delete it:</p>\n<pre><code>await _unitOfWork.Session.DeleteAsync(company);\n</code></pre>\n<p>I could not decipher the error message that I'm deleting a <code>Task&lt;Company&gt;</code> instead of <code>Company</code>:</p>\n<p><em>MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]</em></p>\n" }, { "answer_id": 71228041, "author": "Mitja", "author_id": 1651498, "author_profile": "https://Stackoverflow.com/users/1651498", "pm_score": 0, "selected": false, "text": "<p>You would think that after 14 years, all possible answers to this question have been written down. It seems like that is not the case.</p>\n<p>In the application I'm currently working on, there are <em>several</em> <code>ISessionFactory</code> instances, each one for a different database.</p>\n<p>If you're taking the wrong one to create your <code>ISession</code>, of course it will have no idea of the class you're trying to persist, which was the error in my case.</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
Now, before you say it: I **did** Google and my `hbm.xml` file **is** an Embedded Resource. Here is the code I am calling: ``` ISession session = GetCurrentSession(); var returnObject = session.Get<T>(Id); ``` Here is my mapping file for the class: ```xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true"> <id name="ID" column="ID" unsaved-value="0"> <generator class="identity" /> </id> <property name="Name" column="Name" /> <property name="NumberOfBuckets" column="NumberOfBuckets" /> <property name="SearchCriteriaOne" column="SearchCriteriaOne" /> <bag name="_Businesses" cascade="all"> <key column="SubCategoryId"/> <one-to-many class="HQData.Objects.Business, HQData"/> </bag> <bag name="_Buckets" cascade="all"> <key column="SubCategoryId"/> <one-to-many class="HQData.Objects.Bucket, HQData"/> </bag> </class> </hibernate-mapping> ``` Has anyone run to this issue before? Here is the full error message: > > > ``` > MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound) > in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName) > in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) > in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) > in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id) > in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) > in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id) > in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id) > in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory() > in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e) > in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436 > ``` > > **Update**, here's what the solution for *my* scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime.
Sounds like you forgot to add a mapping assembly to the session factory configuration.. If you're using app.config... ``` . . <property name="show_sql">true</property> <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> <mapping assembly="Project.DomainModel"/> <!-- Here --> </session-factory> . . ```
57,812
<p>I have a div with <code>id="a"</code> that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:</p> <pre><code>$("#a").removeClass("bg*"); </code></pre>
[ { "answer_id": 57819, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": false, "text": "<p>You don't need any jQuery specific code to handle this. Just use a RegExp to replace them:</p>\n\n<pre><code>$(\"#a\").className = $(\"#a\").className.replace(/\\bbg.*?\\b/g, '');\n</code></pre>\n\n<p>You can modify this to support any prefix but the faster method is above as the RegExp will be compiled only once:</p>\n\n<pre><code>function removeClassByPrefix(el, prefix) {\n var regx = new RegExp('\\\\b' + prefix + '.*?\\\\b', 'g');\n el.className = el.className.replace(regx, '');\n return el;\n}\n</code></pre>\n" }, { "answer_id": 58097, "author": "Brad", "author_id": 5464, "author_profile": "https://Stackoverflow.com/users/5464", "pm_score": 0, "selected": false, "text": "<p>Prestaul's answer was helpful, but it didn't quite work for me. The jQuery way to select an object by id didn't work. I had to use</p>\n\n<pre><code>document.getElementById(\"a\").className\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>$(\"#a\").className\n</code></pre>\n" }, { "answer_id": 58533, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 7, "selected": true, "text": "<p>With jQuery, the actual DOM element is at index zero, this should work</p>\n\n<pre><code>$('#a')[0].className = $('#a')[0].className.replace(/\\bbg.*?\\b/g, '');\n</code></pre>\n" }, { "answer_id": 627368, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.mail-archive.com/[email protected]/msg03998.html\" rel=\"nofollow noreferrer\">http://www.mail-archive.com/[email protected]/msg03998.html</a> says:</p>\n\n<p>...and .removeClass() would remove all classes...</p>\n\n<p>It works for me ;)</p>\n\n<p>cheers</p>\n" }, { "answer_id": 3284637, "author": "jamland", "author_id": 344306, "author_profile": "https://Stackoverflow.com/users/344306", "pm_score": 0, "selected": false, "text": "<p>I also use hyphen'-' and digits for class name. So my version include '\\d-'</p>\n\n<pre><code>$('#a')[0].className = $('#a')[0].className.replace(/\\bbg.\\d-*?\\b/g, '');\n</code></pre>\n" }, { "answer_id": 8624674, "author": "Pete B", "author_id": 263643, "author_profile": "https://Stackoverflow.com/users/263643", "pm_score": 5, "selected": false, "text": "<p>I've written a simple <a href=\"https://gist.github.com/1517285\" rel=\"nofollow noreferrer\">jQuery plugin - alterClass</a>, that does wildcard class removal. \nWill optionally add classes too.</p>\n\n<pre><code>$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' ) \n</code></pre>\n" }, { "answer_id": 10835425, "author": "Kabir Sarin", "author_id": 1181570, "author_profile": "https://Stackoverflow.com/users/1181570", "pm_score": 7, "selected": false, "text": "<p>A regex splitting on word boundary <code>\\b</code> isn't the best solution for this:</p>\n\n<pre><code>var prefix = \"prefix\";\nvar classes = el.className.split(\" \").filter(function(c) {\n return c.lastIndexOf(prefix, 0) !== 0;\n});\nel.className = classes.join(\" \").trim();\n</code></pre>\n\n<p>or as a jQuery mixin:</p>\n\n<pre><code>$.fn.removeClassPrefix = function(prefix) {\n this.each(function(i, el) {\n var classes = el.className.split(\" \").filter(function(c) {\n return c.lastIndexOf(prefix, 0) !== 0;\n });\n el.className = $.trim(classes.join(\" \"));\n });\n return this;\n};\n</code></pre>\n\n<p>2018 ES6 Update:</p>\n\n<pre><code>const prefix = \"prefix\";\nconst classes = el.className.split(\" \").filter(c =&gt; !c.startsWith(prefix));\nel.className = classes.join(\" \").trim();\n</code></pre>\n" }, { "answer_id": 12635031, "author": "Jan.J", "author_id": 937367, "author_profile": "https://Stackoverflow.com/users/937367", "pm_score": 1, "selected": false, "text": "<p>I know it's an old question, but I found out new solution and want to know if it has disadvantages?<br /></p>\n\n<pre><code>$('#a')[0].className = $('#a')[0].className\n .replace(/(^|\\s)bg.*?(\\s|$)/g, ' ')\n .replace(/\\s\\s+/g, ' ')\n .replace(/(^\\s|\\s$)/g, '');\n</code></pre>\n" }, { "answer_id": 13944814, "author": "Rob", "author_id": 1200670, "author_profile": "https://Stackoverflow.com/users/1200670", "pm_score": 0, "selected": false, "text": "<pre><code>(function($)\n{\n return this.each(function()\n {\n var classes = $(this).attr('class');\n\n if(!classes || !regex) return false;\n\n var classArray = [];\n\n classes = classes.split(' ');\n\n for(var i=0, len=classes.length; i&lt;len; i++) if(!classes[i].match(regex)) classArray.push(classes[i]);\n\n $(this).attr('class', classArray.join(' '));\n });\n})(jQuery);\n</code></pre>\n" }, { "answer_id": 14855671, "author": "majorsk8", "author_id": 2068678, "author_profile": "https://Stackoverflow.com/users/2068678", "pm_score": -1, "selected": false, "text": "<pre><code>$(\"#element\").removeAttr(\"class\").addClass(\"yourClass\");\n</code></pre>\n" }, { "answer_id": 15235183, "author": "abernier", "author_id": 133327, "author_profile": "https://Stackoverflow.com/users/133327", "pm_score": 3, "selected": false, "text": "<p>Using <a href=\"http://api.jquery.com/removeClass/#removeClass-functionindex--class\" rel=\"noreferrer\">2nd signature</a> of <code>$.fn.removeClass</code> :</p>\n\n<pre><code>// Considering:\nvar $el = $('&lt;div class=\" foo-1 a b foo-2 c foo\"/&gt;');\n\nfunction makeRemoveClassHandler(regex) {\n return function (index, classes) {\n return classes.split(/\\s+/).filter(function (el) {return regex.test(el);}).join(' ');\n }\n}\n\n$el.removeClass(makeRemoveClassHandler(/^foo-/));\n//&gt; [&lt;div class=​\"a b c foo\"&gt;​&lt;/div&gt;​]\n</code></pre>\n" }, { "answer_id": 19368577, "author": "Pawel", "author_id": 696535, "author_profile": "https://Stackoverflow.com/users/696535", "pm_score": 2, "selected": false, "text": "<p>I was looking for solution for exactly the same problem. To remove all classes starting with prefix \"fontid_\" After reading this article I wrote a small plugin which I'm using now.</p>\n\n<pre><code>(function ($) {\n $.fn.removePrefixedClasses = function (prefix) {\n var classNames = $(this).attr('class').split(' '),\n className,\n newClassNames = [],\n i;\n //loop class names\n for(i = 0; i &lt; classNames.length; i++) {\n className = classNames[i];\n // if prefix not found at the beggining of class name\n if(className.indexOf(prefix) !== 0) {\n newClassNames.push(className);\n continue;\n }\n }\n // write new list excluding filtered classNames\n $(this).attr('class', newClassNames.join(' '));\n };\n }(fQuery));\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$('#elementId').removePrefixedClasses('prefix-of-classes_');\n</code></pre>\n" }, { "answer_id": 29002847, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>An approach I would use using simple jQuery constructs and array handling functions, is to declare an function that takes id of the control and prefix of the class and deleted all classed. The code is attached:</p>\n\n<pre><code>function removeclasses(controlIndex,classPrefix){\n var classes = $(\"#\"+controlIndex).attr(\"class\").split(\" \");\n $.each(classes,function(index) {\n if(classes[index].indexOf(classPrefix)==0) {\n $(\"#\"+controlIndex).removeClass(classes[index]);\n }\n });\n}\n</code></pre>\n\n<p>Now this function can be called from anywhere, onclick of button or from code:</p>\n\n<pre><code>removeclasses(\"a\",\"bg\");\n</code></pre>\n" }, { "answer_id": 44884314, "author": "Adam111p", "author_id": 3058581, "author_profile": "https://Stackoverflow.com/users/3058581", "pm_score": 2, "selected": false, "text": "<p>In one line ...\nRemoves all classes that match a regular expression <em>someRegExp</em></p>\n\n<pre><code>$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});\n</code></pre>\n" }, { "answer_id": 53002208, "author": "Max", "author_id": 2944332, "author_profile": "https://Stackoverflow.com/users/2944332", "pm_score": 3, "selected": false, "text": "<p>For modern browsers:</p>\n\n<pre><code>let element = $('#a')[0];\nlet cls = 'bg';\n\nelement.classList.remove.apply(element.classList, Array.from(element.classList).filter(v=&gt;v.startsWith(cls)));\n</code></pre>\n" }, { "answer_id": 68063824, "author": "danday74", "author_id": 1205871, "author_profile": "https://Stackoverflow.com/users/1205871", "pm_score": 0, "selected": false, "text": "<p>The top answer converted to jQuery for those wanting a jQuery only solution:</p>\n<pre><code>const prefix = 'prefix'\nconst classes = el.attr('class').split(' ').filter(c =&gt; !c.startsWith(prefix))\nel.attr('class', classes.join(' ').trim())\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5464/" ]
I have a div with `id="a"` that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works: ``` $("#a").removeClass("bg*"); ```
With jQuery, the actual DOM element is at index zero, this should work ``` $('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, ''); ```
57,840
<p>I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?</p> <p>This is the wrapper that I have which calls GetData() defined in a C++ file:</p> <pre><code> [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl, EntryPoint = "GetData", BestFitMapping = false)] public static extern String GetData(String url); </code></pre> <p>The code is crashing and I want to investigate the root cause.</p> <p>Thanks, Nikhil</p>
[ { "answer_id": 57862, "author": "Lou", "author_id": 4341, "author_profile": "https://Stackoverflow.com/users/4341", "pm_score": 6, "selected": true, "text": "<p>Check the Debug tab on your project's properties page. There should be an \"Enable unmanaged code debugging\" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs.</p>\n\n<p>If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging.</p>\n\n<p>The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally.</p>\n" }, { "answer_id": 57880, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<p>in addition to Lou's advise for starting the debugger, you can select which debug engines are used when attaching to an existing process by clicking on 'Select...' in the 'attach to process' dialog and choosing both 'managed code' and 'native code'.</p>\n\n<p>Debugging in this way is called mixed mode debugging. See this <a href=\"http://blogs.msdn.com/sripod/archive/2006/12/05/debugging-mixed-mode-applications.aspx\" rel=\"noreferrer\">blog post</a> for some tips.</p>\n\n<p>I believe this isn't supported for 64 bit processes ... though would love to be wrong on that point.</p>\n" }, { "answer_id": 58954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>To anyone using WinDbg:</p>\n\n<p>1>Setup symbols</p>\n\n<p>Look at these commands. (Help: in console .hh &lt; command> )</p>\n\n<pre><code>.sympath\n.sympath+ \n.symfix\n</code></pre>\n\n<p>2>Set up source path</p>\n\n<pre><code>.srcpath\n</code></pre>\n\n<p>3>Load SOS extention to debug managed / mixed mode programs.</p>\n\n<p>(Make sure you have extention path setup correctly)</p>\n\n<p>Add Microsoft.NET\\Framework\\v2.0.50727 for x86 using-</p>\n\n<pre><code>.extpath \n</code></pre>\n\n<p>Set a breakpoint for the clr to load.</p>\n\n<pre><code>sxe ld:mscorwks\n</code></pre>\n\n<p>(F5 / g)\n(Wait for ModLoad BP on mscorwks.dll)</p>\n\n<p>Make sure you dont have a duplicate sos extention already loaded. See:</p>\n\n<pre><code>.chain\n</code></pre>\n\n<p>Now we're ready to load the sos extention. :)</p>\n\n<pre><code>.loadby sos mscorwks\n</code></pre>\n\n<p>4> Reload all the symbols..</p>\n\n<pre><code>.reload\n</code></pre>\n\n<p>Now you're all set :)</p>\n\n<p>(YMMV)</p>\n" }, { "answer_id": 732196, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Mixed debugging is not supported in 64bit mode (as of Visual Studio 2008).</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734/" ]
I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code? This is the wrapper that I have which calls GetData() defined in a C++ file: ``` [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl, EntryPoint = "GetData", BestFitMapping = false)] public static extern String GetData(String url); ``` The code is crashing and I want to investigate the root cause. Thanks, Nikhil
Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs. If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging. The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally.
57,849
<p>There doesn't seem to be a way to change the padding (or row height) for all rows in a .NET ListView. Does anybody have an elegant hack-around?</p>
[ { "answer_id": 57975, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 3, "selected": false, "text": "<p>A workaround is to use an ImageList that is as tall as you want the items to be. Just fill a blank image with the background color. You can even make the image 1 wide so as to not take much space horizontally.</p>\n" }, { "answer_id": 13072438, "author": "Quinn Johns", "author_id": 1539718, "author_profile": "https://Stackoverflow.com/users/1539718", "pm_score": 4, "selected": false, "text": "<p>I know this post is fairly old, however, if you never found the best option, I've got a <a href=\"http://qdevblog.blogspot.co.uk/2011/11/c-listview-item-spacing.html\">blog post</a> that may help, it involves utilizing LVM_SETICONSPACING. </p>\n\n<p><strong>According to my blog,</strong></p>\n\n<p>Initially, you'll need to add:</p>\n\n<pre><code>using System.Runtime.InteropServices;\n</code></pre>\n\n<p>Next, you'll need to import the DLL, so that you can utilize SendMessage, to modify the ListView parameters.</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\npublic static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);\n</code></pre>\n\n<p>Once that is complete, create the following two functions:</p>\n\n<pre><code>public int MakeLong(short lowPart, short highPart)\n{\n return (int)(((ushort)lowPart) | (uint)(highPart &lt;&lt; 16));\n}\n\npublic void ListViewItem_SetSpacing(ListView listview, short leftPadding, short topPadding) \n{ \n const int LVM_FIRST = 0x1000; \n const int LVM_SETICONSPACING = LVM_FIRST + 53; \n SendMessage(listview.Handle, LVM_SETICONSPACING, IntPtr.Zero, (IntPtr)MakeLong(leftPadding, topPadding)); \n} \n</code></pre>\n\n<p>Then to use the function, just pass in your ListView, and set the values. In the example, 64 pixels is the image width, and 32 pixels is my horizontal spacing/padding, 100 pixels is the image height, and 16 pixels is my vertical spacing/padding, and both parameters require a minimum of 4 pixels.</p>\n\n<pre><code>ListViewItem_SetSpacing(this.listView1, 64 + 32, 100 + 16);\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There doesn't seem to be a way to change the padding (or row height) for all rows in a .NET ListView. Does anybody have an elegant hack-around?
I know this post is fairly old, however, if you never found the best option, I've got a [blog post](http://qdevblog.blogspot.co.uk/2011/11/c-listview-item-spacing.html) that may help, it involves utilizing LVM\_SETICONSPACING. **According to my blog,** Initially, you'll need to add: ``` using System.Runtime.InteropServices; ``` Next, you'll need to import the DLL, so that you can utilize SendMessage, to modify the ListView parameters. ``` [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); ``` Once that is complete, create the following two functions: ``` public int MakeLong(short lowPart, short highPart) { return (int)(((ushort)lowPart) | (uint)(highPart << 16)); } public void ListViewItem_SetSpacing(ListView listview, short leftPadding, short topPadding) { const int LVM_FIRST = 0x1000; const int LVM_SETICONSPACING = LVM_FIRST + 53; SendMessage(listview.Handle, LVM_SETICONSPACING, IntPtr.Zero, (IntPtr)MakeLong(leftPadding, topPadding)); } ``` Then to use the function, just pass in your ListView, and set the values. In the example, 64 pixels is the image width, and 32 pixels is my horizontal spacing/padding, 100 pixels is the image height, and 16 pixels is my vertical spacing/padding, and both parameters require a minimum of 4 pixels. ``` ListViewItem_SetSpacing(this.listView1, 64 + 32, 100 + 16); ```
57,854
<p>How can I close a browser window without receiving the <em>Do you want to close this window</em> prompt?</p> <p>The prompt occurs when I use the <code>window.close();</code> function.</p>
[ { "answer_id": 57857, "author": "Derek", "author_id": 5440, "author_profile": "https://Stackoverflow.com/users/5440", "pm_score": -1, "selected": false, "text": "<p>The best solution I have found is:</p>\n\n<pre><code>this.focus();\nself.opener=this;\nself.close();\n</code></pre>\n" }, { "answer_id": 57868, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://blogs.x2line.com/al/articles/350.aspx\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>&lt;a href=\"javascript:window.opener='x';window.close();\"&gt;Close&lt;/a&gt;\n</code></pre>\n\n<p>You need to set <code>window.opener</code> to something, otherwise it complains.</p>\n" }, { "answer_id": 57872, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 0, "selected": false, "text": "<p>The browser is complaining because you're using JavaScript to close a window that wasn't opened with JavaScript, i.e. <code>window.open('foo.html');</code>.</p>\n" }, { "answer_id": 713230, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>window.opener=window;\nwindow.close();\n</code></pre>\n" }, { "answer_id": 1412097, "author": "Nick", "author_id": 56256, "author_profile": "https://Stackoverflow.com/users/56256", "pm_score": 6, "selected": false, "text": "<p>My friend... there is a way but \"hack\" does not begin to describe it. You have to basically exploit a bug in IE 6 &amp; 7. </p>\n\n<p>Works every time!</p>\n\n<p>Instead of calling <code>window.close()</code>, redirect to another page. </p>\n\n<p>Opening Page:</p>\n\n<pre><code>alert(\"No whammies!\");\nwindow.open(\"closer.htm\", '_self');\n</code></pre>\n\n<p>Redirect to another page. This fools IE into letting you close the browser on this page. </p>\n\n<p>Closing Page:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n window.close();\n&lt;/script&gt;\n</code></pre>\n\n<p>Awesome huh?!</p>\n" }, { "answer_id": 2730590, "author": "Arabam", "author_id": 326958, "author_profile": "https://Stackoverflow.com/users/326958", "pm_score": 6, "selected": false, "text": "<pre><code>window.open('', '_self', ''); window.close();\n</code></pre>\n\n<p>This works for me.</p>\n" }, { "answer_id": 4432315, "author": "JimB", "author_id": 256960, "author_profile": "https://Stackoverflow.com/users/256960", "pm_score": 4, "selected": false, "text": "<p>In the body tag:</p>\n\n<pre><code>&lt;body onload=\"window.open('', '_self', '');\"&gt;\n</code></pre>\n\n<p>To close the window:</p>\n\n<pre><code>&lt;a href=\"javascript:window.close();\"&gt;\n</code></pre>\n\n<p>Tested on Safari 4.0.5, FF for Mac 3.6, IE 8.0, and FF for Windows 3.5</p>\n" }, { "answer_id": 7262745, "author": "jbabey", "author_id": 386152, "author_profile": "https://Stackoverflow.com/users/386152", "pm_score": 3, "selected": false, "text": "<p>For security reasons, a window can only be closed in JavaScript if it was opened by JavaScript. In order to close the window, you must open a new window with <code>_self</code> as the target, which will overwrite your current window, and then close that one (which you can do since it was opened via JavaScript).</p>\n\n<pre><code>window.open('', '_self', '');\nwindow.close();\n</code></pre>\n" }, { "answer_id": 13914234, "author": "Niloofar", "author_id": 1814925, "author_profile": "https://Stackoverflow.com/users/1814925", "pm_score": 2, "selected": false, "text": "<p>Create a JavaScript function</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n function closeme() {\n window.open('', '_self', '');\n window.close();\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>Now write this code and call the above JavaScript function</p>\n\n<pre><code>&lt;a href=\"Help.aspx\" target=\"_blank\" onclick=\"closeme();\"&gt;Help&lt;/a&gt;\n</code></pre>\n\n<p>Or simply:</p>\n\n<pre><code>&lt;a href=\"\" onclick=\"closeme();\"&gt;close&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 15917784, "author": "Danny Beckett", "author_id": 1563422, "author_profile": "https://Stackoverflow.com/users/1563422", "pm_score": 4, "selected": false, "text": "<p>This works in Chrome 26, Internet Explorer 9 and Safari 5.1.7 (<strong>without</strong> the use of a helper page, ala Nick's answer):</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n window.open('javascript:window.open(\"\", \"_self\", \"\");window.close();', '_self');\n&lt;/script&gt;\n</code></pre>\n\n<p>The nested <code>window.open</code> is to make IE not display the <em>Do you want to close this window</em> prompt.</p>\n\n<p>Unfortunately it is impossible to get Firefox to close the window.</p>\n" }, { "answer_id": 16412945, "author": "Kuldip D Gandhi", "author_id": 2357159, "author_profile": "https://Stackoverflow.com/users/2357159", "pm_score": 5, "selected": false, "text": "<p>Here is Javascript function which I use to close browser without Prompt or Warning, it can also be called from Flash.\nIt should be in html file.</p>\n\n<pre><code> function closeWindows() {\n var browserName = navigator.appName;\n var browserVer = parseInt(navigator.appVersion);\n //alert(browserName + \" : \"+browserVer);\n\n //document.getElementById(\"flashContent\").innerHTML = \"&lt;br&gt;&amp;nbsp;&lt;font face='Arial' color='blue' size='2'&gt;&lt;b&gt; You have been logged out of the Game. Please Close Your Browser Window.&lt;/b&gt;&lt;/font&gt;\";\n\n if(browserName == \"Microsoft Internet Explorer\"){\n var ie7 = (document.all &amp;&amp; !window.opera &amp;&amp; window.XMLHttpRequest) ? true : false; \n if (ie7)\n { \n //This method is required to close a window without any prompt for IE7 &amp; greater versions.\n window.open('','_parent','');\n window.close();\n }\n else\n {\n //This method is required to close a window without any prompt for IE6\n this.focus();\n self.opener = this;\n self.close();\n }\n }else{ \n //For NON-IE Browsers except Firefox which doesnt support Auto Close\n try{\n this.focus();\n self.opener = this;\n self.close();\n }\n catch(e){\n\n }\n\n try{\n window.open('','_self','');\n window.close();\n }\n catch(e){\n\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 18863981, "author": "Vivek", "author_id": 2373500, "author_profile": "https://Stackoverflow.com/users/2373500", "pm_score": 3, "selected": false, "text": "<p>Because of the security enhancements in IE, you can't close a window unless it is opened by a script. So the way around this will be to let the browser think that this page is opened using a script, and then to close the window. Below is the implementation.</p>\n\n<p>Try this, it works like a charm!<br>\n<strong><em><a href=\"http://www.dotnetbull.com/2011/12/closing-window-without-prompt-in.html\" rel=\"nofollow\">javascript close current window without prompt IE</a></em></strong></p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction closeWP() {\n var Browser = navigator.appName;\n var indexB = Browser.indexOf('Explorer');\n\n if (indexB &gt; 0) {\n var indexV = navigator.userAgent.indexOf('MSIE') + 5;\n var Version = navigator.userAgent.substring(indexV, indexV + 1);\n\n if (Version &gt;= 7) {\n window.open('', '_self', '');\n window.close();\n }\n else if (Version == 6) {\n window.opener = null;\n window.close();\n }\n else {\n window.opener = '';\n window.close();\n }\n\n }\nelse {\n window.close();\n }\n}\n&lt;/script&gt;\n</code></pre>\n\n<h2><a href=\"http://www.dotnetbull.com/2011/12/closing-window-without-prompt-in.html\" rel=\"nofollow\">javascript close current window without prompt IE</a></h2>\n" }, { "answer_id": 24854246, "author": "rvighne", "author_id": 1079573, "author_profile": "https://Stackoverflow.com/users/1079573", "pm_score": 6, "selected": false, "text": "<p>Scripts are <em>not allowed</em> to close a window that a user opened. This is considered a security risk. Though it isn't in any standard, all browser vendors follow this (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window.close\">Mozilla docs</a>). If this happens in some browsers, it's a security bug that (ideally) gets patched very quickly.</p>\n\n<p>None of the hacks in the answers on this question work any longer, and if someone would come up with another dirty hack, eventually it will stop working as well.</p>\n\n<p>I suggest you don't waste energy fighting this and embrace the method that the browser so helpfully gives you &mdash; <em>ask</em> the user before you seemingly crash their page.</p>\n" }, { "answer_id": 26864113, "author": "Kamleshkumar Gujarathi", "author_id": 4239394, "author_profile": "https://Stackoverflow.com/users/4239394", "pm_score": 0, "selected": false, "text": "<p>Place the following code in the ASPX.</p>\n\n<pre><code>&lt;script language=javascript&gt;\nfunction CloseWindow() \n{\n window.open('', '_self', '');\n window.close();\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>Place the following code in the code behind button click event.</p>\n\n<pre><code>string myclosescript = \"&lt;script language='javascript' type='text/javascript'&gt;CloseWindow();&lt;/script&gt;\";\n\nPage.ClientScript.RegisterStartupScript(GetType(), \"myclosescript\", myclosescript);\n</code></pre>\n\n<p>If you dont have any processing before close then you can directly put the following code in the ASPX itself in the button click tag.</p>\n\n<pre><code>OnClientClick=\"CloseWindow();\"\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 33018553, "author": "Logan Hasbrouck", "author_id": 3609893, "author_profile": "https://Stackoverflow.com/users/3609893", "pm_score": -1, "selected": false, "text": "<p>I am going to post this because this is what I am currently using for my site and it works in both Google Chrome and IE 10 without receiving any popup messages:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;/head&gt;\n &lt;body onload=\"window.close();\"&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>I have a function on my site that I want to run to save an on/off variable to session without directly going to a new page so I just open a tiny popup webpage. That webpage then closes itself immediately with the <code>onload=\"window.close();\"</code> function.</p>\n" }, { "answer_id": 35335816, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This will work :</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction closeWindowNoPrompt()\n{\nwindow.open('', '_parent', '');\nwindow.close();\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 43452197, "author": "nurmurat", "author_id": 887620, "author_profile": "https://Stackoverflow.com/users/887620", "pm_score": 1, "selected": false, "text": "<p>In my situation the following code was embedded into a php file.</p>\n\n<pre><code>var PreventExitPop = true;\nfunction ExitPop() {\n if (PreventExitPop != false) {\n return \"Hold your horses! \\n\\nTake the time to reserve your place.Registrations might become paid or closed completely to newcomers!\"\n }\n}\nwindow.onbeforeunload = ExitPop;\n</code></pre>\n\n<p>So I opened the console and write the following </p>\n\n<pre><code>PreventExitPop = false\n</code></pre>\n\n<p>This solved the problem.\nSo, find out the JavaScript code and find the variable(s) and assign them to an appropriate \"value\" which in my case was \"false\"</p>\n" }, { "answer_id": 48854816, "author": "Mada Aryakusumah", "author_id": 1837643, "author_profile": "https://Stackoverflow.com/users/1837643", "pm_score": 3, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>window.open('', '_self', '').close();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Sorry a bit late here, but i found the solution, at least for my case. Tested on Safari 11.0.3 and Google Chrome 64.0.3282.167</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5440/" ]
How can I close a browser window without receiving the *Do you want to close this window* prompt? The prompt occurs when I use the `window.close();` function.
My friend... there is a way but "hack" does not begin to describe it. You have to basically exploit a bug in IE 6 & 7. Works every time! Instead of calling `window.close()`, redirect to another page. Opening Page: ``` alert("No whammies!"); window.open("closer.htm", '_self'); ``` Redirect to another page. This fools IE into letting you close the browser on this page. Closing Page: ``` <script type="text/javascript"> window.close(); </script> ``` Awesome huh?!
57,855
<p>I'm troubleshooting a problem with creating Vista shortcuts.</p> <p>I want to make sure that our Installer is reading the Programs folder from the right registry key.</p> <p>It's reading it from:</p> <pre><code>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Programs </code></pre> <p>And it's showing this directory for Programs:</p> <pre><code>C:\Users\NonAdmin2 UAC OFF\AppData\Roaming\Microsoft\Windows\Start Menu\Programs </code></pre> <p>From what I've read, this seems correct, but I wanted to double check.</p>
[ { "answer_id": 57866, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>Sounds correct to me.</p>\n" }, { "answer_id": 57869, "author": "Tadmas", "author_id": 3750, "author_profile": "https://Stackoverflow.com/users/3750", "pm_score": 2, "selected": false, "text": "<p>Don't use the registry to read this. Use <a href=\"http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx\" rel=\"nofollow noreferrer\">SHGetFolderPath</a> with CSIDL_PROGRAMS.</p>\n\n<p>For a reason why, see Raymond Chen's comments on the \"Shell Folders\" key:</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx</a></p>\n" }, { "answer_id": 57871, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": true, "text": "<p>use windows installer properties. will probably be easier.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa370905(VS.85).aspx#system_folder_properties\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa370905(VS.85).aspx#system_folder_properties</a></p>\n" }, { "answer_id": 57873, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 1, "selected": false, "text": "<p>You should probably use API for this, such as <a href=\"http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx\" rel=\"nofollow noreferrer\">SHGetFolderPath</a></p>\n" }, { "answer_id": 58068, "author": "Clay Nichols", "author_id": 4906, "author_profile": "https://Stackoverflow.com/users/4906", "pm_score": 0, "selected": false, "text": "<p>Example of the SHGetFolderPath in VB\n<a href=\"http://support.microsoft.com/kb/252652\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/252652</a></p>\n" }, { "answer_id": 58261, "author": "Clay Nichols", "author_id": 4906, "author_profile": "https://Stackoverflow.com/users/4906", "pm_score": 0, "selected": false, "text": "<p>Helpful code snippet:</p>\n\n<pre><code>public class Utilities\n{\n\n public enum FolderPaths\n {\n CSIDL_DESKTOP = 0x0000, // &lt;desktop&gt;\n CSIDL_INTERNET = 0x0001, // Internet Explorer (icon on desktop)\n CSIDL_PROGRAMS = 0x0002, // Start Menu\\Programs\n CSIDL_CONTROLS = 0x0003, // My Computer\\Control Panel\n CSIDL_PRINTERS = 0x0004, // My Computer\\Printers\n CSIDL_PERSONAL = 0x0005, // My Documents\n CSIDL_FAVORITES = 0x0006, // &lt;user name&gt;\\Favorites\n CSIDL_STARTUP = 0x0007, // Start Menu\\Programs\\Startup\n CSIDL_RECENT = 0x0008, // &lt;user name&gt;\\Recent\n CSIDL_SENDTO = 0x0009, // &lt;user name&gt;\\SendTo\n CSIDL_BITBUCKET = 0x000a, // &lt;desktop&gt;\\Recycle Bin\n CSIDL_STARTMENU = 0x000b, // &lt;user name&gt;\\Start Menu\n CSIDL_MYDOCUMENTS = CSIDL_PERSONAL, // Personal was just a silly name for My Documents\n CSIDL_MYMUSIC = 0x000d, // \"My Music\" folder\n CSIDL_MYVIDEO = 0x000e, // \"My Videos\" folder\n CSIDL_DESKTOPDIRECTORY = 0x0010, // &lt;user name&gt;\\Desktop\n CSIDL_DRIVES = 0x0011, // My Computer\n CSIDL_NETWORK = 0x0012, // Network Neighborhood (My Network Places)\n CSIDL_NETHOOD = 0x0013, // &lt;user name&gt;\\nethood\n CSIDL_FONTS = 0x0014, // windows\\fonts\n CSIDL_TEMPLATES = 0x0015,\n CSIDL_COMMON_STARTMENU = 0x0016, // All Users\\Start Menu\n CSIDL_COMMON_PROGRAMS = 0X0017, // All Users\\Start Menu\\Programs\n CSIDL_COMMON_STARTUP = 0x0018, // All Users\\Startup\n CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019, // All Users\\Desktop\n CSIDL_APPDATA = 0x001a, // &lt;user name&gt;\\Application Data\n CSIDL_PRINTHOOD = 0x001b, // &lt;user name&gt;\\PrintHood\n CSIDL_LOCAL_APPDATA = 0x001c // &lt;user name&gt;\\Local Settings\\Applicaiton Data (non roaming)\n }\n\n\n [DllImport(\"shfolder.dll\", CharSet = CharSet.Unicode)]\n public static extern int SHGetFolderPath(IntPtr owner, int folder, IntPtr token, int flags, StringBuilder path);\n}\n\nvoid MyFunction()\n{\n StringBuilder path = new StringBuilder(260);\n\n String folderPath = \"\";\n if (0 == Utilities.SHGetFolderPath(IntPtr.Zero, (int) Utilities.FolderPaths.CSIDL_MYVIDEO, IntPtr.Zero, 0, path))\n {\n folderPath = path.ToString();\n }\n\n}\n</code></pre>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906/" ]
I'm troubleshooting a problem with creating Vista shortcuts. I want to make sure that our Installer is reading the Programs folder from the right registry key. It's reading it from: ``` HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Programs ``` And it's showing this directory for Programs: ``` C:\Users\NonAdmin2 UAC OFF\AppData\Roaming\Microsoft\Windows\Start Menu\Programs ``` From what I've read, this seems correct, but I wanted to double check.
use windows installer properties. will probably be easier. <http://msdn.microsoft.com/en-us/library/aa370905(VS.85).aspx#system_folder_properties>
57,912
<p>I'm currently updating a legacy system which allows users to dictate part of the schema of one of its tables. Users can create and remove columns from the table through this interface. This legacy system is using ADO 2.8, and is using SQL Server 2005 as its database (you don't even WANT to know what database it was using before the attempt to modernize this beast began... but I digress. =) )</p> <p>In this same editing process, users can define (and change) a list of valid values that can be stored in these user created fields (if the user wants to limit what can be in the field).</p> <p>When the user changes the list of valid entries for a field, if they remove one of the valid values, they are allowed to choose a new "valid value" to map any rows that have this (now invalid) value in it, so that they now have a valid value again.</p> <p>In looking through the old code, I noticed that it is extremely vulnerable to putting the system into an invalid state, because the changes mentioned above are not done within a transaction (so if someone else came along halfway through the process mentioned above and made their own changes... well, you can imagine the problems that might cause).</p> <p>The problem is, I've been trying to get them to update under a single transaction, but whenever the code gets to the part where it changes the schema of that table, all of the other changes (updating values in rows, be it in the table where the schema changed or not... they can be completely unrelated tables even) made up to that point in the transaction appear to be silently dropped. I receive no error message indicating that they were dropped, and when I commit the transaction at the end no error is raised... but when I go to look in the tables that were supposed to be updated in the transaction, only the new columns are there. None of the non-schema changes made are saved.</p> <p>Looking on the net for answers has, thus far, proved to be a waste of a couple hours... so I turn here for help. Has anyone ever tried to perform a transaction through ADO that both updates the schema of a table and updates rows in tables (be it that same table, or others)? Is it not allowed? Is there any documentation out there that could be helpful in this situation?</p> <p>EDIT:</p> <p>Okay, I did a trace, and these commands were sent to the database (explanations in parenthesis)</p> <p><strong>(I don't know what's happening here, looks like it's creating a temporary stored procedure...?)</strong></p> <pre><code> declare @p1 int set @p1=180150003 declare @p3 int set @p3=2 declare @p4 int set @p4=4 declare @p5 int set @p5=-1 </code></pre> <p><strong>(Retreiving the table that holds definition information for the user-generated fields)</strong></p> <pre><code> exec sp_cursoropen @p1 output,N'SELECT * FROM CustomFieldDefs ORDER BY Sequence',@p3 output,@p4 output,@p5 output select @p1, @p3, @p4, @p5 go </code></pre> <p><strong>(I think my code was iterating through the list of them here, grabbing the current information)</strong></p> <pre><code> exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,1025,1,1 go exec sp_cursorfetch 180150003,1028,1,1 go exec sp_cursorfetch 180150003,32,1,1 go </code></pre> <p><strong>(This appears to be where I'm entering the modified data for the definitions, I go through each and update any changes that occurred in the definitions for the custom fields themselves)</strong></p> <pre><code> exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=1,@Description='asdf',@Format='U|',@IsLookUp=1,@Length=50,@Properties='U|',@Required=1,@Title='__asdf',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=2,@Description='give',@Format='Y',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_give',@Type='B',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=3,@Description='up',@Format='###-##-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_up',@Type='N',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=4,@Description='Testy',@Format='',@IsLookUp=0,@Length=50,@Properties='',@Required=0,@Title='_Testy',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=5,@Description='you',@Format='U|',@IsLookUp=0,@Length=250,@Properties='U|',@Required=0,@Title='_you',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=6,@Description='never',@Format='mm/dd/yyyy',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_never',@Type='D',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=7,@Description='gonna',@Format='###-###-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_gonna',@Type='C',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go </code></pre> <p><strong>(This is where my code removes the deleted through the interface before this saving began]... it is also the ONLY thing as far as I can tell that actually happens during this transaction)</strong> </p> <pre><code> ALTER TABLE CustomizableTable DROP COLUMN _weveknown; </code></pre> <p><strong>(Now if any of the definitions were altered in such a way that the user-created column's properties need to be changed or indexes on the columns need to be added/removed, it is done here, along with giving a default value to any rows that didn't have a value yet for the given column... note that, as far as I can tell, NONE of this actually happens when the stored procedure finishes.)</strong></p> <p><code><pre> go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '__asdf' go ALTER TABLE CustomizableTable ALTER COLUMN __asdf VarChar(50) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF); go select * from IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF); go UPDATE CustomizableTable SET [__asdf] = '' WHERE [__asdf] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_give' go ALTER TABLE CustomizableTable ALTER COLUMN _give Bit NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__give') DROP INDEX idx__give ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_give] = 0 WHERE [_give] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_up' go ALTER TABLE CustomizableTable ALTER COLUMN _up Int NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__up') DROP INDEX idx__up ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_up] = 0 WHERE [_up] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_Testy' go ALTER TABLE CustomizableTable ADD _Testy VarChar(50) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__Testy') DROP INDEX idx__Testy ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_Testy] = '' WHERE [_Testy] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_you' go ALTER TABLE CustomizableTable ALTER COLUMN _you VarChar(250) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__you') DROP INDEX idx__you ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_you] = '' WHERE [_you] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_never' go ALTER TABLE CustomizableTable ALTER COLUMN _never DateTime NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__never') DROP INDEX idx__never ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_never] = '1/1/1900' WHERE [_never] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_gonna' go ALTER TABLE CustomizableTable ALTER COLUMN _gonna Money NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__gonna') DROP INDEX idx__gonna ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_gonna] = 0 WHERE [_gonna] IS NULL go </pre></code></p> <p><strong>(Closing the Transaction...?)</strong></p> <p><code><pre> exec sp_cursorclose 180150003 go </pre></code></p> <p>After all that ado above, only the deletion of the column occurs. Everything before and after it in the transaction appears to be ignored, and there were no messages in the SQL Trace to indicate that something went wrong during the transaction.</p>
[ { "answer_id": 57922, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 0, "selected": false, "text": "<p>The behavior you describe is allowed. How is the code making the schema changes? Building SQL on the fly and executing through an ADO Command? Or using ADOX?</p>\n\n<p>If you have access to the database server, try running a SQL Profiler trace while testing the scenario you outlined. See if the trace logs any errors/rollbacks.</p>\n" }, { "answer_id": 58188, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": true, "text": "<p>The code is using a server-side cursor, that's what those calls are for. The first set of calls is preparing/opening the cursor. Then fetching rows from the cursor. Finally closing the cursor. Those sprocs are analogous to the OPEN CURSOR, FETCH NEXT, CLOSE CURSOR T-SQL statements.</p>\n\n<p>I'd have to take a closer look (which I will), but my guess is there is something going on with the server-side cursor, the encapsulating transaction, and the DDL.</p>\n\n<p>Some more questions:</p>\n\n<ol>\n<li>Are you meaning to use server-side cursors in this case?</li>\n<li>Are the ADO Commands all using the same active connection?</li>\n</ol>\n\n<p><strong>Update:</strong></p>\n\n<p>I'm not exactly sure what's going on.</p>\n\n<p>It looks like you're using server-side cursors so you can use Recordset.Update() to push changes back to the server, in addition to executing generated SQL statements to alter schema and update data in the dynamic table(s). Using the same connection, inside an explicit transaction.</p>\n\n<p>I'm not sure what effect the cursor operations will have on the rest of the transaction, or vice-versa, and to be honest I'm surprised this isn't working.</p>\n\n<p>I don't know how large of a change it would be, but I would recommend moving away from the server-side cursors and building the UPDATE statements for your table updates.</p>\n\n<p>Sorry I couldn't be of more help.</p>\n\n<p>BTW- I found the following information on the sp_cursor calls:</p>\n\n<p><a href=\"http://jtds.sourceforge.net/apiCursors.html\" rel=\"nofollow noreferrer\">http://jtds.sourceforge.net/apiCursors.html</a></p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3068/" ]
I'm currently updating a legacy system which allows users to dictate part of the schema of one of its tables. Users can create and remove columns from the table through this interface. This legacy system is using ADO 2.8, and is using SQL Server 2005 as its database (you don't even WANT to know what database it was using before the attempt to modernize this beast began... but I digress. =) ) In this same editing process, users can define (and change) a list of valid values that can be stored in these user created fields (if the user wants to limit what can be in the field). When the user changes the list of valid entries for a field, if they remove one of the valid values, they are allowed to choose a new "valid value" to map any rows that have this (now invalid) value in it, so that they now have a valid value again. In looking through the old code, I noticed that it is extremely vulnerable to putting the system into an invalid state, because the changes mentioned above are not done within a transaction (so if someone else came along halfway through the process mentioned above and made their own changes... well, you can imagine the problems that might cause). The problem is, I've been trying to get them to update under a single transaction, but whenever the code gets to the part where it changes the schema of that table, all of the other changes (updating values in rows, be it in the table where the schema changed or not... they can be completely unrelated tables even) made up to that point in the transaction appear to be silently dropped. I receive no error message indicating that they were dropped, and when I commit the transaction at the end no error is raised... but when I go to look in the tables that were supposed to be updated in the transaction, only the new columns are there. None of the non-schema changes made are saved. Looking on the net for answers has, thus far, proved to be a waste of a couple hours... so I turn here for help. Has anyone ever tried to perform a transaction through ADO that both updates the schema of a table and updates rows in tables (be it that same table, or others)? Is it not allowed? Is there any documentation out there that could be helpful in this situation? EDIT: Okay, I did a trace, and these commands were sent to the database (explanations in parenthesis) **(I don't know what's happening here, looks like it's creating a temporary stored procedure...?)** ``` declare @p1 int set @p1=180150003 declare @p3 int set @p3=2 declare @p4 int set @p4=4 declare @p5 int set @p5=-1 ``` **(Retreiving the table that holds definition information for the user-generated fields)** ``` exec sp_cursoropen @p1 output,N'SELECT * FROM CustomFieldDefs ORDER BY Sequence',@p3 output,@p4 output,@p5 output select @p1, @p3, @p4, @p5 go ``` **(I think my code was iterating through the list of them here, grabbing the current information)** ``` exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursorfetch 180150003,1025,1,1 go exec sp_cursorfetch 180150003,1028,1,1 go exec sp_cursorfetch 180150003,32,1,1 go ``` **(This appears to be where I'm entering the modified data for the definitions, I go through each and update any changes that occurred in the definitions for the custom fields themselves)** ``` exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=1,@Description='asdf',@Format='U|',@IsLookUp=1,@Length=50,@Properties='U|',@Required=1,@Title='__asdf',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=2,@Description='give',@Format='Y',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_give',@Type='B',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=3,@Description='up',@Format='###-##-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_up',@Type='N',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=4,@Description='Testy',@Format='',@IsLookUp=0,@Length=50,@Properties='',@Required=0,@Title='_Testy',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=5,@Description='you',@Format='U|',@IsLookUp=0,@Length=250,@Properties='U|',@Required=0,@Title='_you',@Type='',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=6,@Description='never',@Format='mm/dd/yyyy',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_never',@Type='D',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=7,@Description='gonna',@Format='###-###-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_gonna',@Type='C',@_Version=1 go exec sp_cursorfetch 180150003,32,1,1 go ``` **(This is where my code removes the deleted through the interface before this saving began]... it is also the ONLY thing as far as I can tell that actually happens during this transaction)** ``` ALTER TABLE CustomizableTable DROP COLUMN _weveknown; ``` **(Now if any of the definitions were altered in such a way that the user-created column's properties need to be changed or indexes on the columns need to be added/removed, it is done here, along with giving a default value to any rows that didn't have a value yet for the given column... note that, as far as I can tell, NONE of this actually happens when the stored procedure finishes.)** ```` go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '__asdf' go ALTER TABLE CustomizableTable ALTER COLUMN __asdf VarChar(50) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF); go select * from IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF); go UPDATE CustomizableTable SET [__asdf] = '' WHERE [__asdf] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_give' go ALTER TABLE CustomizableTable ALTER COLUMN _give Bit NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__give') DROP INDEX idx__give ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_give] = 0 WHERE [_give] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_up' go ALTER TABLE CustomizableTable ALTER COLUMN _up Int NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__up') DROP INDEX idx__up ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_up] = 0 WHERE [_up] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_Testy' go ALTER TABLE CustomizableTable ADD _Testy VarChar(50) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__Testy') DROP INDEX idx__Testy ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_Testy] = '' WHERE [_Testy] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_you' go ALTER TABLE CustomizableTable ALTER COLUMN _you VarChar(250) NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__you') DROP INDEX idx__you ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_you] = '' WHERE [_you] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_never' go ALTER TABLE CustomizableTable ALTER COLUMN _never DateTime NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__never') DROP INDEX idx__never ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_never] = '1/1/1900' WHERE [_never] IS NULL go SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_gonna' go ALTER TABLE CustomizableTable ALTER COLUMN _gonna Money NULL go IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__gonna') DROP INDEX idx__gonna ON CustomizableTable WITH ( ONLINE = OFF ); go UPDATE CustomizableTable SET [_gonna] = 0 WHERE [_gonna] IS NULL go ```` **(Closing the Transaction...?)** ```` exec sp_cursorclose 180150003 go ```` After all that ado above, only the deletion of the column occurs. Everything before and after it in the transaction appears to be ignored, and there were no messages in the SQL Trace to indicate that something went wrong during the transaction.
The code is using a server-side cursor, that's what those calls are for. The first set of calls is preparing/opening the cursor. Then fetching rows from the cursor. Finally closing the cursor. Those sprocs are analogous to the OPEN CURSOR, FETCH NEXT, CLOSE CURSOR T-SQL statements. I'd have to take a closer look (which I will), but my guess is there is something going on with the server-side cursor, the encapsulating transaction, and the DDL. Some more questions: 1. Are you meaning to use server-side cursors in this case? 2. Are the ADO Commands all using the same active connection? **Update:** I'm not exactly sure what's going on. It looks like you're using server-side cursors so you can use Recordset.Update() to push changes back to the server, in addition to executing generated SQL statements to alter schema and update data in the dynamic table(s). Using the same connection, inside an explicit transaction. I'm not sure what effect the cursor operations will have on the rest of the transaction, or vice-versa, and to be honest I'm surprised this isn't working. I don't know how large of a change it would be, but I would recommend moving away from the server-side cursors and building the UPDATE statements for your table updates. Sorry I couldn't be of more help. BTW- I found the following information on the sp\_cursor calls: <http://jtds.sourceforge.net/apiCursors.html>
57,918
<p>We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner: </p> <pre><code>SELECT * FROM customer WHERE fname LIKE '%someName%' </code></pre> <p>Does full-text indexing help in the scenario? We're using SQL Server 2005.</p>
[ { "answer_id": 57930, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 6, "selected": true, "text": "<p>It will depend upon your DBMS. I believe that most systems will not take advantage of the full-text index unless you use the full-text functions. (e.g. <a href=\"http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html\" rel=\"nofollow noreferrer\">MATCH/AGAINST</a> in mySQL or FREETEXT/CONTAINS in MS SQL)</p>\n<p>Here is two good articles on when, why, and how to use full-text indexing in SQL Server:</p>\n<ol>\n<li><a href=\"https://www.developer.com/database/sql-server-full-text-searching/\" rel=\"nofollow noreferrer\">How To Use SQL Server Full-Text Searching</a></li>\n<li><a href=\"https://www.developer.com/guides/solving-complex-sql-problems-with-full-text-indexing/\" rel=\"nofollow noreferrer\">Solving Complex SQL Problems with Full-Text Indexing</a></li>\n</ol>\n" }, { "answer_id": 57971, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": false, "text": "<p>To answer the question specifically for MSSQL, full-text indexing will <strong>NOT</strong> help in your scenario.</p>\n\n<p>In order to improve that query you could do one of the following:</p>\n\n<ol>\n<li>Configure a full-text catalog on the column and use the CONTAINS() function.</li>\n<li><p>If you were primarily searching with a prefix (i.e. matching from the start of the name), you could change the predicate to the following and create an index over the column.</p>\n\n<p>where fname like 'prefix%'</p></li>\n</ol>\n\n<p>(1) is probably overkill for this, unless the performance of the query is a big problem. </p>\n" }, { "answer_id": 58176, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 5, "selected": false, "text": "<p>FTS <em>can</em> help in this scenario, the question is whether it is worth it or not.</p>\n\n<p>To begin with, let's look at why <code>LIKE</code> may not be the most effective search. When you use <code>LIKE</code>, especially when you are searching with a <code>%</code> at the beginning of your comparison, SQL Server needs to perform both a table scan of every single row <em>and</em> a byte by byte check of the column you are checking.</p>\n\n<p>FTS has some better algorithms for matching data as does some better statistics on variations of names. Therefore FTS can provide better performance for matching Smith, Smythe, Smithers, etc when you look for Smith.</p>\n\n<p>It is, however, a bit more complex to use FTS, as you'll need to master <code>CONTAINS</code> vs <code>FREETEXT</code> and the arcane format of the search. However, if you want to do a search where either FName or LName match, you can do that with one statement instead of an OR.</p>\n\n<p>To determine if FTS is going to be effective, determine how much data you have. I use FTS on a database of several hundred million rows and that's a real benefit over searching with <code>LIKE</code>, but I don't use it on every table.</p>\n\n<p>If your table size is more reasonable, less than a few million, you can get similar speed by creating an index for each column that you're going to be searching on and SQL Server should perform an index scan rather than a table scan.</p>\n" }, { "answer_id": 17368074, "author": "Strinder", "author_id": 752385, "author_profile": "https://Stackoverflow.com/users/752385", "pm_score": 3, "selected": false, "text": "<p>According to my test scenario:</p>\n\n<ul>\n<li>SQL Server 2008</li>\n<li>10.000.000 rows each with a string like \"wordA wordB\nwordC...\" (varies between 1 and 30 words)</li>\n<li>selecting count(*) with CONTAINS(column, \"wordB\")</li>\n<li>result size several hundred thousands</li>\n<li>catalog size approx 1.8GB</li>\n</ul>\n\n<p>Full-text index was in range of 2s whereas <em>like '% wordB %'</em> was in range of 1-2 minutes.</p>\n\n<p><strong>But this counts only if you don't use any additional selection criteria!</strong> E.g. if I used some <em>\"like 'prefix%'\"</em> on a primary key column additionally, the performance was worse since the operation of going into the full-text index costs more than doing a string search in some fields (as long those are not too much). </p>\n\n<p>So I would recommend full-text index <strong>only</strong> in cases where you have to do a \"free string search\" or use some of the special features of it...</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner: ``` SELECT * FROM customer WHERE fname LIKE '%someName%' ``` Does full-text indexing help in the scenario? We're using SQL Server 2005.
It will depend upon your DBMS. I believe that most systems will not take advantage of the full-text index unless you use the full-text functions. (e.g. [MATCH/AGAINST](http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html) in mySQL or FREETEXT/CONTAINS in MS SQL) Here is two good articles on when, why, and how to use full-text indexing in SQL Server: 1. [How To Use SQL Server Full-Text Searching](https://www.developer.com/database/sql-server-full-text-searching/) 2. [Solving Complex SQL Problems with Full-Text Indexing](https://www.developer.com/guides/solving-complex-sql-problems-with-full-text-indexing/)
57,927
<p>I have an excel spreadsheet in a format similar to the following...</p> <pre><code>| NAME | CLUB | STATUS | SCORE | | Fred | a | Gent | 145 | | Bert | a | Gent | 150 | | Harry | a | Gent | 195 | | Jim | a | Gent | 150 | | Clare | a | Lady | 99 | | Simon | a | Junior | 130 | | John | b | Junior | 130 | : : | Henry | z | Gent | 200 | </code></pre> <p>I need to convert this table into a list of the "Top Ten" teams. The rules are</p> <ul> <li>Each team score is taken from the sum of four members of that club.</li> <li>These totals should be of the best four scores except... <ul> <li>Each team must consist of at least one Junior or Lady</li> </ul></li> </ul> <p>For example in the table above the team score for club A would be 625 <strong>not</strong> 640 as you would take the scores for Harry(190), Bert(150), Jim(150), and Simon(130). You could not take Fred's(145) score as that would give you only Gents.</p> <p>My question is, can this be done easily as a series of Excel formula, or will I need to resort to using something more procedural?</p> <p>Ideally the solution needs to be automatic in the team selections, I don't want to have to create separate hand crafted formula for each team. I also will not necessarily have a neatly ordered list of each clubs members. Although I could probably generate the list via an extra calculation sheet.</p>
[ { "answer_id": 57955, "author": "Knox", "author_id": 4873, "author_profile": "https://Stackoverflow.com/users/4873", "pm_score": 0, "selected": false, "text": "<p>Use a pivot table which will act as a database query on the data you have. Pivot so that the teams go down the columns and team members along with their status type go across the pivot table. I'm not sure for 2003, but Excel 2007 lets you then sort so the highest scores appear to the left. Then your first sum can simply take the first three scores for the each team. However to get the last persons sum, you have to determine if you can use the 4th score, or if you have to use the max of the junior or Lady types. That could be done using a complex and brute force formula somewhat like this:</p>\n\n<p>if (type of position 1 is a junior or a lady or ... 2 or 3... ) then use position 4 else if position 5 is a junior or lady then use 5 else if p 6 is ... and so on.</p>\n" }, { "answer_id": 57959, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>Writing a solution in VBA would be my first choice, especially if the rules have the possibility of becoming more complex.</p>\n" }, { "answer_id": 57981, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 0, "selected": false, "text": "<p>I don't think that this can be done unless the table is sorted in some way. Most of Excel's lookup functions require ordered lists. This could certainly be done with a VBA function.</p>\n" }, { "answer_id": 60187, "author": "Dick Kusleika", "author_id": 4280, "author_profile": "https://Stackoverflow.com/users/4280", "pm_score": 3, "selected": true, "text": "<pre><code>Public Function TopTen(Club As String, Scores As Range)\n\n Dim i As Long\n Dim vaScores As Variant\n Dim bLady As Boolean\n Dim lCnt As Long\n Dim lTotal As Long\n\n vaScores = FilterOnClub(Scores.Value, Club)\n vaScores = SortOnScore(vaScores)\n\n For i = LBound(vaScores, 2) To UBound(vaScores, 2)\n If lCnt = 3 And Not bLady Then\n If vaScores(3, i) &lt;&gt; \"Gent\" Then\n lTotal = lTotal + vaScores(4, i)\n bLady = True\n lCnt = lCnt + 1\n End If\n Else\n lTotal = lTotal + vaScores(4, i)\n lCnt = lCnt + 1\n If vaScores(3, i) &lt;&gt; \"Gent\" Then bLady = True\n End If\n\n If lCnt = 4 Then Exit For\n Next i\n\n TopTen = lTotal\n\nEnd Function\n\nPrivate Function FilterOnClub(vaScores As Variant, sClub As String) As Variant\n\n Dim i As Long, j As Long\n Dim aTemp() As Variant\n\n For i = LBound(vaScores, 1) To UBound(vaScores, 1)\n If vaScores(i, 2) = sClub Then\n j = j + 1\n ReDim Preserve aTemp(1 To 4, 1 To j)\n aTemp(1, j) = vaScores(i, 1)\n aTemp(2, j) = vaScores(i, 2)\n aTemp(3, j) = vaScores(i, 3)\n aTemp(4, j) = vaScores(i, 4)\n End If\n Next i\n\n FilterOnClub = aTemp\n\nEnd Function\n\nPrivate Function SortOnScore(vaScores As Variant) As Variant\n\n Dim i As Long, j As Long, k As Long\n Dim aTemp(1 To 4) As Variant\n\n For i = 1 To UBound(vaScores, 2) - 1\n For j = i To UBound(vaScores, 2)\n If vaScores(4, i) &lt; vaScores(4, j) Then\n For k = 1 To 4\n aTemp(k) = vaScores(k, j)\n vaScores(k, j) = vaScores(k, i)\n vaScores(k, i) = aTemp(k)\n Next k\n End If\n Next j\n Next i\n\n SortOnScore = vaScores\n\nEnd Function\n</code></pre>\n\n<p>Use as <code>=TopTen(H2,$B$2:$E$30)</code> where <code>H2</code> contains the club letter.</p>\n" }, { "answer_id": 62187, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>can this be done easily as a series of\n Excel formula</p>\n</blockquote>\n\n<p>Short answer, YES. (Depending on your definition of \"easily\"). </p>\n\n<p>Long answer...</p>\n\n<p>(I <em>think</em> this works)</p>\n\n<p>Here's my (brief) test data:</p>\n\n<pre><code>\n A B C D\n 1 NAME CLUB STATUS SCORE\n 2 Kevin a Gent 145\n 3 Lyle a Gent 150\n 4 Martin a Gent 195\n 5 Norm a Gent 150\n 6 Oonagh a Lady 100\n 7 Arthur b Gent 200\n 8 Brian b Gent 210\n 9 Charlie b Gent 190\n10 Donald b Gent 220\n11 Eddie b Junior 150\n12 Quentin c Gent 145\n13 Ryan c Gent 150\n14 Sheila c Lady 195\n15 Trevor c Gent 150\n16 Ursula c Junior 200\n</code></pre>\n\n<p>Now, if I've understood the rules correctly, we want the best four scores, except that if the highest score by either a lady or a junior is not in the best four, we use that instead of the fourth highest. I've restated it somewhat, for reasons that may become apparent...</p>\n\n<p>OK. Array formulae to the rescue! (I hope)</p>\n\n<p>The highest score from team a should be</p>\n\n<pre><code>{=LARGE(IF(B2:B16=\"a\",D2:D16,0),1)}\n</code></pre>\n\n<p>where the {} indicates an array formula created by using Control-Shift-Enter to input the formula. The top four are similarly created. For the Lady/Junior bit, we need a bit more complexity. Taking the Lady, we need this:</p>\n\n<pre><code>{=LARGE(IF($B$2:$B$16=$J3,IF($C$2:$C$16=\"Lady\",$D$2:$D$16,0),0),1)}\n</code></pre>\n\n<p>Junior may safely be left as an exercise for the student, I hope.</p>\n\n<p>I'm now looking at a table with the following layout for club \"a\"</p>\n\n<pre><code>\n J K L M N O P\n 1 Club 1 2 3 4 Lady Junior\n 2 a 195 150 150 145 100 0\n</code></pre>\n\n<p>The club score should be the top three \"anyone\" scores plus the best lady or junior <em>if they're not already in the top four</em>.</p>\n\n<p>So in Q2 I'm putting this:</p>\n\n<pre><code>=SUM(K2:M2)+MIN(MAX(O2,P2),N2)\n</code></pre>\n\n<p>MAX(O2,P2) tells me the best lady or junior score, which has to be included. If it's higher than the fourth-highest team score, then it's already in the list and we just take the top four. Otherwise, we replace the fourth-highest score with the best lady/junior one.</p>\n\n<p>Now we could do it all in one formula, by substituting the parts into the final formula:</p>\n\n<pre><code>{=LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),1)+\nLARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),2)+\nLARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),3)+\nMIN(LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),4),\nMAX(LARGE(IF($B$2:$B$18=$J3,IF($C$2:$C$18=\"Lady\",$D$2:$D$18,0),0),1),\nLARGE(IF($B$2:$B$18=$J3,IF($C$2:$C$18=\"Junior\",$D$2:$D$18,0),0),1)))}\n</code></pre>\n\n<p>But I don't recommend it...</p>\n\n<p>So for the above data, I end up with this:</p>\n\n<pre><code>\n Anyone Lady Junior \nClub 1 2 3 4 1 1 Total \na 195 150 150 145 100 0 595 \nb 220 210 200 190 0 150 780 \nc 200 195 150 150 195 200 695 \n</code></pre>\n\n<p>Rats. In my excitement at (I think) getting the hard part to work I forgot to mention that</p>\n\n<ul>\n<li>The list of scores can be in any order</li>\n<li>You can get the club rankings with RANK()</li>\n<li>You can then pull the top 10 into another table using MATCH() and INDEX()</li>\n</ul>\n\n<pre><code>\n A B C D E F G H \n1 club Sc Rank UniqRk Pos Club Score\n2 third-equal#1 80 3 79.999980 1 1 best 100 \n3 second 90 2 89.999970 2 2 second 90 \n4 third-equal#2 80 3 79.999960 3 3 third-equal#1 80 \n5 best 100 1 99.999950 4 3 third-equal#2 80 \n6 worst 70 5 69.999940 5 5 worst 70 \n\n</code></pre>\n\n<p>Columns A and B are our calculated scores, column E is the order in which clubs will be output in the final table. The other formulae are as follows:</p>\n\n<pre><code>C: =RANK(B2,$B$2:$B$6) # what it says, with ties both getting the lower number\nD: =B2-ROW()*0.00001 # score, modified slightly to ensure uniqueness\nF: =SMALL($C$2:$C$6,E2) # first output column, ranks including ties\nG: =INDEX($A$2:$A$6,MATCH(LARGE($D$2:$D$6,E2),$D$2:$D$6,0))\n # club name for position, using the modified score in D\nH: =INDEX($B$2:$B$6,MATCH(LARGE($D$2:$D$6,E2),$D$2:$D$6,0))\n # as G, but indexes into scores\n</code></pre>\n" }, { "answer_id": 7410198, "author": "drew", "author_id": 943658, "author_profile": "https://Stackoverflow.com/users/943658", "pm_score": 1, "selected": false, "text": "<p>What I do is lame, but it works. </p>\n\n<p>Just make a new column then insert this formula <code>=If(a1=N,b1,0)</code> where <code>A1</code> is criteria column, <code>N</code> is criteria and <code>B1</code> is in the column that you are trying to get the large from. Then I just do the large formula in another column.</p>\n\n<p>Sometimes I get all fancy and instead of rolling out a <code>N</code>, I will make it say <code>$C$1</code>, then spell out the criteria in that cell.</p>\n\n<p>The perfect answer would be to have Microsoft add in a <code>largeifs</code> (please read this Microsoft)</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3720/" ]
I have an excel spreadsheet in a format similar to the following... ``` | NAME | CLUB | STATUS | SCORE | | Fred | a | Gent | 145 | | Bert | a | Gent | 150 | | Harry | a | Gent | 195 | | Jim | a | Gent | 150 | | Clare | a | Lady | 99 | | Simon | a | Junior | 130 | | John | b | Junior | 130 | : : | Henry | z | Gent | 200 | ``` I need to convert this table into a list of the "Top Ten" teams. The rules are * Each team score is taken from the sum of four members of that club. * These totals should be of the best four scores except... + Each team must consist of at least one Junior or Lady For example in the table above the team score for club A would be 625 **not** 640 as you would take the scores for Harry(190), Bert(150), Jim(150), and Simon(130). You could not take Fred's(145) score as that would give you only Gents. My question is, can this be done easily as a series of Excel formula, or will I need to resort to using something more procedural? Ideally the solution needs to be automatic in the team selections, I don't want to have to create separate hand crafted formula for each team. I also will not necessarily have a neatly ordered list of each clubs members. Although I could probably generate the list via an extra calculation sheet.
``` Public Function TopTen(Club As String, Scores As Range) Dim i As Long Dim vaScores As Variant Dim bLady As Boolean Dim lCnt As Long Dim lTotal As Long vaScores = FilterOnClub(Scores.Value, Club) vaScores = SortOnScore(vaScores) For i = LBound(vaScores, 2) To UBound(vaScores, 2) If lCnt = 3 And Not bLady Then If vaScores(3, i) <> "Gent" Then lTotal = lTotal + vaScores(4, i) bLady = True lCnt = lCnt + 1 End If Else lTotal = lTotal + vaScores(4, i) lCnt = lCnt + 1 If vaScores(3, i) <> "Gent" Then bLady = True End If If lCnt = 4 Then Exit For Next i TopTen = lTotal End Function Private Function FilterOnClub(vaScores As Variant, sClub As String) As Variant Dim i As Long, j As Long Dim aTemp() As Variant For i = LBound(vaScores, 1) To UBound(vaScores, 1) If vaScores(i, 2) = sClub Then j = j + 1 ReDim Preserve aTemp(1 To 4, 1 To j) aTemp(1, j) = vaScores(i, 1) aTemp(2, j) = vaScores(i, 2) aTemp(3, j) = vaScores(i, 3) aTemp(4, j) = vaScores(i, 4) End If Next i FilterOnClub = aTemp End Function Private Function SortOnScore(vaScores As Variant) As Variant Dim i As Long, j As Long, k As Long Dim aTemp(1 To 4) As Variant For i = 1 To UBound(vaScores, 2) - 1 For j = i To UBound(vaScores, 2) If vaScores(4, i) < vaScores(4, j) Then For k = 1 To 4 aTemp(k) = vaScores(k, j) vaScores(k, j) = vaScores(k, i) vaScores(k, i) = aTemp(k) Next k End If Next j Next i SortOnScore = vaScores End Function ``` Use as `=TopTen(H2,$B$2:$E$30)` where `H2` contains the club letter.
57,947
<p>I'm really confused by the various configuration options for .Net configuration of dll's, ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain.</p> <p>So, for example, some of the applications I work with use settings which we access with:</p> <pre><code>string blah = AppLib.Properties.Settings.Default.TemplatePath; </code></pre> <p>Now, this option seems cool because the members are stongly typed, and I won't be able to type in a property name that doesn't exist in the Visual Studio 2005 IDE. We end up with lines like this in the App.Config of a command-line executable project:</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="AppConnectionString" connectionString="XXXX" /&gt; &lt;add name="AppLib.Properties.Settings.AppConnectionString" connectionString="XXXX" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>(If we don't have the second setting, someone releasing a debug dll to the live box could have built with the debug connection string embedded in it - eek)</p> <p>We also have settings accessed like this:</p> <pre><code>string blah = System.Configuration.ConfigurationManager.AppSettings["TemplatePath_PDF"]; </code></pre> <p>Now, these seem cool because we can access the setting from the dll code, or the exe / aspx code, and all we need in the Web or App.config is:</p> <pre><code>&lt;appSettings&gt; &lt;add key="TemplatePath_PDF" value="xxx"/&gt; &lt;/appSettings&gt; </code></pre> <p>However, the value of course may not be set in the config files, or the string name may be mistyped, and so we have a different set of problems.</p> <p>So... if my understanding is correct, the former methods give strong typing but bad sharing of values between the dll and other projects. The latter provides better sharing, but weaker typing.</p> <p>I feel like I must be missing something. For the moment, I'm not even concerned with the application being able to write-back values to the configuration files, encryption or anything like that. Also, I had decided that the best way to store any non-connection strings was in the DB... and then the very next thing that I have to do is store phone numbers to text people in case of DB connection issues, so they must be stored outside the DB!</p>
[ { "answer_id": 57953, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>I think your confusion comes from the fact that it looks like your first example is a home-brewed library, not part of .NET.\nThe configurationmanager example is an example of built-in functionality.</p>\n" }, { "answer_id": 57980, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 2, "selected": false, "text": "<p>If you use the settings tab in VS 2005+, you can add strongly typed settings and get intellisense, such as in your first example.</p>\n\n<pre><code>string phoneNum = Properties.Settings.Default.EmergencyPhoneNumber;\n</code></pre>\n\n<p>This is physically stored in App.Config.</p>\n\n<p>You could still use the config file's appSettings element, or even roll your own ConfigurationElementCollection, ConfigurationElement, and ConfigurationSection subclasses.</p>\n\n<p>As to where to store your settings, database or config file, in the case of non-connection strings: It depends on your application architecture. If you've got an application server that is shared by all the clients, use the aforementioned method, in App.Config on the app server. Otherwise, you may have to use a database. Placing it in the App.Config on each client will cause versioning/deployment headaches.</p>\n" }, { "answer_id": 57993, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<p>I support Rob Grays answer, but wanted to add to it slightly. This may be overly obvious, but if you are using multiple clients, the app.config should store all settings that are installation specific and the database should store pretty much everything else.</p>\n\n<p>Single client (or server) apps are somewhat different. Here it is more personal choice really. A noticable exception would be if the setting is the ID of a record in the database, in which case I would always store the setting <em>in</em> the database with a foreign key to ensure the reference doesn't get deleted.</p>\n" }, { "answer_id": 58020, "author": "Nij", "author_id": 6004, "author_profile": "https://Stackoverflow.com/users/6004", "pm_score": 0, "selected": false, "text": "<p>Yes - I think I / we are in the headache situation Rob descibes - we have something like 5 or 6 different web-sites and applications across three independent servers that need to access the same DB. As things stand, each one has its own Web or App.config with the settings described setting and / or overriding settings in our main DB-access dll library.</p>\n\n<p>Rob - when you say application server, I'm not sure what you mean? The nearest thing I can think is that we could at least share some settings between sites on the same machine by putting them in a web.config higher in the directory hierarchy... but this too is not something I've been able to investigate... having thought it more important to understand which of the strong or weak-typed routes is 'better'.</p>\n" }, { "answer_id": 58206, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 3, "selected": true, "text": "<p>Nij, our difference in thinking comes from our different perspectives. I'm thinking about developing enterprise apps that predominantly use WinForms clients. In this instance the business logic is contained on an application server. Each client would need to know the phone number to dial, but placing it in the App.config of each client poses a problem if that phone number changes. In that case it seems obvious to store application configuration information (or application wide settings) in a database and have each client read the settings from there. </p>\n\n<p>The other, .NET way, (I make the distinction because we have, in the pre .NET days, stored application settings in DB tables) is to store application settings in the app.config file and access via way of the generated Settings class.</p>\n\n<p>I digress. Your situation sounds different. If all different apps are on the same server, you could place the settings in a web.config at a higher level. However if they are not, you could also have a seperate \"configuration service\" that all three applications talk to get their shared settings. At least in this solution you're not replicating the code in three places, raising the potential of maintenance problems when adding settings. Sounds a bit over engineered though.</p>\n\n<p>My personal preference is to use strong typed settings. I actually generate my own strongly typed settings class based on what it's my settings table in the database. That way I can have the best of both worlds. Intellisense to my settings and settings stored in the db (note: that's in the case where there's no app server).</p>\n\n<p>I'm interested in learning other peoples strategies for this too :)</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6004/" ]
I'm really confused by the various configuration options for .Net configuration of dll's, ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain. So, for example, some of the applications I work with use settings which we access with: ``` string blah = AppLib.Properties.Settings.Default.TemplatePath; ``` Now, this option seems cool because the members are stongly typed, and I won't be able to type in a property name that doesn't exist in the Visual Studio 2005 IDE. We end up with lines like this in the App.Config of a command-line executable project: ``` <connectionStrings> <add name="AppConnectionString" connectionString="XXXX" /> <add name="AppLib.Properties.Settings.AppConnectionString" connectionString="XXXX" /> </connectionStrings> ``` (If we don't have the second setting, someone releasing a debug dll to the live box could have built with the debug connection string embedded in it - eek) We also have settings accessed like this: ``` string blah = System.Configuration.ConfigurationManager.AppSettings["TemplatePath_PDF"]; ``` Now, these seem cool because we can access the setting from the dll code, or the exe / aspx code, and all we need in the Web or App.config is: ``` <appSettings> <add key="TemplatePath_PDF" value="xxx"/> </appSettings> ``` However, the value of course may not be set in the config files, or the string name may be mistyped, and so we have a different set of problems. So... if my understanding is correct, the former methods give strong typing but bad sharing of values between the dll and other projects. The latter provides better sharing, but weaker typing. I feel like I must be missing something. For the moment, I'm not even concerned with the application being able to write-back values to the configuration files, encryption or anything like that. Also, I had decided that the best way to store any non-connection strings was in the DB... and then the very next thing that I have to do is store phone numbers to text people in case of DB connection issues, so they must be stored outside the DB!
Nij, our difference in thinking comes from our different perspectives. I'm thinking about developing enterprise apps that predominantly use WinForms clients. In this instance the business logic is contained on an application server. Each client would need to know the phone number to dial, but placing it in the App.config of each client poses a problem if that phone number changes. In that case it seems obvious to store application configuration information (or application wide settings) in a database and have each client read the settings from there. The other, .NET way, (I make the distinction because we have, in the pre .NET days, stored application settings in DB tables) is to store application settings in the app.config file and access via way of the generated Settings class. I digress. Your situation sounds different. If all different apps are on the same server, you could place the settings in a web.config at a higher level. However if they are not, you could also have a seperate "configuration service" that all three applications talk to get their shared settings. At least in this solution you're not replicating the code in three places, raising the potential of maintenance problems when adding settings. Sounds a bit over engineered though. My personal preference is to use strong typed settings. I actually generate my own strongly typed settings class based on what it's my settings table in the database. That way I can have the best of both worlds. Intellisense to my settings and settings stored in the db (note: that's in the case where there's no app server). I'm interested in learning other peoples strategies for this too :)
57,958
<p>I like HtmlControls because there is no HTML magic going on... the asp source looks similar to what the client sees. </p> <p>I can't argue with the utility of GridView, Repeater, CheckBoxLists, etc, so I use them when I need that functionality. </p> <p>Also, it looks weird to have code that mixes and matches:</p> <pre><code>&lt;asp:Button id='btnOK' runat='server' Text='OK' /&gt; &lt;input id='btnCancel' runat='server' type='button' value='Cancel' /&gt; </code></pre> <p>(The above case in the event you wanted to bind a server-side event listener to OK but Cancel just runs a javascript that hides the current div)</p> <p>Is there some definitive style guide out there? Should HtmlControls just be avoided? </p>
[ { "answer_id": 57961, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>well... i wouldn't use an html control if you don't need to do anything on it on the server. i would do</p>\n\n<pre><code>&lt;input id='btnCancel' type='button' value='Cancel' /&gt;\n</code></pre>\n\n<p>fin.</p>\n" }, { "answer_id": 57972, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 2, "selected": false, "text": "<p>In my experience, there's very little difference. As Darren said, if you don't need server-side functionality, HTML controls are probably lower-impact.</p>\n\n<p>And don't forget, you can bolt server-side functionality onto almost any HTML control just by adding a runat=\"server\" directive and an ID to it.</p>\n" }, { "answer_id": 57986, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 4, "selected": true, "text": "<p>It might be useful to think of HTML controls as an option when you want more control over the mark up that ends up getting emitted by your page. More control in the sense that you want EVERY browser to see exactly the same markup.</p>\n\n<p>If you create System.Web.UI.HtmlControls like:</p>\n\n<pre><code>&lt;input id='btnCancel' runat='server' type='button' value='Cancel' /&gt;\n</code></pre>\n\n<p>Then you know what kind of code is going to be emitted. Even though most of the time:</p>\n\n<pre><code>&lt;asp:Button id='btnCancel' runat='server' Text='Cancel' /&gt;\n</code></pre>\n\n<p>will end up being the same markup. The same markup is not always emitted for all WebControls. Many WebControls have built in adaptive rendering that will render different HTML based on the browser user agent. As an example a DataGrid will look quite different in a mobile browser than it will in a desktop browser.</p>\n\n<p>Using WebControls as opposed to HtmlControls also lets you take advantage of <a href=\"http://msdn.microsoft.com/en-us/library/67276kc5.aspx\" rel=\"noreferrer\">ASP.NET v2.0 ControlAdapters</a> which I believe only works with WebControls, this will allow you programatic config driven control over the markup that gets emitted.</p>\n\n<p>This might seem more valuable when you consider that certain mobile browsers or WebTVs are going to want WML or completely different sets of markups.</p>\n" }, { "answer_id": 21155715, "author": "Jai", "author_id": 3070147, "author_profile": "https://Stackoverflow.com/users/3070147", "pm_score": 0, "selected": false, "text": "<p>By adding runat=\"server\" you can get access to any HTML controls in server side..\nand I believe HTML controls are less weight compared to ASP.NET server controls..</p>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4435/" ]
I like HtmlControls because there is no HTML magic going on... the asp source looks similar to what the client sees. I can't argue with the utility of GridView, Repeater, CheckBoxLists, etc, so I use them when I need that functionality. Also, it looks weird to have code that mixes and matches: ``` <asp:Button id='btnOK' runat='server' Text='OK' /> <input id='btnCancel' runat='server' type='button' value='Cancel' /> ``` (The above case in the event you wanted to bind a server-side event listener to OK but Cancel just runs a javascript that hides the current div) Is there some definitive style guide out there? Should HtmlControls just be avoided?
It might be useful to think of HTML controls as an option when you want more control over the mark up that ends up getting emitted by your page. More control in the sense that you want EVERY browser to see exactly the same markup. If you create System.Web.UI.HtmlControls like: ``` <input id='btnCancel' runat='server' type='button' value='Cancel' /> ``` Then you know what kind of code is going to be emitted. Even though most of the time: ``` <asp:Button id='btnCancel' runat='server' Text='Cancel' /> ``` will end up being the same markup. The same markup is not always emitted for all WebControls. Many WebControls have built in adaptive rendering that will render different HTML based on the browser user agent. As an example a DataGrid will look quite different in a mobile browser than it will in a desktop browser. Using WebControls as opposed to HtmlControls also lets you take advantage of [ASP.NET v2.0 ControlAdapters](http://msdn.microsoft.com/en-us/library/67276kc5.aspx) which I believe only works with WebControls, this will allow you programatic config driven control over the markup that gets emitted. This might seem more valuable when you consider that certain mobile browsers or WebTVs are going to want WML or completely different sets of markups.
57,987
<p>Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:</p> <pre><code> OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection); dbCmd.CommandTimeout = mTimeout; results = dbCmd.ExecuteNonQuery(); </code></pre> <p>But I get an OleDbException thrown with message:</p> <blockquote> <p>"Cannot modify the design of table 'test$'. It is in a read-only database."</p> </blockquote> <p>My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?</p>
[ { "answer_id": 58162, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "<p>A couple questions: </p>\n\n<ul>\n<li>Does the user that executes your app (you?) have permission to write to the file? </li>\n<li>Is the file read-only?</li>\n<li>What is your connection string?</li>\n</ul>\n\n<p>If you're using ASP, you'll need to add the IUSER_* user as in <a href=\"http://support.microsoft.com/kb/195951/\" rel=\"nofollow noreferrer\">this example</a>.</p>\n" }, { "answer_id": 59411, "author": "Danielb", "author_id": 39040, "author_profile": "https://Stackoverflow.com/users/39040", "pm_score": 0, "selected": false, "text": "<ul>\n<li>How do I check the permissions for writing to an excel file for my application (I'm using excel 2007)?</li>\n<li>The file is not read only, or protected (to my knowledge).</li>\n<li>My connection String is: </li>\n</ul>\n\n<blockquote>\n <p>\"Provider=Microsoft.Jet.OLEDB.4.0;Data\n Source=fifa_ng_db.xls;Mode=ReadWrite;Extended\n Properties=\\\"Excel\n 8.0;HDR=Yes;IMEX=1\\\"\"</p>\n</blockquote>\n" }, { "answer_id": 184213, "author": "Zorantula", "author_id": 18108, "author_profile": "https://Stackoverflow.com/users/18108", "pm_score": 4, "selected": true, "text": "<p>You need to add <code>ReadOnly=False;</code> to your connection string</p>\n\n<pre><code>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\\\"Excel 8.0;HDR=Yes;IMEX=1\\\";\n</code></pre>\n" }, { "answer_id": 184271, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 0, "selected": false, "text": "<p>Further to Michael Haren's answer. The account you will need to grant Modify permissions to the XLS file will likely be NETWORK SERVICE if this code is running in an ASP.NET application (it's specified in the IIS Application Pool). To find out exactly what account your code is running as, you can do a simple: </p>\n\n<pre><code>Response.Write(Environment.UserDomainName + \"\\\\\" + Environment.UserName);\n</code></pre>\n" }, { "answer_id": 781193, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I was also looking for and answer but Zorantula's solution didn't work for me.\nI found the solution on <a href=\"http://www.cnblogs.com/zwwon/archive/2009/01/09/1372262.html\" rel=\"noreferrer\">http://www.cnblogs.com/zwwon/archive/2009/01/09/1372262.html</a></p>\n\n<p>I removed the <code>ReadOnly=false</code> parameter and the <code>IMEX=1</code> extended property.</p>\n\n<p>The <code>IMEX=1</code> property opens the workbook in import mode, so structure-modifying commands (like <code>CREATE TABLE</code> or <code>DROP TABLE</code>) don't work.</p>\n\n<p>My working connection string is:</p>\n\n<pre><code>\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=workbook.xls;Mode=ReadWrite;Extended Properties=\\\"Excel 8.0;HDR=Yes;\\\";\"\n</code></pre>\n" }, { "answer_id": 976623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was running under ASP.NET, and encountered both \"Cannot modify the design...\" and \"Cannot locate ISAM...\" error messages.</p>\n\n<p>I found that I needed to:</p>\n\n<p><strong>a</strong>) Use the following connection string:</p>\n\n<p><code>Provider=Microsoft.Jet.OLEDB.4.0;Mode=ReadWrite;Extended Properties='Excel 8.0;HDR=Yes;';Data Source=\" + {path to file};</code></p>\n\n<p>Note I too had issues with <code>IMEX=1</code> and with the <code>ReadOnly=false</code> attributes in the connection string.</p>\n\n<p><strong>b</strong>) Grant EVERYONE full permissions to the folder in which the file was being written. Normally, ASP.NET runs under the NETWORK SERVICE account, and that already had permissions. However, the OleDb code is unmanaged, so it must run under some other security context. (I am currently too lazy to figure out which account, so I just used EVERYONE.)</p>\n" }, { "answer_id": 6947980, "author": "Erwin Aarnoudse", "author_id": 879400, "author_profile": "https://Stackoverflow.com/users/879400", "pm_score": 2, "selected": false, "text": "<p>I also had the same problem. Only remove the extended property <code>IMEX=1</code>. That will solve your problem. Your table will be created in your Excel file...</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/57987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39040/" ]
Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following: ``` OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection); dbCmd.CommandTimeout = mTimeout; results = dbCmd.ExecuteNonQuery(); ``` But I get an OleDbException thrown with message: > > "Cannot modify the design of table > 'test$'. It is in a read-only > database." > > > My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?
You need to add `ReadOnly=False;` to your connection string ``` Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"; ```
58,024
<p>I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser.</p> <p>What is the best way to open a URL in the user's default browser from a Windows Forms application?</p>
[ { "answer_id": 58032, "author": "Aaron Wagner", "author_id": 3909, "author_profile": "https://Stackoverflow.com/users/3909", "pm_score": 5, "selected": false, "text": "<pre><code>using System.Diagnostics;\n\nProcess.Start(\"http://www.google.com/\");\n</code></pre>\n\n<p>This approach has worked for me, but I could be missing something important.</p>\n" }, { "answer_id": 58033, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 8, "selected": true, "text": "<p>This <a href=\"http://support.microsoft.com/kb/320478\" rel=\"noreferrer\">article</a> will walk you through it.</p>\n\n<p>Short answer:</p>\n\n<pre><code>ProcessStartInfo sInfo = new ProcessStartInfo(\"http://mysite.com/\"); \nProcess.Start(sInfo);\n</code></pre>\n" }, { "answer_id": 1500956, "author": "Sumrak", "author_id": 19124, "author_profile": "https://Stackoverflow.com/users/19124", "pm_score": 3, "selected": false, "text": "<p>I like approach described <a href=\"http://code.logos.com/blog/2008/01/using_processstart_to_link_to.html\" rel=\"nofollow noreferrer\">here</a>. It takes into account possible exceptions and delays when launching the browser.</p>\n\n<p>For best practice make sure you don't just ignore the exception, but catch it and perform an appropriate action (for example notify user that opening the browser to navigate him to the url failed).</p>\n" }, { "answer_id": 12674404, "author": "ammrin", "author_id": 1711898, "author_profile": "https://Stackoverflow.com/users/1711898", "pm_score": -1, "selected": false, "text": "<p>The above approach is perfect, I would like to recommend this approach to where you can pass your parameters.</p>\n\n<pre><code>Process mypr;\nmypr = Process.Start(\"iexplore.exe\", \"pass the name of website\");\n</code></pre>\n" }, { "answer_id": 18276042, "author": "Rogala", "author_id": 2025711, "author_profile": "https://Stackoverflow.com/users/2025711", "pm_score": 4, "selected": false, "text": "<p>Here is the best of both worlds:</p>\n\n<pre><code>Dim sInfo As New ProcessStartInfo(\"http://www.mysite.com\")\n\nTry\n Process.Start(sInfo)\nCatch ex As Exception\n Process.Start(\"iexplore.exe\", sInfo.FileName)\nEnd Try\n</code></pre>\n\n<p>I found that the answer provided by Blorgbeard will fail when a desktop application is run on a Windows 8 device. To Camillo's point, you should attempt to open this with the user's default browser application, but if the browswer application is not assigned, an unhandled exception will be thrown. </p>\n\n<p>I am posting this as the answer since it handles the exception while still attempting to open the link in the default browser.</p>\n" }, { "answer_id": 62534375, "author": "Daniel", "author_id": 13761054, "author_profile": "https://Stackoverflow.com/users/13761054", "pm_score": 4, "selected": false, "text": "<p>For those getting a &quot;Win32Exception: The System cannot find the file specified&quot;</p>\n<p>This should do the work:</p>\n<pre><code>ProcessStartInfo psInfo = new ProcessStartInfo\n{\n FileName = &quot;https://www.google.com&quot;,\n UseShellExecute = true\n};\nProcess.Start(psInfo);\n</code></pre>\n<p>UseShellExecute is descriped further <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.useshellexecute?view=netcore-3.1\" rel=\"noreferrer\">here</a></p>\n<p>For me the issue was due to the .NET runtime as descriped <a href=\"https://github.com/dotnet/runtime/issues/17938\" rel=\"noreferrer\">here</a></p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148/" ]
I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser. What is the best way to open a URL in the user's default browser from a Windows Forms application?
This [article](http://support.microsoft.com/kb/320478) will walk you through it. Short answer: ``` ProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/"); Process.Start(sInfo); ```
58,054
<p>I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.</p>
[ { "answer_id": 58060, "author": "parkerfath", "author_id": 6027, "author_profile": "https://Stackoverflow.com/users/6027", "pm_score": 7, "selected": true, "text": "<p>Here is a solution I found. It doesn't seem very elegant, though:</p>\n\n<pre><code>&lt;%@ taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %&gt;\n&lt;% pageContext.setAttribute(\"newLineChar\", \"\\n\"); %&gt;\n\n${fn:replace(item.comments, newLineChar, \"; \")}\n</code></pre>\n" }, { "answer_id": 58096, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 2, "selected": false, "text": "<p>You should be able to do it with fn:replace.</p>\n\n<p>You will need to import the tag library into your JSP with the following declaration:</p>\n\n<pre>\n&lt;%@ taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %&gt;\n</pre>\n\n<p>Then you can use the following expression to replace occurrences of newline in ${data} with a semicolon:</p>\n\n<pre>\n${fn:replace(data, \"\\n\", \";\")}\n</pre>\n\n<p>The documentation is not great on this stuff and I have not had the opportunity to test it.</p>\n" }, { "answer_id": 58105, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 0, "selected": false, "text": "<p>You could write your own JSP function to do the replacement.</p>\n\n<p>This means you'd end up with something like:</p>\n\n<pre><code>&lt;%@ taglib prefix=\"ns\" uri=\"...\" %&gt;\n...\n${ns:replace(data)}\n</code></pre>\n\n<p>Where <code>ns</code> is a namespace prefix you define and <code>replace</code> is your JSP function.</p>\n\n<p>These functions are pretty easy to implement (they're just a static method) although I can't seem to find a good reference for writing these at the moment.</p>\n" }, { "answer_id": 58109, "author": "Geekygecko", "author_id": 6009, "author_profile": "https://Stackoverflow.com/users/6009", "pm_score": 2, "selected": false, "text": "<p>You could create your own JSP function. \n<a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags6.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags6.html</a></p>\n\n<p>This is roughly what you need to do.</p>\n\n<p>Create a tag library descriptor file <br/>\n/src/META-INF/sf.tld</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;taglib version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/j2ee\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd\"&gt;\n &lt;tlib-version&gt;1.0&lt;/tlib-version&gt;\n &lt;short-name&gt;sf&lt;/short-name&gt;\n &lt;uri&gt;http://www.stackoverflow.com&lt;/uri&gt;\n &lt;function&gt;\n &lt;name&gt;clean&lt;/name&gt;\n &lt;function-class&gt;com.stackoverflow.web.tag.function.TagUtils&lt;/function-class&gt;\n &lt;function-signature&gt;\n java.lang.String clean(java.lang.String)\n &lt;/function-signature&gt;\n &lt;/function&gt;\n&lt;/taglib&gt;\n</code></pre>\n\n<p>Create a Java class for the functions logic.<br/>\ncom.stackoverflow.web.tag.function.TagUtils</p>\n\n<pre><code>package com.stackoverflow.web.tag.function;\n\nimport javax.servlet.jsp.tagext.TagSupport;\n\npublic class TagUtils extends TagSupport {\n public static String clean(String comment) {\n return comment.replaceAll(\"\\n\", \"; \");\n }\n}\n</code></pre>\n\n<p>In your JSP you can access your function in the following way.</p>\n\n<pre><code>&lt;%@ taglib prefix=\"sf\" uri=\"http://www.stackoverflow.com\"%&gt;\n${sf:clean(item.comments)}\n</code></pre>\n" }, { "answer_id": 539976, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In the value while setting the var, press ENTER between the double quotes.</p>\n\n<p></p>\n\n<p>${fn:replace(data, newLineChar, \";\")}</p>\n" }, { "answer_id": 733909, "author": "bousch", "author_id": 89037, "author_profile": "https://Stackoverflow.com/users/89037", "pm_score": 3, "selected": false, "text": "<p>This solution is more elegant than your own solution which is setting the pagecontext attribute directly. You should use the <code>&lt;c:set&gt;</code> tag for this:</p>\n\n<pre><code>&lt;%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %&gt;\n&lt;%@ taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %&gt;\n\n&lt;c:set var=\"newLine\" value=\"\\n\"/&gt;\n${fn:replace(data, newLine, \"; \")}\n</code></pre>\n\n<p>BTW: <code>${fn:replace(data, \"\\n\", \";\")}</code> does NOT work.</p>\n" }, { "answer_id": 920681, "author": "Matt", "author_id": 113719, "author_profile": "https://Stackoverflow.com/users/113719", "pm_score": 2, "selected": false, "text": "<p>\\n does not represent the newline character in an EL expression.</p>\n\n<p>The solution which sets a <code>pageContext</code> attribute to the newline character and then uses it with JSTL's <code>fn:replace</code> function does work.</p>\n\n<p>However, I prefer to use the Jakarta String Tab Library to solve this problem:</p>\n\n<pre><code>&lt;%@ taglib prefix=\"str\" uri=\"http://jakarta.apache.org/taglibs/string-1.1\" %&gt;\n...\n&lt;str:replace var=\"result\" replace=\"~n\" with=\";\" newlineToken=\"~n\"&gt;\nText containing newlines\n&lt;/str:replace&gt;\n...\n</code></pre>\n\n<p>You can use whatever you want for the newlineToken; \"~n\" is unlikely to show up in the text I'm doing the replacement on, so it was a reasonable choice for me.</p>\n" }, { "answer_id": 1690888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This does not work for me:</p>\n\n<pre><code>&lt;c:set var=\"newline\" value=\"\\n\"/&gt;\n${fn:replace(data, newLine, \"; \")}\n</code></pre>\n\n<p>This does:</p>\n\n<pre><code>&lt;% pageContext.setAttribute(\"newLineChar\", \"\\n\"); %&gt; \n${fn:replace(item.comments, newLineChar, \"; \")}\n</code></pre>\n" }, { "answer_id": 1690942, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 4, "selected": false, "text": "<p>Just use <code>fn:replace()</code> function to replace <code>\\n</code> by <code>;</code>.</p>\n\n<pre><code>${fn:replace(data, '\\n', ';')}\n</code></pre>\n\n<p>In case you're using Apache's EL implementation instead of Oracle's EL reference implementation (i.e. when you're using Tomcat, TomEE, JBoss, etc instead of GlassFish, Payara, WildFly, WebSphere, etc), then you need to re-escape the backslash.</p>\n\n<pre><code>${fn:replace(data, '\\\\n', ';')}\n</code></pre>\n" }, { "answer_id": 2554822, "author": "wheresrhys", "author_id": 87739, "author_profile": "https://Stackoverflow.com/users/87739", "pm_score": 0, "selected": false, "text": "<p>For the record, I came across this post while tackling this problem: </p>\n\n<p>A multi-line string in JSTL gets added as the title attribute of a textarea. Javascript then adds this as the default text of the textarea. In order to clear this text on focus the value needs to equal the title... but fails as many text-editors put \\r\\n instead of \\n. So the follownig will get rid of the unwanted \\r:</p>\n\n<pre><code>&lt;% pageContext.setAttribute(\"newLineChar\", \"\\r\"); %&gt; \n&lt;c:set var=\"textAreaDefault\" value=\"${fn:replace(textAreaDefault, newLineChar, '')}\" /&gt;\n</code></pre>\n" }, { "answer_id": 4044412, "author": "brunohop", "author_id": 490275, "author_profile": "https://Stackoverflow.com/users/490275", "pm_score": 1, "selected": false, "text": "<p>More easily:</p>\n\n<pre><code>&lt;str:replace var=\"your_Var_replaced\" replace=\"\\n\" with=\"Your ney caracter\" newlineToken=\"\\n\"&gt;${your_Var_to_replaced}&lt;/str:replace&gt; \n</code></pre>\n" }, { "answer_id": 6960566, "author": "Leonid", "author_id": 264834, "author_profile": "https://Stackoverflow.com/users/264834", "pm_score": 2, "selected": false, "text": "<p>If what you really need is a \\n symbol you can use the advice from <a href=\"http://www.coderanch.com/t/283187/JSP/java/New-Line-character-JSTL-set#1298039\" rel=\"nofollow\">here</a>:</p>\n\n<pre><code>${fn:replace(text, \"\n\", \"&lt;br/&gt;\")}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;c:set var=\"nl\" value=\"\n\" /&gt;&lt;%-- this is a new line --%&gt;\n</code></pre>\n\n<p>This includes the new line in your string literal.</p>\n" }, { "answer_id": 7124466, "author": "andy", "author_id": 846977, "author_profile": "https://Stackoverflow.com/users/846977", "pm_score": 4, "selected": false, "text": "<p>This is similar to the accepted answer (because it is using Java to represent the newline rather than EL) but here the &lt;c:set/&gt; element is used to set the attribute:</p>\n\n<pre><code>&lt;c:set var=\"newline\" value=\"&lt;%= \\\"\\n\\\" %&gt;\" /&gt;\n${fn:replace(myAddress, newline, \"&lt;br /&gt;\")}\n</code></pre>\n\n<p>The following snippet also works, but the second line of the &lt;c:set/&gt; element cannot be indented (and may look uglier):</p>\n\n<pre><code> &lt;c:set var=\"newline\" value=\"\n\" /&gt;&lt;!--this line can't be indented --&gt;\n ${fn:replace(myAddress, newline, \"&lt;br /&gt;\")}\n</code></pre>\n" }, { "answer_id": 31520021, "author": "Thomas Meyer", "author_id": 5135628, "author_profile": "https://Stackoverflow.com/users/5135628", "pm_score": 2, "selected": false, "text": "<p>This is a valid solution for the JSP EL:</p>\n\n<pre><code>\"${fn:split(string1, Character.valueOf(10))}\"\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027/" ]
I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.
Here is a solution I found. It doesn't seem very elegant, though: ``` <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <% pageContext.setAttribute("newLineChar", "\n"); %> ${fn:replace(item.comments, newLineChar, "; ")} ```
58,070
<p>I remember back when MS released a forum sample application, the design of the application was like this:</p> <p>/Classes/User.cs /Classes/Post.cs ... /Users.cs /Posts.cs</p> <p>So the classes folder had just the class i.e. properties and getters/setters. The Users.cs, Post.cs, etc. have the actual methods that access the Data Access Layer, so Posts.cs might look like:</p> <pre><code>public class Posts { public static Post GetPostByID(int postID) { SqlDataProvider dp = new SqlDataProvider(); return dp.GetPostByID(postID); } } </code></pre> <p>Another more traditional route would be to put all of the methods in Posts.cs into the class definition also (Post.cs).</p> <p>Splitting things into 2 files makes it much more procedural doesn't it? Isn't this breaking OOP rules since it is taking the behavior out of the class and putting it into another class definition?</p>
[ { "answer_id": 58080, "author": "Eric Haskins", "author_id": 100, "author_profile": "https://Stackoverflow.com/users/100", "pm_score": 0, "selected": false, "text": "<p>Are you sure the classes aren't partial classes. In which case they really aren't two classes, just a single class spread across multiple files for better readability.</p>\n" }, { "answer_id": 58082, "author": "SkunkSpinner", "author_id": 5592, "author_profile": "https://Stackoverflow.com/users/5592", "pm_score": 0, "selected": false, "text": "<p>Based on your code snippet, <strong>Posts</strong> is primarily a class of static helper methods. <strong>Posts</strong> is not the same object as <strong>Post</strong>. Instead of <strong>Posts</strong>, a better name might be <strong>PostManager</strong> or <strong>PostHelper</strong>. If you think of it that way, it may help you understand why they broke it out that way.</p>\n" }, { "answer_id": 58085, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<p>This is also an important step for a decoupling (or loosely coupling) you applications.</p>\n" }, { "answer_id": 58087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What's anti-OOP or pro-OOP depends entirely on the functionality of the software and what's needed to make it work.</p>\n" }, { "answer_id": 58091, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 3, "selected": true, "text": "<p>If every method is just a static call straight to the data source, then the \"Posts\" class is really a Factory. You could certainly put the static methods in \"Posts\" into the \"Post\" class (this is how CSLA works), but they are still factory methods.</p>\n\n<p>I would say that a more modern and accurate name for the \"Posts\" class would be \"PostFactory\" (assuming that all it has is static methods).</p>\n\n<p>I guess I wouldn't say this is a \"procedural\" approach necessarily -- it's just a misleading name, you would assume in the modern OO world that a \"Posts\" object would be stateful and provide methods to manipulate and manage a set of \"Post\" objects.</p>\n" }, { "answer_id": 58094, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 1, "selected": false, "text": "<p>Well it depends where and how you define your separation of concerns. If you put the code to populate the Post in the Post class, then your Business Layer is interceded with Data Access Code, and vice versa. </p>\n\n<p>To me it makes sense to do the data fetching and populating outside the actual domain object, and let the domain object be responsible for using the data.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I remember back when MS released a forum sample application, the design of the application was like this: /Classes/User.cs /Classes/Post.cs ... /Users.cs /Posts.cs So the classes folder had just the class i.e. properties and getters/setters. The Users.cs, Post.cs, etc. have the actual methods that access the Data Access Layer, so Posts.cs might look like: ``` public class Posts { public static Post GetPostByID(int postID) { SqlDataProvider dp = new SqlDataProvider(); return dp.GetPostByID(postID); } } ``` Another more traditional route would be to put all of the methods in Posts.cs into the class definition also (Post.cs). Splitting things into 2 files makes it much more procedural doesn't it? Isn't this breaking OOP rules since it is taking the behavior out of the class and putting it into another class definition?
If every method is just a static call straight to the data source, then the "Posts" class is really a Factory. You could certainly put the static methods in "Posts" into the "Post" class (this is how CSLA works), but they are still factory methods. I would say that a more modern and accurate name for the "Posts" class would be "PostFactory" (assuming that all it has is static methods). I guess I wouldn't say this is a "procedural" approach necessarily -- it's just a misleading name, you would assume in the modern OO world that a "Posts" object would be stateful and provide methods to manipulate and manage a set of "Post" objects.
58,119
<p>I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? </p>
[ { "answer_id": 58129, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": true, "text": "<p>Well, <code>re.compile</code> certainly may:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.compile('he(lo')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"C:\\Python25\\lib\\re.py\", line 180, in compile\n return _compile(pattern, flags)\n File \"C:\\Python25\\lib\\re.py\", line 233, in _compile\n raise error, v # invalid expression\nsre_constants.error: unbalanced parenthesis\n</code></pre>\n\n<p><a href=\"https://web.archive.org/web/20080913142948/http://docs.python.org/lib/node46.html\" rel=\"nofollow noreferrer\">The documentation</a> does support this, in a roundabout way - check the bottom of the \"Module Contents\" page for (brief) description of the <code>error</code> exception.</p>\n\n<p>Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to <a href=\"https://web.archive.org/web/20081004235506/http://www.depython.net/\" rel=\"nofollow noreferrer\">decompile</a> them (if written in Python) or even <a href=\"http://www.python.org/download/\" rel=\"nofollow noreferrer\">look at the source</a>, if they're in the standard library.</p>\n" }, { "answer_id": 58168, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 3, "selected": false, "text": "<p>Unlike Java, where there are exceptions that must be declared to be raised (and some that don't have to be, but that's another story), any Python code may raise any exception at any time.</p>\n\n<p>There are a list of <a href=\"https://docs.python.org/2.7/library/exceptions.html\" rel=\"nofollow noreferrer\">built-in exceptions</a>, which generally has some description of when these exceptions might be raised. Its up to you as to how much exception handling you will do, and if you will handle stuff gracefully, or just fail with a traceback.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are?
Well, `re.compile` certainly may: ``` >>> import re >>> re.compile('he(lo') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python25\lib\re.py", line 180, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 233, in _compile raise error, v # invalid expression sre_constants.error: unbalanced parenthesis ``` [The documentation](https://web.archive.org/web/20080913142948/http://docs.python.org/lib/node46.html) does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the `error` exception. Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to [decompile](https://web.archive.org/web/20081004235506/http://www.depython.net/) them (if written in Python) or even [look at the source](http://www.python.org/download/), if they're in the standard library.
58,123
<p>This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object?</p> <p>And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface:</p> <pre><code>private IWebBase FindWebBase() { if (HttpContext.Current as IWebBase != null) { return (IWebBase)HttpContext.Current.; } throw new NotImplementedException("Crawling for IWebBase not implemented yet"); } </code></pre> <p>The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework.</p> <p>I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work.</p> <p>The compiler error is: Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion.</p>
[ { "answer_id": 58128, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 5, "selected": false, "text": "<p>You're looking for <code>HttpContext.Handler</code>. Since Page implements IHttpHandler, you'll obtain a reference to the currently executing page.You'll have to cast it, or at least try to cast it to the particular type you're looking for. </p>\n\n<p><code>HttpContext.Current</code> simply returns the singleton instance of HttpContext. Therefore, it is not and can never be, a page.</p>\n" }, { "answer_id": 58131, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 8, "selected": true, "text": "<p>No, from MSDN on HttpContext.Current: \"Gets or sets the HttpContext object for the current HTTP request.\" </p>\n\n<p>In other words it is an HttpContext object, not a Page.</p>\n\n<p>You can get to the Page object via HttpContext using:</p>\n\n<pre><code>Page page = HttpContext.Current.Handler as Page;\n\nif (page != null)\n{\n // Use page instance.\n}\n</code></pre>\n" }, { "answer_id": 6617694, "author": "user452427", "author_id": 452427, "author_profile": "https://Stackoverflow.com/users/452427", "pm_score": 4, "selected": false, "text": "<p>You may want to use <code>HttpContext.Current.CurrentHandler</code> if you want the precise page that is currently executing. For example, a request for Default.aspx is sent, but an error is thrown and you do a <code>Response.Transfer</code> to your custom ErrorHandler.aspx page. <code>CurrentHandler</code> will return the instance of ErrorHandler.aspx (if called after the error) whereas <code>HttpContext.Current.Handler</code> would return an instance of Default.aspx.</p>\n" }, { "answer_id": 17983443, "author": "Amin Ghaderi", "author_id": 1395101, "author_profile": "https://Stackoverflow.com/users/1395101", "pm_score": 0, "selected": false, "text": "<p>Please see my answer : <br/>\n<a href=\"https://stackoverflow.com/questions/1054123/why-httpcontext-current-handler-is-null\">Why HttpContext.Current.Handler is null?</a>\n<br/><br/>\nMaybe resolved your problem.<br/></p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1685/" ]
This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object? And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface: ``` private IWebBase FindWebBase() { if (HttpContext.Current as IWebBase != null) { return (IWebBase)HttpContext.Current.; } throw new NotImplementedException("Crawling for IWebBase not implemented yet"); } ``` The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework. I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work. The compiler error is: Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion.
No, from MSDN on HttpContext.Current: "Gets or sets the HttpContext object for the current HTTP request." In other words it is an HttpContext object, not a Page. You can get to the Page object via HttpContext using: ``` Page page = HttpContext.Current.Handler as Page; if (page != null) { // Use page instance. } ```
58,207
<p>To create a playlist for all of the music in a folder, I am using the following command in bash:</p> <pre><code>ls &gt; list.txt </code></pre> <p>I would like to use the result of the <code>pwd</code> command for the name of the playlist.</p> <p>Something like:</p> <pre><code>ls &gt; ${pwd}.txt </code></pre> <p>That doesn't work though - can anyone tell me what syntax I need to use to do something like this?</p> <p><strong>Edit:</strong> As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!</p>
[ { "answer_id": 58212, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 8, "selected": true, "text": "<p>The best way to do this is with <code>\"$(command substitution)\"</code> (thanks, <a href=\"https://stackoverflow.com/a/58233/1899640\">Landon</a>):</p>\n\n<pre><code>ls &gt; \"$(pwd).txt\"\n</code></pre>\n\n<p>You will sometimes also see people use the older backtick notation, but this has <a href=\"https://stackoverflow.com/questions/4708549/what-is-the-difference-between-command-and-command-in-shell-programming\">several drawbacks</a> in terms of nesting and escaping:</p>\n\n<pre><code>ls &gt; \"`pwd`.txt\"\n</code></pre>\n\n<p>Note that the unprocessed substitution of <code>pwd</code> is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a <code>.txt</code> extension. Thomas Kammeyer pointed out that the <code>basename</code> command strips the leading directory, so this would create a text file in the current directory with the name of that directory:</p>\n\n<pre><code>ls &gt; \"$(basename \"$(pwd)\").txt\"\n</code></pre>\n\n<p>Also thanks to erichui for bringing up the problem of spaces in the path.</p>\n" }, { "answer_id": 58214, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 2, "selected": false, "text": "<p>The syntax is:</p>\n\n<pre><code>ls &gt; `pwd`.txt\n</code></pre>\n\n<p>That is the '`' character up underneath the '~', not the regular single quote.</p>\n" }, { "answer_id": 58224, "author": "Thomas Kammeyer", "author_id": 4410, "author_profile": "https://Stackoverflow.com/users/4410", "pm_score": 3, "selected": false, "text": "<p>To do literally what you said, you could try:</p>\n\n<pre><code>ls &gt; `pwd`.txt\n</code></pre>\n\n<p>which will use the full pathname, which should be fine.\nNote that if you do this in your home directory, which might\nbe in /home/hoboben, you will be trying the create /home/hoboben.txt,\na text file in the directory above.</p>\n\n<p>Is this what you wanted?</p>\n\n<p>If you wanted the directory to contain a file named after it, you would get\nthe basename of the current directory and append that with .txt to the pwd.</p>\n\n<p>Now, rather than use the pwd command... why not use the PWD environment variable?</p>\n\n<p>For example:</p>\n\n<pre><code>ls &gt; $PWD.txt\n</code></pre>\n\n<p>or</p>\n\n<pre><code>ls &gt; ${PWD}.txt\n</code></pre>\n\n<p>is probably what you were trying to remember with your second example.</p>\n\n<p>If you're in /home/hoboben and you want to create /home/hoboben/hoboben.txt, try:</p>\n\n<pre><code>ls &gt; ${PWD}/${PWD##*/}.txt\n</code></pre>\n\n<p>If you do this, the file will contain its own name, so most often, you would remedy this in one of a few ways. You could redirect to somewhere else and move the file or name the file beginning with a dot to hide it from the ls command as long as you don't use the -a flag (and then optionally rename the resulting file).</p>\n\n<p>I write my own scripts to manage a directory hierarchy of music files and I use subdirectories named \".info\", for example, to contain track data in some spare files (basically, I \"hide\" metadata this way). It works out okay because my needs are simple and my collection small.</p>\n" }, { "answer_id": 58227, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 2, "selected": false, "text": "<p>Using the above method will create the files one level above your current directory. If you want the play lists to all go to one directory you'd need to do something like:</p>\n\n<pre><code>#!/bin/sh\n\nMYVAR=`pwd | sed \"s|/|_|g\"`\nls &gt; /playlistdir/$MYVAR-list.txt\n</code></pre>\n" }, { "answer_id": 58233, "author": "Landon", "author_id": 1597, "author_profile": "https://Stackoverflow.com/users/1597", "pm_score": 3, "selected": false, "text": "<p>This is equivalent to the backtick solution:</p>\n\n<pre><code>ls &gt; $(pwd).txt\n</code></pre>\n" }, { "answer_id": 58235, "author": "erichui", "author_id": 6034, "author_profile": "https://Stackoverflow.com/users/6034", "pm_score": 3, "selected": false, "text": "<p>I suspect the problem may be that there are spaces in one of the directory names. For example, if your working directory is \"/home/user/music/artist name\". Bash will be confused thinking that you are trying to redirect to /home/user/music/artist and name.txt. You can fix this with double quotes</p>\n\n<pre><code>ls &gt; \"$(pwd).txt\"\n</code></pre>\n\n<p>Also, you may not want to redirect to $(pwd).txt. In the example above, you would be redirecting the output to the file \"/home/user/music/artist name.txt\"</p>\n" }, { "answer_id": 9589723, "author": "technosaurus", "author_id": 1162141, "author_profile": "https://Stackoverflow.com/users/1162141", "pm_score": 0, "selected": false, "text": "<p>to strip all but the directory name</p>\n\n<pre><code>ls &gt;/playlistdir/${PWD##/*}.txt\n</code></pre>\n\n<p>this is probably not what you want because then you don't know where the files are (unless you change the ls command)</p>\n\n<p>to replace \"/\" with \"_\"</p>\n\n<pre><code>ls &gt;/playlistdir/${PWD//\\//_}.txt\n</code></pre>\n\n<p>but then the playlist would look ugly and maybe not even fit in the selection window</p>\n\n<p>So this will give you both a short readable name and usable paths inside the file</p>\n\n<pre><code>ext=.mp3 #leave blank for all files\nfor FILE in \"$PWD/*$ext\"; do echo \"$FILE\";done &gt;/playlistdir/${PWD##/*}.txt\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840/" ]
To create a playlist for all of the music in a folder, I am using the following command in bash: ``` ls > list.txt ``` I would like to use the result of the `pwd` command for the name of the playlist. Something like: ``` ls > ${pwd}.txt ``` That doesn't work though - can anyone tell me what syntax I need to use to do something like this? **Edit:** As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!
The best way to do this is with `"$(command substitution)"` (thanks, [Landon](https://stackoverflow.com/a/58233/1899640)): ``` ls > "$(pwd).txt" ``` You will sometimes also see people use the older backtick notation, but this has [several drawbacks](https://stackoverflow.com/questions/4708549/what-is-the-difference-between-command-and-command-in-shell-programming) in terms of nesting and escaping: ``` ls > "`pwd`.txt" ``` Note that the unprocessed substitution of `pwd` is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a `.txt` extension. Thomas Kammeyer pointed out that the `basename` command strips the leading directory, so this would create a text file in the current directory with the name of that directory: ``` ls > "$(basename "$(pwd)").txt" ``` Also thanks to erichui for bringing up the problem of spaces in the path.