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
96,133
<p>I have uncovered another problem in the effort that we are making to port several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. See <a href="https://stackoverflow.com/questions/74372/how-to-overcome-an-incompatibility-between-the-ksh-on-linux-vs-that-installed-o">here</a> for the previous problem.</p> <p>This code:</p> <pre><code>#!/bin/ksh if [ -a k* ]; then echo "Oh yeah!" else echo "No way!" fi exit 0 </code></pre> <p>(when run in a directory with several files whose name starts with k) produces "Oh yeah!" when called with the AT&amp;T ksh variants (ksh88 and ksh93). On the other hand it produces and error message followed by "No way!" on the other ksh variants (pdksh, MKS ksh and bash).</p> <p>Again, my question are: </p> <ul> <li>Is there an environment variable that will cause pdksh to behave like ksh93? Failing that:</li> <li>Is there an option on pdksh to get the required behavior?</li> </ul>
[ { "answer_id": 96857, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 0, "selected": false, "text": "<p>You do realize that [ is an alias (often a link, symbolic or hard) for <code>/usr/bin/test</code>, right? So perhaps the actual problem is different versions of <code>/usr/bin/test</code> ?</p>\n\n<p>OTOH, ksh overrides it with a builtin. Maybe there's a way to get it to not do that? or maybe you can explicitly alias [ to <code>/usr/bin/test</code>, if <code>/usr/bin/test</code> on all platforms is compatible?</p>\n" }, { "answer_id": 389321, "author": "Cyberdrow", "author_id": 44345, "author_profile": "https://Stackoverflow.com/users/44345", "pm_score": 3, "selected": false, "text": "<p>I wouldn't use pdksh on Linux anymore.\nSince AT&amp;T ksh has become OpenSource there are packages available from the various Linux distributions. E.g. RedHat Enterprise Linux and CentOS include ksh93 as the \"ksh\" RPM package.<p>\npdksh is still mentioned in many installation requirement documentations from software vendors. We replaced pdksh on all our Linux systems with ksh93 with no problems so far.</p>\n" }, { "answer_id": 1439358, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 1, "selected": true, "text": "<p>Well after one year there seems to be no solution to my problem.</p>\n\n<p>I am adding this answer to say that I will have to live with it......</p>\n" }, { "answer_id": 2711586, "author": "masta", "author_id": 325609, "author_profile": "https://Stackoverflow.com/users/325609", "pm_score": 0, "selected": false, "text": "<p>in Bash the test -a operation is for a single file.</p>\n\n<p>I'm guessing that in Ksh88 the test -a operation is for a single file, but doesn't complain because the other test words are an unspecified condition to the -a.</p>\n\n<p>you want something like</p>\n\n<pre><code>for K in /etc/rc2.d/K* ; do test -a $K &amp;&amp; echo heck-yea ; done\n</code></pre>\n\n<p>I can say that ksh93 works just like bash in this regard.\nRegrettably I think the code was written poorly, my opinion, and likely a bad opinion since the root cause of the problem is the ksh88 built-in test allowing for sloppy code.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13029/" ]
I have uncovered another problem in the effort that we are making to port several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. See [here](https://stackoverflow.com/questions/74372/how-to-overcome-an-incompatibility-between-the-ksh-on-linux-vs-that-installed-o) for the previous problem. This code: ``` #!/bin/ksh if [ -a k* ]; then echo "Oh yeah!" else echo "No way!" fi exit 0 ``` (when run in a directory with several files whose name starts with k) produces "Oh yeah!" when called with the AT&T ksh variants (ksh88 and ksh93). On the other hand it produces and error message followed by "No way!" on the other ksh variants (pdksh, MKS ksh and bash). Again, my question are: * Is there an environment variable that will cause pdksh to behave like ksh93? Failing that: * Is there an option on pdksh to get the required behavior?
Well after one year there seems to be no solution to my problem. I am adding this answer to say that I will have to live with it......
96,150
<p>I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server <strong>only</strong>. The application works fine on two other servers (development and testing servers).</p> <p>The following code generates an 'Unspecified Error' in the Exception.Message.</p> <p><strong>Quote:</strong></p> <pre><code> System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"); try { x.Open(); } catch (Exception exp) { string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message; Utilities.SendErrorEmail(errorEmailBody); } </code></pre> <p><strong>:End Quote</strong></p> <p>The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control.</p> <p>I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.</p>
[ { "answer_id": 96166, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>Anything in the inner exception? Is this a 64-bit application? The OLEDB providers don't work in 64-bit. You have to have your application target x86. Found this when getting an error trying to open access DB on my 64-bit computer.</p>\n" }, { "answer_id": 96417, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 0, "selected": false, "text": "<p>I've gotten that error over the permissions thing, but it looks like you have that covered. I also have seen it with one of the flags in the connection string -- you might play with that a bit.</p>\n" }, { "answer_id": 96441, "author": "Mike Smith", "author_id": 18164, "author_profile": "https://Stackoverflow.com/users/18164", "pm_score": 0, "selected": false, "text": "<p>Yup. I did that too. Took out IMEX=1, took out Extended Properties, etc. I managed to break it on the dev and test servers. :) I put those back in one at a time until it was fixed on dev and test again but still no workie on prod.</p>\n" }, { "answer_id": 255298, "author": "Joshua Turner", "author_id": 820, "author_profile": "https://Stackoverflow.com/users/820", "pm_score": 1, "selected": false, "text": "<p>Try wrapping the location in single quotes</p>\n\n<pre><code>System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='\" + location + \"';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'\");\n</code></pre>\n" }, { "answer_id": 2169874, "author": "domoaringatoo", "author_id": 4361, "author_profile": "https://Stackoverflow.com/users/4361", "pm_score": 2, "selected": false, "text": "<p>While the permissions issue may be more common you can also encounter this error from Windows file system/Access Jet DB Engine connection limits, 64/255 I think. If you bust the 255 Access read/write concurrent connections or the 64(?) connection limit per process you can get this exact same error. At least I've come across that in an application where connections were being continually created and never properly closed. A simple <code>Conn.close();</code> dropped in and life was good. I imagine Excel could have similar issues. </p>\n" }, { "answer_id": 16424339, "author": "StronglyTyped", "author_id": 650183, "author_profile": "https://Stackoverflow.com/users/650183", "pm_score": 1, "selected": false, "text": "<p>If you're using impersonation you'll need to give permission to the impersonation user instead of/in addition to the aspnet user.</p>\n" }, { "answer_id": 60542256, "author": "GideonMax", "author_id": 12356513, "author_profile": "https://Stackoverflow.com/users/12356513", "pm_score": 0, "selected": false, "text": "<p>not sure if this is the problem you are facing,<br>\nbut, before disposing of the connection, you should do Connection.Close(),<br>because the Connection.Dispose() command is inherited from Component and does not properly dispose of certain connection resources.<br>\nnot properly disposing of the connection could lead to access issues.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18164/" ]
I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server **only**. The application works fine on two other servers (development and testing servers). The following code generates an 'Unspecified Error' in the Exception.Message. **Quote:** ``` System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"); try { x.Open(); } catch (Exception exp) { string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message; Utilities.SendErrorEmail(errorEmailBody); } ``` **:End Quote** The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control. I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.
While the permissions issue may be more common you can also encounter this error from Windows file system/Access Jet DB Engine connection limits, 64/255 I think. If you bust the 255 Access read/write concurrent connections or the 64(?) connection limit per process you can get this exact same error. At least I've come across that in an application where connections were being continually created and never properly closed. A simple `Conn.close();` dropped in and life was good. I imagine Excel could have similar issues.
96,153
<p>I am trying to figure out how to click a button on a web page programmatically.</p> <p>Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the target ASP.NET login page I'm trying to work with, in the DocumentCompleted event handler I have the following coded:</p> <pre><code>HtmlDocument doc = webBrowser1.Document; HtmlElement userID = doc.GetElementById("userIDTextBox"); userID.InnerText = "user1"; HtmlElement password = doc.GetElementById("userPasswordTextBox"); password.InnerText = "password"; HtmlElement button = doc.GetElementById("logonButton"); button.RaiseEvent("onclick"); </code></pre> <p>This fills the userid and password text boxes fine, but I am not having any success getting that darned button to click; I've also tried "click", "Click", and "onClick" -- what else is there?. A search of msdn of course gives me no clues, nor groups.google.com. I gotta be close. Or maybe not -- somebody told me I should call the POST method of the page, but how this is done was not part of the advice given. </p> <p>BTW The button is coded:</p> <pre><code>&lt;input type="submit" name="logonButton" value="Login" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" id="logonButton" tabindex="4" /&gt; </code></pre>
[ { "answer_id": 96172, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>You can try and invoke the Page_ClientValidate() method directly through the clientscript instead of clicking the button, let me dig up an example.</p>\n\n<p>Using MSHTML</p>\n\n<pre><code>mshtml.IHTMLWindow2 myBroserWindow = (mshtml.IHTMLWindow2)MyWebBrowser.Document.Window.DomWindow;\nmyBroserWindow.execScript(\"Page_ClientValidate();\", \"javascript\");\n</code></pre>\n" }, { "answer_id": 96173, "author": "EvilEddie", "author_id": 12986, "author_profile": "https://Stackoverflow.com/users/12986", "pm_score": 3, "selected": false, "text": "<p>var btn = document.getElementById(btnName);\nif (btn) btn.click();</p>\n" }, { "answer_id": 96175, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 2, "selected": false, "text": "<p>There is an example of how to submit the form using InvokeMember here.\n<a href=\"http://msdn.microsoft.com/en-us/library/ms171716.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms171716.aspx</a></p>\n" }, { "answer_id": 96205, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 1, "selected": false, "text": "<p>Have you tried fireEvent instead of RaiseEvent?</p>\n" }, { "answer_id": 96207, "author": "Mike C.", "author_id": 3799, "author_profile": "https://Stackoverflow.com/users/3799", "pm_score": 1, "selected": false, "text": "<p>You could call the method directly and pass in generic object and EventArgs parameters. Of course, this might not work if you were looking at the sender and EventArgs parameters for specific data. How I usually handle this is to refactor the guts of the method to a doSomeAction() method and the event handler for the button click will simply call this function. That way I don't have to figure out how to invoke what is usually just an event handler to do some bit of logic on the page/form.</p>\n\n<p>In the case of javascript clicking a button for a form post, you can invoke form.submit() in the client side script -- which will run any validation scripts you defined in the tag -- and then parse the Form_Load event and grab the text value of the submit button on that form (assuming there is only one) -- at least that's the ASP.NET 1.1 way with which I'm very familiar... anyone know of something more elegant with 2.0+?</p>\n" }, { "answer_id": 140515, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>You posted a comment along the lines of not wanting to use a client side script on @Phunchak's answer. I think what you are trying to do is impossible. The only way to interact with the form is via a client side script. The C# code can only control what happens before the page is sent out to the browser. </p>\n" }, { "answer_id": 140581, "author": "Starwatcher", "author_id": 21264, "author_profile": "https://Stackoverflow.com/users/21264", "pm_score": 4, "selected": true, "text": "<p>How does this work? Works for me</p>\n\n<pre><code>HtmlDocument doc = webBrowser1.Document;\n\ndoc.All[\"userIDTextBox\"].SetAttribute(\"Value\", \"user1\");\ndoc.All[\"userPasswordTextBox\"].SetAttribute(\"Value\", \"Password!\");\ndoc.All[\"logonButton\"].InvokeMember(\"Click\");\n</code></pre>\n" }, { "answer_id": 354588, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>try this\nbutton.focus\nSystem.Windows.Forms.SendKeys.Send(\"{ENTER}\")</p>\n" }, { "answer_id": 12495060, "author": "MonsCamus", "author_id": 1259649, "author_profile": "https://Stackoverflow.com/users/1259649", "pm_score": 1, "selected": false, "text": "<p>Just a possible useful extra where the submit button has not been given an Id - as is frequently the case.</p>\n\n<pre><code> private HtmlElement GetInputElement(string name, HtmlDocument doc) {\n HtmlElementCollection elems = doc.GetElementsByTagName(\"input\");\n\n foreach (HtmlElement elem in elems)\n {\n String nameStr = elem.GetAttribute(\"value\");\n if (!String.IsNullOrEmpty (nameStr) &amp;&amp; nameStr.Equals (name))\n {\n return elem;\n }\n }\n return null;\n }\n</code></pre>\n\n<p>So you can call it like so:</p>\n\n<pre><code> GetInputElement(\"Login\", webBrowser1.Document).InvokeMember(\"Click\");\n</code></pre>\n\n<p>It'll raise an exception if the submit input with the value 'Login', but you can break it up if you want to conditionally check before invoking the click.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16964/" ]
I am trying to figure out how to click a button on a web page programmatically. Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the target ASP.NET login page I'm trying to work with, in the DocumentCompleted event handler I have the following coded: ``` HtmlDocument doc = webBrowser1.Document; HtmlElement userID = doc.GetElementById("userIDTextBox"); userID.InnerText = "user1"; HtmlElement password = doc.GetElementById("userPasswordTextBox"); password.InnerText = "password"; HtmlElement button = doc.GetElementById("logonButton"); button.RaiseEvent("onclick"); ``` This fills the userid and password text boxes fine, but I am not having any success getting that darned button to click; I've also tried "click", "Click", and "onClick" -- what else is there?. A search of msdn of course gives me no clues, nor groups.google.com. I gotta be close. Or maybe not -- somebody told me I should call the POST method of the page, but how this is done was not part of the advice given. BTW The button is coded: ``` <input type="submit" name="logonButton" value="Login" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" id="logonButton" tabindex="4" /> ```
How does this work? Works for me ``` HtmlDocument doc = webBrowser1.Document; doc.All["userIDTextBox"].SetAttribute("Value", "user1"); doc.All["userPasswordTextBox"].SetAttribute("Value", "Password!"); doc.All["logonButton"].InvokeMember("Click"); ```
96,196
<p>The <strong>C</strong> preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a <code>#define</code>.</p> <p>The following macro: </p> <pre><code>#define SUCCEEDED(hr) ((HRESULT)(hr) &gt;= 0) </code></pre> <p>is in no way superior to the type safe:</p> <pre><code>inline bool succeeded(int hr) { return hr &gt;= 0; } </code></pre> <p>But macros do have their place, please list the uses you find for macros that you <em>can't</em> do without the preprocessor. </p> <p>Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.</p>
[ { "answer_id": 96230, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": false, "text": "<p>When you want to change the program flow (<code>return</code>, <code>break</code> and <code>continue</code>) code in a function behaves differently than code that is actually inlined in the function.</p>\n\n<pre><code>#define ASSERT_RETURN(condition, ret_val) \\\nif (!(condition)) { \\\n assert(false &amp;&amp; #condition); \\\n return ret_val; }\n\n// should really be in a do { } while(false) but that's another discussion.\n</code></pre>\n" }, { "answer_id": 96238, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 0, "selected": false, "text": "<p>Often times I end up with code like:</p>\n\n<pre><code>int SomeAPICallbackMethod(long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx) { ... }\nint AnotherCallback(long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx) { ... }\nint YetAnotherCallback(long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx) { ... }\n</code></pre>\n\n<p>In some cases I'll use the following to make my life easier:</p>\n\n<pre><code>#define APIARGS long a, long b, SomeCrazyClass c, long d, string e, string f, long double yx\nint SomeAPICallbackMethod(APIARGS) { ... } \n</code></pre>\n\n<p>It comes with the caveat of really hiding the variable names, which can be an issue in larger systems, so this isn't always the right thing to do, only <em>sometimes</em>.</p>\n" }, { "answer_id": 96239, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": false, "text": "<p>You can't perform short-circuiting of function call arguments using a regular function call. For example:</p>\n\n<pre><code>#define andm(a, b) (a) &amp;&amp; (b)\n\nbool andf(bool a, bool b) { return a &amp;&amp; b; }\n\nandm(x, y) // short circuits the operator so if x is false, y would not be evaluated\nandf(x, y) // y will always be evaluated\n</code></pre>\n" }, { "answer_id": 96241, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 3, "selected": false, "text": "<p>One common use is for detecting the compile environment, for cross-platform development you can write one set of code for linux, say, and another for windows when no cross platform library already exists for your purposes.</p>\n\n<p>So, in a rough example a cross-platform mutex can have</p>\n\n<pre><code>void lock()\n{\n #ifdef WIN32\n EnterCriticalSection(...)\n #endif\n #ifdef POSIX\n pthread_mutex_lock(...)\n #endif\n}\n</code></pre>\n\n<p>For functions, they are useful when you want to explicitly ignore type safety. Such as the many examples above and below for doing ASSERT. Of course, like a lot of C/C++ features you can shoot yourself in the foot, but the language gives you the tools and lets you decide what to do.</p>\n" }, { "answer_id": 96244, "author": "Kena", "author_id": 8027, "author_profile": "https://Stackoverflow.com/users/8027", "pm_score": 4, "selected": false, "text": "<p>The obvious include guards</p>\n\n<pre><code>#ifndef MYHEADER_H\n#define MYHEADER_H\n\n...\n\n#endif\n</code></pre>\n" }, { "answer_id": 96248, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": false, "text": "<p>When you want to make a string out of an expression, the best example for this is <code>assert</code> (<code>#x</code> turns the value of <code>x</code> to a string).</p>\n\n<pre><code>#define ASSERT_THROW(condition) \\\nif (!(condition)) \\\n throw std::exception(#condition \" is false\");\n</code></pre>\n" }, { "answer_id": 96251, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 7, "selected": false, "text": "<p>Methods must always be complete, compilable code; macros may be code fragments. Thus you can define a foreach macro:</p>\n\n<pre><code>#define foreach(list, index) for(index = 0; index &lt; list.size(); index++)\n</code></pre>\n\n<p>And use it as thus:</p>\n\n<pre><code>foreach(cookies, i)\n printf(\"Cookie: %s\", cookies[i]);\n</code></pre>\n\n<p>Since C++11, this is superseded by the <a href=\"http://en.cppreference.com/w/cpp/language/range-for\" rel=\"noreferrer\">range-based for loop</a>.</p>\n" }, { "answer_id": 96256, "author": "unwieldy", "author_id": 14963, "author_profile": "https://Stackoverflow.com/users/14963", "pm_score": 2, "selected": false, "text": "<p>Compilers can refuse your request to inline.</p>\n\n<p>Macros will always have their place.</p>\n\n<p>Something I find useful is #define DEBUG for debug tracing -- you can leave it 1 while debugging a problem (or even leave it on during the whole development cycle) then turn it off when it is time to ship.</p>\n" }, { "answer_id": 96259, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>When you are making a decision at compile time over Compiler/OS/Hardware specific behavior.<br></p>\n\n<p>It allows you to make your interface to Comppiler/OS/Hardware specific features.</p>\n\n<pre><code>#if defined(MY_OS1) &amp;&amp; defined(MY_HARDWARE1)\n#define MY_ACTION(a,b,c) doSothing_OS1HW1(a,b,c);}\n#elif define(MY_OS1) &amp;&amp; defined(MY_HARDWARE2)\n#define MY_ACTION(a,b,c) doSomthing_OS1HW2(a,b,c);}\n#elif define(MY_SUPER_OS)\n /* On this hardware it is a null operation */\n#define MY_ACTION(a,b,c)\n#else\n#error \"PLEASE DEFINE MY_ACTION() for this Compiler/OS/HArdware configuration\"\n#endif\n</code></pre>\n" }, { "answer_id": 96268, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 8, "selected": true, "text": "<p>As wrappers for debug functions, to automatically pass things like <code>__FILE__</code>, <code>__LINE__</code>, etc:</p>\n<pre><code>#ifdef ( DEBUG )\n#define M_DebugLog( msg ) std::cout &lt;&lt; __FILE__ &lt;&lt; &quot;:&quot; &lt;&lt; __LINE__ &lt;&lt; &quot;: &quot; &lt;&lt; msg\n#else\n#define M_DebugLog( msg )\n#endif\n</code></pre>\n<p>Since C++20 the magic type <a href=\"https://en.cppreference.com/w/cpp/utility/source_location\" rel=\"nofollow noreferrer\"><code>std::source_location</code></a> can however be used instead of <code>__LINE__</code> and <code>__FILE__</code> to implement an analogue as a normal function (template).</p>\n" }, { "answer_id": 96300, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 6, "selected": false, "text": "<p>Inside conditional compilation, to overcome issues of differences between compilers:</p>\n<pre><code>#ifdef WE_ARE_ON_WIN32\n#define close(parm1) _close (parm1)\n#define rmdir(parm1) _rmdir (parm1)\n#define mkdir(parm1, parm2) _mkdir (parm1)\n#define access(parm1, parm2) _access(parm1, parm2)\n#define create(parm1, parm2) _creat (parm1, parm2)\n#define unlink(parm1) _unlink(parm1)\n#endif\n</code></pre>\n" }, { "answer_id": 96316, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 6, "selected": false, "text": "<p>Header file guards necessitate macros.</p>\n\n<p>Are there any other areas that <strong>necessitate</strong> macros? Not many (if any).</p>\n\n<p>Are there any other situations that benefit from macros? YES!!!</p>\n\n<p>One place I use macros is with very repetitive code. For example, when wrapping C++ code to be used with other interfaces (.NET, COM, Python, etc...), I need to catch different types of exceptions. Here's how I do that:</p>\n\n<pre><code>#define HANDLE_EXCEPTIONS \\\ncatch (::mylib::exception&amp; e) { \\\n throw gcnew MyDotNetLib::Exception(e); \\\n} \\\ncatch (::std::exception&amp; e) { \\\n throw gcnew MyDotNetLib::Exception(e, __LINE__, __FILE__); \\\n} \\\ncatch (...) { \\\n throw gcnew MyDotNetLib::UnknownException(__LINE__, __FILE__); \\\n}\n</code></pre>\n\n<p>I have to put these catches in every wrapper function. Rather than type out the full catch blocks each time, I just type:</p>\n\n<pre><code>void Foo()\n{\n try {\n ::mylib::Foo()\n }\n HANDLE_EXCEPTIONS\n}\n</code></pre>\n\n<p>This also makes maintenance easier. If I ever have to add a new exception type, there's only one place I need to add it.</p>\n\n<p>There are other useful examples too: many of which include the <code>__FILE__</code> and <code>__LINE__</code> preprocessor macros.</p>\n\n<p>Anyway, macros are very useful when used correctly. Macros are not evil -- their <strong>misuse</strong> is evil.</p>\n" }, { "answer_id": 96331, "author": "Keshi", "author_id": 2430, "author_profile": "https://Stackoverflow.com/users/2430", "pm_score": 3, "selected": false, "text": "<p>Something like</p>\n\n<pre><code>void debugAssert(bool val, const char* file, int lineNumber);\n#define assert(x) debugAssert(x,__FILE__,__LINE__);\n</code></pre>\n\n<p>So that you can just for example have</p>\n\n<pre><code>assert(n == true);\n</code></pre>\n\n<p>and get the source file name and line number of the problem printed out to your log if n is false.</p>\n\n<p>If you use a normal function call such as</p>\n\n<pre><code>void assert(bool val);\n</code></pre>\n\n<p>instead of the macro, all you can get is your assert function's line number printed to the log, which would be less useful.</p>\n" }, { "answer_id": 96339, "author": "Joe", "author_id": 12567, "author_profile": "https://Stackoverflow.com/users/12567", "pm_score": 4, "selected": false, "text": "<p>Unit test frameworks for C++ like <a href=\"https://github.com/unittest-cpp/unittest-cpp\" rel=\"nofollow noreferrer\" title=\"UnitTest++\">UnitTest++</a> pretty much revolve around preprocessor macros. A few lines of unit test code expand into a hierarchy of classes that wouldn't be fun at all to type manually. Without something like UnitTest++ and it's preprocessor magic, I don't know how you'd efficiently write unit tests for C++.</p>\n" }, { "answer_id": 96354, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 3, "selected": false, "text": "<p>We use the <code>__FILE__</code> and <code>__LINE__</code> macros for diagnostic purposes in information rich exception throwing, catching and logging, together with automated log file scanners in our QA infrastructure.</p>\n\n<p>For instance, a throwing macro <code>OUR_OWN_THROW</code> might be used with exception type and constructor parameters for that exception, including a textual description. Like this:</p>\n\n<pre><code>OUR_OWN_THROW(InvalidOperationException, (L\"Uninitialized foo!\"));\n</code></pre>\n\n<p>This macro will of course throw the <code>InvalidOperationException</code> exception with the description as constructor parameter, but it'll also write a message to a log file consisting of the file name and line number where the throw occured and its textual description. The thrown exception will get an id, which also gets logged. If the exception is ever caught somewhere else in the code, it will be marked as such and the log file will then indicate that that specific exception has been handled and that it's therefore not likely the cause of any crash that might be logged later on. Unhandled exceptions can be easily picked up by our automated QA infrastructure.</p>\n" }, { "answer_id": 96361, "author": "Mathieu Pagé", "author_id": 5861, "author_profile": "https://Stackoverflow.com/users/5861", "pm_score": 0, "selected": false, "text": "<p>I think this trick is a clever use of the preprocessor that can't be emulated with a function :</p>\n\n<pre><code>#define COMMENT COMMENT_SLASH(/)\n#define COMMENT_SLASH(s) /##s\n\n#if defined _DEBUG\n#define DEBUG_ONLY\n#else\n#define DEBUG_ONLY COMMENT\n#endif\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>cout &lt;&lt;\"Hello, World!\" &lt;&lt;endl;\nDEBUG_ONLY cout &lt;&lt;\"This is outputed only in debug mode\" &lt;&lt;endl;\n</code></pre>\n\n<p>You can also define a RELEASE_ONLY macro.</p>\n" }, { "answer_id": 96419, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "<p>Let's say we'll ignore obvious things like header guards.</p>\n\n<p>Sometimes, you want to generate code that needs to be copy/pasted by the precompiler:</p>\n\n<pre><code>#define RAISE_ERROR_STL(p_strMessage) \\\ndo \\\n{ \\\n try \\\n { \\\n std::tstringstream strBuffer ; \\\n strBuffer &lt;&lt; p_strMessage ; \\\n strMessage = strBuffer.str() ; \\\n raiseSomeAlert(__FILE__, __FUNCSIG__, __LINE__, strBuffer.str().c_str()) \\\n } \\\n catch(...){} \\\n { \\\n } \\\n} \\\nwhile(false)\n</code></pre>\n\n<p>which enables you to code this:</p>\n\n<pre><code>RAISE_ERROR_STL(\"Hello... The following values \" &lt;&lt; i &lt;&lt; \" and \" &lt;&lt; j &lt;&lt; \" are wrong\") ;\n</code></pre>\n\n<p>And can generate messages like:</p>\n\n<pre><code>Error Raised:\n====================================\nFile : MyFile.cpp, line 225\nFunction : MyFunction(int, double)\nMessage : \"Hello... The following values 23 and 12 are wrong\"\n</code></pre>\n\n<p>Note that mixing templates with macros can lead to even better results (i.e. automatically generating the values side-by-side with their variable names)</p>\n\n<p>Other times, you need the __FILE__ and/or the __LINE__ of some code, to generate debug info, for example. The following is a classic for Visual C++:</p>\n\n<pre><code>#define WRNG_PRIVATE_STR2(z) #z\n#define WRNG_PRIVATE_STR1(x) WRNG_PRIVATE_STR2(x)\n#define WRNG __FILE__ \"(\"WRNG_PRIVATE_STR1(__LINE__)\") : ------------ : \"\n</code></pre>\n\n<p>As with the following code:</p>\n\n<pre><code>#pragma message(WRNG \"Hello World\")\n</code></pre>\n\n<p>it generates messages like:</p>\n\n<pre><code>C:\\my_project\\my_cpp_file.cpp (225) : ------------ Hello World\n</code></pre>\n\n<p>Other times, you need to generate code using the # and ## concatenation operators, like generating getters and setters for a property (this is for quite a limited cases, through).</p>\n\n<p>Other times, you will generate code than won't compile if used through a function, like:</p>\n\n<pre><code>#define MY_TRY try{\n#define MY_CATCH } catch(...) {\n#define MY_END_TRY }\n</code></pre>\n\n<p>Which can be used as</p>\n\n<pre><code>MY_TRY\n doSomethingDangerous() ;\nMY_CATCH\n tryToRecoverEvenWithoutMeaningfullInfo() ;\n damnThoseMacros() ;\nMY_END_TRY\n</code></pre>\n\n<p>(still, I only saw this kind of code rightly used <strong>once</strong>)</p>\n\n<p>Last, but not least, the famous <a href=\"http://www.boost.org/doc/libs/1_35_0/doc/html/foreach.html\" rel=\"noreferrer\"><code>boost::foreach</code></a> !!!</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;boost/foreach.hpp&gt;\n\nint main()\n{\n std::string hello( \"Hello, world!\" );\n\n BOOST_FOREACH( char ch, hello )\n {\n std::cout &lt;&lt; ch;\n }\n\n return 0;\n}\n</code></pre>\n\n<p>(Note: code copy/pasted from the boost homepage)</p>\n\n<p>Which is (IMHO) way better than <code>std::for_each</code>.</p>\n\n<p>So, macros are always useful because they are outside the normal compiler rules. But I find that most the time I see one, they are effectively remains of C code never translated into proper C++.</p>\n" }, { "answer_id": 96447, "author": "Harold Ekstrom", "author_id": 8429, "author_profile": "https://Stackoverflow.com/users/8429", "pm_score": 0, "selected": false, "text": "<p>You need a macros for resource identifiers in Visual Studio as the resource compiler only understands them (i.e., it doesn't work with const or enum).</p>\n" }, { "answer_id": 96803, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 3, "selected": false, "text": "<p>I occasionally use macros so I can define information in one place, but use it in different ways in different parts of the code. It's only slightly evil :)</p>\n\n<p>For example, in \"field_list.h\":</p>\n\n<pre><code>/*\n * List of fields, names and values.\n */\nFIELD(EXAMPLE1, \"first example\", 10)\nFIELD(EXAMPLE2, \"second example\", 96)\nFIELD(ANOTHER, \"more stuff\", 32)\n...\n#undef FIELD\n</code></pre>\n\n<p>Then for a public enum it can be defined to just use the name:</p>\n\n<pre><code>#define FIELD(name, desc, value) FIELD_ ## name,\n\ntypedef field_ {\n\n#include \"field_list.h\"\n\n FIELD_MAX\n\n} field_en;\n</code></pre>\n\n<p>And in a private init function, all the fields can be used to populate a table with the data:</p>\n\n<pre><code>#define FIELD(name, desc, value) \\\n table[FIELD_ ## name].desc = desc; \\\n table[FIELD_ ## name].value = value;\n\n#include \"field_list.h\"\n</code></pre>\n" }, { "answer_id": 96942, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 2, "selected": false, "text": "<p>You can use #defines to help with debugging and unit test scenarios. For example, create special logging variants of the memory functions and create a special memlog_preinclude.h:</p>\n\n<pre><code>#define malloc memlog_malloc\n#define calloc memlog calloc\n#define free memlog_free\n</code></pre>\n\n<p>Compile you code using:</p>\n\n<pre><code>gcc -Imemlog_preinclude.h ...\n</code></pre>\n\n<p>An link in your memlog.o to the final image. You now control malloc, etc, perhaps for logging purposes, or to simulate allocation failures for unit tests.</p>\n" }, { "answer_id": 97292, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 2, "selected": false, "text": "<pre><code>#define ARRAY_SIZE(arr) (sizeof arr / sizeof arr[0])\n</code></pre>\n\n<p>Unlike the 'preferred' template solution discussed in a current thread, you can use it as a constant expression:</p>\n\n<pre><code>char src[23];\nint dest[ARRAY_SIZE(src)];\n</code></pre>\n" }, { "answer_id": 98993, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 0, "selected": false, "text": "<p>Can you implement this as an inline function?</p>\n\n<pre><code>#define my_free(x) do { free(x); x = NULL; } while (0)\n</code></pre>\n" }, { "answer_id": 99380, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "<p>You can <code>#define</code> constants on the compiler command line using the <code>-D</code> or <code>/D</code> option. This is often useful when cross-compiling the same software for multiple platforms because you can have your makefiles control what constants are defined for each platform.</p>\n" }, { "answer_id": 99437, "author": "LarryF", "author_id": 18518, "author_profile": "https://Stackoverflow.com/users/18518", "pm_score": 2, "selected": false, "text": "<p>In my last job, I was working on a virus scanner. To make thing easier for me to debug, I had lots of logging stuck all over the place, but in a high demand app like that, the expense of a function call is just too expensive. So, I came up with this little Macro, that still allowed me to enable the debug logging on a release version at a customers site, without the cost of a function call would check the debug flag and just return without logging anything, or if enabled, would do the logging... The macro was defined as follows:</p>\n\n<pre><code>#define dbgmsg(_FORMAT, ...) if((debugmsg_flag &amp; 0x00000001) || (debugmsg_flag &amp; 0x80000000)) { log_dbgmsg(_FORMAT, __VA_ARGS__); }\n</code></pre>\n\n<p>Because of the VA_ARGS in the log functions, this was a good case for a macro like this.</p>\n\n<p>Before that, I used a macro in a high security application that needed to tell the user that they didn't have the correct access, and it would tell them what flag they needed.</p>\n\n<p>The Macro(s) defined as:</p>\n\n<pre><code>#define SECURITY_CHECK(lRequiredSecRoles) if(!DoSecurityCheck(lRequiredSecRoles, #lRequiredSecRoles, true)) return\n#define SECURITY_CHECK_QUIET(lRequiredSecRoles) (DoSecurityCheck(lRequiredSecRoles, #lRequiredSecRoles, false))\n</code></pre>\n\n<p>Then, we could just sprinkle the checks all over the UI, and it would tell you which roles were allowed to perform the action you tried to do, if you didn't already have that role. The reason for two of them was to return a value in some places, and return from a void function in others...</p>\n\n<pre><code>SECURITY_CHECK(ROLE_BUSINESS_INFORMATION_STEWARD | ROLE_WORKER_ADMINISTRATOR);\n\nLRESULT CAddPerson1::OnWizardNext() \n{\n if(m_Role.GetItemData(m_Role.GetCurSel()) == parent-&gt;ROLE_EMPLOYEE) {\n SECURITY_CHECK(ROLE_WORKER_ADMINISTRATOR | ROLE_BUSINESS_INFORMATION_STEWARD ) -1;\n } else if(m_Role.GetItemData(m_Role.GetCurSel()) == parent-&gt;ROLE_CONTINGENT) {\n SECURITY_CHECK(ROLE_CONTINGENT_WORKER_ADMINISTRATOR | ROLE_BUSINESS_INFORMATION_STEWARD | ROLE_WORKER_ADMINISTRATOR) -1;\n }\n...\n</code></pre>\n\n<p>Anyways, that's how I've used them, and I'm not sure how this could have been helped with templates... Other than that, I try to avoid them, unless REALLY necessary.</p>\n" }, { "answer_id": 165410, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 1, "selected": false, "text": "<p>If you have a list of fields that get used for a bunch of things, e.g. defining a structure, serializing that structure to/from some binary format, doing database inserts, etc, then you can (recursively!) use the preprocessor to avoid ever repeating your field list.</p>\n\n<p>This is admittedly hideous. But maybe sometimes better than updating a long list of fields in multiple places? I've used this technique exactly once, and it was quite helpful that one time.</p>\n\n<p>Of course the same general idea is used extensively in languages with proper reflection -- just instrospect the class and operate on each field in turn. Doing it in the C preprocessor is fragile, illegible, and not always portable. So I mention it with some trepidation. Nonetheless, here it is...</p>\n\n<p>(EDIT: I see now that this is similar to what @Andrew Johnson said on 9/18; however the idea of recursively including the same file takes the idea a bit further.)</p>\n\n<pre><code>// file foo.h, defines class Foo and various members on it without ever repeating the\n// list of fields.\n\n#if defined( FIELD_LIST )\n // here's the actual list of fields in the class. If FIELD_LIST is defined, we're at\n // the 3rd level of inclusion and somebody wants to actually use the field list. In order\n // to do so, they will have defined the macros STRING and INT before including us.\n STRING( fooString )\n INT( barInt ) \n#else // defined( FIELD_LIST )\n\n#if !defined(FOO_H)\n#define FOO_H\n\n#define DEFINE_STRUCT\n// recursively include this same file to define class Foo\n#include \"foo.h\"\n#undef DEFINE_STRUCT\n\n#define DEFINE_CLEAR\n// recursively include this same file to define method Foo::clear\n#include \"foo.h\"\n#undef DEFINE_CLEAR\n\n// etc ... many more interesting examples like serialization\n\n#else // defined(FOO_H)\n// from here on, we know that FOO_H was defined, in other words we're at the second level of\n// recursive inclusion, and the file is being used to make some particular\n// use of the field list, for example defining the class or a single method of it\n\n#if defined( DEFINE_STRUCT )\n#define STRING(a) std::string a;\n#define INT(a) long a;\n class Foo\n {\n public:\n#define FIELD_LIST\n// recursively include the same file (for the third time!) to get fields\n// This is going to translate into:\n// std::string fooString;\n// int barInt;\n#include \"foo.h\"\n#endif\n\n void clear();\n };\n#undef STRING\n#undef INT\n#endif // defined(DEFINE_STRUCT)\n\n\n#if defined( DEFINE_ZERO )\n#define STRING(a) a = \"\";\n#define INT(a) a = 0;\n#define FIELD_LIST\n void Foo::clear()\n {\n// recursively include the same file (for the third time!) to get fields.\n// This is going to translate into:\n// fooString=\"\";\n// barInt=0;\n#include \"foo.h\"\n#undef STRING\n#undef int\n }\n#endif // defined( DEFINE_ZERO )\n\n// etc...\n\n\n#endif // end else clause for defined( FOO_H )\n\n#endif // end else clause for defined( FIELD_LIST )\n</code></pre>\n" }, { "answer_id": 212711, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>To fear the C preprocessor is like to fear the incandescent bulbs just because we get fluorescent bulbs. Yes, the former can be {electricity | programmer time} inefficient. Yes, you can get (literally) burned by them. But they can get the job done if you properly handle it. </p>\n\n<p>When you program embedded systems, C uses to be the only option apart form assembler. After programming on desktop with C++ and then switching to smaller, embedded targets, you learn to stop worrying about “inelegancies” of so many bare C features (macros included) and just trying to figure out the best and safe usage you can get from those features.</p>\n\n<p>Alexander Stepanov <a href=\"http://www.stepanovpapers.com/notes.pdf\" rel=\"noreferrer\">says</a>:</p>\n\n<blockquote>\n <p>When we program in C++ we should not be ashamed of its C heritage, but make \n full use of it. The only problems with C++, and even the only problems with C, arise \n when they themselves are not consistent with their own logic. </p>\n</blockquote>\n" }, { "answer_id": 212773, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 6, "selected": false, "text": "<p>Mostly:</p>\n\n<ol>\n<li>Include guards</li>\n<li>Conditional compilation</li>\n<li>Reporting (predefined macros like <code>__LINE__</code> and <code>__FILE__</code>)</li>\n<li>(rarely) Duplicating repetitive code patterns.</li>\n<li>In your competitor's code.</li>\n</ol>\n" }, { "answer_id": 212792, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 0, "selected": false, "text": "<p>You can enable additional logging in a debug build and disable it for a release build without the overhead of a Boolean check. So, instead of:</p>\n\n<pre><code>void Log::trace(const char *pszMsg) {\n if (!bDebugBuild) {\n return;\n }\n // Do the logging\n}\n\n...\n\nlog.trace(\"Inside MyFunction\");\n</code></pre>\n\n<p>You can have:</p>\n\n<pre><code>#ifdef _DEBUG\n#define LOG_TRACE log.trace\n#else\n#define LOG_TRACE void\n#endif\n\n...\n\nLOG_TRACE(\"Inside MyFunction\");\n</code></pre>\n\n<p>When _DEBUG is not defined, this will not generate any code at all. Your program will run faster and the text for the trace logging won't be compiled into your executable.</p>\n" }, { "answer_id": 227412, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": false, "text": "<p>String constants are sometimes better defined as macros since you can do more with string literals than with a <code>const char *</code>.</p>\n<p>e.g. String literals can be <a href=\"http://msdn.microsoft.com/en-us/library/c7bt45zf(VS.80).aspx\" rel=\"nofollow noreferrer\">easily concatenated</a>.</p>\n<pre><code>#define BASE_HKEY &quot;Software\\\\Microsoft\\\\Internet Explorer\\\\&quot;\n// Now we can concat with other literals\nRegOpenKey(HKEY_CURRENT_USER, BASE_HKEY &quot;Settings&quot;, &amp;settings);\nRegOpenKey(HKEY_CURRENT_USER, BASE_HKEY &quot;TypedURLs&quot;, &amp;URLs);\n</code></pre>\n<p>If a <code>const char *</code> were used then some sort of string class would have to be used to perform the concatenation at runtime:</p>\n<pre><code>const char* BaseHkey = &quot;Software\\\\Microsoft\\\\Internet Explorer\\\\&quot;;\nRegOpenKey(HKEY_CURRENT_USER, (string(BaseHkey) + &quot;Settings&quot;).c_str(), &amp;settings);\nRegOpenKey(HKEY_CURRENT_USER, (string(BaseHkey) + &quot;TypedURLs&quot;).c_str(), &amp;URLs);\n</code></pre>\n<p>Since C++20 it is however possible to implement a string-like class type that can be used as a non-type template parameter type of a user-defined string literal operator which allows such concatenation operations at compile-time without macros.</p>\n" }, { "answer_id": 231672, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": false, "text": "<p>Some very advanced and useful stuff can still be built using preprocessor (macros), which you would never be able to do using the c++ \"language constructs\" including templates.</p>\n\n<p>Examples:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/126277/making-something-both-a-c-identifier-and-a-string\">Making something both a C identifier and a string</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/147267/easy-way-to-use-variables-of-enum-types-as-string-in-c#202511\">Easy way to use variables of enum types as string in C</a></p>\n\n<p><a href=\"http://www.boost.org/doc/libs/?view=category_Preprocessor\" rel=\"nofollow noreferrer\">Boost Preprocessor Metaprogramming</a></p>\n" }, { "answer_id": 1297177, "author": "dwj", "author_id": 346, "author_profile": "https://Stackoverflow.com/users/346", "pm_score": 1, "selected": false, "text": "<p>I've used the preprocesser to calculate fixed-point numbers from floating point values used in embedded systems that cannot use floating point in the compiled code. It's handy to have all of your math in Real World Units and not have to think about them in fixed-point.</p>\n\n<p>Example:</p>\n\n<pre><code>// TICKS_PER_UNIT is defined in floating point to allow the conversions to compute during compile-time.\n#define TICKS_PER_UNIT 1024.0\n\n\n// NOTE: The TICKS_PER_x_MS will produce constants in the preprocessor. The (long) cast will\n// guarantee there are no floating point values in the embedded code and will produce a warning\n// if the constant is larger than the data type being stored to.\n// Adding 0.5 sec to the calculation forces rounding instead of truncation.\n#define TICKS_PER_1_MS( ms ) (long)( ( ( ms * TICKS_PER_UNIT ) / 1000 ) + 0.5 )\n</code></pre>\n" }, { "answer_id": 2199256, "author": "Notinlist", "author_id": 163454, "author_profile": "https://Stackoverflow.com/users/163454", "pm_score": 1, "selected": false, "text": "<p>Yet another foreach macros. T: type, c: container, i: iterator</p>\n\n<pre><code>#define foreach(T, c, i) for(T::iterator i=(c).begin(); i!=(c).end(); ++i)\n#define foreach_const(T, c, i) for(T::const_iterator i=(c).begin(); i!=(c).end(); ++i)\n</code></pre>\n\n<p>Usage (concept showing, not real):</p>\n\n<pre><code>void MultiplyEveryElementInList(std::list&lt;int&gt;&amp; ints, int mul)\n{\n foreach(std::list&lt;int&gt;, ints, i)\n (*i) *= mul;\n}\n\nint GetSumOfList(const std::list&lt;int&gt;&amp; ints)\n{\n int ret = 0;\n foreach_const(std::list&lt;int&gt;, ints, i)\n ret += *i;\n return ret;\n}\n</code></pre>\n\n<p>Better implementations available: Google <strong>\"BOOST_FOREACH\"</strong></p>\n\n<p>Good articles available: <strong>Conditional Love: FOREACH Redux</strong> (Eric Niebler) <a href=\"http://www.artima.com/cppsource/foreach.html\" rel=\"nofollow noreferrer\">http://www.artima.com/cppsource/foreach.html</a></p>\n" }, { "answer_id": 2662237, "author": "rkellerm", "author_id": 213615, "author_profile": "https://Stackoverflow.com/users/213615", "pm_score": 1, "selected": false, "text": "<p>Maybe the greates usage of macros is in platform-independent development.\nThink about cases of type inconsistency - with macros, you can simply use different header files -- like:\n--WIN_TYPES.H</p>\n\n<pre><code>typedef ...some struct\n</code></pre>\n\n<p>--POSIX_TYPES.h</p>\n\n<pre><code>typedef ...some another struct\n</code></pre>\n\n<p>--program.h</p>\n\n<pre><code>#ifdef WIN32\n#define TYPES_H \"WINTYPES.H\"\n#else \n#define TYPES_H \"POSIX_TYPES.H\"\n#endif\n\n#include TYPES_H\n</code></pre>\n\n<p>Much readable than implementing it in other ways, to my opinion.</p>\n" }, { "answer_id": 5925535, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": -1, "selected": false, "text": "<pre><code>#define COLUMNS(A,B) [(B) - (A) + 1]\n\nstruct \n{\n char firstName COLUMNS( 1, 30);\n char lastName COLUMNS( 31, 60);\n char address1 COLUMNS( 61, 90);\n char address2 COLUMNS( 91, 120);\n char city COLUMNS(121, 150);\n};\n</code></pre>\n" }, { "answer_id": 6364467, "author": "MrBeast", "author_id": 800422, "author_profile": "https://Stackoverflow.com/users/800422", "pm_score": 2, "selected": false, "text": "<p>I use macros to easily define Exceptions:</p>\n\n<pre><code>DEF_EXCEPTION(RessourceNotFound, \"Ressource not found\")\n</code></pre>\n\n<p>where DEF_EXCEPTION is</p>\n\n<pre><code>#define DEF_EXCEPTION(A, B) class A : public exception\\\n {\\\n public:\\\n virtual const char* what() const throw()\\\n {\\\n return B;\\\n };\\\n }\\\n</code></pre>\n" }, { "answer_id": 7077922, "author": "Martin Ba", "author_id": 321013, "author_profile": "https://Stackoverflow.com/users/321013", "pm_score": 1, "selected": false, "text": "<p>Seems VA_ARGS have only been mentioned indirectly so far:</p>\n\n<p>When writing generic C++03 code, and you need a variable number of (generic) parameters, you can use a macro instead of a template.</p>\n\n<pre><code>#define CALL_RETURN_WRAPPER(FnType, FName, ...) \\\n if( FnType theFunction = get_op_from_name(FName) ) { \\\n return theFunction(__VA_ARGS__); \\\n } else { \\\n throw invalid_function_name(FName); \\\n } \\\n/**/\n</code></pre>\n\n<p><sub><strong>Note:</strong> In general, the name check/throw could also be incorporated into the hypothetical <code>get_op_from_name</code> function. This is just an example. There might be other generic code surrounding the VA_ARGS call.</sub></p>\n\n<p>Once we get variadic templates with C++11, we can solve this \"properly\" with a template.</p>\n" }, { "answer_id": 8027050, "author": "Ruggero Turra", "author_id": 238671, "author_profile": "https://Stackoverflow.com/users/238671", "pm_score": 3, "selected": false, "text": "<p>Code repetition.</p>\n\n<p>Have a look to <a href=\"http://www.boost.org/doc/libs/1_47_0/libs/preprocessor/doc/topics/motivation.html\" rel=\"nofollow\">boost preprocessor library</a>, it's a kind of meta-meta-programming. In topic->motivation you can find a good example.</p>\n" }, { "answer_id": 51674754, "author": "einpoklum", "author_id": 1593077, "author_profile": "https://Stackoverflow.com/users/1593077", "pm_score": -1, "selected": false, "text": "<p>Macros are useful for simulating the syntax of switch statements:</p>\n\n<pre><code>switch(x) {\ncase val1: do_stuff(); break;\ncase val2: do_other_stuff();\ncase val3: yet_more_stuff();\ndefault: something_else();\n}\n</code></pre>\n\n<p>for non-integral value types. In this question: </p>\n\n<p><a href=\"https://stackoverflow.com/q/41337256/1593077\">Using strings in switch statements - where do we stand with C++17?</a></p>\n\n<p>you'll find answers suggesting some approaches involving lambdas, but unfortunately, it's macros that get us the closest:</p>\n\n<pre><code>SWITCH(x)\nCASE val1 do_stuff(); break;\nCASE val2 do_other_stuff();\nCASE val3 yet_more_stuff();\nDEFAULT something_else();\nEND\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
The **C** preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a `#define`. The following macro: ``` #define SUCCEEDED(hr) ((HRESULT)(hr) >= 0) ``` is in no way superior to the type safe: ``` inline bool succeeded(int hr) { return hr >= 0; } ``` But macros do have their place, please list the uses you find for macros that you *can't* do without the preprocessor. Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.
As wrappers for debug functions, to automatically pass things like `__FILE__`, `__LINE__`, etc: ``` #ifdef ( DEBUG ) #define M_DebugLog( msg ) std::cout << __FILE__ << ":" << __LINE__ << ": " << msg #else #define M_DebugLog( msg ) #endif ``` Since C++20 the magic type [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location) can however be used instead of `__LINE__` and `__FILE__` to implement an analogue as a normal function (template).
96,249
<p>Adding an element to the head of an alist (Associative list) is simple enough:</p> <pre><code>&gt; (cons '(ding . 53) '((foo . 42) (bar . 27))) ((ding . 53) (foo . 42) (bar . 27)) </code></pre> <p>Appending to the tail of an alist is a bit trickier though. After some experimenting, I produced this:</p> <pre><code>&gt; (define (alist-append alist pair) `(,@alist ,pair)) &gt; (alist-append '((foo . 42) (bar . 27)) '(ding . 53)) '((foo . 42) (bar . 27) (ding . 53)) </code></pre> <p>However, it seems to me, that this isn't the idiomatic solution. So how is this usually done in scheme? Or is this in fact the way?</p>
[ { "answer_id": 96477, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>You don't append to an a-list. You cons onto an a-list.</p>\n\n<p>An a-list is logically a set of associations. You don't care about the order of elements in a set. All you care about is presence or absence of a particular element. In the case of an a-list, all you care about is whether there exists an association for a given tag (i.e., a pair whose CAR is the specified value), and, given that association, the associated value (i.e., in this implementation, the CDR of the pair).</p>\n" }, { "answer_id": 96754, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 3, "selected": false, "text": "<p>Common Lisp defines a function called <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_acons.htm\" rel=\"noreferrer\">ACONS</a> for exactly this purpose, where</p>\n\n<pre><code>(acons key value alist)\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>(cons (cons key value) alist)\n</code></pre>\n\n<p>This strongly suggests that simply consing onto an alist is idiomatic. Note that this means two things:</p>\n\n<ol>\n<li>As searches are usually performed from front to back, recently added associations take precedence over older ones. This can be used for a naive implementation of both lexical and dynamic environments.</li>\n<li>While consing onto a list is O(1), appending is generally O(n) where n is the length of the list, so the idiomatic usage is best for performance as well as being stylistically preferable.</li>\n</ol>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180/" ]
Adding an element to the head of an alist (Associative list) is simple enough: ``` > (cons '(ding . 53) '((foo . 42) (bar . 27))) ((ding . 53) (foo . 42) (bar . 27)) ``` Appending to the tail of an alist is a bit trickier though. After some experimenting, I produced this: ``` > (define (alist-append alist pair) `(,@alist ,pair)) > (alist-append '((foo . 42) (bar . 27)) '(ding . 53)) '((foo . 42) (bar . 27) (ding . 53)) ``` However, it seems to me, that this isn't the idiomatic solution. So how is this usually done in scheme? Or is this in fact the way?
You don't append to an a-list. You cons onto an a-list. An a-list is logically a set of associations. You don't care about the order of elements in a set. All you care about is presence or absence of a particular element. In the case of an a-list, all you care about is whether there exists an association for a given tag (i.e., a pair whose CAR is the specified value), and, given that association, the associated value (i.e., in this implementation, the CDR of the pair).
96,250
<p>My project has both client and server components in the same solution file. I usually have the debugger set to start them together when debugging, but it's often the case where I start the server up outside of the debugger so I can start and stop the client as needed when working on client-side only stuff. (this is much faster). </p> <p>I'm trying to save myself the hassle of poking around in Solution Explorer to start individual projects and would rather just stick a button on the toolbar that calls a macro that starts the debugger for individual projects (while leaving "F5" type debugging alone to start up both processess). </p> <p>I tried recording, but that didn't really result in anything useful. </p> <p>So far all I've managed to do is to locate the project item in the solution explorer: </p> <pre><code> Dim projItem As UIHierarchyItem projItem = DTE.ToolWindows.SolutionExplorer.GetItem("SolutionName\ProjectFolder\ProjectName").Select(vsUISelectionType.vsUISelectionTypeSelect) </code></pre> <p>(This is based loosely on how the macro recorder tried to do it. I'm not sure if navigating the UI object model is the correct approach, or if I should be looking at going through the Solution/Project object model instead). </p>
[ { "answer_id": 96478, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 4, "selected": true, "text": "<p>Ok. This appears to work from most UI (all?) contexts provided the solution is loaded: </p>\n\n<pre><code> Sub DebugTheServer()\n DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate()\n DTE.ActiveWindow.Object.GetItem(\"Solution\\ServerFolder\\ServerProject\").Select(vsUISelectionType.vsUISelectionTypeSelect)\n DTE.Windows.Item(Constants.vsWindowKindOutput).Activate()\n DTE.ExecuteCommand(\"ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance\")\n End Sub\n</code></pre>\n" }, { "answer_id": 32282888, "author": "Erwin Mayer", "author_id": 541420, "author_profile": "https://Stackoverflow.com/users/541420", "pm_score": 0, "selected": false, "text": "<p>From a C# add-in, the following worked for me:</p>\n\n<pre><code>Dte.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate();\nDte.ToolWindows.SolutionExplorer.GetItem(\"SolutionName\\\\SolutionFolderName\\\\ProjectName\").Select(vsUISelectionType.vsUISelectionTypeSelect);\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187/" ]
My project has both client and server components in the same solution file. I usually have the debugger set to start them together when debugging, but it's often the case where I start the server up outside of the debugger so I can start and stop the client as needed when working on client-side only stuff. (this is much faster). I'm trying to save myself the hassle of poking around in Solution Explorer to start individual projects and would rather just stick a button on the toolbar that calls a macro that starts the debugger for individual projects (while leaving "F5" type debugging alone to start up both processess). I tried recording, but that didn't really result in anything useful. So far all I've managed to do is to locate the project item in the solution explorer: ``` Dim projItem As UIHierarchyItem projItem = DTE.ToolWindows.SolutionExplorer.GetItem("SolutionName\ProjectFolder\ProjectName").Select(vsUISelectionType.vsUISelectionTypeSelect) ``` (This is based loosely on how the macro recorder tried to do it. I'm not sure if navigating the UI object model is the correct approach, or if I should be looking at going through the Solution/Project object model instead).
Ok. This appears to work from most UI (all?) contexts provided the solution is loaded: ``` Sub DebugTheServer() DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate() DTE.ActiveWindow.Object.GetItem("Solution\ServerFolder\ServerProject").Select(vsUISelectionType.vsUISelectionTypeSelect) DTE.Windows.Item(Constants.vsWindowKindOutput).Activate() DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance") End Sub ```
96,264
<p>I have two code bases of an application. I need to copy all the files in all the directories with .java from the newer code base, to the older (so I can commit it to svn).</p> <p>How can I write a batch files to do this?</p>
[ { "answer_id": 96270, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 4, "selected": true, "text": "<p>XCOPY /D ?</p>\n\n<pre><code>xcopy c:\\olddir\\*.java c:\\newdir /D /E /Q /Y\n</code></pre>\n" }, { "answer_id": 96319, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 1, "selected": false, "text": "<p>If you've lots of different instances of this problem to solve, I've had some success with <a href=\"http://ant.apache.org/\" rel=\"nofollow noreferrer\">Apache Ant</a> for this kind of copy/update/backup kind of thing.</p>\n\n<p>There <em>is</em> a bit of a learning curve, though, and it <em>does</em> require you to have a Java runtime environment installed. </p>\n" }, { "answer_id": 96376, "author": "Mackaaij", "author_id": 13222, "author_profile": "https://Stackoverflow.com/users/13222", "pm_score": 1, "selected": false, "text": "<p>I like <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"nofollow noreferrer\">Robocopy</a> (\"Robust File Copy\"). It is a command-line directory replication command. It was available as part of the Windows Resource Kit, and is introduced as a standard feature of Windows Vista and Windows Server 2008.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
I have two code bases of an application. I need to copy all the files in all the directories with .java from the newer code base, to the older (so I can commit it to svn). How can I write a batch files to do this?
XCOPY /D ? ``` xcopy c:\olddir\*.java c:\newdir /D /E /Q /Y ```
96,265
<p>I am programming a game on the iPhone. I am currently using NSTimer to trigger my game update/render. The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer. </p> <p>So my question is what is the best alternative to using NSTimer?</p> <p>One alternative per answer please.</p>
[ { "answer_id": 224791, "author": "Galghamon", "author_id": 26511, "author_profile": "https://Stackoverflow.com/users/26511", "pm_score": 2, "selected": false, "text": "<p>I don't know about the iPhone in particular, but I may still be able to help:\nInstead of simply plugging in a fixed delay at the end of the loop, use the following: </p>\n\n<ul>\n<li>Determine a refresh interval that you would be happy with and that is larger than a single pass through your main loop.</li>\n<li>At the start of the loop, take a current timestamp of whatever resolution you have available and store it.</li>\n<li>At the end of the loop, take another timestamp, and determine the elapsed time since the last timestamp (initialize this before the loop).</li>\n<li>sleep/delay for the difference between your ideal frame time and the already elapsed time this for the frame.</li>\n<li>At the next frame, you can even try to compensate for inaccuracies in the sleep interval by comparing to the timestamp at the start of the previous loop. Store the difference and add/subtract it from the sleep interval at the end of this loop (sleep/delay can go too long OR too short).</li>\n</ul>\n\n<p>You might want to have an alert mechanism that lets you know if you're timing is too tight(i,e, if your sleep time after all the compensating is less than 0, which would mean you're taking more time to process than your frame rate allows). The effect will be that your game slows down. For extra points, you may want to simplify rendering for a while, if you detect this happening, until you have enough spare capacity again.</p>\n" }, { "answer_id": 224891, "author": "zoul", "author_id": 17279, "author_profile": "https://Stackoverflow.com/users/17279", "pm_score": 4, "selected": false, "text": "<p>You can get a better performance with threads, try something like this:</p>\n\n<pre><code>- (void) gameLoop\n{\n while (running)\n {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n [self renderFrame];\n [pool release];\n }\n}\n\n- (void) startLoop\n{\n running = YES;\n#ifdef THREADED_ANIMATION\n [NSThread detachNewThreadSelector:@selector(gameLoop)\n toTarget:self withObject:nil];\n#else\n timer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60\n target:self selector:@selector(renderFrame) userInfo:nil repeats:YES];\n#endif\n}\n\n- (void) stopLoop\n{\n [timer invalidate];\n running = NO;\n}\n</code></pre>\n\n<p>In the <code>renderFrame</code> method You prepare the framebuffer, draw frame and present the framebuffer on screen. (P.S. There is a great <a href=\"http://dewitters.koonsolo.com/gameloop.html\" rel=\"noreferrer\">article</a> on various types of game loops and their pros and cons.)</p>\n" }, { "answer_id": 4304069, "author": "scriba", "author_id": 216865, "author_profile": "https://Stackoverflow.com/users/216865", "pm_score": 0, "selected": false, "text": "<p>Use the CADisplayLink, you can find how in the OpenGL ES template project provided in XCODE (create a project starting from this template and give a look to the EAGLView class, this example is based on open GL, but you can use CADisplayLink only for other kind of games</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25868/" ]
I am programming a game on the iPhone. I am currently using NSTimer to trigger my game update/render. The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer. So my question is what is the best alternative to using NSTimer? One alternative per answer please.
You can get a better performance with threads, try something like this: ``` - (void) gameLoop { while (running) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self renderFrame]; [pool release]; } } - (void) startLoop { running = YES; #ifdef THREADED_ANIMATION [NSThread detachNewThreadSelector:@selector(gameLoop) toTarget:self withObject:nil]; #else timer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60 target:self selector:@selector(renderFrame) userInfo:nil repeats:YES]; #endif } - (void) stopLoop { [timer invalidate]; running = NO; } ``` In the `renderFrame` method You prepare the framebuffer, draw frame and present the framebuffer on screen. (P.S. There is a great [article](http://dewitters.koonsolo.com/gameloop.html) on various types of game loops and their pros and cons.)
96,285
<p>I'm fresh out of college and have been working in C++ for some time now. I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes. I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out. This is killing me because I feel like its keeping me from bring my C++ programming to the next level. Did anybody else have this problem? If so, how did you break through it? Does anyone know of any books or tutorials that really describe pointers and class concepts well? or maybe some example code with good descriptive comments using advanced pointers and class techniques? any help would be greatly appreciated.</p>
[ { "answer_id": 96310, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "<p>Pretend a pointer is an array address.</p>\n\n<pre><code>x = 500; // memory address for hello;\nMEMORY[x] = \"hello\"; \nprint MEMORY[x]; \n</code></pre>\n\n<p>its a graphic oversimplification, but for the most part as long as you never want to know what that number is or set it by hand you should be fine. </p>\n\n<p>Back when I understood C I had a few macros I had which more or less permitted you to use pointers just like they <em>were</em> an array index in memory. But I've long since lost that code and long since forgotten. </p>\n\n<p>I recall it started with </p>\n\n<pre><code>#define MEMORY 0; \n#define MEMORYADDRESS( a ) *a;\n</code></pre>\n\n<p>and that on its own is hardly useful. Hopefully somebody else can expand on that logic. </p>\n" }, { "answer_id": 96312, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 1, "selected": false, "text": "<p>For Pointers:</p>\n\n<p>I found <a href=\"https://stackoverflow.com/questions/92001/whats-this-obsession-with-pointers\">this post</a> had very thoughtful discussion about pointers. Maybe that would help. Are you familar with refrences such as in C#? That is something that actually <em>refers</em> to something else? Thats probably a good start for understanding pointers.</p>\n\n<p>Also, look at Kent Fredric's post below on another way to introduce yourself to pointers.</p>\n" }, { "answer_id": 96329, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 2, "selected": false, "text": "<p>I used to have a problem understand pointers in pascal way back :) Once i started doing assembler pointers was really the only way to access memory and it just hit me. It might sound like a far shot, but trying out assembler (which is always a good idea to try and understand what computers is really about) probably will teach you pointers. Classes - well i don't understand your problem - was your schooling pure structured programming? A class is just a logical way of looking at real life models - you're trying to solve a problem which could be summed up in a number of objects/classes.</p>\n" }, { "answer_id": 96332, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p>To understand pointers, I can't recommend the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131103628\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">K&amp;R</a> book highly enough.</p>\n" }, { "answer_id": 96333, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 0, "selected": false, "text": "<p>The best book I've read on these topics is Thinking in C++ by Bruce Eckel. You can download it for free <a href=\"http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 96342, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>Pointers and classes are completely different topics so I wouldn't really lump them in together like this. Of the two, I would say pointers are more fundamental.</p>\n\n<p>A good exercise for learning about what pointers are is the following:</p>\n\n<ol>\n<li>create a linked list</li>\n<li>iterate through it from start to finish</li>\n<li>reverse it so that the head is now the back and the back is now the head</li>\n</ol>\n\n<p>Do it all on a whiteboard first. If you can do this easily, you should have no more problems understanding what pointers are.</p>\n" }, { "answer_id": 96353, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://cslibrary.stanford.edu/104/\" rel=\"noreferrer\">This link</a> has a video describing how pointers work, with claymation. Informative, and easy to digest.</p>\n\n<p><a href=\"http://parashift.com/c++-faq-lite/classes-and-objects.html\" rel=\"noreferrer\">This page</a> has some good information on the basic of classes.</p>\n" }, { "answer_id": 96355, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 4, "selected": false, "text": "<p>Pointers and classes aren't really advanced topics in C++. They are pretty fundamental.</p>\n\n<p>For me, pointers solidified when I started drawing boxes with arrows. Draw a box for an int. And int* is now a separate box with an arrow pointing to the int box. </p>\n\n<p>So:</p>\n\n<pre><code>int foo = 3; // integer\nint* bar = &amp;foo; // assigns the address of foo to my pointer bar\n</code></pre>\n\n<p>With my pointer's box (bar) I have the choice of either looking at the address inside the box. (Which is the memory address of foo). Or I can manipulate whatever I have an address to. That manipulation means I'm following that arrow to the integer (foo). </p>\n\n<pre><code>*bar = 5; // asterix means \"dereference\" (follow the arrow), foo is now 5\nbar = 0; // I just changed the address that bar points to\n</code></pre>\n\n<p>Classes are another topic entirely. There's some books on object oriented design, but I don't know good ones for beginners of the top of my head. You might have luck with an intro Java book.</p>\n" }, { "answer_id": 96394, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 0, "selected": false, "text": "<p>For classes:</p>\n\n<p>The breakthru moment for me was when I learned about interfaces. The idea of abstracting away the details of how you wrote solved a problem, and giving just a list of methods that interact with the class was very insightful.</p>\n\n<p>In fact, my professor explicitly told us that he would grade our programs by plugging our classes into his test harness. Grading would be done based on the requirements he gave to us and whether the program crashed.</p>\n\n<p>Long story short, classes let you wrap up functionality and call it in a cleaner manner (most of the time, there are always exceptions)</p>\n" }, { "answer_id": 96400, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 1, "selected": false, "text": "<p>The book that cracked pointers for me was <a href=\"http://www.amazon.co.uk/Illustrating-Ansi-Iso-Versio-Version/dp/0521468213/ref=sr_1_3?ie=UTF8&amp;s=books&amp;qid=1221768473&amp;sr=8-3\" rel=\"nofollow noreferrer\">Illustrating Ansi C</a> by Donald Alcock. Its full of hand-drawn-style box and arrow diagrams that illustrate pointers, pointer arithmetic, arrays, string functions etc...</p>\n\n<p>Obviously its a 'C' book but for core fundamentals its hard to beat</p>\n" }, { "answer_id": 96408, "author": "shadit", "author_id": 9925, "author_profile": "https://Stackoverflow.com/users/9925", "pm_score": 0, "selected": false, "text": "<p>One of the things that really helped me understand these concepts is to learn UML - the Unified Modeling Language. Seeing concepts of object-oriented design in a graphical format really helped me learn what they mean. Sometimes trying to understand these concepts purely by looking at what source code implements them can be difficult to comprehend.</p>\n\n<p>Seeing object-oriented paradigms like inheritance in graphical form is a very powerful way to grasp the concept.</p>\n\n<p>Martin Fowler's <em>UML Distilled</em> is a good, brief introduction.</p>\n" }, { "answer_id": 96411, "author": "Kevin Pang", "author_id": 1574, "author_profile": "https://Stackoverflow.com/users/1574", "pm_score": 1, "selected": false, "text": "<p>From lassevek's response to a <a href=\"https://stackoverflow.com/questions/5727/understanding-pointers#5754\">similar question on SO</a>:</p>\n\n<blockquote>\n <p>Pointers is a concept that for many\n can be confusing at first, in\n particular when it comes to copying\n pointer values around and still\n referencing the same memory block.</p>\n \n <p>I've found that the best analogy is to\n consider the pointer as a piece of\n paper with a house address on it, and\n the memory block it references as the\n actual house. All sorts of operations\n can thus be easily explained:</p>\n \n <ul>\n <li>Copy pointer value, just write the address on a new piece of paper</li>\n <li>Linked lists, piece of paper at the house with the address of the next\n house on it</li>\n <li>Freeing the memory, demolish the house and erase the address</li>\n <li>Memory leak, you lose the piece of paper and cannot find the house</li>\n <li>Freeing the memory but keeping a (now invalid) reference, demolish the\n house, erase one of the pieces of\n paper but have another piece of paper\n with the old address on it, when you\n go to the address, you won't find a\n house, but you might find something\n that resembles the ruins of one</li>\n <li>Buffer overrun, you move more stuff into the house than you can\n possibly fit, spilling into the\n neighbours house</li>\n </ul>\n</blockquote>\n" }, { "answer_id": 96412, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 0, "selected": false, "text": "<p>To better understand pointers, I think, it may be useful to look at how the assembly language works with pointers. The concept of pointers is really one of the fundamental parts of the assembly language and x86 processor instruction architecture. Maybe it'll kind of let you fell like pointers are a natural part of a program.</p>\n\n<p>As to classes, aside from the OO paradigm I think it may be interesting to look at classes from a low-level binary perspective. They aren't that complex in this respect on the basic level.</p>\n\n<p>You may read <a href=\"http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fwww.amazon.com%2FInside-Object-Model-Stanley-Lippman%2Fdp%2F0201834545&amp;ei=FLnSSO2ZLp3uQont5IkK&amp;usg=AFQjCNFzPwXc6GMJqD9y17GTJKczXltwGg&amp;sig2=98ty8nCVp0qJCSplwp0IDQ\" rel=\"nofollow noreferrer\">Inside the C++ Object Model</a> if you want to get a better understanding of what is underneath C++ object model. </p>\n" }, { "answer_id": 96425, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 2, "selected": false, "text": "<p>Pointers already seem to be addressed (no pun intended) in other answers.</p>\n\n<p>Classes are fundamental to OO. I had tremendous trouble wrenching my head into OO - like, ten years of failed attempts. The book that finally helped me was Craig Larman's \"Applying UML and Patterns\". I know it sounds as if it's about something different, but it really does a great job of easing you into the world of classes and objects.</p>\n" }, { "answer_id": 96442, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>We were just discussing some of the aspects of C++ and OO at lunch, someone (a great engineer actually) was saying that unless you have a really strong programming background before you learn C++, it will literally ruin you.</p>\n\n<p>I highly recommend learning another language first, then shifting to C++ when you need it. It's not like there is anything great about pointers, they are simply a vestigial piece left over from when it was difficult for a compiler convert operations to assembly efficiently without them.</p>\n\n<p>These days if a compiler can't optimize an array operation better then you can using pointers, your compiler is broken.</p>\n\n<p>Please don't get me wrong, I'm not saying C++ is horrible or anything and don't want to start an advocacy discussion, I've used it and use it occasionally now, I'm just recommending you start with something else.</p>\n\n<p>It's really NOT like learning to drive a manual car then easily being able to apply that to an automatic, it's more like learning to drive on one of those huge construction cranes then assuming that will apply when you start to drive a car--then you find yourself driving your car down the middle of the street at 5mph with your emergency lights on.</p>\n\n<p>[edit] reviewing that last paragraph--I think that may have been my most accurate analogy ever!</p>\n" }, { "answer_id": 96457, "author": "Ashley Davis", "author_id": 25868, "author_profile": "https://Stackoverflow.com/users/25868", "pm_score": 1, "selected": false, "text": "<p>Learn assembly language and then learn C. Then you will know what the underlying principles of machine are (and thefore pointers).</p>\n\n<p>Pointers and classes are fundamental aspects of C++. If you don't understand them then it means that you don't really understand C++. </p>\n\n<p>Personally I held back on C++ for several years until I felt I had a firm grasp of C and what was happening under the hood in assembly language. Although this was quite a long time ago now I think it really benefited my career to understand how the computer works at a low-level.</p>\n\n<p>Learning to program can take many years, but you should stick with it because it is a very rewarding career. </p>\n" }, { "answer_id": 96503, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 0, "selected": false, "text": "<p>Classes are relatively easy to grasp; OOP can take you many years. Personally, I didn't fully grasp true OOP until last year-ish. It is too bad that Smalltalk isn't as widespread in colleges as it should be. It really drives home the point that OOP is about objects trading messages, instead of classes being self-contained global variables with functions.</p>\n\n<p>If you truly are new to classes, then the concept can take a while to grasp. When I first encountered them in 10th grade, I didn't get it until I had someone who knew what they were doing step through the code and explain what was going on. That is what I suggest you try.</p>\n" }, { "answer_id": 96512, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "<p>There's no substitute for practicing.</p>\n<p>It's easy to read through a book or listen to a lecture and feel like you're following what's going on.</p>\n<p>What I would recommend is taking some of the code examples (I assume you have them on disk somewhere), compile them and run them, then try to change them to do something different.</p>\n<ul>\n<li>Add another subclass to a hierarchy</li>\n<li>Add a method to an existing class</li>\n<li>Change an algorithm that iterates\nforward through a collection to go\nbackward instead.</li>\n</ul>\n<p>I don't think there's any &quot;silver bullet&quot; book that's going to do it.</p>\n<p>For me, what drove home what pointers meant was working in assembly, and seeing that a pointer was actually just an address, and that having a pointer didn't mean that what it pointed to was a meaningful object.</p>\n" }, { "answer_id": 96595, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 0, "selected": false, "text": "<p>The point at which I really got pointers was coding TurboPascal on a FatMac (around 1984 or so) - which was the native Mac language at the time.</p>\n\n<p>The Mac had an odd memory model whereby when allocated the address the memory was stored in a pointer on the heap, but the location of that itself was not guaranteed and instead the memory handling routines returned a pointer to the pointer - referred to as a handle. Consequently to access any part of the allocated memory it was necessary to dereference the handle twice. It took a while, but constant practice eventually drove the lesson home.</p>\n\n<p>Pascal's pointer handling is easier to grasp than C++, where the syntax doesn't help the beginner. If you are really and truly stuck understanding pointers in C then your best option might be to obtain a copy a a Pascal compiler and try writing some basic pointer code in it (Pascal is near enough to C you'll get the basics in a few hours). Linked lists and the like would be a good choice. Once you're comfortable with those return to C++ and with the concepts mastered you'll find that the cliff won't look so steep.</p>\n" }, { "answer_id": 96635, "author": "Dan", "author_id": 8251, "author_profile": "https://Stackoverflow.com/users/8251", "pm_score": 1, "selected": false, "text": "<p>In a sense, you can consider \"pointers\" to be one of the two most fundamental types in software - the other being \"values\" (or \"data\") - that exist in a huge block of uniquely-addressable memory locations. Think about it. Objects and structs etc don't really exist in memory, only values and pointers do. In fact, a pointer is a value too....the value of a memory address, which in turn contains another value....and so on.</p>\n\n<p>So, in C/C++, when you declare an \"int\" (intA), you are defining a 32bit chunk of memory that contains a value - a number. If you then declare an \"int pointer\" (intB), you are defining a 32bit chunk of memory that contains the address of an int. I can assign the latter to point to the former by stating \"intB = &amp;intA\", and now the 32bits of memory defined as intB, contains an address corresponding to intA's location in memory.</p>\n\n<p>When you \"dereference\" the intB pointer, you are looking at the address stored within intB's memory, finding that location, and then looking at the value stored there (a number).</p>\n\n<p>Commonly, I have encountered confusion when people lose track of exactly what it is they're dealing with as they use the \"&amp;\", \"*\" and \"->\" operators - is it an address, a value or what? You just need to keep focused on the fact that memory addresses are simply locations, and that values are the binary information stored there.</p>\n" }, { "answer_id": 96755, "author": "John", "author_id": 13895, "author_profile": "https://Stackoverflow.com/users/13895", "pm_score": 0, "selected": false, "text": "<p>Did you read Bjarne Stroustrup's <em>The C++ Programming Language</em>? He created C++.</p>\n\n<p>The C++ FAQ Lite is also good.</p>\n" }, { "answer_id": 96891, "author": "PiNoYBoY82", "author_id": 13646, "author_profile": "https://Stackoverflow.com/users/13646", "pm_score": 1, "selected": false, "text": "<p>For pointers and classes, here is my analogy. I'll use a deck of cards. The deck of cards has a face value and a type (9 of hearts, 4 of spades, etc.). So in our C++ like programming language of \"Deck of Cards\" we'll say the following:</p>\n\n<pre><code>HeartCard card = 4; // 4 of hearts!\n</code></pre>\n\n<p>Now, you know where the 4 of hearts is because by golly, you're holding the deck, face up in your hand, and it's at the top! So in relation to the rest of the cards, we'll just say the 4 of hearts is at BEGINNING. So, if I asked you what card is at BEGINNING, you would say, \"The 4 of hearts of course!\". Well, you just \"pointed\" me to where the card is. In our \"Deck of Cards\" programming language, you could just as well say the following:</p>\n\n<pre><code>HeartCard card = 4; // 4 of hearts!\nprint &amp;card // the address is BEGINNING!\n</code></pre>\n\n<p>Now, turn your deck of cards over. The back side is now BEGINNING and you don't know what the card is. But, let's say you can make it whatever you want because you're full of magic. Let's do this in our \"Deck of Cards\" langauge!</p>\n\n<pre><code>HeartCard *pointerToCard = MakeMyCard( \"10 of hearts\" );\nprint pointerToCard // the value of this is BEGINNING!\nprint *pointerToCard // this will be 10 of hearts!\n</code></pre>\n\n<p>Well, MakeMyCard( \"10 of hearts\" ) was you doing your magic and knowing that you wanted to point to BEGINNING, making the card a 10 of hearts! You turn your card over and, voila! Now, the * may throw you off. If so, check this out:</p>\n\n<pre><code>HeartCard *pointerToCard = MakeMyCard( \"10 of hearts\" );\nHeartCard card = 4; // 4 of hearts!\nprint *pointerToCard; // prints 10 of hearts\nprint pointerToCard; // prints BEGINNING\nprint card; // prints 4 of hearts\nprint &amp;card; // prints END - the 4 of hearts used to be on top but we flipped over the deck!\n</code></pre>\n\n<p>As for classes, we've been using classes in the example by defining a type as HeartCard. We know what a HeartCard is... It's a card with a value and the type of heart! So, we've classified that as a HeartCard. Each language has a similar way of defining or \"classifying\" what you want, but they all share the same concept! Hope this helped...</p>\n" }, { "answer_id": 97638, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>You may find this <a href=\"http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html\" rel=\"nofollow noreferrer\">article by Joel</a> instructive. As an aside, if you've been \"working in C++ for some time\" and have graduated in CS, you may have gone to a JavaSchool (I'd argue that you haven't been working in C++ at all; you've been working in C but using the C++ compiler). </p>\n\n<p>Also, just to second the answers of hojou and nsanders, pointers are very fundamental to C++. If you don't understand pointers, then you don't understand the basics of C++ (acknowledging this fact is the beginning of understanding C++, by the way). Similarly, if you don't understand classes, then you don't understand the basics of C++ (or OO for that matter).</p>\n\n<p>For pointers, I think drawing with boxes is a fine idea, but working in assembly is also a good idea. Any instructions that use relative addressing will get you to an understanding of what pointers are rather quickly, I think.</p>\n\n<p>As for classes (and object-oriented programming more generally), I would recommend Stroustrups \"The C++ Programming Language\" latest edition. Not only is it the canonical C++ reference material, but it also has quite a bit of material on a lot of other things, from basic object-oriented class hierarchies and inheritance all the way up to design principles in large systems. It's a very good read (if not a little thick and terse in spots).</p>\n" }, { "answer_id": 98525, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 4, "selected": false, "text": "<p>Understanding Pointers in C/C++</p>\n\n<p>Before one can understand how pointers work, it is necessary to understand how variables are stored and accessed in programs. Every variable has 2 parts to it - (1) the memory address where the data is stored and (2) the value of the data stored.</p>\n\n<p>The memory address is often referred to as the lvalue of a variable, and the value of the data stored is referred to as the rvalue (l and r meaning left and right).</p>\n\n<p>Consider the statement: </p>\n\n<pre><code>int x = 10;\n</code></pre>\n\n<p>Internally, the program associates a memory address with the variable x. In this case, let's assume that the program assigns x to reside at the address 1001 (not a realistic address, but chosen for simplicity). Therefore, the lvalue (memory address) of x is 1001, and the rvalue (data value) of x is 10.</p>\n\n<p>The rvalue is accessed by simply using the variable “x”. In order to access the lvalue, the “address of” operator (‘&amp;’) is needed. The expression ‘&amp;x’ is read as \"the address of x\". </p>\n\n<pre><code>Expression Value\n----------------------------------\nx 10\n&amp;x 1001\n</code></pre>\n\n<p>The value stored in x can be changed at any time (e.g. x = 20), but the address of x (&amp;x) can never be changed.</p>\n\n<p>A pointer is simply a variable that can be used to modify another variable. It does this by having a memory address for its rvalue. That is, it points to another location in memory.</p>\n\n<p>Creating a pointer to “x” is done as follows:</p>\n\n<pre><code>int* xptr = &amp;x;\n</code></pre>\n\n<p>The “int*” tells the compiler that we are creating a pointer to an integer value. The “= &amp;x” part tells the compiler that we are assigning the address of x to the rvalue of xptr. Thus, we are telling the compiler that xptr “points to” x.</p>\n\n<p>Assuming that xptr is assigned to a memory address of 1002, then the program’s memory might look like this:</p>\n\n<pre><code>Variable lvalue rvalue\n--------------------------------------------\nx 1001 10 \nxptr 1002 1001\n</code></pre>\n\n<p>The next piece of the puzzle is the \"indirection operator\" (‘*’), which is used as follows:</p>\n\n<pre><code>int y = *xptr;\n</code></pre>\n\n<p>The indirection operator tells the program to interpret the rvalue of xptr as a memory address rather than a data value. That is, the program looks for the data value (10) stored at the address provided by xptr (1001).</p>\n\n<p>Putting it all together:</p>\n\n<pre><code>Expression Value\n--------------------------------------------\nx 10\n&amp;x 1001\nxptr 1001\n&amp;xptr 1002\n*xptr 10\n</code></pre>\n\n<p>Now that the concepts have been explained, here is some code to demonstrate the power of pointers:</p>\n\n<pre><code>int x = 10;\nint *xptr = &amp;x;\n\nprintf(\"x = %d\\n\", x);\nprintf(\"&amp;x = %d\\n\", &amp;x); \nprintf(\"xptr = %d\\n\", xptr);\nprintf(\"*xptr = %d\\n\", *xptr);\n\n*xptr = 20;\n\nprintf(\"x = %d\\n\", x);\nprintf(\"*xptr = %d\\n\", *xptr);\n</code></pre>\n\n<p>For output you would see (Note: the memory address will be different each time):</p>\n\n<pre><code>x = 10\n&amp;x = 3537176\nxptr = 3537176\n*xptr = 10\nx = 20\n*xptr = 20\n</code></pre>\n\n<p>Notice how assigning a value to ‘*xptr’ changed the value of ‘x’. This is because ‘*xptr’ and ‘x’ refer to the same location in memory, as evidenced by ‘&amp;x’ and ‘xptr’ having the same value.</p>\n" }, { "answer_id": 112083, "author": "radu_c", "author_id": 19577, "author_profile": "https://Stackoverflow.com/users/19577", "pm_score": 0, "selected": false, "text": "<p>Pointers are not some sort of magical stuff, you're using them all the time!<br>\nWhen you say:<br></p>\n\n<p>int a;<br></p>\n\n<p>and the compiler generates storage for 'a', you're practically saying that you're declaring<br>an int and you want to name its memory location 'a'.<br></p>\n\n<p>When you say:<br></p>\n\n<p>int *a;<br></p>\n\n<p>you're declaring a variable that can hold a memory location of an int.\nIt's that simple. Also, don't be scared about pointer arithmetics, just always\nhave in mind a \"memory map\" when you're dealing with pointers and think in terms\nof walking through memory addresses.</p>\n\n<p>Classes in C++ are just one way of defining abstract data types. I'd suggest reading a good OOP book to understand the concept, then, if you're interested, learn how C++ compilers generate code to simulate OOP. But this knowledge will come in time, if you stick with C++ long enough :)</p>\n" }, { "answer_id": 112177, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 0, "selected": false, "text": "<p>Your problem seems to be the C core in C++, not C++ itself. Get yourself the Kernighan &amp; Ritchie (<em>The C Programming Language</em>). Inhale it. It's very good stuff, one of the best programming language books ever written.</p>\n" }, { "answer_id": 115993, "author": "Matt Pascoe", "author_id": 20229, "author_profile": "https://Stackoverflow.com/users/20229", "pm_score": 1, "selected": false, "text": "<p>In the case of classes I had three techniques that really helped me make the jump into real object oriented programming. </p>\n\n<p>The first was I worked on a game project that made heavy use of classes and objects, with heavy use of generalization (kind-of or is-a relationship, ex. student is a kind of person) and composition (has-a relationship, ex. student has a student loan). Breaking apart this code took a lot of work, but really brought things into perspective.</p>\n\n<p>The second thing that helped was in my System Analysis class, where I had to make http://www.agilemodeling.com/artifacts/classDiagram.htm\">UML class diagrams. These I just really found helped me understand the structure of classes in a program.</p>\n\n<p>Lastly, I help tutor students at my college in programming. All I can really say about this is you learn a lot by teaching and by seeing other people's approach to a problem. Many times a student will try things that I would never have thought of, but usually make a lot of sense and they just have problems implementing their idea.</p>\n\n<p>My best word of advice is it takes a lot of practice, and the more you program the better you will understand it. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117494/" ]
I'm fresh out of college and have been working in C++ for some time now. I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes. I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out. This is killing me because I feel like its keeping me from bring my C++ programming to the next level. Did anybody else have this problem? If so, how did you break through it? Does anyone know of any books or tutorials that really describe pointers and class concepts well? or maybe some example code with good descriptive comments using advanced pointers and class techniques? any help would be greatly appreciated.
Pointers and classes aren't really advanced topics in C++. They are pretty fundamental. For me, pointers solidified when I started drawing boxes with arrows. Draw a box for an int. And int\* is now a separate box with an arrow pointing to the int box. So: ``` int foo = 3; // integer int* bar = &foo; // assigns the address of foo to my pointer bar ``` With my pointer's box (bar) I have the choice of either looking at the address inside the box. (Which is the memory address of foo). Or I can manipulate whatever I have an address to. That manipulation means I'm following that arrow to the integer (foo). ``` *bar = 5; // asterix means "dereference" (follow the arrow), foo is now 5 bar = 0; // I just changed the address that bar points to ``` Classes are another topic entirely. There's some books on object oriented design, but I don't know good ones for beginners of the top of my head. You might have luck with an intro Java book.
96,297
<h2>General</h2> <ul> <li>Follow the same standards for all tests.</li> <li>Be clear about what each test state is.</li> <li>Be specific about the expected behavior.</li> </ul> <h2>Examples</h2> <p>1) MethodName_StateUnderTest_ExpectedBehavior</p> <pre><code>Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () Public void Sum_simpleValues_Calculated () </code></pre> <p>Source: <a href="http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html" rel="noreferrer">Naming standards for Unit Tests</a></p> <p>2) Separating Each Word By Underscore</p> <pre><code>Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () Public void Sum_Simple_Values_Calculated () </code></pre> <h2>Other</h2> <ul> <li>End method names with <em>Test</em></li> <li>Start method names with class name</li> </ul>
[ { "answer_id": 96344, "author": "Munger", "author_id": 17661, "author_profile": "https://Stackoverflow.com/users/17661", "pm_score": -1, "selected": false, "text": "<p>As long as you follow a single practice, it doesn't really matter. Generally, I write a single unit test for a method that covers all the variations for a method (I have simple methods;) and then write more complex sets of tests for methods that require it. My naming structure is thus usually test (a holdover from JUnit 3).</p>\n" }, { "answer_id": 96347, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 3, "selected": false, "text": "<p>The first set of names is more readable to me, since the CamelCasing separates words and the underbars separate parts of the naming scheme.</p>\n\n<p>I also tend to include \"Test\" somewhere, either in the function name or the enclosing namespace or class.</p>\n" }, { "answer_id": 96602, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 8, "selected": true, "text": "<p>I am pretty much with you on this one man. The naming conventions you have used are:</p>\n\n<ul>\n<li>Clear about what each test state is.</li>\n<li>Specific about the expected behaviour.</li>\n</ul>\n\n<p>What more do you need from a test name?</p>\n\n<p>Contrary to <a href=\"https://stackoverflow.com/questions/96297/naming-conventions-for-unit-tests#96476\">Ray's answer</a> I don't think the <em>Test</em> prefix is necessary. It's test code, we know that. If you need to do this to identify the code, then you have bigger problems, <strong>your test code should not be mixed up with your production code.</strong></p>\n\n<p>As for length and use of underscore, its <strong>test code</strong>, who the hell cares? Only you and your team will see it, so long as it is readable, and clear about what the test is doing, carry on! :)</p>\n\n<p>That said, I am still quite new to testing and <a href=\"http://cantgrokwontgrok.blogspot.com/2008/09/tdd-getting-started-with-test-driven.html\" rel=\"noreferrer\">blogging my adventures with it</a> :)</p>\n" }, { "answer_id": 1292173, "author": "Jehof", "author_id": 83039, "author_profile": "https://Stackoverflow.com/users/83039", "pm_score": 5, "selected": false, "text": "<p>I do name my test methods like other methods using \"PascalCasing\" without any underscores or separators. I leave the postfix <em>Test</em> for the method out, cause it adds no value. That the method is a test method is indicated by the attribute <em>TestMethod</em>.</p>\n\n<pre><code>[TestMethod]\npublic void CanCountAllItems() {\n // Test the total count of items in collection.\n}\n</code></pre>\n\n<p>Due to the fact that each Test class should only test one other class i leave the name of the class out of the method name. The name of the class that contains the test methods is named like the class under test with the postfix \"Tests\".</p>\n\n<pre><code>[TestClass]\npublic class SuperCollectionTests(){\n // Any test methods that test the class SuperCollection\n}\n</code></pre>\n\n<p>For methods that test for exceptions or actions that are not possible, i prefix the test method with the word <em>Cannot</em>.</p>\n\n<pre><code>[TestMethod]\n[ExpectedException(typeOf(ArgumentException))]\npublic void CannotAddSameObjectAgain() {\n // Cannot add the same object again to the collection.\n}\n</code></pre>\n\n<p>My naming convension are base on the article <a href=\"http://www.bryancook.net/2008/06/test-naming-conventions-guidelines.html\" rel=\"noreferrer\">\"TDD Tips: Test Naming Conventions &amp; Guidelines\"</a> of Bryan Cook. I found this article very helpful.</p>\n" }, { "answer_id": 4622383, "author": "user566399", "author_id": 566399, "author_profile": "https://Stackoverflow.com/users/566399", "pm_score": -1, "selected": false, "text": "<p>I use a 'T' prefix for test namespaces, classes and methods.</p>\n\n<p>I try to be neat and create folders that replicate the namespaces, then create a tests folder or separate project for the tests and replicate the production structure for the basic tests:</p>\n\n<pre><code>AProj\n Objects\n AnObj\n AProp\n Misc\n Functions\n AFunc\n Tests\n TObjects\n TAnObj\n TAnObjsAreEqualUnderCondition\n TMisc\n TFunctions\n TFuncBehavesUnderCondition\n</code></pre>\n\n<p>I can easily see that something is a test, I know exactly what original code it pertains to, (if you can't work that out, then the test is too convoluted anyway).</p>\n\n<p>It looks just like the interfaces naming convention, (I mean, you don't get confused with things starting with 'I', nor will you with 'T').</p>\n\n<p>It's easy to just compile with or without the tests.</p>\n\n<p>It's good in theory anyway, and works pretty well for small projects.</p>\n" }, { "answer_id": 8955564, "author": "Robs", "author_id": 78077, "author_profile": "https://Stackoverflow.com/users/78077", "pm_score": 5, "selected": false, "text": "<p>This is also worth a read: <a href=\"http://haacked.com/archive/2012/01/02/structuring-unit-tests.aspx\" rel=\"noreferrer\">Structuring Unit Tests</a></p>\n<blockquote>\n<p>The structure has a test class per class being tested. That’s not so unusual. But what was unusual to me was that he had a nested class for each method being tested.</p>\n</blockquote>\n<p>e.g.</p>\n<pre><code>using Xunit;\n\npublic class TitleizerFacts\n{\n public class TheTitleizerMethod\n {\n [Fact]\n public void NullName_ReturnsDefaultTitle()\n {\n // Test code\n }\n\n [Fact]\n public void Name_AppendsTitle()\n {\n // Test code\n }\n }\n\n public class TheKnightifyMethod\n {\n [Fact]\n public void NullName_ReturnsDefaultTitle()\n {\n // Test code\n }\n\n [Fact]\n public void MaleNames_AppendsSir()\n {\n // Test code\n }\n\n [Fact]\n public void FemaleNames_AppendsDame()\n {\n // Test code\n }\n }\n}\n</code></pre>\n<p>And here is why:</p>\n<blockquote>\n<p>Well for one thing, it’s a nice way to keep tests organized. All the\ntests (or facts) for a method are grouped together. For example, if\nyou use the CTRL+M, CTRL+O shortcut to collapse method bodies, you can\neasily scan your tests and read them like a spec for your code.</p>\n</blockquote>\n<p>I also like this approach:</p>\n<p><strong>MethodName_StateUnderTest_ExpectedBehavior</strong></p>\n<p>So perhaps adjust to:</p>\n<p><strong>StateUnderTest_ExpectedBehavior</strong></p>\n<p>Because each test will already be in a nested class</p>\n" }, { "answer_id": 9298985, "author": "CodingWithSpike", "author_id": 28278, "author_profile": "https://Stackoverflow.com/users/28278", "pm_score": 5, "selected": false, "text": "<p>I tend to use the convention of <code>MethodName_DoesWhat_WhenTheseConditions</code> so for example:</p>\n\n<pre><code>Sum_ThrowsException_WhenNegativeNumberAs1stParam\n</code></pre>\n\n<p>However, what I do see a lot is to make the test name follow the unit testing structure of</p>\n\n<ul>\n<li>Arrange</li>\n<li>Act</li>\n<li>Assert</li>\n</ul>\n\n<p>Which also follows the BDD / Gherkin syntax of:</p>\n\n<ul>\n<li>Given</li>\n<li>When</li>\n<li>Then</li>\n</ul>\n\n<p>which would be to name the test in the manner of: <code>UnderTheseTestConditions_WhenIDoThis_ThenIGetThis</code></p>\n\n<p>so to your example:</p>\n\n<pre><code>WhenNegativeNumberAs1stParam_Sum_ThrowsAnException\n</code></pre>\n\n<p>However I do much prefer putting the method name being tested first, because then the tests can be arranged alphabetically, or appear alphabetically sorted in the member dropdown box in VisStudio, and all the tests for 1 method are grouped together.</p>\n\n<hr>\n\n<p>In any case, I like separating the major <em>sections</em> of the test name with underscores, as opposed to every <em>word</em>, because I think it makes it easier to read and get the point of the test across.</p>\n\n<p>In other words, I like: <code>Sum_ThrowsException_WhenNegativeNumberAs1stParam</code> better than <code>Sum_Throws_Exception_When_Negative_Number_As_1st_Param</code>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18170/" ]
General ------- * Follow the same standards for all tests. * Be clear about what each test state is. * Be specific about the expected behavior. Examples -------- 1) MethodName\_StateUnderTest\_ExpectedBehavior ``` Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () Public void Sum_simpleValues_Calculated () ``` Source: [Naming standards for Unit Tests](http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html) 2) Separating Each Word By Underscore ``` Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () Public void Sum_Simple_Values_Calculated () ``` Other ----- * End method names with *Test* * Start method names with class name
I am pretty much with you on this one man. The naming conventions you have used are: * Clear about what each test state is. * Specific about the expected behaviour. What more do you need from a test name? Contrary to [Ray's answer](https://stackoverflow.com/questions/96297/naming-conventions-for-unit-tests#96476) I don't think the *Test* prefix is necessary. It's test code, we know that. If you need to do this to identify the code, then you have bigger problems, **your test code should not be mixed up with your production code.** As for length and use of underscore, its **test code**, who the hell cares? Only you and your team will see it, so long as it is readable, and clear about what the test is doing, carry on! :) That said, I am still quite new to testing and [blogging my adventures with it](http://cantgrokwontgrok.blogspot.com/2008/09/tdd-getting-started-with-test-driven.html) :)
96,313
<p>I've got a couple large checkouts where the .svn folder has become damaged so I'm getting and error, "Cleanup failed to process the following path.." And I can no longer commit or update files in that directory.</p> <p>I'd just delete and do the checkout again but the whole directory is over a gig.</p> <p>Is there a tool that will restore the .svn folders for specific folders without having to download everything?</p> <p>I understand that it's going to have to download all the files in that one folder so that it can determine if they've been changed..but subdirectories with valid .svn folders should be fine.</p> <p>Oh.. I'm a big fan of TortoiseSVN or the command line for linux.</p> <p>Thoughts?</p>
[ { "answer_id": 96364, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "<p>I've hit this in the past and found no working solution except the \"nuclear option\" (i.e. delete the directory and re-checkout).</p>\n\n<p>Not sure if this is your problem, but my corruption was being caused by an on-access virus scanner on the same machine as SVN server.</p>\n" }, { "answer_id": 96372, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>If you know which folder has the damaged .svn directory, you can just delete that one directory and run an svn update again. You may have to delete the whole directory including its current contents. Of course, if the folder with the damaged .svn directory is the one containing a gigabyte, then you're back where you started.</p>\n" }, { "answer_id": 96415, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 6, "selected": true, "text": "<p>In case you have changes to the files, and cannot delete them, you can use the Subversion 1.5 feature that allows you to 'checkout with obstructions'.</p>\n\n<p>Just delete the .svn directory in this directory and:<br>\n(you don't need to delete inside directories when using --depth files, thanks Eric)</p>\n\n<p>In case the broken directory was the top directory of the working copy:</p>\n\n<pre><code>svn checkout --depth files --force REPOS WC\n</code></pre>\n\n<p>And if the directory above the broken one is still versioned run:</p>\n\n<pre><code>svn update --depth files --force WC\n</code></pre>\n\n<p>in that directory.<br>\nIn both samples REPOS is the url in the repository that matches the broken directory, and WC is the path to the directory.</p>\n\n<p>Files that were originally modified will be in the modified state after this.</p>\n" }, { "answer_id": 96437, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>If the subdirectories and OK and it's the subdirectories that are large, you could try a non-recursive fresh checkout.</p>\n" }, { "answer_id": 96449, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 2, "selected": false, "text": "<p>Make a backup of the folder that has the missing .svn</p>\n\n<p>Then delete the folder</p>\n\n<p>If it is the root of the checkout, you will have to re-checkout</p>\n\n<p>If it is not the root, just run an update from a directory above.</p>\n\n<p>Then move the backup folder on top of it. (Ideally do not move back the .svn folders)</p>\n\n<p>Continue working and be sure to update/commit!</p>\n" }, { "answer_id": 279620, "author": "wen", "author_id": 10318, "author_profile": "https://Stackoverflow.com/users/10318", "pm_score": 0, "selected": false, "text": "<p>I encountered the same error today. It happened when I tried to switch branches and fail to delete one of the file that is not in svn repository. After that, the folder was locked and I can't use any command to get it work again. </p>\n\n<p>I basically deleted what I had and redo the checkout. It is time consuming, but I really want to make sure svn is clear before I can start working again. Thanks!</p>\n" }, { "answer_id": 4056230, "author": "Jon L.", "author_id": 441739, "author_profile": "https://Stackoverflow.com/users/441739", "pm_score": 1, "selected": false, "text": "<p>The selected solution worked for me to restore the top-level .svn folder, but it doesn't recognize the child objects, so everything seems foreign to SVN at this point, despite versioning being intact in subfolders.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430/" ]
I've got a couple large checkouts where the .svn folder has become damaged so I'm getting and error, "Cleanup failed to process the following path.." And I can no longer commit or update files in that directory. I'd just delete and do the checkout again but the whole directory is over a gig. Is there a tool that will restore the .svn folders for specific folders without having to download everything? I understand that it's going to have to download all the files in that one folder so that it can determine if they've been changed..but subdirectories with valid .svn folders should be fine. Oh.. I'm a big fan of TortoiseSVN or the command line for linux. Thoughts?
In case you have changes to the files, and cannot delete them, you can use the Subversion 1.5 feature that allows you to 'checkout with obstructions'. Just delete the .svn directory in this directory and: (you don't need to delete inside directories when using --depth files, thanks Eric) In case the broken directory was the top directory of the working copy: ``` svn checkout --depth files --force REPOS WC ``` And if the directory above the broken one is still versioned run: ``` svn update --depth files --force WC ``` in that directory. In both samples REPOS is the url in the repository that matches the broken directory, and WC is the path to the directory. Files that were originally modified will be in the modified state after this.
96,326
<p>I need to attach a file with mailx but at the moment I am not having success.</p> <p><strong>Here's my code:</strong></p> <pre><code>subject="Something happened" to="[email protected]" body="Attachment Test" attachment=/path/to/somefile.csv uuencode $attachment | mailx -s "$subject" "$to" &lt;&lt; EOF The message is ready to be sent with the following file or link attachments: somefile.csv Note: To protect against computer viruses, e-mail programs may prevent sending or receiving certain types of file attachments. Check your e-mail security settings to determine how attachments are handled. EOF </code></pre> <p>Any feedback would be highly appreciated.</p> <hr> <p><strong>Update</strong> I have added the attachment var to avoid having to use the path every time.</p>
[ { "answer_id": 96616, "author": "Thomas Kammeyer", "author_id": 4410, "author_profile": "https://Stackoverflow.com/users/4410", "pm_score": 1, "selected": false, "text": "<p>Well, here are the first few problems you've got.</p>\n\n<ol>\n<li><p>You appear to be assuming that a mail client is going to handle uuencoded attachment without any headers. That won't happen.</p></li>\n<li><p>You're misusing I/O redirection: uuencode's output and the here-document are both being fed to mailx, which can't happen.</p></li>\n<li><p>You're misusing uuencode: if one path is given, it's just a name to give the decoded file, not an input file name. Giving the file twice will assign the same name to the decoded file as that which was read. The -m flag forces base64 encode. But this still isn't going to provide attachment headers for mailx.</p></li>\n</ol>\n\n<p>You're way better getting a copy of mpack, which will do what you want.</p>\n\n<p>If you must do it, you could do something like this:</p>\n\n<pre><code>cat &lt;&lt;EOF | ( cat -; uuencode -m /path/to/somefile.csv /path/to/somefile.csv; ) | mailx -s \"$subject\" \"$to\" \nplace your message from the here block in your example here\nEOF\n</code></pre>\n\n<p>There are lots of other possibilities... but this one still has the here document\nas in your example and was easy off the top of my head, and there's no temp file involved.</p>\n" }, { "answer_id": 96636, "author": "Palmin", "author_id": 5949, "author_profile": "https://Stackoverflow.com/users/5949", "pm_score": 3, "selected": true, "text": "<p>You have to concat both the text of your message and the uuencoded attachment:</p>\n\n<pre><code>$ subject=\"Something happened\"\n$ to=\"[email protected]\"\n$ body=\"Attachment Test\"\n$ attachment=/path/to/somefile.csv\n$\n$ cat &gt;msg.txt &lt;&lt;EOF\n&gt; The message is ready to be sent with the following file or link attachments:\n&gt;\n&gt; somefile.csv\n&gt;\n&gt; Note: To protect against computer viruses, e-mail programs may prevent\n&gt; sending or receiving certain types of file attachments. Check your\n&gt; e-mail security settings to determine how attachments are handled.\n&gt;\n&gt; EOF\n$ ( cat msg.txt ; uuencode $attachment somefile.csv) | mailx -s \"$subject\" \"$to\"\n</code></pre>\n\n<p>There are different ways to provide the message text, this is just an example that is close to your original question. If the message should be reused it makes sense to just store it in a file and use this file.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
I need to attach a file with mailx but at the moment I am not having success. **Here's my code:** ``` subject="Something happened" to="[email protected]" body="Attachment Test" attachment=/path/to/somefile.csv uuencode $attachment | mailx -s "$subject" "$to" << EOF The message is ready to be sent with the following file or link attachments: somefile.csv Note: To protect against computer viruses, e-mail programs may prevent sending or receiving certain types of file attachments. Check your e-mail security settings to determine how attachments are handled. EOF ``` Any feedback would be highly appreciated. --- **Update** I have added the attachment var to avoid having to use the path every time.
You have to concat both the text of your message and the uuencoded attachment: ``` $ subject="Something happened" $ to="[email protected]" $ body="Attachment Test" $ attachment=/path/to/somefile.csv $ $ cat >msg.txt <<EOF > The message is ready to be sent with the following file or link attachments: > > somefile.csv > > Note: To protect against computer viruses, e-mail programs may prevent > sending or receiving certain types of file attachments. Check your > e-mail security settings to determine how attachments are handled. > > EOF $ ( cat msg.txt ; uuencode $attachment somefile.csv) | mailx -s "$subject" "$to" ``` There are different ways to provide the message text, this is just an example that is close to your original question. If the message should be reused it makes sense to just store it in a file and use this file.
96,340
<p>We have a suite of interlinked .Net 3.5 applications. Some are web sites, some are web services, and some are windows applications. Each app currently has its own configuration file (app.config or web.config), and currently there are some duplicate keys across the config files (which at the moment are kept in sync manually) as multiple apps require the same config value. Also, this suite of applications is deployed across various envrionemnts (dev, test, live etc)</p> <p>What is the best approach to managing the configuration of these multiple apps from a single configuration source, so configuration values can be shared between multiple apps if required? We would also like to have separate configs for each environment (so when deploying you don't have to manually change certain config values that are environment specific such as conenction strings), but at the same time don't want to maintain multiple large config files (one for each environment) as keeping this in sync when adding new config keys will prove troublesome.</p>
[ { "answer_id": 96371, "author": "Kevin Pang", "author_id": 1574, "author_profile": "https://Stackoverflow.com/users/1574", "pm_score": 3, "selected": false, "text": "<p>Visual Studio has a relatively obscure feature that lets you add existing items as links, which should accomplish what you're looking for. Check out <a href=\"http://devlicio.us/blogs/derik_whittaker/archive/2008/04/15/how-to-share-configuration-files-between-projects.aspx\" rel=\"nofollow noreferrer\">Derik Whittaker's post</a> on this topic for more detail.</p>\n\n<p>Visual Studio really should make this option more visible. Nobody really thinks to click on that little arrow next to the \"Add\" button.</p>\n" }, { "answer_id": 96389, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>Check out the prism framework from Microsofts patterns and practices group?</p>\n" }, { "answer_id": 96454, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "<p>You can split App.config into multiple configuration files. You just specify the name of the file that contains the config section.</p>\n\n<p>Change app.config:</p>\n\n<pre><code>&lt;SomeConfigSection&gt;\n &lt;SettingA/&gt;\n &lt;SettingB/&gt;\n&lt;/SomeConfigSection&gt;\n&lt;OtherSection&gt;\n &lt;SettingX/&gt;\n&lt;/OtherSection&gt;\n</code></pre>\n\n<p>Into app.config and SomeSetting.xml:</p>\n\n<pre><code>&lt;SomeConfigSection file=\"SomeSetting.xml\" /&gt;\n&lt;OtherSection file=\"Other.xml\" /&gt;\n</code></pre>\n\n<p>Where SomeSetting.xml contains:\n \n \n \n </p>\n\n<p>Now you can compose your app.config from different section files with some sort of build or deploy script. E.g.:</p>\n\n<pre><code>if debug copy SomeSettingDebug.xml deploydir/SomeSetting.xml\nif MySql copy OtherSectionMySql.xml deploydir/OtherSetting.xml\n</code></pre>\n" }, { "answer_id": 96466, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 2, "selected": true, "text": "<p>We use file templates such as MyApp.config.template and MyWeb.config.template with NAnt properties for the bits that are different between environments. So the template file might look a bit like this:</p>\n\n<pre><code>&lt;MyAppConfig&gt;\n &lt;DbConnString&gt;${DbConnString}&lt;/DbConnString&gt;\n &lt;WebServiceUri uri=\"${WebServiceUri}\" /&gt;\n&lt;/MyAppConfig&gt;\n</code></pre>\n\n<p>During a build we generate all the configs for the different environments by just looping through each environment in a NAnt script, changing the value of the NAnt properties ${DbConnString} and ${WebServiceUri} for each environment (in fact these are all set in a single file with sections for each environment), and doing a NAnt copy with the option to expand properties turned on.</p>\n\n<p>It took a little while to get set up but it has paid us back at least tenfold in the amount of time saved messing around with different versions of config files. </p>\n" }, { "answer_id": 99641, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 1, "selected": false, "text": "<p>These 2 questions might help you: <a href=\"https://stackoverflow.com/questions/94053/how-are-you-using-the-machineconfig-or-are-you\">Utilizing machine.config</a> and <a href=\"https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications\">Managing app.config for large projects</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17765/" ]
We have a suite of interlinked .Net 3.5 applications. Some are web sites, some are web services, and some are windows applications. Each app currently has its own configuration file (app.config or web.config), and currently there are some duplicate keys across the config files (which at the moment are kept in sync manually) as multiple apps require the same config value. Also, this suite of applications is deployed across various envrionemnts (dev, test, live etc) What is the best approach to managing the configuration of these multiple apps from a single configuration source, so configuration values can be shared between multiple apps if required? We would also like to have separate configs for each environment (so when deploying you don't have to manually change certain config values that are environment specific such as conenction strings), but at the same time don't want to maintain multiple large config files (one for each environment) as keeping this in sync when adding new config keys will prove troublesome.
We use file templates such as MyApp.config.template and MyWeb.config.template with NAnt properties for the bits that are different between environments. So the template file might look a bit like this: ``` <MyAppConfig> <DbConnString>${DbConnString}</DbConnString> <WebServiceUri uri="${WebServiceUri}" /> </MyAppConfig> ``` During a build we generate all the configs for the different environments by just looping through each environment in a NAnt script, changing the value of the NAnt properties ${DbConnString} and ${WebServiceUri} for each environment (in fact these are all set in a single file with sections for each environment), and doing a NAnt copy with the option to expand properties turned on. It took a little while to get set up but it has paid us back at least tenfold in the amount of time saved messing around with different versions of config files.
96,360
<p>I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST. (Non essential xml generating code replaced with "Hello there")</p> <pre><code> StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close(); </code></pre> <p>This is causing a server error, and the second servlet is never invoked.</p>
[ { "answer_id": 96393, "author": "Craig B.", "author_id": 10780, "author_profile": "https://Stackoverflow.com/users/10780", "pm_score": 2, "selected": false, "text": "<p>Don't forget to use: </p>\n\n<pre><code>connection.setDoOutput( true)\n</code></pre>\n\n<p>if you intend on sending output.</p>\n" }, { "answer_id": 96410, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 3, "selected": false, "text": "<p>I recommend using Apache <a href=\"http://hc.apache.org/\" rel=\"noreferrer\">HTTPClient</a> instead, because it's a nicer API. </p>\n\n<p>But to solve this current problem: try calling <code>connection.setDoOutput(true);</code> after you open the connection.</p>\n\n<pre><code>StringBuilder sb= new StringBuilder();\nsb.append(\"Hello there\");\n\nURL url = new URL(\"theservlet's URL\");\nHttpURLConnection connection = (HttpURLConnection)url.openConnection(); \nconnection.setDoOutput(true);\nconnection.setRequestMethod(\"POST\");\nconnection.setRequestProperty(\"Content-Length\", \"\" + sb.length());\n\nOutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());\noutputWriter.write(sb.toString());\noutputWriter.flush();\noutputWriter.close();\n</code></pre>\n" }, { "answer_id": 96422, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 5, "selected": true, "text": "<p>This kind of thing is much easier using a library like <a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"noreferrer\">HttpClient</a>. There's even a <a href=\"http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/PostXML.java?view=markup\" rel=\"noreferrer\">post XML code example</a>:</p>\n\n<pre><code>PostMethod post = new PostMethod(url);\nRequestEntity entity = new FileRequestEntity(inputFile, \"text/xml; charset=ISO-8859-1\");\npost.setRequestEntity(entity);\nHttpClient httpclient = new HttpClient();\nint result = httpclient.executeMethod(post);\n</code></pre>\n" }, { "answer_id": 105711, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 2, "selected": false, "text": "<p>The contents of an HTTP post upload stream and the mechanics of it don't seem to be what you are expecting them to be. You cannot just write a file as the post content, because POST has very specific RFC standards on how the data included in a POST request is supposed to be sent. It is not just the formatted of the content itself, but it is also the mechanic of how it is \"written\" to the outputstream. Alot of the time POST is now written in chunks. If you look at the source code of Apache's HTTPClient you will see how it writes the chunks.</p>\n\n<p>There are quirks with the content length as result, because the content length is increased by a small number identifying the chunk and a random small sequence of characters that delimits each chunk as it is written over the stream. Look at some of the other methods described in newer Java versions of the HTTPURLConnection.</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode(int)\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode(int)</a></p>\n\n<p>If you don't know what you are doing and don't want to learn it, dealing with adding a dependency like Apache HTTPClient really does end up being much easier because it abstracts all the complexity and just works.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27/" ]
I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST. (Non essential xml generating code replaced with "Hello there") ``` StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close(); ``` This is causing a server error, and the second servlet is never invoked.
This kind of thing is much easier using a library like [HttpClient](http://hc.apache.org/httpclient-3.x/). There's even a [post XML code example](http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/PostXML.java?view=markup): ``` PostMethod post = new PostMethod(url); RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); int result = httpclient.executeMethod(post); ```
96,377
<p>I am trying to use Validation in WPF. I created a NotNullOrEmptyValidationRule as shown below: </p> <pre><code>public class NotNullOrEmptyValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (String.IsNullOrEmpty(value as String)) return new ValidationResult(false, "Value cannot be null or empty"); return new ValidationResult(true, null); } } </code></pre> <p>Now, I need to use it in my application. In my App.xaml file I declared the Style for the TextBox. Here is the declaration. </p> <pre><code> &lt;Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}"&gt; &lt;Setter Property="Background" Value="Green"/&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="Validation.HasError" Value="True"&gt; &lt;Setter Property="Background" Value="Red"/&gt; &lt;Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>Now, I want to use it on my TextBox so I am using the following code: </p> <pre><code> &lt;TextBox Style="{StaticResource textBoxStyle}"&gt; &lt;TextBox.Text&gt; &lt;Binding&gt; &lt;Binding.ValidationRules&gt; &lt;NotNullOrEmptyValidationRule /&gt; &lt;/Binding.ValidationRules&gt; &lt;/Binding&gt; &lt;/TextBox.Text&gt; &lt;/TextBox&gt; </code></pre> <p>The error comes on the Tag NotNullOrEmptyValidationRule. The XAML syntax checker is not able to resolve the NotNullOrEmptyValidationRule. I have even tried putting the namespace but it does not seem to work. </p>
[ { "answer_id": 96432, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>There is a bug in Visual Studio and Expression Blend that causes this problem. What you need to do is make sure that the Validation rule is in a separately project/assembly that you can reference. This should resolve the problem.</p>\n\n<p>However, you will have to add back the namespace in order for it to work.</p>\n" }, { "answer_id": 96497, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 3, "selected": false, "text": "<p>You just need to add the xmlns to your Window, and use that to reference your ValidationRule. </p>\n\n<p>In WPF, the object is perfectly fine to be used from the same assembly.</p>\n\n<p>Since your rule isn't defined in the standard XAML namespace, you have to create a mapping to your clr namespace like so:</p>\n\n<pre><code>&lt;Window ...\n xmlns:local=\"clr-namespace:MyNamespaceName\"&gt;\n</code></pre>\n\n<p>And then you would use it like so:</p>\n\n<pre><code>&lt;Binding Path=\".\"&gt;\n &lt;Binding.ValidationRules&gt;\n &lt;local:NotNullOrEmptyValidationRule /&gt;\n &lt;/Binding.ValidationRules&gt;\n&lt;/Binding&gt;\n</code></pre>\n\n<p><em>Edit</em>\nI added a Path statement to the Binding. You have to tell the Binding what to bind to :)</p>\n" }, { "answer_id": 99169, "author": "SmartyP", "author_id": 18005, "author_profile": "https://Stackoverflow.com/users/18005", "pm_score": 2, "selected": true, "text": "<p>i see your binding on the TextBox is set to a path of 'Text' - is that a field on whatever the datacontext of this textbox is? is the textbox actually getting a value put into it? also, if you put a breakpoint in your validation method, is that ever getting fired?</p>\n\n<p>you may want to lookup how to log failures in binding and review those as well.. </p>\n" }, { "answer_id": 3633539, "author": "lmheah", "author_id": 438683, "author_profile": "https://Stackoverflow.com/users/438683", "pm_score": 1, "selected": false, "text": "<p>You do not have this line in ur code behind</p>\n\n<pre><code>Public Sub New()\n\n ' This call is required by the Windows Form Designer.\n InitializeComponent()\n\n Me.**NameOfTextBox**.DataContext = Me\nEnd Sub\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
I am trying to use Validation in WPF. I created a NotNullOrEmptyValidationRule as shown below: ``` public class NotNullOrEmptyValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (String.IsNullOrEmpty(value as String)) return new ValidationResult(false, "Value cannot be null or empty"); return new ValidationResult(true, null); } } ``` Now, I need to use it in my application. In my App.xaml file I declared the Style for the TextBox. Here is the declaration. ``` <Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}"> <Setter Property="Background" Value="Green"/> <Style.Triggers> <Trigger Property="Validation.HasError" Value="True"> <Setter Property="Background" Value="Red"/> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> ``` Now, I want to use it on my TextBox so I am using the following code: ``` <TextBox Style="{StaticResource textBoxStyle}"> <TextBox.Text> <Binding> <Binding.ValidationRules> <NotNullOrEmptyValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> ``` The error comes on the Tag NotNullOrEmptyValidationRule. The XAML syntax checker is not able to resolve the NotNullOrEmptyValidationRule. I have even tried putting the namespace but it does not seem to work.
i see your binding on the TextBox is set to a path of 'Text' - is that a field on whatever the datacontext of this textbox is? is the textbox actually getting a value put into it? also, if you put a breakpoint in your validation method, is that ever getting fired? you may want to lookup how to log failures in binding and review those as well..
96,390
<p>I have a SQL statement that looks like:</p> <pre><code>SELECT [Phone] FROM [Table] WHERE ( [Phone] LIKE '[A-Z][a-z]' OR [Phone] = 'N/A' OR [Phone] LIKE '[0]' ) </code></pre> <p>The part I'm having trouble with is the where statement with the "LIKEs". I've seen SQL statements where authors used <code>like</code> statements in the way I'm using them above. At first, I thought this might be a version of Regular Expressions but I've since learned. </p> <p>Is anyone familiar with using like statements in such a way. Note: the "N/A" is working fine. </p> <p>What I need to match is phone numbers that have characters. Or phone numbers which contain nothing but zero.</p>
[ { "answer_id": 96445, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 4, "selected": true, "text": "<p>Check <a href=\"http://technet.microsoft.com/en-us/library/aa933232(v=sql.80).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>[] matches a range of characters.</p>\n\n<p>I think you want something like this:</p>\n\n<pre><code>SELECT [Phone]\nFROM [Table]\nWHERE\n(\n [Phone] LIKE '%[A-Z]%'\n OR [Phone] LIKE '%[a-z]%'\n OR [Phone] = 'N/A'\n OR [Phone] LIKE '0'\n)\n</code></pre>\n" }, { "answer_id": 96451, "author": "therealhoff", "author_id": 18175, "author_profile": "https://Stackoverflow.com/users/18175", "pm_score": 2, "selected": false, "text": "<p>Try using the <code>t-sql</code> <code>ISNUMERIC</code> function. That will show you which ones are/are not numeric.</p>\n\n<p>You may also need to <code>TRIM</code> or <code>REPLACE</code> spaces to get what you want.</p>\n\n<p>For example, to find valid phone numbers, replace spaces with '', test with <code>ISNUMERIC</code>, and test with <code>LEN</code>.</p>\n\n<p>Although I will warn you, this will be tedious if you have to deal with international phone numbers.</p>\n\n<p>The thing to note with your SQL above, is that SQL Server doesn't understand Regex.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18196/" ]
I have a SQL statement that looks like: ``` SELECT [Phone] FROM [Table] WHERE ( [Phone] LIKE '[A-Z][a-z]' OR [Phone] = 'N/A' OR [Phone] LIKE '[0]' ) ``` The part I'm having trouble with is the where statement with the "LIKEs". I've seen SQL statements where authors used `like` statements in the way I'm using them above. At first, I thought this might be a version of Regular Expressions but I've since learned. Is anyone familiar with using like statements in such a way. Note: the "N/A" is working fine. What I need to match is phone numbers that have characters. Or phone numbers which contain nothing but zero.
Check [here](http://technet.microsoft.com/en-us/library/aa933232(v=sql.80).aspx). [] matches a range of characters. I think you want something like this: ``` SELECT [Phone] FROM [Table] WHERE ( [Phone] LIKE '%[A-Z]%' OR [Phone] LIKE '%[a-z]%' OR [Phone] = 'N/A' OR [Phone] LIKE '0' ) ```
96,414
<p>I'm experimenting with adding icons to a shell extension. I have this code (sanitized for easy reading), which works:</p> <pre><code>InsertMenu(hmenu, index, MF_POPUP|MF_BYPOSITION, (UINT)hParentMenu, namestring); </code></pre> <p>The next step is this code:</p> <pre><code>HICON hIconLarge, hIconSmall; ICONINFO oIconInfo; ExtractIconEx("c:\\progra~1\\winzip\\winzip32.exe", 0, &amp;hIconLarge, &amp;hIconSmall, 1); GetIconInfo(hIconSmall, &amp;oIconInfo); //??????? SetMenuItemBitmaps(hParentMenu, indexMenu-1, MF_BITMAP | MF_BYPOSITION, hbmp, hbmp); </code></pre> <p>What do I put in to replace the ?'s. Attempts to Google this knowledge have found many tips that I failed to get working. Any advice on getting this to work, especially on older machines (e.g. no .net framework, no vista) is appreciated.</p>
[ { "answer_id": 96429, "author": "Lee H", "author_id": 18201, "author_profile": "https://Stackoverflow.com/users/18201", "pm_score": 2, "selected": false, "text": "<p>Setting up password-less publickey authentication with ssh would allow you to scp your files to any of your servers very quickly (or be automated by a shell script).</p>\n\n<p>Here's a simple tutorial: <a href=\"http://rcsg-gsir.imsb-dsgi.nrc-cnrc.gc.ca/documents/internet/node31.html\" rel=\"nofollow noreferrer\">http://rcsg-gsir.imsb-dsgi.nrc-cnrc.gc.ca/documents/internet/node31.html</a></p>\n" }, { "answer_id": 96435, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I've used <a href=\"http://www.automatedqa.com/products/abs/index.asp\" rel=\"nofollow noreferrer\">Automated Build Studio</a> before for a similar task. It gives you a lot of flexibility in what you can do.</p>\n" }, { "answer_id": 96453, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 1, "selected": false, "text": "<p>I concur -- set your svn tree up, and use rsync over ssh to copy the tree out to the remote locations. rsync will make it fast and efficient, only copying changes rather than full files.</p>\n\n<p>You want to export your svn tree to some directory, then rsync from there to the remote host's directory tree.</p>\n" }, { "answer_id": 96517, "author": "Lee H", "author_id": 18201, "author_profile": "https://Stackoverflow.com/users/18201", "pm_score": 1, "selected": false, "text": "<p>I also forgot to mention that if you use rsync, you can set up rsync to use ssh, so you will only transfer the files that have changed, saving on time and bandwidth.</p>\n" }, { "answer_id": 96576, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 2, "selected": false, "text": "<p>If you're running on Redhat or Debian, consider packaging up your code into RPM's or Debs. Then build a yum or dpkg repository and put your packages there. You can then use your system's package management to do upgrades/rollbacks, etc. You can even use <a href=\"http://reductivelabs.com/trac/puppet/\" rel=\"nofollow noreferrer\">puppet</a> to automate the process.</p>\n\n<p>If you want to tie it into subversion, you can create a branch for each new version. Use the commit scripts to build the RPM's when a new branch shows up in a directory.</p>\n" }, { "answer_id": 96675, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://capify.org/\" rel=\"noreferrer\">Capistrano</a> is pretty handy for that. There's a few people using it (<a href=\"http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/\" rel=\"noreferrer\">1</a>, <a href=\"http://www.contentwithstyle.co.uk/Blog/178\" rel=\"noreferrer\">2</a>, <a href=\"http://laurentbois.com/2008/08/05/use-capistrano-in-enterprise-for-php-and-ruby-on-rails-applications/\" rel=\"noreferrer\">3</a>) for deploying PHP code as evidenced by doing a <a href=\"http://www.google.com/search?q=capistrano+php+deployment\" rel=\"noreferrer\">quick search</a>.</p>\n" }, { "answer_id": 98084, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 2, "selected": false, "text": "<p>I'll second Capistrano. It's incredibly powerful and flexible. Our current project uses Capistrano for deploying to different servers as well as multiple servers. We pass two arguments to the cap command:\n1) the name of the set of machine specific config options to run and\n2) the name of the action to run</p>\n\n<p>ends up looking like this: </p>\n\n<pre><code>cap -f deploy.rb live deploy\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cap -f deploy.rb dev deploy\n</code></pre>\n\n<p>Of course the default use case - deploy to lots of machines at once - is a doddle with Capistrano AND you don't need to have Capistrano on the machines you are deploying to. All in all, tasty technology. </p>\n" }, { "answer_id": 100408, "author": "Michel", "author_id": 17316, "author_profile": "https://Stackoverflow.com/users/17316", "pm_score": 0, "selected": false, "text": "<p>I had marked a post on how to deploy your websites using Subversion : <a href=\"http://blog.lavablast.com/post/2008/02/I2c-for-one2c-welcome-our-new-revision-control-overlords!.aspx\" rel=\"nofollow noreferrer\">http://blog.lavablast.com/post/2008/02/I2c-for-one2c-welcome-our-new-revision-control-overlords!.aspx</a></p>\n" }, { "answer_id": 1861357, "author": "Nick", "author_id": 191221, "author_profile": "https://Stackoverflow.com/users/191221", "pm_score": 0, "selected": false, "text": "<p>I found capistrano to be very easy to use once it's setup. The configuration file can be a bit confusing at first for more complicated environments but it soon becomes worthwhile. I deploy to 14 servers on production. I also use multiple environments for deployment to a staging server. One quirk, there's a bug in Ruby that breaks parallel deployment but serially isn't too bad with svn exports.</p>\n" }, { "answer_id": 5705648, "author": "kwatee", "author_id": 713732, "author_profile": "https://Stackoverflow.com/users/713732", "pm_score": 1, "selected": false, "text": "<p>You can also use <a href=\"http://www.kwatee.net\" rel=\"nofollow\">kwateeSDCM</a> which is free and allows remote installation via ssh. It also enables you to manage server-specific configuration from a central location and make upgrades seemless.</p>\n" }, { "answer_id": 6336411, "author": "Steve Kawolsky", "author_id": 796599, "author_profile": "https://Stackoverflow.com/users/796599", "pm_score": 0, "selected": false, "text": "<p>Capistrano setup is just too complicated. We found that KwateeSDCM was very straightforward to use with a simple web interface and no scripting. We've got our deployment configuration done in no time for Dev and QA configuration on windows and linux servers.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18192/" ]
I'm experimenting with adding icons to a shell extension. I have this code (sanitized for easy reading), which works: ``` InsertMenu(hmenu, index, MF_POPUP|MF_BYPOSITION, (UINT)hParentMenu, namestring); ``` The next step is this code: ``` HICON hIconLarge, hIconSmall; ICONINFO oIconInfo; ExtractIconEx("c:\\progra~1\\winzip\\winzip32.exe", 0, &hIconLarge, &hIconSmall, 1); GetIconInfo(hIconSmall, &oIconInfo); //??????? SetMenuItemBitmaps(hParentMenu, indexMenu-1, MF_BITMAP | MF_BYPOSITION, hbmp, hbmp); ``` What do I put in to replace the ?'s. Attempts to Google this knowledge have found many tips that I failed to get working. Any advice on getting this to work, especially on older machines (e.g. no .net framework, no vista) is appreciated.
[Capistrano](http://capify.org/) is pretty handy for that. There's a few people using it ([1](http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/), [2](http://www.contentwithstyle.co.uk/Blog/178), [3](http://laurentbois.com/2008/08/05/use-capistrano-in-enterprise-for-php-and-ruby-on-rails-applications/)) for deploying PHP code as evidenced by doing a [quick search](http://www.google.com/search?q=capistrano+php+deployment).
96,428
<p>I have this string</p> <pre><code>'john smith~123 Street~Apt 4~New York~NY~12345' </code></pre> <p>Using JavaScript, what is the fastest way to parse this into</p> <pre><code>var name = "john smith"; var street= "123 Street"; //etc... </code></pre>
[ { "answer_id": 96452, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 11, "selected": true, "text": "<p>With JavaScript’s <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"noreferrer\"><code>String.prototype.split</code></a> function:</p>\n\n<pre><code>var input = 'john smith~123 Street~Apt 4~New York~NY~12345';\n\nvar fields = input.split('~');\n\nvar name = fields[0];\nvar street = fields[1];\n// etc.\n</code></pre>\n" }, { "answer_id": 96458, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": false, "text": "<p>You'll want to look into JavaScript's <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr\" rel=\"nofollow noreferrer\">substr</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"nofollow noreferrer\">split</a>, as this is not really a task suited for jQuery.</p>\n" }, { "answer_id": 96467, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 6, "selected": false, "text": "<p>You don't need jQuery.</p>\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>var s = 'john smith~123 Street~Apt 4~New York~NY~12345';\nvar fields = s.split(/~/);\nvar name = fields[0];\nvar street = fields[1];\n\nconsole.log(name);\nconsole.log(street);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 96471, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<p>well, easiest way would be something like:</p>\n\n<pre><code>var address = theEncodedString.split(/~/)\nvar name = address[0], street = address[1]\n</code></pre>\n" }, { "answer_id": 96479, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 2, "selected": false, "text": "<p>Something like:</p>\n\n<pre><code>var divided = str.split(\"/~/\");\nvar name=divided[0];\nvar street = divided[1];\n</code></pre>\n\n<p>Is probably going to be easiest</p>\n" }, { "answer_id": 11951118, "author": "Torsten Walter", "author_id": 1393908, "author_profile": "https://Stackoverflow.com/users/1393908", "pm_score": 4, "selected": false, "text": "<p>Even though this is not the simplest way, you could do this:</p>\n\n<pre><code>var addressString = \"~john smith~123 Street~Apt 4~New York~NY~12345~\",\n keys = \"name address1 address2 city state zipcode\".split(\" \"),\n address = {};\n\n// clean up the string with the first replace\n// \"abuse\" the second replace to map the keys to the matches\naddressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){\n address[ keys.unshift() ] = match;\n});\n\n// address will contain the mapped result\naddress = {\n address1: \"123 Street\"\n address2: \"Apt 4\"\n city: \"New York\"\n name: \"john smith\"\n state: \"NY\"\n zipcode: \"12345\"\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Update for ES2015, using destructuring</strong></p>\n\n<pre><code>const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);\n\n// The variables defined above now contain the appropriate information:\n\nconsole.log(address1, address2, city, name, state, zipcode);\n// -&gt; john smith 123 Street Apt 4 New York NY 12345\n</code></pre>\n" }, { "answer_id": 13622899, "author": "BJ Patel", "author_id": 2683759, "author_profile": "https://Stackoverflow.com/users/2683759", "pm_score": 3, "selected": false, "text": "<p>If <strong>Spliter is found</strong> then only</p>\n<p>it will Split it</p>\n<p>else return the <strong>same string</strong></p>\n<blockquote>\n<pre><code>function SplitTheString(ResultStr) {\n if (ResultStr != null) {\n var SplitChars = '~';\n if (ResultStr.indexOf(SplitChars) &gt;= 0) {\n var DtlStr = ResultStr.split(SplitChars);\n var name = DtlStr[0];\n var street = DtlStr[1];\n }\n }\n}\n</code></pre>\n</blockquote>\n" }, { "answer_id": 19610068, "author": "Billy Hallman", "author_id": 2010101, "author_profile": "https://Stackoverflow.com/users/2010101", "pm_score": 2, "selected": false, "text": "<p>Zach had this one right.. using his method you could also make a seemingly \"multi-dimensional\" array.. I created a quick example at JSFiddle <a href=\"http://jsfiddle.net/LcnvJ/2/\" rel=\"nofollow\">http://jsfiddle.net/LcnvJ/2/</a></p>\n\n<pre><code>// array[0][0] will produce brian\n// array[0][1] will produce james\n\n// array[1][0] will produce kevin\n// array[1][1] will produce haley\n\nvar array = [];\n array[0] = \"brian,james,doug\".split(\",\");\n array[1] = \"kevin,haley,steph\".split(\",\");\n</code></pre>\n" }, { "answer_id": 32921252, "author": "Tushar", "author_id": 2025923, "author_profile": "https://Stackoverflow.com/users/2025923", "pm_score": 3, "selected": false, "text": "<p>You can use <code>split</code> to split the text.</p>\n\n<p>As an alternative, you can also use <code>match</code> as follow</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var str = 'john smith~123 Street~Apt 4~New York~NY~12345';\r\nmatches = str.match(/[^~]+/g);\r\n\r\nconsole.log(matches);\r\ndocument.write(matches);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The regex <code>[^~]+</code> will match all the characters except <code>~</code> and return the matches in an array. You can then extract the matches from it.</p>\n" }, { "answer_id": 42185907, "author": "Vahid Hallaji", "author_id": 1121982, "author_profile": "https://Stackoverflow.com/users/1121982", "pm_score": 6, "selected": false, "text": "<p>According to ECMAScript6 <code>ES6</code>, the clean way is destructuring arrays:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const input = 'john smith~123 Street~Apt 4~New York~NY~12345';\r\n\r\nconst [name, street, unit, city, state, zip] = input.split('~');\r\n\r\nconsole.log(name); // john smith\r\nconsole.log(street); // 123 Street\r\nconsole.log(unit); // Apt 4\r\nconsole.log(city); // New York\r\nconsole.log(state); // NY\r\nconsole.log(zip); // 12345</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You may have extra items in the input string. In this case, you can use rest operator to get an array for the rest or just ignore them: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const input = 'john smith~123 Street~Apt 4~New York~NY~12345';\r\n\r\nconst [name, street, ...others] = input.split('~');\r\n\r\nconsole.log(name); // john smith\r\nconsole.log(street); // 123 Street\r\nconsole.log(others); // [\"Apt 4\", \"New York\", \"NY\", \"12345\"]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I supposed a read-only reference for values and used the <code>const</code> declaration.</p>\n\n<p><strong>Enjoy ES6!</strong></p>\n" }, { "answer_id": 49048718, "author": "Bal mukund kumar", "author_id": 7393281, "author_profile": "https://Stackoverflow.com/users/7393281", "pm_score": -1, "selected": false, "text": "<p>Use this code --</p>\n\n<pre><code>function myFunction() {\nvar str = \"How are you doing today?\";\nvar res = str.split(\"/\");\n\n}\n</code></pre>\n" }, { "answer_id": 54228055, "author": "imtk", "author_id": 3159162, "author_profile": "https://Stackoverflow.com/users/3159162", "pm_score": 2, "selected": false, "text": "<p>This <code>string.split(\"~\")[0];</code> gets things done.</p>\n\n<p>source: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"nofollow noreferrer\">String.prototype.split()</a></p>\n\n<hr>\n\n<p><strong>Another functional approach using curry and function composition.</strong></p>\n\n<p>So the first thing would be the split function. We want to make this <code>\"john smith~123 Street~Apt 4~New York~NY~12345\"</code> into this <code>[\"john smith\", \"123 Street\", \"Apt 4\", \"New York\", \"NY\", \"12345\"]</code></p>\n\n<pre><code>const split = (separator) =&gt; (text) =&gt; text.split(separator);\nconst splitByTilde = split('~');\n</code></pre>\n\n<p>So now we can use our specialized <code>splitByTilde</code> function. Example:</p>\n\n<pre><code>splitByTilde(\"john smith~123 Street~Apt 4~New York~NY~12345\") // [\"john smith\", \"123 Street\", \"Apt 4\", \"New York\", \"NY\", \"12345\"]\n</code></pre>\n\n<p>To get the first element we can use the <code>list[0]</code> operator. Let's build a <code>first</code> function:</p>\n\n<pre><code>const first = (list) =&gt; list[0];\n</code></pre>\n\n<p>The algorithm is: split by the colon and then get the first element of the given list. So we can compose those functions to build our final <code>getName</code> function. Building a <code>compose</code> function with <code>reduce</code>:</p>\n\n<pre><code>const compose = (...fns) =&gt; (value) =&gt; fns.reduceRight((acc, fn) =&gt; fn(acc), value);\n</code></pre>\n\n<p>And now using it to compose <code>splitByTilde</code> and <code>first</code> functions.</p>\n\n<pre><code>const getName = compose(first, splitByTilde);\n\nlet string = 'john smith~123 Street~Apt 4~New York~NY~12345';\ngetName(string); // \"john smith\"\n</code></pre>\n" }, { "answer_id": 55399440, "author": "Chris Bartholomew", "author_id": 10234183, "author_profile": "https://Stackoverflow.com/users/10234183", "pm_score": 1, "selected": false, "text": "<p>Since the splitting on commas question is duplicated to this question, adding this here.</p>\n\n<p>If you want to split on a character and also handle extra whitespace that might follow that character, which often happens with commas, you can use <code>replace</code> then <code>split</code>, like this:</p>\n\n<pre><code>var items = string.replace(/,\\s+/, \",\").split(',')\n</code></pre>\n" }, { "answer_id": 55589395, "author": "Hari Lakkakula", "author_id": 6601939, "author_profile": "https://Stackoverflow.com/users/6601939", "pm_score": 2, "selected": false, "text": "<h1>Try in Plain Javascript</h1>\n<pre><code> //basic url=http://localhost:58227/ExternalApproval.html?Status=1\n\n var ar= [url,statu] = window.location.href.split(&quot;=&quot;);\n</code></pre>\n" }, { "answer_id": 57693059, "author": "Developer", "author_id": 10755206, "author_profile": "https://Stackoverflow.com/users/10755206", "pm_score": 2, "selected": false, "text": "<p>JavaScript: Convert String to Array JavaScript Split</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> var str = \"This-javascript-tutorial-string-split-method-examples-tutsmake.\"\r\n \r\n var result = str.split('-'); \r\n \r\n console.log(result);\r\n \r\n document.getElementById(\"show\").innerHTML = result; </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;title&gt;How do you split a string, breaking at a particular character in javascript?&lt;/title&gt;\r\n&lt;/head&gt;\r\n&lt;body&gt;\r\n \r\n&lt;p id=\"show\"&gt;&lt;/p&gt; \r\n \r\n&lt;/body&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"https://www.tutsmake.com/javascript-convert-string-to-array-javascript/\" rel=\"nofollow noreferrer\">https://www.tutsmake.com/javascript-convert-string-to-array-javascript/</a></p>\n" }, { "answer_id": 63754660, "author": "Ankit21ks", "author_id": 5143638, "author_profile": "https://Stackoverflow.com/users/5143638", "pm_score": 3, "selected": false, "text": "<p><code>split()</code> method in JavaScript is used to convert a string to an array.\nIt takes one optional argument, as a character, on which to split. In your case (~).</p>\n<p>If splitOn is skipped, it will simply put string as it is on 0th position of an array.</p>\n<p>If splitOn is just a “”, then it will convert array of single characters.</p>\n<p>So in your case:</p>\n<pre><code>var arr = input.split('~');\n</code></pre>\n<p>will get the name at <code>arr[0]</code> and the street at <code>arr[1]</code>.</p>\n<p>You can read for a more detailed explanation at\n<a href=\"https://codetopology.com/scripts/javascript-tutorials/javascript-string-methods/#splitsplitOn\" rel=\"noreferrer\">Split on in JavaScript</a></p>\n" }, { "answer_id": 64845911, "author": "PHP Guru", "author_id": 10587413, "author_profile": "https://Stackoverflow.com/users/10587413", "pm_score": 0, "selected": false, "text": "<p>This isn't as good as the destructuring answer, but seeing as this question was asked 12 years ago, I decided to give it an answer that also would have worked 12 years ago.</p>\n<pre><code>function Record(s) {\n var keys = [&quot;name&quot;, &quot;address&quot;, &quot;address2&quot;, &quot;city&quot;, &quot;state&quot;, &quot;zip&quot;], values = s.split(&quot;~&quot;), i\n for (i = 0; i&lt;keys.length; i++) {\n this[keys[i]] = values[i]\n }\n}\n\nvar record = new Record('john smith~123 Street~Apt 4~New York~NY~12345')\n\nrecord.name // contains john smith\nrecord.address // contains 123 Street\nrecord.address2 // contains Apt 4\nrecord.city // contains New York\nrecord.state // contains NY\nrecord.zip // contains zip\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
I have this string ``` 'john smith~123 Street~Apt 4~New York~NY~12345' ``` Using JavaScript, what is the fastest way to parse this into ``` var name = "john smith"; var street= "123 Street"; //etc... ```
With JavaScript’s [`String.prototype.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) function: ``` var input = 'john smith~123 Street~Apt 4~New York~NY~12345'; var fields = input.split('~'); var name = fields[0]; var street = fields[1]; // etc. ```
96,440
<p>I have a Flex application, which loads a SWF from CS3. The loaded SWF contains a text input called "myText". I can see this in the SWFLoader.content with no problems, but I don't know what type I should be treating it as in my Flex App. I thought the flex docs covered this but I can only find how to interact with another Flex SWF.</p> <p>The Flex debugger tells me it is of type fl.controls.TextInput, which makes sense. But FlexBuilder doesn't seem to know this class. While Flash and Flex both use AS3, Flex has a whole new library of GUI classes. I thought it also had all the Flash classes, but I can't get it to know of ANY fl.*** packages.</p>
[ { "answer_id": 96536, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 0, "selected": false, "text": "<p>Flex and Flash SWFs are essentially the same, just built using different tools. I'm not sure if they share the same component libraries, but based on the package names I'm guessing they at least mostly do.</p>\n\n<p>If it's a normal Text Input then I would guess it's an instance of mx.controls.TextInput.</p>\n" }, { "answer_id": 103094, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>The <code>fl.*</code> hierarchy of classes is Flash CS3-only. It's the Flash Components 3 library (I believe it's called, I might be wrong). However, you don't need the class to work with the object. As long as you can get a reference to it in your code, which you seem to have, you can assign the reference to an untyped variable and work with it anyway:</p>\n\n<pre><code>var textInput : * = getTheTextInput(); // insert your own method here\n\ntextInput.text = \"Lorem ipsum dolor sit amet\";\n\ntextInput.setSelection(4, 15);\n</code></pre>\n\n<p>There is no need to know the type of an object in order to interact with it. Of course you lose type checking at compile time, but that's really not much of an issue, you just have to be extra careful.</p>\n\n<p>If you really, really want to reference the object as its real type, the class in question is located in </p>\n\n<pre><code>Adobe Flash CS3/Configuration/Component Source/ActionScript 3.0/User Interface/fl/controls/TextInput.as\n</code></pre>\n\n<p>...if you have Flash CS3 installed, because it only ships with that application.</p>\n" }, { "answer_id": 104128, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 0, "selected": false, "text": "<p>Keep in mind that if you do as Theo said and reference it with the correct type it will compile that class in both swfs, even if you're not using it in the first one. Unfortunately the fl.* classes don't implement any interfaces so you can't type them to the interface instead of the implementation. If you could, only the interface would get compiled, which is much smaller than the implementation. For this one it won't be a big deal, it's probably going to add only a couple kb, but in the long run it adds up. Just a heads up ;)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
I have a Flex application, which loads a SWF from CS3. The loaded SWF contains a text input called "myText". I can see this in the SWFLoader.content with no problems, but I don't know what type I should be treating it as in my Flex App. I thought the flex docs covered this but I can only find how to interact with another Flex SWF. The Flex debugger tells me it is of type fl.controls.TextInput, which makes sense. But FlexBuilder doesn't seem to know this class. While Flash and Flex both use AS3, Flex has a whole new library of GUI classes. I thought it also had all the Flash classes, but I can't get it to know of ANY fl.\*\*\* packages.
The `fl.*` hierarchy of classes is Flash CS3-only. It's the Flash Components 3 library (I believe it's called, I might be wrong). However, you don't need the class to work with the object. As long as you can get a reference to it in your code, which you seem to have, you can assign the reference to an untyped variable and work with it anyway: ``` var textInput : * = getTheTextInput(); // insert your own method here textInput.text = "Lorem ipsum dolor sit amet"; textInput.setSelection(4, 15); ``` There is no need to know the type of an object in order to interact with it. Of course you lose type checking at compile time, but that's really not much of an issue, you just have to be extra careful. If you really, really want to reference the object as its real type, the class in question is located in ``` Adobe Flash CS3/Configuration/Component Source/ActionScript 3.0/User Interface/fl/controls/TextInput.as ``` ...if you have Flash CS3 installed, because it only ships with that application.
96,448
<p>I need to import a large CSV file into an SQL server. I'm using this :</p> <pre><code>BULK INSERT CSVTest FROM 'c:\csvfile.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) GO </code></pre> <p>problem is all my fields are surrounded by quotes (" ") so a row actually looks like :</p> <pre><code>"1","","2","","sometimes with comma , inside", "" </code></pre> <p>Can I somehow bulk import them and tell SQL to use the quotes as field delimiters?</p> <p><strong>Edit</strong>: The problem with using '","' as delimiter, as in the examples suggested is that : What most examples do, is they import the data including the first " in the first column and the last " in the last, then they go ahead and strip that out. Alas my first (and last) column are datetime and will not allow a "20080902 to be imported as datetime.</p> <p>From what I've been reading arround I think FORMATFILE is the way to go, but documentation (including MSDN) is terribly unhelpfull.</p>
[ { "answer_id": 96474, "author": "K Richard", "author_id": 16771, "author_profile": "https://Stackoverflow.com/users/16771", "pm_score": 4, "selected": false, "text": "<p>Try <code>FIELDTERMINATOR='\",\"'</code></p>\n\n<p>Here is a great link to help with the first and last quote...look how he used the substring the SP</p>\n\n<p><a href=\"http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file\" rel=\"noreferrer\">http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file</a></p>\n" }, { "answer_id": 96488, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 1, "selected": false, "text": "<p>Do you need to do this programmatically, or is it a one-time shot?</p>\n\n<p>Using the Enterprise Manager, right-click Import Data lets you select your delimiter. </p>\n" }, { "answer_id": 96489, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 0, "selected": false, "text": "<p>Yup, K Richard is right: <code>FIELDTERMINATOR = '\",\"'</code></p>\n\n<p>See <a href=\"http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file\" rel=\"nofollow noreferrer\">http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file</a> for more info.</p>\n" }, { "answer_id": 96507, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>Try <a href=\"http://support.microsoft.com/kb/321686\" rel=\"nofollow noreferrer\">OpenRowSet</a>. This can be used to import Excel stuff. Excel can open CSV files, so you only need to figure out the correct [ConnectionString][2].</p>\n\n<p>[2]: Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=c:\\txtFilesFolder\\;Extensions=asc,csv,tab,txt;</p>\n" }, { "answer_id": 96799, "author": "µBio", "author_id": 9796, "author_profile": "https://Stackoverflow.com/users/9796", "pm_score": 0, "selected": false, "text": "<p>You could also use DTS or SSIS.</p>\n" }, { "answer_id": 97243, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>You have to watch out with BCP/BULK INSERT because neither BSP or Bulk Insert handle this well if the quoting is not consistent, even with format files (even XML format files don't offer the option) and dummy [\"] characters at the beginning and end and using [\",\"] as the separator. Technically CSV files do not need to have [\"] characters if there are no embedded [,] characters</p>\n\n<p>It is for this reason that comma-delimited files are sometimes referred to as comedy-limited files.</p>\n\n<p>OpenRowSet will require Excel on the server and could be problematic in 64-bit environments - I know it's problematic using Excel in Jet in 64-bit.</p>\n\n<p>SSIS is really your best bet if the file is likely to vary from your expectations in the future.</p>\n" }, { "answer_id": 97366, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 0, "selected": false, "text": "<p>Do you have control over the input format? | (pipes), and \\t usually make for better field terminators.</p>\n" }, { "answer_id": 99976, "author": "Alex Andronov", "author_id": 3168, "author_profile": "https://Stackoverflow.com/users/3168", "pm_score": 3, "selected": true, "text": "<p>I know this isn't a real solution but I use a dummy table for the import with nvarchar set for everything. Then I do an insert which strips out the \" characters and does the conversions. It isn't pretty but it does the job.</p>\n" }, { "answer_id": 99988, "author": "RKitson", "author_id": 16947, "author_profile": "https://Stackoverflow.com/users/16947", "pm_score": 0, "selected": false, "text": "<p>If you figure out how to get the file parsed into a DataTable, I'd suggest the SqlBulkInsert class for inserting it into SQL Server.</p>\n" }, { "answer_id": 151662, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>u can try this code which is very sweet if you want ,\nthis will remove unwanted semicolons from your code.\nif for example your data is like this :<br>\"Kelly\",\"Reynold\",\"[email protected]\"<br></p>\n\n<pre><code>Bulk insert test1\nfrom 'c:\\1.txt' with ( \n fieldterminator ='\",\"'\n ,rowterminator='\\n')\n\nupdate test1&lt;br&gt;\nset name =Substring (name , 2,len(name))\nwhere name like **' \"% '**\n\nupdate test1\nset email=substring(email, 1,len(email)-1)\nwhere email like **' %\" '**\n</code></pre>\n" }, { "answer_id": 151678, "author": "cbp", "author_id": 21966, "author_profile": "https://Stackoverflow.com/users/21966", "pm_score": 3, "selected": false, "text": "<p>Another hack which I sometimes use, is to open the CSV in Excel, then write your sql statement into a cell at the end of each row.\nFor example:</p>\n\n<pre><code>=concatenate(\"insert into myTable (columnA,columnB) values ('\",a1,\"','\",b1,\"'\")\")\n</code></pre>\n\n<p>A fill-down can populate this into every row for you. Then just copy and paste the output into a new query window.</p>\n\n<p>It's old-school, but if you only need to do imports once in a while it saves you messing around with reading all the obscure documentation on the 'proper' way to do it.</p>\n" }, { "answer_id": 215397, "author": "roundcrisis", "author_id": 162325, "author_profile": "https://Stackoverflow.com/users/162325", "pm_score": 2, "selected": false, "text": "<p>Id say use FileHelpers its an open source library</p>\n" }, { "answer_id": 18928719, "author": "Kevin M", "author_id": 1838481, "author_profile": "https://Stackoverflow.com/users/1838481", "pm_score": 1, "selected": false, "text": "<p>Firs you need to import CSV file into Data Table </p>\n\n<p>Then you can insert bulk rows using SQLBulkCopy </p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.SqlClient;\n\nnamespace SqlBulkInsertExample\n{\n class Program\n {\n static void Main(string[] args)\n {\n DataTable prodSalesData = new DataTable(\"ProductSalesData\");\n\n // Create Column 1: SaleDate\n DataColumn dateColumn = new DataColumn();\n dateColumn.DataType = Type.GetType(\"System.DateTime\");\n dateColumn.ColumnName = \"SaleDate\";\n\n // Create Column 2: ProductName\n DataColumn productNameColumn = new DataColumn();\n productNameColumn.ColumnName = \"ProductName\";\n\n // Create Column 3: TotalSales\n DataColumn totalSalesColumn = new DataColumn();\n totalSalesColumn.DataType = Type.GetType(\"System.Int32\");\n totalSalesColumn.ColumnName = \"TotalSales\";\n\n // Add the columns to the ProductSalesData DataTable\n prodSalesData.Columns.Add(dateColumn);\n prodSalesData.Columns.Add(productNameColumn);\n prodSalesData.Columns.Add(totalSalesColumn);\n\n // Let's populate the datatable with our stats.\n // You can add as many rows as you want here!\n\n // Create a new row\n DataRow dailyProductSalesRow = prodSalesData.NewRow();\n dailyProductSalesRow[\"SaleDate\"] = DateTime.Now.Date;\n dailyProductSalesRow[\"ProductName\"] = \"Nike\";\n dailyProductSalesRow[\"TotalSales\"] = 10;\n\n // Add the row to the ProductSalesData DataTable\n prodSalesData.Rows.Add(dailyProductSalesRow);\n\n // Copy the DataTable to SQL Server using SqlBulkCopy\n using (SqlConnection dbConnection = new SqlConnection(\"Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;\"))\n {\n dbConnection.Open();\n using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))\n {\n s.DestinationTableName = prodSalesData.TableName;\n\n foreach (var column in prodSalesData.Columns)\n s.ColumnMappings.Add(column.ToString(), column.ToString());\n\n s.WriteToServer(prodSalesData);\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 53729566, "author": "user10191093", "author_id": 10191093, "author_profile": "https://Stackoverflow.com/users/10191093", "pm_score": 1, "selected": false, "text": "<p>This is an old question, so I write this to help anyone who stumble upon it.</p>\n\n<p>SQL Server 2017 introduces the FIELDQUOTE parameter which is intended for this exact use case.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
I need to import a large CSV file into an SQL server. I'm using this : ``` BULK INSERT CSVTest FROM 'c:\csvfile.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) GO ``` problem is all my fields are surrounded by quotes (" ") so a row actually looks like : ``` "1","","2","","sometimes with comma , inside", "" ``` Can I somehow bulk import them and tell SQL to use the quotes as field delimiters? **Edit**: The problem with using '","' as delimiter, as in the examples suggested is that : What most examples do, is they import the data including the first " in the first column and the last " in the last, then they go ahead and strip that out. Alas my first (and last) column are datetime and will not allow a "20080902 to be imported as datetime. From what I've been reading arround I think FORMATFILE is the way to go, but documentation (including MSDN) is terribly unhelpfull.
I know this isn't a real solution but I use a dummy table for the import with nvarchar set for everything. Then I do an insert which strips out the " characters and does the conversions. It isn't pretty but it does the job.
96,463
<p>How do you access the response from the Request object in MooTools? I've been looking at the documentation and the MooTorial, but I can't seem to make any headway. Other Ajax stuff I've done with MooTools I haven't had to manipulate the response at all, so I've just been able to inject it straight into the document, but now I need to make some changes to it first. I don't want to alert the response, I'd like to access it so I can make further changes to it. Any help would be greatly appreciated. Thanks.</p> <p>Edit:</p> <p>I'd like to be able to access the response after the request has already been made, preferably outside of the Request object. It's for an RSS reader, so I need to do some parsing and Request is just being used to get the feed from a server file. This function is a method in a class, which should return the response in a string, but it isn't returning anything but undefined:</p> <pre><code> fetch: function(site){ var feed; var req = new Request({ method: this.options.method, url: this.options.rssFetchPath, data: { 'url' : site }, onRequest: function() { if (this.options.targetId) { $ (this.options.targetId).setProperty('html', this.options.onRequestMessage); } }.bind(this), onSuccess: function(responseText) { feed = responseText; } }); req.send(); return feed; } </code></pre>
[ { "answer_id": 96573, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "<p>The response content is returned to the anonymous function defined in onComplete.</p>\n\n<p>It can be accessed from there.</p>\n\n<pre><code>var req = new Request({\n method: 'get',\n url: ...,\n data: ...,\n onRequest: function() { alert('Request made. Please wait...'); },\n\n // the response is passed to the callback as the first parameter\n onComplete: function(response) { alert('Response: ' + response); }\n\n}).send(); \n</code></pre>\n" }, { "answer_id": 97126, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 1, "selected": true, "text": "<p>I was able to find my answer on the <a href=\"http://groups.google.com/group/mootools-users/browse_thread/thread/7ade43ef51c91922\" rel=\"nofollow noreferrer\">MooTools Group at Google</a>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
How do you access the response from the Request object in MooTools? I've been looking at the documentation and the MooTorial, but I can't seem to make any headway. Other Ajax stuff I've done with MooTools I haven't had to manipulate the response at all, so I've just been able to inject it straight into the document, but now I need to make some changes to it first. I don't want to alert the response, I'd like to access it so I can make further changes to it. Any help would be greatly appreciated. Thanks. Edit: I'd like to be able to access the response after the request has already been made, preferably outside of the Request object. It's for an RSS reader, so I need to do some parsing and Request is just being used to get the feed from a server file. This function is a method in a class, which should return the response in a string, but it isn't returning anything but undefined: ``` fetch: function(site){ var feed; var req = new Request({ method: this.options.method, url: this.options.rssFetchPath, data: { 'url' : site }, onRequest: function() { if (this.options.targetId) { $ (this.options.targetId).setProperty('html', this.options.onRequestMessage); } }.bind(this), onSuccess: function(responseText) { feed = responseText; } }); req.send(); return feed; } ```
I was able to find my answer on the [MooTools Group at Google](http://groups.google.com/group/mootools-users/browse_thread/thread/7ade43ef51c91922).
96,500
<p>Suppose I have the following code:</p> <pre><code>class some_class{}; some_class some_function() { return some_class(); } </code></pre> <p>This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?</p>
[ { "answer_id": 96530, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 5, "selected": true, "text": "<p>No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary.</p>\n" }, { "answer_id": 96532, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p>That is perfectly reasonable C++.</p>\n" }, { "answer_id": 96549, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>This is perfectly legal C++ and any compiler should accept it. What makes you think it might be doing something wrong?</p>\n" }, { "answer_id": 96599, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 3, "selected": false, "text": "<p>Returning objects from a function call is the \"Factory\" Design Pattern, and is used extensively.</p>\n\n<p>However, you will want to be careful whether you return objects, or pointers to objects. The former of these will introduce you to copy constructors / assignment operators, which can be a pain.</p>\n" }, { "answer_id": 96665, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>It is valid, but performance may not be ideal depending on how it is called.</p>\n\n<p>For example:</p>\n\n<pre><code>A a;\na = fn();\n</code></pre>\n\n<p>and </p>\n\n<pre><code>A a = fn();\n</code></pre>\n\n<p>are not the same.</p>\n\n<p>In the first case the default constructor is called, and then the assignment operator is invoked on a which requires a temporary variable to be constructed.</p>\n\n<p>In the second case the copy constructor is used.</p>\n\n<p>An intelligent enough compiler will work out what optimizations are possible. But, if the copy constructor is user supplied then I don't see how the compiler can optimize out the temporary variable. It has to invoke the copy constructor, and to do that it has to have another instance.</p>\n" }, { "answer_id": 96735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>That's the best way to do it if your class is pretty lightweight - I mean that it isn't very expensive to make a copy of it.</p>\n\n<p>One side effect of that method though is that it does tend to make it more likely to have temporary objects created, although that can depend on how well the compiler can optimize things.</p>\n\n<p>For more heavyweight classes that you want to make sure are not copied (say for example a large bitmap image) then it is a good idea to pass stuff like that around as a reference parameter which then gets filled in, just to make absolutely sure that there won't be any temporary objects created.</p>\n\n<p>Overall it can happen that simplifying syntax and making things turned more directly can have a side effect of creating more temporary objects in expressions, just something that you should keep in mind when designing the interfaces for more heavyweight objects.</p>\n" }, { "answer_id": 96773, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": false, "text": "<p>The difference between Rob Walker's example is called Return Value Optimisation (RVO) if you want to google for it.</p>\n\n<p>Incidentally, if you want to enure your object gets returned in the most efficient manner, create the object on the heap (ie via new) using a shared_ptr and return a shared_ptr instead. The pointer gets returned and reference counts correctly.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Suppose I have the following code: ``` class some_class{}; some_class some_function() { return some_class(); } ``` This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?
No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary.
96,541
<p>This isn't legal:</p> <pre><code>public class MyBaseClass { public MyBaseClass() {} public MyBaseClass(object arg) {} } public void ThisIsANoNo&lt;T&gt;() where T : MyBaseClass { T foo = new T("whoops!"); } </code></pre> <p>In order to do this, you have to do some reflection on the type object for T or you have to use Activator.CreateInstance. Both are pretty nasty. Is there a better way?</p>
[ { "answer_id": 96557, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<pre><code>where T : MyBaseClass, new()\n</code></pre>\n\n<p>only works w/ parameterless public constructor. beyond that, back to activator.CreateInstance (which really isn't THAT bad).</p>\n" }, { "answer_id": 96558, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 2, "selected": false, "text": "<p>Nope. If you weren't passing in parameters, then you could constrain your type param to require a parameterless constructor. But, if you need to pass arguments you are out of luck.</p>\n" }, { "answer_id": 96581, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": -1, "selected": false, "text": "<p>I can see that not working.</p>\n\n<p>But what is stopping you from doing this?</p>\n\n<pre><code>public void ThisIsANoNo&lt;T&gt;() where T : MyBaseClass\n{\n MyBaseClass foo = new MyBaseClass(\"whoops!\");\n}\n</code></pre>\n\n<p>Since everything is going to inherit from MyBaseClass they will al be MyBaseClass, right?</p>\n\n<p>I tried it and this works.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n ThisIsANoNo&lt;MyClass&gt;();\n ThisIsANoNo&lt;MyBaseClass&gt;();\n }\n\n public class MyBaseClass\n {\n public MyBaseClass() { }\n public MyBaseClass(object arg) { }\n }\n\n public class MyClass :MyBaseClass\n {\n public MyClass() { }\n public MyClass(object arg, Object arg2) { }\n }\n\n public static void ThisIsANoNo&lt;T&gt;() where T : MyBaseClass\n {\n MyBaseClass foo = new MyBaseClass(\"whoops!\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 96752, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 2, "selected": true, "text": "<p>You can't constrain T to have a particular constructor signature other than an empty constructor, but you can constrain T to have a factory method with the desired signature:</p>\n\n<pre><code>public abstract class MyBaseClass\n{\n protected MyBaseClass() {}\n protected abstract MyBaseClass CreateFromObject(object arg);\n}\n\npublic void ThisWorksButIsntGreat&lt;T&gt;() where T : MyBaseClass, new()\n{\n T foo = new T().CreateFromObject(\"whoopee!\") as T;\n}\n</code></pre>\n\n<p>However, I would suggest perhaps using a different creational pattern such as Abstract Factory for this scenario.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This isn't legal: ``` public class MyBaseClass { public MyBaseClass() {} public MyBaseClass(object arg) {} } public void ThisIsANoNo<T>() where T : MyBaseClass { T foo = new T("whoops!"); } ``` In order to do this, you have to do some reflection on the type object for T or you have to use Activator.CreateInstance. Both are pretty nasty. Is there a better way?
You can't constrain T to have a particular constructor signature other than an empty constructor, but you can constrain T to have a factory method with the desired signature: ``` public abstract class MyBaseClass { protected MyBaseClass() {} protected abstract MyBaseClass CreateFromObject(object arg); } public void ThisWorksButIsntGreat<T>() where T : MyBaseClass, new() { T foo = new T().CreateFromObject("whoopee!") as T; } ``` However, I would suggest perhaps using a different creational pattern such as Abstract Factory for this scenario.
96,553
<p>Is it particularly bad to have a very, very large SQL query with lots of (potentially redundant) WHERE clauses?</p> <p>For example, here's a query I've generated from my web application with everything turned off, which should be the largest possible query for this program to generate:</p> <pre><code>SELECT * FROM 4e_magic_items INNER JOIN 4e_magic_item_levels ON 4e_magic_items.id = 4e_magic_item_levels.itemid INNER JOIN 4e_monster_sources ON 4e_magic_items.source = 4e_monster_sources.id WHERE (itemlevel BETWEEN 1 AND 30) AND source!=16 AND source!=2 AND source!=5 AND source!=13 AND source!=15 AND source!=3 AND source!=4 AND source!=12 AND source!=7 AND source!=14 AND source!=11 AND source!=10 AND source!=8 AND source!=1 AND source!=6 AND source!=9 AND type!='Arms' AND type!='Feet' AND type!='Hands' AND type!='Head' AND type!='Neck' AND type!='Orb' AND type!='Potion' AND type!='Ring' AND type!='Rod' AND type!='Staff' AND type!='Symbol' AND type!='Waist' AND type!='Wand' AND type!='Wondrous Item' AND type!='Alchemical Item' AND type!='Elixir' AND type!='Reagent' AND type!='Whetstone' AND type!='Other Consumable' AND type!='Companion' AND type!='Mount' AND (type!='Armor' OR (false )) AND (type!='Weapon' OR (false )) ORDER BY type ASC, itemlevel ASC, name ASC </code></pre> <p>It seems to work well enough, but it's also not particularly high traffic (a few hundred hits a day or so), and I wonder if it would be worth the effort to try and optimize the queries to remove redundancies and such.</p>
[ { "answer_id": 96572, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": 0, "selected": false, "text": "<p>Most databases support stored procedures to avoid this issue. If your code is fast enough to execute and easy to read, you don't want to have to change it in order to get the compile time down.</p>\n\n<p>An alternative is to use prepared statements so you get the hit only once per client connection and then pass in only the parameters for each call</p>\n" }, { "answer_id": 96593, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 4, "selected": false, "text": "<p>Default MySQL 5.0 server limitation is \"<strong>1MB</strong>\", configurable up to 1GB.</p>\n\n<p>This is configured via the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/packet-too-large.html\" rel=\"noreferrer\">max_allowed_packet</a> setting on both client and server, and the effective limitation is the lessor of the two.</p>\n\n<p>Caveats:</p>\n\n<ul>\n<li>It's likely that this \"packet\" limitation does not map directly to characters in a SQL statement. Surely you want to take into account character encoding within the client, some packet metadata, etc.)</li>\n</ul>\n" }, { "answer_id": 96598, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 5, "selected": true, "text": "<p>Reading your query makes me want to play an RPG.</p>\n\n<p>This is definitely not too long. As long as they are well formatted, I'd say a practical limit is about 100 lines. After that, you're better off breaking subqueries into views just to keep your eyes from crossing.</p>\n\n<p>I've worked with some queries that are 1000+ lines, and that's hard to debug.</p>\n\n<p>By the way, may I suggest a reformatted version? This is mostly to demonstrate the importance of formatting; I trust this will be easier to understand.</p>\n\n<pre><code>select * \nfrom\n 4e_magic_items mi\n ,4e_magic_item_levels mil\n ,4e_monster_sources ms\nwhere mi.id = mil.itemid\n and mi.source = ms.id\n and itemlevel between 1 and 30\n and source not in(16,2,5,13,15,3,4,12,7,14,11,10,8,1,6,9) \n and type not in(\n 'Arms' ,'Feet' ,'Hands' ,'Head' ,'Neck' ,'Orb' ,\n 'Potion' ,'Ring' ,'Rod' ,'Staff' ,'Symbol' ,'Waist' ,\n 'Wand' ,'Wondrous Item' ,'Alchemical Item' ,'Elixir' ,\n 'Reagent' ,'Whetstone' ,'Other Consumable' ,'Companion' ,\n 'Mount'\n )\n and ((type != 'Armor') or (false))\n and ((type != 'Weapon') or (false))\norder by\n type asc\n ,itemlevel asc\n ,name asc\n\n/*\nSome thoughts:\n==============\n0 - Formatting really matters, in SQL even more than most languages.\n1 - consider selecting only the columns you need, not \"*\"\n2 - use of table aliases makes it short &amp; clear (\"MI\", \"MIL\" in my example)\n3 - joins in the WHERE clause will un-clutter your FROM clause\n4 - use NOT IN for long lists\n5 - logically, the last two lines can be added to the \"type not in\" section.\n I'm not sure why you have the \"or false\", but I'll assume some good reason\n and leave them here.\n*/\n</code></pre>\n" }, { "answer_id": 96628, "author": "Matthew Rapati", "author_id": 15000, "author_profile": "https://Stackoverflow.com/users/15000", "pm_score": 0, "selected": false, "text": "<p>I'm assuming you mean by 'turned off' that a field doesn't have a value?</p>\n\n<p>Instead of checking if something is not this, and it's also not that etc. can't you just check if the field is null? Or set the field to 'off', and check if type or whatever equals 'off'.</p>\n" }, { "answer_id": 96689, "author": "Kate Bertelsen", "author_id": 16633, "author_profile": "https://Stackoverflow.com/users/16633", "pm_score": 1, "selected": false, "text": "<p>From a practical perspective, I generally consider any SELECT that ends up taking more than 10 lines to write (putting each clause/condition on a separate line) to be too long to easily maintain. At this point, it should probably be done as a stored procedure of some sort, or I should try to find a better way to express the same concept--possibly by creating an intermediate table to capture some relationship I seem to be frequently querying.</p>\n\n<p>Your mileage may vary, and there are some exceptionally long queries that have a good reason to be. But my rule of thumb is 10 lines.</p>\n\n<p><strong>Example</strong> (mildly improper SQL):</p>\n\n<pre><code>SELECT x, y, z\nFROM a, b\nWHERE fiz = 1\nAND foo = 2\nAND a.x = b.y\nAND b.z IN (SELECT q, r, s, t\n FROM c, d, e\n WHERE c.q = d.r\n AND d.s = e.t\n AND c.gar IS NOT NULL)\nORDER BY b.gonk\n</code></pre>\n\n<p>This is probably too large; optimizing, however, would depend largely on context.</p>\n\n<p>Just remember, the longer and more complex the query, the harder it's going to be to maintain.</p>\n" }, { "answer_id": 35791620, "author": "Ga1der", "author_id": 2694969, "author_profile": "https://Stackoverflow.com/users/2694969", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>SELECT @@global.max_allowed_packet</p>\n</blockquote>\n\n<p>this is the only real limit it's adjustable on a server so there is no real straight answer</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18210/" ]
Is it particularly bad to have a very, very large SQL query with lots of (potentially redundant) WHERE clauses? For example, here's a query I've generated from my web application with everything turned off, which should be the largest possible query for this program to generate: ``` SELECT * FROM 4e_magic_items INNER JOIN 4e_magic_item_levels ON 4e_magic_items.id = 4e_magic_item_levels.itemid INNER JOIN 4e_monster_sources ON 4e_magic_items.source = 4e_monster_sources.id WHERE (itemlevel BETWEEN 1 AND 30) AND source!=16 AND source!=2 AND source!=5 AND source!=13 AND source!=15 AND source!=3 AND source!=4 AND source!=12 AND source!=7 AND source!=14 AND source!=11 AND source!=10 AND source!=8 AND source!=1 AND source!=6 AND source!=9 AND type!='Arms' AND type!='Feet' AND type!='Hands' AND type!='Head' AND type!='Neck' AND type!='Orb' AND type!='Potion' AND type!='Ring' AND type!='Rod' AND type!='Staff' AND type!='Symbol' AND type!='Waist' AND type!='Wand' AND type!='Wondrous Item' AND type!='Alchemical Item' AND type!='Elixir' AND type!='Reagent' AND type!='Whetstone' AND type!='Other Consumable' AND type!='Companion' AND type!='Mount' AND (type!='Armor' OR (false )) AND (type!='Weapon' OR (false )) ORDER BY type ASC, itemlevel ASC, name ASC ``` It seems to work well enough, but it's also not particularly high traffic (a few hundred hits a day or so), and I wonder if it would be worth the effort to try and optimize the queries to remove redundancies and such.
Reading your query makes me want to play an RPG. This is definitely not too long. As long as they are well formatted, I'd say a practical limit is about 100 lines. After that, you're better off breaking subqueries into views just to keep your eyes from crossing. I've worked with some queries that are 1000+ lines, and that's hard to debug. By the way, may I suggest a reformatted version? This is mostly to demonstrate the importance of formatting; I trust this will be easier to understand. ``` select * from 4e_magic_items mi ,4e_magic_item_levels mil ,4e_monster_sources ms where mi.id = mil.itemid and mi.source = ms.id and itemlevel between 1 and 30 and source not in(16,2,5,13,15,3,4,12,7,14,11,10,8,1,6,9) and type not in( 'Arms' ,'Feet' ,'Hands' ,'Head' ,'Neck' ,'Orb' , 'Potion' ,'Ring' ,'Rod' ,'Staff' ,'Symbol' ,'Waist' , 'Wand' ,'Wondrous Item' ,'Alchemical Item' ,'Elixir' , 'Reagent' ,'Whetstone' ,'Other Consumable' ,'Companion' , 'Mount' ) and ((type != 'Armor') or (false)) and ((type != 'Weapon') or (false)) order by type asc ,itemlevel asc ,name asc /* Some thoughts: ============== 0 - Formatting really matters, in SQL even more than most languages. 1 - consider selecting only the columns you need, not "*" 2 - use of table aliases makes it short & clear ("MI", "MIL" in my example) 3 - joins in the WHERE clause will un-clutter your FROM clause 4 - use NOT IN for long lists 5 - logically, the last two lines can be added to the "type not in" section. I'm not sure why you have the "or false", but I'll assume some good reason and leave them here. */ ```
96,579
<p>I'm writing an inner loop that needs to place <code>struct</code>s in contiguous storage. I don't know how many of these <code>struct</code>s there will be ahead of time. My problem is that STL's <code>vector</code> initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the <code>struct</code>'s members to their values.</p> <p>Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements?</p> <p>(I'm certain that this part of the code needs to be optimized, and I'm certain that the initialization is a significant cost.)</p> <p>Also, see my comments below for a clarification about when the initialization occurs.</p> <p>SOME CODE:</p> <pre><code>void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size() memberVector.resize(mvSize + count); // causes 0-initialization for (int i = 0; i &lt; count; ++i) { memberVector[mvSize + i].d1 = data1[i]; memberVector[mvSize + i].d2 = data2[i]; } } </code></pre>
[ { "answer_id": 96601, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 1, "selected": false, "text": "<p>Use the std::vector::reserve() method. It won't resize the vector, but it will allocate the space.</p>\n" }, { "answer_id": 96630, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "<p>Err...</p>\n\n<p>try the method:</p>\n\n<pre><code>std::vector&lt;T&gt;::reserve(x)\n</code></pre>\n\n<p>It will enable you to reserve enough memory for x items without initializing any (your vector is still empty). Thus, there won't be reallocation until to go over x.</p>\n\n<p>The second point is that vector won't initialize the values to zero. Are you testing your code in debug ?</p>\n\n<p>After verification on g++, the following code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nstruct MyStruct\n{\n int m_iValue00 ;\n int m_iValue01 ;\n} ;\n\nint main()\n{\n MyStruct aaa, bbb, ccc ;\n\n std::vector&lt;MyStruct&gt; aMyStruct ;\n\n aMyStruct.push_back(aaa) ;\n aMyStruct.push_back(bbb) ;\n aMyStruct.push_back(ccc) ;\n\n aMyStruct.resize(6) ; // [EDIT] double the size\n\n for(std::vector&lt;MyStruct&gt;::size_type i = 0, iMax = aMyStruct.size(); i &lt; iMax; ++i)\n {\n std::cout &lt;&lt; \"[\" &lt;&lt; i &lt;&lt; \"] : \" &lt;&lt; aMyStruct[i].m_iValue00 &lt;&lt; \", \" &lt;&lt; aMyStruct[0].m_iValue01 &lt;&lt; \"\\n\" ;\n }\n\n return 0 ;\n}\n</code></pre>\n\n<p>gives the following results:</p>\n\n<pre><code>[0] : 134515780, -16121856\n[1] : 134554052, -16121856\n[2] : 134544501, -16121856\n[3] : 0, -16121856\n[4] : 0, -16121856\n[5] : 0, -16121856\n</code></pre>\n\n<p>The initialization you saw was probably an artifact.</p>\n\n<p>[EDIT] After the comment on resize, I modified the code to add the resize line. The resize effectively calls the default constructor of the object inside the vector, but if the default constructor does nothing, then nothing is initialized... I still believe it was an artifact (I managed the first time to have the whole vector zerooed with the following code:</p>\n\n<pre><code>aMyStruct.push_back(MyStruct()) ;\naMyStruct.push_back(MyStruct()) ;\naMyStruct.push_back(MyStruct()) ;\n</code></pre>\n\n<p>So...\n:-/</p>\n\n<p>[EDIT 2] Like already offered by Arkadiy, the solution is to use an inline constructor taking the desired parameters. Something like</p>\n\n<pre><code>struct MyStruct\n{\n MyStruct(int p_d1, int p_d2) : d1(p_d1), d2(p_d2) {}\n int d1, d2 ;\n} ;\n</code></pre>\n\n<p>This will probably get inlined in your code.</p>\n\n<p>But you should anyway study your code with a profiler to be sure this piece of code is the bottleneck of your application.</p>\n" }, { "answer_id": 96745, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "<p>Do the structs themselves need to be in contiguous memory, or can you get away with having a vector of struct*?</p>\n\n<p>Vectors make a copy of whatever you add to them, so using vectors of pointers rather than objects is one way to improve performance.</p>\n" }, { "answer_id": 96836, "author": "mbyrne215", "author_id": 5241, "author_profile": "https://Stackoverflow.com/users/5241", "pm_score": 0, "selected": false, "text": "<p>I don't think STL is your answer. You're going to need to roll your own sort of solution using realloc(). You'll have to store a pointer and either the size, or number of elements, and use that to find where to start adding elements after a realloc().</p>\n\n<pre><code>int *memberArray;\nint arrayCount;\nvoid GetsCalledALot(int* data1, int* data2, int count) {\n memberArray = realloc(memberArray, sizeof(int) * (arrayCount + count);\n for (int i = 0; i &lt; count; ++i) {\n memberArray[arrayCount + i].d1 = data1[i];\n memberArray[arrayCount + i].d2 = data2[i];\n }\n arrayCount += count;\n}\n</code></pre>\n" }, { "answer_id": 96856, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 3, "selected": false, "text": "<p>So here's the problem, resize is calling insert, which is doing a copy construction from a default constructed element for each of the newly added elements. To get this to 0 cost you need to write your own default constructor AND your own copy constructor as empty functions. Doing this to your copy constructor is a <strong>very bad idea</strong> because it will break std::vector's internal reallocation algorithms.</p>\n\n<p>Summary: You're not going to be able to do this with std::vector.</p>\n" }, { "answer_id": 96864, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>To clarify on reserve() responses: you need to use reserve() in conjunction with push_back(). This way, the default constructor is not called for each element, but rather the copy constructor. You still incur the penalty of setting up your struct on stack, and then copying it to the vector. On the other hand, it's possible that if you use</p>\n\n<pre><code>vect.push_back(MyStruct(fieldValue1, fieldValue2))\n</code></pre>\n\n<p>the compiler will construct the new instance directly in the memory thatbelongs to the vector. It depends on how smart the optimizer is. You need to check the generated code to find out.</p>\n" }, { "answer_id": 96878, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>From your comments to other posters, it looks like you're left with malloc() and friends. Vector won't let you have unconstructed elements.</p>\n" }, { "answer_id": 97061, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>From your code, it looks like you have a vector of structs each of which comprises 2 ints. Could you instead use 2 vectors of ints? Then</p>\n\n<pre><code>copy(data1, data1 + count, back_inserter(v1));\ncopy(data2, data2 + count, back_inserter(v2));\n</code></pre>\n\n<p>Now you don't pay for copying a struct each time.</p>\n" }, { "answer_id": 97434, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 0, "selected": false, "text": "<p>I would do something like:</p>\n\n<pre><code>void GetsCalledALot(int* data1, int* data2, int count)\n{\n const size_t mvSize = memberVector.size();\n memberVector.reserve(mvSize + count);\n\n for (int i = 0; i &lt; count; ++i) {\n memberVector.push_back(MyType(data1[i], data2[i]));\n }\n}\n</code></pre>\n\n<p>You need to define a ctor for the type that is stored in the memberVector, but that's a small cost as it will give you the best of both worlds; no unnecessary initialization is done and no reallocation will occur during the loop.</p>\n" }, { "answer_id": 97536, "author": "Lloyd", "author_id": 9952, "author_profile": "https://Stackoverflow.com/users/9952", "pm_score": 6, "selected": true, "text": "<p><code>std::vector</code> must initialize the values in the array somehow, which means some constructor (or copy-constructor) must be called. The behavior of <code>vector</code> (or any container class) is undefined if you were to access the uninitialized section of the array as if it were initialized.</p>\n\n<p>The best way is to use <code>reserve()</code> and <code>push_back()</code>, so that the copy-constructor is used, avoiding default-construction.</p>\n\n<p>Using your example code:</p>\n\n<pre><code>struct YourData {\n int d1;\n int d2;\n YourData(int v1, int v2) : d1(v1), d2(v2) {}\n};\n\nstd::vector&lt;YourData&gt; memberVector;\n\nvoid GetsCalledALot(int* data1, int* data2, int count) {\n int mvSize = memberVector.size();\n\n // Does not initialize the extra elements\n memberVector.reserve(mvSize + count);\n\n // Note: consider using std::generate_n or std::copy instead of this loop.\n for (int i = 0; i &lt; count; ++i) {\n // Copy construct using a temporary.\n memberVector.push_back(YourData(data1[i], data2[i]));\n }\n}\n</code></pre>\n\n<p>The only problem with calling <code>reserve()</code> (or <code>resize()</code>) like this is that you may end up invoking the copy-constructor more often than you need to. If you can make a good prediction as to the final size of the array, it's better to <code>reserve()</code> the space once at the beginning. If you don't know the final size though, at least the number of copies will be minimal on average.</p>\n\n<p>In the current version of C++, the inner loop is a bit inefficient as a temporary value is constructed on the stack, copy-constructed to the vectors memory, and finally the temporary is destroyed. However the next version of C++ has a feature called R-Value references (<code>T&amp;&amp;</code>) which will help.</p>\n\n<p>The interface supplied by <code>std::vector</code> does not allow for another option, which is to use some factory-like class to construct values other than the default. Here is a rough example of what this pattern would look like implemented in C++:</p>\n\n<pre><code>template &lt;typename T&gt;\nclass my_vector_replacement {\n\n // ...\n\n template &lt;typename F&gt;\n my_vector::push_back_using_factory(F factory) {\n // ... check size of array, and resize if needed.\n\n // Copy construct using placement new,\n new(arrayData+end) T(factory())\n end += sizeof(T);\n }\n\n char* arrayData;\n size_t end; // Of initialized data in arrayData\n};\n\n// One of many possible implementations\nstruct MyFactory {\n MyFactory(int* p1, int* p2) : d1(p1), d2(p2) {}\n YourData operator()() const {\n return YourData(*d1,*d2);\n }\n int* d1;\n int* d2;\n};\n\nvoid GetsCalledALot(int* data1, int* data2, int count) {\n // ... Still will need the same call to a reserve() type function.\n\n // Note: consider using std::generate_n or std::copy instead of this loop.\n for (int i = 0; i &lt; count; ++i) {\n // Copy construct using a factory\n memberVector.push_back_using_factory(MyFactory(data1+i, data2+i));\n }\n}\n</code></pre>\n\n<p>Doing this does mean you have to create your own vector class. In this case it also complicates what should have been a simple example. But there may be times where using a factory function like this is better, for instance if the insert is conditional on some other value, and you would have to otherwise unconditionally construct some expensive temporary even if it wasn't actually needed.</p>\n" }, { "answer_id": 2798740, "author": "fredoverflow", "author_id": 252000, "author_profile": "https://Stackoverflow.com/users/252000", "pm_score": 4, "selected": false, "text": "<p>C++0x adds a new member function template <code>emplace_back</code> to <code>vector</code> (which relies on variadic templates and perfect forwarding) that gets rid of any temporaries entirely:</p>\n\n<pre><code>memberVector.emplace_back(data1[i], data2[i]);\n</code></pre>\n" }, { "answer_id": 7337665, "author": "Darko Veberic", "author_id": 933219, "author_profile": "https://Stackoverflow.com/users/933219", "pm_score": 1, "selected": false, "text": "<p>If you really insist on having the elements uninitialized and sacrifice some methods like front(), back(), push_back(), use boost vector from numeric . It allows you even not to preserve existing elements when calling resize()...</p>\n" }, { "answer_id": 18468610, "author": "goertzenator", "author_id": 398021, "author_profile": "https://Stackoverflow.com/users/398021", "pm_score": 4, "selected": false, "text": "<p>In C++11 (and boost) you can use the array version of <code>unique_ptr</code> to allocate an uninitialized array. This isn't quite an stl container, but is still memory managed and C++-ish which will be good enough for many applications.</p>\n\n<pre><code>auto my_uninit_array = std::unique_ptr&lt;mystruct[]&gt;(new mystruct[count]);\n</code></pre>\n" }, { "answer_id": 42510583, "author": "deonb", "author_id": 7508986, "author_profile": "https://Stackoverflow.com/users/7508986", "pm_score": 2, "selected": false, "text": "<p>You can use a wrapper type around your element type, with a default constructor that does nothing. E.g.:</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct no_init\n{\n T value;\n\n no_init() { static_assert(std::is_standard_layout&lt;no_init&lt;T&gt;&gt;::value &amp;&amp; sizeof(T) == sizeof(no_init&lt;T&gt;), \"T does not have standard layout\"); }\n\n no_init(T&amp; v) { value = v; }\n T&amp; operator=(T&amp; v) { value = v; return value; }\n\n no_init(no_init&lt;T&gt;&amp; n) { value = n.value; }\n no_init(no_init&lt;T&gt;&amp;&amp; n) { value = std::move(n.value); }\n T&amp; operator=(no_init&lt;T&gt;&amp; n) { value = n.value; return this; }\n T&amp; operator=(no_init&lt;T&gt;&amp;&amp; n) { value = std::move(n.value); return this; }\n\n T* operator&amp;() { return &amp;value; } // So you can use &amp;(vec[0]) etc.\n};\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>std::vector&lt;no_init&lt;char&gt;&gt; vec;\nvec.resize(2ul * 1024ul * 1024ul * 1024ul);\n</code></pre>\n" }, { "answer_id": 61641730, "author": "Maxim Egorushkin", "author_id": 412080, "author_profile": "https://Stackoverflow.com/users/412080", "pm_score": 3, "selected": false, "text": "<p>You can use <code>boost::noinit_adaptor</code> to <a href=\"https://en.cppreference.com/w/cpp/language/default_initialization\" rel=\"noreferrer\"><em>default initialize</em></a> new elements (which is no initialization for built-in types):</p>\n\n<pre><code>std::vector&lt;T, boost::noinit_adaptor&lt;std::allocator&lt;T&gt;&gt; memberVector;\n</code></pre>\n\n<p>As long as you don't pass an initializer into <code>resize</code>, it <em>default initializes</em> the new elements.</p>\n" }, { "answer_id": 64211027, "author": "SunlayGGX", "author_id": 14395275, "author_profile": "https://Stackoverflow.com/users/14395275", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about all those answers that says it is impossible or tell us about undefined behavior.</p>\n<p>Sometime, you need to use an std::vector. But sometime, you know the final size of it. And you also know that your elements will be constructed later.\nExample : When you serialize the vector contents into a binary file, then read it back later.\nUnreal Engine has its TArray::setNumUninitialized, why not std::vector ?</p>\n<p>To answer the initial question\n&quot;Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements?&quot;</p>\n<p>yes and no.\nNo, because STL doesn't expose a way to do so.</p>\n<p>Yes because we're coding in C++, and C++ allows to do a lot of thing. If you're ready to be a bad guy (and if you really know what you are doing). You can hijack the vector.</p>\n<p>Here a sample code that works only for the Windows's STL implementation, for another platform, look how std::vector is implemented to use its internal members :</p>\n<pre><code>// This macro is to be defined before including VectorHijacker.h. Then you will be able to reuse the VectorHijacker.h with different objects.\n#define HIJACKED_TYPE SomeStruct\n\n// VectorHijacker.h\n#ifndef VECTOR_HIJACKER_STRUCT\n#define VECTOR_HIJACKER_STRUCT\n\nstruct VectorHijacker\n{\n std::size_t _newSize;\n};\n\n#endif\n\n\ntemplate&lt;&gt;\ntemplate&lt;&gt;\ninline decltype(auto) std::vector&lt;HIJACKED_TYPE, std::allocator&lt;HIJACKED_TYPE&gt;&gt;::emplace_back&lt;const VectorHijacker &amp;&gt;(const VectorHijacker &amp;hijacker)\n{\n // We're modifying directly the size of the vector without passing by the extra initialization. This is the part that relies on how the STL was implemented.\n _Mypair._Myval2._Mylast = _Mypair._Myval2._Myfirst + hijacker._newSize;\n}\n\ninline void setNumUninitialized_hijack(std::vector&lt;HIJACKED_TYPE&gt; &amp;hijackedVector, const VectorHijacker &amp;hijacker)\n{\n hijackedVector.reserve(hijacker._newSize);\n hijackedVector.emplace_back&lt;const VectorHijacker &amp;&gt;(hijacker);\n}\n</code></pre>\n<p>But beware, this is hijacking we're speaking about. This is really dirty code, and this is only to be used if you really know what you are doing. Besides, it is not portable and relies heavily on how the STL implementation was done.</p>\n<p>I won't advise you to use it because everyone here (me included) is a good person. But I wanted to let you know that it is possible contrary to all previous answers that stated it wasn't.</p>\n" }, { "answer_id": 72015151, "author": "Henryk", "author_id": 10503465, "author_profile": "https://Stackoverflow.com/users/10503465", "pm_score": 1, "selected": false, "text": "<p>I tested a few of the approaches suggested here.\nI allocated a huge set of data (200GB) in one container/pointer:</p>\n<p>Compiler/OS:</p>\n<pre><code>g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0\n</code></pre>\n<p>Settings: (c++-17, -O3 optimizations)</p>\n<pre><code>g++ --std=c++17 -O3\n</code></pre>\n<p>I timed the total program runtime with linux-time</p>\n<p>1.) std::vector:</p>\n<pre><code>#include &lt;vector&gt;\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector&lt;size_t&gt; vec(size);\n}\nreal 0m36.246s\nuser 0m4.549s\nsys 0m31.604s\n</code></pre>\n<p>That is 36 seconds.</p>\n<p>2.) std::vector with boost::noinit_adaptor</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;boost/core/noinit_adaptor.hpp&gt;\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector&lt;size_t,boost::noinit_adaptor&lt;std::allocator&lt;size_t&gt;&gt;&gt; vec(size);\n}\n\nreal 0m0.002s\nuser 0m0.001s\nsys 0m0.000s\n</code></pre>\n<p>So this solves the problem. Just allocating without initializing costs basically nothing (at least for large arrays).</p>\n<p>3.) std::unique_ptr&lt;T[]&gt;:</p>\n<pre><code>#include &lt;memory&gt;\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n auto data = std::unique_ptr&lt;size_t[]&gt;(new size_t[size]);\n}\n\nreal 0m0.002s\nuser 0m0.002s\nsys 0m0.000s\n</code></pre>\n<p>So basically the same performance as 2.), but does not require boost.\nI also tested simple new/delete and malloc/free with the same performance as 2.) and 3.).</p>\n<p>So the default-construction can have a huge performance penalty if you deal with large data sets.\nIn practice you want to actually initialize the allocated data afterwards.\nHowever, some of the performance penalty still remains, especially if the later initialization is performed in parallel.\nE.g., I initialize a huge vector with a set of (pseudo)random numbers:</p>\n<p>(now I use fopenmp for parallelization on a 24 core AMD Threadripper 3960X)</p>\n<pre><code>g++ --std=c++17-fopenmp -O3\n</code></pre>\n<p>1.) std::vector:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;random&gt;\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector&lt;size_t&gt; vec(size);\n #pragma omp parallel\n {\n std::minstd_rand0 gen(42);\n #pragma omp for schedule(static)\n for (size_t i = 0; i &lt; size; ++i) vec[i] = gen();\n }\n}\nreal 0m41.958s\nuser 4m37.495s\nsys 0m31.348s\n</code></pre>\n<p>That is 42s, only 6s more than the default initialization.\nThe problem is, that the initialization of std::vector is sequential.</p>\n<p>2.) std::vector with boost::noinit_adaptor:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;random&gt;\n#include &lt;boost/core/noinit_adaptor.hpp&gt;\n\nint main(){\n constexpr size_t size = 1024lu*1024lu*1024lu*25lu;//25B elements = 200GB\n std::vector&lt;size_t,boost::noinit_adaptor&lt;std::allocator&lt;size_t&gt;&gt;&gt; vec(size);\n #pragma omp parallel\n {\n std::minstd_rand0 gen(42);\n #pragma omp for schedule(static)\n for (size_t i = 0; i &lt; size; ++i) vec[i] = gen();\n }\n}\nreal 0m10.508s\nuser 1m37.665s\nsys 3m14.951s\n</code></pre>\n<p>So even with the random-initialization, the code is 4 times faster because we can skip the sequential initialization of <code>std::vector</code>.</p>\n<p>So if you deal with huge data sets and plan to initialize them afterwards in parallel, you should avoid using the default std::vector.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6160/" ]
I'm writing an inner loop that needs to place `struct`s in contiguous storage. I don't know how many of these `struct`s there will be ahead of time. My problem is that STL's `vector` initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the `struct`'s members to their values. Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements? (I'm certain that this part of the code needs to be optimized, and I'm certain that the initialization is a significant cost.) Also, see my comments below for a clarification about when the initialization occurs. SOME CODE: ``` void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size() memberVector.resize(mvSize + count); // causes 0-initialization for (int i = 0; i < count; ++i) { memberVector[mvSize + i].d1 = data1[i]; memberVector[mvSize + i].d2 = data2[i]; } } ```
`std::vector` must initialize the values in the array somehow, which means some constructor (or copy-constructor) must be called. The behavior of `vector` (or any container class) is undefined if you were to access the uninitialized section of the array as if it were initialized. The best way is to use `reserve()` and `push_back()`, so that the copy-constructor is used, avoiding default-construction. Using your example code: ``` struct YourData { int d1; int d2; YourData(int v1, int v2) : d1(v1), d2(v2) {} }; std::vector<YourData> memberVector; void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size(); // Does not initialize the extra elements memberVector.reserve(mvSize + count); // Note: consider using std::generate_n or std::copy instead of this loop. for (int i = 0; i < count; ++i) { // Copy construct using a temporary. memberVector.push_back(YourData(data1[i], data2[i])); } } ``` The only problem with calling `reserve()` (or `resize()`) like this is that you may end up invoking the copy-constructor more often than you need to. If you can make a good prediction as to the final size of the array, it's better to `reserve()` the space once at the beginning. If you don't know the final size though, at least the number of copies will be minimal on average. In the current version of C++, the inner loop is a bit inefficient as a temporary value is constructed on the stack, copy-constructed to the vectors memory, and finally the temporary is destroyed. However the next version of C++ has a feature called R-Value references (`T&&`) which will help. The interface supplied by `std::vector` does not allow for another option, which is to use some factory-like class to construct values other than the default. Here is a rough example of what this pattern would look like implemented in C++: ``` template <typename T> class my_vector_replacement { // ... template <typename F> my_vector::push_back_using_factory(F factory) { // ... check size of array, and resize if needed. // Copy construct using placement new, new(arrayData+end) T(factory()) end += sizeof(T); } char* arrayData; size_t end; // Of initialized data in arrayData }; // One of many possible implementations struct MyFactory { MyFactory(int* p1, int* p2) : d1(p1), d2(p2) {} YourData operator()() const { return YourData(*d1,*d2); } int* d1; int* d2; }; void GetsCalledALot(int* data1, int* data2, int count) { // ... Still will need the same call to a reserve() type function. // Note: consider using std::generate_n or std::copy instead of this loop. for (int i = 0; i < count; ++i) { // Copy construct using a factory memberVector.push_back_using_factory(MyFactory(data1+i, data2+i)); } } ``` Doing this does mean you have to create your own vector class. In this case it also complicates what should have been a simple example. But there may be times where using a factory function like this is better, for instance if the insert is conditional on some other value, and you would have to otherwise unconditionally construct some expensive temporary even if it wasn't actually needed.
96,597
<p>My development server (CentOS 5) is running Subversion 1.4.2, and I wish to upgrade it to 1.5. I have read in various blogs and documents scattered around the web that this may be done by using RPMForge. I have followed the instructions found on <a href="http://wiki.centos.org/AdditionalResources/Repositories/RPMForge?action=show&amp;redirect=Repositories%2FRPMForge" rel="nofollow noreferrer">CentOS Wiki</a>, including installing yum-priorities and setting my priorities as indicated (1 and 2 for core repo sources, and 20 for RPMForge).</p> <p>However, when I attempt to run:</p> <pre><code>$ yum info subversion </code></pre> <p>the version number given to me is still 1.4.2, with a status of Installed. My other option at this point is compiling from source, but I would like to find a package-managed solution for ease of future upgrades.</p> <p>Any thoughts?</p>
[ { "answer_id": 96662, "author": "Peter Stone", "author_id": 1806, "author_profile": "https://Stackoverflow.com/users/1806", "pm_score": 1, "selected": false, "text": "<p>If you install <a href=\"http://wiki.centos.org/AdditionalResources/Repositories/RPMForge\" rel=\"nofollow noreferrer\">RPMForge</a>'s repos, you should then be able to get a newer package - this isn't working for you?</p>\n\n<p>You should see rpmforge.list in /etc/apt/sources.list.d with a line like:</p>\n\n<pre><code>repomd http://apt.sw.be redhat/el$(VERSION)/en/$(ARCH)/dag\n</code></pre>\n\n<p>I just tested on a clean CentOS 5 install, and <code>yum check-update</code> shows</p>\n\n<pre><code>subversion.i386 1.5.2-0.1.el5.rf rpmforge\nsubversion-perl.i386 1.5.2-0.1.el5.rf rpmforge\n</code></pre>\n\n<p>So check your sources list and run check-update again.</p>\n\n<p>Edit: Whoops, lost part of my answer. Added it back above.</p>\n" }, { "answer_id": 96714, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 0, "selected": false, "text": "<p>its up to v 1.4.6 in Dag's repository.</p>\n\n<p>You can try the one from <a href=\"https://admin.fedoraproject.org/pkgdb/packages/name/subversion\" rel=\"nofollow noreferrer\">Fedora's repo</a> or have a bit of patience for the main repositories to upgrade it.</p>\n\n<p>Making it from source is easy, read the INSTALL file when you download the source package, bear in mind CentOS may have moved where the files get installed. (Use \"rpm -ql subversion\" to see where the old files were installed to). </p>\n\n<p>When v1.5.0 gets released to the repository, you can delete your built version and install using yum as before.</p>\n" }, { "answer_id": 96767, "author": "jperras", "author_id": 5570, "author_profile": "https://Stackoverflow.com/users/5570", "pm_score": 0, "selected": false, "text": "<p>RPMForge is already in /etc/yum.repos.d/ as rpmforge.repo, and the contents are:</p>\n\n<pre>\n# Name: RPMforge RPM Repository for Red Hat Enterprise 5 - dag\n# URL: http://rpmforge.net/\n[rpmforge]\nname = Red Hat Enterprise $releasever - RPMforge.net - dag\n#baseurl = http://apt.sw.be/redhat/el5/en/$basearch/dag\nmirrorlist = http://apt.sw.be/redhat/el5/en/mirrors-rpmforge\n#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge\nenabled = 1\nprotect = 0\ngpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag\ngpgcheck = 1\npriority=20\n</pre>\n" }, { "answer_id": 96889, "author": "jperras", "author_id": 5570, "author_profile": "https://Stackoverflow.com/users/5570", "pm_score": 0, "selected": false, "text": "<p>I have that exact line in in /etc/apt/sources.list.d/rpmforge.list .</p>\n\n<p>When I run check-update, I get:</p>\n\n<pre>\nLoading \"priorities\" plugin\nLoading \"fastestmirror\" plugin\nLoading mirror speeds from cached hostfile\n * epel: mirror.unl.edu\n * rpmforge: fr2.rpmfind.net\n * base: mirrors.portafixe.com\n * updates: mirrors.portafixe.com\n * addons: mirrors.portafixe.com\n * extras: mirrors.portafixe.com\n2202 packages excluded due to repository priority protections\n\nbzip2.i386 1.0.3-4.el5_2 updates \nbzip2-devel.i386 1.0.3-4.el5_2 updates \nbzip2-libs.i386 1.0.3-4.el5_2 updates \nlibxml2.i386 2.6.26-2.1.2.6 updates \nlibxml2-devel.i386 2.6.26-2.1.2.6 updates \nlibxml2-python.i386 2.6.26-2.1.2.6 updates \nperl.i386 4:5.8.8-15.el5_2.1 updates \nsos.noarch 1.7-9.2.el5_2.2 updates \ntzdata.noarch 2008e-1.el5 updates \n</pre>\n\n<p>I'm not overly concerned about the other outdated packages at the moment, but as you can see there is no Subversion update available.</p>\n" }, { "answer_id": 97105, "author": "Peter Stone", "author_id": 1806, "author_profile": "https://Stackoverflow.com/users/1806", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I'm not overly concerned about the other outdated packages at the moment, but as you can see there is no Subversion update available.</p>\n</blockquote>\n\n<p>Nor any packages from <code>rpmforge</code>. It's your priority settings. Try disabling yum-priorities (change <code>enabled=1</code> to <code>enabled=0</code> in <code>/etc/yum/pluginconf.d/priorities.conf</code>) - then it should work.</p>\n\n<p>So I guess the next question is why the priority is screwing it up.... I'm not sure on this, though.</p>\n\n<p>Edit: See <a href=\"https://stackoverflow.com/questions/96597/how-do-i-upgrade-to-subversion-15-on-centos-5#97106\">8jean's answer</a> for more about priorities.</p>\n" }, { "answer_id": 97106, "author": "8jean", "author_id": 10011, "author_profile": "https://Stackoverflow.com/users/10011", "pm_score": 7, "selected": true, "text": "<p>What you are trying to do is to replace a \"core\" package (one which is\ncontained in the CentOS repository) with a newer package from a \"3rd\nparty\" repository (RPMForge), which is what the priorities plugin is\ndesigned to prevent.</p>\n\n<p>The RPMForge repository contains both additional packages not found in\nCentOS, as well as newer versions of core packages. Unfortunately, <code>yum</code>\nis pretty stupid and will always update a package to the latest version\nit can find in <em>any</em> repository. So running \"<code>yum update</code>\" with RPMforge\nenabled will update half of your system with the latest (bleeding edge,\npossibly unstable and less well supported) packages from RPMForge.</p>\n\n<p>Therefore, the recommended way to use repos like RPMForge is to use them\nonly together with a yum plugin like \"priorites\", which prevents\npackages from \"high\" priority repos to overwrite those from \"low\"\npriority repos (the name of the \"priority\" parameter is very\nmisleading). This way you can savely install <em>additional</em> packages (that\nare not in core) from RPMForge, which is what most people want.</p>\n\n<p>Now to your original question ...</p>\n\n<p>If you <em>want</em> to replace a core package, things get a little tricky.\nBasically, you have two options:</p>\n\n<ol>\n<li><p>Uninstall the priority plugin, and <em>disable</em> the RPMForge repository by\ndefault (set <code>enabled = 0</code> in <code>/etc/yum.repos.d/rpmforge.repo</code>). You can\nthen selectively enable it on the command line:</p>\n\n<pre><code>yum --enablerepo=rpmforge install subversion\n</code></pre>\n\n<p>will install the latest subversion and dependencies from RPMForge.</p>\n\n<p>The problem with this approach is that if there is an update to the\nsubversion package in RPMForge, you will not see it when the repo is\ndisabled. To keep subversion up to date, you have to remember to run</p>\n\n<pre><code>yum --enablerepo=rpmforge update subversion\n</code></pre>\n\n<p>from time to time.</p></li>\n<li><p>The second possibility is to use the priorites plugin, but manually\n\"mask\" the core subversion package (add <code>exclude=subversion</code> to the\n<code>[base]</code> and <code>[update]</code> sections in <code>/etc/yum.repos.d/CentOS-Base.repo</code>).</p>\n\n<p>Now yum will behave as if there is no package named \"subversion\" in\nthe core repository and happily install the latest version from\nRPMForge. Plus, you will always get the latest subversion updates\nwhen running <code>yum update</code>.</p></li>\n</ol>\n" }, { "answer_id": 2156067, "author": "intoxicadocoder", "author_id": 261154, "author_profile": "https://Stackoverflow.com/users/261154", "pm_score": 2, "selected": false, "text": "<p>1.- if you are using yum-priorities disable this in the file <code>/etc/yum/pluginconf.d/priorities.conf</code></p>\n\n<p>2.- check the version of subversion </p>\n\n<pre><code> $ rpm -qa|grep subversion\n subversion-1.4.2-4.el5_3.1\n subversion-1.4.2-4.el5_3.1 \n</code></pre>\n\n<p>3.- search the last version of the subversion from rpmforge repository </p>\n\n<pre><code>$ yum --enablerepo=rpmforge check-update subversion\nsubversion.x86_64 1.6.6-0.1.el5.rf rpmforge\n</code></pre>\n\n<p>4.- now proced to upgrade subversion with rpmforge repository</p>\n\n<pre><code>$ yum shell\n&gt;erase mod_dav_svn-1.4.2-4.el5_3.1\n&gt;erase subversion-1.4.2-4.el5_3.1\n&gt;install mod_dav_svn-1.6.6-0.1.el5.rf\n&gt;install subversion-1.6.6-0.1.el5.rf.x86_64\n&gt;run\n</code></pre>\n\n<p>that's all it works for me im running centos 5.4 </p>\n" }, { "answer_id": 3367432, "author": "Matt H", "author_id": 406253, "author_profile": "https://Stackoverflow.com/users/406253", "pm_score": 0, "selected": false, "text": "<p>All you need to do is get this script. worked perfectly for me on CentOS 5.3</p>\n\n<p><a href=\"http://wandisco.com/subversion/os/downloads\" rel=\"nofollow noreferrer\">http://wandisco.com/subversion/os/downloads</a></p>\n\n<p>No, i don't work there or have any affiliation what-so-ever ... just found it and figured I would let you guys knows. </p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 8083629, "author": "Elaine Murphy", "author_id": 1040244, "author_profile": "https://Stackoverflow.com/users/1040244", "pm_score": 2, "selected": false, "text": "<p>Thanks Matt - we also have the only distro of SVN 1.7 on <a href=\"http://wandisco.com/subversion/downloads\" rel=\"nofollow\">SVN</a>.</p>\n\n<p>You may also want to try <a href=\"http://www.uberSVN.com\" rel=\"nofollow\">uberSVN</a>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5570/" ]
My development server (CentOS 5) is running Subversion 1.4.2, and I wish to upgrade it to 1.5. I have read in various blogs and documents scattered around the web that this may be done by using RPMForge. I have followed the instructions found on [CentOS Wiki](http://wiki.centos.org/AdditionalResources/Repositories/RPMForge?action=show&redirect=Repositories%2FRPMForge), including installing yum-priorities and setting my priorities as indicated (1 and 2 for core repo sources, and 20 for RPMForge). However, when I attempt to run: ``` $ yum info subversion ``` the version number given to me is still 1.4.2, with a status of Installed. My other option at this point is compiling from source, but I would like to find a package-managed solution for ease of future upgrades. Any thoughts?
What you are trying to do is to replace a "core" package (one which is contained in the CentOS repository) with a newer package from a "3rd party" repository (RPMForge), which is what the priorities plugin is designed to prevent. The RPMForge repository contains both additional packages not found in CentOS, as well as newer versions of core packages. Unfortunately, `yum` is pretty stupid and will always update a package to the latest version it can find in *any* repository. So running "`yum update`" with RPMforge enabled will update half of your system with the latest (bleeding edge, possibly unstable and less well supported) packages from RPMForge. Therefore, the recommended way to use repos like RPMForge is to use them only together with a yum plugin like "priorites", which prevents packages from "high" priority repos to overwrite those from "low" priority repos (the name of the "priority" parameter is very misleading). This way you can savely install *additional* packages (that are not in core) from RPMForge, which is what most people want. Now to your original question ... If you *want* to replace a core package, things get a little tricky. Basically, you have two options: 1. Uninstall the priority plugin, and *disable* the RPMForge repository by default (set `enabled = 0` in `/etc/yum.repos.d/rpmforge.repo`). You can then selectively enable it on the command line: ``` yum --enablerepo=rpmforge install subversion ``` will install the latest subversion and dependencies from RPMForge. The problem with this approach is that if there is an update to the subversion package in RPMForge, you will not see it when the repo is disabled. To keep subversion up to date, you have to remember to run ``` yum --enablerepo=rpmforge update subversion ``` from time to time. 2. The second possibility is to use the priorites plugin, but manually "mask" the core subversion package (add `exclude=subversion` to the `[base]` and `[update]` sections in `/etc/yum.repos.d/CentOS-Base.repo`). Now yum will behave as if there is no package named "subversion" in the core repository and happily install the latest version from RPMForge. Plus, you will always get the latest subversion updates when running `yum update`.
96,615
<p>So if I'm using branches that are remote (tracked) branches, and I want to get the lastest, I'm still unclear if I should be doing <code>git pull</code> or <code>git rebase</code>. I thought I had read that doing <code>git rebase</code> when working on a branch with other users, it can screw them up when they pull or rebase. Is that true? Should we all be using <code>git pull</code>?</p>
[ { "answer_id": 96666, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p><code>git pull</code> does a merge if you've got commits that aren't in the remote branch. <code>git rebase</code> rewrites any existing commits you have to be relative to the tip of the remote branch. They're similar in that they can both cause conflicts, but I think using <code>git rebase</code> if you can allows for smoother collaboration. During the rebase operation you can refine your commits so they look like they were newly applied to the latest revision of the remote branch. A merge is perhaps more appropriate for longer development cycles on a branch that have more history.</p>\n\n<p>Like most other things in git, there is a lot of overlapping functionality to accommodate different styles of working.</p>\n" }, { "answer_id": 96684, "author": "Lee H", "author_id": 18201, "author_profile": "https://Stackoverflow.com/users/18201", "pm_score": 0, "selected": false, "text": "<p>If you want to pull source without affecting remote branches and without any changes in your local copy, it's best to use git pull.</p>\n\n<p>I believe if you have a working branch that you have made changes to, use git rebase to change the base of that branch to be latest remote master, you will keep all of your branch changes, however the branch will now be branching from the master location, rather than where it was previously branched from.</p>\n" }, { "answer_id": 96924, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 7, "selected": true, "text": "<p>Git pull is a combination of 2 commands</p>\n\n<ul>\n<li>git fetch (syncs your local repo with the newest stuff on the remote)</li>\n<li>git merge (merges the changes from the distant branch, if any, into your local tracking branch)</li>\n</ul>\n\n<p>git rebase is only a rough equivalent to git merge. It doesn't fetch anything remotely. In fact it doesn't do a proper merge either, it replays the commits of the branch you're standing on after the new commits from a second branch. </p>\n\n<p>Its purpose is mainly to let you have a cleaner history. It doesn't take many merges by many people before the past history in gitk gets terribly spaghetti-like.</p>\n\n<p>The best graphical explanation can be seen in the first 2 graphics <a href=\"http://www.kernel.org/pub/software/scm/git/docs/v1.5.4.3/git-rebase.html\" rel=\"noreferrer\">here</a>. But let me explain here with an example.</p>\n\n<p>I have 2 branches: master and mybranch. When standing on mybranch I can run</p>\n\n<pre><code>git rebase master\n</code></pre>\n\n<p>and I'll get anything new in master inserted before my most recent commits in mybranch. This is perfect, because if I now merge or rebase the stuff from mybranch in master, my new commits are added linearly right after the most recent commits. </p>\n\n<p>The problem you refer to happens if I rebase in the \"wrong\" direction. If I just got the most recent master (with new changes) and from master I rebase like this (before syncing my branch):</p>\n\n<pre><code>git rebase mybranch\n</code></pre>\n\n<p>Now what I just did is that I inserted my new changes somewhere in master's past. The main line of commits has changed. And due to the way git works with commit ids, all the commits (from master) that were just replayed over my new changes have new ids.</p>\n\n<p>Well, it's a bit hard to explain just in words... Hope this makes a bit of sense :-)</p>\n\n<p>Anyway, my own workflow is this:</p>\n\n<ul>\n<li>'git pull' new changes from remote</li>\n<li>switch to mybranch</li>\n<li>'git rebase master' to bring master's new changes in my commit history</li>\n<li>switch back to master</li>\n<li>'git merge mybranch', which only fast-forwards when everything in master is also in mybranch (thus avoiding the commit reordering problem on a public branch)</li>\n<li>'git push'</li>\n</ul>\n\n<p>One last word. I strongly recommend using rebase when the differences are trivial (e.g. people working on different files or at least different lines). It has the gotcha I tried to explain just up there, but it makes for a much cleaner history.</p>\n\n<p>As soon as there may be significant conflicts (e.g. a coworker has renamed something in a bunch of files), I strongly recommend merge. In this case, you'll be asked to resolve the conflict and then commit the resolution. On the plus side, a merge is much easier to resolve when there are conflicts. The down side is that your history may become hard to follow if a lot of people do merges all the time :-)</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 98077, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 3, "selected": false, "text": "<p>Git <code>rebase</code> is a re-write of history. You should never do this on branches that are \"public\" (i.e., branches that you share with others). If someone clones your branch and then you rebase that branch -- then they can no longer pull/merge changes from your branch -- they'll have to throw their old one away and re-pull.</p>\n\n<p>This article on <a href=\"http://www.golden-gryphon.com/software/misc/packaging.html\" rel=\"noreferrer\">packaging software with git</a> is a very worthwhile read. It's more about managing software distributions but it's quite technical and talks about how branches can be used/managed/shared. They talk about when to rebase and when to pull and what the various consequences of each are.</p>\n\n<p>In short, they both have their place but you need to really grok the difference.</p>\n" }, { "answer_id": 103906, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "<p>Check out the excellent Gitcasts on <a href=\"http://www.techscreencast.com/tool/versioncontrol/git-branching-and-merging/794\" rel=\"nofollow noreferrer\">Branching and merging</a> as well as <a href=\"http://www.techscreencast.com/tool/versioncontrol/git-rebasing/795\" rel=\"nofollow noreferrer\">rebasing</a>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14873/" ]
So if I'm using branches that are remote (tracked) branches, and I want to get the lastest, I'm still unclear if I should be doing `git pull` or `git rebase`. I thought I had read that doing `git rebase` when working on a branch with other users, it can screw them up when they pull or rebase. Is that true? Should we all be using `git pull`?
Git pull is a combination of 2 commands * git fetch (syncs your local repo with the newest stuff on the remote) * git merge (merges the changes from the distant branch, if any, into your local tracking branch) git rebase is only a rough equivalent to git merge. It doesn't fetch anything remotely. In fact it doesn't do a proper merge either, it replays the commits of the branch you're standing on after the new commits from a second branch. Its purpose is mainly to let you have a cleaner history. It doesn't take many merges by many people before the past history in gitk gets terribly spaghetti-like. The best graphical explanation can be seen in the first 2 graphics [here](http://www.kernel.org/pub/software/scm/git/docs/v1.5.4.3/git-rebase.html). But let me explain here with an example. I have 2 branches: master and mybranch. When standing on mybranch I can run ``` git rebase master ``` and I'll get anything new in master inserted before my most recent commits in mybranch. This is perfect, because if I now merge or rebase the stuff from mybranch in master, my new commits are added linearly right after the most recent commits. The problem you refer to happens if I rebase in the "wrong" direction. If I just got the most recent master (with new changes) and from master I rebase like this (before syncing my branch): ``` git rebase mybranch ``` Now what I just did is that I inserted my new changes somewhere in master's past. The main line of commits has changed. And due to the way git works with commit ids, all the commits (from master) that were just replayed over my new changes have new ids. Well, it's a bit hard to explain just in words... Hope this makes a bit of sense :-) Anyway, my own workflow is this: * 'git pull' new changes from remote * switch to mybranch * 'git rebase master' to bring master's new changes in my commit history * switch back to master * 'git merge mybranch', which only fast-forwards when everything in master is also in mybranch (thus avoiding the commit reordering problem on a public branch) * 'git push' One last word. I strongly recommend using rebase when the differences are trivial (e.g. people working on different files or at least different lines). It has the gotcha I tried to explain just up there, but it makes for a much cleaner history. As soon as there may be significant conflicts (e.g. a coworker has renamed something in a bunch of files), I strongly recommend merge. In this case, you'll be asked to resolve the conflict and then commit the resolution. On the plus side, a merge is much easier to resolve when there are conflicts. The down side is that your history may become hard to follow if a lot of people do merges all the time :-) Good luck!
96,618
<p>Let's say I have data structures that're something like this:</p> <pre><code>Public Class AttendenceRecord Public CourseDate As Date Public StudentsInAttendence As Integer End Class Public Class Course Public Name As String Public CourseID As String Public Attendance As List(Of AttendenceRecord) End Class </code></pre> <p>And I want a table that looks something like this:</p> <pre> | Course Name | Course ID | [Attendence(0).CourseDate] | [Attendence(1).CourseDate]| ... | Intro to CS | CS-1000 | 23 | 24 | ... | Data Struct | CS-2103 | 15 | 14 | ... </pre> <p>How would I, in the general case, get everything to the right of Course ID to be horizontally scrollable, while holding Course Name and Course ID in place? Ideally using a table, listview, or datagrid inside ASP.NET and/or WinForms.</p>
[ { "answer_id": 96642, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "<p>In pure .Net I don't know of anything. There are <a href=\"http://www.imaputz.com/cssStuff/bigFourVersion.html\" rel=\"nofollow noreferrer\">CSS Solutions</a> for a fixed header. But a fixed left column, in my experience, requires some javascript finangling.</p>\n\n<p>Took me a minute to find the old example. Host has since gone down. <a href=\"http://web.archive.org/web/20080215013647/http://www.litotes.demon.co.uk/example_scripts/tableScroll.html\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20080215013647/http://www.litotes.demon.co.uk/example_scripts/tableScroll.html</a></p>\n\n<p>This is the mechanism I used to get it to work: Take a normal table, and separate it out into 4 other tables. Get the column widths and row heights to match up using business constraints, and then link the onscroll event to scroll the other tables.</p>\n" }, { "answer_id": 96804, "author": "Brian Sullivan", "author_id": 767, "author_profile": "https://Stackoverflow.com/users/767", "pm_score": 0, "selected": false, "text": "<p>Here's an example using just HTML and CSS to achieve what I think you're looking for:</p>\n\n<p><a href=\"http://www.shrutigupta.com/index.php/2005/12/12/how-to-create-table-with-first-column-frozen/\" rel=\"nofollow noreferrer\">http://www.shrutigupta.com/index.php/2005/12/12/how-to-create-table-with-first-column-frozen/</a></p>\n" }, { "answer_id": 188292, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 2, "selected": true, "text": "<p>You can get this functionality from the System.Windows.Forms.DataGridView control. When you create columns you can set them to be <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.frozen.aspx\" rel=\"nofollow noreferrer\">frozen</a> which will then only scroll those columns to the right of the frozen column(s).</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18224/" ]
Let's say I have data structures that're something like this: ``` Public Class AttendenceRecord Public CourseDate As Date Public StudentsInAttendence As Integer End Class Public Class Course Public Name As String Public CourseID As String Public Attendance As List(Of AttendenceRecord) End Class ``` And I want a table that looks something like this: ``` | Course Name | Course ID | [Attendence(0).CourseDate] | [Attendence(1).CourseDate]| ... | Intro to CS | CS-1000 | 23 | 24 | ... | Data Struct | CS-2103 | 15 | 14 | ... ``` How would I, in the general case, get everything to the right of Course ID to be horizontally scrollable, while holding Course Name and Course ID in place? Ideally using a table, listview, or datagrid inside ASP.NET and/or WinForms.
You can get this functionality from the System.Windows.Forms.DataGridView control. When you create columns you can set them to be [frozen](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.frozen.aspx) which will then only scroll those columns to the right of the frozen column(s).
96,624
<p>I have an assembly which should <strong>not</strong> be used by any application other than the designated executable. Please give me some instructions to do so.</p>
[ { "answer_id": 96647, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 1, "selected": false, "text": "<p>You might be able to set this in the Code Access Security policies on the assembly.</p>\n" }, { "answer_id": 96650, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "<p>You should be able to make everything internally scoped, and then use the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\">InternalsVisibleTo</a> Attribute to grant only that one assembly access to the internal methods.</p>\n" }, { "answer_id": 96654, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 4, "selected": false, "text": "<p>In .Net 2.0 or better, make everything internal, and then use Friend Assemblies</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/0tke9fxk.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/0tke9fxk.aspx</a></p>\n\n<p>This will not stop reflection. I want to incorporate some of the information from below. If you absolutely need to stop anyone from calling, probably the best solution is:</p>\n\n<ol>\n<li>ILMerge the .exe and .dll</li>\n<li>obfuscate the final .exe</li>\n</ol>\n\n<p>You could also check up the call stack and get the assembly for each caller and make sure that they are all signed with the same key as the assembly.</p>\n" }, { "answer_id": 96660, "author": "Dr Zimmerman", "author_id": 4605, "author_profile": "https://Stackoverflow.com/users/4605", "pm_score": 0, "selected": false, "text": "<p>If the assembly was a web service for example, you could ensure the designated executable passes a secret value in the SOAP message.</p>\n" }, { "answer_id": 96681, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 1, "selected": false, "text": "<p>You can use obfuscation. </p>\n\n<p>That will turn:</p>\n\n<pre><code>int MySecretPrimeDetectionAlgorithm(int lastPrimeNumber);\n</code></pre>\n\n<p>Into something unreadable like:</p>\n\n<pre><code>int Asdfasdfasdfasdfasdfasdfasdf(int qwerqwerqwerqwerqwerqwer);\n</code></pre>\n\n<p>Others will still be able to use your assembly, but it will be difficult to make any sensible.</p>\n" }, { "answer_id": 96698, "author": "Chris Smith", "author_id": 322, "author_profile": "https://Stackoverflow.com/users/322", "pm_score": 3, "selected": false, "text": "<p>100% completely impossible without jumping through some hoops.</p>\n\n<p>One of the perks of using the .NET is the ability to use reflection, that is load up an assembly and inspect it, dynamically call methods, etc. This is what makes interop between VB.NET and F# possible.</p>\n\n<p>However, since your code is in a managed assembly that means that <strong>anybody can add a reference to your code and invoke its public methods or load it using reflection and call private methods</strong>. Even if you 'obfuscate' your code, people will still be able to use reflection and invoke your code. However, since all the names will be masked doing anything is prohibitavely difficult.</p>\n\n<p>If you must ship your .NET code in a fashion that prevents other people from executing it, you might be able to NGEN your binary (compile it to x86) and ship those binaries. </p>\n\n<p>I don't know the specifics of your situation, but obfuscation should be good enough.</p>\n" }, { "answer_id": 96710, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "<p>The Code Access Security attribute that @<a href=\"https://stackoverflow.com/questions/96624/how-to-prevent-others-from-using-my-net-assembly#96647\">Charles Graham</a> mentions is <a href=\"http://msdn.microsoft.com/en-us/library/system.security.permissions.strongnameidentitypermissionattribute.aspx\" rel=\"nofollow noreferrer\">StrongNameIdentityPermissionAttribute</a></p>\n" }, { "answer_id": 96769, "author": "spmason", "author_id": 5793, "author_profile": "https://Stackoverflow.com/users/5793", "pm_score": 2, "selected": false, "text": "<p>As some people have mentioned, use the InternalsVisibleTo attribute and mark everything as internal. This of course won't guard against reflection.</p>\n\n<p>One thing that hasnt been mentioned is to <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=22914587-b4ad-4eae-87cf-b14ae6a939b0&amp;displaylang=en\" rel=\"nofollow noreferrer\">ilmerge</a> your assemblies into your main .exe/.dll/whatever, this will up the barrier for entry a bit (people won't be able to see your assemby sitting on its own asking to be referenced), but wont stop the reflection route..</p>\n\n<p>UPDATE: Also, IIRC, ilmerge has a feature where it can automaticaly internalise the merged assemblies, which would mean you don't need to use InternalsVisibleTo at all</p>\n" }, { "answer_id": 96796, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 5, "selected": true, "text": "<p>You can sign the assembly and the executable with the same key and then put a check in the constructor of the classes you want to protect:</p>\n\n<pre><code>public class NotForAnyoneElse {\n public NotForAnyoneElse() {\n if (typeof(NotForAnyoneElse).Assembly.GetName().GetPublicKeyToken() != Assembly.GetEntryAssembly().GetName().GetPublicKeyToken()) {\n throw new SomeException(...);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 96863, "author": "Mark Smith", "author_id": 16874, "author_profile": "https://Stackoverflow.com/users/16874", "pm_score": 2, "selected": false, "text": "<p>You could also look at using the <a href=\"http://madebits.com/netz/\" rel=\"nofollow noreferrer\">Netz</a> executable packer and compressor. </p>\n\n<p>This takes your assemblies and your .exe file and packs them into a single executable so they're not visible to the outside world without a bit of digging around. </p>\n\n<p>My guess is that this is sufficient to prevent access for most .net programmers. </p>\n\n<p>A big benefit of the .netz approach is that it does not require you to change your code. Another benefit is that it really simplifies your installation process.</p>\n" }, { "answer_id": 97118, "author": "Jeffrey LeCours", "author_id": 18051, "author_profile": "https://Stackoverflow.com/users/18051", "pm_score": 1, "selected": false, "text": "<p>It sounds like you are looking for a protection or obfuscation tool. While there isn't a silver bullet, the protection tool I recommend is <a href=\"http://www.smartassembly.com/\" rel=\"nofollow noreferrer\">smartassembly</a>. Some alternatives are <a href=\"http://www.remotesoft.com/salamander/obfuscator.html\" rel=\"nofollow noreferrer\">Salamander Obfuscator</a>, <a href=\"http://www.preemptive.com/dotfuscator.html\" rel=\"nofollow noreferrer\">dotfuscator</a>, and <a href=\"http://www.xenocode.com/\" rel=\"nofollow noreferrer\">Xenocode</a>.</p>\n\n<p>Unfortunately, if you give your bytes to someone to be read... if they have enough time and effort, they can find way to load and call your code. To preemptively answer a comment I see you ask frequently: Salamander will prevent your code from being loaded directly into the Reflector tool, but I've had better (ie: more reliable) experiences with smartassembly.</p>\n\n<p>Hope this helps. :)</p>\n" }, { "answer_id": 97241, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if this is an available avenue for you, but perhaps you can host the assembly using WCF or ASP.NET web services and use some sort of authentication scheme (LDAP, public/rpivate key pairs, etc.) to ensure only allowed clients connect. This would keep your assembly physically out of anyone else's hands and you can control who connects to it. Just a thought.</p>\n" }, { "answer_id": 97684, "author": "MetaGuru", "author_id": 18309, "author_profile": "https://Stackoverflow.com/users/18309", "pm_score": -1, "selected": false, "text": "<p>Just require a pass code to be sent in using a function call and if it hasn't been authorized then nothing works, like .setAuthorizeCode('123456') then in every single place that can be used have it check if authorizeCode != 123456 then throw error or just exit out... It doesn't sound like a good answer for re-usability but that is exactly the point.</p>\n\n<p>The only time it could be used is by you and when you hard code the authorize code into the program.</p>\n\n<p>Just a thought, could be what you are looking for or could inspire you to something better.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18198/" ]
I have an assembly which should **not** be used by any application other than the designated executable. Please give me some instructions to do so.
You can sign the assembly and the executable with the same key and then put a check in the constructor of the classes you want to protect: ``` public class NotForAnyoneElse { public NotForAnyoneElse() { if (typeof(NotForAnyoneElse).Assembly.GetName().GetPublicKeyToken() != Assembly.GetEntryAssembly().GetName().GetPublicKeyToken()) { throw new SomeException(...); } } } ```
96,661
<p>I have a query that I would like to filter in different ways at different times. The way I have done this right now by placing parameters in the criteria field of the relevant query fields, however there are many cases in which I do not want to filter on a given field but only on the other fields. Is there any way in which a wildcard of some sort can be passed to the criteria parameter so that I can bypass the filtering for that particular call of the query?</p>
[ { "answer_id": 96782, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 0, "selected": false, "text": "<p>I don't think you can. How are you running the query? </p>\n\n<p>I'd say if you need a query that has that many open variables, put it in a vba module or class, and call it, letting it build the string every time.</p>\n" }, { "answer_id": 96866, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 0, "selected": false, "text": "<p>I'm not sure this helps, because I suspect you want to do this with a saved query rather than in VBA; however, the easiest thing you can do is build up a query line by line in VBA, and then creating a recordset from it.</p>\n\n<p>A quite hackish way would be to re-write the saved query on the fly and then access that; however, if you have multiple people using the same DB you might run into conflicts, and you'll confuse the next developer down the line.</p>\n\n<p>You could also programatically pass default value to the query (as discussed in you r previous question)</p>\n" }, { "answer_id": 96950, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "<p>Well, you can return non-null values by passing * as the parameter for fields you don't wish to use in the current filter. In Access 2003 (and possibly earlier and later versions), if you are using <code>like [paramName]</code> as your criterion for a numeric, Text, Date, or Boolean field, an asterisk will display all records (that match the other criteria you specify). If you want to return null values as well, then you can use <code>like [paramName] or Is Null</code> as the criterion so that it returns all records. (This works best if you are building the query in code. If you are using an existing query, and you don't want to return null values when you do have a value for filtering, this won't work.)</p>\n\n<p>If you're filtering a Memo field, you'll have to try another approach.</p>\n" }, { "answer_id": 96978, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 4, "selected": false, "text": "<p>If you construct your query like so:</p>\n\n<pre><code>PARAMETERS ParamA Text ( 255 );\nSELECT t.id, t.topic_id\nFROM SomeTable t\nWHERE t.id Like IIf(IsNull([ParamA]),\"*\",[ParamA])\n</code></pre>\n\n<p>All records will be selected if the parameter is not filled in.</p>\n" }, { "answer_id": 100078, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 1, "selected": false, "text": "<p>Back to my previous exampe in your previous question. Your parameterized query is a string looking like that:</p>\n\n<pre><code>qr = \"Select Tbl_Country.* From Tbl_Country WHERE id_Country = [fid_country]\"\n</code></pre>\n\n<p>depending on the nature of fid_Country (number, text, guid, date, etc), you'll have to replace it with a joker value and specific delimitation characters:</p>\n\n<pre><code>qr = replace(qr,\"[fid_country]\",\"\"\"*\"\"\")\n</code></pre>\n\n<p>In order to fully allow wild cards, your original query could also be:</p>\n\n<pre><code>qr = \"Select Tbl_Country.* From Tbl_Country _\n WHERE id_Country LIKE [fid_country]\"\n</code></pre>\n\n<p>You can then get wild card values for fid_Country such as</p>\n\n<pre><code>qr = replace(qr,\"[fid_country]\",\"G*\")\n</code></pre>\n\n<p>Once you're done with that, you can use the string to open a recordset</p>\n\n<pre><code>set rs = currentDb.openRecordset(qr)\n</code></pre>\n" }, { "answer_id": 148614, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "<p>Note the <code>*</code> wildcard with the <code>LIKE</code> keyword will only have the desired effect in ANSI-89 Query Mode.</p>\n\n<p>Many people mistakenly assume the wildcard character in Access/Jet is always *. Not so. Jet has two wildcards: % in ANSI-92 Query Mode and * in ANSI-89 Query Mode. </p>\n\n<p>ADO is always ANSI-92 and DAO is always ANSI-89 but the Access interface can be either. </p>\n\n<p>When using the LIKE keyword in a database object (i.e. something that will be persisted in the mdb file), you should to think to yourself: what would happen if someone used this database using a Query Mode other than the one I usually use myself? Say you wanted to restrict a text field to numeric characters only and you'd written your Validation Rule like this:</p>\n\n<pre><code>NOT LIKE \"*[!0-9]*\"\n</code></pre>\n\n<p>If someone unwittingly (or otherwise) connected to your .mdb via ADO then the validation rule above would allow them to add data with non-numeric characters and your data integrity would be shot. Not good.</p>\n\n<p>Better IMO to always code for both ANSI Query Modes. Perhaps this is best achieved by explicitly coding for both Modes e.g. </p>\n\n<pre><code>NOT LIKE \"*[!0-9]*\" AND NOT LIKE \"%[!0-9]%\"\n</code></pre>\n\n<p>But with more involved Jet SQL DML/DDL, this can become very hard to achieve concisely. That is why I recommend using the ALIKE keyword, which uses the ANSI-92 Query Mode wildcard character regardless of Query Mode e.g. </p>\n\n<pre><code>NOT ALIKE \"%[!0-9]%\"\n</code></pre>\n\n<p>Note ALIKE is undocumented (and I assume this is why my original post got marked down). I've tested this in Jet 3.51 (Access97), Jet 4.0 (Access2000 to 2003) and ACE (Access2007) and it works fine. I've previously posted this in the newsgroups and had the approval of Access MVPs. Normally I would steer clear of undocumented features myself but make an exception in this case because Jet has been deprecated for nearly a decade and the Access team who keep it alive don't seem interested in making deep changes to the engines (or bug fixes!), which has the effect of making the Jet engine a very stable product. </p>\n\n<p>For more details on Jet's ANSI Query modes, see <a href=\"http://web.archive.org/web/20140614093902/http://office.microsoft.com/en-gb/access-help/about-ansi-sql-query-mode-mdb-HP003070483.aspx\" rel=\"nofollow noreferrer\">About ANSI SQL query mode</a>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I have a query that I would like to filter in different ways at different times. The way I have done this right now by placing parameters in the criteria field of the relevant query fields, however there are many cases in which I do not want to filter on a given field but only on the other fields. Is there any way in which a wildcard of some sort can be passed to the criteria parameter so that I can bypass the filtering for that particular call of the query?
If you construct your query like so: ``` PARAMETERS ParamA Text ( 255 ); SELECT t.id, t.topic_id FROM SomeTable t WHERE t.id Like IIf(IsNull([ParamA]),"*",[ParamA]) ``` All records will be selected if the parameter is not filled in.
96,671
<p>I have a flash app (SWF) running Flash 8 embedded in an HTML page. How do I get flash to reload the parent HTML page it is embedded in? I've tried using ExternalInterface to call a JavaScript function to reload the page but that doesn't seem to work. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 96717, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 2, "selected": false, "text": "<p>Try something like this:</p>\n\n<p><code>getURL(\"javascript:location.reload(true)\");</code></p>\n" }, { "answer_id": 211359, "author": "Yaba", "author_id": 7524, "author_profile": "https://Stackoverflow.com/users/7524", "pm_score": 4, "selected": false, "text": "<p>Check the <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html\" rel=\"noreferrer\">ExternalInterface</a> in Action Script. Using this you can call any JavaScript function in your code:</p>\n\n<pre><code> if (ExternalInterface.available)\n {\n var result = ExternalInterface.call(\"reload\");\n }\n</code></pre>\n\n<p>In the Embedding HTML code enter a JavaScript function:</p>\n\n<pre><code> function reload()\n {\n document.location.reload(true);\n return true;\n }\n</code></pre>\n\n<p>This has the advantage that you can also check, if the function call succeeded and act accordingly. getUrl along with a call to JavaScript should not be used today anymore. It's an old hack.</p>\n" }, { "answer_id": 2595348, "author": "stach", "author_id": 64653, "author_profile": "https://Stackoverflow.com/users/64653", "pm_score": 1, "selected": false, "text": "<p>In Flash 10 you can do:</p>\n\n<pre><code>navigateToURL(new URLRequest(\"path_to_page\"), \"_self\");\n</code></pre>\n" }, { "answer_id": 3563569, "author": "Eliram", "author_id": 18790, "author_profile": "https://Stackoverflow.com/users/18790", "pm_score": 2, "selected": false, "text": "<p>Quick and dirty: This will work in most cases (without modifying the HTML page at all):</p>\n\n<pre><code>import flash.external.ExternalInterface;\n\nExternalInterface.call(\"history.go\", 0);\n</code></pre>\n" }, { "answer_id": 15966881, "author": "xLite", "author_id": 745888, "author_profile": "https://Stackoverflow.com/users/745888", "pm_score": 2, "selected": false, "text": "<p>Simple one line solution.</p>\n\n<pre><code>ExternalInterface.call(\"document.location.reload\", true);\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a flash app (SWF) running Flash 8 embedded in an HTML page. How do I get flash to reload the parent HTML page it is embedded in? I've tried using ExternalInterface to call a JavaScript function to reload the page but that doesn't seem to work. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Check the [ExternalInterface](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html) in Action Script. Using this you can call any JavaScript function in your code: ``` if (ExternalInterface.available) { var result = ExternalInterface.call("reload"); } ``` In the Embedding HTML code enter a JavaScript function: ``` function reload() { document.location.reload(true); return true; } ``` This has the advantage that you can also check, if the function call succeeded and act accordingly. getUrl along with a call to JavaScript should not be used today anymore. It's an old hack.
96,718
<p>How do you organize your Extension Methods? Say if I had extensions for the object class and string class I'm tempted to separate these extension methods into classes IE:</p> <pre><code>public class ObjectExtensions { ... } public class StringExtensions { ... } </code></pre> <p>am I making this too complicated or does this make sense?</p>
[ { "answer_id": 96771, "author": "Geir-Tore Lindsve", "author_id": 4582, "author_profile": "https://Stackoverflow.com/users/4582", "pm_score": 2, "selected": false, "text": "<p>There are two ways that I organize the extension methods which I use,</p>\n\n<p>1) If the extension is specific to the project I am working on, then I keep it in the same project/assembly, but in its own namespace.</p>\n\n<p>2) If the extension is of a kind so that I may or is using it in other projects too, then I separate them in a common assembly for extensions.</p>\n\n<p>The most important thing to keep in mind is, what is the scope which I will be using these in? Organizing them isn't hard if I just keep this in mind.</p>\n" }, { "answer_id": 96788, "author": "Travis Illig", "author_id": 8116, "author_profile": "https://Stackoverflow.com/users/8116", "pm_score": 5, "selected": true, "text": "<p>I organize extension methods using a combination of namespace and class name, and it's similar to the way you describe in the question.</p>\n\n<p>Generally I have some sort of \"primary assembly\" in my solution that provides the majority of the shared functionality (like extension methods). We'll call this assembly \"Framework\" for the sake of discussion.</p>\n\n<p>Within the Framework assembly, I try to mimic the namespaces of the things for which I have extension methods. For example, if I'm extending System.Web.HttpApplication, I'd have a \"Framework.Web\" namespace. Classes like \"String\" and \"Object,\" being in the \"System\" namespace, translate to the root \"Framework\" namespace in that assembly.</p>\n\n<p>Finally, naming goes along the lines you've specified in the question - the type name with \"Extensions\" as a suffix. This yields a class hierarchy like this:</p>\n\n<ul>\n<li>Framework (namespace)\n\n<ul>\n<li>Framework.ObjectExtensions (class)</li>\n<li>Framework.StringExtensions (class)</li>\n<li>Framework.Web (namespace)\n\n<ul>\n<li>Framework.Web.HttpApplicationExtensions (class)</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>The benefit is that, from a maintenance perspective, it's really easy later to go find the extension methods for a given type.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980/" ]
How do you organize your Extension Methods? Say if I had extensions for the object class and string class I'm tempted to separate these extension methods into classes IE: ``` public class ObjectExtensions { ... } public class StringExtensions { ... } ``` am I making this too complicated or does this make sense?
I organize extension methods using a combination of namespace and class name, and it's similar to the way you describe in the question. Generally I have some sort of "primary assembly" in my solution that provides the majority of the shared functionality (like extension methods). We'll call this assembly "Framework" for the sake of discussion. Within the Framework assembly, I try to mimic the namespaces of the things for which I have extension methods. For example, if I'm extending System.Web.HttpApplication, I'd have a "Framework.Web" namespace. Classes like "String" and "Object," being in the "System" namespace, translate to the root "Framework" namespace in that assembly. Finally, naming goes along the lines you've specified in the question - the type name with "Extensions" as a suffix. This yields a class hierarchy like this: * Framework (namespace) + Framework.ObjectExtensions (class) + Framework.StringExtensions (class) + Framework.Web (namespace) - Framework.Web.HttpApplicationExtensions (class) The benefit is that, from a maintenance perspective, it's really easy later to go find the extension methods for a given type.
96,732
<p>I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible.</p> <p>This with is C# and .NET 3.5.</p> <p>The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL.</p> <p>The way I originally planned to do this is by writing code to put the third party DLL in the location specified by <code>System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()</code> minus the last <code>/nameOfMyAssembly.dll</code>. I can successfully save the third party <code>.DLL</code> in this location (which ends up being </p> <blockquote> <p>C:\Documents and Settings\myUserName\Local Settings\Application Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb_fe18c901 </p> </blockquote> <p>), but when I get to the part of my code requiring this DLL, it can't find it.</p> <p>Does anybody have any idea as to what I need to be doing differently?</p>
[ { "answer_id": 96791, "author": "Fostah", "author_id": 16524, "author_profile": "https://Stackoverflow.com/users/16524", "pm_score": 4, "selected": false, "text": "<p>There's a tool called IlMerge that can accomplish this: <a href=\"http://research.microsoft.com/~mbarnett/ILMerge.aspx\" rel=\"noreferrer\">http://research.microsoft.com/~mbarnett/ILMerge.aspx</a></p>\n\n<p>Then you can just make a build event similar to the following.</p>\n\n<p>Set Path=\"C:\\Program Files\\Microsoft\\ILMerge\"</p>\n\n<p>ilmerge /out:$(ProjectDir)\\Deploy\\LevelEditor.exe $(ProjectDir)\\bin\\Release\\release.exe $(ProjectDir)\\bin\\Release\\InteractLib.dll $(ProjectDir)\\bin\\Release\\SpriteLib.dll $(ProjectDir)\\bin\\Release\\LevelLibrary.dll</p>\n" }, { "answer_id": 96868, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "<p>Instead of writing the assembly to disk you can try to do Assembly.Load(byte[] rawAssembly) where you create rawAssembly from the embedded resource.</p>\n" }, { "answer_id": 96932, "author": "Mark Smith", "author_id": 16874, "author_profile": "https://Stackoverflow.com/users/16874", "pm_score": 3, "selected": false, "text": "<p>You can achieve this remarkably easily using <a href=\"http://madebits.com/netz/\" rel=\"noreferrer\">Netz</a>, a .net NET Executables Compressor &amp; Packer.</p>\n" }, { "answer_id": 97080, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 3, "selected": false, "text": "<p>I've had success doing what you are describing, but because the third-party DLL is also a .NET assembly, I never write it out to disk, I just load it from memory.</p>\n\n<p>I get the embedded resource assembly as a byte array like so:</p>\n\n<pre><code> Assembly resAssembly = Assembly.LoadFile(assemblyPathName);\n\n byte[] assemblyData;\n using (Stream stream = resAssembly.GetManifestResourceStream(resourceName))\n {\n assemblyData = ReadBytesFromStream(stream);\n stream.Close();\n }\n</code></pre>\n\n<p>Then I load the data with Assembly.Load().</p>\n\n<p>Finally, I add a handler to AppDomain.CurrentDomain.AssemblyResolve to return my loaded assembly when the type loader looks it.</p>\n\n<p>See the <a href=\"http://www.grimes.demon.co.uk/workshops/fusWSEight.htm\" rel=\"noreferrer\">.NET Fusion Workshop</a> for additional details.</p>\n" }, { "answer_id": 97290, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 6, "selected": true, "text": "<p>Once you've embedded the third-party assembly as a resource, add code to subscribe to the <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx\" rel=\"noreferrer\"><code>AppDomain.AssemblyResolve</code></a> event of the current domain during application start-up. This event fires whenever the Fusion sub-system of the CLR fails to locate an assembly according to the probing (policies) in effect. In the event handler for <code>AppDomain.AssemblyResolve</code>, load the resource using <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx\" rel=\"noreferrer\"><code>Assembly.GetManifestResourceStream</code></a> and feed its content as a byte array into the corresponding <a href=\"http://msdn.microsoft.com/en-us/library/h538bck7.aspx\" rel=\"noreferrer\"><code>Assembly.Load</code></a> overload. Below is how one such implementation could look like in C#:</p>\n\n<pre><code>AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =&gt;\n{\n var resName = args.Name + \".dll\"; \n var thisAssembly = Assembly.GetExecutingAssembly(); \n using (var input = thisAssembly.GetManifestResourceStream(resName))\n {\n return input != null \n ? Assembly.Load(StreamToBytes(input))\n : null;\n }\n};\n</code></pre>\n\n<p>where <code>StreamToBytes</code> could be defined as:</p>\n\n<pre><code>static byte[] StreamToBytes(Stream input) \n{\n var capacity = input.CanSeek ? (int) input.Length : 0;\n using (var output = new MemoryStream(capacity))\n {\n int readLength;\n var buffer = new byte[4096];\n\n do\n {\n readLength = input.Read(buffer, 0, buffer.Length);\n output.Write(buffer, 0, readLength);\n }\n while (readLength != 0);\n\n return output.ToArray();\n }\n}\n</code></pre>\n\n<p>Finally, as a few have already mentioned, <a href=\"http://research.microsoft.com/~mbarnett/ILMerge.aspx\" rel=\"noreferrer\">ILMerge</a> may be another option to consider, albeit somewhat more involved. </p>\n" }, { "answer_id": 103773, "author": "Redwood", "author_id": 1512, "author_profile": "https://Stackoverflow.com/users/1512", "pm_score": 4, "selected": false, "text": "<p>In the end I did it almost exactly the way raboof suggested (and similar to what dgvid suggested), except with some minor changes and some omissions fixed. I chose this method because it was closest to what I was looking for in the first place and didn't require using any third party executables and such. It works great!</p>\n\n<p>This is what my code ended up looking like:</p>\n\n<p>EDIT: I decided to move this function to another assembly so I could reuse it in multiple files (I just pass in Assembly.GetExecutingAssembly()). </p>\n\n<p>This is the updated version which allows you to pass in the assembly with the embedded dlls. </p>\n\n<p>embeddedResourcePrefix is the string path to the embedded resource, it will usually be the name of the assembly followed by any folder structure containing the resource (e.g. \"MyComapny.MyProduct.MyAssembly.Resources\" if the dll is in a folder called Resources in the project). It also assumes that the dll has a .dll.resource extension.</p>\n\n<pre><code> public static void EnableDynamicLoadingForDlls(Assembly assemblyToLoadFrom, string embeddedResourcePrefix) {\n AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =&gt; { // had to add =&gt;\n try {\n string resName = embeddedResourcePrefix + \".\" + args.Name.Split(',')[0] + \".dll.resource\";\n using (Stream input = assemblyToLoadFrom.GetManifestResourceStream(resName)) {\n return input != null\n ? Assembly.Load(StreamToBytes(input))\n : null;\n }\n } catch (Exception ex) {\n _log.Error(\"Error dynamically loading dll: \" + args.Name, ex);\n return null;\n }\n }; // Had to add colon\n }\n\n private static byte[] StreamToBytes(Stream input) {\n int capacity = input.CanSeek ? (int)input.Length : 0;\n using (MemoryStream output = new MemoryStream(capacity)) {\n int readLength;\n byte[] buffer = new byte[4096];\n\n do {\n readLength = input.Read(buffer, 0, buffer.Length); // had to change to buffer.Length\n output.Write(buffer, 0, readLength);\n }\n while (readLength != 0);\n\n return output.ToArray();\n }\n }\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible. This with is C# and .NET 3.5. The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL. The way I originally planned to do this is by writing code to put the third party DLL in the location specified by `System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()` minus the last `/nameOfMyAssembly.dll`. I can successfully save the third party `.DLL` in this location (which ends up being > > C:\Documents and Settings\myUserName\Local Settings\Application > Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb\_fe18c901 > > > ), but when I get to the part of my code requiring this DLL, it can't find it. Does anybody have any idea as to what I need to be doing differently?
Once you've embedded the third-party assembly as a resource, add code to subscribe to the [`AppDomain.AssemblyResolve`](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx) event of the current domain during application start-up. This event fires whenever the Fusion sub-system of the CLR fails to locate an assembly according to the probing (policies) in effect. In the event handler for `AppDomain.AssemblyResolve`, load the resource using [`Assembly.GetManifestResourceStream`](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx) and feed its content as a byte array into the corresponding [`Assembly.Load`](http://msdn.microsoft.com/en-us/library/h538bck7.aspx) overload. Below is how one such implementation could look like in C#: ``` AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var resName = args.Name + ".dll"; var thisAssembly = Assembly.GetExecutingAssembly(); using (var input = thisAssembly.GetManifestResourceStream(resName)) { return input != null ? Assembly.Load(StreamToBytes(input)) : null; } }; ``` where `StreamToBytes` could be defined as: ``` static byte[] StreamToBytes(Stream input) { var capacity = input.CanSeek ? (int) input.Length : 0; using (var output = new MemoryStream(capacity)) { int readLength; var buffer = new byte[4096]; do { readLength = input.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, readLength); } while (readLength != 0); return output.ToArray(); } } ``` Finally, as a few have already mentioned, [ILMerge](http://research.microsoft.com/~mbarnett/ILMerge.aspx) may be another option to consider, albeit somewhat more involved.
96,759
<p>I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file.</p> <pre><code>function f_parse_csv($file, $longest, $delimiter) { $mdarray = array(); $file = fopen($file, "r"); while ($line = fgetcsv($file, $longest, $delimiter)) { array_push($mdarray, $line); } fclose($file); return $mdarray; } </code></pre> <p>I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of <code>Y-m-d H:i:s</code> and I would like to be able to sort with the most recent date being the first row.</p>
[ { "answer_id": 96812, "author": "Jan Hančič", "author_id": 185527, "author_profile": "https://Stackoverflow.com/users/185527", "pm_score": 0, "selected": false, "text": "<p>The \"Usort\" function is your answer.<br>\n<a href=\"http://php.net/usort\" rel=\"nofollow noreferrer\">http://php.net/usort</a></p>\n" }, { "answer_id": 96832, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 5, "selected": false, "text": "<p>With <a href=\"http://docs.php.net/manual/en/function.usort.php\" rel=\"noreferrer\">usort</a>. Here's a generic solution, that you can use for different columns:</p>\n\n<pre><code>class TableSorter {\n protected $column;\n function __construct($column) {\n $this-&gt;column = $column;\n }\n function sort($table) {\n usort($table, array($this, 'compare'));\n return $table;\n }\n function compare($a, $b) {\n if ($a[$this-&gt;column] == $b[$this-&gt;column]) {\n return 0;\n }\n return ($a[$this-&gt;column] &lt; $b[$this-&gt;column]) ? -1 : 1;\n }\n}\n</code></pre>\n\n<p>To sort by first column:</p>\n\n<pre><code>$sorter = new TableSorter(0); // sort by first column\n$mdarray = $sorter-&gt;sort($mdarray);\n</code></pre>\n" }, { "answer_id": 96845, "author": "Tim Boland", "author_id": 70, "author_profile": "https://Stackoverflow.com/users/70", "pm_score": -1, "selected": false, "text": "<p>I prefer to use array_multisort. See the documentation\n<a href=\"http://us2.php.net/manual/en/function.array-multisort.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 96870, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 9, "selected": true, "text": "<p>You can use <a href=\"http://php.net/manual/en/function.array-multisort.php\" rel=\"noreferrer\">array_multisort()</a></p>\n\n<p>Try something like this:</p>\n\n<pre><code>foreach ($mdarray as $key =&gt; $row) {\n // replace 0 with the field's index/key\n $dates[$key] = $row[0];\n}\n\narray_multisort($dates, SORT_DESC, $mdarray);\n</code></pre>\n\n<p>For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:</p>\n\n<pre><code>array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);\n</code></pre>\n" }, { "answer_id": 97572, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 2, "selected": false, "text": "<p>Here is a php4/php5 class that will sort one or more fields:</p>\n\n<pre><code>// a sorter class\n// php4 and php5 compatible\nclass Sorter {\n\n var $sort_fields;\n var $backwards = false;\n var $numeric = false;\n\n function sort() {\n $args = func_get_args();\n $array = $args[0];\n if (!$array) return array();\n $this-&gt;sort_fields = array_slice($args, 1);\n if (!$this-&gt;sort_fields) return $array();\n\n if ($this-&gt;numeric) {\n usort($array, array($this, 'numericCompare'));\n } else {\n usort($array, array($this, 'stringCompare'));\n }\n return $array;\n }\n\n function numericCompare($a, $b) {\n foreach($this-&gt;sort_fields as $sort_field) {\n if ($a[$sort_field] == $b[$sort_field]) {\n continue;\n }\n return ($a[$sort_field] &lt; $b[$sort_field]) ? ($this-&gt;backwards ? 1 : -1) : ($this-&gt;backwards ? -1 : 1);\n }\n return 0;\n }\n\n function stringCompare($a, $b) {\n foreach($this-&gt;sort_fields as $sort_field) {\n $cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);\n if ($cmp_result == 0) continue;\n\n return ($this-&gt;backwards ? -$cmp_result : $cmp_result);\n }\n return 0;\n }\n}\n\n/////////////////////\n// usage examples\n\n// some starting data\n$start_data = array(\n array('first_name' =&gt; 'John', 'last_name' =&gt; 'Smith', 'age' =&gt; 10),\n array('first_name' =&gt; 'Joe', 'last_name' =&gt; 'Smith', 'age' =&gt; 11),\n array('first_name' =&gt; 'Jake', 'last_name' =&gt; 'Xample', 'age' =&gt; 9),\n);\n\n// sort by last_name, then first_name\n$sorter = new Sorter();\nprint_r($sorter-&gt;sort($start_data, 'last_name', 'first_name'));\n\n// sort by first_name, then last_name\n$sorter = new Sorter();\nprint_r($sorter-&gt;sort($start_data, 'first_name', 'last_name'));\n\n// sort by last_name, then first_name (backwards)\n$sorter = new Sorter();\n$sorter-&gt;backwards = true;\nprint_r($sorter-&gt;sort($start_data, 'last_name', 'first_name'));\n\n// sort numerically by age\n$sorter = new Sorter();\n$sorter-&gt;numeric = true;\nprint_r($sorter-&gt;sort($start_data, 'age'));\n</code></pre>\n" }, { "answer_id": 98058, "author": "Melikoth", "author_id": 1536217, "author_profile": "https://Stackoverflow.com/users/1536217", "pm_score": 0, "selected": false, "text": "<p>Before I could get the TableSorter class to run I had came up with a function based on what <a href=\"https://stackoverflow.com/users/18219/shinhan\">Shinhan</a> had provided.</p>\n\n<pre><code>function sort2d_bycolumn($array, $column, $method, $has_header)\n {\n if ($has_header) $header = array_shift($array);\n foreach ($array as $key => $row) {\n $narray[$key] = $row[$column]; \n }\n array_multisort($narray, $method, $array);\n if ($has_header) array_unshift($array, $header);\n return $array;\n }</code></pre>\n\n<ul>\n<li>$array is the MD Array you want to sort.</li>\n<li>$column is the column you wish to sort by.</li>\n<li>$method is how you want the sort performed, such as SORT_DESC</li>\n<li>$has_header is set to true if the first row contains header values that you don't want sorted.</li>\n</ul>\n" }, { "answer_id": 4230273, "author": "Mike C", "author_id": 474192, "author_profile": "https://Stackoverflow.com/users/474192", "pm_score": 3, "selected": false, "text": "<p>I know it's 2 years since this question was asked and answered, but here's another function that sorts a two-dimensional array. It accepts a variable number of arguments, allowing you to pass in more than one key (ie column name) to sort by. PHP 5.3 required.</p>\n\n<pre><code>function sort_multi_array ($array, $key)\n{\n $keys = array();\n for ($i=1;$i&lt;func_num_args();$i++) {\n $keys[$i-1] = func_get_arg($i);\n }\n\n // create a custom search function to pass to usort\n $func = function ($a, $b) use ($keys) {\n for ($i=0;$i&lt;count($keys);$i++) {\n if ($a[$keys[$i]] != $b[$keys[$i]]) {\n return ($a[$keys[$i]] &lt; $b[$keys[$i]]) ? -1 : 1;\n }\n }\n return 0;\n };\n\n usort($array, $func);\n\n return $array;\n}\n</code></pre>\n\n<p>Try it here: <a href=\"http://www.exorithm.com/algorithm/view/sort_multi_array\" rel=\"noreferrer\">http://www.exorithm.com/algorithm/view/sort_multi_array</a></p>\n" }, { "answer_id": 10142887, "author": "feeela", "author_id": 341201, "author_profile": "https://Stackoverflow.com/users/341201", "pm_score": 4, "selected": false, "text": "<h2>Multiple row sorting using a closure</h2>\n\n<p>Here's another approach using uasort() and an anonymous callback function (closure). I've used that function regularly. <strong>PHP 5.3 required</strong> – no more dependencies!</p>\n\n<pre><code>/**\n * Sorting array of associative arrays - multiple row sorting using a closure.\n * See also: http://the-art-of-web.com/php/sortarray/\n *\n * @param array $data input-array\n * @param string|array $fields array-keys\n * @license Public Domain\n * @return array\n */\nfunction sortArray( $data, $field ) {\n $field = (array) $field;\n uasort( $data, function($a, $b) use($field) {\n $retval = 0;\n foreach( $field as $fieldname ) {\n if( $retval == 0 ) $retval = strnatcmp( $a[$fieldname], $b[$fieldname] );\n }\n return $retval;\n } );\n return $data;\n}\n\n/* example */\n$data = array(\n array( \"firstname\" =&gt; \"Mary\", \"lastname\" =&gt; \"Johnson\", \"age\" =&gt; 25 ),\n array( \"firstname\" =&gt; \"Amanda\", \"lastname\" =&gt; \"Miller\", \"age\" =&gt; 18 ),\n array( \"firstname\" =&gt; \"James\", \"lastname\" =&gt; \"Brown\", \"age\" =&gt; 31 ),\n array( \"firstname\" =&gt; \"Patricia\", \"lastname\" =&gt; \"Williams\", \"age\" =&gt; 7 ),\n array( \"firstname\" =&gt; \"Michael\", \"lastname\" =&gt; \"Davis\", \"age\" =&gt; 43 ),\n array( \"firstname\" =&gt; \"Sarah\", \"lastname\" =&gt; \"Miller\", \"age\" =&gt; 24 ),\n array( \"firstname\" =&gt; \"Patrick\", \"lastname\" =&gt; \"Miller\", \"age\" =&gt; 27 )\n);\n\n$data = sortArray( $data, 'age' );\n$data = sortArray( $data, array( 'lastname', 'firstname' ) );\n</code></pre>\n" }, { "answer_id": 16788610, "author": "Jon", "author_id": 50079, "author_profile": "https://Stackoverflow.com/users/50079", "pm_score": 8, "selected": false, "text": "<h2>Introducing: a very generalized solution for PHP 5.3+</h2>\n\n<p>I 'd like to add my own solution here, since it offers features that other answers do not.</p>\n\n<p>Specifically, advantages of this solution include:</p>\n\n<ol>\n<li>It's <strong>reusable</strong>: you specify the sort column as a variable instead of hardcoding it.</li>\n<li>It's <strong>flexible</strong>: you can specify multiple sort columns (as many as you want) -- additional columns are used as tiebreakers between items that initially compare equal.</li>\n<li>It's <strong>reversible</strong>: you can specify that the sort should be reversed -- individually for each column.</li>\n<li>It's <strong>extensible</strong>: if the data set contains columns that cannot be compared in a \"dumb\" manner (e.g. date strings) you can also specify how to convert these items to a value that can be directly compared (e.g. a <code>DateTime</code> instance).</li>\n<li>It's <strong>associative if you want</strong>: this code takes care of sorting items, but <em>you</em> select the actual sort function (<code>usort</code> or <code>uasort</code>).</li>\n<li>Finally, it does not use <code>array_multisort</code>: while <code>array_multisort</code> is convenient, it depends on creating a projection of all your input data before sorting. This consumes time and memory and may be simply prohibitive if your data set is large.</li>\n</ol>\n\n<h3>The code</h3>\n\n<pre><code>function make_comparer() {\n // Normalize criteria up front so that the comparer finds everything tidy\n $criteria = func_get_args();\n foreach ($criteria as $index =&gt; $criterion) {\n $criteria[$index] = is_array($criterion)\n ? array_pad($criterion, 3, null)\n : array($criterion, SORT_ASC, null);\n }\n\n return function($first, $second) use (&amp;$criteria) {\n foreach ($criteria as $criterion) {\n // How will we compare this round?\n list($column, $sortOrder, $projection) = $criterion;\n $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;\n\n // If a projection was defined project the values now\n if ($projection) {\n $lhs = call_user_func($projection, $first[$column]);\n $rhs = call_user_func($projection, $second[$column]);\n }\n else {\n $lhs = $first[$column];\n $rhs = $second[$column];\n }\n\n // Do the actual comparison; do not return if equal\n if ($lhs &lt; $rhs) {\n return -1 * $sortOrder;\n }\n else if ($lhs &gt; $rhs) {\n return 1 * $sortOrder;\n }\n }\n\n return 0; // tiebreakers exhausted, so $first == $second\n };\n}\n</code></pre>\n\n<h2>How to use</h2>\n\n<p>Throughout this section I will provide links that sort this sample data set:</p>\n\n<pre><code>$data = array(\n array('zz', 'name' =&gt; 'Jack', 'number' =&gt; 22, 'birthday' =&gt; '12/03/1980'),\n array('xx', 'name' =&gt; 'Adam', 'number' =&gt; 16, 'birthday' =&gt; '01/12/1979'),\n array('aa', 'name' =&gt; 'Paul', 'number' =&gt; 16, 'birthday' =&gt; '03/11/1987'),\n array('cc', 'name' =&gt; 'Helen', 'number' =&gt; 44, 'birthday' =&gt; '24/06/1967'),\n);\n</code></pre>\n\n<h3>The basics</h3>\n\n<p>The function <code>make_comparer</code> accepts a variable number of arguments that define the desired sort and returns a function that you are supposed to use as the argument to <code>usort</code> or <code>uasort</code>.</p>\n\n<p>The simplest use case is to pass in the key that you 'd like to use to compare data items. For example, to sort <code>$data</code> by the <code>name</code> item you would do</p>\n\n<pre><code>usort($data, make_comparer('name'));\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/g5jNqs\">See it in action</a></strong>.</p>\n\n<p>The key can also be a number if the items are numerically indexed arrays. For the example in the question, this would be</p>\n\n<pre><code>usort($data, make_comparer(0)); // 0 = first numerically indexed column\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/upHxqf\">See it in action</a></strong>.</p>\n\n<h3>Multiple sort columns</h3>\n\n<p>You can specify multiple sort columns by passing additional parameters to <code>make_comparer</code>. For example, to sort by \"number\" and then by the zero-indexed column:</p>\n\n<pre><code>usort($data, make_comparer('number', 0));\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/C5OqJT\">See it in action</a></strong>.</p>\n\n<h2>Advanced features</h2>\n\n<p>More advanced features are available if you specify a sort column as an array instead of a simple string. This array should be numerically indexed, and must contain these items:</p>\n\n<pre><code>0 =&gt; the column name to sort on (mandatory)\n1 =&gt; either SORT_ASC or SORT_DESC (optional)\n2 =&gt; a projection function (optional)\n</code></pre>\n\n<p>Let's see how we can use these features.</p>\n\n<h3>Reverse sort</h3>\n\n<p>To sort by name descending:</p>\n\n<pre><code>usort($data, make_comparer(['name', SORT_DESC]));\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/eLUqjb\">See it in action</a></strong>.</p>\n\n<p>To sort by number descending and then by name descending:</p>\n\n<pre><code>usort($data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC]));\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/RpyQZ3\">See it in action</a></strong>.</p>\n\n<h3>Custom projections</h3>\n\n<p>In some scenarios you may need to sort by a column whose values do not lend well to sorting. The \"birthday\" column in the sample data set fits this description: it does not make sense to compare birthdays as strings (because e.g. \"01/01/1980\" comes before \"10/10/1970\"). In this case we want to specify how to <em>project</em> the actual data to a form that <em>can</em> be compared directly with the desired semantics.</p>\n\n<p>Projections can be specified as any type of <a href=\"http://php.net/manual/en/language.types.callable.php\">callable</a>: as strings, arrays, or anonymous functions. A projection is assumed to accept one argument and return its projected form.</p>\n\n<p>It should be noted that while projections are similar to the custom comparison functions used with <code>usort</code> and family, they are simpler (you only need to convert one value to another) and take advantage of all the functionality already baked into <code>make_comparer</code>.</p>\n\n<p>Let's sort the example data set without a projection and see what happens:</p>\n\n<pre><code>usort($data, make_comparer('birthday'));\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/GvXmoM\">See it in action</a></strong>.</p>\n\n<p>That was not the desired outcome. But we can use <a href=\"http://php.net/manual/en/function.date-create.php\"><code>date_create</code></a> as a projection:</p>\n\n<pre><code>usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/sZE4hO\">See it in action</a></strong>.</p>\n\n<p>This is the correct order that we wanted.</p>\n\n<p>There are many more things that projections can achieve. For example, a quick way to get a case-insensitive sort is to use <code>strtolower</code> as a projection.</p>\n\n<p>That said, I should also mention that it's better to not use projections if your data set is large: in that case it would be much faster to project all your data manually up front and then sort without using a projection, although doing so will trade increased memory usage for faster sort speed.</p>\n\n<p>Finally, here is an example that uses all the features: it first sorts by number descending, then by birthday ascending:</p>\n\n<pre><code>usort($data, make_comparer(\n ['number', SORT_DESC],\n ['birthday', SORT_ASC, 'date_create']\n));\n</code></pre>\n\n<p><strong><a href=\"http://ideone.com/RLmvsm\">See it in action</a></strong>.</p>\n" }, { "answer_id": 17201125, "author": "PJ Brunet", "author_id": 722796, "author_profile": "https://Stackoverflow.com/users/722796", "pm_score": 0, "selected": false, "text": "<p>I tried several popular array_multisort() and usort() answers and none of them worked for me. The data just gets jumbled and the code is unreadable. Here's a quick a dirty solution. WARNING: Only use this if you're sure a rogue delimiter won't come back to haunt you later! </p>\n\n<p>Let's say each row in your multi array looks like: name, stuff1, stuff2:</p>\n\n<pre><code>// Sort by name, pull the other stuff along for the ride\nforeach ($names_stuff as $name_stuff) {\n // To sort by stuff1, that would be first in the contatenation\n $sorted_names[] = $name_stuff[0] .','. name_stuff[1] .','. $name_stuff[2];\n}\nsort($sorted_names, SORT_STRING);\n</code></pre>\n\n<p>Need your stuff back in alphabetical order?</p>\n\n<pre><code>foreach ($sorted_names as $sorted_name) {\n $name_stuff = explode(',',$sorted_name);\n // use your $name_stuff[0] \n // use your $name_stuff[1] \n // ... \n}\n</code></pre>\n\n<p>Yeah, it's dirty. But super easy, won't make your head explode. </p>\n" }, { "answer_id": 24486990, "author": "Kamal", "author_id": 1093184, "author_profile": "https://Stackoverflow.com/users/1093184", "pm_score": 3, "selected": false, "text": "<p>You can sort an array using <a href=\"https://www.php.net/usort\" rel=\"nofollow noreferrer\">usort</a> function.</p>\n<pre><code> $array = array(\n array('price'=&gt;'1000.50','product'=&gt;'product 1'),\n array('price'=&gt;'8800.50','product'=&gt;'product 2'),\n array('price'=&gt;'200.0','product'=&gt;'product 3')\n);\n\nfunction cmp($a, $b) {\n return $a['price'] &gt; $b['price'];\n}\nusort($array, &quot;cmp&quot;);\nprint_r($array);\n</code></pre>\n<p>Output :</p>\n<pre><code>Array\n(\n [0] =&gt; Array\n (\n [price] =&gt; 134.50\n [product] =&gt; product 1\n )\n\n [1] =&gt; Array\n (\n [price] =&gt; 2033.0\n [product] =&gt; product 3\n )\n\n [2] =&gt; Array\n (\n [price] =&gt; 8340.50\n [product] =&gt; product 2\n )\n\n)\n</code></pre>\n<p><a href=\"https://qoify.com/how-to-sort-an-array-of-associative-arrays-by-value-of-given-key-in-php\" rel=\"nofollow noreferrer\">Example</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536217/" ]
I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file. ``` function f_parse_csv($file, $longest, $delimiter) { $mdarray = array(); $file = fopen($file, "r"); while ($line = fgetcsv($file, $longest, $delimiter)) { array_push($mdarray, $line); } fclose($file); return $mdarray; } ``` I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of `Y-m-d H:i:s` and I would like to be able to sort with the most recent date being the first row.
You can use [array\_multisort()](http://php.net/manual/en/function.array-multisort.php) Try something like this: ``` foreach ($mdarray as $key => $row) { // replace 0 with the field's index/key $dates[$key] = $row[0]; } array_multisort($dates, SORT_DESC, $mdarray); ``` For PHP >= 5.5.0 just extract the column to sort by. No need for the loop: ``` array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray); ```
96,826
<p>Pretty basic question, I'm trying to write a regex in Vim to match any phrase starting with <code>"abc "</code> directly followed by anything other than <code>"defg"</code>. </p> <p>I've used <code>"[^defg]"</code> to match any single character other than d, e, f or g.</p> <p>My first instinct was to try <code>/abc [^\(defg\)]</code> or <code>/abc [^\&lt;defg\&gt;]</code> but neither one of those works.</p>
[ { "answer_id": 96946, "author": "Lee H", "author_id": 18201, "author_profile": "https://Stackoverflow.com/users/18201", "pm_score": 1, "selected": false, "text": "<p>Here we go, this is a hairy one:</p>\n\n<pre><code>/\\%(\\%(.\\{-}\\)\\@&lt;=XXXXXX\\zs\\)*\n</code></pre>\n\n<p>(replace XXXXXX with the search word). This will search for everything that does <em>not</em> contain XXXXXX. I imagine if you did:</p>\n\n<pre><code>/abc \\%(\\%(.\\{-}\\)\\@&lt;=defg\\zs\\)*\n</code></pre>\n\n<p>This may work like you want it to. Hope this helps a little!</p>\n" }, { "answer_id": 96973, "author": "Andy", "author_id": 13505, "author_profile": "https://Stackoverflow.com/users/13505", "pm_score": -1, "selected": false, "text": "<p>/abc\\ [^d][^e][^f][^g]</p>\n\n<p>It's pretty cumbersome for larger words, but works like a charm.</p>\n" }, { "answer_id": 97008, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 7, "selected": true, "text": "<p>Here's the search string.</p>\n\n<pre><code>/abc \\(defg\\)\\@!\n</code></pre>\n\n<p>The concept you're looking for is called a negative look-ahead assertion. Try this in vim for more info:</p>\n\n<pre><code>:help \\@!\n</code></pre>\n" }, { "answer_id": 99129, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 4, "selected": false, "text": "<p>preceeded or followed by?</p>\n\n<p>If it's anything starting with 'abc ' that's not (immediately) followed by 'defg', you want <a href=\"https://stackoverflow.com/questions/96826/vim-how-do-i-exclude-an-entire-word-from-my-search#97008\">bmdhacks' solution</a>.</p>\n\n<p>If it's anything starting with 'abc ' that's not (immediately) preceeded by 'defg', you want a negative lookbehind:</p>\n\n<pre><code>/\\%(defg\\)\\@&lt;!abc /\n</code></pre>\n\n<p>This will match any occurance of 'abc ' as long as it's not part of 'defgabc '. See <code>:help \\@&lt;!</code> for more details.</p>\n\n<p>If you want to match 'abc ' as long as it's not part of 'defg.*abc ', then just add a <code>.*</code>:</p>\n\n<pre><code>/\\%(defg.*\\)\\@&lt;!abc /\n</code></pre>\n\n<p>Matching 'abc ' only on lines where 'defg' doesn't occur is similar:</p>\n\n<pre><code>/\\%(defg.*\\)\\@&lt;!abc \\%(.*defg\\)\\@!/\n</code></pre>\n\n<p>Although, if you're just doing this for a substitution, you can make this easier by combining <code>:v//</code> and <code>:s//</code></p>\n\n<pre><code>:%v/defg/s/abc /&lt;whatever&gt;/g\n</code></pre>\n\n<p>This will substitute '&lt;whatever>' for 'abc ' on all lines that don't contain 'defg'. See <code>:help :v</code> for more.</p>\n" }, { "answer_id": 72109908, "author": "Yao Li", "author_id": 10222225, "author_profile": "https://Stackoverflow.com/users/10222225", "pm_score": 0, "selected": false, "text": "<p>I don't have enough reputation to comment Andy's answer, but his answer is wrong, so I explain it here, the expression&quot;/abc\\ [^d][^e][^f][^g]&quot; is not match 'abc d111', 'abc def1' etc.\nthe best way is the expression &quot;/abc (defg)@!&quot;</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5379/" ]
Pretty basic question, I'm trying to write a regex in Vim to match any phrase starting with `"abc "` directly followed by anything other than `"defg"`. I've used `"[^defg]"` to match any single character other than d, e, f or g. My first instinct was to try `/abc [^\(defg\)]` or `/abc [^\<defg\>]` but neither one of those works.
Here's the search string. ``` /abc \(defg\)\@! ``` The concept you're looking for is called a negative look-ahead assertion. Try this in vim for more info: ``` :help \@! ```
96,837
<p>This is a good candidate for the <a href="http://www.codinghorror.com/blog/archives/000818.html" rel="nofollow noreferrer">"Works on My Machine Certification Program"</a>.</p> <p>I have the following code for a LinkButton...</p> <pre><code>&lt;cc1:PopupDialog ID="pdFamilyPrompt" runat="server" CloseLink="false" Display="true"&gt; &lt;p&gt;Do you wish to upgrade?&lt;/p&gt; &lt;asp:HyperLink ID="hlYes" runat="server" Text="Yes" CssClass="button"&gt;&lt;/asp:HyperLink&gt; &lt;asp:LinkButton ID="lnkbtnNo" runat="server" Text="No" CssClass="button"&gt;&lt;/asp:LinkButton&gt; &lt;/cc1:PopupDialog&gt; </code></pre> <p>It uses a custom control that simply adds code before and after the content to format it as a popup dialog. The <strong>Yes</strong> button is a HyperLink because it executes javascript to hide the dialog and show a different one. The <strong>No</strong> button is a LinkButton because it needs to PostBack to process this value.</p> <p>I do not have an onClick event registered with the LinkButton because I simply check if IsPostBack is true. When executed locally, the PostBack works fine and all goes well. When published to our Development server, the <strong>No</strong> button does nothing when clicked on. I am using the same browser when testing locally versus on the development server. </p> <p>My initial thought is that perhaps a Validator is preventing the PostBack from firing. I do use a couple of Validators on another section of the page, but they are all assigned to a specific Validation Group which the <strong>No</strong> LinkButton is not assigned to. However the problem is why it would work locally on not on the development server.</p> <p>Any ideas?</p>
[ { "answer_id": 96881, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": true, "text": "<p>Check the html that is emitted on production and make sure that it has the __doPostback() and that there are no global methods watching click and canceling the event. Other than that if you think it could be related to validation you could try adding CausesValidation or whatever to false and see if that helps. Otherwise a \"works on my machine\" error is kind of hard to debug without being present and knowing the configurations of DEV vs PROD.</p>\n" }, { "answer_id": 96917, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 0, "selected": false, "text": "<p>My understanding of ValidationGroup is that a button with no group specified would trigger all validators on the page. Have you tried giving the LinkButton a different ValidationGroup?</p>\n" }, { "answer_id": 2733930, "author": "yougotiger", "author_id": 322932, "author_profile": "https://Stackoverflow.com/users/322932", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem. I created a form with an updatePanel, in the form were some linkbuttons that would open a modalpopup Ajax extender. They worked fine until I added authentication to the site. After that they didn't do anything at all.</p>\n\n<p>Reading your solution I found that some of the linkbuttons WERE working, they were the ones that had CausesValidation explicity set (I only put it in for the ones where I would make that true). Adding CausesValidation=\"false\" to all the other linkbuttons allowed them to work correctly after I was authenticated.</p>\n\n<p>Thanks for your comments everyone, it saved my day!</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4624/" ]
This is a good candidate for the ["Works on My Machine Certification Program"](http://www.codinghorror.com/blog/archives/000818.html). I have the following code for a LinkButton... ``` <cc1:PopupDialog ID="pdFamilyPrompt" runat="server" CloseLink="false" Display="true"> <p>Do you wish to upgrade?</p> <asp:HyperLink ID="hlYes" runat="server" Text="Yes" CssClass="button"></asp:HyperLink> <asp:LinkButton ID="lnkbtnNo" runat="server" Text="No" CssClass="button"></asp:LinkButton> </cc1:PopupDialog> ``` It uses a custom control that simply adds code before and after the content to format it as a popup dialog. The **Yes** button is a HyperLink because it executes javascript to hide the dialog and show a different one. The **No** button is a LinkButton because it needs to PostBack to process this value. I do not have an onClick event registered with the LinkButton because I simply check if IsPostBack is true. When executed locally, the PostBack works fine and all goes well. When published to our Development server, the **No** button does nothing when clicked on. I am using the same browser when testing locally versus on the development server. My initial thought is that perhaps a Validator is preventing the PostBack from firing. I do use a couple of Validators on another section of the page, but they are all assigned to a specific Validation Group which the **No** LinkButton is not assigned to. However the problem is why it would work locally on not on the development server. Any ideas?
Check the html that is emitted on production and make sure that it has the \_\_doPostback() and that there are no global methods watching click and canceling the event. Other than that if you think it could be related to validation you could try adding CausesValidation or whatever to false and see if that helps. Otherwise a "works on my machine" error is kind of hard to debug without being present and knowing the configurations of DEV vs PROD.
96,848
<p>Is there any way to use a constant as a hash key?</p> <p>For example:</p> <pre><code>use constant X =&gt; 1; my %x = (X =&gt; 'X'); </code></pre> <p>The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.</p>
[ { "answer_id": 96869, "author": "nohat", "author_id": 3101, "author_profile": "https://Stackoverflow.com/users/3101", "pm_score": 7, "selected": true, "text": "<p><code>use constant</code> actually makes constant subroutines.</p>\n\n<p>To do what you want, you need to explicitly call the sub:</p>\n\n<pre><code>use constant X =&gt; 1;\n\nmy %x = ( &amp;X =&gt; 'X');\n</code></pre>\n\n<p>or</p>\n\n<pre><code>use constant X =&gt; 1;\n\nmy %x = ( X() =&gt; 'X');\n</code></pre>\n" }, { "answer_id": 96877, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": false, "text": "<p>Your problem is that => is a magic comma that automatically quotes the word in front of it. So what you wrote is equivalent to ('X', 'X').</p>\n\n<p>The simplest way is to just use a comma:</p>\n\n<pre><code>my %x = (X, 'X');\n</code></pre>\n\n<p>Or, you can add various punctuation so that you no longer have a simple word in front of the =>:</p>\n\n<pre><code>my %x = ( X() =&gt; 'X' );\nmy %x = ( &amp;X =&gt; 'X' );\n</code></pre>\n" }, { "answer_id": 96885, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>=> operator interprets its left side as a \"string\", the way qw() does.</p>\n\n<p>Try using </p>\n\n<pre><code>my %x = ( X, 'X');\n</code></pre>\n" }, { "answer_id": 96888, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 2, "selected": false, "text": "<p>One way is to encapsulate X as (X):</p>\n\n<pre><code>my %x ( (X) =&gt; 1 );\n</code></pre>\n\n<p>Another option is to do away with '=>' and use ',' instead:</p>\n\n<pre><code>my %x ( X, 1 );\n</code></pre>\n" }, { "answer_id": 96902, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 3, "selected": false, "text": "<p>Use <code>$hash{CONSTANT()}</code> or <code>$hash{+CONSTANT}</code> to prevent the bareword quoting mechanism from kicking in.</p>\n\n<p>From: <a href=\"http://perldoc.perl.org/constant.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/constant.html</a></p>\n" }, { "answer_id": 97019, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 4, "selected": false, "text": "<p>Another option is to not use the use constant pragma and flip to Readonly as per recommendations in the Perl Best Practices by Damian Conway.</p>\n\n<p>I switched a while back after realizing that constant hash ref's are just a constant reference to the hash, but don't do anything about the data inside the hash.</p>\n\n<p>The readonly syntax creates \"normal looking\" variables, but will actually enforce the constantness or readonlyness. You can use it just like you would any other variable as a key.</p>\n\n<pre>\n<code>\nuse Readonly;\n\nReadonly my $CONSTANT => 'Some value';\n\n$hash{$CONSTANT} = 1;\n</code>\n</pre>\n" }, { "answer_id": 97070, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "<p>The <code>use constant</code> pragma creates a subroutine prototyped to take no arguments. While it <em>looks</em> like a C-style constant, it's really a subroutine that returns a constant value.</p>\n\n<p>The <code>=&gt;</code> (fat comma) automatically quotes left operand if its a bareword, as does the $hash{key} notation.</p>\n\n<p>If your use of the constant name looks like a bareword, the quoting mechanisms will kick in and you'll get its name as the key instead of its value. To prevent this, change the usage so that it's not a bareword. For example:</p>\n\n<pre><code>use constant X =&gt; 1;\n%hash = (X() =&gt; 1);\n%hash = (+X =&gt; 1);\n$hash{X()} = 1;\n$hash{+X} = 1;\n</code></pre>\n\n<p>In initializers, you could also use the plain comma instead:</p>\n\n<pre><code>%hash = (X, 1);\n</code></pre>\n" }, { "answer_id": 97440, "author": "jjohn", "author_id": 16513, "author_profile": "https://Stackoverflow.com/users/16513", "pm_score": 3, "selected": false, "text": "<p>Most of the other folks have answered your question well. Taken together, these create a very full explanation of the problem and recommended workarounds. The issue is that the Perl pragma \"use constant\" really creates a subroutine in your current package whose name is the the first argument of the pragma and whose value is the last.</p>\n\n<p>In Perl, once a subroutine is declared, it may be called without parens.</p>\n\n<p>Understanding that \"constants\" are simply subroutines, you can see why they are not interpolated in strings and why the \"fat comma\" operator \"=>\" which quotes the left-hand argument thinks you've handed it a string (try other built-in functions like time() and keys() sometime with the fat comma for extra fun). </p>\n\n<p>Luckily, you may invoke the constant using explicit punctuation like parens or the ampersand sigil.</p>\n\n<p>However, I've got a question for you: why are you using constants for hash keys at all? </p>\n\n<p>I can think of a few scenarios that might lead you in this direction:</p>\n\n<ol>\n<li><p>You want control over which keys can be in the hash.</p></li>\n<li><p>You want to abstract the name of the keys in case these change later</p></li>\n</ol>\n\n<p>In the case of number 1, constants probably won't save your hash. Instead, consider creating an Class that has public setters and getters that populate a hash visible only to the object. This is a very un-Perl like solution, but very easily to do.</p>\n\n<p>In the case of number 2, I'd still advocate strongly for a Class. If access to the hash is regulated through a well-defined interface, only the implementer of the class is responsible for getting the hash key names right. In which case, I wouldn't suggest using constants at all.</p>\n\n<p>Hope this helps and thanks for your time.</p>\n" }, { "answer_id": 114340, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 1, "selected": false, "text": "<p>Comment @shelfoo (reputation not high enough to add comment directly there yet!)</p>\n\n<p>Totally agree about Perl Best Practices by Damian Conway... its highly recommended reading.</p>\n\n<p>However please read <a href=\"http://www.perlfoundation.org/perl5/index.cgi?pbp_module_recommendation_commentary\" rel=\"nofollow noreferrer\">PBP Module Recommendation Commentary</a> which is a useful \"errata\" if you plan to use PBP for an in-house style guide.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406/" ]
Is there any way to use a constant as a hash key? For example: ``` use constant X => 1; my %x = (X => 'X'); ``` The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.
`use constant` actually makes constant subroutines. To do what you want, you need to explicitly call the sub: ``` use constant X => 1; my %x = ( &X => 'X'); ``` or ``` use constant X => 1; my %x = ( X() => 'X'); ```
96,871
<p>I'd like to make status icons for a C# WinForms TreeList control. The statuses are combinations of other statuses (eg. a user node might be inactive or banned or inactive and banned), and the status icon is comprised of non-overlapping, smaller glyphs. </p> <p>I'd really like to avoid having to hand-generate all the possibly permutations of status icons if I can avoid it. </p> <p>Is it possible to create an image list (or just a bunch of bitmap resources or something) that I can use to generate the ImageList programmatically?</p> <p>I'm poking around the System.Drawing classes and nothing's jumping out at me. Also, I'm stuck with .Net 2.0.</p>
[ { "answer_id": 96907, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": true, "text": "<pre><code>Bitmap image1 = ...\nBitmap image2 = ...\n\nBitmap combined = new Bitmap(image1.Width, image1.Height);\nusing (Graphics g = Graphics.FromImage(combined)) {\n g.DrawImage(image1, new Point(0, 0));\n g.DrawImage(image2, new Point(0, 0);\n}\n\nimageList.Add(combined);\n</code></pre>\n" }, { "answer_id": 97793, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 0, "selected": false, "text": "<p>Just use Images.Add from the ImageList to add in the individual images. So, something like:</p>\n\n<pre><code>\nImage img = Image.FromStream( /*get stream from resources*/ );\nImageList1.Images.Add( img );\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5062/" ]
I'd like to make status icons for a C# WinForms TreeList control. The statuses are combinations of other statuses (eg. a user node might be inactive or banned or inactive and banned), and the status icon is comprised of non-overlapping, smaller glyphs. I'd really like to avoid having to hand-generate all the possibly permutations of status icons if I can avoid it. Is it possible to create an image list (or just a bunch of bitmap resources or something) that I can use to generate the ImageList programmatically? I'm poking around the System.Drawing classes and nothing's jumping out at me. Also, I'm stuck with .Net 2.0.
``` Bitmap image1 = ... Bitmap image2 = ... Bitmap combined = new Bitmap(image1.Width, image1.Height); using (Graphics g = Graphics.FromImage(combined)) { g.DrawImage(image1, new Point(0, 0)); g.DrawImage(image2, new Point(0, 0); } imageList.Add(combined); ```
96,882
<p>I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image.</p> <p>I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately). </p> <p>I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.</p>
[ { "answer_id": 97025, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 5, "selected": false, "text": "<p>Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.</p>\n<p>Here's how I'm doing it for a long time, very successfully:</p>\n<ol>\n<li><p>Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).</p>\n</li>\n<li><p>Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that. The background image is usually an image we put into a hidden folder (&quot;.something&quot;) on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).</p>\n</li>\n<li><p>Unmount the DMG again, all settings should be stored by now.</p>\n</li>\n<li><p>Write a create DMG script, that works as follows:</p>\n</li>\n</ol>\n<ul>\n<li>It copies the DMG, so the original one is never touched again.</li>\n<li>It mounts the copy.</li>\n<li>It replaces all files with the most up to date ones (e.g. latest app after build). You can simply use <em>mv</em> or <em>ditto</em> for that on command line. Note, when you replace a file like that, the icon will stay the same, the position will stay the same, everything but the file (or directory) content stays the same (at least with ditto, which we usually use for that task). You can of course also replace the background image with another one (just make sure it has the same dimensions).</li>\n<li>After replacing the files, make the script unmount the DMG copy again.</li>\n<li>Finally call hdiutil to convert the writable, to a compressed (and such not writable) DMG.</li>\n</ul>\n<p>This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named &quot;Create DMG&quot;) and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).</p>\n<p>Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a release DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).</p>\n" }, { "answer_id": 97042, "author": "Ludvig A. Norin", "author_id": 16909, "author_profile": "https://Stackoverflow.com/users/16909", "pm_score": 5, "selected": false, "text": "<p>For those of you that are interested in this topic, I should mention how I create the DMG:</p>\n\n<pre><code>hdiutil create XXX.dmg -volname \"YYY\" -fs HFS+ -srcfolder \"ZZZ\"\n</code></pre>\n\n<p>where</p>\n\n<pre><code>XXX == disk image file name (duh!)\nYYY == window title displayed when DMG is opened\nZZZ == Path to a folder containing the files that will be copied into the DMG\n</code></pre>\n" }, { "answer_id": 628874, "author": "Andrey Tarantsov", "author_id": 58146, "author_profile": "https://Stackoverflow.com/users/58146", "pm_score": 6, "selected": false, "text": "<p>There's a little Bash script called <a href=\"https://github.com/andreyvit/create-dmg\" rel=\"noreferrer\">create-dmg</a> that builds fancy DMGs with custom backgrounds, custom icon positioning and volume name.</p>\n\n<p>I've built it many years ago for the company that I ran at the time; it survives on other people's contribution since then, and reportedly works well.</p>\n\n<p>There's also <a href=\"https://github.com/LinusU/node-appdmg\" rel=\"noreferrer\">node-appdmg</a> which looks like a more modern and active effort based on Node.js; check it out as well.</p>\n" }, { "answer_id": 1513578, "author": "Ludvig A. Norin", "author_id": 16909, "author_profile": "https://Stackoverflow.com/users/16909", "pm_score": 9, "selected": true, "text": "<p>After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference:</p>\n\n<ol>\n<li><p>Make sure that \"Enable access for assistive devices\" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4).</p></li>\n<li><p>Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable \"size\" contains the size in Kb and the contents of the folder in the \"source\" bash variable will be copied into the DMG:</p>\n\n<pre><code>hdiutil create -srcfolder \"${source}\" -volname \"${title}\" -fs HFS+ \\\n -fsargs \"-c c=64,a=16,e=16\" -format UDRW -size ${size}k pack.temp.dmg\n</code></pre></li>\n<li><p>Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation):</p>\n\n<pre><code>device=$(hdiutil attach -readwrite -noverify -noautoopen \"pack.temp.dmg\" | \\\n egrep '^/dev/' | sed 1q | awk '{print $1}')\n</code></pre></li>\n<li><p>Store the background picture (in PNG format) in a folder called \".background\" in the DMG, and store its name in the \"backgroundPictureName\" variable. </p></li>\n<li><p>Use AppleScript to set the visual styles (name of .app must be in bash variable \"applicationName\", use variables for the other properties as needed):</p>\n\n<pre><code>echo '\n tell application \"Finder\"\n tell disk \"'${title}'\"\n open\n set current view of container window to icon view\n set toolbar visible of container window to false\n set statusbar visible of container window to false\n set the bounds of container window to {400, 100, 885, 430}\n set theViewOptions to the icon view options of container window\n set arrangement of theViewOptions to not arranged\n set icon size of theViewOptions to 72\n set background picture of theViewOptions to file \".background:'${backgroundPictureName}'\"\n make new alias file at container window to POSIX file \"/Applications\" with properties {name:\"Applications\"}\n set position of item \"'${applicationName}'\" of container window to {100, 100}\n set position of item \"Applications\" of container window to {375, 100}\n update without registering applications\n delay 5\n close\n end tell\n end tell\n' | osascript\n</code></pre></li>\n<li><p>Finialize the DMG by setting permissions properly, compressing and releasing it:</p>\n\n<pre><code>chmod -Rf go-w /Volumes/\"${title}\"\nsync\nsync\nhdiutil detach ${device}\nhdiutil convert \"/pack.temp.dmg\" -format UDZO -imagekey zlib-level=9 -o \"${finalDMGName}\"\nrm -f /pack.temp.dmg \n</code></pre></li>\n</ol>\n\n<p>On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.:</p>\n\n<pre><code>..\nset position of item \"'${applicationName}'\" of container window to {100, 100}\nset position of item \"Applications\" of container window to {375, 100}\nclose\nopen\n</code></pre>\n" }, { "answer_id": 2635811, "author": "hor10zs", "author_id": 316281, "author_profile": "https://Stackoverflow.com/users/316281", "pm_score": 2, "selected": false, "text": "<p>.DS_Store files stores windows settings in Mac. Windows settings include the icons layout, the window background, the size of the window, etc. The .DS_Store file is needed in creating the window for mounted images to preserve the arrangement of files and the windows background.</p>\n\n<p>Once you have .DS_Store file created, you can just copy it to your created installer (DMG).</p>\n" }, { "answer_id": 3150866, "author": "Michael Tsai", "author_id": 6311, "author_profile": "https://Stackoverflow.com/users/6311", "pm_score": 4, "selected": false, "text": "<p>My app, <a href=\"http://c-command.com/dropdmg/\" rel=\"noreferrer\">DropDMG</a>, is an easy way to create disk images with background pictures, icon layouts, custom volume icons, and software license agreements. It can be controlled from a build system via the \"dropdmg\" command-line tool or AppleScript. If desired, the picture and license RTF files can be stored under your version control system.</p>\n" }, { "answer_id": 7703638, "author": "T.J. Yang", "author_id": 986350, "author_profile": "https://Stackoverflow.com/users/986350", "pm_score": 2, "selected": false, "text": "<p>I also in need of using command line approach to do the packaging and dmg creation \"programmatically in a script\". The best answer I found so far is from Adium project' Release building framework (See R1). There is a custom script(AdiumApplescriptRunner) to allow you avoid OSX WindowsServer GUI interaction. \"osascript applescript.scpt\" approach require you to login as builder and run the dmg creation from a command line vt100 session.</p>\n\n<p>OSX package management system is not so advanced compared to other Unixen which can do this task easily and systematically.</p>\n\n<p>R1: <a href=\"http://hg.adium.im/adium-1.4/file/00d944a3ef16/Release\" rel=\"nofollow\">http://hg.adium.im/adium-1.4/file/00d944a3ef16/Release</a></p>\n" }, { "answer_id": 9396368, "author": "Saurabh", "author_id": 303073, "author_profile": "https://Stackoverflow.com/users/303073", "pm_score": 3, "selected": false, "text": "<p>I found this great mac app to automate the process - <a href=\"http://www.araelium.com/dmgcanvas/\" rel=\"noreferrer\">http://www.araelium.com/dmgcanvas/</a>\nyou must have a look if you are creating dmg installer for your mac app</p>\n" }, { "answer_id": 18443866, "author": "Parag Bafna", "author_id": 944634, "author_profile": "https://Stackoverflow.com/users/944634", "pm_score": 3, "selected": false, "text": "<p>If you want to set custom volume icon then use below command</p>\n\n<pre><code>/*Add a drive icon*/\ncp \"/Volumes/customIcon.icns\" \"/Volumes/dmgName/.VolumeIcon.icns\" \n\n\n/*SetFile -c icnC will change the creator of the file to icnC*/\nSetFile -c icnC /&lt;your path&gt;/.VolumeIcon.icns\n</code></pre>\n\n<p>Now create read/write dmg</p>\n\n<pre><code>/*to set custom icon attribute*/\nSetFile -a C /Volumes/dmgName\n</code></pre>\n" }, { "answer_id": 20879598, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>These answers are way too complicated and times have changed. The following works on 10.9 just fine, permissions are correct and it looks nice.</p>\n\n<h3>Create a read-only DMG from a directory</h3>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n# create_dmg Frobulator Frobulator.dmg path/to/frobulator/dir [ 'Your Code Sign Identity' ]\nset -e\n\nVOLNAME=\"$1\"\nDMG=\"$2\"\nSRC_DIR=\"$3\"\nCODESIGN_IDENTITY=\"$4\"\n\nhdiutil create -srcfolder \"$SRC_DIR\" \\\n -volname \"$VOLNAME\" \\\n -fs HFS+ -fsargs \"-c c=64,a=16,e=16\" \\\n -format UDZO -imagekey zlib-level=9 \"$DMG\"\n\nif [ -n \"$CODESIGN_IDENTITY\" ]; then\n codesign -s \"$CODESIGN_IDENTITY\" -v \"$DMG\"\nfi\n</code></pre>\n\n<h3>Create read-only DMG with an icon (.icns type)</h3>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n# create_dmg_with_icon Frobulator Frobulator.dmg path/to/frobulator/dir path/to/someicon.icns [ 'Your Code Sign Identity' ]\nset -e\nVOLNAME=\"$1\"\nDMG=\"$2\"\nSRC_DIR=\"$3\"\nICON_FILE=\"$4\"\nCODESIGN_IDENTITY=\"$5\"\n\nTMP_DMG=\"$(mktemp -u -t XXXXXXX)\"\ntrap 'RESULT=$?; rm -f \"$TMP_DMG\"; exit $RESULT' INT QUIT TERM EXIT\nhdiutil create -srcfolder \"$SRC_DIR\" -volname \"$VOLNAME\" -fs HFS+ \\\n -fsargs \"-c c=64,a=16,e=16\" -format UDRW \"$TMP_DMG\"\nTMP_DMG=\"${TMP_DMG}.dmg\" # because OSX appends .dmg\nDEVICE=\"$(hdiutil attach -readwrite -noautoopen \"$TMP_DMG\" | awk 'NR==1{print$1}')\"\nVOLUME=\"$(mount | grep \"$DEVICE\" | sed 's/^[^ ]* on //;s/ ([^)]*)$//')\"\n# start of DMG changes\ncp \"$ICON_FILE\" \"$VOLUME/.VolumeIcon.icns\"\nSetFile -c icnC \"$VOLUME/.VolumeIcon.icns\"\nSetFile -a C \"$VOLUME\"\n# end of DMG changes\nhdiutil detach \"$DEVICE\"\nhdiutil convert \"$TMP_DMG\" -format UDZO -imagekey zlib-level=9 -o \"$DMG\"\nif [ -n \"$CODESIGN_IDENTITY\" ]; then\n codesign -s \"$CODESIGN_IDENTITY\" -v \"$DMG\"\nfi\n</code></pre>\n\n<p>If anything else needs to happen, these easiest thing is to make a temporary copy of the SRC_DIR and apply changes to that before creating a DMG.</p>\n" }, { "answer_id": 21826676, "author": "al45tair", "author_id": 346335, "author_profile": "https://Stackoverflow.com/users/346335", "pm_score": 2, "selected": false, "text": "<p>I've just written a new (friendly) command line utility to do this. It doesn’t rely on Finder/AppleScript, or on any of the (deprecated) Alias Manager APIs, and it’s easy to configure and use.</p>\n\n<p>Anyway, anyone who is interested can <a href=\"https://pypi.python.org/pypi/dmgbuild\" rel=\"nofollow\">find it on PyPi</a>; the documentation is <a href=\"http://dmgbuild.rtfd.org\" rel=\"nofollow\">available on Read The Docs</a>.</p>\n" }, { "answer_id": 28112853, "author": "Linus Unnebäck", "author_id": 148072, "author_profile": "https://Stackoverflow.com/users/148072", "pm_score": 5, "selected": false, "text": "<p>Bringing this question up to date by providing this answer.</p>\n\n<p><code>appdmg</code> is a simple, easy-to-use, open-source command line program that creates dmg-files from a simple json specification. Take a look at the readme at the official website:</p>\n\n<p><a href=\"https://github.com/LinusU/node-appdmg\">https://github.com/LinusU/node-appdmg</a></p>\n\n<p>Quick example:</p>\n\n<ol>\n<li><p>Install appdmg</p>\n\n<pre><code>npm install -g appdmg\n</code></pre></li>\n<li><p>Write a json file (<code>spec.json</code>)</p>\n\n<pre><code>{\n \"title\": \"Test Title\",\n \"background\": \"background.png\",\n \"icon-size\": 80,\n \"contents\": [\n { \"x\": 192, \"y\": 344, \"type\": \"file\", \"path\": \"TestApp.app\" },\n { \"x\": 448, \"y\": 344, \"type\": \"link\", \"path\": \"/Applications\" }\n ]\n}\n</code></pre></li>\n<li><p>Run program</p>\n\n<pre><code>appdmg spec.json test.dmg\n</code></pre></li>\n</ol>\n\n<p>(disclaimer. I'm the creator of appdmg)</p>\n" }, { "answer_id": 31619515, "author": "P.M.", "author_id": 702391, "author_profile": "https://Stackoverflow.com/users/702391", "pm_score": 2, "selected": false, "text": "<p>I finally got this working in my own project (which happens to be in Xcode). Adding these 3 scripts to your build phase will automatically create a Disk Image for your product that is nice and neat. All you have to do is build your project and the DMG will be waiting in your products folder.</p>\n\n<p>Script 1 (Create Temp Disk Image):</p>\n\n<pre><code>#!/bin/bash\n#Create a R/W DMG\n\ndir=\"$TEMP_FILES_DIR/disk\"\ndmg=\"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg\"\n\nrm -rf \"$dir\"\nmkdir \"$dir\"\ncp -R \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app\" \"$dir\"\nln -s \"/Applications\" \"$dir/Applications\"\nmkdir \"$dir/.background\"\ncp \"$PROJECT_DIR/$PROJECT_NAME/some_image.png\" \"$dir/.background\"\nrm -f \"$dmg\"\nhdiutil create \"$dmg\" -srcfolder \"$dir\" -volname \"$PRODUCT_NAME\" -format UDRW\n\n#Mount the disk image, and store the device name\nhdiutil attach \"$dmg\" -noverify -noautoopen -readwrite\n</code></pre>\n\n<p>Script 2 (Set Window Properties Script):</p>\n\n<pre><code>#!/usr/bin/osascript\n#get the dimensions of the main window using a bash script\n\nset {width, height, scale} to words of (do shell script \"system_profiler SPDisplaysDataType | awk '/Main Display: Yes/{found=1} /Resolution/{width=$2; height=$4} /Retina/{scale=($2 == \\\"Yes\\\" ? 2 : 1)} /^ {8}[^ ]+/{if(found) {exit}; scale=1} END{printf \\\"%d %d %d\\\\n\\\", width, height, scale}'\")\nset x to ((width / 2) / scale)\nset y to ((height / 2) / scale)\n\n#get the product name using a bash script\nset {product_name} to words of (do shell script \"printf \\\"%s\\\", $PRODUCT_NAME\")\nset background to alias (\"Volumes:\"&amp;product_name&amp;\":.background:some_image.png\")\n\ntell application \"Finder\"\n tell disk product_name\n open\n set current view of container window to icon view\n set toolbar visible of container window to false\n set statusbar visible of container window to false\n set the bounds of container window to {x, y, (x + 479), (y + 383)}\n set theViewOptions to the icon view options of container window\n set arrangement of theViewOptions to not arranged\n set icon size of theViewOptions to 128\n set background picture of theViewOptions to background\n set position of item (product_name &amp; \".app\") of container window to {100, 225}\n set position of item \"Applications\" of container window to {375, 225}\n update without registering applications\n close\n end tell\nend tell\n</code></pre>\n\n<p>The above measurement for the window work for my project specifically due to the size of my background pic and icon resolution; you may need to modify these values for your own project.</p>\n\n<p>Script 3 (Make Final Disk Image Script):</p>\n\n<pre><code>#!/bin/bash\ndir=\"$TEMP_FILES_DIR/disk\"\ncp \"$PROJECT_DIR/$PROJECT_NAME/some_other_image.png\" \"$dir/\"\n\n#unmount the temp image file, then convert it to final image file\nsync\nsync\nhdiutil detach /Volumes/$PRODUCT_NAME\nrm -f \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\nhdiutil convert \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg\" -format UDZO -imagekey zlib-level=9 -o \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\nrm -f \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg\"\n\n#Change the icon of the image file\nsips -i \"$dir/some_other_image.png\"\nDeRez -only icns \"$dir/some_other_image.png\" &gt; \"$dir/tmpicns.rsrc\"\nRez -append \"$dir/tmpicns.rsrc\" -o \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\nSetFile -a C \"$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg\"\n\nrm -rf \"$dir\"\n</code></pre>\n\n<p>Make sure the image files you are using are in the $PROJECT_DIR/$PROJECT_NAME/ directory!</p>\n" }, { "answer_id": 34381427, "author": "Anni S", "author_id": 843266, "author_profile": "https://Stackoverflow.com/users/843266", "pm_score": 3, "selected": false, "text": "<p>For creating a nice looking DMG, you can now just use some well written open sources:</p>\n\n<ul>\n<li><a href=\"https://github.com/andreyvit/create-dmg\" rel=\"noreferrer\">create-dmg</a></li>\n<li><a href=\"https://github.com/LinusU/node-appdmg\" rel=\"noreferrer\">node-appdmg</a></li>\n<li><a href=\"https://pypi.python.org/pypi/dmgbuild\" rel=\"noreferrer\">dmgbuild</a></li>\n</ul>\n" }, { "answer_id": 67092989, "author": "mmerle", "author_id": 10983525, "author_profile": "https://Stackoverflow.com/users/10983525", "pm_score": 2, "selected": false, "text": "<p>I used <a href=\"https://pypi.org/project/dmgbuild/\" rel=\"nofollow noreferrer\">dmgbuild</a>.</p>\n<ul>\n<li>Installation: <code>pip3 install dmgbuild</code></li>\n<li>Mount your volume</li>\n<li>Create a settings file:</li>\n</ul>\n<pre class=\"lang-json prettyprint-override\"><code>{\n &quot;title&quot;: &quot;NAME&quot;,\n &quot;background&quot;: &quot;YOUR_BACKGROUND.png&quot;,\n &quot;format&quot;: &quot;UDZO&quot;,\n &quot;compression-level&quot;: 9,\n &quot;window&quot;: { &quot;position&quot;: { &quot;x&quot;: 100, &quot;y&quot;: 100 },\n &quot;size&quot;: { &quot;width&quot;: 640, &quot;height&quot;: 300 } },\n &quot;contents&quot;: [\n { &quot;x&quot;: 140, &quot;y&quot;: 165, &quot;type&quot;: &quot;file&quot;, &quot;path&quot;: &quot;/Volumes/YOUR_VOLUME_NAME/YOUR_APP.app&quot; },\n { &quot;x&quot;: 480, &quot;y&quot;: 165, &quot;type&quot;: &quot;link&quot;, &quot;path&quot;: &quot;/Applications&quot; }\n ]\n}\n</code></pre>\n<ul>\n<li><p>The width value is the width of the background.</p>\n</li>\n<li><p>The height value should be the background height + 20 for the window bar.</p>\n</li>\n<li><p>In a terminal: <code>dmgbuild -s settings.json &quot;YOUR_VOLUME_NAME&quot; output.dmg</code></p>\n</li>\n</ul>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16909/" ]
I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image. I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately). I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.
After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference: 1. Make sure that "Enable access for assistive devices" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4). 2. Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable "size" contains the size in Kb and the contents of the folder in the "source" bash variable will be copied into the DMG: ``` hdiutil create -srcfolder "${source}" -volname "${title}" -fs HFS+ \ -fsargs "-c c=64,a=16,e=16" -format UDRW -size ${size}k pack.temp.dmg ``` 3. Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation): ``` device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \ egrep '^/dev/' | sed 1q | awk '{print $1}') ``` 4. Store the background picture (in PNG format) in a folder called ".background" in the DMG, and store its name in the "backgroundPictureName" variable. 5. Use AppleScript to set the visual styles (name of .app must be in bash variable "applicationName", use variables for the other properties as needed): ``` echo ' tell application "Finder" tell disk "'${title}'" open set current view of container window to icon view set toolbar visible of container window to false set statusbar visible of container window to false set the bounds of container window to {400, 100, 885, 430} set theViewOptions to the icon view options of container window set arrangement of theViewOptions to not arranged set icon size of theViewOptions to 72 set background picture of theViewOptions to file ".background:'${backgroundPictureName}'" make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"} set position of item "'${applicationName}'" of container window to {100, 100} set position of item "Applications" of container window to {375, 100} update without registering applications delay 5 close end tell end tell ' | osascript ``` 6. Finialize the DMG by setting permissions properly, compressing and releasing it: ``` chmod -Rf go-w /Volumes/"${title}" sync sync hdiutil detach ${device} hdiutil convert "/pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${finalDMGName}" rm -f /pack.temp.dmg ``` On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.: ``` .. set position of item "'${applicationName}'" of container window to {100, 100} set position of item "Applications" of container window to {375, 100} close open ```
96,922
<p>The standard answer is that it's useful when you only need to write a few lines of code ...</p> <p>I have both languages integrated inside of Eclipse. Because Eclipse handles the compiling, interpreting, running etc. both "run" exactly the same.</p> <p>The Eclipse IDE for both is similar - instant "compilation", intellisense etc. Both allow the use of the Debug perspective.</p> <p>If I want to test a few lines of Java, I don't have to create a whole new Java project - I just use the <a href="http://www.eclipsezone.com/eclipse/forums/t61137.html" rel="noreferrer">Scrapbook</a> feature inside Eclipse which which allows me to <em>"execute Java expressions without having to create a new Java program. This is a neat way to quickly test an existing class or evaluate a code snippet"</em>. </p> <p>Jython allows the use of the Java libraries - but then so (by definition) does Java!</p> <p>So what other benefits does Jython offer?</p>
[ { "answer_id": 96934, "author": "Lucas S.", "author_id": 7363, "author_profile": "https://Stackoverflow.com/users/7363", "pm_score": 0, "selected": false, "text": "<p>Syntax sugar.</p>\n" }, { "answer_id": 96935, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": false, "text": "<p>Python syntax (used by Jython) is considerably more concise and quicker to develop for many programmers.</p>\n\n<p>In addition, you can use existing Python libraries in a Java application.</p>\n" }, { "answer_id": 96941, "author": "typicalrunt", "author_id": 13996, "author_profile": "https://Stackoverflow.com/users/13996", "pm_score": 1, "selected": false, "text": "<p>No need to compile. Maybe you want to get something rolling faster than using a compiled language, like a prototype.</p>\n\n<p>...and you can embed the Jython interpreter into your apps. Nice feature, I can't say I've used it, but tis cool nonetheless.</p>\n" }, { "answer_id": 96954, "author": "Frank Pape", "author_id": 10367, "author_profile": "https://Stackoverflow.com/users/10367", "pm_score": 0, "selected": false, "text": "<p>In your situation, it doesn't make much sense. But that doesn't mean it never does. For example, if you are developing a product that allows end users to create extensions or plugins, it might be nice for that to be scriptable.</p>\n" }, { "answer_id": 96988, "author": "sumek", "author_id": 11439, "author_profile": "https://Stackoverflow.com/users/11439", "pm_score": 2, "selected": false, "text": "<p>Python libraries ;) For example <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a> - an HTML parser that accepts incorrect markup. AFAIK there is no similar pure Java lib.</p>\n" }, { "answer_id": 97069, "author": "toluju", "author_id": 12457, "author_profile": "https://Stackoverflow.com/users/12457", "pm_score": 2, "selected": false, "text": "<p>Python has some features of functional programming, such as lambdas. Java does not have such functionality, and some programs would be considerably easier to write if such support was available. Thus it is sometimes easier to write the code in Python and integrate it via Jython that to attempt to write the code in Java.</p>\n" }, { "answer_id": 97359, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 2, "selected": false, "text": "<p>Some tasks are easier in some languages then others. If I had to parse some file, I'd choose Python over Java in a blink.</p>\n" }, { "answer_id": 97382, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 2, "selected": false, "text": "<p>Using Python is more than \"syntactic sugar\" unless you <em>enjoy</em> writing (or having your IDE generate) hundreds of lines of boiler plate code. There's the advantage of Rapid Development techniques when using dynamically typed languages, though the disadvantage is that it complicates your API and integration because you no longer have a homogeneous codebase. This can also affect maintenance because not everybody on your team loves Python as much as you and won't be as efficient with it. That can be a problem.</p>\n" }, { "answer_id": 97466, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 1, "selected": false, "text": "<p>Jython can also be used as an embedded scripting language within a Java program. You may find it useful at some point to write something with a built in extension language. If working with Java Jython is an option for this (Groovy is another). </p>\n\n<p>I have mainly used Jython for exploratory programming on Java systems. I could import parts of the application and poke around the API to see what happened by invoking calls from an interactive Jython session.</p>\n" }, { "answer_id": 97540, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 5, "selected": false, "text": "<p>A quick example (from <a href=\"http://coreygoldberg.blogspot.com/2008/09/python-vs-java-http-get-request.html\" rel=\"noreferrer\">http://coreygoldberg.blogspot.com/2008/09/python-vs-java-http-get-request.html</a>) : </p>\n\n<p>You have a back end in Java, and you need to perform HTTP GET resquests.</p>\n\n<p>Natively :</p>\n\n<pre><code>import java.net.*;\nimport java.io.*;\n\npublic class JGet {\n public static void main (String[] args) throws IOException {\n try {\n URL url = new URL(\"http://www.google.com\");\n\n BufferedReader in = \n new BufferedReader(new InputStreamReader(url.openStream()));\n String str;\n\n while ((str = in.readLine()) != null) {\n System.out.println(str);\n }\n\n in.close();\n } \n catch (MalformedURLException e) {} \n catch (IOException e) {}\n }\n}\n</code></pre>\n\n<p>In Python :</p>\n\n<pre><code>import urllib\nprint urllib.urlopen('http://www.google.com').read()\n</code></pre>\n\n<p>Jython allows you to use the java robustness and when needed, the Python clarity.</p>\n\n<p>What else ? As Georges would say...</p>\n" }, { "answer_id": 98229, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 3, "selected": false, "text": "<p>I use Jython for <em>interactive</em> testing of Java code. This is often much faster than writing Java test applications or even any scripting language. I can just play with the methods and see how it reacts. From there I can learn enough to go and write some real code or test cases. </p>\n" }, { "answer_id": 99157, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 0, "selected": false, "text": "<p>Porting existing code to a new environment may be one reason. Some of your business logic and domain functionality may exist in Python, and the group that writes that code insists on using Python. But the group that deploys and maintains it may want the managability of a J2EE cluster for the scale. You can wrap the logic in Jython in a EAR/WAR and then the deployment group is just seeing another J2EE bundle to be managed like all the other J2EE bundles.</p>\n\n<p>i.e. it is a means to deal with an impedance mismatch.</p>\n" }, { "answer_id": 344882, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 3, "selected": false, "text": "<p>Analogy: Why drink coffee when you can instead drink hot tap water and chew on roasted bitter beans. :-)</p>\n\n<p>For some tasks, Python just tastes better, works better, and is fast enough (takes time to brew?). If your programming or deployment environment is focused on the JVM, Jython lets you code Python but without changing your deployment and runtime enviroment.</p>\n" }, { "answer_id": 6103093, "author": "mike rodent", "author_id": 595305, "author_profile": "https://Stackoverflow.com/users/595305", "pm_score": 3, "selected": false, "text": "<p>I've just discovered Jython and, as a bit of a linguist, I think I'd say it's a bit like asking \"why use Latin when you can use French\" (forgetting about the fact that Latin came before French, of course).</p>\n\n<p>Different human languages actually make you think in different ways. French is a great language, I've lived in France a long time and done a degree in it. But Latin's startling power and concision puts your mind into a different zone, where word order can be swapped around to produce all sorts of subtle effects, for example.</p>\n\n<p>I think, from my cursory acquaintance with Jython, which has really fired up my enthusiasm by the way, that it's going to make me think in different ways. I was very sceptical about Python/Jython for some time, and have been a big fan of Java generics for example (which ironically reduce the amount of typing and therefore \"latinise\" the French if you like). I don't quite understand the full implications of \"dynamically typed\" languages like Jython, but I think the best thing is to go with the flow and see what Jython does to my mind!</p>\n\n<p>It's funny how languages come and go. Another \"Latin\" might be considered to be Algol68 with its infinitely recursive syntax. But the need to develop massively recursive code, and the capacity to read it and think in it, has not (yet) made itself felt. Jython <em>seems</em> to be a very powerful and elegant fit with where we are now, with OO libraries, the power of Java swing, and everything wrapped up in a very elegant bundle. Maybe one day Jython will adopt infinitely recursive syntax too?</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9922/" ]
The standard answer is that it's useful when you only need to write a few lines of code ... I have both languages integrated inside of Eclipse. Because Eclipse handles the compiling, interpreting, running etc. both "run" exactly the same. The Eclipse IDE for both is similar - instant "compilation", intellisense etc. Both allow the use of the Debug perspective. If I want to test a few lines of Java, I don't have to create a whole new Java project - I just use the [Scrapbook](http://www.eclipsezone.com/eclipse/forums/t61137.html) feature inside Eclipse which which allows me to *"execute Java expressions without having to create a new Java program. This is a neat way to quickly test an existing class or evaluate a code snippet"*. Jython allows the use of the Java libraries - but then so (by definition) does Java! So what other benefits does Jython offer?
A quick example (from <http://coreygoldberg.blogspot.com/2008/09/python-vs-java-http-get-request.html>) : You have a back end in Java, and you need to perform HTTP GET resquests. Natively : ``` import java.net.*; import java.io.*; public class JGet { public static void main (String[] args) throws IOException { try { URL url = new URL("http://www.google.com"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (MalformedURLException e) {} catch (IOException e) {} } } ``` In Python : ``` import urllib print urllib.urlopen('http://www.google.com').read() ``` Jython allows you to use the java robustness and when needed, the Python clarity. What else ? As Georges would say...
96,923
<p>What's the name of the circled UI element here? And how do I access it using keyboard shortcuts? Sometimes it's nearly impossible to get the mouse to focus on it.</p> <pre><code>catch (ItemNotFoundException e) { } </code></pre>
[ { "answer_id": 96937, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 4, "selected": true, "text": "<p>I don't know the name, but the shortcuts are CTRL-period (.) and ALT-SHIFT-F10. Handy to know :)</p>\n" }, { "answer_id": 96943, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "<p>It's called a SmartTag</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15050/" ]
What's the name of the circled UI element here? And how do I access it using keyboard shortcuts? Sometimes it's nearly impossible to get the mouse to focus on it. ``` catch (ItemNotFoundException e) { } ```
I don't know the name, but the shortcuts are CTRL-period (.) and ALT-SHIFT-F10. Handy to know :)
96,945
<p>I am using Oracle 9 and JDBC and would like to encyrpt a clob as it is inserted into the DB. Ideally I'd like to be able to just insert the plaintext and have it encrypted by a stored procedure:</p> <pre><code>String SQL = "INSERT INTO table (ID, VALUE) values (?, encrypt(?))"; PreparedStatement ps = connection.prepareStatement(SQL); ps.setInt(id); ps.setString(plaintext); ps.executeUpdate(); </code></pre> <p>The plaintext is not expected to exceed 4000 characters but encrypting makes text longer. Our current approach to encryption uses dbms_obfuscation_toolkit.DESEncrypt() but we only process varchars. Will the following work?</p> <pre><code>FUNCTION encrypt(p_clob IN CLOB) RETURN CLOB IS encrypted_string CLOB; v_string CLOB; BEGIN dbms_lob.createtemporary(encrypted_string, TRUE); v_string := p_clob; dbms_obfuscation_toolkit.DESEncrypt( input_string =&gt; v_string, key_string =&gt; key_string, encrypted_string =&gt; encrypted_string ); RETURN UTL_RAW.CAST_TO_RAW(encrypted_string); END; </code></pre> <p>I'm confused about the temporary clob; do I need to close it? Or am I totally off-track?</p> <p>Edit: The purpose of the obfuscation is to prevent trivial access to the data. My other purpose is to obfuscate clobs in the same way that we are already obfuscating the varchar columns. The oracle sample code does not deal with clobs which is where my specific problem lies; encrypting varchars (smaller than 2000 chars) is straightforward.</p>
[ { "answer_id": 97469, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 2, "selected": false, "text": "<p>There is an example in Oracle Documentation:</p>\n\n<p><a href=\"http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96612/d_obtoo2.htm\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96612/d_obtoo2.htm</a></p>\n\n<p>You do not need to close it</p>\n\n<pre><code>DECLARE\n input_string VARCHAR2(16) := 'tigertigertigert';\n raw_input RAW(128) := UTL_RAW.CAST_TO_RAW(input_string);\n key_string VARCHAR2(8) := 'scottsco';\n raw_key RAW(128) := UTL_RAW.CAST_TO_RAW(key_string);\n encrypted_raw RAW(2048);\n encrypted_string VARCHAR2(2048);\n decrypted_raw RAW(2048);\n decrypted_string VARCHAR2(2048); \n error_in_input_buffer_length EXCEPTION;\n PRAGMA EXCEPTION_INIT(error_in_input_buffer_length, -28232);\n INPUT_BUFFER_LENGTH_ERR_MSG VARCHAR2(100) :=\n '*** DES INPUT BUFFER NOT A MULTIPLE OF 8 BYTES - IGNORING \nEXCEPTION ***';\n double_encrypt_not_permitted EXCEPTION;\n PRAGMA EXCEPTION_INIT(double_encrypt_not_permitted, -28233);\n DOUBLE_ENCRYPTION_ERR_MSG VARCHAR2(100) :=\n '*** CANNOT DOUBLE ENCRYPT DATA - IGNORING EXCEPTION ***';\n\n -- 1. Begin testing raw data encryption and decryption\n BEGIN\n dbms_output.put_line('&gt; ========= BEGIN TEST RAW DATA =========');\n dbms_output.put_line('&gt; Raw input : ' || \n UTL_RAW.CAST_TO_VARCHAR2(raw_input));\n BEGIN \n dbms_obfuscation_toolkit.DESEncrypt(input =&gt; raw_input, \n key =&gt; raw_key, encrypted_data =&gt; encrypted_raw );\n dbms_output.put_line('&gt; encrypted hex value : ' || \n rawtohex(encrypted_raw));\n dbms_obfuscation_toolkit.DESDecrypt(input =&gt; encrypted_raw, \n key =&gt; raw_key, decrypted_data =&gt; decrypted_raw);\n dbms_output.put_line('&gt; Decrypted raw output : ' || \n UTL_RAW.CAST_TO_VARCHAR2(decrypted_raw));\n dbms_output.put_line('&gt; '); \n if UTL_RAW.CAST_TO_VARCHAR2(raw_input) = \n UTL_RAW.CAST_TO_VARCHAR2(decrypted_raw) THEN\n dbms_output.put_line('&gt; Raw DES Encyption and Decryption successful');\n END if;\n EXCEPTION\n WHEN error_in_input_buffer_length THEN\n dbms_output.put_line('&gt; ' || INPUT_BUFFER_LENGTH_ERR_MSG);\n END;\n dbms_output.put_line('&gt; ');\n</code></pre>\n" }, { "answer_id": 100713, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>Slightly off-topic: What's the point of the encryption/obfuscation in the first place? An attacker having access to your database will be able to obtain the plaintext -- finding the above stored procedure will enable the attacker to perform the decryption.</p>\n" }, { "answer_id": 113291, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 1, "selected": true, "text": "<p>I note you are on Oracle 9, but just for the record in Oracle 10g+ the dbms_obfuscation_toolkit was deprecated in favour of dbms_crypto.</p>\n\n<p><a href=\"http://68.142.116.68/docs/cd/B28359_01/appdev.111/b28419/d_crypto.htm#i1005082\" rel=\"nofollow noreferrer\">dbms_crypto</a> does include CLOB support:</p>\n\n<pre><code>DBMS_CRYPTO.ENCRYPT(\n dst IN OUT NOCOPY BLOB,\n src IN CLOB CHARACTER SET ANY_CS,\n typ IN PLS_INTEGER,\n key IN RAW,\n iv IN RAW DEFAULT NULL);\n\nDBMS_CRYPT.DECRYPT(\n dst IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,\n src IN BLOB,\n typ IN PLS_INTEGER,\n key IN RAW,\n iv IN RAW DEFAULT NULL);\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867/" ]
I am using Oracle 9 and JDBC and would like to encyrpt a clob as it is inserted into the DB. Ideally I'd like to be able to just insert the plaintext and have it encrypted by a stored procedure: ``` String SQL = "INSERT INTO table (ID, VALUE) values (?, encrypt(?))"; PreparedStatement ps = connection.prepareStatement(SQL); ps.setInt(id); ps.setString(plaintext); ps.executeUpdate(); ``` The plaintext is not expected to exceed 4000 characters but encrypting makes text longer. Our current approach to encryption uses dbms\_obfuscation\_toolkit.DESEncrypt() but we only process varchars. Will the following work? ``` FUNCTION encrypt(p_clob IN CLOB) RETURN CLOB IS encrypted_string CLOB; v_string CLOB; BEGIN dbms_lob.createtemporary(encrypted_string, TRUE); v_string := p_clob; dbms_obfuscation_toolkit.DESEncrypt( input_string => v_string, key_string => key_string, encrypted_string => encrypted_string ); RETURN UTL_RAW.CAST_TO_RAW(encrypted_string); END; ``` I'm confused about the temporary clob; do I need to close it? Or am I totally off-track? Edit: The purpose of the obfuscation is to prevent trivial access to the data. My other purpose is to obfuscate clobs in the same way that we are already obfuscating the varchar columns. The oracle sample code does not deal with clobs which is where my specific problem lies; encrypting varchars (smaller than 2000 chars) is straightforward.
I note you are on Oracle 9, but just for the record in Oracle 10g+ the dbms\_obfuscation\_toolkit was deprecated in favour of dbms\_crypto. [dbms\_crypto](http://68.142.116.68/docs/cd/B28359_01/appdev.111/b28419/d_crypto.htm#i1005082) does include CLOB support: ``` DBMS_CRYPTO.ENCRYPT( dst IN OUT NOCOPY BLOB, src IN CLOB CHARACTER SET ANY_CS, typ IN PLS_INTEGER, key IN RAW, iv IN RAW DEFAULT NULL); DBMS_CRYPT.DECRYPT( dst IN OUT NOCOPY CLOB CHARACTER SET ANY_CS, src IN BLOB, typ IN PLS_INTEGER, key IN RAW, iv IN RAW DEFAULT NULL); ```
96,952
<p>What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field? </p> <p>Field with value "00345ABC" would need to return "345ABC".</p>
[ { "answer_id": 96971, "author": "Chris Bartow", "author_id": 497, "author_profile": "https://Stackoverflow.com/users/497", "pm_score": 8, "selected": true, "text": "<p>You are looking for the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim\" rel=\"noreferrer\">trim() function</a>.</p>\n\n<p>Alright, here is your example</p>\n\n<pre><code>SELECT TRIM(LEADING '0' FROM myfield) FROM table\n</code></pre>\n" }, { "answer_id": 96992, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 3, "selected": false, "text": "<p>I believe you'd be best off with this:</p>\n\n<pre><code>SELECT TRIM(LEADING '0' FROM myField)\n</code></pre>\n" }, { "answer_id": 1247202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>simply perfect:</p>\n\n<pre><code>SELECT TRIM(LEADING '0' FROM myfield) FROM table\n</code></pre>\n" }, { "answer_id": 10829460, "author": "Hemali", "author_id": 1427809, "author_profile": "https://Stackoverflow.com/users/1427809", "pm_score": 2, "selected": false, "text": "<p>just remove space between <code>TRIM ( LEADING</code> \nuse </p>\n\n<pre><code>SELECT * FROM my_table WHERE TRIM(LEADING '0' FROM accountid ) = '00322994' \n</code></pre>\n" }, { "answer_id": 14157004, "author": "lubosdz", "author_id": 1485984, "author_profile": "https://Stackoverflow.com/users/1485984", "pm_score": 4, "selected": false, "text": "<p>TIP:</p>\n\n<p>If your values are purely numerical, you can also use simple casting, e.g. </p>\n\n<pre><code>SELECT * FROM my_table WHERE accountid = '00322994' * 1\n</code></pre>\n\n<p>will actually convert into </p>\n\n<pre><code>SELECT * FROM my_table WHERE accountid = 322994\n</code></pre>\n\n<p>which is sufficient solution in many cases and also I believe is performance more effective. (warning - value type changes from STRING to INT/FLOAT).</p>\n\n<p>In some situations, using some casting function might be also a way to go:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html\">http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html</a></p>\n" }, { "answer_id": 35144965, "author": "theBuzzyCoder", "author_id": 2147023, "author_profile": "https://Stackoverflow.com/users/2147023", "pm_score": 4, "selected": false, "text": "<p>If you want to update one entire column of a table, you can use</p>\n\n<pre><code>USE database_name;\nUPDATE `table_name` SET `field` = TRIM(LEADING '0' FROM `field`) WHERE `field` LIKE '0%';\n</code></pre>\n" }, { "answer_id": 40980354, "author": "cacti5", "author_id": 5839007, "author_profile": "https://Stackoverflow.com/users/5839007", "pm_score": 2, "selected": false, "text": "<p>TRIM will allow you to remove the trailing, leading or all characters. Some examples on the use of the TRIM function in MySQL:</p>\n\n<pre><code>select trim(myfield) from (select ' test' myfield) t;\n&gt;&gt; 'test'\nselect trim('0' from myfield) from (select '000000123000' myfield) t;\n&gt;&gt; '123'\nselect trim(both '0' from myfield) from (select '000000123000' myfield) t;\n&gt;&gt; '123'\nselect trim(leading '0' from myfield) from (select '000000123000' myfield) t;\n&gt;&gt; '123000'\nselect trim(trailing '0' from myfield) from (select '000000123000' myfield) t;\n&gt;&gt; '000000123'\n</code></pre>\n\n<p>If you want to remove only a select amount of leading/trailing characters, look into the LEFT/RIGHT functions, with combination of the LEN and INSTR functions</p>\n" }, { "answer_id": 49064319, "author": "sanduniYW", "author_id": 9373268, "author_profile": "https://Stackoverflow.com/users/9373268", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT TRIM(LEADING '0' FROM *columnName*) FROM *tableName* ;\n</code></pre>\n\n<p>This also work correctly</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5446/" ]
What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field? Field with value "00345ABC" would need to return "345ABC".
You are looking for the [trim() function](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim). Alright, here is your example ``` SELECT TRIM(LEADING '0' FROM myfield) FROM table ```
97,013
<p>Does anyone know is there a way to open a project in Eclipse in read-only mode? If there is a lot of similar projects open it is easy to make changes to a wrong one.</p>
[ { "answer_id": 97047, "author": "Martin OConnor", "author_id": 18233, "author_profile": "https://Stackoverflow.com/users/18233", "pm_score": 2, "selected": false, "text": "<p>One sub-optimal solution is to make the project directory read-only in the file system in the underlying OS. I'm not sure how eclipse will react though.</p>\n" }, { "answer_id": 121612, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": -1, "selected": false, "text": "<p>You can also use the close project/open project feature : close all projects and only open the one you need to work on ?</p>\n" }, { "answer_id": 1272994, "author": "wires", "author_id": 72787, "author_profile": "https://Stackoverflow.com/users/72787", "pm_score": 2, "selected": false, "text": "<p>This feature is called \"binary projects\" and is provided by the eclipse plug-in developement environment (PDE). Note that this only works for eclipse plug-in project, see</p>\n\n<p><a href=\"http://books.google.com/books?id=0X6wZRd5OOQC&amp;pg=PA11&amp;lpg=PA11\" rel=\"nofollow noreferrer\">Contributing to Eclipse - Principles, patterns and plug-ins</a></p>\n\n<p>or</p>\n\n<p><a href=\"http://www.vogella.de/articles/EclipseCodeAccess/article.html#importplugins_binary\" rel=\"nofollow noreferrer\">http://www.vogella.de/articles/EclipseCodeAccess/article.html#importplugins_binary</a></p>\n" }, { "answer_id": 2304667, "author": "s3m3n", "author_id": 277937, "author_profile": "https://Stackoverflow.com/users/277937", "pm_score": 3, "selected": false, "text": "<p>Putting project in read-only mode is really useful, when you make another instance from the previous project. So you copy all files from old project, then make changes in the new instance. It's really simple to edit files from old project by mistake (they have the same names)!</p>\n\n<p>Serg if you use linux, I suggest to put all files in read only mode with chmod in terminal:</p>\n\n<pre><code>sudo chmod 444 -R /path/to/your/project\n</code></pre>\n\n<p>After this operation Eclipse will tell you that file you are trying to edit is in read-only mode. I think that's enough to make the previous project safe :)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
Does anyone know is there a way to open a project in Eclipse in read-only mode? If there is a lot of similar projects open it is easy to make changes to a wrong one.
Putting project in read-only mode is really useful, when you make another instance from the previous project. So you copy all files from old project, then make changes in the new instance. It's really simple to edit files from old project by mistake (they have the same names)! Serg if you use linux, I suggest to put all files in read only mode with chmod in terminal: ``` sudo chmod 444 -R /path/to/your/project ``` After this operation Eclipse will tell you that file you are trying to edit is in read-only mode. I think that's enough to make the previous project safe :)
97,050
<p>Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted?</p>
[ { "answer_id": 97076, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 3, "selected": false, "text": "<p>There will be barely any difference in speed between the 2, find will return an iterator, insert does the same and will search the map anyway to determine if the entry already exists.</p>\n\n<p>So.. its down to personal preference. I always try insert and then update if necessary, but some people don't like handling the pair that is returned.</p>\n" }, { "answer_id": 97094, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>map[ key ] - let stl sort it out. That's communicating your intention most effectively.</p>\n\n<p>Yeah, fair enough. </p>\n\n<p>If you do a find and then an insert you're performing 2 x O(log N) when you get a miss as the find only lets you know if you need to insert not where the insert should go (lower_bound might help you there). Just a straight insert and then examining the result is the way that I'd go.</p>\n" }, { "answer_id": 97109, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": -1, "selected": false, "text": "<p>Any answers about efficiency will depend on the exact implementation of your STL. The only way to know for sure is to benchmark it both ways. I'd guess that the difference is unlikely to be significant, so decide based on the style you prefer.</p>\n" }, { "answer_id": 97144, "author": "PiNoYBoY82", "author_id": 13646, "author_profile": "https://Stackoverflow.com/users/13646", "pm_score": 3, "selected": false, "text": "<p>I would think if you do a find then insert, the extra cost would be when you don't find the key and performing the insert after. It's sort of like looking through books in alphabetical order and not finding the book, then looking through the books again to see where to insert it. It boils down to how you will be handling the keys and if they are constantly changing. Now there is some flexibility in that if you don't find it, you can log, exception, do whatever you want...</p>\n" }, { "answer_id": 97162, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 1, "selected": false, "text": "<p>If you are concerned about efficiency, you may want to check out <a href=\"http://www.sgi.com/tech/stl/hash_map.html\" rel=\"nofollow noreferrer\">hash_map&lt;></a>. </p>\n\n<p>Typically map&lt;> is implemented as a binary tree. Depending on your needs, a hash_map may be more efficient.</p>\n" }, { "answer_id": 101129, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 4, "selected": false, "text": "<p>The answer to this question also depends on how expensive it is to create the value type you're storing in the map:</p>\n<pre><code>typedef std::map &lt;int, int&gt; MapOfInts;\ntypedef std::pair &lt;MapOfInts::iterator, bool&gt; IResult;\n\nvoid foo (MapOfInts &amp; m, int k, int v) {\n IResult ir = m.insert (std::make_pair (k, v));\n if (ir.second) {\n // insertion took place (ie. new entry)\n }\n else if ( replaceEntry ( ir.first-&gt;first ) ) {\n ir.first-&gt;second = v;\n }\n}\n</code></pre>\n<p>For a value type such as an int, the above will more efficient than a find followed by an insert (in the absence of compiler optimizations). As stated above, this is because the search through the map only takes place once.</p>\n<p>However, the call to insert requires that you already have the new &quot;value&quot; constructed:</p>\n<pre><code>class LargeDataType { /* ... */ };\ntypedef std::map &lt;int, LargeDataType&gt; MapOfLargeDataType;\ntypedef std::pair &lt;MapOfLargeDataType::iterator, bool&gt; IResult;\n\nvoid foo (MapOfLargeDataType &amp; m, int k) {\n\n // This call is more expensive than a find through the map:\n LargeDataType const &amp; v = VeryExpensiveCall ( /* ... */ );\n\n IResult ir = m.insert (std::make_pair (k, v));\n if (ir.second) {\n // insertion took place (ie. new entry)\n }\n else if ( replaceEntry ( ir.first-&gt;first ) ) {\n ir.first-&gt;second = v;\n }\n}\n</code></pre>\n<p>In order to call 'insert' we are paying for the expensive call to construct our value type - and from what you said in the question you won't use this new value 20% of the time. In the above case, if changing the map value type is not an option then it is more efficient to first perform the 'find' to check if we need to construct the element.</p>\n<p>Alternatively, the value type of the map can be changed to store handles to the data using your favourite smart pointer type. The call to insert uses a null pointer (very cheap to construct) and only if necessary is the new data type constructed.</p>\n" }, { "answer_id": 101980, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 8, "selected": true, "text": "<p>The answer is you do neither. Instead you want to do something suggested by Item 24 of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201749629\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective STL</a> by <a href=\"http://www.aristeia.com/\" rel=\"noreferrer\">Scott Meyers</a>:</p>\n\n<pre><code>typedef map&lt;int, int&gt; MapType; // Your map type may vary, just change the typedef\n\nMapType mymap;\n// Add elements to map here\nint k = 4; // assume we're searching for keys equal to 4\nint v = 0; // assume we want the value 0 associated with the key of 4\n\nMapType::iterator lb = mymap.lower_bound(k);\n\nif(lb != mymap.end() &amp;&amp; !(mymap.key_comp()(k, lb-&gt;first)))\n{\n // key already exists\n // update lb-&gt;second if you care to\n}\nelse\n{\n // the key does not exist in the map\n // add it to the map\n mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert,\n // so it can avoid another lookup\n}\n</code></pre>\n" }, { "answer_id": 6855016, "author": "Stonky", "author_id": 465489, "author_profile": "https://Stackoverflow.com/users/465489", "pm_score": 0, "selected": false, "text": "<p>I don't seem to have enough points to leave a comment, but the ticked answer seems to be long winded to me - when you consider that insert returns the iterator anyway, why go searching lower_bound, when you can just use the iterator returned. Strange.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16496/" ]
Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted?
The answer is you do neither. Instead you want to do something suggested by Item 24 of [Effective STL](https://rads.stackoverflow.com/amzn/click/com/0201749629) by [Scott Meyers](http://www.aristeia.com/): ``` typedef map<int, int> MapType; // Your map type may vary, just change the typedef MapType mymap; // Add elements to map here int k = 4; // assume we're searching for keys equal to 4 int v = 0; // assume we want the value 0 associated with the key of 4 MapType::iterator lb = mymap.lower_bound(k); if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first))) { // key already exists // update lb->second if you care to } else { // the key does not exist in the map // add it to the map mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert, // so it can avoid another lookup } ```
97,081
<p>Someone told me about a C++ style difference in their team. I have my own viewpoint on the subject, but I would be interested by <em>pros</em> and <em>cons</em> coming from everyone.</p> <p>So, in case you have a class property you want to expose via two getters, one read/write, and the other, readonly (i.e. there is no set method). There are at least two ways of doing it:</p> <pre><code>class T ; class MethodA { public : const T &amp; get() const ; T &amp; get() ; // etc. } ; class MethodB { public : const T &amp; getAsConst() const ; T &amp; get() ; // etc. } ; </code></pre> <p>What would be the pros and the cons of each method?</p> <p>I am interested more by C++ technical/semantic reasons, but style reasons are welcome, too.</p> <p>Note that <code>MethodB</code> has one major technical drawback (hint: in generic code).</p>
[ { "answer_id": 97117, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>While it appears your question only addresses one method, I'd be happy to give my input on style. Personally, for style reasons, I prefer the former. Most IDEs will pop up the type signature of functions for you.</p>\n" }, { "answer_id": 97141, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>C++ should be perfectly capable to cope with method A in almost all situations. I always use it, and I never had a problem.</p>\n\n<p>Method B is, in my opinion, a case of violation of OnceAndOnlyOnce. And, now you need to go figure out whether you're dealing with const reference to write the code that compiles first time.</p>\n\n<p>I guess this is a stylistic thing - technically they both works, but MethodA makes the compiler to work a bit harder. To me, it's a good thing.</p>\n" }, { "answer_id": 97153, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 0, "selected": false, "text": "<p>I would prefer the first. It looks better in code when two things that essentially do the same thing look the same. Also, it is rare for you to have a non-const object but want to call the const method, so that isn't much of a consern (and in the worst case, you'd only need a const_cast&lt;>).</p>\n" }, { "answer_id": 97158, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 2, "selected": false, "text": "<p>Personally, I prefer the first method, because it makes for a more consistent interface. Also, to me getAsConst() sounds just about as silly as getAsInt(). </p>\n\n<p>On a different note, you really should think twice before returning a non-const reference or a non-const pointer to a data member of your class. This is an invitation for people to exploit the inner workings of your class, which ideally should be hidden. In other words it breaks encapsulation. I would use a get() const and a set(), and return a non-const reference only if there is no other way, or when it really makes sense, such as to give read/write access to an element of an array or a matrix.</p>\n" }, { "answer_id": 97170, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 0, "selected": false, "text": "<p>The first allows changes to the variable type (whether it is <code>const</code> or not) without further modification of the code. Of course, this means that there is no notification to the developer that this might have changed from the intended path. So it's really whether you value being able to quickly refactor, or having the extra safety net.</p>\n" }, { "answer_id": 97229, "author": "moswald", "author_id": 8368, "author_profile": "https://Stackoverflow.com/users/8368", "pm_score": 4, "selected": true, "text": "<p>Well, for one thing, getAsConst <em>must</em> be called when the 'this' pointer is const -- not when you want to receive a const object. So, alongside any other issues, it's subtly misnamed. (You can still call it when 'this' is non-const, but that's neither here nor there.)</p>\n\n<p>Ignoring that, getAsConst earns you nothing, and puts an undue burden on the developer using the interface. Instead of just calling \"get\" and knowing he's getting what he needs, now he has to ascertain whether or not he's currently using a const variable, and if the new object he's grabbing needs to be const. And later, if both objects become non-const due to some refactoring, he's got to switch out his call.</p>\n" }, { "answer_id": 97262, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p>Given the style precedent set by the standard library (ie begin() and begin() const to name just one example), it should be obvious that method A is the correct choice. I question the person's sanity that chooses method B.</p>\n" }, { "answer_id": 97309, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "<p>The second one is something related to Hungarian notation which I personally <em>DON'T</em> like so I will stick with the <strong>first</strong> method.</p>\n\n<p>I don't like Hungarian notation because it adds redundancy which I usually detest in programming. It is just my opinion.</p>\n" }, { "answer_id": 97393, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 0, "selected": false, "text": "<p>Since you hide the names of the classes, this food for thought on style may or may not apply:</p>\n\n<p>Does it make sense to tell these two objects, MethodA and MethodB, to \"get\" or \"getAsConst\"? Would you send \"get\" or \"getAsConst\" as messages to either object? </p>\n\n<p>The way I see it, as the sender of the message / invoker of the method, <em>you</em> are the one getting the value; so in response to this \"get\" message, you are sending some message to MethodA / MethodB, the result of which is the value you need to get.</p>\n\n<p>Example: If the caller of MethodA is, say, a service in SOA, and MethodA is a repository, then inside the service's get_A(), call MethodA.find_A_by_criteria(...).</p>\n" }, { "answer_id": 98082, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 1, "selected": false, "text": "<p>So, the first style is generally preferable.</p>\n\n<p>We do use a variation of the second style quite a bit in the codebase I'm currently working on though, because we want a big distinction between const and non-const usage.</p>\n\n<p>In my specific example, we have getTessellation and getMutableTessellation. It's implemented with a copy-on-write pointer. For performance reasons we want the const version to be use wherever possible, so we make the name shorter, and we make it a different name so people don't accidentally cause a copy when they weren't going to write anyway.</p>\n" }, { "answer_id": 103534, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "<p>The major technological drawback of MethodB I saw is that when applying generic code to it, we must double the code to handle both the const and the non-const version. For example:</p>\n\n<p>Let's say T is an order-able object (ie, we can compare to objects of type T with operator &lt;), and let's say we want to find the max between two MethodA (resp. two MethodB).</p>\n\n<p>For MethodA, all we need to code is:</p>\n\n<pre><code>template &lt;typename T&gt;\nT &amp; getMax(T &amp; p_oLeft, T &amp; p_oRight)\n{\n if(p_oLeft.get() &gt; p_oRight.get())\n {\n return p_oLeft ;\n }\n else\n {\n return p_oRight ;\n }\n}\n</code></pre>\n\n<p>This code will work both with const objects and non-const objects of type T:</p>\n\n<pre><code>// Ok\nconst MethodA oA_C0(), oA_C1() ;\nconst MethodA &amp; oA_CResult = getMax(oA_C0, oA_C1) ;\n\n// Ok again\nMethodA oA_0(), oA_1() ;\nMethodA &amp; oA_Result = getMax(oA_0, oA_1) ;\n</code></pre>\n\n<p>The problem comes when we want to apply this easy code to something following the MethodB convention:</p>\n\n<pre><code>// NOT Ok\nconst MethodB oB_C0(), oB_C1() ;\nconst MethodB &amp; oB_CResult = getMax(oB_C0, oB_C1) ; // Won't compile\n\n// Ok\nMethodA oB_0(), oB_1() ;\nMethodA &amp; oB_Result = getMax(oB_0, oB_1) ;\n</code></pre>\n\n<p>For the MethodB to work on both const and non-const version, we must both use the already defined getMax, but add to it the following version of getMax:</p>\n\n<pre><code>template &lt;typename T&gt;\nconst T &amp; getMax(const T &amp; p_oLeft, const T &amp; p_oRight)\n{\n if(p_oLeft.getAsConst() &gt; p_oRight.getAsConst())\n {\n return p_oLeft ;\n }\n else\n {\n return p_oRight ;\n }\n}\n</code></pre>\n\n<p>Conclusion, by not trusting the compiler on const-ness use, we burden ourselves with the creation of two generic functions when one should have been enough.</p>\n\n<p>Of course, with enough paranoia, the secondth template function should have been called getMaxAsConst... And thus, the problem would propagate itself through all the code...</p>\n\n<p>:-p</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
Someone told me about a C++ style difference in their team. I have my own viewpoint on the subject, but I would be interested by *pros* and *cons* coming from everyone. So, in case you have a class property you want to expose via two getters, one read/write, and the other, readonly (i.e. there is no set method). There are at least two ways of doing it: ``` class T ; class MethodA { public : const T & get() const ; T & get() ; // etc. } ; class MethodB { public : const T & getAsConst() const ; T & get() ; // etc. } ; ``` What would be the pros and the cons of each method? I am interested more by C++ technical/semantic reasons, but style reasons are welcome, too. Note that `MethodB` has one major technical drawback (hint: in generic code).
Well, for one thing, getAsConst *must* be called when the 'this' pointer is const -- not when you want to receive a const object. So, alongside any other issues, it's subtly misnamed. (You can still call it when 'this' is non-const, but that's neither here nor there.) Ignoring that, getAsConst earns you nothing, and puts an undue burden on the developer using the interface. Instead of just calling "get" and knowing he's getting what he needs, now he has to ascertain whether or not he's currently using a const variable, and if the new object he's grabbing needs to be const. And later, if both objects become non-const due to some refactoring, he's got to switch out his call.
97,092
<p>What I am trying to achieve is a form that has a button on it that causes the Form to 'drop-down' and become larger, displaying more information. My current attempt is this:</p> <pre><code>private void btnExpand_Click(object sender, EventArgs e) { if (btnExpand.Text == "&gt;") { btnExpand.Text = "&lt;"; _expanded = true; this.MinimumSize = new Size(1, 300); this.MaximumSize = new Size(int.MaxValue, 300); } else { btnExpand.Text = "&gt;"; _expanded = false; this.MinimumSize = new Size(1, 104); this.MaximumSize = new Size(int.MaxValue, 104); } } </code></pre> <p>Which works great! Except for one small detail... Note that the width values are supposed to be able to go from 1 to int.MaxValue? Well, in practice, they go from this.Width to int.MaxValue, ie. you can make the form larger, but never smaller again. I'm at a loss for why this would occur. Anyone have any ideas?</p> <p>For the record: I've also tried a Form.Resize handler that set the Height of the form to the same value depending on whatever the boolean _expanded was set to, but I ended up with the same side effect.</p> <p>PS: I'm using .NET 3.5 in Visual Studio 2008. Other solutions are welcome, but this was my thoughts on how it "should" be done and how I attempted to do it.</p> <p>Edit: Seems the code works, as per the accepted answers response. If anyone else has troubles with this particular problem, check the AutoSize property of your form, it should be FALSE, not TRUE. (This is the default, but I'd switched it on as I was using the form and a label with autosize also on for displaying debugging info earlier)</p>
[ { "answer_id": 97689, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 2, "selected": true, "text": "<p>As per the docs, use 0 to denote no maximum or minimum size. Tho, I just tried it and it didn't like 0 at all. So I used int.MaxValue like you did and it worked. What version of the the framework you using?</p>\n" }, { "answer_id": 97870, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 0, "selected": false, "text": "<p>Actually, having a look at the <code>MinimumSize</code> and <code>MaximumSize</code> (.NET 3.5) in reflector its pretty clear that the designed behaviour is not quite the same as the docs suggest. There is some minimum width constraints determined from a helper class and 0 has no special meaning (i.e. no limit.</p>\n\n<p>Another note, I see in your code above that you are Expanding or Contracting based upon the text value of your Button, this is a bad idea, if someone comes along later and changes the text in the designer to say, \"Expand\" instead of &lt; without looking at your code it will then have an unexpected side effect, presumably you have some code somewhere that changes the button text, it would be better to have a state variable somewhere and switch on that.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
What I am trying to achieve is a form that has a button on it that causes the Form to 'drop-down' and become larger, displaying more information. My current attempt is this: ``` private void btnExpand_Click(object sender, EventArgs e) { if (btnExpand.Text == ">") { btnExpand.Text = "<"; _expanded = true; this.MinimumSize = new Size(1, 300); this.MaximumSize = new Size(int.MaxValue, 300); } else { btnExpand.Text = ">"; _expanded = false; this.MinimumSize = new Size(1, 104); this.MaximumSize = new Size(int.MaxValue, 104); } } ``` Which works great! Except for one small detail... Note that the width values are supposed to be able to go from 1 to int.MaxValue? Well, in practice, they go from this.Width to int.MaxValue, ie. you can make the form larger, but never smaller again. I'm at a loss for why this would occur. Anyone have any ideas? For the record: I've also tried a Form.Resize handler that set the Height of the form to the same value depending on whatever the boolean \_expanded was set to, but I ended up with the same side effect. PS: I'm using .NET 3.5 in Visual Studio 2008. Other solutions are welcome, but this was my thoughts on how it "should" be done and how I attempted to do it. Edit: Seems the code works, as per the accepted answers response. If anyone else has troubles with this particular problem, check the AutoSize property of your form, it should be FALSE, not TRUE. (This is the default, but I'd switched it on as I was using the form and a label with autosize also on for displaying debugging info earlier)
As per the docs, use 0 to denote no maximum or minimum size. Tho, I just tried it and it didn't like 0 at all. So I used int.MaxValue like you did and it worked. What version of the the framework you using?
97,097
<p>What is the C# version of VB.net's InputBox?</p>
[ { "answer_id": 97119, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": -1, "selected": false, "text": "<p>There is no such thing: I recommend to write it for yourself and use it whenever you need.</p>\n" }, { "answer_id": 97120, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You mean InputBox? Just look in the Microsoft.VisualBasic namespace.</p>\n\n<p>C# and VB.Net share a common library. If one language can use it, so can the other.</p>\n" }, { "answer_id": 97135, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 3, "selected": false, "text": "<p>There isn't one. If you really wanted to use the VB InputBox in C# you can. Just add reference to Microsoft.VisualBasic.dll and you'll find it there. </p>\n\n<p>But I would suggest to <em>not</em> use it. It is ugly and outdated IMO.</p>\n" }, { "answer_id": 97156, "author": "Ozgur Ozcitak", "author_id": 976, "author_profile": "https://Stackoverflow.com/users/976", "pm_score": 9, "selected": true, "text": "<p>Add a reference to <code>Microsoft.VisualBasic</code>, <code>InputBox</code> is in the <code>Microsoft.VisualBasic.Interaction</code> namespace:</p>\n\n<pre><code>using Microsoft.VisualBasic;\nstring input = Interaction.InputBox(\"Prompt\", \"Title\", \"Default\", x_coordinate, y_coordinate);\n</code></pre>\n\n<p>Only the first argument for <code>prompt</code> is mandatory</p>\n" }, { "answer_id": 97190, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>Add reference to <code>Microsoft.VisualBasic</code> and use this function:</p>\n\n<pre><code>string response = Microsoft.VisualBasic.Interaction.InputBox(\"What's 1+1?\", \"Title\", \"2\", 0, 0);\n</code></pre>\n\n<p>The last 2 number is an X/Y position to display the input dialog.</p>\n" }, { "answer_id": 97467, "author": "Tomas Sedovic", "author_id": 2239, "author_profile": "https://Stackoverflow.com/users/2239", "pm_score": 7, "selected": false, "text": "<p>To sum it up: </p>\n\n<ul>\n<li>There is <a href=\"http://www.google.com/search?hl=en&amp;q=c%23+inputbox\" rel=\"noreferrer\">none in C#</a>.</li>\n<li><p>You can use the dialog from Visual Basic by adding a reference to Microsoft.VisualBasic: </p>\n\n<ol>\n<li>In <strong>Solution Explorer</strong> right-click on the <strong>References</strong> folder.</li>\n<li>Select <strong>Add Reference...</strong></li>\n<li>In the <strong>.NET</strong> tab (in newer Visual Studio verions - <strong>Assembly</strong> tab) - select <strong>Microsoft.VisualBasic</strong></li>\n<li>Click on <strong>OK</strong></li>\n</ol></li>\n</ul>\n\n<p>Then you can use the previously mentioned code: </p>\n\n<pre><code>string input = Microsoft.VisualBasic.Interaction.InputBox(\"Prompt\", \"Title\", \"Default\", 0, 0);\n</code></pre>\n\n<ul>\n<li>Write your own InputBox.</li>\n<li>Use <a href=\"http://www.reflectionit.nl/Articles/InputBox.aspx\" rel=\"noreferrer\">someone else's</a>.</li>\n</ul>\n\n<p>That said, I suggest that you consider the need of an input box in the first place. Dialogs are not always the best way to do things and sometimes they do more harm than good - but that depends on the particular situation.</p>\n" }, { "answer_id": 14965504, "author": "AdamL", "author_id": 429460, "author_profile": "https://Stackoverflow.com/users/429460", "pm_score": 3, "selected": false, "text": "<p>Not only should you add Microsoft.VisualBasic to your reference list for the project, but also you should declare 'using Microsoft.VisualBasic;' so you just have to use 'Interaction.Inputbox(\"...\")' instead of Microsoft.VisualBasic.Interaction.Inputbox</p>\n" }, { "answer_id": 15013055, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "<p>Returns the string the user entered; empty string if they hit <kbd>Cancel</kbd>:</p>\n\n<pre><code> public static String InputBox(String caption, String prompt, String defaultText)\n {\n String localInputText = defaultText;\n if (InputQuery(caption, prompt, ref localInputText))\n {\n return localInputText;\n }\n else\n {\n return \"\";\n }\n }\n</code></pre>\n\n<p>Returns the <code>String</code> as a <strong>ref</strong> parameter, returning <code>true</code> if they hit <kbd>OK</kbd>, or <code>false</code> if they hit <kbd>Cancel</kbd>:</p>\n\n<pre><code> public static Boolean InputQuery(String caption, String prompt, ref String value)\n {\n Form form;\n form = new Form();\n form.AutoScaleMode = AutoScaleMode.Font;\n form.Font = SystemFonts.IconTitleFont;\n\n SizeF dialogUnits;\n dialogUnits = form.AutoScaleDimensions;\n\n form.FormBorderStyle = FormBorderStyle.FixedDialog;\n form.MinimizeBox = false;\n form.MaximizeBox = false;\n form.Text = caption;\n\n form.ClientSize = new Size(\n Toolkit.MulDiv(180, dialogUnits.Width, 4),\n Toolkit.MulDiv(63, dialogUnits.Height, 8));\n\n form.StartPosition = FormStartPosition.CenterScreen;\n\n System.Windows.Forms.Label lblPrompt;\n lblPrompt = new System.Windows.Forms.Label();\n lblPrompt.Parent = form;\n lblPrompt.AutoSize = true;\n lblPrompt.Left = Toolkit.MulDiv(8, dialogUnits.Width, 4);\n lblPrompt.Top = Toolkit.MulDiv(8, dialogUnits.Height, 8);\n lblPrompt.Text = prompt;\n\n System.Windows.Forms.TextBox edInput;\n edInput = new System.Windows.Forms.TextBox();\n edInput.Parent = form;\n edInput.Left = lblPrompt.Left;\n edInput.Top = Toolkit.MulDiv(19, dialogUnits.Height, 8);\n edInput.Width = Toolkit.MulDiv(164, dialogUnits.Width, 4);\n edInput.Text = value;\n edInput.SelectAll();\n\n\n int buttonTop = Toolkit.MulDiv(41, dialogUnits.Height, 8);\n //Command buttons should be 50x14 dlus\n Size buttonSize = Toolkit.ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8);\n\n System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button();\n bbOk.Parent = form;\n bbOk.Text = \"OK\";\n bbOk.DialogResult = DialogResult.OK;\n form.AcceptButton = bbOk;\n bbOk.Location = new Point(Toolkit.MulDiv(38, dialogUnits.Width, 4), buttonTop);\n bbOk.Size = buttonSize;\n\n System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button();\n bbCancel.Parent = form;\n bbCancel.Text = \"Cancel\";\n bbCancel.DialogResult = DialogResult.Cancel;\n form.CancelButton = bbCancel;\n bbCancel.Location = new Point(Toolkit.MulDiv(92, dialogUnits.Width, 4), buttonTop);\n bbCancel.Size = buttonSize;\n\n if (form.ShowDialog() == DialogResult.OK)\n {\n value = edInput.Text;\n return true;\n }\n else\n {\n return false;\n }\n }\n\n /// &lt;summary&gt;\n /// Multiplies two 32-bit values and then divides the 64-bit result by a \n /// third 32-bit value. The final result is rounded to the nearest integer.\n /// &lt;/summary&gt;\n public static int MulDiv(int nNumber, int nNumerator, int nDenominator)\n {\n return (int)Math.Round((float)nNumber * nNumerator / nDenominator);\n }\n</code></pre>\n\n<blockquote>\n <p><strong>Note</strong>: Any code is released into the public domain. No attribution required.</p>\n</blockquote>\n" }, { "answer_id": 17546909, "author": "Gorkem", "author_id": 2138992, "author_profile": "https://Stackoverflow.com/users/2138992", "pm_score": 7, "selected": false, "text": "<p>Dynamic creation of a dialog box. You can customize to your taste.</p>\n\n<p><em>Note there is no external dependency here except winform</em></p>\n\n<pre><code>private static DialogResult ShowInputDialog(ref string input)\n {\n System.Drawing.Size size = new System.Drawing.Size(200, 70);\n Form inputBox = new Form();\n\n inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;\n inputBox.ClientSize = size;\n inputBox.Text = \"Name\";\n\n System.Windows.Forms.TextBox textBox = new TextBox();\n textBox.Size = new System.Drawing.Size(size.Width - 10, 23);\n textBox.Location = new System.Drawing.Point(5, 5);\n textBox.Text = input;\n inputBox.Controls.Add(textBox);\n\n Button okButton = new Button();\n okButton.DialogResult = System.Windows.Forms.DialogResult.OK;\n okButton.Name = \"okButton\";\n okButton.Size = new System.Drawing.Size(75, 23);\n okButton.Text = \"&amp;OK\";\n okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39);\n inputBox.Controls.Add(okButton);\n\n Button cancelButton = new Button();\n cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;\n cancelButton.Name = \"cancelButton\";\n cancelButton.Size = new System.Drawing.Size(75, 23);\n cancelButton.Text = \"&amp;Cancel\";\n cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39);\n inputBox.Controls.Add(cancelButton);\n\n inputBox.AcceptButton = okButton;\n inputBox.CancelButton = cancelButton; \n\n DialogResult result = inputBox.ShowDialog();\n input = textBox.Text;\n return result;\n }\n</code></pre>\n\n<p>usage</p>\n\n<pre><code>string input=\"hede\";\nShowInputDialog(ref input);\n</code></pre>\n" }, { "answer_id": 25912587, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "<p>Without adding a reference to Microsoft.VisualBasic: </p>\n\n<pre><code>// \"dynamic\" requires reference to Microsoft.CSharp\nType tScriptControl = Type.GetTypeFromProgID(\"ScriptControl\");\ndynamic oSC = Activator.CreateInstance(tScriptControl);\n\noSC.Language = \"VBScript\";\nstring sFunc = @\"Function InBox(prompt, title, default) \nInBox = InputBox(prompt, title, default) \nEnd Function\n\";\noSC.AddCode(sFunc);\ndynamic Ret = oSC.Run(\"InBox\", \"メッセージ\", \"タイトル\", \"初期値\");\n</code></pre>\n\n<p>See these for further information:<br />\n<a href=\"http://www.geocities.jp/maru3128/SakuraMacro/usage/scriptcontrol.html\" rel=\"nofollow\">ScriptControl</a><br />\n<a href=\"http://with-love-from-siberia.blogspot.ch/2009/12/msgbox-inputbox-in-jscript.html\" rel=\"nofollow\">MsgBox in JScript</a><br />\n<a href=\"http://cwestblog.com/2012/03/10/jscript-using-inputbox-and-msgbox/\" rel=\"nofollow\">Input and MsgBox in JScript</a><br /></p>\n\n<p>.NET 2.0:</p>\n\n<pre><code>string sFunc = @\"Function InBox(prompt, title, default) \nInBox = InputBox(prompt, title, default) \nEnd Function\n\";\n\nType tScriptControl = Type.GetTypeFromProgID(\"ScriptControl\");\nobject oSC = Activator.CreateInstance(tScriptControl);\n\n// https://github.com/mono/mono/blob/master/mcs/class/corlib/System/MonoType.cs\n// System.Reflection.PropertyInfo pi = tScriptControl.GetProperty(\"Language\", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.IgnoreCase);\n// pi.SetValue(oSC, \"VBScript\", null);\n\ntScriptControl.InvokeMember(\"Language\", System.Reflection.BindingFlags.SetProperty, null, oSC, new object[] { \"VBScript\" });\ntScriptControl.InvokeMember(\"AddCode\", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { sFunc });\nobject ret = tScriptControl.InvokeMember(\"Run\", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { \"InBox\", \"メッセージ\", \"タイトル\", \"初期値\" });\nConsole.WriteLine(ret);\n</code></pre>\n" }, { "answer_id": 32616012, "author": "David Carrigan", "author_id": 2305236, "author_profile": "https://Stackoverflow.com/users/2305236", "pm_score": 2, "selected": false, "text": "<p>I was able to achieve this by coding my own. I don't like extending into and relying on large library's for something rudimental.</p>\n\n<p>Form and Designer:</p>\n\n<pre><code>public partial class InputBox \n : Form\n{\n\n public String Input\n {\n get { return textInput.Text; }\n }\n\n public InputBox()\n {\n InitializeComponent();\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n DialogResult = System.Windows.Forms.DialogResult.OK;\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n DialogResult = System.Windows.Forms.DialogResult.Cancel;\n }\n\n private void InputBox_Load(object sender, EventArgs e)\n {\n this.ActiveControl = textInput;\n }\n\n public static DialogResult Show(String title, String message, String inputTitle, out String inputValue)\n {\n InputBox inputBox = null;\n DialogResult results = DialogResult.None;\n\n using (inputBox = new InputBox() { Text = title })\n {\n inputBox.labelMessage.Text = message;\n inputBox.splitContainer2.SplitterDistance = inputBox.labelMessage.Width;\n inputBox.labelInput.Text = inputTitle;\n inputBox.splitContainer1.SplitterDistance = inputBox.labelInput.Width;\n inputBox.Size = new Size(\n inputBox.Width,\n 8 + inputBox.labelMessage.Height + inputBox.splitContainer2.SplitterWidth + inputBox.splitContainer1.Height + 8 + inputBox.button2.Height + 12 + (50));\n results = inputBox.ShowDialog();\n inputValue = inputBox.Input;\n }\n\n return results;\n }\n\n void labelInput_TextChanged(object sender, System.EventArgs e)\n {\n }\n\n}\n\npartial class InputBox\n{\n /// &lt;summary&gt;\n /// Required designer variable.\n /// &lt;/summary&gt;\n private System.ComponentModel.IContainer components = null;\n\n /// &lt;summary&gt;\n /// Clean up any resources being used.\n /// &lt;/summary&gt;\n /// &lt;param name=\"disposing\"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;\n protected override void Dispose(bool disposing)\n {\n if (disposing &amp;&amp; (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Windows Form Designer generated code\n\n /// &lt;summary&gt;\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// &lt;/summary&gt;\n private void InitializeComponent()\n {\n this.labelMessage = new System.Windows.Forms.Label();\n this.button1 = new System.Windows.Forms.Button();\n this.button2 = new System.Windows.Forms.Button();\n this.labelInput = new System.Windows.Forms.Label();\n this.textInput = new System.Windows.Forms.TextBox();\n this.splitContainer1 = new System.Windows.Forms.SplitContainer();\n this.splitContainer2 = new System.Windows.Forms.SplitContainer();\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();\n this.splitContainer1.Panel1.SuspendLayout();\n this.splitContainer1.Panel2.SuspendLayout();\n this.splitContainer1.SuspendLayout();\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();\n this.splitContainer2.Panel1.SuspendLayout();\n this.splitContainer2.Panel2.SuspendLayout();\n this.splitContainer2.SuspendLayout();\n this.SuspendLayout();\n // \n // labelMessage\n // \n this.labelMessage.AutoSize = true;\n this.labelMessage.Location = new System.Drawing.Point(3, 0);\n this.labelMessage.MaximumSize = new System.Drawing.Size(379, 0);\n this.labelMessage.Name = \"labelMessage\";\n this.labelMessage.Size = new System.Drawing.Size(50, 13);\n this.labelMessage.TabIndex = 99;\n this.labelMessage.Text = \"Message\";\n // \n // button1\n // \n this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));\n this.button1.Location = new System.Drawing.Point(316, 126);\n this.button1.Name = \"button1\";\n this.button1.Size = new System.Drawing.Size(75, 23);\n this.button1.TabIndex = 3;\n this.button1.Text = \"Cancel\";\n this.button1.UseVisualStyleBackColor = true;\n this.button1.Click += new System.EventHandler(this.button1_Click);\n // \n // button2\n // \n this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));\n this.button2.Location = new System.Drawing.Point(235, 126);\n this.button2.Name = \"button2\";\n this.button2.Size = new System.Drawing.Size(75, 23);\n this.button2.TabIndex = 2;\n this.button2.Text = \"OK\";\n this.button2.UseVisualStyleBackColor = true;\n this.button2.Click += new System.EventHandler(this.button2_Click);\n // \n // labelInput\n // \n this.labelInput.AutoSize = true;\n this.labelInput.Location = new System.Drawing.Point(3, 6);\n this.labelInput.Name = \"labelInput\";\n this.labelInput.Size = new System.Drawing.Size(31, 13);\n this.labelInput.TabIndex = 99;\n this.labelInput.Text = \"Input\";\n this.labelInput.TextChanged += new System.EventHandler(this.labelInput_TextChanged);\n // \n // textInput\n // \n this.textInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) \n | System.Windows.Forms.AnchorStyles.Right)));\n this.textInput.Location = new System.Drawing.Point(3, 3);\n this.textInput.Name = \"textInput\";\n this.textInput.Size = new System.Drawing.Size(243, 20);\n this.textInput.TabIndex = 1;\n // \n // splitContainer1\n // \n this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;\n this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;\n this.splitContainer1.IsSplitterFixed = true;\n this.splitContainer1.Location = new System.Drawing.Point(0, 0);\n this.splitContainer1.Name = \"splitContainer1\";\n // \n // splitContainer1.Panel1\n // \n this.splitContainer1.Panel1.Controls.Add(this.labelInput);\n // \n // splitContainer1.Panel2\n // \n this.splitContainer1.Panel2.Controls.Add(this.textInput);\n this.splitContainer1.Size = new System.Drawing.Size(379, 50);\n this.splitContainer1.SplitterDistance = 126;\n this.splitContainer1.TabIndex = 99;\n // \n // splitContainer2\n // \n this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) \n | System.Windows.Forms.AnchorStyles.Left) \n | System.Windows.Forms.AnchorStyles.Right)));\n this.splitContainer2.IsSplitterFixed = true;\n this.splitContainer2.Location = new System.Drawing.Point(12, 12);\n this.splitContainer2.Name = \"splitContainer2\";\n this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;\n // \n // splitContainer2.Panel1\n // \n this.splitContainer2.Panel1.Controls.Add(this.labelMessage);\n // \n // splitContainer2.Panel2\n // \n this.splitContainer2.Panel2.Controls.Add(this.splitContainer1);\n this.splitContainer2.Size = new System.Drawing.Size(379, 108);\n this.splitContainer2.SplitterDistance = 54;\n this.splitContainer2.TabIndex = 99;\n // \n // InputBox\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.ClientSize = new System.Drawing.Size(403, 161);\n this.Controls.Add(this.splitContainer2);\n this.Controls.Add(this.button2);\n this.Controls.Add(this.button1);\n this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;\n this.MaximizeBox = false;\n this.MinimizeBox = false;\n this.Name = \"InputBox\";\n this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;\n this.Text = \"Title\";\n this.TopMost = true;\n this.Load += new System.EventHandler(this.InputBox_Load);\n this.splitContainer1.Panel1.ResumeLayout(false);\n this.splitContainer1.Panel1.PerformLayout();\n this.splitContainer1.Panel2.ResumeLayout(false);\n this.splitContainer1.Panel2.PerformLayout();\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();\n this.splitContainer1.ResumeLayout(false);\n this.splitContainer2.Panel1.ResumeLayout(false);\n this.splitContainer2.Panel1.PerformLayout();\n this.splitContainer2.Panel2.ResumeLayout(false);\n ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();\n this.splitContainer2.ResumeLayout(false);\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private System.Windows.Forms.Label labelMessage;\n private System.Windows.Forms.Button button1;\n private System.Windows.Forms.Button button2;\n private System.Windows.Forms.Label labelInput;\n private System.Windows.Forms.TextBox textInput;\n private System.Windows.Forms.SplitContainer splitContainer1;\n private System.Windows.Forms.SplitContainer splitContainer2;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>String output = \"\";\n\nresult = System.Windows.Forms.DialogResult.None;\n\nresult = InputBox.Show(\n \"Input Required\",\n \"Please enter the value (if available) below.\",\n \"Value\",\n out output);\n\nif (result != System.Windows.Forms.DialogResult.OK)\n{\n return;\n}\n</code></pre>\n\n<p>Note this exhibits a bit of auto sizing to keep it pretty based on how much text you ask it display. I also know it's lacking the bells and whistles but it's a solid step forward for those facing this same dilemma.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
What is the C# version of VB.net's InputBox?
Add a reference to `Microsoft.VisualBasic`, `InputBox` is in the `Microsoft.VisualBasic.Interaction` namespace: ``` using Microsoft.VisualBasic; string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate); ``` Only the first argument for `prompt` is mandatory
97,113
<p>I have the following string:</p> <pre><code>cn=abcd,cn=groups,dc=domain,dc=com </code></pre> <p>Can a regular expression be used here to extract the string after the first <code>cn=</code> and before the first <code>,</code>? In the example above the answer should be <code>abcd</code>. </p>
[ { "answer_id": 97125, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>Yeah, using perl/java syntax <code>cn=([^,]*),</code>. You'd then get the 1st group.</p>\n" }, { "answer_id": 97129, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 3, "selected": false, "text": "<pre><code>/^cn=([^,]+),/</code></pre>\n" }, { "answer_id": 97131, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 5, "selected": true, "text": "<pre><code> /cn=([^,]+),/ \n</code></pre>\n\n<p>most languages will extract the match as $1 or matches[1] </p>\n\n<p>If you can't for some reason wield subscripts, </p>\n\n<pre><code>$x =~ s/^cn=//\n$x =~ s/,.*$//\n</code></pre>\n\n<p>Thats a way to do it in 2 steps.</p>\n\n<p>If you were parsing it out of a log with sed </p>\n\n<pre><code>sed -n -r '/cn=/s/^cn=([^,]+),.*$/\\1/p' &lt; logfile &gt; dumpfile \n</code></pre>\n\n<p>will get you what you want. ( Extra commands added to only print matching lines )</p>\n" }, { "answer_id": 97148, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Also, look for a pre-built LDAP parser.</p>\n" }, { "answer_id": 11585720, "author": "renoirb", "author_id": 852395, "author_profile": "https://Stackoverflow.com/users/852395", "pm_score": 0, "selected": false, "text": "<p>I had to work that out in PHP.</p>\n\n<p>Since a LDAP string can sometimes be lengthy and have many attributes, I thought of contributing how I am using it in a project.</p>\n\n<p>I wanted to use:</p>\n\n<pre><code>CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com\n</code></pre>\n\n<p>And turn it into:</p>\n\n<pre><code>array (\n [CN] =&gt; array( username )\n [OU] =&gt; array( UNITNAME, Region, Country )\n [DC] =&gt; array ( subdomain, domain, com )\n)\n</code></pre>\n\n<p>Here is how I built my method.</p>\n\n<pre><code>/**\n * Read a LDAP DN, and return what is needed\n *\n * Takes care of the character escape and unescape\n *\n * Using:\n * CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com\n *\n * Would normally return:\n * Array (\n * [count] =&gt; 9\n * [0] =&gt; CN=username\n * [1] =&gt; OU=UNITNAME\n * [2] =&gt; OU=Region\n * [5] =&gt; OU=Country\n * [6] =&gt; DC=subdomain\n * [7] =&gt; DC=domain\n * [8] =&gt; DC=com\n * )\n *\n * Returns instead a manageable array:\n * array (\n * [CN] =&gt; array( username )\n * [OU] =&gt; array( UNITNAME, Region, Country )\n * [DC] =&gt; array ( subdomain, domain, com )\n * )\n *\n *\n * @author gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27 (part of the character replacement)\n * @author Renoir Boulanger\n * \n * @param string $dn The DN\n * @return array\n */\nfunction parseLdapDn($dn)\n{\n $parsr=ldap_explode_dn($dn, 0);\n //$parsr[] = 'EE=Sôme Krazï string';\n //$parsr[] = 'AndBogusOne';\n $out = array();\n foreach($parsr as $key=&gt;$value){\n if(FALSE !== strstr($value, '=')){\n list($prefix,$data) = explode(\"=\",$value);\n $data=preg_replace(\"/\\\\\\([0-9A-Fa-f]{2})/e\", \"''.chr(hexdec('\\\\1')).''\", $data);\n if(isset($current_prefix) &amp;&amp; $prefix == $current_prefix){\n $out[$prefix][] = $data;\n } else {\n $current_prefix = $prefix;\n $out[$prefix][] = $data;\n }\n }\n }\n return $out;\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17273/" ]
I have the following string: ``` cn=abcd,cn=groups,dc=domain,dc=com ``` Can a regular expression be used here to extract the string after the first `cn=` and before the first `,`? In the example above the answer should be `abcd`.
``` /cn=([^,]+),/ ``` most languages will extract the match as $1 or matches[1] If you can't for some reason wield subscripts, ``` $x =~ s/^cn=// $x =~ s/,.*$// ``` Thats a way to do it in 2 steps. If you were parsing it out of a log with sed ``` sed -n -r '/cn=/s/^cn=([^,]+),.*$/\1/p' < logfile > dumpfile ``` will get you what you want. ( Extra commands added to only print matching lines )
97,114
<p>In a recent question on stubbing, many answers suggested C# interfaces or delegates for implementing stubs, but <a href="https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43718">one answer</a> suggested using conditional compilation, retaining static binding in the production code. This answer was modded -2 at the time of reading, so at least 2 people really thought this was a <em>wrong</em> answer. Perhaps misuse of DEBUG was the reason, or perhaps use of fixed value instead of more extensive validation. But I can't help wondering:</p> <p>Is the use of conditional compilation an inappropriate technique for implementing unit test stubs? Sometimes? Always?</p> <p>Thanks.</p> <p><strong>Edit-add:</strong> I'd like to add an example as a though experiment:</p> <pre><code>class Foo { public Foo() { .. } private DateTime Now { get { #if UNITTEST_Foo return Stub_DateTime.Now; #else return DateTime.Now; #endif } } // .. rest of Foo members } </code></pre> <p>comparing to</p> <pre><code>interface IDateTimeStrategy { DateTime Now { get; } } class ProductionDateTimeStrategy : IDateTimeStrategy { public DateTime Now { get { return DateTime.Now; } } } class Foo { public Foo() : Foo(new ProductionDateTimeStrategy()) {} public Foo(IDateTimeStrategy s) { datetimeStrategy = s; .. } private IDateTime_Strategy datetimeStrategy; private DateTime Now { get { return datetimeStrategy.Now; } } } </code></pre> <p>Which allows the outgoing dependency on "DateTime.Now" to be stubbed through a C# interface. However, we've now added a dynamic dispatch call where static would suffice, the object is larger even in the production version, and we've added a new failure path for Foo's constructor (allocation can fail). </p> <p>Am I worrying about nothing here? Thanks for the feedback so far!</p>
[ { "answer_id": 97174, "author": "plyawn", "author_id": 5964, "author_profile": "https://Stackoverflow.com/users/5964", "pm_score": 2, "selected": false, "text": "<p>I think it lessens the clarity for people reviewing the code. You shouldn't have to remember that there's a conditional tag around specific code to understand the context.</p>\n" }, { "answer_id": 97227, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 1, "selected": false, "text": "<p>No this is terrible. It leaks test into your production code (even if its conditioned off)</p>\n\n<p>Bad bad.</p>\n" }, { "answer_id": 97245, "author": "Bradley Harris", "author_id": 10503, "author_profile": "https://Stackoverflow.com/users/10503", "pm_score": 0, "selected": false, "text": "<p>It might be useful as a tool to lean on as you refactor to testability in a large code base. I can see how you might use such techniques to enable smaller changes and avoid a \"big bang\" refactoring. However I would worry about leaning too hard on such a technique and would try to ensure that such tricks didn't live too long in the code base otherwise you risk making the application code very complex and hard to follow. </p>\n" }, { "answer_id": 97248, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>Test code should be obvious and not inter-mixed in the same blocks as the tested code.</p>\n\n<p>This is pretty much the same reason you shouldn't write</p>\n\n<pre><code>if (globals.isTest)\n</code></pre>\n" }, { "answer_id": 97318, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": true, "text": "<p>Try to keep production code separate from test code. Maintain different folder hierarchies.. different solutions/projects. </p>\n\n<p><strong>Unless</strong>.. you're in the world of legacy C++ Code. Here anything goes.. if conditional blocks help you get some of the code testable and you see a benefit.. By all means do it. But try to not let it get messier than the initial state. Clearly comment and demarcate conditional blocks. Proceed with caution. It is a valid technique for getting legacy code under a test harness.</p>\n" }, { "answer_id": 102440, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 1, "selected": false, "text": "<p>I thought of another reason this was terrible:</p>\n\n<p>Many times you mock/stub something, you want its methods to return different results depending on what you're testing. This either precludes that or makes it awkward as all heck.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14153/" ]
In a recent question on stubbing, many answers suggested C# interfaces or delegates for implementing stubs, but [one answer](https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43718) suggested using conditional compilation, retaining static binding in the production code. This answer was modded -2 at the time of reading, so at least 2 people really thought this was a *wrong* answer. Perhaps misuse of DEBUG was the reason, or perhaps use of fixed value instead of more extensive validation. But I can't help wondering: Is the use of conditional compilation an inappropriate technique for implementing unit test stubs? Sometimes? Always? Thanks. **Edit-add:** I'd like to add an example as a though experiment: ``` class Foo { public Foo() { .. } private DateTime Now { get { #if UNITTEST_Foo return Stub_DateTime.Now; #else return DateTime.Now; #endif } } // .. rest of Foo members } ``` comparing to ``` interface IDateTimeStrategy { DateTime Now { get; } } class ProductionDateTimeStrategy : IDateTimeStrategy { public DateTime Now { get { return DateTime.Now; } } } class Foo { public Foo() : Foo(new ProductionDateTimeStrategy()) {} public Foo(IDateTimeStrategy s) { datetimeStrategy = s; .. } private IDateTime_Strategy datetimeStrategy; private DateTime Now { get { return datetimeStrategy.Now; } } } ``` Which allows the outgoing dependency on "DateTime.Now" to be stubbed through a C# interface. However, we've now added a dynamic dispatch call where static would suffice, the object is larger even in the production version, and we've added a new failure path for Foo's constructor (allocation can fail). Am I worrying about nothing here? Thanks for the feedback so far!
Try to keep production code separate from test code. Maintain different folder hierarchies.. different solutions/projects. **Unless**.. you're in the world of legacy C++ Code. Here anything goes.. if conditional blocks help you get some of the code testable and you see a benefit.. By all means do it. But try to not let it get messier than the initial state. Clearly comment and demarcate conditional blocks. Proceed with caution. It is a valid technique for getting legacy code under a test harness.
97,173
<p>I'm using freemarker, SiteMesh and Spring framework. For the pages I use ${requestContext.getMessage()} to get the message from message.properties. But for the decorators this doesn't work. How should I do to get the internationalization working for sitemesh?</p>
[ { "answer_id": 105142, "author": "mathd", "author_id": 16309, "author_profile": "https://Stackoverflow.com/users/16309", "pm_score": 2, "selected": false, "text": "<p>You have to use the <strong><em>fmt</em></strong> taglib.</p>\n\n<p>First, add the taglib for sitemesh and fmt on the fisrt line of the decorator.</p>\n\n<pre><code>&lt;%@ taglib prefix=\"decorator\" uri=\"http://www.opensymphony.com/sitemesh/decorator\"%&gt;\n&lt;%@ taglib prefix=\"page\" uri=\"http://www.opensymphony.com/sitemesh/page\"%&gt;\n&lt;%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jstl/core\"%&gt;\n&lt;%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jstl/fmt\"%&gt;\n&lt;fmt:setBundle basename=\"messages\" /&gt;\n</code></pre>\n\n<p>In my example, the i18n file is messages.properties. Then you need to use the fmt tag to use the mesages.</p>\n\n<pre><code>&lt;fmt:message key=\"key_of_message\" /&gt;\n</code></pre>\n" }, { "answer_id": 182046, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you prefer templates and the freemarker servlet instead you can enter the following in your templates:</p>\n\n<pre><code>&lt;#assign fmt=JspTaglibs[\"http://java.sun.com/jstl/fmt\"]&gt;\n&lt;@fmt.message key=\"webapp.name\" /&gt;\n</code></pre>\n\n<p>and in your <code>web.xml</code>:</p>\n\n<pre><code>&lt;context-param&gt;\n &lt;param-name&gt;javax.servlet.jsp.jstl.fmt.localizationContext&lt;/param-name&gt;\n &lt;param-value&gt;messages&lt;/param-value&gt;\n&lt;/context-param&gt;\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8041/" ]
I'm using freemarker, SiteMesh and Spring framework. For the pages I use ${requestContext.getMessage()} to get the message from message.properties. But for the decorators this doesn't work. How should I do to get the internationalization working for sitemesh?
You have to use the ***fmt*** taglib. First, add the taglib for sitemesh and fmt on the fisrt line of the decorator. ``` <%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator"%> <%@ taglib prefix="page" uri="http://www.opensymphony.com/sitemesh/page"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%> <fmt:setBundle basename="messages" /> ``` In my example, the i18n file is messages.properties. Then you need to use the fmt tag to use the mesages. ``` <fmt:message key="key_of_message" /> ```
97,193
<p>Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself?</p> <p>For example, something along these lines</p> <pre><code>class A { public void DoSomething() { StaticClass.ExecuteMethod(); } } class B { public void DoSomething() { SomeOtherClass.ExecuteMethod(); } } public class SomeOtherClass { public static void ExecuteMethod() { // Returns an instance of A if called from class A // or an instance of B if called from class B. object caller = getCallingInstance(); } } </code></pre> <p>I can get the type using <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframes.aspx" rel="noreferrer">System.Diagnostics.StackTrace.GetFrames</a>, but is there a way to get a reference to the actual instance?</p> <p>I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in.</p> <pre><code>ExecuteMethod(instance) </code></pre> <p>And I just wondered if this was possible and still being able to access the instance.</p> <pre><code>ExecuteMethod() </code></pre> <hr> <p>@Steve Cooper: I hadn't considered extension methods. Some variation of that might work.</p>
[ { "answer_id": 97267, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 1, "selected": false, "text": "<p>Just have ExecuteMethod take an object. Then you have the instance no matter what.</p>\n" }, { "answer_id": 97278, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 4, "selected": true, "text": "<p>I do not believe you can. Even the StackTrace and StackFrame classes just give you naming information, not access to instances. </p>\n\n<p>I'm not sure exactly why you'd want to do this, but know that even if you could do it it would likely be very slow.</p>\n\n<p>A better solution would be to push the instance to a thread local context before calling ExecuteMethod that you can retrieve within it or just pass the instance.</p>\n" }, { "answer_id": 97315, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": false, "text": "<p>Consider making the method an extension method. Define it as:</p>\n\n<pre><code>public static StaticExecute(this object instance)\n{\n // Reference to 'instance'\n}\n</code></pre>\n\n<p>It is called like:</p>\n\n<pre><code>this.StaticExecute();\n</code></pre>\n\n<p>I can't think of a way to do what you want to do directly, but I can only suggest that if you find something, you watch out for static methods, which won't have one, and anonymous methods, which will have instances of auto-generated classes, which will be a little odd. </p>\n\n<p>I do wonder whether you should just pass the invoking object in as a proper parameter. After all, a <code>static</code> is a hint that this method doesn't depend on anything other than its input parameters. Also note that this method may be a bitch to test, as any test code you write will not have the same invoking object as the running system.</p>\n" }, { "answer_id": 97322, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 0, "selected": false, "text": "<p>I feel like I'm missing something, here. The static method can be called from literally anywhere. There's no guarantee that a class A or class B instance will appear anywhere in the call stack.</p>\n\n<p>There's got to be a better way to accomplish whatever you're trying to do.</p>\n" }, { "answer_id": 97333, "author": "therealhoff", "author_id": 18175, "author_profile": "https://Stackoverflow.com/users/18175", "pm_score": 1, "selected": false, "text": "<p>In the case of a static method calling your static method, there is no calling instance.</p>\n\n<p>Find a different way to accomplish whatever you are trying to do.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4299/" ]
Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself? For example, something along these lines ``` class A { public void DoSomething() { StaticClass.ExecuteMethod(); } } class B { public void DoSomething() { SomeOtherClass.ExecuteMethod(); } } public class SomeOtherClass { public static void ExecuteMethod() { // Returns an instance of A if called from class A // or an instance of B if called from class B. object caller = getCallingInstance(); } } ``` I can get the type using [System.Diagnostics.StackTrace.GetFrames](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframes.aspx), but is there a way to get a reference to the actual instance? I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in. ``` ExecuteMethod(instance) ``` And I just wondered if this was possible and still being able to access the instance. ``` ExecuteMethod() ``` --- @Steve Cooper: I hadn't considered extension methods. Some variation of that might work.
I do not believe you can. Even the StackTrace and StackFrame classes just give you naming information, not access to instances. I'm not sure exactly why you'd want to do this, but know that even if you could do it it would likely be very slow. A better solution would be to push the instance to a thread local context before calling ExecuteMethod that you can retrieve within it or just pass the instance.
97,197
<p>The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world.</p> <p>Does anybody have a more detailed explanation of the problem?</p>
[ { "answer_id": 97223, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 5, "selected": false, "text": "<p>Suppose you have COMPANY and EMPLOYEE. COMPANY has many EMPLOYEES (i.e. EMPLOYEE has a field COMPANY_ID).</p>\n\n<p>In some O/R configurations, when you have a mapped Company object and go to access its Employee objects, the O/R tool will do one select for every employee, wheras if you were just doing things in straight SQL, you could <code>select * from employees where company_id = XX</code>. Thus N (# of employees) plus 1 (company)</p>\n\n<p>This is how the initial versions of EJB Entity Beans worked. I believe things like Hibernate have done away with this, but I'm not too sure. Most tools usually include info as to their strategy for mapping.</p>\n" }, { "answer_id": 97253, "author": "Matt Solnit", "author_id": 6198, "author_profile": "https://Stackoverflow.com/users/6198", "pm_score": 11, "selected": true, "text": "<p>Let's say you have a collection of <code>Car</code> objects (database rows), and each <code>Car</code> has a collection of <code>Wheel</code> objects (also rows). In other words, <code>Car</code> → <code>Wheel</code> is a 1-to-many relationship.</p>\n<p>Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:</p>\n<pre><code>SELECT * FROM Cars;\n</code></pre>\n<p>And then <strong>for each <code>Car</code>:</strong></p>\n<pre><code>SELECT * FROM Wheel WHERE CarId = ?\n</code></pre>\n<p>In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.</p>\n<p>Alternatively, one could get all wheels and perform the lookups in memory:</p>\n<pre><code>SELECT * FROM Wheel;\n</code></pre>\n<p>This reduces the number of round-trips to the database from N+1 to 2.\nMost ORM tools give you several ways to prevent N+1 selects.</p>\n<p>Reference: <em><a href=\"http://www.manning.com/bauer2/\" rel=\"noreferrer\">Java Persistence with Hibernate</a></em>, chapter 13.</p>\n" }, { "answer_id": 97308, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 7, "selected": false, "text": "<pre><code>SELECT \ntable1.*\n, table2.*\nINNER JOIN table2 ON table2.SomeFkId = table1.SomeId\n</code></pre>\n\n<p>That gets you a result set where child rows in table2 cause duplication by returning the table1 results for each child row in table2. O/R mappers should differentiate table1 instances based on a unique key field, then use all the table2 columns to populate child instances.</p>\n\n<pre><code>SELECT table1.*\n\nSELECT table2.* WHERE SomeFkId = #\n</code></pre>\n\n<p>The N+1 is where the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.</p>\n\n<p>Consider:</p>\n\n<pre><code>class House\n{\n int Id { get; set; }\n string Address { get; set; }\n Person[] Inhabitants { get; set; }\n}\n\nclass Person\n{\n string Name { get; set; }\n int HouseId { get; set; }\n}\n</code></pre>\n\n<p>and tables with a similar structure. A single query for the address \"22 Valley St\" may return:</p>\n\n<pre><code>Id Address Name HouseId\n1 22 Valley St Dave 1\n1 22 Valley St John 1\n1 22 Valley St Mike 1\n</code></pre>\n\n<p>The O/RM should fill an instance of Home with ID=1, Address=\"22 Valley St\" and then populate the Inhabitants array with People instances for Dave, John, and Mike with just one query.</p>\n\n<p>A N+1 query for the same address used above would result in:</p>\n\n<pre><code>Id Address\n1 22 Valley St\n</code></pre>\n\n<p>with a separate query like</p>\n\n<pre><code>SELECT * FROM Person WHERE HouseId = 1\n</code></pre>\n\n<p>and resulting in a separate data set like</p>\n\n<pre><code>Name HouseId\nDave 1\nJohn 1\nMike 1\n</code></pre>\n\n<p>and the final result being the same as above with the single query.</p>\n\n<p>The advantages to single select is that you get all the data up front which may be what you ultimately desire. The advantages to N+1 is query complexity is reduced and you can use lazy loading where the child result sets are only loaded upon first request.</p>\n" }, { "answer_id": 97311, "author": "Joe Dean", "author_id": 5917, "author_profile": "https://Stackoverflow.com/users/5917", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://web.archive.org/web/20160310145416/http://www.realsolve.co.uk/site/tech/hib-tip-pitfall.php?name=why-lazy\" rel=\"noreferrer\">Here's a good description of the problem</a></p>\n\n<p>Now that you understand the problem it can typically be avoided by doing a join fetch in your query. This basically forces the fetch of the lazy loaded object so the data is retrieved in one query instead of n+1 queries. Hope this helps.</p>\n" }, { "answer_id": 568733, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The supplied link has a very simply example of the n + 1 problem. If you apply it to Hibernate it's basically talking about the same thing. When you query for an object, the entity is loaded but any associations (unless configured otherwise) will be lazy loaded. Hence one query for the root objects and another query to load the associations for each of these. 100 objects returned means one initial query and then 100 additional queries to get the association for each, n + 1.</p>\n\n<p><a href=\"http://pramatr.com/2009/02/05/sql-n-1-selects-explained/\" rel=\"noreferrer\">http://pramatr.com/2009/02/05/sql-n-1-selects-explained/</a></p>\n" }, { "answer_id": 1826225, "author": "Summy", "author_id": 210353, "author_profile": "https://Stackoverflow.com/users/210353", "pm_score": 6, "selected": false, "text": "<p>Supplier with a one-to-many relationship with Product. One Supplier has (supplies) many Products.</p>\n\n<pre><code>***** Table: Supplier *****\n+-----+-------------------+\n| ID | NAME |\n+-----+-------------------+\n| 1 | Supplier Name 1 |\n| 2 | Supplier Name 2 |\n| 3 | Supplier Name 3 |\n| 4 | Supplier Name 4 |\n+-----+-------------------+\n\n***** Table: Product *****\n+-----+-----------+--------------------+-------+------------+\n| ID | NAME | DESCRIPTION | PRICE | SUPPLIERID |\n+-----+-----------+--------------------+-------+------------+\n|1 | Product 1 | Name for Product 1 | 2.0 | 1 |\n|2 | Product 2 | Name for Product 2 | 22.0 | 1 |\n|3 | Product 3 | Name for Product 3 | 30.0 | 2 |\n|4 | Product 4 | Name for Product 4 | 7.0 | 3 |\n+-----+-----------+--------------------+-------+------------+\n</code></pre>\n\n<p>Factors:</p>\n\n<ul>\n<li><p>Lazy mode for Supplier set to “true” (default)</p></li>\n<li><p>Fetch mode used for querying on Product is Select</p></li>\n<li><p>Fetch mode (default): Supplier information is accessed</p></li>\n<li><p>Caching does not play a role for the first time the</p></li>\n<li><p>Supplier is accessed</p></li>\n</ul>\n\n<p>Fetch mode is Select Fetch (default)</p>\n\n<pre><code>// It takes Select fetch mode as a default\nQuery query = session.createQuery( \"from Product p\");\nList list = query.list();\n// Supplier is being accessed\ndisplayProductsListWithSupplierName(results);\n\nselect ... various field names ... from PRODUCT\nselect ... various field names ... from SUPPLIER where SUPPLIER.id=?\nselect ... various field names ... from SUPPLIER where SUPPLIER.id=?\nselect ... various field names ... from SUPPLIER where SUPPLIER.id=?\n</code></pre>\n\n<p>Result:</p>\n\n<ul>\n<li>1 select statement for Product</li>\n<li>N select statements for Supplier</li>\n</ul>\n\n<p>This is N+1 select problem!</p>\n" }, { "answer_id": 3298897, "author": "Anoop Isaac", "author_id": 397897, "author_profile": "https://Stackoverflow.com/users/397897", "pm_score": 4, "selected": false, "text": "<p>In my opinion the article written in <a href=\"http://www.realsolve.co.uk/site/tech/hib-tip-pitfall.php?name=why-lazy\" rel=\"noreferrer\">Hibernate Pitfall: Why Relationships Should Be Lazy</a> is exactly opposite of real N+1 issue is.</p>\n\n<p>If you need correct explanation please refer <a href=\"http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html#performance-fetching\" rel=\"noreferrer\">Hibernate - Chapter 19: Improving Performance - Fetching Strategies</a></p>\n\n<blockquote>\n <p>Select fetching (the default) is\n extremely vulnerable to N+1 selects\n problems, so we might want to enable\n join fetching</p>\n</blockquote>\n" }, { "answer_id": 6299416, "author": "rorycl", "author_id": 299031, "author_profile": "https://Stackoverflow.com/users/299031", "pm_score": 5, "selected": false, "text": "<p>We moved away from the ORM in Django because of this problem. Basically, if you try and do</p>\n\n<pre><code>for p in person:\n print p.car.colour\n</code></pre>\n\n<p>The ORM will happily return all people (typically as instances of a Person object), but then it will need to query the car table for each Person.</p>\n\n<p>A simple and very effective approach to this is something I call \"<strong>fanfolding</strong>\", which avoids the nonsensical idea that query results from a relational database should map back to the original tables from which the query is composed.</p>\n\n<p>Step 1: Wide select</p>\n\n<pre><code> select * from people_car_colour; # this is a view or sql function\n</code></pre>\n\n<p>This will return something like</p>\n\n<pre><code> p.id | p.name | p.telno | car.id | car.type | car.colour\n -----+--------+---------+--------+----------+-----------\n 2 | jones | 2145 | 77 | ford | red\n 2 | jones | 2145 | 1012 | toyota | blue\n 16 | ashby | 124 | 99 | bmw | yellow\n</code></pre>\n\n<p>Step 2: Objectify</p>\n\n<p>Suck the results into a generic object creator with an argument to split after the third item. This means that \"jones\" object won't be made more than once.</p>\n\n<p>Step 3: Render</p>\n\n<pre><code>for p in people:\n print p.car.colour # no more car queries\n</code></pre>\n\n<p>See <a href=\"http://campbell-lange.net/company/articles/dbwrapper/\" rel=\"noreferrer\">this web page</a> for an implementation of <strong>fanfolding</strong> for python.</p>\n" }, { "answer_id": 10905819, "author": "Nathan", "author_id": 497982, "author_profile": "https://Stackoverflow.com/users/497982", "pm_score": 4, "selected": false, "text": "<p>Check Ayende post on the topic: <a href=\"http://ayende.com/blog/1328/combating-the-select-n-1-problem-in-nhibernate\" rel=\"nofollow noreferrer\">Combating the Select N + 1 Problem In NHibernate</a>.</p>\n\n<p>Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, \"N\" being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.</p>\n\n<p>More database query calls → more latency time → decreased application/database performance.</p>\n\n<p>However, ORMs have options to avoid this problem, mainly using JOINs.</p>\n" }, { "answer_id": 12927312, "author": "Adam Gent", "author_id": 318174, "author_profile": "https://Stackoverflow.com/users/318174", "pm_score": 3, "selected": false, "text": "<p>The issue as others have stated more elegantly is that you either have a Cartesian product of the OneToMany columns or you're doing N+1 Selects. Either possible gigantic resultset or chatty with the database, respectively.</p>\n\n<p>I'm surprised this isn't mentioned but this how I have gotten around this issue... <strong>I make a semi-temporary ids table</strong>. <a href=\"https://stackoverflow.com/a/11119642/318174\">I also do this when you have the <code>IN ()</code> clause limitation</a>. </p>\n\n<p>This doesn't work for all cases (probably not even a majority) but it works particularly well if you have a lot of child objects such that the Cartesian product will get out of hand (ie lots of <code>OneToMany</code> columns the number of results will be a multiplication of the columns) and its more of a batch like job.</p>\n\n<p>First you insert your parent object ids as batch into an ids table.\nThis batch_id is something we generate in our app and hold onto.</p>\n\n<pre><code>INSERT INTO temp_ids \n (product_id, batch_id)\n (SELECT p.product_id, ? \n FROM product p ORDER BY p.product_id\n LIMIT ? OFFSET ?);\n</code></pre>\n\n<p>Now for each <code>OneToMany</code> column you just do a <code>SELECT</code> on the ids table <code>INNER JOIN</code>ing the child table with a <code>WHERE batch_id=</code> (or vice versa). You just want to make sure you order by the id column as it will make merging result columns easier (otherwise you will need a HashMap/Table for the entire result set which may not be that bad).</p>\n\n<p>Then you just periodically clean the ids table.</p>\n\n<p>This also works particularly well if the user selects say 100 or so distinct items for some sort of bulk processing. Put the 100 distinct ids in the temporary table.</p>\n\n<p>Now the number of queries you are doing is by the number of OneToMany columns.</p>\n" }, { "answer_id": 17621164, "author": "martins.tuga", "author_id": 2004087, "author_profile": "https://Stackoverflow.com/users/2004087", "pm_score": 1, "selected": false, "text": "<p>Take Matt Solnit example, imagine that you define an association between Car and Wheels as LAZY and you need some Wheels fields. This means that after the first select, hibernate is going to do \"Select * from Wheels where car_id = :id\" FOR EACH Car.</p>\n\n<p>This makes the first select and more 1 select by each N car, that's why it's called n+1 problem.</p>\n\n<p>To avoid this, make the association fetch as eager, so that hibernate loads data with a join.</p>\n\n<p>But attention, if many times you don't access associated Wheels, it's better to keep it LAZY or change fetch type with Criteria.</p>\n" }, { "answer_id": 20996154, "author": "Mark Goodge", "author_id": 472204, "author_profile": "https://Stackoverflow.com/users/472204", "pm_score": 6, "selected": false, "text": "<p>I can't comment directly on other answers, because I don't have enough reputation. But it's worth noting that the problem essentially only arises because, historically, a lot of dbms have been quite poor when it comes to handling joins (MySQL being a particularly noteworthy example). So n+1 has, often, been notably faster than a join. And then there are ways to improve on n+1 but still without needing a join, which is what the original problem relates to.</p>\n\n<p>However, MySQL is now a lot better than it used to be when it comes to joins. When I first learned MySQL, I used joins a lot. Then I discovered how slow they are, and switched to n+1 in the code instead. But, recently, I've been moving back to joins, because MySQL is now a heck of a lot better at handling them than it was when I first started using it.</p>\n\n<p>These days, a simple join on a properly indexed set of tables is rarely a problem, in performance terms. And if it does give a performance hit, then the use of index hints often solves them.</p>\n\n<p>This is discussed here by one of the MySQL development team:</p>\n\n<p><a href=\"http://jorgenloland.blogspot.co.uk/2013/02/dbt-3-q3-6-x-performance-in-mysql-5610.html\" rel=\"noreferrer\">http://jorgenloland.blogspot.co.uk/2013/02/dbt-3-q3-6-x-performance-in-mysql-5610.html</a></p>\n\n<p>So the summary is: If you've been avoiding joins in the past because of MySQL's abysmal performance with them, then try again on the latest versions. You'll probably be pleasantly surprised.</p>\n" }, { "answer_id": 26799148, "author": "Redoman", "author_id": 988591, "author_profile": "https://Stackoverflow.com/users/988591", "pm_score": 5, "selected": false, "text": "<p>The good short explanation of the problem can be found in the <a href=\"https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/\" rel=\"nofollow noreferrer\">Phabricator documentation</a>:</p>\n<blockquote>\n<p>The N+1 query problem is a common performance antipattern. It looks like this:</p>\n<pre><code>$cats = load_cats();\nforeach ($cats as $cat) {\n $cats_hats =&gt; load_hats_for_cat($cat);\n // ...\n}\n</code></pre>\n<p>Assuming <code>load_cats()</code> has an implementation that boils down to:</p>\n<pre><code>SELECT * FROM cat WHERE ...\n</code></pre>\n<p>..and <code>load_hats_for_cat($cat)</code> has an implementation something like this:</p>\n<pre><code>SELECT * FROM hat WHERE catID = ...\n</code></pre>\n<p>..you will issue &quot;N+1&quot; queries when the code executes, where N is the number of cats:</p>\n<pre><code>SELECT * FROM cat WHERE ...\nSELECT * FROM hat WHERE catID = 1\nSELECT * FROM hat WHERE catID = 2\nSELECT * FROM hat WHERE catID = 3\nSELECT * FROM hat WHERE catID = 4\n...\n</code></pre>\n</blockquote>\n<p>Solution:</p>\n<blockquote>\n<p>It is much faster to issue 1 query which returns 100 results than to\nissue 100 queries which each return 1 result.</p>\n</blockquote>\n<blockquote>\n<p>Load all your data before iterating through it.</p>\n</blockquote>\n" }, { "answer_id": 29644570, "author": "bedrin", "author_id": 504452, "author_profile": "https://Stackoverflow.com/users/504452", "pm_score": 3, "selected": false, "text": "<p>N+1 select issue is a pain, and it makes sense to detect such cases in unit tests.\nI have developed a small library for verifying the number of queries executed by a given test method or just an arbitrary block of code - <a href=\"https://github.com/bedrin/jdbc-sniffer\" rel=\"noreferrer\">JDBC Sniffer</a></p>\n\n<p>Just add a special JUnit rule to your test class and place annotation with expected number of queries on your test methods:</p>\n\n<pre><code>@Rule\npublic final QueryCounter queryCounter = new QueryCounter();\n\n@Expectation(atMost = 3)\n@Test\npublic void testInvokingDatabase() {\n // your JDBC or JPA code\n}\n</code></pre>\n" }, { "answer_id": 39696775, "author": "Vlad Mihalcea", "author_id": 1025118, "author_profile": "https://Stackoverflow.com/users/1025118", "pm_score": 8, "selected": false, "text": "<h2>What is the N+1 query problem</h2>\n<p>The N+1 query problem happens when the data access framework executed N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.</p>\n<p>The larger the value of N, the more queries will be executed, the larger the performance impact. And, unlike the slow query log that can help you find slow running queries, the N+1 issue won’t be spot because each individual additional query runs sufficiently fast to not trigger the slow query log.</p>\n<p>The problem is executing a large number of additional queries that, overall, take sufficient time to slow down response time.</p>\n<p>Let’s consider we have the following post and post_comments database tables which form a one-to-many table relationship:</p>\n<p><a href=\"https://i.stack.imgur.com/T1uWG.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/T1uWG.png\" alt=\"The post and post_comments tables\" /></a></p>\n<p>We are going to create the following 4 <code>post</code> rows:</p>\n<pre><code>INSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 1', 1)\n \nINSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 2', 2)\n \nINSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 3', 3)\n \nINSERT INTO post (title, id)\nVALUES ('High-Performance Java Persistence - Part 4', 4)\n</code></pre>\n<p>And, we will also create 4 <code>post_comment</code> child records:</p>\n<pre><code>INSERT INTO post_comment (post_id, review, id)\nVALUES (1, 'Excellent book to understand Java Persistence', 1)\n \nINSERT INTO post_comment (post_id, review, id)\nVALUES (2, 'Must-read for Java developers', 2)\n \nINSERT INTO post_comment (post_id, review, id)\nVALUES (3, 'Five Stars', 3)\n \nINSERT INTO post_comment (post_id, review, id)\nVALUES (4, 'A great reference book', 4)\n</code></pre>\n<h2>N+1 query problem with plain SQL</h2>\n<p>If you select the <code>post_comments</code> using this SQL query:</p>\n<pre><code>List&lt;Tuple&gt; comments = entityManager.createNativeQuery(&quot;&quot;&quot;\n SELECT\n pc.id AS id,\n pc.review AS review,\n pc.post_id AS postId\n FROM post_comment pc\n &quot;&quot;&quot;, Tuple.class)\n.getResultList();\n</code></pre>\n<p>And, later, you decide to fetch the associated <code>post</code> <code>title</code> for each <code>post_comment</code>:</p>\n<pre><code>for (Tuple comment : comments) {\n String review = (String) comment.get(&quot;review&quot;);\n Long postId = ((Number) comment.get(&quot;postId&quot;)).longValue();\n \n String postTitle = (String) entityManager.createNativeQuery(&quot;&quot;&quot;\n SELECT\n p.title\n FROM post p\n WHERE p.id = :postId\n &quot;&quot;&quot;)\n .setParameter(&quot;postId&quot;, postId)\n .getSingleResult();\n \n LOGGER.info(\n &quot;The Post '{}' got this review '{}'&quot;,\n postTitle,\n review\n );\n}\n</code></pre>\n<p>You are going to trigger the N+1 query issue because, instead of one SQL query, you executed 5 (1 + 4):</p>\n<pre><code>SELECT\n pc.id AS id,\n pc.review AS review,\n pc.post_id AS postId\nFROM post_comment pc\n \nSELECT p.title FROM post p WHERE p.id = 1\n-- The Post 'High-Performance Java Persistence - Part 1' got this review\n-- 'Excellent book to understand Java Persistence'\n \nSELECT p.title FROM post p WHERE p.id = 2\n-- The Post 'High-Performance Java Persistence - Part 2' got this review\n-- 'Must-read for Java developers'\n \nSELECT p.title FROM post p WHERE p.id = 3\n-- The Post 'High-Performance Java Persistence - Part 3' got this review\n-- 'Five Stars'\n \nSELECT p.title FROM post p WHERE p.id = 4\n-- The Post 'High-Performance Java Persistence - Part 4' got this review\n-- 'A great reference book'\n</code></pre>\n<p>Fixing the N+1 query issue is very easy. All you need to do is extract all the data you need in the original SQL query, like this:</p>\n<pre><code>List&lt;Tuple&gt; comments = entityManager.createNativeQuery(&quot;&quot;&quot;\n SELECT\n pc.id AS id,\n pc.review AS review,\n p.title AS postTitle\n FROM post_comment pc\n JOIN post p ON pc.post_id = p.id\n &quot;&quot;&quot;, Tuple.class)\n.getResultList();\n \nfor (Tuple comment : comments) {\n String review = (String) comment.get(&quot;review&quot;);\n String postTitle = (String) comment.get(&quot;postTitle&quot;);\n \n LOGGER.info(\n &quot;The Post '{}' got this review '{}'&quot;,\n postTitle,\n review\n );\n}\n</code></pre>\n<p>This time, only one SQL query is executed to fetch all the data we are further interested in using.</p>\n<h2>N+1 query problem with JPA and Hibernate</h2>\n<p>When using JPA and Hibernate, there are several ways you can trigger the N+1 query issue, so it’s very important to know how you can avoid these situations.</p>\n<p>For the next examples, consider we are mapping the <code>post</code> and <code>post_comments</code> tables to the following entities:</p>\n<p><a href=\"https://i.stack.imgur.com/rZJne.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/rZJne.png\" alt=\"Post and PostComment entities\" /></a></p>\n<p>The JPA mappings look like this:</p>\n<pre><code>@Entity(name = &quot;Post&quot;)\n@Table(name = &quot;post&quot;)\npublic class Post {\n \n @Id\n private Long id;\n \n private String title;\n \n //Getters and setters omitted for brevity\n}\n \n@Entity(name = &quot;PostComment&quot;)\n@Table(name = &quot;post_comment&quot;)\npublic class PostComment {\n \n @Id\n private Long id;\n \n @ManyToOne\n private Post post;\n \n private String review;\n \n //Getters and setters omitted for brevity\n}\n</code></pre>\n<h2><code>FetchType.EAGER</code></h2>\n<p>Using <code>FetchType.EAGER</code> either implicitly or explicitly for your JPA associations is a bad idea because you are going to fetch way more data that you need. More, the <code>FetchType.EAGER</code> strategy is also prone to N+1 query issues.</p>\n<p>Unfortunately, the <code>@ManyToOne</code> and <code>@OneToOne</code> associations use <code>FetchType.EAGER</code> by default, so if your mappings look like this:</p>\n<pre><code>@ManyToOne\nprivate Post post;\n</code></pre>\n<p>You are using the <code>FetchType.EAGER</code> strategy, and, every time you forget to use <code>JOIN FETCH</code> when loading some <code>PostComment</code> entities with a JPQL or Criteria API query:</p>\n<pre><code>List&lt;PostComment&gt; comments = entityManager\n.createQuery(&quot;&quot;&quot;\n select pc\n from PostComment pc\n &quot;&quot;&quot;, PostComment.class)\n.getResultList();\n</code></pre>\n<p>You are going to trigger the N+1 query issue:</p>\n<pre><code>SELECT \n pc.id AS id1_1_, \n pc.post_id AS post_id3_1_, \n pc.review AS review2_1_ \nFROM \n post_comment pc\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 1\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 2\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 3\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 4\n</code></pre>\n<p>Notice the additional SELECT statements that are executed because the <code>post</code> association has to be fetched prior to returning the <code>List</code> of <code>PostComment</code> entities.</p>\n<p>Unlike the default fetch plan, which you are using when calling the <code>find</code> method of the <code>EntityManager</code>, a JPQL or Criteria API query defines an explicit plan that Hibernate cannot change by injecting a JOIN FETCH automatically. So, you need to do it manually.</p>\n<p>If you didn't need the <code>post</code> association at all, you are out of luck when using <code>FetchType.EAGER</code> because there is no way to avoid fetching it. That's why it's better to use <code>FetchType.LAZY</code> by default.</p>\n<p>But, if you wanted to use <code>post</code> association, then you can use <code>JOIN FETCH</code> to avoid the N+1 query problem:</p>\n<pre><code>List&lt;PostComment&gt; comments = entityManager.createQuery(&quot;&quot;&quot;\n select pc\n from PostComment pc\n join fetch pc.post p\n &quot;&quot;&quot;, PostComment.class)\n.getResultList();\n\nfor(PostComment comment : comments) {\n LOGGER.info(\n &quot;The Post '{}' got this review '{}'&quot;, \n comment.getPost().getTitle(), \n comment.getReview()\n );\n}\n</code></pre>\n<p>This time, Hibernate will execute a single SQL statement:</p>\n<pre><code>SELECT \n pc.id as id1_1_0_, \n pc.post_id as post_id3_1_0_, \n pc.review as review2_1_0_, \n p.id as id1_0_1_, \n p.title as title2_0_1_ \nFROM \n post_comment pc \nINNER JOIN \n post p ON pc.post_id = p.id\n \n-- The Post 'High-Performance Java Persistence - Part 1' got this review \n-- 'Excellent book to understand Java Persistence'\n\n-- The Post 'High-Performance Java Persistence - Part 2' got this review \n-- 'Must-read for Java developers'\n\n-- The Post 'High-Performance Java Persistence - Part 3' got this review \n-- 'Five Stars'\n\n-- The Post 'High-Performance Java Persistence - Part 4' got this review \n-- 'A great reference book'\n</code></pre>\n<h2><code>FetchType.LAZY</code></h2>\n<p>Even if you switch to using <code>FetchType.LAZY</code> explicitly for all associations, you can still bump into the N+1 issue.</p>\n<p>This time, the <code>post</code> association is mapped like this:</p>\n<pre><code>@ManyToOne(fetch = FetchType.LAZY)\nprivate Post post;\n</code></pre>\n<p>Now, when you fetch the <code>PostComment</code> entities:</p>\n<pre><code>List&lt;PostComment&gt; comments = entityManager\n.createQuery(&quot;&quot;&quot;\n select pc\n from PostComment pc\n &quot;&quot;&quot;, PostComment.class)\n.getResultList();\n</code></pre>\n<p>Hibernate will execute a single SQL statement:</p>\n<pre><code>SELECT \n pc.id AS id1_1_, \n pc.post_id AS post_id3_1_, \n pc.review AS review2_1_ \nFROM \n post_comment pc\n</code></pre>\n<p>But, if afterward, you are going to reference the lazy-loaded <code>post</code> association:</p>\n<pre><code>for(PostComment comment : comments) {\n LOGGER.info(\n &quot;The Post '{}' got this review '{}'&quot;, \n comment.getPost().getTitle(), \n comment.getReview()\n );\n}\n</code></pre>\n<p>You will get the N+1 query issue:</p>\n<pre><code>SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 1\n-- The Post 'High-Performance Java Persistence - Part 1' got this review \n-- 'Excellent book to understand Java Persistence'\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 2\n-- The Post 'High-Performance Java Persistence - Part 2' got this review \n-- 'Must-read for Java developers'\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 3\n-- The Post 'High-Performance Java Persistence - Part 3' got this review \n-- 'Five Stars'\n\nSELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 4\n-- The Post 'High-Performance Java Persistence - Part 4' got this review \n-- 'A great reference book'\n</code></pre>\n<p>Because the <code>post</code> association is fetched lazily, a secondary SQL statement will be executed when accessing the lazy association in order to build the log message.</p>\n<p>Again, the fix consists in adding a <code>JOIN FETCH</code> clause to the JPQL query:</p>\n<pre><code>List&lt;PostComment&gt; comments = entityManager.createQuery(&quot;&quot;&quot;\n select pc\n from PostComment pc\n join fetch pc.post p\n &quot;&quot;&quot;, PostComment.class)\n.getResultList();\n\nfor(PostComment comment : comments) {\n LOGGER.info(\n &quot;The Post '{}' got this review '{}'&quot;, \n comment.getPost().getTitle(), \n comment.getReview()\n );\n}\n</code></pre>\n<p>And, just like in the <code>FetchType.EAGER</code> example, this JPQL query will generate a single SQL statement.</p>\n<blockquote>\n<p>Even if you are using <code>FetchType.LAZY</code> and don't reference the child association of a bidirectional <code>@OneToOne</code> JPA relationship, you can still trigger the N+1 query issue.</p>\n</blockquote>\n<h2>How to automatically detect the N+1 query issue</h2>\n<p>If you want to automatically detect N+1 query issue in your data access layer, you can use the <a href=\"https://github.com/vladmihalcea/db-util\" rel=\"noreferrer\"><code>db-util</code></a> open-source project.</p>\n<p>First, you need to add the following Maven dependency:</p>\n<pre><code>&lt;dependency&gt;\n &lt;groupId&gt;com.vladmihalcea&lt;/groupId&gt;\n &lt;artifactId&gt;db-util&lt;/artifactId&gt;\n &lt;version&gt;${db-util.version}&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n<p>Afterward, you just have to use <code>SQLStatementCountValidator</code> utility to assert the underlying SQL statements that get generated:</p>\n<pre><code>SQLStatementCountValidator.reset();\n\nList&lt;PostComment&gt; comments = entityManager.createQuery(&quot;&quot;&quot;\n select pc\n from PostComment pc\n &quot;&quot;&quot;, PostComment.class)\n.getResultList();\n\nSQLStatementCountValidator.assertSelectCount(1);\n</code></pre>\n<p>In case you are using <code>FetchType.EAGER</code> and run the above test case, you will get the following test case failure:</p>\n<pre><code>SELECT \n pc.id as id1_1_, \n pc.post_id as post_id3_1_, \n pc.review as review2_1_ \nFROM \n post_comment pc\n\nSELECT p.id as id1_0_0_, p.title as title2_0_0_ FROM post p WHERE p.id = 1\n\nSELECT p.id as id1_0_0_, p.title as title2_0_0_ FROM post p WHERE p.id = 2\n\n\n-- SQLStatementCountMismatchException: Expected 1 statement(s) but recorded 3 instead!\n</code></pre>\n" }, { "answer_id": 64487275, "author": "Adam Gaj", "author_id": 14231619, "author_profile": "https://Stackoverflow.com/users/14231619", "pm_score": 0, "selected": false, "text": "<p>N+1 SELECT problem is really hard to spot, especially in projects with large domain, to the moment when it starts degrading the performance. Even if the problem is fixed i.e. by adding eager loading, a further development may break the solution and/or introduce N+1 SELECT problem again in other places.</p>\n<p>I've created open source library <a href=\"https://github.com/adgadev/jplusone\" rel=\"nofollow noreferrer\">jplusone</a> to address those problems in JPA based Spring Boot Java applications. The library provides two major features:</p>\n<ol>\n<li>Generates reports correlating SQL statements with executions of JPA operations which triggered them and places in source code of your application which were involved in it</li>\n</ol>\n<pre>\n2020-10-22 18:41:43.236 DEBUG 14913 --- [ main] c.a.j.core.report.ReportGenerator :\n ROOT\n com.adgadev.jplusone.test.domain.bookshop.BookshopControllerTest.shouldGetBookDetailsLazily(BookshopControllerTest.java:65)\n com.adgadev.jplusone.test.domain.bookshop.BookshopController.getSampleBookUsingLazyLoading(BookshopController.java:31)\n com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading [PROXY]\n SESSION BOUNDARY\n OPERATION [IMPLICIT]\n com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:35)\n com.adgadev.jplusone.test.domain.bookshop.Author.getName [PROXY]\n com.adgadev.jplusone.test.domain.bookshop.Author [FETCHING ENTITY]\n STATEMENT [READ]\n select [...] from\n author author0_\n left outer join genre genre1_ on author0_.genre_id=genre1_.id\n where\n author0_.id=1\n OPERATION [IMPLICIT]\n com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:36)\n com.adgadev.jplusone.test.domain.bookshop.Author.countWrittenBooks(Author.java:53)\n com.adgadev.jplusone.test.domain.bookshop.Author.books [FETCHING COLLECTION]\n STATEMENT [READ]\n select [...] from\n book books0_\n where\n books0_.author_id=1\n</pre>\n<ol start=\"2\">\n<li>Provides API which allows to write tests checking how effectively your application is using JPA (i.e. assert amount of lazy loading operations )</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>@SpringBootTest\nclass LazyLoadingTest {\n\n @Autowired\n private JPlusOneAssertionContext assertionContext;\n\n @Autowired\n private SampleService sampleService;\n\n @Test\n public void shouldBusinessCheckOperationAgainstJPlusOneAssertionRule() {\n JPlusOneAssertionRule rule = JPlusOneAssertionRule\n .within().lastSession()\n .shouldBe().noImplicitOperations().exceptAnyOf(exclusions -&gt; exclusions\n .loadingEntity(Author.class).times(atMost(2))\n .loadingCollection(Author.class, &quot;books&quot;)\n );\n\n // trigger business operation which you wish to be asserted against the rule,\n // i.e. calling a service or sending request to your API controller\n sampleService.executeBusinessOperation();\n\n rule.check(assertionContext);\n }\n}\n</code></pre>\n" }, { "answer_id": 65628609, "author": "Toma Velev", "author_id": 5459212, "author_profile": "https://Stackoverflow.com/users/5459212", "pm_score": 2, "selected": false, "text": "<p>Without going into tech stack implementation details, architecturally speaking there are at least two solutions to N + 1 Problem:</p>\n<ul>\n<li>Have Only 1 - big query - with Joins. This makes a lot of information be transported from the database to the application layer, especially if there are multiple child records. The typical result of a database is a set of rows, not graph of objects (there are solutions to that with different DB systems)</li>\n<li>Have Two(or more for more children needed to be joined) Queries - 1 for the parent and after you have them - query by IDs the children and map them. This will minimize data transfer between the DB and APP layers.</li>\n</ul>\n" }, { "answer_id": 69531377, "author": "Jimmy", "author_id": 11527968, "author_profile": "https://Stackoverflow.com/users/11527968", "pm_score": 3, "selected": false, "text": "<p><strong>N+1 problem in Hibernate &amp; Spring Data JPA</strong></p>\n<p>N+1 problem is a performance issue in Object Relational Mapping that fires multiple select queries (N+1 to be exact, where N = number of records in table) in database for a single select query at application layer. Hibernate &amp; Spring Data JPA provides multiple ways to catch and address this performance problem.</p>\n<p><strong>What is N+1 Problem?</strong></p>\n<p>To understand N+1 problem, lets consider with a scenario. Let’s say we have a collection of <em>User</em> objects mapped to <em>DB_USER</em> table in database, and each user has collection or <em>Role</em> mapped to <em>DB_ROLE</em> table using a joining table <em>DB_USER_ROLE</em>. At the ORM level a <strong>User</strong> has <strong>many to many</strong> relationship with <strong>Role</strong>.</p>\n<pre><code>Entity Model\n@Entity\n@Table(name = &quot;DB_USER&quot;)\npublic class User {\n\n @Id\n @GeneratedValue(strategy=GenerationType.AUTO)\n private Long id;\n private String name;\n\n @ManyToMany(fetch = FetchType.LAZY) \n private Set&lt;Role&gt; roles;\n //Getter and Setters \n }\n\n@Entity\n@Table(name = &quot;DB_ROLE&quot;)\npublic class Role {\n\n @Id\n @GeneratedValue(strategy= GenerationType.AUTO)\n private Long id;\n\n private String name;\n //Getter and Setters\n }\n</code></pre>\n<p><strong>A user can have many roles. Roles are loaded Lazily.</strong> Now lets say we want to <em>fetch all users from this table and print roles for each one</em>. Very naive Object Relational implementation could be -\n<strong>UserRepository</strong> with <strong>findAllBy</strong> method</p>\n<pre><code>public interface UserRepository extends CrudRepository&lt;User, Long&gt; {\n\n List&lt;User&gt; findAllBy();\n}\n</code></pre>\n<p><strong>The equivalent SQL queries executed by ORM will be:</strong></p>\n<p>First Get <strong>All User</strong> (1)</p>\n<pre><code>Select * from DB_USER;\n</code></pre>\n<p>Then get <strong>roles for each user</strong> executed N times (where N is number of users)</p>\n<pre><code>Select * from DB_USER_ROLE where userid = &lt;userid&gt;;\n</code></pre>\n<p>So we need <strong>one select for User</strong> and <strong>N additional selects for fetching roles for each user</strong>, where <em>N is total number of users</em>. <em><strong>This is a classic N+1 problem in ORM</strong></em>.</p>\n<p><strong>How to identify it?</strong></p>\n<p>Hibernate provide tracing option that enables SQL logging in the console/logs. <em><strong>using logs you can easily see if hibernate is issuing N+1 queries for a given call</strong></em>.</p>\n<p>If you see multiple entries for SQL for a given select query, then there are high chances that its due to N+1 problem.</p>\n<p><strong>N+1 Resolution</strong></p>\n<p><strong>At SQL level</strong>, what ORM needs to achieve to avoid N+1 is to <em>fire a query that joins the two tables and get the combined results in single query</em>.</p>\n<p><em><strong>Fetch Join SQL that retrieves everything (user and roles) in Single Query</strong></em></p>\n<p><strong>OR Plain SQL</strong></p>\n<pre><code>select user0_.id, role2_.id, user0_.name, role2_.name, roles1_.user_id, roles1_.roles_id from db_user user0_ left outer join db_user_roles roles1_ on user0_.id=roles1_.user_id left outer join db_role role2_ on roles1_.roles_id=role2_.id\n</code></pre>\n<p><strong>Hibernate &amp; Spring Data JPA provide mechanism to solve the N+1 ORM issue.</strong></p>\n<p><strong>1. Spring Data JPA Approach:</strong></p>\n<p>If we are using Spring Data JPA, then we have two options to achieve this - using <em><strong>EntityGraph</strong></em> or using <em><strong>select query with fetch join.</strong></em></p>\n<pre><code>public interface UserRepository extends CrudRepository&lt;User, Long&gt; {\n\n List&lt;User&gt; findAllBy(); \n\n @Query(&quot;SELECT p FROM User p LEFT JOIN FETCH p.roles&quot;) \n List&lt;User&gt; findWithoutNPlusOne();\n\n @EntityGraph(attributePaths = {&quot;roles&quot;}) \n List&lt;User&gt; findAll();\n}\n</code></pre>\n<p>N+1 queries are issued at database level using left join fetch, we resolve the N+1 problem using attributePaths, Spring Data JPA avoids N+1 problem</p>\n<p><strong>2. Hibernate Approach:</strong></p>\n<p>If its pure Hibernate, then the following solutions will work.</p>\n<p>Using <strong>HQL</strong> :</p>\n<pre><code>from User u *join fetch* u.roles roles roles\n</code></pre>\n<p>Using <strong>Criteria</strong> API:</p>\n<pre><code>Criteria criteria = session.createCriteria(User.class);\ncriteria.setFetchMode(&quot;roles&quot;, FetchMode.EAGER);\n</code></pre>\n<p>All these approaches work similar and they issue a similar database query with left join fetch</p>\n" }, { "answer_id": 71123306, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 2, "selected": false, "text": "<h3>A generalisation of N+1</h3>\n<p>The N+1 problem is an ORM specific name of a problem where you move loops that could be reasonably executed on a server to the client. The generic problem isn't specific to ORMs, you can have it with any remote API. <a href=\"https://blog.jooq.org/the-cost-of-jdbc-server-roundtrips/\" rel=\"nofollow noreferrer\">In this article, I've shown how JDBC roundtrips are very costly</a>, if you're calling an API N times instead of only 1 time. The difference in the example is whether you're calling the Oracle PL/SQL procedure:</p>\n<ul>\n<li><code>dbms_output.get_lines</code> (call it once, receive N items)</li>\n<li><code>dbms_output.get_line</code> (call it N times, receive 1 item each time)</li>\n</ul>\n<p>They're logically equivalent, but due to the latency between server and client, you're adding N latency waits to your loop, instead of waiting only once.</p>\n<h3>The ORM case</h3>\n<p>In fact, the ORM-y N+1 problem isn't even ORM specific either, you can achieve it by running your own queries manually as well, e.g. when you do something like this in PL/SQL:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>-- This loop is executed once\nfor parent in (select * from parent) loop\n\n -- This loop is executed N times\n for child in (select * from child where parent_id = parent.id) loop\n ...\n end loop;\nend loop;\n</code></pre>\n<p>It would be much better to implement this using a join (in this case):</p>\n<pre class=\"lang-sql prettyprint-override\"><code>for rec in (\n select *\n from parent p\n join child c on c.parent_id = p.id\n)\nloop\n ...\nend loop;\n</code></pre>\n<p>Now, the loop is executed only once, and the logic of the loop has been moved from the client (PL/SQL) to the server (SQL), which can even optimise it differently, e.g. by running a hash join (<code>O(N)</code>) rather than a nested loop join (<code>O(N log N)</code> with index)</p>\n<h3>Auto-detecting N+1 problems</h3>\n<p>If you're using JDBC, <a href=\"https://blog.jooq.org/using-jooqs-diagnosticsconnection-to-detect-n1-queries/\" rel=\"nofollow noreferrer\">you could use jOOQ as a JDBC proxy behind the scenes to auto-detect your N+1 problems</a>. jOOQ's parser normalises your SQL queries and caches data about consecutive executions of parent and child queries. This even works if your queries aren't exactly the same, but semantically equivalent.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6120/" ]
The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world. Does anybody have a more detailed explanation of the problem?
Let's say you have a collection of `Car` objects (database rows), and each `Car` has a collection of `Wheel` objects (also rows). In other words, `Car` → `Wheel` is a 1-to-many relationship. Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following: ``` SELECT * FROM Cars; ``` And then **for each `Car`:** ``` SELECT * FROM Wheel WHERE CarId = ? ``` In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars. Alternatively, one could get all wheels and perform the lookups in memory: ``` SELECT * FROM Wheel; ``` This reduces the number of round-trips to the database from N+1 to 2. Most ORM tools give you several ways to prevent N+1 selects. Reference: *[Java Persistence with Hibernate](http://www.manning.com/bauer2/)*, chapter 13.
97,228
<p>Ok, here's the breakdown of my project: I have a web project with a "Scripts" subfolder. That folder contains a few javascript files and a copy of JSMin.exe along with a batch file that runs the JSMin.exe on a few of the files. I tried to set up a post build step of 'call "$(ProjectDir)Scripts\jsmin.bat"'. When I perform the build, the batch file is always "exited with code 1." This happens going through Visual Studio or through the msbuild command line. I can run the batch file manually from the Scripts folder and it seems to work as expected, so I'm not sure what the issue here is. The $(ProjectDir)Scripts\jsmin.bat call is in quotes because $(ProjectDir) could have spaces (and in fact does on my machine). I'm not sure what to do at this point. I've tried removing the contents of the batch file as the post build step but that doesn't seem to work either.</p> <p>Ideally I would like to solve this problem through the post or pre-build steps so that the build manager won't have to go through an extra step when deploying code.</p> <p>Thanks!</p>
[ { "answer_id": 97284, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": true, "text": "<p>If you have something in your custom build step that returns an error code, you can add:</p>\n\n<pre><code>exit 0\n</code></pre>\n\n<p>as the last line of your build step. This will stop the build from failing.</p>\n" }, { "answer_id": 97299, "author": "Sam Erwin", "author_id": 18224, "author_profile": "https://Stackoverflow.com/users/18224", "pm_score": 0, "selected": false, "text": "<p>Somehow, and I'm not familiar with the specifics of how .bat files exit, but either JSMin or the batch file execution is exiting with a non-zero return code.</p>\n\n<p>Have you tried running the scripts directly (i.e. not through JSMin.bat) as part of the post-build?</p>\n\n<p>Edit: Looks Hallgrim has it.</p>\n" }, { "answer_id": 167155, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 1, "selected": false, "text": "<p>Do your script or batch files use any path references internally?</p>\n\n<p>I've found that batch files will not work correctly if path references are not fully qualified.\n<br />\n<br /></p>\n\n<p>Example: a batch file called DoStuff.bat uses the echo command to append a text file.</p>\n\n<p>This does <strong>not</strong> work inside the .bat file:</p>\n\n<pre><code>echo \"test\" &gt;&gt;\"test.txt\"\n</code></pre>\n\n<p>This <strong>does work</strong> inside the .bat file:</p>\n\n<pre><code>echo \"test\" &gt;&gt;\"C:\\Temp\\CompileTest\\test.txt\"\n</code></pre>\n\n<p>The Visual Studio <strong>Post-build event command line</strong> is this:</p>\n\n<pre><code>call \"C:\\Temp\\CompileTest\\DoStuff.bat\"\n</code></pre>\n" }, { "answer_id": 219907, "author": "sdanna", "author_id": 16149, "author_profile": "https://Stackoverflow.com/users/16149", "pm_score": 0, "selected": false, "text": "<p>Getting back to this issue now (had to move onto other fires for a bit)</p>\n\n<p>@Jonathan Webb - I tried some the ideas but with no success. In fact I learned we are doing something similar (calling an external program using post build tasks) in other internal projects. I'm inclined to believe it is some interaction with the jsmin.exe tool or some other foolish error on my part.</p>\n\n<p>All is not lost however, another developer turned my attention to the YUI Compressor and its <a href=\"http://www.codeplex.com/YUICompressor\" rel=\"nofollow noreferrer\">implementation in .NET</a>. Through some manual .csproj manipulation I was able to achieve my goals and then some (including CSS compression)!</p>\n" }, { "answer_id": 271948, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A working sollution for this that i use:</p>\n\n<p>CD $(ProjectDir)</p>\n\n<p>DoStuff.bat</p>\n\n<p>No call commands or anything else is needed, this of course if you have the file in your project directory.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16149/" ]
Ok, here's the breakdown of my project: I have a web project with a "Scripts" subfolder. That folder contains a few javascript files and a copy of JSMin.exe along with a batch file that runs the JSMin.exe on a few of the files. I tried to set up a post build step of 'call "$(ProjectDir)Scripts\jsmin.bat"'. When I perform the build, the batch file is always "exited with code 1." This happens going through Visual Studio or through the msbuild command line. I can run the batch file manually from the Scripts folder and it seems to work as expected, so I'm not sure what the issue here is. The $(ProjectDir)Scripts\jsmin.bat call is in quotes because $(ProjectDir) could have spaces (and in fact does on my machine). I'm not sure what to do at this point. I've tried removing the contents of the batch file as the post build step but that doesn't seem to work either. Ideally I would like to solve this problem through the post or pre-build steps so that the build manager won't have to go through an extra step when deploying code. Thanks!
If you have something in your custom build step that returns an error code, you can add: ``` exit 0 ``` as the last line of your build step. This will stop the build from failing.
97,276
<p>If I've got a time_t value from <code>gettimeofday()</code> or compatible in a Unix environment (e.g., Linux, BSD), is there a compact algorithm available that would be able to tell me the corresponding week number within the month?</p> <p>Ideally the return value would work in similar to the way <code>%W</code> behaves in <code>strftime()</code> , except giving the week within the month rather than the week within the year.</p> <p>I think Java has a <code>W</code> formatting token that does something more or less like what I'm asking.</p> <hr> <p>[Everything below written after answers were posted by David Nehme, Branan, and Sparr.]</p> <p>I realized that to return this result in a similar way to <code>%W</code>, we want to count the number of Mondays that have occurred in the month so far. If that number is zero, then 0 should be returned.</p> <p>Thanks to David Nehme and Branan in particular for their solutions which started things on the right track. The bit of code returning [using Branan's variable names] <code>((ts-&gt;mday - 1) / 7)</code> tells the number of complete weeks that have occurred before the current day.</p> <p>However, if we're counting the number of Mondays that have occurred so far, then we want to count the number of integral weeks, including today, then consider if the fractional week left over also contains any Mondays.</p> <p>To figure out whether the fractional week left after taking out the whole weeks contains a Monday, we need to consider <code>ts-&gt;mday % 7</code> and compare it to the day of the week, <code>ts-&gt;wday</code>. This is easy to see if you write out the combinations, but if we insure the day is not Sunday (<code>wday &gt; 0</code>), then anytime <code>ts-&gt;wday &lt;= (ts-&gt;mday % 7)</code> we need to increment the count of Mondays by 1. This comes from considering the number of days since the start of the month, and whether, based on the current day of the week within the the first fractional week, the fractional week contains a Monday.</p> <p>So I would rewrite Branan's return statement as follows:</p> <p><code>return (ts-&gt;tm_mday / 7) + ((ts-&gt;tm_wday &gt; 0) &amp;&amp; (ts-&gt;tm_wday &lt;= (ts-&gt;tm_mday % 7)));</code></p>
[ { "answer_id": 97377, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 1, "selected": false, "text": "<p>Assuming your first week is week 1:</p>\n\n<pre><code>int getWeekOfMonth()\n{\n time_t my_time;\n struct tm *ts;\n\n my_time = time(NULL);\n ts = localtime(&amp;my_time);\n\n return ((ts-&gt;tm_mday -1) / 7) + 1;\n}\n</code></pre>\n\n<p>For 0-index, drop the <code>+1</code> in the return statement.</p>\n" }, { "answer_id": 97475, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 1, "selected": false, "text": "<p>If you define the first week to be days 1-7 of the month, the second week days 8-14, ... then the following code will work.</p>\n\n<pre><code>int week_of_month( const time_t *my_time)\n{\n struct tm *timeinfo;\n\n timeinfo =localtime(my_time);\n return 1 + (timeinfo-&gt;tm_mday-1) / 7;\n\n}\n</code></pre>\n" }, { "answer_id": 97493, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 0, "selected": false, "text": "<p>Consider this pseudo-code, since I am writing it in mostly C syntax but pretending I can borrow functionality from other languages (string->int assignment, string->time conversion). Adapt or expand for your language of choice.</p>\n\n<pre><code>int week_num_in_month(time_t timestamp) {\n int first_weekday_of_month, day_of_month;\n day_of_month = strftime(timestamp,\"%d\");\n first_weekday_of_month = strftime(timefstr(strftime(timestamp,\"%d/%m/01\")),\"%w\");\n return (day_of_month + first_weekday_of_month - 1 ) / 7 + 1;\n}\n</code></pre>\n\n<p>Obviously I am assuming that you want to handle weeks of the month the way the standard time functions handle weeks of the year, as opposed to just days 1-7, 8-13, etc.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I've got a time\_t value from `gettimeofday()` or compatible in a Unix environment (e.g., Linux, BSD), is there a compact algorithm available that would be able to tell me the corresponding week number within the month? Ideally the return value would work in similar to the way `%W` behaves in `strftime()` , except giving the week within the month rather than the week within the year. I think Java has a `W` formatting token that does something more or less like what I'm asking. --- [Everything below written after answers were posted by David Nehme, Branan, and Sparr.] I realized that to return this result in a similar way to `%W`, we want to count the number of Mondays that have occurred in the month so far. If that number is zero, then 0 should be returned. Thanks to David Nehme and Branan in particular for their solutions which started things on the right track. The bit of code returning [using Branan's variable names] `((ts->mday - 1) / 7)` tells the number of complete weeks that have occurred before the current day. However, if we're counting the number of Mondays that have occurred so far, then we want to count the number of integral weeks, including today, then consider if the fractional week left over also contains any Mondays. To figure out whether the fractional week left after taking out the whole weeks contains a Monday, we need to consider `ts->mday % 7` and compare it to the day of the week, `ts->wday`. This is easy to see if you write out the combinations, but if we insure the day is not Sunday (`wday > 0`), then anytime `ts->wday <= (ts->mday % 7)` we need to increment the count of Mondays by 1. This comes from considering the number of days since the start of the month, and whether, based on the current day of the week within the the first fractional week, the fractional week contains a Monday. So I would rewrite Branan's return statement as follows: `return (ts->tm_mday / 7) + ((ts->tm_wday > 0) && (ts->tm_wday <= (ts->tm_mday % 7)));`
Assuming your first week is week 1: ``` int getWeekOfMonth() { time_t my_time; struct tm *ts; my_time = time(NULL); ts = localtime(&my_time); return ((ts->tm_mday -1) / 7) + 1; } ``` For 0-index, drop the `+1` in the return statement.
97,283
<p>For example if the user is currently running VS2008 then I want the value VS2008.</p>
[ { "answer_id": 97517, "author": "Ozgur Ozcitak", "author_id": 976, "author_profile": "https://Stackoverflow.com/users/976", "pm_score": 5, "selected": true, "text": "<p>I am assuming you want to get the name of the process owning the currently focused window. With some P/Invoke:</p>\n\n<pre><code>// The GetForegroundWindow function returns a handle to the foreground window\n// (the window with which the user is currently working).\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetForegroundWindow();\n\n// The GetWindowThreadProcessId function retrieves the identifier of the thread\n// that created the specified window and, optionally, the identifier of the\n// process that created the window.\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n\n// Returns the name of the process owning the foreground window.\nprivate string GetForegroundProcessName()\n{\n IntPtr hwnd = GetForegroundWindow();\n\n // The foreground window can be NULL in certain circumstances, \n // such as when a window is losing activation.\n if (hwnd == null)\n return \"Unknown\";\n\n uint pid;\n GetWindowThreadProcessId(hwnd, out pid);\n\n foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())\n {\n if (p.Id == pid)\n return p.ProcessName;\n }\n\n return \"Unknown\";\n}\n</code></pre>\n" }, { "answer_id": 19045382, "author": "user2533527", "author_id": 2533527, "author_profile": "https://Stackoverflow.com/users/2533527", "pm_score": 2, "selected": false, "text": "<pre><code>using System;\nusing System.Windows;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nnamespace FGHook\n{\n class ForegroundTracker\n {\n // Delegate and imports from pinvoke.net:\n\n delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType,\n IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr\n hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess,\n uint idThread, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n\n\n [DllImport(\"user32.dll\")]\n static extern bool UnhookWinEvent(IntPtr hWinEventHook);\n\n\n\n // Constants from winuser.h\n const uint EVENT_SYSTEM_FOREGROUND = 3;\n const uint WINEVENT_OUTOFCONTEXT = 0;\n\n // Need to ensure delegate is not collected while we're using it,\n // storing it in a class field is simplest way to do this.\n static WinEventDelegate procDelegate = new WinEventDelegate(WinEventProc);\n\n public static void Main()\n {\n // Listen for foreground changes across all processes/threads on current desktop...\n IntPtr hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero,\n procDelegate, 0, 0, WINEVENT_OUTOFCONTEXT);\n\n // MessageBox provides the necessary mesage loop that SetWinEventHook requires.\n MessageBox.Show(\"Tracking focus, close message box to exit.\");\n\n UnhookWinEvent(hhook);\n }\n\n static void WinEventProc(IntPtr hWinEventHook, uint eventType,\n IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)\n {\n Console.WriteLine(\"Foreground changed to {0:x8}\", hwnd.ToInt32());\n //Console.WriteLine(\"ObjectID changed to {0:x8}\", idObject);\n //Console.WriteLine(\"ChildID changed to {0:x8}\", idChild);\n GetForegroundProcessName();\n\n }\n static void GetForegroundProcessName()\n {\n IntPtr hwnd = GetForegroundWindow();\n\n // The foreground window can be NULL in certain circumstances, \n // such as when a window is losing activation.\n if (hwnd == null)\n return;\n\n uint pid;\n GetWindowThreadProcessId(hwnd, out pid);\n\n foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())\n {\n if (p.Id == pid)\n {\n Console.WriteLine(\"Pid is: {0}\",pid);\n Console.WriteLine(\"Process name is {0}\",p.ProcessName);\n return;\n }\n //return;\n }\n\n Console.WriteLine(\"Unknown\");\n }\n }\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
For example if the user is currently running VS2008 then I want the value VS2008.
I am assuming you want to get the name of the process owning the currently focused window. With some P/Invoke: ``` // The GetForegroundWindow function returns a handle to the foreground window // (the window with which the user is currently working). [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); // The GetWindowThreadProcessId function retrieves the identifier of the thread // that created the specified window and, optionally, the identifier of the // process that created the window. [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); // Returns the name of the process owning the foreground window. private string GetForegroundProcessName() { IntPtr hwnd = GetForegroundWindow(); // The foreground window can be NULL in certain circumstances, // such as when a window is losing activation. if (hwnd == null) return "Unknown"; uint pid; GetWindowThreadProcessId(hwnd, out pid); foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) { if (p.Id == pid) return p.ProcessName; } return "Unknown"; } ```
97,312
<p>How do I find out what directory my console app is running in with C#?</p>
[ { "answer_id": 97330, "author": "Jakub Kotrla", "author_id": 16943, "author_profile": "https://Stackoverflow.com/users/16943", "pm_score": 1, "selected": false, "text": "<p>On windows (not sure about Unix etc.) it is the first argument in commandline.</p>\n\n<p>In C/C++ firts item in argv*</p>\n\n<p>WinAPI - GetModuleFileName(NULL, char*, MAX_PATH)</p>\n" }, { "answer_id": 97331, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 8, "selected": true, "text": "<p>To get the directory where the .exe file is:</p>\n\n<pre><code>AppDomain.CurrentDomain.BaseDirectory\n</code></pre>\n\n<p>To get the current directory:</p>\n\n<pre><code>Environment.CurrentDirectory\n</code></pre>\n" }, { "answer_id": 97343, "author": "Travis Illig", "author_id": 8116, "author_profile": "https://Stackoverflow.com/users/8116", "pm_score": 2, "selected": false, "text": "<p>In .NET, you can use <code>System.Environment.CurrentDirectory</code> to get the directory from which the process was started.<br>\n<code>System.Reflection.Assembly.GetExecutingAssembly().Location</code> will tell you the location of the currently executing assembly (that's only interesting if the currently executing assembly is loaded from somewhere different than the location of the assembly where the process started).</p>\n" }, { "answer_id": 97491, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 4, "selected": false, "text": "<p>Depending on the rights granted to your application, whether <a href=\"http://msdn.microsoft.com/en-us/library/ms404279.aspx\" rel=\"nofollow noreferrer\">shadow copying</a> is in effect or not and other invocation and deployment options, different methods may work or yield different results so you will have to choose your weapon wisely. Having said that,\nall of the following will yield the same result for a fully-trusted console application that is executed locally at the machine where it resides:</p>\n<pre><code>Console.WriteLine( Assembly.GetEntryAssembly().Location );\nConsole.WriteLine( new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath );\nConsole.WriteLine( Environment.GetCommandLineArgs()[0] );\nConsole.WriteLine( Process.GetCurrentProcess().MainModule.FileName );\n</code></pre>\n<p>You will need to consult the documentation of the above members to see the exact permissions needed.</p>\n" }, { "answer_id": 564037, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Application.StartUpPath;</p>\n" }, { "answer_id": 2365676, "author": "410", "author_id": 24522, "author_profile": "https://Stackoverflow.com/users/24522", "pm_score": 3, "selected": false, "text": "<p>Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)</p>\n" }, { "answer_id": 58547501, "author": "R M Shahidul Islam Shahed", "author_id": 3201212, "author_profile": "https://Stackoverflow.com/users/3201212", "pm_score": 2, "selected": false, "text": "<p>Let's say your .Net core console application project name is DataPrep.</p>\n\n<p>Get Project Base Directory:</p>\n\n<pre><code>Console.WriteLine(Environment.CurrentDirectory);\n</code></pre>\n\n<p><strong>Output:</strong> ~DataPrep\\bin\\Debug\\netcoreapp2.2</p>\n\n<pre><code>Get Project .csproj file directory:\nstring ProjectDirPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @\"..\\..\\..\\\"));\nConsole.WriteLine(ProjectDirPath);\n</code></pre>\n\n<p><strong>Output:</strong> ~DataPrep\\</p>\n" }, { "answer_id": 63185948, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "<p>Use <code>AppContext.BaseDirectory</code> for .net5.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
How do I find out what directory my console app is running in with C#?
To get the directory where the .exe file is: ``` AppDomain.CurrentDomain.BaseDirectory ``` To get the current directory: ``` Environment.CurrentDirectory ```
97,324
<p>I'm writing a WCF service for the first time. The service and all of its clients (at least for now) are written in C#. The service has to do a lot of input validation on the data it gets passed, so I need to have some way to indicate invalid data back to the client. I've been reading a lot about faults and exceptions, wrapping exceptions in faults, and a lot of conflicting articles that are just confusing me further. What is the proper way to handle this case? </p> <p>Should I avoid exceptions altogether and package a Results return message? Should I create a special Fault, or a special Exception, or just throw ArgumentExceptions like I would for a non-WCF validation function?</p> <p>The code I have right now (influenced by <a href="http://msdn.microsoft.com/en-us/library/ms733841.aspx" rel="noreferrer">MSDN</a>) is:</p> <pre><code>[DataContract] public class ValidationFault { [DataMember] public Dictionary&lt;string, string&gt; Errors { get; private set; } [DataMember] public bool Fatal { get; private set; } [DataMember] public Guid SeriesIdentifier { get; private set; } public ValidationFault(Guid id, string argument, string error, bool fatal) { SeriesIdentifier = id; Errors = new Dictionary&lt;string, string&gt; {{argument, error}}; Fatal = fatal; } public void AddError(string argument, string error, bool fatal) { Errors.Add(argument, error); Fatal |= fatal; } } </code></pre> <p>And on the method there's [FaultContract(typeof(ValidationFault))]. So is this the "right" way to approach this?</p>
[ { "answer_id": 97676, "author": "Brennan", "author_id": 10366, "author_profile": "https://Stackoverflow.com/users/10366", "pm_score": 3, "selected": true, "text": "<p>If you are doing validation on the client and should have valid values once they are passed into the method (the web service call) then I would throw an exception. It could be an exception indicating that a parameters is invalid with the name of the parameter. (see: ArgumentException)</p>\n\n<p>But you may not want to rely on the client to properly validate the data and that leaves you with the assumption that data could be invalid coming into the web service. In that case it is not truly an exceptional case and should not be an exception. In that case you could return an enum or a Result object that has a Status property set to an enum (OK, Invalid, Incomplete) and a Message property set with specifics, like the name of the parameter.</p>\n\n<p>I would ensure that these sorts of errors are found and fixed during development. Your QA process should carefully test valid and invalid uses of the client and you do not want to relay these technical messages back to the client. What you want to do instead is update your validation system to prevent invalid data from getting to the service call.</p>\n\n<p>My assumption for any WCF service is that there will be more than one UI. One could be a web UI now, but later I may add another using WinForms, WinCE or even a native iPhone/Android mobile application that does not conform to what you expect from .NET clients.</p>\n" }, { "answer_id": 114560, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": 2, "selected": false, "text": "<p>you might want to take a look at the MS Patterns and Practices Enterprise Library Validation block in conjunction with the policy injection block <a href=\"http://www.codeplex.com/entlib\" rel=\"nofollow noreferrer\">link text</a> it allows you to decorate your data contract members with validation attributes and also decorate the service implementation, this together with its integration with WCF this means that failures in validation are returned as ArgumentValidationException faults automatically each containing a ValidationDetail object for each validation failure.</p>\n\n<p>Using the entlib with WCf you can get a lot of validation, error reporting without having to write much code</p>\n" }, { "answer_id": 114622, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 2, "selected": false, "text": "<p>Throwing an exception is not useful from a WCF service Why not? Because it comes back as a bare fault and you need to</p>\n\n<p>a) Set the fault to include exceptions</p>\n\n<p>b) Parse the fault to get the text of the exception and see what happened.</p>\n\n<p>So yes you need a fault rather than an exception. I would, in your case, create a custom fault which contains a list of the fields that failed the validation as part of the fault contract.</p>\n\n<p>Note that WCF does fun things with dictionaries, which aren't ISerializable; it has special handling, so check the message coming back looks good over the wire; if not it's back to arrays for you.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17697/" ]
I'm writing a WCF service for the first time. The service and all of its clients (at least for now) are written in C#. The service has to do a lot of input validation on the data it gets passed, so I need to have some way to indicate invalid data back to the client. I've been reading a lot about faults and exceptions, wrapping exceptions in faults, and a lot of conflicting articles that are just confusing me further. What is the proper way to handle this case? Should I avoid exceptions altogether and package a Results return message? Should I create a special Fault, or a special Exception, or just throw ArgumentExceptions like I would for a non-WCF validation function? The code I have right now (influenced by [MSDN](http://msdn.microsoft.com/en-us/library/ms733841.aspx)) is: ``` [DataContract] public class ValidationFault { [DataMember] public Dictionary<string, string> Errors { get; private set; } [DataMember] public bool Fatal { get; private set; } [DataMember] public Guid SeriesIdentifier { get; private set; } public ValidationFault(Guid id, string argument, string error, bool fatal) { SeriesIdentifier = id; Errors = new Dictionary<string, string> {{argument, error}}; Fatal = fatal; } public void AddError(string argument, string error, bool fatal) { Errors.Add(argument, error); Fatal |= fatal; } } ``` And on the method there's [FaultContract(typeof(ValidationFault))]. So is this the "right" way to approach this?
If you are doing validation on the client and should have valid values once they are passed into the method (the web service call) then I would throw an exception. It could be an exception indicating that a parameters is invalid with the name of the parameter. (see: ArgumentException) But you may not want to rely on the client to properly validate the data and that leaves you with the assumption that data could be invalid coming into the web service. In that case it is not truly an exceptional case and should not be an exception. In that case you could return an enum or a Result object that has a Status property set to an enum (OK, Invalid, Incomplete) and a Message property set with specifics, like the name of the parameter. I would ensure that these sorts of errors are found and fixed during development. Your QA process should carefully test valid and invalid uses of the client and you do not want to relay these technical messages back to the client. What you want to do instead is update your validation system to prevent invalid data from getting to the service call. My assumption for any WCF service is that there will be more than one UI. One could be a web UI now, but later I may add another using WinForms, WinCE or even a native iPhone/Android mobile application that does not conform to what you expect from .NET clients.
97,329
<p>Suppose I have a collection (be it an array, generic List, or whatever is the <strong>fastest</strong> solution to this problem) of a certain class, let's call it <code>ClassFoo</code>:</p> <pre><code>class ClassFoo { public string word; public float score; //... etc ... } </code></pre> <p>Assume there's going to be like 50.000 items in the collection, all in memory. Now I want to obtain as fast as possible all the instances in the collection that obey a condition on its bar member, for example like this:</p> <pre><code>List&lt;ClassFoo&gt; result = new List&lt;ClassFoo&gt;(); foreach (ClassFoo cf in collection) { if (cf.word.StartsWith(query) || cf.word.EndsWith(query)) result.Add(cf); } </code></pre> <p>How do I get the results as fast as possible? Should I consider some advanced indexing techniques and datastructures?</p> <p>The application domain for this problem is an autocompleter, that gets a query and gives a collection of suggestions as a result. Assume that the condition doesn't get any more complex than this. Assume also that there's going to be a lot of searches.</p>
[ { "answer_id": 97347, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>var Answers = myList.Where(item => item.bar.StartsWith(query) || item.bar.EndsWith(query));</p>\n\n<p>that's the easiest in my opinion, should execute rather quickly.</p>\n" }, { "answer_id": 97355, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 0, "selected": false, "text": "<p>Not sure I understand... All you can really do is optimize the rule, that's the part that needs to be fastest. You can't speed up the loop without just throwing more hardware at it. </p>\n\n<p>You could parallelize if you have multiple cores or machines.</p>\n" }, { "answer_id": 97401, "author": "Morikal", "author_id": 18272, "author_profile": "https://Stackoverflow.com/users/18272", "pm_score": 0, "selected": false, "text": "<p>I'm not up on my Java right now, but I would think about the following things.</p>\n\n<p>How you are creating your list? Perhaps you can create it already ordered in a way which cuts down on comparison time.</p>\n\n<p>If you are just doing a straight loop through your collection, you won't see much difference between storing it as an array or as a linked list. </p>\n\n<p>For storing the results, depending on how you are collecting them, the structure could make a difference (but assuming Java's generic structures are smart, it won't). As I said, I'm not up on my Java, but I assume that the generic linked list would keep a tail pointer. In this case, it wouldn't really make a difference. Someone with more knowledge of the underlying array vs linked list implementation and how it ends up looking in the byte code could probably tell you whether appending to a linked list with a tail pointer or inserting into an array is faster (my guess would be the array). On the other hand, you would need to know the size of your result set or sacrifice some storage space and make it as big as the whole collection you are iterating through if you wanted to use an array.</p>\n\n<p>Optimizing your comparison query by figuring out which comparison is most likely to be true and doing that one first could also help. ie: If in general 10% of the time a member of the collection starts with your query, and 30% of the time a member ends with the query, you would want to do the end comparison first.</p>\n" }, { "answer_id": 97404, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 0, "selected": false, "text": "<p>For your particular example, sorting the collection would help as you could binarychop to the first item that starts with query and terminate early when you reach the next one that doesn't; you could also produce a table of pointers to collection items sorted by the reverse of each string for the second clause.</p>\n\n<p>In general, if you know the structure of the query in advance, you can sort your collection (or build several sorted indexes for your collection if there are multiple clauses) appropriately; if you do not, you will not be able to do better than linear search.</p>\n" }, { "answer_id": 97432, "author": "Jon Turner", "author_id": 16979, "author_profile": "https://Stackoverflow.com/users/16979", "pm_score": 0, "selected": false, "text": "<p>If it's something where you populate the list once and then do many lookups (thousands or more) then you could create some kind of lookup dictionary that maps starts with/ends with values to their actual values. That would be a fast lookup, but would use much more memory. If you aren't doing that many lookups or know you're going to be repopulating the list at least semi-frequently I'd go with the LINQ query that CQ suggested.</p>\n" }, { "answer_id": 97449, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "<p>You can create some sort of index and it might get faster.</p>\n\n<p>We can build a index like this:</p>\n\n<pre><code>Dictionary&lt;char, List&lt;ClassFoo&gt;&gt; indexByFirstLetter;\nforeach (var cf in collection) {\n indexByFirstLetter[cf.bar[0]] = indexByFirstLetter[cf.bar[0]] ?? new List&lt;ClassFoo&gt;();\n indexByFirstLetter[cf.bar[0]].Add(cf);\n indexByFirstLetter[cf.bar[cf.bar.length - 1]] = indexByFirstLetter[cf.bar[cf.bar.Length - 1]] ?? new List&lt;ClassFoo&gt;();\n indexByFirstLetter[cf.bar[cf.bar.Length - 1]].Add(cf);\n}\n</code></pre>\n\n<p>Then use the it like this:</p>\n\n<pre><code>foreach (ClasssFoo cf in indexByFirstLetter[query[0]]) {\n if (cf.bar.StartsWith(query) || cf.bar.EndsWith(query))\n result.Add(cf);\n}\n</code></pre>\n\n<p>Now we possibly do not have to loop through as many ClassFoo as in your example, but then again we have to keep the index up to date. There is no guarantee that it is faster, but it is definately more complicated.</p>\n" }, { "answer_id": 97545, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 3, "selected": true, "text": "<p>With the constraint that the condition clause can be \"anything\", then you're limited to scanning the entire list and applying the condition.</p>\n\n<p>If there are limitations on the condition clause, then you can look at organizing the data to more efficiently handle the queries.</p>\n\n<p>For example, the code sample with the \"byFirstLetter\" dictionary doesn't help at all with an \"endsWith\" query.</p>\n\n<p>So, it really comes down to what queries you want to do against that data.</p>\n\n<p>In Databases, this problem is the burden of the \"query optimizer\". In a typical database, if you have a database with no indexes, obviously every query is going to be a table scan. As you add indexes to the table, the optimizer can use that data to make more sophisticated query plans to better get to the data. That's essentially the problem you're describing.</p>\n\n<p>Once you have a more concrete subset of the types of queries then you can make a better decision as to what structure is best. Also, you need to consider the amount of data. If you have a list of 10 elements each less than 100 byte, a scan of everything may well be the fastest thing you can do since you have such a small amount of data. Obviously that doesn't scale to a 1M elements, but even clever access techniques carry a cost in setup, maintenance (like index maintenance), and memory.</p>\n\n<p><strong>EDIT</strong>, based on the comment</p>\n\n<p>If it's an auto completer, if the data is static, then sort it and use a binary search. You're really not going to get faster than that.</p>\n\n<p>If the data is dynamic, then store it in a balanced tree, and search that. That's effectively a binary search, and it lets you keep add the data randomly.</p>\n\n<p>Anything else is some specialization on these concepts.</p>\n" }, { "answer_id": 97611, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 0, "selected": false, "text": "<p>Depends. Are all your objects always going to be loaded in memory? Do you have a finite limit of objects that may be loaded? Will your queries have to consider objects that haven't been loaded yet?</p>\n\n<p>If the collection will get large, I would definitely use an index.</p>\n\n<p>In fact, if the collection can grow to an arbitrary size and you're not sure that you will be able to fit it all in memory, I'd look into an ORM, an in-memory database, or another embedded database. XPO from DevExpress for ORM or SQLite.Net for in-memory database comes to mind.</p>\n\n<p>If you don't want to go this far, make a simple index consisting of the \"bar\" member references mapping to class references.</p>\n" }, { "answer_id": 106035, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "<p>If the set of possible criteria is fixed and small, you can assign a bitmask to each element in the list. The size of the bitmask is the size of the set of the criteria. When you create an element/add it to the list, you check which criteria it satisfies and then set the corresponding bits in the bitmask of this element. Matching the elements from the list will be as easy as matching their bitmasks with the target bitmask. A more general method is the Bloom filter.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
Suppose I have a collection (be it an array, generic List, or whatever is the **fastest** solution to this problem) of a certain class, let's call it `ClassFoo`: ``` class ClassFoo { public string word; public float score; //... etc ... } ``` Assume there's going to be like 50.000 items in the collection, all in memory. Now I want to obtain as fast as possible all the instances in the collection that obey a condition on its bar member, for example like this: ``` List<ClassFoo> result = new List<ClassFoo>(); foreach (ClassFoo cf in collection) { if (cf.word.StartsWith(query) || cf.word.EndsWith(query)) result.Add(cf); } ``` How do I get the results as fast as possible? Should I consider some advanced indexing techniques and datastructures? The application domain for this problem is an autocompleter, that gets a query and gives a collection of suggestions as a result. Assume that the condition doesn't get any more complex than this. Assume also that there's going to be a lot of searches.
With the constraint that the condition clause can be "anything", then you're limited to scanning the entire list and applying the condition. If there are limitations on the condition clause, then you can look at organizing the data to more efficiently handle the queries. For example, the code sample with the "byFirstLetter" dictionary doesn't help at all with an "endsWith" query. So, it really comes down to what queries you want to do against that data. In Databases, this problem is the burden of the "query optimizer". In a typical database, if you have a database with no indexes, obviously every query is going to be a table scan. As you add indexes to the table, the optimizer can use that data to make more sophisticated query plans to better get to the data. That's essentially the problem you're describing. Once you have a more concrete subset of the types of queries then you can make a better decision as to what structure is best. Also, you need to consider the amount of data. If you have a list of 10 elements each less than 100 byte, a scan of everything may well be the fastest thing you can do since you have such a small amount of data. Obviously that doesn't scale to a 1M elements, but even clever access techniques carry a cost in setup, maintenance (like index maintenance), and memory. **EDIT**, based on the comment If it's an auto completer, if the data is static, then sort it and use a binary search. You're really not going to get faster than that. If the data is dynamic, then store it in a balanced tree, and search that. That's effectively a binary search, and it lets you keep add the data randomly. Anything else is some specialization on these concepts.
97,338
<p>I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me?</p> <pre><code>gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) &gt;&gt;$(DEP) </code></pre>
[ { "answer_id": 97374, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 0, "selected": false, "text": "<p>If there is an argument to GCC to do this, I don't know what it is. We end up piping the dependency output through <a href=\"http://en.wikipedia.org/wiki/Sed\" rel=\"nofollow noreferrer\">sed</a> to rewrite all occurrences of <code>&lt;blah&gt;.o</code> as <code>${OBJDIR}/&lt;blah&gt;.o</code>.</p>\n" }, { "answer_id": 97710, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Ok, just to make sure I've got the question right: I'm assuming you have <code>test.c</code> which includes <code>test.h</code>, and you want to generate <code>subdir/test.d</code> (while <em>not</em> generating <code>subdir/test.o</code>) where <code>subdir/test.d</code> contains</p>\n\n<pre><code>subdir/test.o: test.c test.h\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>test.o: test.c test.h\n</code></pre>\n\n<p>which is what you get right now. Is that right?</p>\n\n<p>I was not able to come up with an easy way to do exactly what you're asking for. However, looking at <em><a href=\"http://www.gnu.org/software/gcc/news/dependencies.html\" rel=\"nofollow noreferrer\">Dependency Generation Improvements</a></em>, if you want to create the <code>.d</code> file while you generate the .o file, you can use:</p>\n\n<pre><code>gcc $(INCLUDES) -MMD $(CFLAGS) $(SRC) -o $(SUBDIR)/$(OBJ)\n</code></pre>\n\n<p>(Given <code>SRC=test.c</code>, <code>SUBDIR=subdir</code>, and <code>OBJ=test.o</code>.) This will create both subdir/test.o and subdir/test.d, where <code>subdir/test.d</code> contains the desired output as above.</p>\n" }, { "answer_id": 97893, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>[GNU] make gets angry if you don't place the output in the current directory. You should really run make from the build directory, and use the VPATH make variable to locate the source code. If you lie to a compiler, sooner or later it will take its revenge.</p></li>\n<li><p>If you insist on generating your objects and dependencies in some other directory, you need to use the <code>-o</code> argument, as <a href=\"https://stackoverflow.com/questions/97338/gcc-dependency-generation-for-a-different-output-directory/97710#97710\">answered by Emile</a>.</p></li>\n</ol>\n" }, { "answer_id": 99282, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 6, "selected": true, "text": "<p>The answer is in the <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.2/cpp/Invocation.html\" rel=\"noreferrer\">GCC manual</a>: use the <code>-MT</code> flag.</p>\n\n<blockquote>\n <p><code>-MT target</code></p>\n \n <p>Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as <code>.c</code>, and appends the platform's usual object suffix. The result is the target.</p>\n \n <p>An <code>-MT</code> option will set the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to <code>-MT</code>, or use multiple <code>-MT</code> options.</p>\n \n <p>For example, <code>-MT '$(objpfx)foo.o'</code> might give</p>\n\n<pre><code>$(objpfx)foo.o: foo.c\n</code></pre>\n</blockquote>\n" }, { "answer_id": 2045668, "author": "Don McCaughey", "author_id": 65764, "author_profile": "https://Stackoverflow.com/users/65764", "pm_score": 5, "selected": false, "text": "<p>I'm assuming you're using GNU Make and GCC. First add a variable to hold your list of dependency files. Assuming you already have one that lists all our sources:</p>\n\n<pre><code>SRCS = \\\n main.c \\\n foo.c \\\n stuff/bar.c\n\nDEPS = $(SRCS:.c=.d)\n</code></pre>\n\n<p>Then include the generated dependencies in the makefile:</p>\n\n<pre><code>include $(DEPS)\n</code></pre>\n\n<p>Then add this pattern rule:</p>\n\n<pre><code># automatically generate dependency rules\n\n%.d : %.c\n $(CC) $(CCFLAGS) -MF\"$@\" -MG -MM -MP -MT\"$@\" -MT\"$(&lt;:.c=.o)\" \"$&lt;\"\n\n# -MF write the generated dependency rule to a file\n# -MG assume missing headers will be generated and don't stop with an error\n# -MM generate dependency rule for prerequisite, skipping system headers\n# -MP add phony target for each header to prevent errors when header is missing\n# -MT add a target to the generated dependency\n</code></pre>\n\n<p>\"$@\" is the target (the thing on the left side of the : ), \"$&lt;\" is the prerequisite (the thing on the right side of the : ). The expression \"$(&lt;:.c=.o)\" replaces the .c extension with .o.</p>\n\n<p>The trick here is to generate the rule with two targets by adding -MT twice; this makes both the .o file and the .d file depend on the source file and its headers; that way the dependency file gets automatically regenerated whenever any of the corresponding .c or .h files are changed.</p>\n\n<p>The -MG and -MP options keep make from freaking out if a header file is missing.</p>\n" }, { "answer_id": 16969086, "author": "Steve Pitchers", "author_id": 7255, "author_profile": "https://Stackoverflow.com/users/7255", "pm_score": 4, "selected": false, "text": "<p>You may like this briefer version of <a href=\"https://stackoverflow.com/questions/97338/gcc-dependency-generation-for-a-different-output-directory/2045668#2045668\">Don McCaughey's answer</a>:</p>\n\n<pre><code>SRCS = \\\n main.c \\\n foo.c \\\n stuff/bar.c\n</code></pre>\n\n<p><code>DEPS = $(SRCS:.c=.d)</code></p>\n\n<p>Add <code>-include $(DEPS)</code> note the <code>-</code> prefix, which silences errors if the <code>.d</code> files don't yet exist. </p>\n\n<p>There's no need for a separate pattern rule to generate the dependency files. Simply add <code>-MD</code> or <code>-MMD</code> to your normal compilation line, and the <code>.d</code> files get generated at the same time your source files are compiled. For example:</p>\n\n<pre><code>%.o: %.c\n gcc $(INCLUDE) -MMD -c $&lt; -o $@\n\n# -MD can be used to generate a dependency output file as a side-effect of the compilation process.\n</code></pre>\n" }, { "answer_id": 24129675, "author": "rsp1984", "author_id": 1232524, "author_profile": "https://Stackoverflow.com/users/1232524", "pm_score": 2, "selected": false, "text": "<p>Detailing on <a href=\"https://stackoverflow.com/questions/97338/gcc-dependency-generation-for-a-different-output-directory/97374#97374\">DGentry's answer</a>, this has worked well for me:</p>\n\n<pre><code>.depend: $(SOURCES)\n $(CC) $(CFLAGS) -MM $(SOURCES) | sed 's|[a-zA-Z0-9_-]*\\.o|$(OBJDIR)/&amp;|' &gt; ./.depend\n</code></pre>\n\n<p>This also works in the case where there is only one dependency file that contains the dependency rules for all source files.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me? ``` gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP) ```
The answer is in the [GCC manual](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/cpp/Invocation.html): use the `-MT` flag. > > `-MT target` > > > Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as `.c`, and appends the platform's usual object suffix. The result is the target. > > > An `-MT` option will set the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to `-MT`, or use multiple `-MT` options. > > > For example, `-MT '$(objpfx)foo.o'` might give > > > > ``` > $(objpfx)foo.o: foo.c > > ``` > >
97,349
<p>We want to store our overridden build targets in an external file and include that targets file in the TFSBuild.proj. We have a core set steps that happens and would like to get those additional steps by simply adding the import line to the TFSBuild.proj created by the wizard. </p> <pre><code>&lt;Import Project="$(SolutionRoot)/libs/my.team.build/my.team.build.targets"/&gt; </code></pre> <p>We cannot have an import on any file in the <code>$(SolutionRoot)</code> because at the time the Import statement is validated, the source has not be fetched from the repository. It looks like TFS is pulling down the <code>TFSBuild.proj</code> first without any other files.</p> <p>Even if we add a conditional import, the version in source control will not be imported if present. The previous version, already present on disk will be imported. </p> <p>We can give up storing those build targets with our source, but it is the first dependency to move out of our source tree so we are reluctant to do it.</p> <p>Is there a way to either:</p> <ol> <li>Tell Team Build to pull down a few more files so those <code>Import</code> statements evaluate correctly?</li> <li>Override those Team Build targets like <code>AfterCompile</code> in a manner besides the <code>Import</code>?</li> <li>Ultimately run build targets in Team Build that are kept under the source it's trying to build?</li> </ol>
[ { "answer_id": 97486, "author": "Gregg", "author_id": 18266, "author_profile": "https://Stackoverflow.com/users/18266", "pm_score": 1, "selected": false, "text": "<p>If the targets should only be run when TFS is running the build and not on your local development machines, you can put your targets file in the folder for the build itself and reference it with:</p>\n\n<pre><code>&lt;Import Project=\"$(MSBuildProjectDirectory)\\my.team.build.targets.proj\" /&gt;\n</code></pre>\n\n<p>However, if you want the targets to run for all builds, you can set it up so that the individual projects reference it by adding something like:</p>\n\n<pre><code>&lt;Import Project=\"$(SolutionRoot)/libs/my.team.build/my.team.build.targets\" Condition=\"Exists('$(SolutionRoot)/libs/my.team.build/my.team.build.targets')\" /&gt;\n</code></pre>\n\n<p>On my project we actually use both of these, the first allows us to customize the nightly builds so we can do extra steps before and after running the full solution compile, and the second allows project-by-project customization.</p>\n" }, { "answer_id": 99893, "author": "Mr. Kraus", "author_id": 5132, "author_profile": "https://Stackoverflow.com/users/5132", "pm_score": 0, "selected": false, "text": "<p>If you create an overrides target file to import and call it something like TeamBuildOverrides.targets and put it in the same folder in source control where TFSBuild.proj lives for your Build Type, it will be pulled first and be available for import into the TFSBuild.proj file. By default, the TFSBuild.proj file is added to the TeamBuildTypes folder in Source Control directly under the root folder of your project.</p>\n\n<p>use the following import statement in your TFSBuild.proj file:</p>\n\n<pre><code>&lt;Import Project=\"$(MSBuildProjectDirectory)\\TeamBuildOverrides.targets\" /&gt;\n</code></pre>\n\n<p>Make sure you don't have any duplicate overrides in your TFSBuild.proj file or the imported overrides will not get fired.</p>\n" }, { "answer_id": 100493, "author": "Martin Woodward", "author_id": 6438, "author_profile": "https://Stackoverflow.com/users/6438", "pm_score": 5, "selected": true, "text": "<p>The Team Build has a \"bootstrap\" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj.</p>\n\n<p>If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e.</p>\n\n<pre><code>&lt;Import Project=\"myTeamBuild.targets\"/&gt;\n</code></pre>\n\n<p>If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path.</p>\n\n<p>Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this:</p>\n\n<pre><code>$/TeamProject/main/MySolution/TeamBuild\n</code></pre>\n\n<p>Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\\Visual Studio 9.0\\Common7\\IDE\\PrivateAssemblies)</p>\n\n<pre><code>&lt;add key=\"ConfigurationFolderRecursionType\" value=\"Full\" /&gt;\n</code></pre>\n\n<p>Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can.</p>\n\n<p>Good luck,</p>\n\n<p>Martin.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18264/" ]
We want to store our overridden build targets in an external file and include that targets file in the TFSBuild.proj. We have a core set steps that happens and would like to get those additional steps by simply adding the import line to the TFSBuild.proj created by the wizard. ``` <Import Project="$(SolutionRoot)/libs/my.team.build/my.team.build.targets"/> ``` We cannot have an import on any file in the `$(SolutionRoot)` because at the time the Import statement is validated, the source has not be fetched from the repository. It looks like TFS is pulling down the `TFSBuild.proj` first without any other files. Even if we add a conditional import, the version in source control will not be imported if present. The previous version, already present on disk will be imported. We can give up storing those build targets with our source, but it is the first dependency to move out of our source tree so we are reluctant to do it. Is there a way to either: 1. Tell Team Build to pull down a few more files so those `Import` statements evaluate correctly? 2. Override those Team Build targets like `AfterCompile` in a manner besides the `Import`? 3. Ultimately run build targets in Team Build that are kept under the source it's trying to build?
The Team Build has a "bootstrap" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj. If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e. ``` <Import Project="myTeamBuild.targets"/> ``` If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path. Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this: ``` $/TeamProject/main/MySolution/TeamBuild ``` Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\Visual Studio 9.0\Common7\IDE\PrivateAssemblies) ``` <add key="ConfigurationFolderRecursionType" value="Full" /> ``` Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can. Good luck, Martin.
97,370
<p>I have a macro which refreshes all fields in a document (the equivalent of doing an <kbd>F9</kbd> on the fields). I'd like to fire this macro automatically when the user saves the document.</p> <p>Under options I can select "update fields when document is printed", but that's not what I want. In the VBA editor I only seem to find events for the <code>Document_Open()</code> event, not the <code>Document_Save()</code> event.</p> <p>Is it possible to get the macro to fire when the user saves the document?</p> <p>Please note:</p> <ol> <li>This is Word 97. I know it is possible in later versions of Word</li> <li>I don't want to replace the standard Save button on the toolbar with a button to run my custom macro. Replacing the button on the toolbar applies to all documents and I only want it to affect this one document.</li> </ol> <p>To understand why I need this, the document contains a "SaveDate" field and I'd like this field to update on the screen when the user clicks Save. So if you can suggest another way to achieve this, then that would be just as good.</p>
[ { "answer_id": 97486, "author": "Gregg", "author_id": 18266, "author_profile": "https://Stackoverflow.com/users/18266", "pm_score": 1, "selected": false, "text": "<p>If the targets should only be run when TFS is running the build and not on your local development machines, you can put your targets file in the folder for the build itself and reference it with:</p>\n\n<pre><code>&lt;Import Project=\"$(MSBuildProjectDirectory)\\my.team.build.targets.proj\" /&gt;\n</code></pre>\n\n<p>However, if you want the targets to run for all builds, you can set it up so that the individual projects reference it by adding something like:</p>\n\n<pre><code>&lt;Import Project=\"$(SolutionRoot)/libs/my.team.build/my.team.build.targets\" Condition=\"Exists('$(SolutionRoot)/libs/my.team.build/my.team.build.targets')\" /&gt;\n</code></pre>\n\n<p>On my project we actually use both of these, the first allows us to customize the nightly builds so we can do extra steps before and after running the full solution compile, and the second allows project-by-project customization.</p>\n" }, { "answer_id": 99893, "author": "Mr. Kraus", "author_id": 5132, "author_profile": "https://Stackoverflow.com/users/5132", "pm_score": 0, "selected": false, "text": "<p>If you create an overrides target file to import and call it something like TeamBuildOverrides.targets and put it in the same folder in source control where TFSBuild.proj lives for your Build Type, it will be pulled first and be available for import into the TFSBuild.proj file. By default, the TFSBuild.proj file is added to the TeamBuildTypes folder in Source Control directly under the root folder of your project.</p>\n\n<p>use the following import statement in your TFSBuild.proj file:</p>\n\n<pre><code>&lt;Import Project=\"$(MSBuildProjectDirectory)\\TeamBuildOverrides.targets\" /&gt;\n</code></pre>\n\n<p>Make sure you don't have any duplicate overrides in your TFSBuild.proj file or the imported overrides will not get fired.</p>\n" }, { "answer_id": 100493, "author": "Martin Woodward", "author_id": 6438, "author_profile": "https://Stackoverflow.com/users/6438", "pm_score": 5, "selected": true, "text": "<p>The Team Build has a \"bootstrap\" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj.</p>\n\n<p>If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e.</p>\n\n<pre><code>&lt;Import Project=\"myTeamBuild.targets\"/&gt;\n</code></pre>\n\n<p>If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path.</p>\n\n<p>Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this:</p>\n\n<pre><code>$/TeamProject/main/MySolution/TeamBuild\n</code></pre>\n\n<p>Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\\Visual Studio 9.0\\Common7\\IDE\\PrivateAssemblies)</p>\n\n<pre><code>&lt;add key=\"ConfigurationFolderRecursionType\" value=\"Full\" /&gt;\n</code></pre>\n\n<p>Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can.</p>\n\n<p>Good luck,</p>\n\n<p>Martin.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
I have a macro which refreshes all fields in a document (the equivalent of doing an `F9` on the fields). I'd like to fire this macro automatically when the user saves the document. Under options I can select "update fields when document is printed", but that's not what I want. In the VBA editor I only seem to find events for the `Document_Open()` event, not the `Document_Save()` event. Is it possible to get the macro to fire when the user saves the document? Please note: 1. This is Word 97. I know it is possible in later versions of Word 2. I don't want to replace the standard Save button on the toolbar with a button to run my custom macro. Replacing the button on the toolbar applies to all documents and I only want it to affect this one document. To understand why I need this, the document contains a "SaveDate" field and I'd like this field to update on the screen when the user clicks Save. So if you can suggest another way to achieve this, then that would be just as good.
The Team Build has a "bootstrap" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj. If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e. ``` <Import Project="myTeamBuild.targets"/> ``` If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path. Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this: ``` $/TeamProject/main/MySolution/TeamBuild ``` Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\Visual Studio 9.0\Common7\IDE\PrivateAssemblies) ``` <add key="ConfigurationFolderRecursionType" value="Full" /> ``` Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can. Good luck, Martin.
97,371
<p>I need to copy the newest file in a directory to a new location. So far I've found resources on the <a href="http://www.ss64.com/nt/forfiles.html" rel="noreferrer">forfiles</a> command, a <a href="https://stackoverflow.com/q/51837">date-related question</a> here, and another <a href="https://stackoverflow.com/q/50902">related question</a>. I'm just having a bit of trouble putting the pieces together! How do I copy the newest file in that directory to a new place?</p>
[ { "answer_id": 97414, "author": "Robert Swisher", "author_id": 1852, "author_profile": "https://Stackoverflow.com/users/1852", "pm_score": 2, "selected": false, "text": "<p>I know you asked for Windows but thought I'd add this anyway,in Unix/Linux you could do:</p>\n\n<pre><code>cp `ls -t1 | head -1` /somedir/\n</code></pre>\n\n<p>Which will list all files in the current directory sorted by modification time and then cp the most recent to /somedir/</p>\n" }, { "answer_id": 97427, "author": "moswald", "author_id": 8368, "author_profile": "https://Stackoverflow.com/users/8368", "pm_score": 2, "selected": false, "text": "<p>This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.</p>\n\n<p>Obviously, replace new_file_loc with whatever your new file location will be.</p>\n\n<pre><code>@echo off\nfor /F %%i in ('dir /B /O:-D *.txt') do (\n call :open \"%%i\"\n exit /B 0\n)\n:open\n start \"window title\" \"cmd /K copy %~1 new_file_loc\"\nexit /B 0\n</code></pre>\n" }, { "answer_id": 97438, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": -1, "selected": false, "text": "<p>Bash:</p>\n\n<pre><code> find -type f -printf \"%T@ %p \\n\" \\\n | sort \\\n | tail -n 1 \\\n | sed -r \"s/^\\S+\\s//;s/\\s*$//\" \\\n | xargs -iSTR cp STR newestfile\n</code></pre>\n\n<p>where \"newestfile\" will become the newestfile </p>\n\n<p>alternatively, you could do newdir/STR or just newdir </p>\n\n<p>Breakdown: </p>\n\n<ol>\n<li>list all files in {time} {file} format. </li>\n<li>sort them by time </li>\n<li>get the last one</li>\n<li>cut off the time, and whitespace from the start/end</li>\n<li>copy resulting value </li>\n</ol>\n\n<p><strong>Important</strong> </p>\n\n<p>After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ).\nSo you may have to adjust which filenumber you copy if you want this to work more than once.</p>\n" }, { "answer_id": 97782, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 7, "selected": true, "text": "<p>Windows shell, one liner:</p>\n<pre><code>FOR /F &quot;delims=&quot; %%I IN ('DIR *.* /A-D /B /O:-D') DO COPY &quot;%%I&quot; &lt;&lt;NewDir&gt;&gt; &amp; EXIT\n</code></pre>\n" }, { "answer_id": 978259, "author": "Chris Magnuson", "author_id": 101679, "author_profile": "https://Stackoverflow.com/users/101679", "pm_score": 7, "selected": false, "text": "<p>The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:</p>\n<pre><code>FOR /F &quot;delims=&quot; %%I IN ('DIR &quot;*.*&quot; /A-D /B /O:D') DO SET &quot;NewestFile=%%I&quot;\n</code></pre>\n<p>Now you can reference <code>%NewestFile%</code> throughout the rest of your bat file.</p>\n<p>For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:</p>\n<pre><code>:Variables\nSET DatabaseBackupPath=\\\\virtualserver1\\Database Backups\n\necho.\necho Restore WebServer Database\nFOR /F &quot;delims=|&quot; %%I IN ('DIR &quot;%DatabaseBackupPath%\\WebServer\\*.bak&quot; /B /O:D') DO SET NewestFile=%%I\ncopy &quot;%DatabaseBackupPath%\\WebServer\\%NewestFile%&quot; &quot;D:\\&quot;\n\nsqlcmd -U &lt;username&gt; -P &lt;password&gt; -d master -Q ^\n&quot;RESTORE DATABASE [ExampleDatabaseName] ^\nFROM DISK = N'D:\\%NewestFile%' ^\nWITH FILE = 1, ^\nMOVE N'Example_CS' TO N'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Example.mdf', ^\nMOVE N'Example_CS_log' TO N'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Example_1.LDF', ^\nNOUNLOAD, STATS = 10&quot;\n</code></pre>\n" }, { "answer_id": 5082562, "author": "TimH - Codidact", "author_id": 382254, "author_profile": "https://Stackoverflow.com/users/382254", "pm_score": 4, "selected": false, "text": "<p>To allow this to work with filenames using spaces, a modified version of the accepted answer is needed:</p>\n\n<pre><code>FOR /F \"delims=\" %%I IN ('DIR . /B /O:-D') DO COPY \"%%I\" &lt;&lt;NewDir&gt;&gt; &amp; GOTO :END\n:END\n</code></pre>\n" }, { "answer_id": 6524910, "author": "Richard", "author_id": 821597, "author_profile": "https://Stackoverflow.com/users/821597", "pm_score": 2, "selected": false, "text": "<p>@Chris Noe</p>\n\n<blockquote>\n <p>Note that the space in front of the &amp; becomes part of the previous command.\n That has bitten me with SET, which happily puts trailing blanks into the value.</p>\n</blockquote>\n\n<p>To get around the trailing-space being added to an environment variable, wrap the set command in parens.</p>\n\n<p>E.g. <code>FOR /F %%I IN ('DIR \"*.*\" /B /O:D') DO (SET NewestFile=%%I)</code></p>\n" }, { "answer_id": 27028828, "author": "DoTheEvo", "author_id": 1383369, "author_profile": "https://Stackoverflow.com/users/1383369", "pm_score": 3, "selected": false, "text": "<pre><code>@echo off\nset source=\"C:\\test case\"\nset target=\"C:\\Users\\Alexander\\Desktop\\random folder\"\n\nFOR /F \"delims=\" %%I IN ('DIR %source%\\*.* /A:-D /O:-D /B') DO COPY %source%\\\"%%I\" %target% &amp; echo %%I &amp; GOTO :END\n:END\nTIMEOUT 4\n</code></pre>\n\n<p>My attempt to copy the newest file from a folder</p>\n\n<p>just set your source and target folders and it should work</p>\n\n<p>This one ignores folders, concern itself only with files</p>\n\n<p>Recommed that you choose filetype in the DIR path changing <code>*.*</code> to <code>*.zip</code> for example</p>\n\n<p>TIMEOUT wont work on winXP I think</p>\n" }, { "answer_id": 68243394, "author": "Bharathiraja", "author_id": 2648257, "author_profile": "https://Stackoverflow.com/users/2648257", "pm_score": 0, "selected": false, "text": "<p>Copy most recent files based on <code>date</code> from one directory to another directory</p>\n<pre><code>echo off\nrem copying latest file with current date from one folder to another folder\ncls\necho Copying files. Please wait...\n:: echo Would you like to do a copy?\nrem pause\nfor /f &quot;tokens=1-4 delims=/ &quot; %%i in (&quot;%date%&quot;) do (\n set dow=%%i\n set month=%%j\n set day=%%k\n set year=%%l\n)\n:: Pad digits with leading zeros e.g Sample_01-01-21.csv\n set yy=%year:~-2%\n:: Alternate way - set datestr=%date:~0,2%-%date:~3,2%-%date:~6,2%\nset datestr=%day%-%month%-%yy%\n:: echo &quot;\\\\networkdrive\\Test\\Sample_%datestr%.csv&quot;\nrem copy files from src to dest e.g copy &lt;src path&gt; &lt;dest path&gt;\ncopy &quot;D:\\Source\\Sample_%datestr%.csv&quot; D:\\Destination\necho Completed\nrem pause\n</code></pre>\n<p><code>Save</code> the above code with <code>.bat</code> file format and Change the directory as per your needs and run the <code>batch</code> file.</p>\n" }, { "answer_id": 72858926, "author": "YazanGhafir", "author_id": 11886045, "author_profile": "https://Stackoverflow.com/users/11886045", "pm_score": 1, "selected": false, "text": "<p>The previous answers compares the modification date and NOT the creation date. Here is an example of a script that compares based on the creation date and time:</p>\n<pre><code>set origFolderPath=..\\Source\\Customization.Solution\nset distFolderPath=.\\PublishCustomization.Solution\n\nFOR /F &quot;tokens=*&quot; %%I IN ('DIR &quot;%origFolderPath%\\*.zip&quot; /T:C /B /O:D') DO SET &quot;NewestFile=%%I&quot;\ncopy %origFolderPath%\\%NewestFile% %distFolderPath%\n</code></pre>\n<p>The trick is that /A-D that is used in previous answers checks the modification date which can be the same for all edited files if you run the script on grabbed files from a source control system like tfs and then a wrong answer will be yeilded. /T:C compares the creation date time instead which might be a solution in such cases.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5269/" ]
I need to copy the newest file in a directory to a new location. So far I've found resources on the [forfiles](http://www.ss64.com/nt/forfiles.html) command, a [date-related question](https://stackoverflow.com/q/51837) here, and another [related question](https://stackoverflow.com/q/50902). I'm just having a bit of trouble putting the pieces together! How do I copy the newest file in that directory to a new place?
Windows shell, one liner: ``` FOR /F "delims=" %%I IN ('DIR *.* /A-D /B /O:-D') DO COPY "%%I" <<NewDir>> & EXIT ```
97,391
<p>I have the following enum declared:</p> <pre><code> public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' } </code></pre> <p>How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ?</p> <p>Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard.</p>
[ { "answer_id": 97395, "author": "Andy", "author_id": 13505, "author_profile": "https://Stackoverflow.com/users/13505", "pm_score": 1, "selected": false, "text": "<p>I believe Enum.GetValues() is what you're looking for.</p>\n" }, { "answer_id": 97397, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": -1, "selected": true, "text": "<p>Marking this as not correct, but I can't delete it.</p>\n<p>Try this:</p>\n<pre><code>string value = (string)TransactionTypeCode.Shipment;\n</code></pre>\n" }, { "answer_id": 123545, "author": "IaCoder", "author_id": 17337, "author_profile": "https://Stackoverflow.com/users/17337", "pm_score": -1, "selected": false, "text": "<p>This is how I generally set up my enums:</p>\n\n<pre><code>public enum TransactionTypeCode {\n\n Shipment(\"S\"),Receipt (\"R\");\n\n private final String val;\n\n TransactionTypeCode(String val){\n this.val = val;\n }\n\n public String getTypeCode(){\n return val;\n }\n}\n\nSystem.out.println(TransactionTypeCode.Shipment.getTypeCode());\n</code></pre>\n" }, { "answer_id": 703937, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was Searching For That and i get the Solution \nUse the Convert Class</p>\n\n<pre><code>int value = Convert.ToInt32(TransactionTypeCode.Shipment);\n</code></pre>\n\n<p>see how it easy</p>\n" }, { "answer_id": 2292564, "author": "Andre", "author_id": 276515, "author_profile": "https://Stackoverflow.com/users/276515", "pm_score": 5, "selected": false, "text": "<p>You have to check the underlying type of the enumeration and then convert to a proper type:</p>\n\n<pre><code>public enum SuperTasks : int\n {\n Sleep = 5,\n Walk = 7,\n Run = 9\n }\n\n private void btnTestEnumWithReflection_Click(object sender, EventArgs e)\n {\n SuperTasks task = SuperTasks.Walk;\n Type underlyingType = Enum.GetUnderlyingType(task.GetType());\n object value = Convert.ChangeType(task, underlyingType); // x will be int\n } \n</code></pre>\n" }, { "answer_id": 20312247, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 1, "selected": false, "text": "<p>The underlying type of your enum is still int, just that there's an implicit conversion from <code>char</code> to <code>int</code> for some reason. Your enum is equivalent to </p>\n\n<pre><code>TransactionTypeCode { Shipment = 83, Receipt = 82, }\n</code></pre>\n\n<p>Also note that <a href=\"http://msdn.microsoft.com/en-us/library/sbbt4032%28VS.80%29.aspx\" rel=\"nofollow\"><code>enum</code> can have any integral type as underlying type except <code>char</code></a>, probably for some semantic reason. This is not possible:</p>\n\n<pre><code>TransactionTypeCode : char { Shipment = 'S', Receipt = 'R', }\n</code></pre>\n\n<hr>\n\n<p>To get the <code>char</code> value back, you can just use a cast.</p>\n\n<pre><code>var value = (char)TransactionTypeCode.Shipment;\n\n// or to make it more explicit:\nvar value = Convert.ToChar(TransactionTypeCode.Shipment);\n</code></pre>\n\n<p>The second one causes boxing, and hence should preform worse. So may be slightly better is</p>\n\n<pre><code>var value = Convert.ToChar((int)TransactionTypeCode.Shipment);\n</code></pre>\n\n<p>but ugly. Given performance/readability trade-off I prefer the first (cast) version..</p>\n" }, { "answer_id": 31048652, "author": "Tonio", "author_id": 5048578, "author_profile": "https://Stackoverflow.com/users/5048578", "pm_score": 0, "selected": false, "text": "<p>the underlying values of the enum has to be numeric. If the type of underlying values are known, then a simple cast returns the underlying value for a given instance of the enum.</p>\n\n<pre><code>enum myEnum : byte {Some = 1, SomeMore, Alot, TooMuch};\nmyEnum HowMuch = myEnum.Alot;\nConsole.Writeline(\"How much: {0}\", (byte)HowMuch);\n</code></pre>\n\n<p>OUTPUT: How much: 3</p>\n\n<p>OR (closer to the original question)</p>\n\n<pre><code>enum myFlags:int {None='N',Alittle='A',Some='S',Somemore='M',Alot='L'};\nmyFlags howMuch = myFlags.Some;\nConsole.WriteLine(\"How much: {0}\", (char)howMuch);\n//If you cast as int you get the ASCII value not the character.\n</code></pre>\n\n<p>This is recurring question for me, I always forget that a simple cast gets you the value.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have the following enum declared: ``` public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' } ``` How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ? Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard.
Marking this as not correct, but I can't delete it. Try this: ``` string value = (string)TransactionTypeCode.Shipment; ```
97,402
<p>I've been trying to install PDT in Eclipse 3.4 for a few hours now and I'm not having any success.</p> <p>I have a previous installation of the Eclipse for Java EE developers (my main deal) distro and I just want to add the PDT to my install so I can also work on some of my websites in Eclipse. </p> <p>I've done my best to follow <a href="http://wiki.eclipse.org/PDT/Installation" rel="nofollow noreferrer">the instructions</a> at the PDT Wiki and I'm just not having any success. The specific message that it barks at me when I attempt to select the <strong>PDT Features</strong> option in the PDT Update Site section of the available software dialog is thus: </p> <pre><code>Cannot complete the request. See the details. Cannot find a solution satisfying the following requirements Match[requiredCapability: org.eclipse.equinox.p2.iu/org.eclipse.wst.web_ui.feature.feature.group/ [3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF, 3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF]]. </code></pre> <p>What is the solution?</p>
[ { "answer_id": 198709, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 1, "selected": false, "text": "<p>If you have a list of all the plugins that you already have it may be faster and easier to go to <a href=\"http://www.yoxos.com/ondemand/\" rel=\"nofollow noreferrer\">YOXOS</a> and download a new copy of eclipse with all the plugins already loaded. just remember to change your workspace if you do this.</p>\n" }, { "answer_id": 212340, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I had the same issue with the PDT plugin. Just follow this guide <a href=\"http://wiki.eclipse.org/PDT/Installation\" rel=\"nofollow noreferrer\">http://wiki.eclipse.org/PDT/Installation</a> and ensure you're using the latest PDT version (2). The PDT update site serves the previous stable version.</p>\n" }, { "answer_id": 246287, "author": "deresh", "author_id": 11851, "author_profile": "https://Stackoverflow.com/users/11851", "pm_score": 0, "selected": false, "text": "<p>I have looked at lots of guides, but i finaly figured it out on myself:</p>\n\n<ol>\n<li>Download Ganyamede SDK</li>\n<li>Through update manager install Web Developer Tools ( v 3.0.x )</li>\n<li>Again using update manager instal DLTK version 1.0 or higher</li>\n<li><p>manualy download latest integration or nightly od PDT 2.0 and unpack it in eclipse folder</p></li>\n<li><p>and now you should have working PDT 2.0 in ganyamede ;)</p></li>\n</ol>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I've been trying to install PDT in Eclipse 3.4 for a few hours now and I'm not having any success. I have a previous installation of the Eclipse for Java EE developers (my main deal) distro and I just want to add the PDT to my install so I can also work on some of my websites in Eclipse. I've done my best to follow [the instructions](http://wiki.eclipse.org/PDT/Installation) at the PDT Wiki and I'm just not having any success. The specific message that it barks at me when I attempt to select the **PDT Features** option in the PDT Update Site section of the available software dialog is thus: ``` Cannot complete the request. See the details. Cannot find a solution satisfying the following requirements Match[requiredCapability: org.eclipse.equinox.p2.iu/org.eclipse.wst.web_ui.feature.feature.group/ [3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF, 3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF]]. ``` What is the solution?
If you have a list of all the plugins that you already have it may be faster and easier to go to [YOXOS](http://www.yoxos.com/ondemand/) and download a new copy of eclipse with all the plugins already loaded. just remember to change your workspace if you do this.
97,435
<p>Suppose you have the following string:</p> <pre><code>white sand, tall waves, warm sun </code></pre> <p>It's easy to write a regular expression that will match the delimiters, which the Java String.split() method can use to give you an array containing the tokens "white sand", "tall waves" and "warm sun":</p> <pre><code>\s*,\s* </code></pre> <p>Now say you have this string:</p> <pre><code>white sand and tall waves and warm sun </code></pre> <p>Again, the regex to split the tokens is easy (ensuring you don't get the "and" inside the word "sand"):</p> <pre><code>\s+and\s+ </code></pre> <p>Now, consider this string:</p> <pre><code>white sand, tall waves and warm sun </code></pre> <p>Can a regex be written that will match the delimiters correctly, allowing you to split the string into the same tokens as in the previous two cases? Alternatively, can a regex be written that will match the tokens themselves and omit the delimiters? (Any amount of white space on either side of a comma or the word "and" should be considered part of the delimiter.)</p> <p>Edit: As has been pointed out in the comments, the correct answer should robustly handle delimiters at the beginning or end of the input string. The <em>ideal</em> answer should be able to take a string like ",white sand, tall waves and warm sun and " and provide these exact three tokens:</p> <pre><code>[ "white sand", "tall waves", "warm sun" ] </code></pre> <p>...without <del>extra empty tokens or</del> extra white space at the start or end of any token.</p> <p>Edit: It's been pointed out that extra empty tokens are unavoidable with String.split(), so that's been removed as a criterion for the "perfect" regex.</p> <hr> <p>Thanks everyone for your responses! I've tried to make sure I upvoted everyone who contributed a workable regex that wasn't essentially a duplicate. Dan's answer was the most robust (it even handles ",white sand, tall waves,and warm sun and " reasonably, with that odd comma placement after the word "waves"), so I've marked his as the accepted answer. The regex provided by nsayer was a close second.</p>
[ { "answer_id": 97457, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 2, "selected": false, "text": "<p>This should catch both 'and' or ','</p>\n\n<pre><code>(?:\\sand|,)\\s\n</code></pre>\n" }, { "answer_id": 97458, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "<p>Yes, that's what regexp are for :</p>\n\n<pre><code>\\s*(?:and|,)\\s*\n</code></pre>\n\n<p>The | defines alternatives, the () groups the selectors and the :? ensure the regexp engine won't try to retain the value between the ().</p>\n\n<p>EDIT : to avoid the sand pitfall (thanks for notifying) :</p>\n\n<pre><code>\\s*(?:[^s]and|,)\\s*\n</code></pre>\n" }, { "answer_id": 97470, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 2, "selected": false, "text": "<p>The problem with</p>\n\n<pre><code>\\s*(,|(and))\\s*\n</code></pre>\n\n<p>is that it would split up \"sand\" inappropriately.</p>\n\n<p>The problem with</p>\n\n<pre><code>\\s+(,|(and))\\s+\n</code></pre>\n\n<p>is that it requires spaces around commas.</p>\n\n<p>The right answer probably has to be</p>\n\n<pre><code>(\\s*,\\s*)|(\\s+and\\s+)\n</code></pre>\n\n<p>I'll cheat a little on the concept of returning the strings surrounded by delimiters by suggesting that lots of languages have a \"split\" operator that does exactly what you want when the regex specifies the form of the delimiter itself. See the Java String.split() function.</p>\n" }, { "answer_id": 97482, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 2, "selected": false, "text": "<p>Would this work?</p>\n\n<pre><code>\\s*(,|\\s+and)\\s+\n</code></pre>\n" }, { "answer_id": 97494, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 0, "selected": false, "text": "<pre><code>(?:(?&lt;!s)and\\s+|\\,\\s+)\n</code></pre>\n\n<p>Might work</p>\n\n<p>Don't have a way to test it, but took out the just space matcher.</p>\n" }, { "answer_id": 97632, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": true, "text": "<p>This should be pretty resilient, and handle stuff like delimiters at the end of the string (\"foo and bar and \", for example)</p>\n\n<pre><code>\\s*(?:\\band\\b|,)\\s*\n</code></pre>\n" }, { "answer_id": 97843, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "<p>Maybe:</p>\n\n<p>((\\s*,\\s*)|(\\s+and\\s+))</p>\n\n<p>I'm not a java programmer, so I'm not sure if java regex allows '?'</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287/" ]
Suppose you have the following string: ``` white sand, tall waves, warm sun ``` It's easy to write a regular expression that will match the delimiters, which the Java String.split() method can use to give you an array containing the tokens "white sand", "tall waves" and "warm sun": ``` \s*,\s* ``` Now say you have this string: ``` white sand and tall waves and warm sun ``` Again, the regex to split the tokens is easy (ensuring you don't get the "and" inside the word "sand"): ``` \s+and\s+ ``` Now, consider this string: ``` white sand, tall waves and warm sun ``` Can a regex be written that will match the delimiters correctly, allowing you to split the string into the same tokens as in the previous two cases? Alternatively, can a regex be written that will match the tokens themselves and omit the delimiters? (Any amount of white space on either side of a comma or the word "and" should be considered part of the delimiter.) Edit: As has been pointed out in the comments, the correct answer should robustly handle delimiters at the beginning or end of the input string. The *ideal* answer should be able to take a string like ",white sand, tall waves and warm sun and " and provide these exact three tokens: ``` [ "white sand", "tall waves", "warm sun" ] ``` ...without ~~extra empty tokens or~~ extra white space at the start or end of any token. Edit: It's been pointed out that extra empty tokens are unavoidable with String.split(), so that's been removed as a criterion for the "perfect" regex. --- Thanks everyone for your responses! I've tried to make sure I upvoted everyone who contributed a workable regex that wasn't essentially a duplicate. Dan's answer was the most robust (it even handles ",white sand, tall waves,and warm sun and " reasonably, with that odd comma placement after the word "waves"), so I've marked his as the accepted answer. The regex provided by nsayer was a close second.
This should be pretty resilient, and handle stuff like delimiters at the end of the string ("foo and bar and ", for example) ``` \s*(?:\band\b|,)\s* ```
97,447
<p>If I am writing a library and I have a function that needs to return a sequence of values, I could do something like:</p> <pre><code>std::vector&lt;int&gt; get_sequence(); </code></pre> <p>However, this requires the library user to use the std::vector&lt;> container rather than allowing them to use whatever container they want to use. In addition, it can add an extra copy of the returned array (depending on whether the compiler could optimize this or not) that might have a negative impact on performance.</p> <p>You could theoretically enable the use of arbitrary containers (and avoid the unnecessary extra copying) by making a templated function that takes a start and an end iter:</p> <pre><code>template&lt;class T_iter&gt; void get_sequence(T_iter begin, T_iter end); </code></pre> <p>The function would then store the sequence values in the range given by the iterators. But the problem with this is that it requires you to know the size of the sequence so you have enough elements between <code>begin</code> and <code>end</code> to store all of the values in the sequence.</p> <p>I thought about an interface such as:</p> <pre><code>template&lt;T_insertIter&gt; get_sequence(T_insertIter inserter); </code></pre> <p>which requires that the T_insertIter be an insert iterator (e.g. created with <code>std::back_inserter(my_vector)</code>), but this seems way too easy to misuse since the compiler would happily accept a non-insert iterator but would behave incorrectly at run-time.</p> <p>So is there a best practice for designing generic interfaces that return sequences of arbitrary length?</p>
[ { "answer_id": 97519, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 0, "selected": false, "text": "<p><code>std::list&lt;int&gt;</code> is slightly nicer, IMO. Note that this would not require an extra copy of the data in the list, as it's only pointers being copied.</p>\n\n<p>It depends entirely on your consumers. If you can expect them to be C++ developers, give them one of the <code>std</code> container classes, I say.</p>\n\n<p>The only other thing that occurs to me is that you'd do this:</p>\n\n<pre><code>void get_sequence(std::tr1::function&lt;void(int)&gt; f);\n</code></pre>\n\n<p>Then the caller can use<code>std::tr1::bind</code> to make your <code>get_sequence</code> function call whatever function on whatever object (or not) that they want. You just keep calling <code>f</code> for each element you're creating.</p>\n" }, { "answer_id": 97541, "author": "moswald", "author_id": 8368, "author_profile": "https://Stackoverflow.com/users/8368", "pm_score": 0, "selected": false, "text": "<p>You could do something like</p>\n\n<pre><code>template&lt;typename container&gt;\ncontainer get_sequence();\n</code></pre>\n\n<p>and require that the supplied container type conforms to some standard interface (like having a member push_back and maybe reserve, so that the user of your interface can use vector/deque/list).</p>\n" }, { "answer_id": 97551, "author": "user17481", "author_id": 17481, "author_profile": "https://Stackoverflow.com/users/17481", "pm_score": 2, "selected": false, "text": "<p>Why do you need your interface to be container-independent? Scott Meyers in his \"Effective STL\" gives a good reasoning for <em>not</em> trying to make your code container-independent, no matter how strong the temptation is. Basically, containers are intended for completely different usage: you probably don't want to store your output in map or set (they're not interval containers), so you're left with vector, list and deque, and why do you wish to have vector where you need list and vice versa? They're completely different, and you'll have better results using all the features of one of them than trying to make both work. Well, just consider reading \"Effective STL\": it's worth your time.</p>\n\n<p>If you know something about your container, though, you may consider doing something like</p>\n\n<pre><code>\ntemplate void get_sequence(T_Container & container)\n{\n //...\n container.assign(iter1, iter2);\n //...\n}\n</code></pre>\n\n<p>or maybe</p>\n\n<pre><code>\ntemplate void get_sequence(T_Container & container)\n{\n //...\n container.resize(size);\n //use push_back or whatever\n //...\n}\n</code></pre>\n\n<p>or even control what you do with a strategy, like</p>\n\n<pre><code>\nclass AssignStrategy // for stl\n{\npublic:\n template\n void fill(T_Container & container, T_Container::iterator it1, T_Container::iterator it2){\n container.assign(it1, it2);\n }\n};\n\nclass ReserveStrategy // for vectors and stuff\n{\npublic:\n template\n void fill(T_Container & container, T_Container::iterator it1, T_Container::iterator it2){\n container.reserve(it2 - it1);\n while(it1 != it2)\n container.push_back(*it1++);\n }\n};\n\n\ntemplate \nvoid get_sequence(T_Container & container)\n{\n //...\n T_FillStrategy::fill(container, iter1, iter2);\n //...\n}\n</code></pre>\n" }, { "answer_id": 97597, "author": "David Pierre", "author_id": 18296, "author_profile": "https://Stackoverflow.com/users/18296", "pm_score": 0, "selected": false, "text": "<p>You can statically dispatch on the type of iterator using iterator_traits</p>\n\n<p>Something like this :</p>\n\n<pre><code>template&lt;T_insertIter&gt; get_sequence(T_insertIter inserter)\n{\n return get_sequence(inserter, typename iterator_traits&lt;Iterator&gt;::iterator_category());\n}\n\ntemplate&lt;T_insertIter&gt; get_sequence(T_insertIter inserter, input_iterator_tag);\n</code></pre>\n" }, { "answer_id": 97623, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "<p>Have get_sequence return a (custom) <code>forward_iterator</code> class that generates the sequence on-demand. (It could also be a more advanced iterator type like <code>bidirectional_iterator</code> if that's practical for your sequence.)</p>\n\n<p>Then the user can copy the sequence into whatever container type they want. Or, they can just loop directly on your iterator and skip the container entirely.</p>\n\n<p>You will need some sort of end iterator. Without knowing exactly how you're generating the sequence, it's hard to say exactly how you should implement that. One way would be for your iterator class to have a static member function that returned an end iterator, like:</p>\n\n<pre><code>static const my_itr&amp; end() { static const my_itr e(...); return e; };\n</code></pre>\n\n<p>where <code>...</code> represents whatever parameters you need to create the end iterator (which might use a private constructor). Then your loop would look like:</p>\n\n<pre><code>for (my_itr i = get_sequence(); i != my_itr::end(); ++i) { ... }\n</code></pre>\n\n<p>Here's a trivial example of a forward iterator class that generates a sequence of consecutive integers. Obviously, this could easily be turned into a bidirectional or random access iterator, but I wanted to keep the example small.</p>\n\n<pre><code>#include &lt;iterator&gt;\n\nclass integer_sequence_itr\n : public std::iterator&lt;std::forward_iterator_tag, int&gt;\n{\n private:\n int i;\n\n public:\n explicit integer_sequence_itr(int start) : i(start) {};\n\n const int&amp; operator*() const { return i; };\n const int* operator-&gt;() const { return &amp;i; };\n\n integer_sequence_itr&amp; operator++() { ++i; return *this; };\n integer_sequence_itr operator++(int)\n { integer_sequence_itr copy(*this); ++i; return copy; };\n\n inline bool operator==(const integer_sequence_itr&amp; rhs) const\n { return i == rhs.i; };\n\n inline bool operator!=(const integer_sequence_itr&amp; rhs) const\n { return i != rhs.i; };\n}; // end integer_sequence_itr\n\n//Example: Print the integers from 1 to 10.\n#include &lt;iostream&gt;\n\nint main()\n{\n const integer_sequence_itr stop(11);\n\n for (integer_sequence_itr i(1); i != stop; ++i)\n std::cout &lt;&lt; *i &lt;&lt; std::endl;\n\n return 0;\n} // end main\n</code></pre>\n" }, { "answer_id": 97628, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 2, "selected": false, "text": "<p>One thing to pay extra attention to is if you by <em>library</em> mean a DLL or similar. Then there might be problems if the library consumer, say an application, is built with another compiler than the library itself.</p>\n\n<p>Consider the case where you in your example return a <code>std::vector&lt;&gt;</code> by value. Memory will then be allocated in the context of the library, but deallocated in the context of the application. Two different compilers might allocate/deallocate differently and so havoc might occur.</p>\n" }, { "answer_id": 97712, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "<p>Err... Just my two cents, but:</p>\n\n<pre><code>void get_sequence(std::vector&lt;int&gt; &amp; p_aInt);\n</code></pre>\n\n<p>This would remove the potential return by copy problem.\nNow, if you really want to avoid imposing a container, you could try something like:</p>\n\n<pre><code>template &lt;typename T&gt;\nvoid get_sequence(T &amp; p_aInt)\n{\n p_aInt.push_back(25) ; // Or whatever you need to add\n}\n</code></pre>\n\n<p>This would compile only for vectors, lists and deque (and similar containers). Should you want a larget set of possible containers, the code would be:</p>\n\n<pre><code>template &lt;typename T&gt;\nvoid get_sequence(T &amp; p_aInt)\n{\n p_aInt.insert(p_aInt.end(), 25) ; // Or whatever you need to add\n}\n</code></pre>\n\n<p>But as said by other posts, you should accept to limit your interface to one kind of containers only.</p>\n" }, { "answer_id": 98443, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If your already manage memory for your sequence, you can return a pair of iterators for the caller to use in for loop or an algorithm call.</p>\n\n<p>If the returned sequence needs to manage its own memory, then things are more convoluted. You can use @paercebal's solution, or you can implement your own iterators that hold shared_ptr to the sequence they are iterating.</p>\n" }, { "answer_id": 3736379, "author": "Alexandre C.", "author_id": 373025, "author_profile": "https://Stackoverflow.com/users/373025", "pm_score": 0, "selected": false, "text": "<p>For outputting sequences, I see two options. The first is something like</p>\n\n<pre><code>template &lt;typename OutputIter&gt;\nvoid generate_sequence(OutputIter out)\n{\n //...\n while (...) { *out = ...; ++out; }\n}\n</code></pre>\n\n<p>The second is something like</p>\n\n<pre><code>struct sequence_generator\n{\n bool has_next() { ... }\n your_type next() { mutate_state(); return next_value; }\n\nprivate:\n // some state\n};\n</code></pre>\n\n<p>that you would want to turn into a standard C++ iterator (using <code>boost::iterator_facade</code> for convenience) to use it in standard algorithms (<code>copy</code>, <code>transform</code>, ...).</p>\n\n<p>Have also a look at <code>boost::transform_iterator</code>, combined with some iterator returning integers in sequence.</p>\n" }, { "answer_id": 3736499, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p>You could pass a functor to your function which accepts a single value. The functor would then be responsible for storing the value in whatever container you are using at the time.</p>\n\n<pre><code>struct vector_adder {\n vector_adder(std::vector&lt;int&gt;&amp; v) : v(v) {}\n void operator()(int n) { v.push_back(n); }\n std::vector&lt;int&gt;&amp; v;\n};\n\nvoid gen_sequence(boost::function&lt; void(int) &gt; f) {\n ...\n f(n);\n ...\n}\n\nmain() {\n std::vector&lt;int&gt; vi;\n gen_sequence(vector_adder(vi));\n}\n</code></pre>\n\n<p>Note: I'm using boost.function here to define the functor parameter. You don't need boost to be able to do this. It just makes it a lot simpler.</p>\n\n<p>You could also use a function pointer instead of a functor, but I don't recommend it. It's error prone and there's no easy way to bind data to it.</p>\n\n<p>Also, if your compiler supports C++0x lambda functions, you can simplify the code by eliminating the explicit functor definition:</p>\n\n<pre><code>main() {\n std::vector&lt;int&gt; ui;\n gen_sequence([&amp;](int n)-&gt;void{ui.push_back(n);});\n}\n</code></pre>\n\n<p>(I'm still using VS2008 so I'm not sure if I got the lambda syntax right)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78437/" ]
If I am writing a library and I have a function that needs to return a sequence of values, I could do something like: ``` std::vector<int> get_sequence(); ``` However, this requires the library user to use the std::vector<> container rather than allowing them to use whatever container they want to use. In addition, it can add an extra copy of the returned array (depending on whether the compiler could optimize this or not) that might have a negative impact on performance. You could theoretically enable the use of arbitrary containers (and avoid the unnecessary extra copying) by making a templated function that takes a start and an end iter: ``` template<class T_iter> void get_sequence(T_iter begin, T_iter end); ``` The function would then store the sequence values in the range given by the iterators. But the problem with this is that it requires you to know the size of the sequence so you have enough elements between `begin` and `end` to store all of the values in the sequence. I thought about an interface such as: ``` template<T_insertIter> get_sequence(T_insertIter inserter); ``` which requires that the T\_insertIter be an insert iterator (e.g. created with `std::back_inserter(my_vector)`), but this seems way too easy to misuse since the compiler would happily accept a non-insert iterator but would behave incorrectly at run-time. So is there a best practice for designing generic interfaces that return sequences of arbitrary length?
Have get\_sequence return a (custom) `forward_iterator` class that generates the sequence on-demand. (It could also be a more advanced iterator type like `bidirectional_iterator` if that's practical for your sequence.) Then the user can copy the sequence into whatever container type they want. Or, they can just loop directly on your iterator and skip the container entirely. You will need some sort of end iterator. Without knowing exactly how you're generating the sequence, it's hard to say exactly how you should implement that. One way would be for your iterator class to have a static member function that returned an end iterator, like: ``` static const my_itr& end() { static const my_itr e(...); return e; }; ``` where `...` represents whatever parameters you need to create the end iterator (which might use a private constructor). Then your loop would look like: ``` for (my_itr i = get_sequence(); i != my_itr::end(); ++i) { ... } ``` Here's a trivial example of a forward iterator class that generates a sequence of consecutive integers. Obviously, this could easily be turned into a bidirectional or random access iterator, but I wanted to keep the example small. ``` #include <iterator> class integer_sequence_itr : public std::iterator<std::forward_iterator_tag, int> { private: int i; public: explicit integer_sequence_itr(int start) : i(start) {}; const int& operator*() const { return i; }; const int* operator->() const { return &i; }; integer_sequence_itr& operator++() { ++i; return *this; }; integer_sequence_itr operator++(int) { integer_sequence_itr copy(*this); ++i; return copy; }; inline bool operator==(const integer_sequence_itr& rhs) const { return i == rhs.i; }; inline bool operator!=(const integer_sequence_itr& rhs) const { return i != rhs.i; }; }; // end integer_sequence_itr //Example: Print the integers from 1 to 10. #include <iostream> int main() { const integer_sequence_itr stop(11); for (integer_sequence_itr i(1); i != stop; ++i) std::cout << *i << std::endl; return 0; } // end main ```
97,459
<p>When a C# WinForms textbox receives focus, I want it to behave like your browser's address bar.</p> <p>To see what I mean, click in your web browser's address bar. You'll notice the following behavior: </p> <ol> <li>Clicking in the textbox should select all the text if the textbox wasn't previously focused.</li> <li>Mouse down and drag in the textbox should select only the text I've highlighted with the mouse.</li> <li>If the textbox is already focused, clicking does not select all text.</li> <li>Focusing the textbox programmatically or via keyboard tabbing should select all text.</li> </ol> <p>I want to do exactly this in WinForms.</p> <p><strong>FASTEST GUN ALERT: please read the following before answering!</strong> Thanks guys. :-)</p> <blockquote> <p><strong>Calling .SelectAll() during the .Enter or .GotFocus events won't work</strong> because if the user clicked the textbox, the caret will be placed where he clicked, thus deselecting all text.</p> <p><strong>Calling .SelectAll() during the .Click event won't work</strong> because the user won't be able to select any text with the mouse; the .SelectAll() call will keep overwriting the user's text selection.</p> <p><strong>Calling BeginInvoke((Action)textbox.SelectAll) on focus/enter event enter doesn't work</strong> because it breaks rule #2 above, it will keep overriding the user's selection on focus.</p> </blockquote>
[ { "answer_id": 97499, "author": "Jakub Kotrla", "author_id": 16943, "author_profile": "https://Stackoverflow.com/users/16943", "pm_score": 2, "selected": false, "text": "<p>Click event of textbox? Or even MouseCaptureChanged event works for me. - OK. doesn't work.</p>\n\n<p>So you have to do 2 things:</p>\n\n<pre><code>private bool f = false;\n\nprivate void textBox_MouseClick(object sender, MouseEventArgs e)\n{ \n if (this.f) { this.textBox.SelectAll(); }\n this.f = false;\n}\n\nprivate void textBox_Enter(object sender, EventArgs e)\n{\n this.f = true;\n this.textBox.SelectAll();\n}\nprivate void textBox_MouseMove(object sender, MouseEventArgs e) // idea from the other answer\n{\n this.f = false; \n}\n</code></pre>\n\n<p>Works for tabbing (through textBoxes to the one) as well - call SelectAll() in Enter just in case...</p>\n" }, { "answer_id": 97509, "author": "Todd Benning", "author_id": 18298, "author_profile": "https://Stackoverflow.com/users/18298", "pm_score": 3, "selected": false, "text": "<p>It's a bit kludgey, but in your click event, use <code>SendKeys.Send( \"{HOME}+{END}\" );</code>.</p>\n" }, { "answer_id": 97515, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 2, "selected": false, "text": "<pre><code>'Inside the Enter event\nTextBox1.SelectAll();\n</code></pre>\n\n<p>Ok, after trying it here is what you want:</p>\n\n<ul>\n<li>On the Enter event start a flag that states that you have been in the enter event</li>\n<li>On the Click event, if you set the flag, call .SelectAll() and reset the flag.</li>\n<li>On the MouseMove event, set the entered flag to false, which will allow you to click highlight without having to enter the textbox first.</li>\n</ul>\n\n<p>This selected all the text on entry, but allowed me to highlight part of the text afterwards, or allow you to highlight on the first click.</p>\n\n<p>By request:</p>\n\n<pre><code> bool entered = false;\n private void textBox1_Enter(object sender, EventArgs e)\n {\n entered = true;\n textBox1.SelectAll(); //From Jakub's answer.\n }\n\n private void textBox1_Click(object sender, EventArgs e)\n {\n if (entered) textBox1.SelectAll();\n entered = false;\n }\n\n private void textBox1_MouseMove(object sender, MouseEventArgs e)\n {\n if (entered) entered = false;\n }\n</code></pre>\n\n<p>For me, the tabbing into the control selects all the text.</p>\n" }, { "answer_id": 97664, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 0, "selected": false, "text": "<pre><code>private bool _isSelected = false;\nprivate void textBox_Validated(object sender, EventArgs e)\n{\n _isSelected = false;\n}\n\nprivate void textBox_MouseClick(object sender, MouseEventArgs e)\n{\n SelectAllText(textBox);\n}\n\nprivate void textBox_Enter(object sender, EventArgs e)\n{\n SelectAllText(textBox);\n}\n\nprivate void SelectAllText(TextBox text)\n{\n if (!_isSelected)\n {\n _isSelected = true;\n textBox.SelectAll();\n }\n}\n</code></pre>\n" }, { "answer_id": 97735, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": -1, "selected": false, "text": "<p>The below seems to work.\nThe enter event handles the tabbing to the control and the MouseDown works when the control is clicked.</p>\n\n<pre><code> private ########### void textBox1_Enter(object sender, EventArgs e)\n {\n textBox1.SelectAll();\n }\n\n private void textBox1_MouseDown(object sender, MouseEventArgs e)\n {\n if (textBox1.Focused)\n textBox1.SelectAll();\n }\n</code></pre>\n" }, { "answer_id": 97814, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Interestingly, a ComboBox with DropDownStyle=Simple has pretty much exactly the behaviour you are looking for, I think.</p>\n\n<p>(If you reduce the height of the control to not show the list - and then by a couple of pixels more - there's no effective difference between the ComboBox and the TextBox.)</p>\n" }, { "answer_id": 100362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Actually GotFocus is the right event (message really) that you are interested in, since no matter how you get to the control you’ll get this even eventually. The question is when do you call SelectAll().</p>\n\n<p>Try this:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n this.textBox1.GotFocus += new EventHandler(textBox1_GotFocus);\n }\n\n private delegate void SelectAllDelegate(); \n private IAsyncResult _selectAllar = null; //So we can clean up afterwards.\n\n //Catch the input focus event\n void textBox1_GotFocus(object sender, EventArgs e)\n {\n //We could have gotten here many ways (including mouse click)\n //so there could be other messages queued up already that might change the selection.\n //Don't call SelectAll here, since it might get undone by things such as positioning the cursor.\n //Instead use BeginInvoke on the form to queue up a message\n //to select all the text after everything caused by the current event is processed.\n this._selectAllar = this.BeginInvoke(new SelectAllDelegate(this._SelectAll));\n }\n\n private void _SelectAll()\n {\n //Clean-up the BeginInvoke\n if (this._selectAllar != null)\n {\n this.EndInvoke(this._selectAllar);\n }\n //Now select everything.\n this.textBox1.SelectAll();\n }\n}\n</code></pre>\n" }, { "answer_id": 102095, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 8, "selected": true, "text": "<p>First of all, thanks for answers! 9 total answers. Thank you.</p>\n\n<p>Bad news: all of the answers had some quirks or didn't work quite right (or at all). I've added a comment to each of your posts.</p>\n\n<p>Good news: I've found a way to make it work. This solution is pretty straightforward and seems to work in all the scenarios (mousing down, selecting text, tabbing focus, etc.)</p>\n\n<pre><code>bool alreadyFocused;\n\n...\n\ntextBox1.GotFocus += textBox1_GotFocus;\ntextBox1.MouseUp += textBox1_MouseUp;\ntextBox1.Leave += textBox1_Leave;\n\n...\n\nvoid textBox1_Leave(object sender, EventArgs e)\n{\n alreadyFocused = false;\n}\n\n\nvoid textBox1_GotFocus(object sender, EventArgs e)\n{\n // Select all text only if the mouse isn't down.\n // This makes tabbing to the textbox give focus.\n if (MouseButtons == MouseButtons.None)\n {\n this.textBox1.SelectAll();\n alreadyFocused = true;\n }\n}\n\nvoid textBox1_MouseUp(object sender, MouseEventArgs e)\n{\n // Web browsers like Google Chrome select the text on mouse up.\n // They only do it if the textbox isn't already focused,\n // and if the user hasn't selected all text.\n if (!alreadyFocused &amp;&amp; this.textBox1.SelectionLength == 0)\n {\n alreadyFocused = true;\n this.textBox1.SelectAll();\n }\n}\n</code></pre>\n\n<p>As far as I can tell, this causes a textbox to behave exactly like a web browser's address bar.</p>\n\n<p>Hopefully this helps the next guy who tries to solve this deceptively simple problem.</p>\n\n<p>Thanks again, guys, for all your answers that helped lead me towards the correct path.</p>\n" }, { "answer_id": 277254, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Why don't you simply use the MouseDown-Event of the text box? It works fine for me and doesn't need an additional boolean. Very clean and simple, eg.:</p>\n\n<pre><code>private void textbox_MouseDown(object sender, MouseEventArgs e) {\n if (textbox != null &amp;&amp; !string.IsNullOrEmpty(textbox.Text))\n {\n textbox.SelectAll();\n } }\n</code></pre>\n" }, { "answer_id": 385839, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 0, "selected": false, "text": "<p>Have you tried <a href=\"http://social.msdn.microsoft.com/forums/en-US/winforms/thread/e0d183d7-5bfe-4e68-abbb-fba9fdd209fd/\" rel=\"nofollow noreferrer\">the solution suggested on the MSDN Forum \"Windows Forms General\"</a> which simply subclasses TextBox?</p>\n" }, { "answer_id": 722965, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A one line answer that I use...you might be kicking yourself...</p>\n\n<p>In the Enter Event:</p>\n\n<p>txtFilter.BeginInvoke(new MethodInvoker( txtFilter.SelectAll));</p>\n" }, { "answer_id": 1625439, "author": "Sreejith K.", "author_id": 196700, "author_profile": "https://Stackoverflow.com/users/196700", "pm_score": 0, "selected": false, "text": "<p>I called SelectAll inside MouseUp event and it worked fine for me.</p>\n\n<pre><code> private bool _tailTextBoxFirstClick = false;\n\n private void textBox1_MouseUp(object sender, MouseEventArgs e)\n {\n if(_textBoxFirstClick) \n textBox1.SelectAll();\n\n _textBoxFirstClick = false;\n } \n\n private void textBox1_Leave(object sender, EventArgs e)\n {\n _textBoxFirstClick = true;\n textBox1.Select(0, 0);\n }\n</code></pre>\n" }, { "answer_id": 2011104, "author": "Mohammad Mahdipour", "author_id": 244468, "author_profile": "https://Stackoverflow.com/users/244468", "pm_score": 0, "selected": false, "text": "<p>Just derive a class from TextBox or MaskedTextBox:</p>\n\n<pre><code>public class SMaskedTextBox : MaskedTextBox\n{\n protected override void OnGotFocus(EventArgs e)\n {\n base.OnGotFocus(e);\n this.SelectAll();\n }\n}\n</code></pre>\n\n<p>And use it on your forms.</p>\n" }, { "answer_id": 2647823, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": -1, "selected": false, "text": "<p>I created a new VB.Net Wpf project. I created one TextBox and used the following for the codebehind:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Class MainWindow \n\n Sub New()\n\n ' This call is required by the designer.\n InitializeComponent()\n\n ' Add any initialization after the InitializeComponent() call.\n AddHandler PreviewMouseLeftButtonDown, New MouseButtonEventHandler(AddressOf SelectivelyIgnoreMouseButton)\n AddHandler GotKeyboardFocus, New KeyboardFocusChangedEventHandler(AddressOf SelectAllText)\n AddHandler MouseDoubleClick, New MouseButtonEventHandler(AddressOf SelectAllText)\n End Sub\n\n Private Shared Sub SelectivelyIgnoreMouseButton(ByVal sender As Object, ByVal e As MouseButtonEventArgs)\n ' Find the TextBox\n Dim parent As DependencyObject = TryCast(e.OriginalSource, UIElement)\n While parent IsNot Nothing AndAlso Not (TypeOf parent Is TextBox)\n parent = VisualTreeHelper.GetParent(parent)\n End While\n\n If parent IsNot Nothing Then\n Dim textBox As Object = DirectCast(parent, TextBox)\n If Not textBox.IsKeyboardFocusWithin Then\n ' If the text box is not yet focussed, give it the focus and\n ' stop further processing of this click event.\n textBox.Focus()\n e.Handled = True\n End If\n End If\n End Sub\n\n Private Shared Sub SelectAllText(ByVal sender As Object, ByVal e As RoutedEventArgs)\n Dim textBox As Object = TryCast(e.OriginalSource, TextBox)\n If textBox IsNot Nothing Then\n textBox.SelectAll()\n End If\n End Sub\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 3678888, "author": "nzhenry", "author_id": 443649, "author_profile": "https://Stackoverflow.com/users/443649", "pm_score": 5, "selected": false, "text": "<p>Your solution is good, but fails in one specific case. If you give the TextBox focus by selecting a range of text instead of just clicking, the alreadyFocussed flag doesn't get set to true, so when you click in the TextBox a second time, all the text gets selected.</p>\n\n<p>Here is my version of the solution. I've also put the code into a class which inherits TextBox, so the logic is nicely hidden away.</p>\n\n<pre><code>public class MyTextBox : System.Windows.Forms.TextBox\n{\n private bool _focused;\n\n protected override void OnEnter(EventArgs e)\n {\n base.OnEnter(e);\n if (MouseButtons == MouseButtons.None)\n {\n SelectAll();\n _focused = true;\n }\n }\n\n protected override void OnLeave(EventArgs e)\n {\n base.OnLeave(e);\n _focused = false;\n }\n\n protected override void OnMouseUp(MouseEventArgs mevent)\n {\n base.OnMouseUp(mevent);\n if (!_focused)\n {\n if (SelectionLength == 0)\n SelectAll();\n _focused = true;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 6101372, "author": "Yfiua", "author_id": 766508, "author_profile": "https://Stackoverflow.com/users/766508", "pm_score": 0, "selected": false, "text": "<p>For a group of textboxes in a form:</p>\n\n<pre><code>private System.Windows.Forms.TextBox lastFocus; \n\nprivate void textBox_GotFocus(object sender, System.Windows.Forms.MouseEventArgs e) \n{\n TextBox senderTextBox = sender as TextBox;\n if (lastFocus!=senderTextBox){\n senderTextBox.SelectAll();\n }\n lastFocus = senderTextBox; \n}\n</code></pre>\n" }, { "answer_id": 6857301, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 6, "selected": false, "text": "<p>I found a simpler solution to this. It involves kicking off the SelectAll asynchronously using <code>Control.BeginInvoke</code> so that it occurs after the Enter and Click events have occurred:</p>\n<p>In C#:</p>\n<pre><code>private void MyTextBox_Enter(object sender, EventArgs e)\n{\n // Kick off SelectAll asynchronously so that it occurs after Click\n BeginInvoke((Action)delegate\n {\n MyTextBox.SelectAll();\n });\n}\n</code></pre>\n<p>In VB.NET (thanks to <a href=\"https://stackoverflow.com/users/1309193/krishanu-dey\">Krishanu Dey</a>)</p>\n<pre><code>Private Sub MyTextBox_Enter(sender As Object, e As EventArgs) Handles MyTextBox.Enter \n BeginInvoke(DirectCast(Sub() MyTextBox.SelectAll(), Action)) \nEnd Sub\n</code></pre>\n" }, { "answer_id": 6970941, "author": "Ross K.", "author_id": 882448, "author_profile": "https://Stackoverflow.com/users/882448", "pm_score": 2, "selected": false, "text": "<p>Here's a helper function taking the solution to the next level - reuse without inheritance.</p>\n\n<pre><code> public static void WireSelectAllOnFocus( TextBox aTextBox )\n {\n bool lActive = false;\n aTextBox.GotFocus += new EventHandler( ( sender, e ) =&gt;\n {\n if ( System.Windows.Forms.Control.MouseButtons == MouseButtons.None )\n {\n aTextBox.SelectAll();\n lActive = true;\n }\n } );\n\n aTextBox.Leave += new EventHandler( (sender, e ) =&gt; {\n lActive = false;\n } );\n\n aTextBox.MouseUp += new MouseEventHandler( (sender, e ) =&gt; {\n if ( !lActive )\n {\n lActive = true;\n if ( aTextBox.SelectionLength == 0 ) aTextBox.SelectAll();\n } \n });\n }\n</code></pre>\n\n<p>To use this simply call the function passing a TextBox and it takes care of all the messy bits for you. I suggest wiring up all your text boxes in the Form_Load event. You can place this function in your form, or if your like me, somewhere in a utility class for even more reuse.</p>\n" }, { "answer_id": 8853861, "author": "Eluem", "author_id": 1148085, "author_profile": "https://Stackoverflow.com/users/1148085", "pm_score": 0, "selected": false, "text": "<p>I know this was already solved but I have a suggestion that I think is actually rather simple.</p>\n\n<p>In the mouse up event all you have to do is place</p>\n\n<pre><code>if(textBox.SelectionLength = 0)\n{\n textBox.SelectAll();\n}\n</code></pre>\n\n<p>It seems to work for me in VB.NET (I know this is a C# question... sadly I'm forced to use VB at my job.. and I was having this issue, which is what brought me here...)</p>\n\n<p>I haven't found any problems with it yet.. except for the fact that it doesn't immediately select on click, but I was having problems with that....</p>\n" }, { "answer_id": 10416412, "author": "Chris", "author_id": 1370369, "author_profile": "https://Stackoverflow.com/users/1370369", "pm_score": 2, "selected": false, "text": "<p>This is similar to <a href=\"https://stackoverflow.com/a/3678888/7444103\">nzhenry</a>'s popular answer, but I find it easier to not have to subclass:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private LastFocused As Control = Nothing\n\nPrivate Sub TextBox1_Enter(sender As Object, e As System.EventArgs) Handles TextBox1.Enter, TextBox2.Enter, TextBox3.Enter\n If MouseButtons = Windows.Forms.MouseButtons.None Then LastFocused = sender\nEnd Sub\n\nPrivate Sub TextBox1_Leave(sender As Object, e As System.EventArgs) Handles TextBox1.Leave, TextBox2.Leave, TextBox3.Leave\n LastFocused = Nothing\nEnd Sub\n\nPrivate Sub TextBox1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp, TextBox2.MouseUp, TextBox3.MouseUp\n With CType(sender, TextBox)\n If LastFocused IsNot sender AndAlso .SelectionLength = 0 Then .SelectAll()\n End With\n LastFocused = sender\nEnd Sub\n</code></pre>\n" }, { "answer_id": 10420952, "author": "Adam Bruss", "author_id": 638740, "author_profile": "https://Stackoverflow.com/users/638740", "pm_score": 1, "selected": false, "text": "<p>SelectAll never worked for me.</p>\n\n<p>This works.</p>\n\n<pre><code>ActiveControl = textBox1;\ntextBox1-&gt;SelectionStart = 0;\ntextBox1-&gt;SelectionLength = textBox1-&gt;Text-&gt;Length;\n</code></pre>\n" }, { "answer_id": 12212017, "author": "abrfra", "author_id": 978489, "author_profile": "https://Stackoverflow.com/users/978489", "pm_score": 0, "selected": false, "text": "<p>The following solution works for me. I added <code>OnKeyDown</code> and <code>OnKeyUp</code> event override to keep the TextBox text always selected.</p>\n\n<pre><code> public class NumericTextBox : TextBox\n{\n private bool _focused;\n protected override void OnGotFocus(EventArgs e)\n {\n base.OnGotFocus(e);\n if (MouseButtons == MouseButtons.None)\n {\n this.SelectAll();\n _focused = true;\n }\n }\n protected override void OnEnter(EventArgs e)\n {\n base.OnEnter(e);\n if (MouseButtons == MouseButtons.None)\n {\n SelectAll();\n _focused = true;\n }\n }\n\n protected override void OnLeave(EventArgs e)\n {\n base.OnLeave(e);\n _focused = false;\n }\n\n protected override void OnMouseUp(MouseEventArgs mevent)\n {\n base.OnMouseUp(mevent);\n if (!_focused)\n {\n if (SelectionLength == 0)\n SelectAll();\n _focused = true;\n }\n }\n\n protected override void OnKeyUp(KeyEventArgs e)\n {\n base.OnKeyUp(e);\n\n if (SelectionLength == 0)\n SelectAll();\n _focused = true;\n }\n protected override void OnKeyDown(KeyEventArgs e)\n {\n base.OnKeyDown(e);\n if (SelectionLength == 0)\n SelectAll();\n _focused = true;\n }\n}\n</code></pre>\n" }, { "answer_id": 15284242, "author": "slobs", "author_id": 2146540, "author_profile": "https://Stackoverflow.com/users/2146540", "pm_score": 2, "selected": false, "text": "<p>This worked for a WPF/XAML TextBox.</p>\n\n<pre><code> private bool initialEntry = true;\n private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)\n {\n if (initialEntry)\n {\n e.Handled = true;\n initialEntry = false;\n TextBox.SelectAll();\n }\n }\n private void TextBox_GotFocus(object sender, RoutedEventArgs e)\n {\n TextBox.SelectAll();\n initialEntry = true; \n }\n</code></pre>\n" }, { "answer_id": 17221130, "author": "Joel", "author_id": 2506459, "author_profile": "https://Stackoverflow.com/users/2506459", "pm_score": 0, "selected": false, "text": "<p>Set the selction when you leave the control. It will be there when you get back. Tab around the form and when you return to the control, all the text will be selected. </p>\n\n<p>If you go in by mouse, then the caret will rightly be placed at the point where you clicked.</p>\n\n<pre><code>private void maskedTextBox1_Leave(object sender, CancelEventArgs e)\n {\n maskedTextBox1.SelectAll();\n }\n</code></pre>\n" }, { "answer_id": 22812804, "author": "MDB", "author_id": 3489564, "author_profile": "https://Stackoverflow.com/users/3489564", "pm_score": -1, "selected": false, "text": "<p>The answer can be actually quite more simple than ALL of the above, for example (in WPF):</p>\n\n<pre><code>public void YourTextBox_MouseEnter(object sender, MouseEventArgs e)\n {\n YourTextBox.Focus();\n YourTextBox.SelectAll();\n }\n</code></pre>\n\n<p>of course I can't know how you want to use this code, but the main part to look at here is: First call .Focus() and then call .SelectAll();</p>\n" }, { "answer_id": 25998482, "author": "Mauro Sampietro", "author_id": 711061, "author_profile": "https://Stackoverflow.com/users/711061", "pm_score": 0, "selected": false, "text": "<p>Very simple solution:</p>\n\n<pre><code> private bool _focusing = false;\n\n protected override void OnEnter( EventArgs e )\n {\n _focusing = true;\n base.OnEnter( e );\n }\n\n protected override void OnMouseUp( MouseEventArgs mevent )\n {\n base.OnMouseUp( mevent );\n\n if( _focusing )\n {\n this.SelectAll();\n _focusing = false;\n }\n }\n</code></pre>\n\n<p><strong>EDIT:</strong> Original OP was in particular concerned about the mouse-down / text-selection / mouse-up sequence, in which case the above simple solution would end up with text being partially selected.</p>\n\n<p>This should solve* the problem (in practice I intercept WM_SETCURSOR):</p>\n\n<pre><code> protected override void WndProc( ref Message m )\n {\n if( m.Msg == 32 ) //WM_SETCURSOR=0x20\n {\n this.SelectAll(); // or your custom logic here \n }\n\n base.WndProc( ref m );\n }\n</code></pre>\n\n<p>*Actually the following sequence ends up with partial text selection but then if you move the mouse over the textbox all text will be selected again: </p>\n\n<p>mouse-down / text-selection / mouse-move-out-textbox / mouse-up </p>\n" }, { "answer_id": 27229467, "author": "Pieter Heemeryck", "author_id": 2568944, "author_profile": "https://Stackoverflow.com/users/2568944", "pm_score": 1, "selected": false, "text": "<p>I've found an even simpler solution:</p>\n\n<p>To make sure all text is selected when clicking on a textBox, make sure that the Click handler calls the Enter handler. No need for extra variables!</p>\n\n<p>Example:</p>\n\n<pre><code>private void textBox1_Click(object sender, EventArgs e){\n textBox1_Enter(sender, e);\n }\n\nprivate void textBox1_Enter(object sender, EventArgs e){\n TextBox tb = ((TextBox)sender);\n tb.SelectAll();\n }\n</code></pre>\n" }, { "answer_id": 29624996, "author": "EKanadily", "author_id": 365867, "author_profile": "https://Stackoverflow.com/users/365867", "pm_score": -1, "selected": false, "text": "<p>just use selectall() on enter and click events</p>\n\n<pre><code>private void textBox1_Enter(object sender, EventArgs e)\n {\n\n textBox1.SelectAll();\n }\n private void textBox1_Click(object sender, EventArgs e)\n {\n textBox1.SelectAll();\n }\n</code></pre>\n" }, { "answer_id": 30487179, "author": "Hawston", "author_id": 3729779, "author_profile": "https://Stackoverflow.com/users/3729779", "pm_score": 0, "selected": false, "text": "<p>I find this work best, when mouse click and not release immediately:</p>\n\n<pre><code> private bool SearchBoxInFocusAlready = false;\n private void SearchBox_LostFocus(object sender, RoutedEventArgs e)\n {\n SearchBoxInFocusAlready = false;\n }\n\n private void SearchBox_PreviewMouseUp(object sender, MouseButtonEventArgs e)\n {\n if (e.ButtonState == MouseButtonState.Released &amp;&amp; e.ChangedButton == MouseButton.Left &amp;&amp;\n SearchBox.SelectionLength == 0 &amp;&amp; SearchBoxInFocusAlready == false)\n {\n SearchBox.SelectAll();\n }\n\n SearchBoxInFocusAlready = true;\n }\n</code></pre>\n" }, { "answer_id": 31502179, "author": "BlueWizard", "author_id": 4773888, "author_profile": "https://Stackoverflow.com/users/4773888", "pm_score": 0, "selected": false, "text": "<p>My Solution is pretty primitive but works fine for my purpose</p>\n\n<pre><code>private async void TextBox_GotFocus(object sender, RoutedEventArgs e)\n{\n if (sender is TextBox)\n {\n await Task.Delay(100);\n (sender as TextBox).SelectAll();\n }\n}\n</code></pre>\n" }, { "answer_id": 34028458, "author": "Cody", "author_id": 5627196, "author_profile": "https://Stackoverflow.com/users/5627196", "pm_score": -1, "selected": false, "text": "<p>This is working for me in .NET 2005 - </p>\n\n<pre><code> ' * if the mouse button is down, do not run the select all.\n If MouseButtons = Windows.Forms.MouseButtons.Left Then\n Exit Sub\n End If\n\n ' * OTHERWISE INVOKE THE SELECT ALL AS DISCUSSED.\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
When a C# WinForms textbox receives focus, I want it to behave like your browser's address bar. To see what I mean, click in your web browser's address bar. You'll notice the following behavior: 1. Clicking in the textbox should select all the text if the textbox wasn't previously focused. 2. Mouse down and drag in the textbox should select only the text I've highlighted with the mouse. 3. If the textbox is already focused, clicking does not select all text. 4. Focusing the textbox programmatically or via keyboard tabbing should select all text. I want to do exactly this in WinForms. **FASTEST GUN ALERT: please read the following before answering!** Thanks guys. :-) > > **Calling .SelectAll() during > the .Enter or .GotFocus events won't > work** because if the user clicked the > textbox, the caret will be placed > where he clicked, thus deselecting all > text. > > > **Calling .SelectAll() during the .Click event won't work** because the user won't be able to select any text with the mouse; the .SelectAll() call will keep overwriting the user's text selection. > > > **Calling BeginInvoke((Action)textbox.SelectAll) on focus/enter event enter doesn't work** because it breaks rule #2 above, it will keep overriding the user's selection on focus. > > >
First of all, thanks for answers! 9 total answers. Thank you. Bad news: all of the answers had some quirks or didn't work quite right (or at all). I've added a comment to each of your posts. Good news: I've found a way to make it work. This solution is pretty straightforward and seems to work in all the scenarios (mousing down, selecting text, tabbing focus, etc.) ``` bool alreadyFocused; ... textBox1.GotFocus += textBox1_GotFocus; textBox1.MouseUp += textBox1_MouseUp; textBox1.Leave += textBox1_Leave; ... void textBox1_Leave(object sender, EventArgs e) { alreadyFocused = false; } void textBox1_GotFocus(object sender, EventArgs e) { // Select all text only if the mouse isn't down. // This makes tabbing to the textbox give focus. if (MouseButtons == MouseButtons.None) { this.textBox1.SelectAll(); alreadyFocused = true; } } void textBox1_MouseUp(object sender, MouseEventArgs e) { // Web browsers like Google Chrome select the text on mouse up. // They only do it if the textbox isn't already focused, // and if the user hasn't selected all text. if (!alreadyFocused && this.textBox1.SelectionLength == 0) { alreadyFocused = true; this.textBox1.SelectAll(); } } ``` As far as I can tell, this causes a textbox to behave exactly like a web browser's address bar. Hopefully this helps the next guy who tries to solve this deceptively simple problem. Thanks again, guys, for all your answers that helped lead me towards the correct path.
97,465
<p>Has anyone figured out how to use Crystal Reports with Linq to SQL?</p>
[ { "answer_id": 99193, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 1, "selected": false, "text": "<p>Altough I haven't tried it myself it seems to be possible by using a combination of DataContext.LoadOptions to make it eager to accept relations and GetCommand(IQueryable) to return a SQLCommand object that preserves relations.</p>\n\n<p>See more info on <a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3421530&amp;SiteID=1\" rel=\"nofollow noreferrer\">MSDN Forums</a>.</p>\n" }, { "answer_id": 99290, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms227595(VS.80).aspx\" rel=\"nofollow noreferrer\">msdn doc</a>'s suggest that you can bind a Crystal Report to an ICollection.</p>\n\n<p>Might I recommend a List(T) ?</p>\n" }, { "answer_id": 7691717, "author": "Mohammad Sepahvand", "author_id": 189756, "author_profile": "https://Stackoverflow.com/users/189756", "pm_score": 3, "selected": true, "text": "<p>You can convert your LINQ result set to a <code>List</code>, you need not strictly use a <code>DataSet</code> as the reports <code>SetDataSource</code>, you can supply a Crystal Reports data with an <code>IEnumerable</code>. Since <code>List</code> inherits from <code>IEnumerable</code> you can set your reports' Data Source to a List, you just have to call the <code>.ToList()</code> method on your LINQ result set. Basically:</p>\n\n<pre><code> CrystalReport1 cr1 = new CrystalReport1();\n\n var results = (from obj in context.tSamples\n where obj.ID == 112\n select new { obj.Name, obj.Model, obj.Producer }).ToList();\n\n cr1.SetDataSource(results);\n crystalReportsViewer1.ReportSource = cr1;\n</code></pre>\n" }, { "answer_id": 23882327, "author": "user3243012", "author_id": 3243012, "author_profile": "https://Stackoverflow.com/users/3243012", "pm_score": 0, "selected": false, "text": "<p>The above code wont work in web application if you have dbnull values. You have to convert the results list object to dataset or datatable. There is no built in method for it. I have gone through the same issue and after hours of exploring on the internet, I found the solution and wanna share here to help anyone stuck up with it. You have to make a class in your project:-</p>\n\n<pre><code> public class CollectionHelper\n {\n public CollectionHelper()\n {\n }\n\n // this is the method I have been using\n public DataTable ConvertTo&lt;T&gt;(IList&lt;T&gt; list)\n {\n DataTable table = CreateTable&lt;T&gt;();\n Type entityType = typeof(T);\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);\n\n foreach (T item in list)\n {\n DataRow row = table.NewRow();\n\n foreach (PropertyDescriptor prop in properties)\n {\n row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;\n }\n\n table.Rows.Add(row);\n }\n\n return table;\n }\n\n public static DataTable CreateTable&lt;T&gt;()\n {\n Type entityType = typeof(T);\n DataTable table = new DataTable(entityType.Name);\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);\n\n foreach (PropertyDescriptor prop in properties)\n {\n // HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES\n table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(\n prop.PropertyType) ?? prop.PropertyType);\n }\n\n return table;\n }\n }\n</code></pre>\n\n<p>and here setting up your crystal report </p>\n\n<pre><code>CrystalReport1 cr1 = new CrystalReport1();\n\n var results = (from obj in context.tSamples\n where obj.ID == 112\n select new { obj.Name, obj.Model, obj.Producer }).ToList();\n CollectionHelper ch = new CollectionHelper();\n DataTable dt = ch.ConvertTo(results);\n cr1.SetDataSource(dt);\n crystalReportsViewer1.ReportSource = cr1;\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11063/" ]
Has anyone figured out how to use Crystal Reports with Linq to SQL?
You can convert your LINQ result set to a `List`, you need not strictly use a `DataSet` as the reports `SetDataSource`, you can supply a Crystal Reports data with an `IEnumerable`. Since `List` inherits from `IEnumerable` you can set your reports' Data Source to a List, you just have to call the `.ToList()` method on your LINQ result set. Basically: ``` CrystalReport1 cr1 = new CrystalReport1(); var results = (from obj in context.tSamples where obj.ID == 112 select new { obj.Name, obj.Model, obj.Producer }).ToList(); cr1.SetDataSource(results); crystalReportsViewer1.ReportSource = cr1; ```
97,468
<p><a href="http://github.com/rails/ssl_requirement/tree/master/lib/ssl_requirement.rb" rel="nofollow noreferrer">Take a look at the ssl_requirement plugin.</a></p> <p>Shouldn't it check to see if you're in production mode? We're seeing a redirect to https in development mode, which seems odd. Or is that the normal behavior for the plugin? I thought it behaved differently in the past.</p>
[ { "answer_id": 98697, "author": "Nathan de Vries", "author_id": 11109, "author_profile": "https://Stackoverflow.com/users/11109", "pm_score": 4, "selected": true, "text": "<p>I guess they believe that you should probably be using HTTPS (perhaps with a self-signed certificate) in development mode. If that's not the desired behaviour, there's nothing stopping you from special casing SSL behaviour in the development environment yourself:</p>\n\n<pre><code>class YourController &lt; ApplicationController\n ssl_required :update unless Rails.env.development?\nend\n</code></pre>\n" }, { "answer_id": 1902278, "author": "Rob", "author_id": 149615, "author_profile": "https://Stackoverflow.com/users/149615", "pm_score": 0, "selected": false, "text": "<p>Ideally you should be testing that your application redirects to https during sensitive stages.</p>\n" }, { "answer_id": 2152995, "author": "tfentonz", "author_id": 254356, "author_profile": "https://Stackoverflow.com/users/254356", "pm_score": 0, "selected": false, "text": "<p>There isn't much point in requiring SSL in the development environment.</p>\n\n<p>You can stub out the plugins <strong>ssl_required?</strong> method using Rails' built in mocking facilities.</p>\n\n<p>Under your application root directory create a file test/mocks/development/application.rb</p>\n\n<pre><code>require 'controllers/application_controller'\n\nclass ApplicationController &lt; ActionController::Base\n def ssl_required?\n false\n end\nend\n</code></pre>\n\n<p>This way SSL is never required in the development environment.</p>\n" }, { "answer_id": 2482569, "author": "Anatoly", "author_id": 290338, "author_profile": "https://Stackoverflow.com/users/290338", "pm_score": 2, "selected": false, "text": "<pre><code> def ssl_required?\n return false if local_request? || RAILS_ENV == 'test' || RAILS_ENV == 'development'\n super\n end\n</code></pre>\n" }, { "answer_id": 6715756, "author": "Anatoly", "author_id": 290338, "author_profile": "https://Stackoverflow.com/users/290338", "pm_score": 0, "selected": false, "text": "<p>actually, redirect over https is a webserver responsibility. Add extra request hash verification per each request into Rails is a overhead IMHO. I wrote nginx <a href=\"https://gist.github.com/711913\" rel=\"nofollow\">config</a>, which include following rewrite:</p>\n\n<p>rewrite ^(.*) https://$host$1 permanent;</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17076/" ]
[Take a look at the ssl\_requirement plugin.](http://github.com/rails/ssl_requirement/tree/master/lib/ssl_requirement.rb) Shouldn't it check to see if you're in production mode? We're seeing a redirect to https in development mode, which seems odd. Or is that the normal behavior for the plugin? I thought it behaved differently in the past.
I guess they believe that you should probably be using HTTPS (perhaps with a self-signed certificate) in development mode. If that's not the desired behaviour, there's nothing stopping you from special casing SSL behaviour in the development environment yourself: ``` class YourController < ApplicationController ssl_required :update unless Rails.env.development? end ```
97,474
<p>I need to get the value of the 'test' attribute in the xsl:when tag, and the 'name' attribute in the xsl:call-template tag. This xpath gets me pretty close: </p> <pre><code>..../xsl:template/xsl:choose/xsl:when </code></pre> <p>But that just returns the 'when' elements, not the exact attribute values I need.</p> <p>Here is a snippet of my XML:</p> <pre><code>&lt;xsl:template match="field"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@name='First Name'"&gt; &lt;xsl:call-template name="handleColumn_1" /&gt; &lt;/xsl:when&gt; &lt;/xsl:choose&gt; </code></pre>
[ { "answer_id": 97500, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 2, "selected": false, "text": "<p>do you want <code>.../xsl:template/xsl:choose/xsl:when/@test</code></p>\n\n<p>If you want to actually get the value 'First Name' out of the test attribute, you're out of luck -- the content inside the attribute is just a string, and not a piece of xml, so you can't xpath it. If you need to get that, you must use string manipulation (Eg, substring) to get the right content</p>\n" }, { "answer_id": 97738, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": true, "text": "<p>Steve Cooper answered the first part. For the second part, you can use:</p>\n\n<pre><code>.../xsl:template/xsl:choose/xsl:when[@test=\"@name='First Name'\"]/xsl:call-template/@name\n</code></pre>\n\n<p>Which will match specifically the xsl:when in your above snippet. If you want it to match generally, then you can use:</p>\n\n<pre><code>.../xsl:template/xsl:choose/xsl:when/xsl:call-template/@name\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10876/" ]
I need to get the value of the 'test' attribute in the xsl:when tag, and the 'name' attribute in the xsl:call-template tag. This xpath gets me pretty close: ``` ..../xsl:template/xsl:choose/xsl:when ``` But that just returns the 'when' elements, not the exact attribute values I need. Here is a snippet of my XML: ``` <xsl:template match="field"> <xsl:choose> <xsl:when test="@name='First Name'"> <xsl:call-template name="handleColumn_1" /> </xsl:when> </xsl:choose> ```
Steve Cooper answered the first part. For the second part, you can use: ``` .../xsl:template/xsl:choose/xsl:when[@test="@name='First Name'"]/xsl:call-template/@name ``` Which will match specifically the xsl:when in your above snippet. If you want it to match generally, then you can use: ``` .../xsl:template/xsl:choose/xsl:when/xsl:call-template/@name ```
97,480
<p>I have a Progress database that I'm performing an ETL from. One of the tables that I'm reading from does not have a unique key on it, so I need to access the ROWID to be able to uniquely identify the row. What is the syntax for accessing the ROWID in Progress?</p> <p>I understand there are problems with using ROWID for row identification, but it's all I have right now.</p>
[ { "answer_id": 97579, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": -1, "selected": false, "text": "<p>A quick google search turns up this: \n<a href=\"http://bytes.com/forum/thread174440.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread174440.html</a></p>\n\n<p>Read the message towards the bottom by [email protected] (you either want oid or ctid depending on what guarantees you want re persistence and uniqueness)</p>\n" }, { "answer_id": 100430, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 4, "selected": true, "text": "<p>A quick caveat for my answer - it's nearly 10 years since I worked with <a href=\"http://www.progress.com/\" rel=\"noreferrer\">Progress</a> so my knowledge is probably more than a little out of date.</p>\n\n<p>Checking the <a href=\"http://www.psdn.com/library/servlet/KbServlet/download/1078-102-885/langref.pdf\" rel=\"noreferrer\">Progress Language Reference</a> [PDF] seems to show the two functions I remember are still there: <code>ROWID</code> and <code>RECID</code>. The <code>ROWID</code> function is newer and is preferred.</p>\n\n<p>In Progress 4GL you'd use it something like this:</p>\n\n<pre><code>FIND customer WHERE cust-num = 123.\ncrowid = ROWID(customer).\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>FIND customer WHERE ROWID(customer) = crowid EXCLUSIVE-LOCK.\n</code></pre>\n\n<p>Checking the <a href=\"http://www.psdn.com/library/servlet/KbServlet/download/1223-102-1092/s92.pdf\" rel=\"noreferrer\">Progress SQL Reference</a> [PDF] shows <code>ROWID</code> is also available in SQL as a Progress extension. You'd use it like so:</p>\n\n<pre><code>SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123\n</code></pre>\n\n<p><strong>Edit:</strong> Edited following Stefan's feedback.</p>\n" }, { "answer_id": 102910, "author": "Stefan Moser", "author_id": 8739, "author_profile": "https://Stackoverflow.com/users/8739", "pm_score": 2, "selected": false, "text": "<p>Just to add a little to Dave Webb's answers. I had tried ROWID in the select statement but was given a syntax error. ROWID only works if you specify the rest of the columns to select, you cannot use *.</p>\n\n<p>This does NOT work:</p>\n\n<pre><code>SELECT ROWID, * FROM customer WHERE cust-num = 123\n</code></pre>\n\n<p>This does work:</p>\n\n<pre><code>SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123\n</code></pre>\n" }, { "answer_id": 1026862, "author": "Tom Bascom", "author_id": 123238, "author_profile": "https://Stackoverflow.com/users/123238", "pm_score": 3, "selected": false, "text": "<p>Depending on your situation and the behavior of the application this may or may not matter but you should be aware that ROWIDs &amp; RECIDs are reused and that they may change.</p>\n\n<p>1) If a record is deleted it's ROWID will eventually be reused.</p>\n\n<p>2) If the table is reorganized via a dump &amp; load or a tablemove to a new storage area then the ROWIDs will change.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8739/" ]
I have a Progress database that I'm performing an ETL from. One of the tables that I'm reading from does not have a unique key on it, so I need to access the ROWID to be able to uniquely identify the row. What is the syntax for accessing the ROWID in Progress? I understand there are problems with using ROWID for row identification, but it's all I have right now.
A quick caveat for my answer - it's nearly 10 years since I worked with [Progress](http://www.progress.com/) so my knowledge is probably more than a little out of date. Checking the [Progress Language Reference](http://www.psdn.com/library/servlet/KbServlet/download/1078-102-885/langref.pdf) [PDF] seems to show the two functions I remember are still there: `ROWID` and `RECID`. The `ROWID` function is newer and is preferred. In Progress 4GL you'd use it something like this: ``` FIND customer WHERE cust-num = 123. crowid = ROWID(customer). ``` or: ``` FIND customer WHERE ROWID(customer) = crowid EXCLUSIVE-LOCK. ``` Checking the [Progress SQL Reference](http://www.psdn.com/library/servlet/KbServlet/download/1223-102-1092/s92.pdf) [PDF] shows `ROWID` is also available in SQL as a Progress extension. You'd use it like so: ``` SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123 ``` **Edit:** Edited following Stefan's feedback.
97,505
<p>Working on a somewhat complex page for configuring customers at work. The setup is that there's a main page, which contains various "panels" for various groups of settings. </p> <p>In one case, there's an email address field on the main table and an "export" configuration that controls how emails are sent out. I created a main panel that selects the company, and binds to a FormView. The FormView contains a Web User Control that handles the display/configuration of the export details.</p> <p>The Web User Control Contains a property to define which Config it should be handling, and it gets the value from the FormView using Bind().</p> <p>Basically the control is used like this:</p> <pre><code>&lt;syn:ExportInfo ID="eiConfigDetails" ExportInfoID='&lt;%# Bind("ExportInfoID" ) %&gt;' runat="server" /&gt; </code></pre> <p>The property being bound is declared like this in CodeBehind:</p> <pre><code>public int ExportInfoID { get { return Convert.ToInt32(hfID.Value); } set { try { hfID.Value = value.ToString(); } catch(Exception) { hfID.Value="-1"; } } } </code></pre> <p>Whenever the <code>ExportInfoID</code> is null I get a null reference exception, but the kicker is that it happens BEFORE it actually tries to set the property (or it would be caught in this version.)</p> <p>Anyone know what's going on or, more importantly, how to fix it...?</p>
[ { "answer_id": 97579, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": -1, "selected": false, "text": "<p>A quick google search turns up this: \n<a href=\"http://bytes.com/forum/thread174440.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread174440.html</a></p>\n\n<p>Read the message towards the bottom by [email protected] (you either want oid or ctid depending on what guarantees you want re persistence and uniqueness)</p>\n" }, { "answer_id": 100430, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 4, "selected": true, "text": "<p>A quick caveat for my answer - it's nearly 10 years since I worked with <a href=\"http://www.progress.com/\" rel=\"noreferrer\">Progress</a> so my knowledge is probably more than a little out of date.</p>\n\n<p>Checking the <a href=\"http://www.psdn.com/library/servlet/KbServlet/download/1078-102-885/langref.pdf\" rel=\"noreferrer\">Progress Language Reference</a> [PDF] seems to show the two functions I remember are still there: <code>ROWID</code> and <code>RECID</code>. The <code>ROWID</code> function is newer and is preferred.</p>\n\n<p>In Progress 4GL you'd use it something like this:</p>\n\n<pre><code>FIND customer WHERE cust-num = 123.\ncrowid = ROWID(customer).\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>FIND customer WHERE ROWID(customer) = crowid EXCLUSIVE-LOCK.\n</code></pre>\n\n<p>Checking the <a href=\"http://www.psdn.com/library/servlet/KbServlet/download/1223-102-1092/s92.pdf\" rel=\"noreferrer\">Progress SQL Reference</a> [PDF] shows <code>ROWID</code> is also available in SQL as a Progress extension. You'd use it like so:</p>\n\n<pre><code>SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123\n</code></pre>\n\n<p><strong>Edit:</strong> Edited following Stefan's feedback.</p>\n" }, { "answer_id": 102910, "author": "Stefan Moser", "author_id": 8739, "author_profile": "https://Stackoverflow.com/users/8739", "pm_score": 2, "selected": false, "text": "<p>Just to add a little to Dave Webb's answers. I had tried ROWID in the select statement but was given a syntax error. ROWID only works if you specify the rest of the columns to select, you cannot use *.</p>\n\n<p>This does NOT work:</p>\n\n<pre><code>SELECT ROWID, * FROM customer WHERE cust-num = 123\n</code></pre>\n\n<p>This does work:</p>\n\n<pre><code>SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123\n</code></pre>\n" }, { "answer_id": 1026862, "author": "Tom Bascom", "author_id": 123238, "author_profile": "https://Stackoverflow.com/users/123238", "pm_score": 3, "selected": false, "text": "<p>Depending on your situation and the behavior of the application this may or may not matter but you should be aware that ROWIDs &amp; RECIDs are reused and that they may change.</p>\n\n<p>1) If a record is deleted it's ROWID will eventually be reused.</p>\n\n<p>2) If the table is reorganized via a dump &amp; load or a tablemove to a new storage area then the ROWIDs will change.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ]
Working on a somewhat complex page for configuring customers at work. The setup is that there's a main page, which contains various "panels" for various groups of settings. In one case, there's an email address field on the main table and an "export" configuration that controls how emails are sent out. I created a main panel that selects the company, and binds to a FormView. The FormView contains a Web User Control that handles the display/configuration of the export details. The Web User Control Contains a property to define which Config it should be handling, and it gets the value from the FormView using Bind(). Basically the control is used like this: ``` <syn:ExportInfo ID="eiConfigDetails" ExportInfoID='<%# Bind("ExportInfoID" ) %>' runat="server" /> ``` The property being bound is declared like this in CodeBehind: ``` public int ExportInfoID { get { return Convert.ToInt32(hfID.Value); } set { try { hfID.Value = value.ToString(); } catch(Exception) { hfID.Value="-1"; } } } ``` Whenever the `ExportInfoID` is null I get a null reference exception, but the kicker is that it happens BEFORE it actually tries to set the property (or it would be caught in this version.) Anyone know what's going on or, more importantly, how to fix it...?
A quick caveat for my answer - it's nearly 10 years since I worked with [Progress](http://www.progress.com/) so my knowledge is probably more than a little out of date. Checking the [Progress Language Reference](http://www.psdn.com/library/servlet/KbServlet/download/1078-102-885/langref.pdf) [PDF] seems to show the two functions I remember are still there: `ROWID` and `RECID`. The `ROWID` function is newer and is preferred. In Progress 4GL you'd use it something like this: ``` FIND customer WHERE cust-num = 123. crowid = ROWID(customer). ``` or: ``` FIND customer WHERE ROWID(customer) = crowid EXCLUSIVE-LOCK. ``` Checking the [Progress SQL Reference](http://www.psdn.com/library/servlet/KbServlet/download/1223-102-1092/s92.pdf) [PDF] shows `ROWID` is also available in SQL as a Progress extension. You'd use it like so: ``` SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123 ``` **Edit:** Edited following Stefan's feedback.
97,506
<p><strong>This isn't a holy war, this isn't a question of "which is better".</strong></p> <p>What are the pros of using the following format for single statement if blocks.</p> <pre><code>if (x) print "x is true"; if(x) print "x is true"; </code></pre> <p>As opposed to</p> <pre><code>if (x) { print "x is true"; } if(x) { print "x is true"; } </code></pre> <p><strong>If you format your single statement ifs without brackets</strong> or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you.</p> <p><strong>Update</strong>: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros.</p> <ol> <li>Compactness</li> <li>More readable to some</li> <li>Brackets invoke scope, which has a theoretical overhead in some cases</li> </ol>
[ { "answer_id": 97516, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 6, "selected": false, "text": "<p><strong>I strongly dislike any style that places the if's test and body on the same line.</strong></p>\n\n<p>This is because sharing the line makes it impossible to set a breakpoint on the if's body in many debuggers because breakpoints are typically line number based.</p>\n" }, { "answer_id": 97525, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 2, "selected": false, "text": "<p>Whitespace is your friend ....</p>\n\n<p>but, then again, I like:</p>\n\n<pre><code>if (foo)\n{\n Console.WriteLine(\"Foobar\");\n}\n</code></pre>\n" }, { "answer_id": 97526, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 7, "selected": true, "text": "<p>I find this:</p>\n\n<pre><code>if( true ) {\n DoSomething();\n} else {\n DoSomethingElse();\n}\n</code></pre>\n\n<p>better than this:</p>\n\n<pre><code>if( true )\n DoSomething();\nelse\n DoSomethingElse();\n</code></pre>\n\n<p>This way, if I (or someone else) comes back to this code later to add more code to one of the branches, I won't have to worry about forgetting to surround the code in braces. Our eyes will visually see the indenting as clues to what we're trying to do, but most languages won't.</p>\n" }, { "answer_id": 97529, "author": "user18301", "author_id": 18301, "author_profile": "https://Stackoverflow.com/users/18301", "pm_score": 4, "selected": false, "text": "<p>I always use </p>\n\n<pre><code>if(x) \n{\n print \"x is true\"; \n}\n</code></pre>\n\n<p>leaving out the braces can result in someone maintaining the code mistakenly thinking they are adding to the if clause if they add a line after the current line.</p>\n" }, { "answer_id": 97531, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": false, "text": "<pre><code>if\n{\n// code\n}\nelse \n{\n// else code\n}\n</code></pre>\n\n<p>because i like when blocks of code line up (including their braces).</p>\n" }, { "answer_id": 97538, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "<p>For me, braces make it easier to see the flow of the program. It also makes it easier to add a statement to the body of the if statement. When there aren't braces, you have to add braces to add another statement.</p>\n\n<p>I guess the pros of not using braces would be that it looks cleaner and you don't waste a line with a closing brace.</p>\n" }, { "answer_id": 97549, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 0, "selected": false, "text": "<p>Lines spacing and indentation can do alot for readability.</p>\n\n<p>As far as readability I prefer the following:</p>\n\n<pre><code>// Do this if you only have one line of code\n// executing within the if statement\nif (x)\n print \"x is true\";\n\n// Do this when you have multiple lines of code\n// getting executed within the if statement \nif (x)\n{\n print \"x is true\";\n}\n</code></pre>\n" }, { "answer_id": 97552, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<p>If I code:</p>\n\n<pre><code>if(x) \n print \"x is true\";\n</code></pre>\n\n<p>and 6 months later need to add a new line, the presence of curly braces makes it much less likely that I'll type</p>\n\n<pre><code>if(x) \n print \"x is true\";\n print \"x is still true\";\n</code></pre>\n\n<p>which would result in a logical error, versus: </p>\n\n<pre><code>if(x) { \n print \"x is true\";\n print \"x is still true\";\n}\n</code></pre>\n\n<p>So curly braces make such logical errors easier to read and avoid, I find.</p>\n" }, { "answer_id": 97558, "author": "Alex King", "author_id": 15813, "author_profile": "https://Stackoverflow.com/users/15813", "pm_score": 1, "selected": false, "text": "<p>I prefer the bracketed style, mainly because it gives the eyes a clear start and stop point. It makes it easier to see what is actually contained in the statement, and that it actually is an if statement. A small thing, perhaps, but that's why I use it. </p>\n" }, { "answer_id": 97561, "author": "ChrisCa", "author_id": 17194, "author_profile": "https://Stackoverflow.com/users/17194", "pm_score": 1, "selected": false, "text": "<p>so long as it is consistent amongst the team you work in then it doesnt matter too much</p>\n\n<p>that everyone does the same is the main thing</p>\n" }, { "answer_id": 97562, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 2, "selected": false, "text": "<p>I use</p>\n\n<pre><code>if (cond) {\n ...\n} else {\n ...\n}\n</code></pre>\n\n<ul>\n<li>Everything should always have braces. Even if now I only have one line in the if block, I made add more later.</li>\n<li>I don't put the braces on their own lines because it's pointless waste of space.</li>\n<li>I rarely put the block on the same line as the conditional for readability.</li>\n</ul>\n" }, { "answer_id": 97564, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<pre><code>if (x)\n{\n print \"x is true\";\n}\n</code></pre>\n\n<p>Opening and closing brace in same column makes it easy to find mismatched braces, and visually isolates the block. Opening brace in same column as \"if\" makes it easy to see that the block is part of a conditional. The extra white space around the block created by the rows containing just braces makes it easy to pick it out the logical structure when skimreading code. Always explicitly using braces helps avoid problems when people edit the code later and misread which statements are part of the conditional and which are not - indentation may not match reality, but being enclosed in braces always will.</p>\n" }, { "answer_id": 97566, "author": "Josh Millard", "author_id": 13600, "author_profile": "https://Stackoverflow.com/users/13600", "pm_score": 1, "selected": false, "text": "<p>Bracketing your one-liner if statements has the considerable sane-making advantage of protecting you from headaches if, at some later point, you (or other coders maintaining or altering your code) need to add statements to some part of that conditional block.</p>\n" }, { "answer_id": 97583, "author": "Matthew Jaskula", "author_id": 4356, "author_profile": "https://Stackoverflow.com/users/4356", "pm_score": 3, "selected": false, "text": "<p>Single statement if blocks lacking braces:</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>fewer characters</li>\n<li>cleaner look</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>uniformity: not all if blocks look the same</li>\n<li>potential for bugs when adding statements to the block: a user may forget to add the braces and the new statement would no be covered by the if.</li>\n</ul>\n\n<blockquote>\n <p>As in:</p>\n</blockquote>\n\n<pre><code>if(x) \n print \"x is true\";\n print \"something else\";\n</code></pre>\n" }, { "answer_id": 97596, "author": "user17000", "author_id": 17000, "author_profile": "https://Stackoverflow.com/users/17000", "pm_score": 1, "selected": false, "text": "<p>No matter what, this is the way I go! It looks the best.</p>\n\n<pre><code>If(x)\n{\n print \"Hello World !!\"\n}\nElse\n{\n print \"Good bye!!\"\n}\n</code></pre>\n" }, { "answer_id": 97631, "author": "Tom Kidd", "author_id": 2577, "author_profile": "https://Stackoverflow.com/users/2577", "pm_score": 1, "selected": false, "text": "<p>If you're curious what the names for the various code formatting styles are, Wikipedia has an article on <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow noreferrer\">Indent Styles</a>.</p>\n" }, { "answer_id": 97680, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/4/joel-spolsky\">Joel Spolsky</a> wrote a good article: <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Making Wrong Code Look Wrong</a></p>\n\n<p>He specifically addresses this issue&hellip;</p>\n\n<blockquote>\n<pre><code>if (i != 0) \n foo(i);\n</code></pre>\n \n <p>In this case the code is 100% correct;\n it conforms to most coding conventions\n and there’s nothing wrong with it, but\n the fact that the single-statement\n body of the ifstatement is not\n enclosed in braces may be bugging you,\n because you might be thinking in the\n back of your head, gosh, somebody\n might insert another line of code\n there</p>\n\n<pre><code>if (i != 0)\n bar(i);\n foo(i);\n</code></pre>\n \n <p>&hellip; and forget to add the braces, and\n thus accidentally make\n foo(i)unconditional! So when you see\n blocks of code that aren’t in braces,\n you might sense just a tiny, wee,\n soupçon of uncleanliness which makes\n you uneasy.</p>\n</blockquote>\n\n<p>He suggests that you&hellip;</p>\n\n<blockquote>\n <p>&hellip; deliberately architect your code\n in such a way that your nose for\n uncleanliness makes your code more\n likely to be correct.</p>\n</blockquote>\n" }, { "answer_id": 97791, "author": "mike511", "author_id": 9593, "author_profile": "https://Stackoverflow.com/users/9593", "pm_score": 1, "selected": false, "text": "<p>If you do something like this:</p>\n\n<pre><code>if(x)\n{\n somecode;\n}\nelse\n{\n morecode;\n}\n</code></pre>\n\n<p>This works out better for source control and preprocessor directives\non code that lives a long time. It's easier to add a #if or so without\ninadvertently breaking the statement or having to add extra lines.</p>\n\n<p>it's a little strange to get used to, but works out quite well after a\nwhile.</p>\n" }, { "answer_id": 97826, "author": "Learning", "author_id": 18275, "author_profile": "https://Stackoverflow.com/users/18275", "pm_score": 0, "selected": false, "text": "<p>I wish the IDE would enforce this behaviour. As you correctly pointed out there is no \"right\" behaviour. Consistency is more important ... it could be either style. </p>\n" }, { "answer_id": 97862, "author": "Matt H", "author_id": 18049, "author_profile": "https://Stackoverflow.com/users/18049", "pm_score": 4, "selected": false, "text": "<p>I use <br></p>\n\n<pre>\nif (x)\n{\n DoSomething();\n}\n</pre>\n\n<p>for multiple lines, but I prefer bracketless one liners:<br></p>\n\n<pre>\nif (x)\n DoSomething();\nelse\n DoSomethingElse();\n</pre>\n\n<p>I find the extraneous brackets visually offensive, and I've never made\none of the above-mentioned mistakes not adding brackets when adding another statement.</p>\n" }, { "answer_id": 97917, "author": "Jeff", "author_id": 16639, "author_profile": "https://Stackoverflow.com/users/16639", "pm_score": 2, "selected": false, "text": "<p>Seriously, when's the last time you had a bug in any code anywhere that was cause someone did:</p>\n\n<pre><code>if (a)\n foo();\n bar();\n</code></pre>\n\n<p>Yeah, never...* The only real 'pro' here is to just match the style of the surrounding code and leave the aesthetic battles to the kids that just got outta college.</p>\n\n<p>*(caveat being when foo(); bar(); was a macro expansion, but that's a problem w/ macros, not curly braces w/ ifs.)</p>\n" }, { "answer_id": 97918, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 3, "selected": false, "text": "<p>I tend only to single line when I'm testing for break conditions at the beginning of a function, because I like to keep this code as simple and uncluttered as possible</p>\n\n<pre><code>public void MyFunction(object param)\n{\n if (param == null) return;\n\n ...\n}\n</code></pre>\n\n<p>Also, if I find I do want to avoid braces and inline an if clause code, I may single line them, just so it is obvious to anyone adding new lines to the if that brackets do need to be added</p>\n" }, { "answer_id": 97919, "author": "Jason Hanford-Smith", "author_id": 18345, "author_profile": "https://Stackoverflow.com/users/18345", "pm_score": 3, "selected": false, "text": "<p>Like Matt (3 above), I prefer:</p>\n\n<pre><code>if (x)\n{\n ...statement1\n ...statement2\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>if (x)\n ...statement\nelse\n ...statement\n</code></pre>\n\n<p>I think its pretty strange to think that someone may come along later and NOT realise they have to add the braces to form a multi-line if block. If that's beyond their capabilities, I wonder what other things are!</p>\n" }, { "answer_id": 97921, "author": "Doron Yaacoby", "author_id": 3389, "author_profile": "https://Stackoverflow.com/users/3389", "pm_score": 2, "selected": false, "text": "<p>I dislike using braces when they're not required. I feel like it bloats the number of lines in a method and makes it unreadable. So I almost always go for the following:</p>\n\n<pre><code>if (x)\n print \"x is true\"\nfor (int i=0; i&lt;10; i++)\n print \"y is true\"\n</code></pre>\n\n<p>And so forth. If someone needs to add another statement then he can just add the braces. Even if you don't have R# or something similar it is a very small deal.</p>\n\n<p>Still, there are some cases that I would use braces even if there is only one line in the statement, and that is if the line is especially long, or if I need comments inside the that 'if'. Basically, I just use whatever seems nicer to my eyes to look at.</p>\n" }, { "answer_id": 97970, "author": "Arthur Vanderbilt", "author_id": 18354, "author_profile": "https://Stackoverflow.com/users/18354", "pm_score": 1, "selected": false, "text": "<p>If it's one line of if (and optionally one line of else) I prefer to not use the brackets. It's more readable and concise. I say that I prefer it because it is purely a matter of preference. Though I think that trying to enforce a standard that you must always use the braces is kind of silly.</p>\n\n<p>If you have to worry about someone adding another line to the body of the if statement and not adding the (only then required) braces, I think you have bigger problems than sub-byzantine coding standards.</p>\n" }, { "answer_id": 98086, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 2, "selected": false, "text": "<pre><code>if (x) {\n print \"x is true\"; \n}\nelse {\n do something else;\n}\n</code></pre>\n\n<p>I always type braces. It's just a good habit. Compared to thinking, typing is not \"work\".</p>\n\n<p>Note the space before the conditional. That helps it look not like a method call.</p>\n" }, { "answer_id": 98569, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "<p>Always using braces is a good idea but the standard answer that's always given \"what if somebody adds a line of code and forgets to add the braces?\" is a rather weak reason.</p>\n\n<p>There is a subtle bug which can be introduced by not having the braces from the start. It's happened to me a few times and I've seen it happen to other programmers.</p>\n\n<p>It starts out, innocently enough, with a simple if statement.</p>\n\n<pre><code>if (condition)\n do_something();\nelse\n do_something_else();\n</code></pre>\n\n<p>Which is all well and good.</p>\n\n<p>Then someone comes along and adds another condition to the if. They can't add it using &amp;&amp; to the if statement itself because the logic would be incorrect, so they add another if. We now have:</p>\n\n<pre><code>if (condition)\n if (condition2)\n do_something();\nelse\n do_something_else();\n</code></pre>\n\n<p>Do you see the problem? It may look right but the compiler sees it differently. It sees it like this:</p>\n\n<pre><code>if (condition)\n if (condition2)\n do_something();\n else\n do_something_else();\n</code></pre>\n\n<p>Which means something completely different. The compiler doesn't care about formatting. The else goes with the nearest if. Humans, on the other hand, rely on formatting and can easily miss the problem.</p>\n" }, { "answer_id": 98646, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 0, "selected": false, "text": "<p>I feel like outvoted so far, but I'll vouch for one of:</p>\n\n<pre><code>if (expr) {\n funcA();\n}\nelse {\n funcB();\n}\n</code></pre>\n\n<p>Or, shorthand in limited cases for readability:</p>\n\n<pre><code>if (expr) funcA();\nelse funcB();\n</code></pre>\n\n<p>To me, the shorthand format is nice when you want it to read like English grammar. If the code doesn't look readable enough, I'll break out the lines:</p>\n\n<pre><code>if (expr)\n funcA();\nelse\n funcB();\n</code></pre>\n\n<p>With careful consideration I don't put nested conditionals within the <code>if</code>/<code>else</code> blocks to avoid coder/compiler ambiguity. If it's any more complex than this, I use the braces on both <code>if</code> and <code>else</code> blocks.</p>\n" }, { "answer_id": 99615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>/* I type one liners with brackets like this */\nif(0){return(0);}\n/* If else blocks like this */\nif(0){\n return(0);\n}else{\n return(-1);\n}\n</code></pre>\n\n<p>I never use superfluous whitespace beyond tabs, but always including the brackets saves heaps of time.</p>\n" }, { "answer_id": 99898, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 2, "selected": false, "text": "<p>About the only time no-bracing seems to be accepted is when parameter checking variables at the start of a method:</p>\n\n<pre><code>public int IndexOf(string haystack, string needle)\n{\n // check parameters.\n if (haystack == null)\n throw new ArgumentNullException(\"haystack\");\n if (string.IsNullOrEmpty(needle))\n return -1;\n\n // rest of method here ...\n</code></pre>\n\n<p>The only benefit is compactness. The programmer doesn't have to wade throught un-necessary {}'s when it's quite obvious that:</p>\n\n<ul>\n<li>the method exits on any true branch</li>\n<li>it's fairly obvious these are all 1-liners</li>\n</ul>\n\n<p>That said, I would always {} for program logic for the reasons stated by others. When you drop the braces it's too easy to mentally brace when it's not there and introduce subtle code defects. </p>\n" }, { "answer_id": 99968, "author": "Chris de Vries", "author_id": 3836, "author_profile": "https://Stackoverflow.com/users/3836", "pm_score": 0, "selected": false, "text": "<p>Any formatting of this type is fine. People will argue with you black and blue over this because it is something easy to understand. People like to talk about things they understand instead of dealing with bigger problems such as good design and solving hard problems with new algorithms. I tend to prefer no brackets for simple one-liners. However, I am also happy to read it with brackets. If there is a particular style guide for a given project I prefer to follow that. I believe in consistency over some subjective ideal of correctness.</p>\n\n<p>My personal choice for no brackets for one-liners is due to typing less characters, shorter code and succinctness.</p>\n" }, { "answer_id": 103168, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "<p>Of the options provided, I'd go with</p>\n\n<pre><code>if (x) {\n print \"x is true\"; \n}\n</code></pre>\n\n<p>simply by virtue of the braces being habit to type.</p>\n\n<p>Realistically, though, as a mostly-Perl programmer, I'm more likely to use</p>\n\n<pre><code>print \"x is true\" if x;\n</code></pre>\n\n<p>(Which always trips me up when I'm working in a language which doesn't support postfix conditionals.)</p>\n" }, { "answer_id": 109750, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 0, "selected": false, "text": "<p>I prefer single line statements with out brackets, I know that there is the danger that I can forget to add them when I insert a new line of code, but I cannot remember the last time this happened. My editor (vim) prevents me to write things like this:</p>\n\n<pre><code>\nif (x)\n x = x + 1;\n printf(\"%d\\n\", x);\n</code></pre>\n\n<p>because it will indent it differently. The only thing I had problems with, are bad written macros:</p>\n\n<pre><code>\n#define FREE(ptr) {free(ptr); ptr = NULL;}\n\nif (x)\n FREE(x);\nelse\n ...\n</code></pre>\n\n<p>This doesn't work of course, but I think it is better to fix the macro, to avoid those possible bugs or problems instead of changing the formating style.</p>\n\n<p>So there are possible problems with that way of formating, but they are imho not fatal. It ends up to be a matter of taste.</p>\n" }, { "answer_id": 118600, "author": "David Medinets", "author_id": 219658, "author_profile": "https://Stackoverflow.com/users/219658", "pm_score": 0, "selected": false, "text": "<p>I haven't seen anyone mention the most useful reason to place the bracket on the same line as the if -- bracket matching in emacs. When you place the cursor on the ending bracket, emacs shows the line with the matching start bracket. Placing the start bracket on its own line, negates the feature.</p>\n" }, { "answer_id": 118679, "author": "Dan Adams", "author_id": 1628, "author_profile": "https://Stackoverflow.com/users/1628", "pm_score": 0, "selected": false, "text": "<p>I prefer the following...i think it looks cleaner.</p>\n\n<pre><code>if(x)\n{\n code;\n}\nelse\n{\n other code;\n}\n</code></pre>\n" }, { "answer_id": 154775, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 1, "selected": false, "text": "<p>I dislike closing braces on the same line with the follow keyword:</p>\n\n<pre>\nif (x) {\n print \"x is true\"; \n} else {\n do something else;\n}\n</pre>\n\n<p>This makes it harder to remove/comment-out just the else clause. By putting the follow keyword on the next line, I can take advantage of, for example, editors that let me select a range of lines, and comment/uncomment them all at once.</p>\n\n<pre>\nif (x) {\n print \"x is true\"; \n}\n//else {\n// do something else;\n//}\n</pre>\n" }, { "answer_id": 154813, "author": "Lucas Gabriel Sánchez", "author_id": 20601, "author_profile": "https://Stackoverflow.com/users/20601", "pm_score": 1, "selected": false, "text": "<p>I always prefer this:</p>\n\n<pre><code>if (x) doSomething();\n\nif (x) {\n doSomthing();\n doOtherthing();\n}\n</code></pre>\n\n<p>But always depend on the language and the actions you're doing. Sometimes i like to put braces and sometimes not. Depend on the code, but i coding like a have to write once, re-write ten times, and read one hundred times; so, just do it like you want to and like you want to read and understand more quickly</p>\n" }, { "answer_id": 1107746, "author": "TSomKes", "author_id": 18347, "author_profile": "https://Stackoverflow.com/users/18347", "pm_score": 0, "selected": false, "text": "<p>I guess I'm more of an outlier than I thought; I haven't noticed this one yet.</p>\n\n<p>I'm a fan of </p>\n\n<pre><code>if (x)\n{ foo(); }\n</code></pre>\n\n<p>It feels compact &amp; readable (I hate sprawling braces), but it makes the scope of the condition explicit.</p>\n\n<p>It's also more breakpoint-friendly than single-line if's. It also feels more at home in my braces-on-newline world:</p>\n\n<pre><code>if (x)\n{ foo(); }\nelse\n{\n bar();\n baz();\n}\n</code></pre>\n\n<p><strong>Edit</strong>: it appears I misread the original question, so this answer off-topic. I'm still curious about any response, though.</p>\n" }, { "answer_id": 1107839, "author": "Newtopian", "author_id": 25812, "author_profile": "https://Stackoverflow.com/users/25812", "pm_score": 0, "selected": false, "text": "<p>One liners are just that... one liners and should remain like this :</p>\n\n<pre><code>if (param == null || parameterDoesNotValidateForMethod) throw new InvalidArgumentExeption(\"Parameter null or invalid\");\n</code></pre>\n\n<p>I like this style for argument checking for example,it is compact and usually reads easily. I used to put braces with indented code all the time but found that in many trivial cases it just wasted spaces on the monitor. Dropping the braces for some cases allowed me to get into the meat of methods faster and made the overall presentation easier on the eyes. If however it gets more involved then I treat it like everything else and I go all out with braces like so :</p>\n\n<pre><code>if (something)\n{\n for(blablabla)\n {\n }\n}else if\n{\n //one liner or bunch of other code all get the braces\n}else\n{\n //... well you get the point\n}\n</code></pre>\n\n<p>This being said... I despise braces on the same line like so :</p>\n\n<pre><code>if(someCondition) { doSimpleStuff; }\n</code></pre>\n\n<p>of worst</p>\n\n<pre><code>if(somethingElse){\n //then do something\n}\n</code></pre>\n\n<p>It is more compact but I find it harder to keep track of the braces. </p>\n\n<p>Overall it's more a question of personal taste so long as one does not adopt some really strange way to indent and brace...</p>\n\n<pre><code> if(someStuff)\n {\n //do something\n }\n</code></pre>\n" }, { "answer_id": 28863415, "author": "RicardoVallejo", "author_id": 3429457, "author_profile": "https://Stackoverflow.com/users/3429457", "pm_score": 2, "selected": false, "text": "<p>Other way would be to write:</p>\n\n<pre><code>(a==b) ? printf(\"yup true\") : printf(\"nop false\");\n</code></pre>\n\n<p>This will be practical if you want to store a value comparing a simple condition, like so:</p>\n\n<pre><code>int x = (a==b) ? printf(\"yup true\") : printf(\"nop false\");\n</code></pre>\n" }, { "answer_id": 37676645, "author": "user160917", "author_id": 160917, "author_profile": "https://Stackoverflow.com/users/160917", "pm_score": 2, "selected": false, "text": "<p>H8ers be damned I'm not really one for dogmatic rules. In certain situations, I'll actually favor compactness if it doesn't run over a certain width, for example:</p>\n\n<pre><code>if(x &gt; y) { xIsGreaterThanY(); }\nelse if(y &gt; x) { yIsGreaterThanX; }\nelse { xEqualsY(); }\n</code></pre>\n\n<p>This is far more readable to me than:</p>\n\n<pre><code>if( x &gt; y ){\n xIsGreaterThanY(); \n}else if( x &lt; y){\n yIsGreaterThanX();\n}else{\n xEqualsY();\n}\n</code></pre>\n\n<p>This has the added benefit of encouraging people to abstract logic into methods (as i've done) rather than keep lumping more logic into nested if-else blocks. It also takes up three lines rather than seven, which might make it possible to not have to scroll to see multiple methods, or other code. </p>\n" }, { "answer_id": 45828183, "author": "Scott - Слава Україні", "author_id": 1672723, "author_profile": "https://Stackoverflow.com/users/1672723", "pm_score": 0, "selected": false, "text": "<p>I believe that this is the most important reason,\nand I’m astounded to see that it hasn’t been given as an answer yet\n(although it has been mentioned in <a href=\"https://stackoverflow.com/q/97506/1672723#comment15865_97526\">a comment</a>,\na footnote in <a href=\"https://stackoverflow.com/q/97506/1672723#97917\">an answer</a>, and an aside in <a href=\"https://stackoverflow.com/a/109750/1672723\">an answer</a>).</p>\n\n<p>You should always use brackets, because</p>\n\n<pre><code>if (x)\n DoSomething();\n</code></pre>\n\n<p>breaks if <code>DoSomething</code> is subsequently redefined to be a multi-statement macro:</p>\n\n<pre>#define DoSomething() <i>statement<sub>1</sub></i><b> ;</b> <i>statement<sub>2</sub></i><b> ;</b></pre>\n\n<p>Of course, <a href=\"https://stackoverflow.com/q/154136/1672723\" title=\"Why use apparently meaningless do-while statements in macros?\">we all know</a> that the right thing to do\nis to define the macro like this:<pre>#define DoSomething() <b>do {</b> <i>statement<sub>1</sub></i> ; <i>statement<sub>2</sub></i> ; <b>} while (0)</b></pre>which makes the macro behave more like a statement.</p>\n\n<p>That said, I admit that I don’t follow my own advice;\nI usually don’t use braces when I have (what appears to be) a single statement. \n(Hangs head in shame.)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
**This isn't a holy war, this isn't a question of "which is better".** What are the pros of using the following format for single statement if blocks. ``` if (x) print "x is true"; if(x) print "x is true"; ``` As opposed to ``` if (x) { print "x is true"; } if(x) { print "x is true"; } ``` **If you format your single statement ifs without brackets** or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you. **Update**: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros. 1. Compactness 2. More readable to some 3. Brackets invoke scope, which has a theoretical overhead in some cases
I find this: ``` if( true ) { DoSomething(); } else { DoSomethingElse(); } ``` better than this: ``` if( true ) DoSomething(); else DoSomethingElse(); ``` This way, if I (or someone else) comes back to this code later to add more code to one of the branches, I won't have to worry about forgetting to surround the code in braces. Our eyes will visually see the indenting as clues to what we're trying to do, but most languages won't.
97,522
<p>What are all the valid self-closing elements (e.g. &lt;br/&gt;) in XHTML (as implemented by the major browsers)?</p> <p>I know that XHTML technically allows any element to be self-closed, but I'm looking for a list of those elements supported by all major browsers. See <a href="http://dusan.fora.si/blog/self-closing-tags" rel="noreferrer">http://dusan.fora.si/blog/self-closing-tags</a> for examples of some problems caused by self-closing elements such as &lt;div /&gt;.</p>
[ { "answer_id": 97543, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": -1, "selected": false, "text": "<p>&lt;hr /&gt; is another</p>\n" }, { "answer_id": 97575, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 3, "selected": false, "text": "<p>You should have a look the <a href=\"http://www.w3.org/TR/xhtml1/#dtds\" rel=\"nofollow noreferrer\">xHTML DTDs</a>, they're all listed. Here is a quick review all the main ones:</p>\n\n<pre><code>&lt;br /&gt;\n&lt;hr /&gt;\n&lt;img /&gt;\n&lt;input /&gt;\n</code></pre>\n" }, { "answer_id": 97585, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 5, "selected": false, "text": "<p>From the <a href=\"http://www.w3schools.com/tags/ref_byfunc.asp\" rel=\"noreferrer\">W3 Schools reference site</a>:</p>\n\n<pre><code>&lt;area /&gt;\n&lt;base /&gt;\n&lt;basefont /&gt;\n&lt;br /&gt;\n&lt;hr /&gt;\n&lt;input /&gt;\n&lt;img /&gt;\n&lt;link /&gt;\n&lt;meta /&gt;\n</code></pre>\n" }, { "answer_id": 142447, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 3, "selected": false, "text": "<p>What about <code>&lt;meta&gt;</code> and <code>&lt;link&gt;</code>? Why aren't they on that list?</p>\n\n<p>Quick rule of thumb, do not self-close any element which is intended to have content, because it will definitely cause browser problems sooner or later. </p>\n\n<p>The ones which are naturally self-closing, like <code>&lt;br&gt;</code> and <code>&lt;img&gt;</code>, should be obvious. The ones which aren't ... just don't self-close them!</p>\n" }, { "answer_id": 142457, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 5, "selected": false, "text": "<p>One element to be very careful with on this topic is the <code>&lt;script</code>> element. If you have an external source file, it WILL cause problems when you self close it. Try it:</p>\n\n<pre><code>&lt;!-- this will not consistently work in all browsers! --&gt;\n&lt;script type=\"text/javascript\" src=\"external.js\" /&gt;\n</code></pre>\n\n<p>This will work in Firefox, but breaks in IE6 at least. I know, because I ran into this when over-zealously self closing every element I saw ;-)</p>\n" }, { "answer_id": 196249, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 2, "selected": false, "text": "<p>Another self closing tag problem for IE is the title element. When IE (just tried it in IE7) sees this, it presents the user a blank page. However you \"view source\" and everything is there.</p>\n\n<pre><code>&lt;title/&gt;\n</code></pre>\n\n<p>I originally saw this when my XSLT generated the self closing tag.</p>\n" }, { "answer_id": 206409, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 9, "selected": true, "text": "<p>Every browser that supports XHTML (Firefox, Opera, Safari, <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ie/xhtml-in-ie9\" rel=\"noreferrer\">IE9</a>) supports self-closing syntax on <strong>every element</strong>.</p>\n<p><code>&lt;div/&gt;</code>, <code>&lt;script/&gt;</code>, <code>&lt;br&gt;&lt;/br&gt;</code> all should work just fine. If they don't, then you have <em>HTML</em> with inappropriately added XHTML DOCTYPE.</p>\n<p><strong>DOCTYPE does not change how document is interpreted. <a href=\"http://www.webdevout.net/articles/beware-of-xhtml#content_type\" rel=\"noreferrer\">Only MIME type does</a></strong>.</p>\n<p><a href=\"https://lists.w3.org/Archives/Public/www-html/2000Sep/0024.html\" rel=\"noreferrer\">W3C decision about ignoring DOCTYPE</a>:</p>\n<blockquote>\n<p>The HTML WG has discussed this issue: the intention was to allow old\n(HTML-only) browsers to accept XHTML 1.0 documents by following the\nguidelines, and serving them as text/html. Therefore, documents served as\ntext/html should be treated as HTML and not as XHTML.</p>\n</blockquote>\n<p>It's a very common pitfall, because W3C Validator largely ignores that rule, but browsers follow it religiously. Read\n<a href=\"https://webkit.org/blog/68/understanding-html-xml-and-xhtml/\" rel=\"noreferrer\">Understanding HTML, XML and XHTML</a> from WebKit blog:</p>\n<blockquote>\n<p>In fact, the vast majority of supposedly XHTML documents on the internet are served as <code>text/html</code>. Which means they are not XHTML at all, but actually invalid HTML that’s getting by on the error handling of HTML parsers. All those “Valid XHTML 1.0!” links on the web are really saying “Invalid HTML 4.01!”.</p>\n</blockquote>\n<hr />\n<p>To test whether you have real XHTML or invalid HTML with XHTML's DOCTYPE, put this in your document:</p>\n<pre><code>&lt;span style=&quot;color:green&quot;&gt;&lt;span style=&quot;color:red&quot;/&gt; \n If it's red, it's HTML. Green is XHTML.\n&lt;/span&gt;\n</code></pre>\n<p>It validates, and in real XHTML it works perfectly (see: <a href=\"https://kornel.ski/1\" rel=\"noreferrer\">1</a> vs <a href=\"https://kornel.ski/2\" rel=\"noreferrer\">2</a>). If you can't believe your eyes (or don't know how to set MIME types), open your page via <a href=\"https://schneegans.de/xp/\" rel=\"noreferrer\">XHTML proxy</a>.</p>\n<p>Another way to check is view source in Firefox. It will highlight slashes in red when they're invalid.</p>\n<p>In HTML5/XHTML5 this hasn't changed, and the distinction is even clearer, because you don't even have additional <code>DOCTYPE</code>. <code>Content-Type</code> is the king.</p>\n<hr />\n<p>For the record, the XHTML spec allows any element to be self-closing by making XHTML an <a href=\"https://www.w3.org/TR/REC-xml/#sec-starttags\" rel=\"noreferrer\">XML application</a>: [emphasis mine]</p>\n<blockquote>\n<p>Empty-element tags may be used for <strong>any element which has no content</strong>, whether or not it is declared using the keyword EMPTY.</p>\n</blockquote>\n<p>It's also explicitly shown in the <a href=\"https://www.w3.org/TR/xhtml1/#h-4.6\" rel=\"noreferrer\">XHTML spec</a>:</p>\n<blockquote>\n<p>Empty elements must <strong>either</strong> have an end tag or the start tag must end with <code>/&gt;</code>. For instance, <code>&lt;br/&gt;</code> or <code>&lt;hr&gt;&lt;/hr&gt;</code></p>\n</blockquote>\n" }, { "answer_id": 283292, "author": "hsivonen", "author_id": 18721, "author_profile": "https://Stackoverflow.com/users/18721", "pm_score": 5, "selected": false, "text": "<p>The self-closing syntax works on all elements in application/xhtml+xml. It isn’t supported on any element in text/html, but the elements that are “empty” in HTML4 or “void” in HTML5 don’t take an end tag anyway, so if you put a slash on those it appears as though the self-closing syntax were supported.</p>\n" }, { "answer_id": 283412, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 3, "selected": false, "text": "<p>The last time I checked, the following were the empty/void elements listed in HTML5.</p>\n\n<p>Valid for authors: area, base, br, col, command, embed, eventsource, hr, img, input, link, meta, param, source</p>\n\n<p>Invalid for authors: basefont, bgsound, frame, spacer, wbr</p>\n\n<p>Besides the few that are new in HTML5, that should give you an idea of ones that might be supported when serving XHTML as text/html. (Just test them by examining the DOM produced.)</p>\n\n<p>As for XHTML served as application/xhtml+xml (which makes it XML), XML rules apply and any element can be empty (even though the XHTML DTD can't express this).</p>\n" }, { "answer_id": 1735748, "author": "Jeff", "author_id": 142233, "author_profile": "https://Stackoverflow.com/users/142233", "pm_score": 4, "selected": false, "text": "<p>Hope this helps someone:</p>\n\n<pre><code>&lt;base /&gt;\n&lt;basefont /&gt;\n&lt;frame /&gt;\n&lt;link /&gt;\n&lt;meta /&gt;\n\n&lt;area /&gt;\n&lt;br /&gt;\n&lt;col /&gt;\n&lt;hr /&gt;\n&lt;img /&gt;\n&lt;input /&gt;\n&lt;param /&gt;\n</code></pre>\n" }, { "answer_id": 3581293, "author": "Nathan Sokalski", "author_id": 432546, "author_profile": "https://Stackoverflow.com/users/432546", "pm_score": 2, "selected": false, "text": "<p>I'm not going to try to overelaborate on this, especially since the majority of pages that I write are either generated or the tag does have content. The only two that have ever given me trouble when making them self-closing are:</p>\n\n<p><code>&lt;title/&gt;</code></p>\n\n<p>For this, I have simply resorted to always giving it a separate closing tag, since once it's up there in the <code>&lt;head&gt;&lt;/head&gt;</code> it doesn't really make your code any messier to work with anyway.</p>\n\n<p><code>&lt;script/&gt;</code></p>\n\n<p>This is the big one that I very recently ran into problems with. For years I had always used self-closing <code>&lt;script/&gt;</code> tags when the script is coming from an external source. But I very recently started recieving JavaScript error messages about a null form. After several days of research, I found that the problem was (supposedly) that the browser was never getting to the <code>&lt;form&gt;</code> tag because it didn't realize this was the end of the <code>&lt;script/&gt;</code> tag. So when I made it into separate <code>&lt;script&gt;&lt;/script&gt;</code> tags, everything worked. Why different in different pages I made on the same browser, I don't know, but it was a big relief to find the solution!</p>\n" }, { "answer_id": 8853550, "author": "Dmitry Osinovskiy", "author_id": 194020, "author_profile": "https://Stackoverflow.com/users/194020", "pm_score": 5, "selected": false, "text": "<p>Better question would be: what tags can be self-closed even in HTML mode without affecting code? Answer: only those that have empty content (are void).\nAccording to <a href=\"http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements\" rel=\"noreferrer\">HTML specs</a> the following elements are void:</p>\n\n<p><code>area, base, br, col, embed, hr, img, input, keygen, link, menuitem, meta, param, source, track, wbr</code></p>\n\n<p>Older version of specification also listed <code>command</code>. \nBesides, according to various sources the following obsolete or non-standard tags are void:</p>\n\n<p><code>basefont, bgsound, frame, isindex</code></p>\n" }, { "answer_id": 16155807, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 3, "selected": false, "text": "<p>They're called \"void\" elements in HTML 5. They're listed in the <a href=\"https://www.w3.org/TR/html/syntax.html#void-elements\" rel=\"nofollow noreferrer\">official W3 spec</a>. </p>\n\n<blockquote>\n <p>A void element is an element whose content model never allows it to have contents under any circumstances. </p>\n</blockquote>\n\n<p>As of April 2013, they are:</p>\n\n<blockquote>\n <p>area, base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, wbr</p>\n</blockquote>\n\n<p>As of December 2018 (HTML 5.2), they are:</p>\n\n<blockquote>\n <p>area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr</p>\n</blockquote>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1335/" ]
What are all the valid self-closing elements (e.g. <br/>) in XHTML (as implemented by the major browsers)? I know that XHTML technically allows any element to be self-closed, but I'm looking for a list of those elements supported by all major browsers. See <http://dusan.fora.si/blog/self-closing-tags> for examples of some problems caused by self-closing elements such as <div />.
Every browser that supports XHTML (Firefox, Opera, Safari, [IE9](https://learn.microsoft.com/en-us/archive/blogs/ie/xhtml-in-ie9)) supports self-closing syntax on **every element**. `<div/>`, `<script/>`, `<br></br>` all should work just fine. If they don't, then you have *HTML* with inappropriately added XHTML DOCTYPE. **DOCTYPE does not change how document is interpreted. [Only MIME type does](http://www.webdevout.net/articles/beware-of-xhtml#content_type)**. [W3C decision about ignoring DOCTYPE](https://lists.w3.org/Archives/Public/www-html/2000Sep/0024.html): > > The HTML WG has discussed this issue: the intention was to allow old > (HTML-only) browsers to accept XHTML 1.0 documents by following the > guidelines, and serving them as text/html. Therefore, documents served as > text/html should be treated as HTML and not as XHTML. > > > It's a very common pitfall, because W3C Validator largely ignores that rule, but browsers follow it religiously. Read [Understanding HTML, XML and XHTML](https://webkit.org/blog/68/understanding-html-xml-and-xhtml/) from WebKit blog: > > In fact, the vast majority of supposedly XHTML documents on the internet are served as `text/html`. Which means they are not XHTML at all, but actually invalid HTML that’s getting by on the error handling of HTML parsers. All those “Valid XHTML 1.0!” links on the web are really saying “Invalid HTML 4.01!”. > > > --- To test whether you have real XHTML or invalid HTML with XHTML's DOCTYPE, put this in your document: ``` <span style="color:green"><span style="color:red"/> If it's red, it's HTML. Green is XHTML. </span> ``` It validates, and in real XHTML it works perfectly (see: [1](https://kornel.ski/1) vs [2](https://kornel.ski/2)). If you can't believe your eyes (or don't know how to set MIME types), open your page via [XHTML proxy](https://schneegans.de/xp/). Another way to check is view source in Firefox. It will highlight slashes in red when they're invalid. In HTML5/XHTML5 this hasn't changed, and the distinction is even clearer, because you don't even have additional `DOCTYPE`. `Content-Type` is the king. --- For the record, the XHTML spec allows any element to be self-closing by making XHTML an [XML application](https://www.w3.org/TR/REC-xml/#sec-starttags): [emphasis mine] > > Empty-element tags may be used for **any element which has no content**, whether or not it is declared using the keyword EMPTY. > > > It's also explicitly shown in the [XHTML spec](https://www.w3.org/TR/xhtml1/#h-4.6): > > Empty elements must **either** have an end tag or the start tag must end with `/>`. For instance, `<br/>` or `<hr></hr>` > > >
97,565
<p>C# question (.net 3.5). I have a class, ImageData, that has a field ushort[,] pixels. I am dealing with proprietary image formats. The ImageData class takes a file location in the constructor, then switches on file extension to determine how to decode. In several of the image files, there is a "bit depth" field in the header. After I decode the header I read the pixel values into the "pixels" array. So far I have not had more than 16bpp, so I'm okay. But what if I have 32bpp?</p> <p>What I want to do is have the type of pixels be determined at runtime. I want to do this after I read the bit depth out of the header and before I copy the pixel data into memory. Any ideas?</p>
[ { "answer_id": 97626, "author": "Colin Mackay", "author_id": 8152, "author_profile": "https://Stackoverflow.com/users/8152", "pm_score": 2, "selected": false, "text": "<p>I would say not to do that work in the construtor - A constructor should not do so much work, in my opinion. Use a factory method that reads the file to determine the bit depth, then have it construct the correct generic variant of the class and return it.</p>\n" }, { "answer_id": 97713, "author": "apenwarr", "author_id": 42219, "author_profile": "https://Stackoverflow.com/users/42219", "pm_score": 0, "selected": false, "text": "<p>Have your decode function return an object of type Array, which is the base class of all arrays. Then people who care about the type can do \"if (a is ushort[,])\" and so on if they want to go through the pixels. If you do it this way, you need to allocate the array in ImageData, not the other way around.</p>\n\n<p>Alternatively, the caller probably knows what kind of pixel array <em>they</em> want you to use. Even if it's an 8bpp or 16bpp image, if you're decoding it to a 32bpp screen, you need to use uint instead of ushort. So you could write an ImageData function that will decode into integers of whatever type T is.</p>\n\n<p>The root of your problem is that you don't know how to decide what kind of output format you want. You need to figure that out first, and the program syntax comes second.</p>\n" }, { "answer_id": 97788, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": true, "text": "<p>To boil down your problem, you want to be able to have a class that has a <strong>ushort[,] pixels</strong> field (16-bits per pixel) sometimes and a <strong>uint32[,] pixels</strong> field (32-bits per pixel) some other times. There are a couple different ways to achieve this.</p>\n\n<p>You could create replacements for ushort / uint32 by making a Pixel class with 32-bit and 16-bit sub-classes, overriding various operators up the wazoo, but this incurs a lot of overhead, is tricky to get right and even trickier to determine if its right. Alternately you could create proxy classes for your pixel data (which would contain the ushort[,] or uint32[,] arrays and would have all the necessary accessors to be useful). The downside there is that you would likely end up with a lot of special case code in the ImageData class which executed one way or the other depending on some 16-bit/32-bit mode flag.</p>\n\n<p>The better solution, I think, would be to sub-class ImageData into 16-bit and 32-bit classes, and use a factory method to create instances. E.g. ImageData is the base class, ImageData16bpp and ImageData32bpp are sub-classes, static method ImageData.Create(string imageFilename) is the factory method which creates either ImageData16bpp or ImageData32bpp depending on the header data. For example:</p>\n\n<pre><code>public static ImageData Create(string imageFilename)\n{\n // ...\n ImageDataHeader imageHeader = ParseHeader(imageFilename);\n ImageData newImageData;\n if (imageHeader.bpp == 32)\n {\n newImageData = new ImageData32(imageFilename, imageHeader);\n }\n else\n {\n newImageData = new ImageData16(imageFilename, imageHeader);\n }\n // ...\n return newImageData;\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1812999/" ]
C# question (.net 3.5). I have a class, ImageData, that has a field ushort[,] pixels. I am dealing with proprietary image formats. The ImageData class takes a file location in the constructor, then switches on file extension to determine how to decode. In several of the image files, there is a "bit depth" field in the header. After I decode the header I read the pixel values into the "pixels" array. So far I have not had more than 16bpp, so I'm okay. But what if I have 32bpp? What I want to do is have the type of pixels be determined at runtime. I want to do this after I read the bit depth out of the header and before I copy the pixel data into memory. Any ideas?
To boil down your problem, you want to be able to have a class that has a **ushort[,] pixels** field (16-bits per pixel) sometimes and a **uint32[,] pixels** field (32-bits per pixel) some other times. There are a couple different ways to achieve this. You could create replacements for ushort / uint32 by making a Pixel class with 32-bit and 16-bit sub-classes, overriding various operators up the wazoo, but this incurs a lot of overhead, is tricky to get right and even trickier to determine if its right. Alternately you could create proxy classes for your pixel data (which would contain the ushort[,] or uint32[,] arrays and would have all the necessary accessors to be useful). The downside there is that you would likely end up with a lot of special case code in the ImageData class which executed one way or the other depending on some 16-bit/32-bit mode flag. The better solution, I think, would be to sub-class ImageData into 16-bit and 32-bit classes, and use a factory method to create instances. E.g. ImageData is the base class, ImageData16bpp and ImageData32bpp are sub-classes, static method ImageData.Create(string imageFilename) is the factory method which creates either ImageData16bpp or ImageData32bpp depending on the header data. For example: ``` public static ImageData Create(string imageFilename) { // ... ImageDataHeader imageHeader = ParseHeader(imageFilename); ImageData newImageData; if (imageHeader.bpp == 32) { newImageData = new ImageData32(imageFilename, imageHeader); } else { newImageData = new ImageData16(imageFilename, imageHeader); } // ... return newImageData; } ```
97,578
<p>Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example:</p> <pre><code>&lt;a href="#" onclick="SelectSurveyItem('&lt;%itemid%&gt;', '&lt;%itemname%&gt;'); return false;"&gt;Select&lt;/a&gt; </code></pre> <p>The <code>&lt;%itemid%&gt;</code> and <code>&lt;%itemname%&gt;</code> are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code.</p> <p>My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler?</p> <p>If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons...</p> <p>This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result.</p> <p>Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me.</p>
[ { "answer_id": 97591, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 1, "selected": false, "text": "<p>Declare separate functions in the &lt;head&gt; section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function. </p>\n" }, { "answer_id": 97593, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 1, "selected": false, "text": "<p>Use the <a href=\"http://blogs.msdn.com/ace_team/archive/2006/11/20/microsoft-anti-cross-site-scripting-library-v1-5-is-done.aspx\" rel=\"nofollow noreferrer\">Microsoft Anti-XSS library</a> which includes a JavaScript encode.</p>\n" }, { "answer_id": 97613, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<p>If it's going into an HTML attribute, you'll need to both HTML-encode (as a minimum: <code>&gt;</code> to <code>&amp;gt;</code> <code>&lt;</code> to <code>&amp;lt</code> and <code>\"</code> to <code>&amp;quot;</code>) it, <em>and</em> escape single-quotes (with a backslash) so they don't interfere with your javascript quoting. </p>\n\n<p>Best way to do it is with your templating system (extending it, if necessary), but you could simply make a couple of escaping/encoding functions and wrap them both around any data that's going in there.</p>\n\n<p>And yes, it's perfectly valid (correct, even) to HTML-escape the entire contents of your HTML attributes, even if they contain javascript.</p>\n" }, { "answer_id": 97670, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 1, "selected": false, "text": "<p>First, it would be simpler if the onclick handler was set this way:</p>\n\n<pre><code>&lt;a id=\"someLinkId\"href=\"#\"&gt;Select&lt;/a&gt;\n&lt;script type=\"text/javascript\"&gt;\n document.getElementById(\"someLinkId\").onClick = \n function() {\n SelectSurveyItem('&lt;%itemid%&gt;', '&lt;%itemname%&gt;'); return false;\n };\n\n&lt;/script&gt;\n</code></pre>\n\n<p>Then itemid and itemname need to be escaped for JavaScript (that is, <code>\"</code> becomes <code>\\\"</code>, etc.).</p>\n\n<p>If you are using Java on the server side, you might take a look at the class <a href=\"http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeJavaScript(java.lang.String)\" rel=\"nofollow noreferrer\">StringEscapeUtils</a> from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.</p>\n" }, { "answer_id": 97687, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "<p>Try avoid using string-literals in your HTML and use JavaScript to bind JavaScript events.</p>\n\n<p>Also, avoid 'href=#' unless you <em>really</em> know what you're doing. It breaks so much usability for compulsive middleclickers (tab opener).</p>\n\n<pre><code>&lt;a id=\"tehbutton\" href=\"somewhereToGoWithoutWorkingJavascript.com\"&gt;Select&lt;/a&gt;\n</code></pre>\n\n<p>My JavaScript library of choice just happens to be jQuery:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;!-- &lt;![CDATA[\njQuery(function($){\n $(\"#tehbutton\").click(function(){\n SelectSurveyItem('&lt;%itemid%&gt;', '&lt;%itemname%&gt;');\n return false;\n });\n});\n//]]&gt;--&gt;&lt;/script&gt;\n</code></pre>\n\n<p>If you happen to be rendering a list of links like that, you may want to do this:</p>\n\n<pre><code>&lt;a id=\"link_1\" href=\"foo\"&gt;Bar&lt;/a&gt;\n&lt;a id=\"link_2\" href=\"foo2\"&gt;Baz&lt;/a&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n jQuery(function($){\n var l = [[1,'Bar'],[2,'Baz']];\n $(l).each(function(k,v){\n $(\"#link_\" + v[0] ).click(function(){\n SelectSurveyItem(v[0],v[1]);\n return false;\n });\n });\n });\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 97724, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>Another interesting solution might be to do this:</p>\n\n<pre><code>&lt;a href=\"#\" itemid=\"&lt;%itemid%&gt;\" itemname=\"&lt;%itemname%&gt;\" onclick=\"SelectSurveyItem(this.itemid, this.itemname); return false;\"&gt;Select&lt;/a&gt;\n</code></pre>\n\n<p>Then you can use a standard HTML-encoding on both the variables, without having to worry about the extra complication of the javascript quoting.</p>\n\n<p>Yes, this <em>does</em> create HTML that is strictly invalid. However, it <em>is</em> a valid technique, and all modern browsers support it.</p>\n\n<p>If it was my, I'd probably go with my first suggestion, and ensure the values are HTML-encoded <em>and</em> have single-quotes escaped.</p>\n" }, { "answer_id": 97804, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 7, "selected": true, "text": "<p>In JavaScript you can encode single quotes as \"\\x27\" and double quotes as \"\\x22\". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \\x27 \\x22 with impunity without fear of any embedded quotes \"breaking out\" of your string. </p>\n\n<p>\\xXX is for chars &lt; 127, and \\uXXXX for <a href=\"http://en.wikipedia.org/wiki/Unicode\" rel=\"noreferrer\">Unicode</a>, so armed with this knowledge you can create a robust <em>JSEncode</em> function for all characters that are out of the usual whitelist.</p>\n\n<p>For example,</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"SelectSurveyItem('&lt;% JSEncode(itemid) %&gt;', '&lt;% JSEncode(itemname) %&gt;'); return false;\"&gt;Select&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 101224, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<p>Is the answers here that you can't escape quotes using JavaScript and that you need to start with escaped strings.</p>\n\n<p>Therefore. There's no way of JavaScript being able to handle the string 'Marge said \"I'd look that was\" to Peter' and you need your data be cleaned before offering it to the script?</p>\n" }, { "answer_id": 102735, "author": "livingtech", "author_id": 18961, "author_profile": "https://Stackoverflow.com/users/18961", "pm_score": 1, "selected": false, "text": "<p>Any good templating engine worth its salt will have an \"escape quotes\" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.</p>\n" }, { "answer_id": 506347, "author": "Shyam Kumar Sundarakumar", "author_id": 35392, "author_profile": "https://Stackoverflow.com/users/35392", "pm_score": 4, "selected": false, "text": "<p>Use hidden spans, one each for each of the parameters <code>&lt;%itemid%&gt;</code> and <code>&lt;%itemname%&gt;</code> and write their values inside them.</p>\n\n<p>For example, the span for <code>&lt;%itemid%&gt;</code> would look like <code>&lt;span id='itemid' style='display:none'&gt;&lt;%itemid%&gt;&lt;/span&gt;</code> and in the javascript function <code>SelectSurveyItem</code> to pick the arguments from these spans' <code>innerHTML</code>.</p>\n" }, { "answer_id": 5273245, "author": "AhmedGamal", "author_id": 655389, "author_profile": "https://Stackoverflow.com/users/655389", "pm_score": 0, "selected": false, "text": "<p>I faced the same problem, and I solved it in a tricky way. First make global variables, v1, v2, and v3. And in the onclick, send an indicator, 1, 2, or 3 and in the function check for 1, 2, 3 to put the v1, v2, and v3 like:</p>\n\n<pre><code>onclick=\"myfun(1)\"\nonclick=\"myfun(2)\"\nonclick=\"myfun(3)\"\n\nfunction myfun(var)\n{\n if (var ==1)\n alert(v1);\n\n if (var ==2)\n alert(v2);\n\n if (var ==3)\n alert(v3);\n}\n</code></pre>\n" }, { "answer_id": 8611916, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 5, "selected": false, "text": "<p>Depending on the server-side language, you could use one of these:</p>\n\n<p>.NET 4.0</p>\n\n<pre><code>string result = System.Web.HttpUtility.JavaScriptStringEncode(\"jsString\")\n</code></pre>\n\n<p>Java</p>\n\n<pre><code>import org.apache.commons.lang.StringEscapeUtils;\n...\n\nString result = StringEscapeUtils.escapeJavaScript(jsString);\n</code></pre>\n\n<p>Python</p>\n\n<pre><code>import json\nresult = json.dumps(jsString)\n</code></pre>\n\n<p>PHP</p>\n\n<pre><code>$result = strtr($jsString, array('\\\\' =&gt; '\\\\\\\\', \"'\" =&gt; \"\\\\'\", '\"' =&gt; '\\\\\"', \n \"\\r\" =&gt; '\\\\r', \"\\n\" =&gt; '\\\\n' ));\n</code></pre>\n\n<p>Ruby on Rails</p>\n\n<pre><code>&lt;%= escape_javascript(jsString) %&gt;\n</code></pre>\n" }, { "answer_id": 9303208, "author": "Starbuck Johnson", "author_id": 1212632, "author_profile": "https://Stackoverflow.com/users/1212632", "pm_score": 1, "selected": false, "text": "<p>I have faced this problem as well. I made a script to convert single quotes into escaped double quotes that won't break the HTML.</p>\n\n<pre><code>function noQuote(text)\n{\n var newtext = \"\";\n for (var i = 0; i &lt; text.length; i++) {\n if (text[i] == \"'\") {\n newtext += \"\\\"\";\n }\n else {\n newtext += text[i];\n }\n }\n return newtext;\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ]
Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example: ``` <a href="#" onclick="SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;">Select</a> ``` The `<%itemid%>` and `<%itemname%>` are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code. My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler? If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons... This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result. Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me.
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string. \xXX is for chars < 127, and \uXXXX for [Unicode](http://en.wikipedia.org/wiki/Unicode), so armed with this knowledge you can create a robust *JSEncode* function for all characters that are out of the usual whitelist. For example, ``` <a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a> ```
97,586
<p>My boss loves VB (we work in a Java shop) because he thinks it's easy to learn and maintain. We want to replace some of the VB with java equivalents using the Eclipse SWT editor, because we think it is almost as easy to maintain. To sell this, we'd like to use an aerith style L&amp;F.</p> <p>Can anyone provide an example of an SWT application still being able to edit the GUI in eclipse, but having the Aerith L&amp;F?</p>
[ { "answer_id": 97591, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 1, "selected": false, "text": "<p>Declare separate functions in the &lt;head&gt; section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function. </p>\n" }, { "answer_id": 97593, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 1, "selected": false, "text": "<p>Use the <a href=\"http://blogs.msdn.com/ace_team/archive/2006/11/20/microsoft-anti-cross-site-scripting-library-v1-5-is-done.aspx\" rel=\"nofollow noreferrer\">Microsoft Anti-XSS library</a> which includes a JavaScript encode.</p>\n" }, { "answer_id": 97613, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<p>If it's going into an HTML attribute, you'll need to both HTML-encode (as a minimum: <code>&gt;</code> to <code>&amp;gt;</code> <code>&lt;</code> to <code>&amp;lt</code> and <code>\"</code> to <code>&amp;quot;</code>) it, <em>and</em> escape single-quotes (with a backslash) so they don't interfere with your javascript quoting. </p>\n\n<p>Best way to do it is with your templating system (extending it, if necessary), but you could simply make a couple of escaping/encoding functions and wrap them both around any data that's going in there.</p>\n\n<p>And yes, it's perfectly valid (correct, even) to HTML-escape the entire contents of your HTML attributes, even if they contain javascript.</p>\n" }, { "answer_id": 97670, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 1, "selected": false, "text": "<p>First, it would be simpler if the onclick handler was set this way:</p>\n\n<pre><code>&lt;a id=\"someLinkId\"href=\"#\"&gt;Select&lt;/a&gt;\n&lt;script type=\"text/javascript\"&gt;\n document.getElementById(\"someLinkId\").onClick = \n function() {\n SelectSurveyItem('&lt;%itemid%&gt;', '&lt;%itemname%&gt;'); return false;\n };\n\n&lt;/script&gt;\n</code></pre>\n\n<p>Then itemid and itemname need to be escaped for JavaScript (that is, <code>\"</code> becomes <code>\\\"</code>, etc.).</p>\n\n<p>If you are using Java on the server side, you might take a look at the class <a href=\"http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeJavaScript(java.lang.String)\" rel=\"nofollow noreferrer\">StringEscapeUtils</a> from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.</p>\n" }, { "answer_id": 97687, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "<p>Try avoid using string-literals in your HTML and use JavaScript to bind JavaScript events.</p>\n\n<p>Also, avoid 'href=#' unless you <em>really</em> know what you're doing. It breaks so much usability for compulsive middleclickers (tab opener).</p>\n\n<pre><code>&lt;a id=\"tehbutton\" href=\"somewhereToGoWithoutWorkingJavascript.com\"&gt;Select&lt;/a&gt;\n</code></pre>\n\n<p>My JavaScript library of choice just happens to be jQuery:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;!-- &lt;![CDATA[\njQuery(function($){\n $(\"#tehbutton\").click(function(){\n SelectSurveyItem('&lt;%itemid%&gt;', '&lt;%itemname%&gt;');\n return false;\n });\n});\n//]]&gt;--&gt;&lt;/script&gt;\n</code></pre>\n\n<p>If you happen to be rendering a list of links like that, you may want to do this:</p>\n\n<pre><code>&lt;a id=\"link_1\" href=\"foo\"&gt;Bar&lt;/a&gt;\n&lt;a id=\"link_2\" href=\"foo2\"&gt;Baz&lt;/a&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n jQuery(function($){\n var l = [[1,'Bar'],[2,'Baz']];\n $(l).each(function(k,v){\n $(\"#link_\" + v[0] ).click(function(){\n SelectSurveyItem(v[0],v[1]);\n return false;\n });\n });\n });\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 97724, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>Another interesting solution might be to do this:</p>\n\n<pre><code>&lt;a href=\"#\" itemid=\"&lt;%itemid%&gt;\" itemname=\"&lt;%itemname%&gt;\" onclick=\"SelectSurveyItem(this.itemid, this.itemname); return false;\"&gt;Select&lt;/a&gt;\n</code></pre>\n\n<p>Then you can use a standard HTML-encoding on both the variables, without having to worry about the extra complication of the javascript quoting.</p>\n\n<p>Yes, this <em>does</em> create HTML that is strictly invalid. However, it <em>is</em> a valid technique, and all modern browsers support it.</p>\n\n<p>If it was my, I'd probably go with my first suggestion, and ensure the values are HTML-encoded <em>and</em> have single-quotes escaped.</p>\n" }, { "answer_id": 97804, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 7, "selected": true, "text": "<p>In JavaScript you can encode single quotes as \"\\x27\" and double quotes as \"\\x22\". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \\x27 \\x22 with impunity without fear of any embedded quotes \"breaking out\" of your string. </p>\n\n<p>\\xXX is for chars &lt; 127, and \\uXXXX for <a href=\"http://en.wikipedia.org/wiki/Unicode\" rel=\"noreferrer\">Unicode</a>, so armed with this knowledge you can create a robust <em>JSEncode</em> function for all characters that are out of the usual whitelist.</p>\n\n<p>For example,</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"SelectSurveyItem('&lt;% JSEncode(itemid) %&gt;', '&lt;% JSEncode(itemname) %&gt;'); return false;\"&gt;Select&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 101224, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<p>Is the answers here that you can't escape quotes using JavaScript and that you need to start with escaped strings.</p>\n\n<p>Therefore. There's no way of JavaScript being able to handle the string 'Marge said \"I'd look that was\" to Peter' and you need your data be cleaned before offering it to the script?</p>\n" }, { "answer_id": 102735, "author": "livingtech", "author_id": 18961, "author_profile": "https://Stackoverflow.com/users/18961", "pm_score": 1, "selected": false, "text": "<p>Any good templating engine worth its salt will have an \"escape quotes\" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.</p>\n" }, { "answer_id": 506347, "author": "Shyam Kumar Sundarakumar", "author_id": 35392, "author_profile": "https://Stackoverflow.com/users/35392", "pm_score": 4, "selected": false, "text": "<p>Use hidden spans, one each for each of the parameters <code>&lt;%itemid%&gt;</code> and <code>&lt;%itemname%&gt;</code> and write their values inside them.</p>\n\n<p>For example, the span for <code>&lt;%itemid%&gt;</code> would look like <code>&lt;span id='itemid' style='display:none'&gt;&lt;%itemid%&gt;&lt;/span&gt;</code> and in the javascript function <code>SelectSurveyItem</code> to pick the arguments from these spans' <code>innerHTML</code>.</p>\n" }, { "answer_id": 5273245, "author": "AhmedGamal", "author_id": 655389, "author_profile": "https://Stackoverflow.com/users/655389", "pm_score": 0, "selected": false, "text": "<p>I faced the same problem, and I solved it in a tricky way. First make global variables, v1, v2, and v3. And in the onclick, send an indicator, 1, 2, or 3 and in the function check for 1, 2, 3 to put the v1, v2, and v3 like:</p>\n\n<pre><code>onclick=\"myfun(1)\"\nonclick=\"myfun(2)\"\nonclick=\"myfun(3)\"\n\nfunction myfun(var)\n{\n if (var ==1)\n alert(v1);\n\n if (var ==2)\n alert(v2);\n\n if (var ==3)\n alert(v3);\n}\n</code></pre>\n" }, { "answer_id": 8611916, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 5, "selected": false, "text": "<p>Depending on the server-side language, you could use one of these:</p>\n\n<p>.NET 4.0</p>\n\n<pre><code>string result = System.Web.HttpUtility.JavaScriptStringEncode(\"jsString\")\n</code></pre>\n\n<p>Java</p>\n\n<pre><code>import org.apache.commons.lang.StringEscapeUtils;\n...\n\nString result = StringEscapeUtils.escapeJavaScript(jsString);\n</code></pre>\n\n<p>Python</p>\n\n<pre><code>import json\nresult = json.dumps(jsString)\n</code></pre>\n\n<p>PHP</p>\n\n<pre><code>$result = strtr($jsString, array('\\\\' =&gt; '\\\\\\\\', \"'\" =&gt; \"\\\\'\", '\"' =&gt; '\\\\\"', \n \"\\r\" =&gt; '\\\\r', \"\\n\" =&gt; '\\\\n' ));\n</code></pre>\n\n<p>Ruby on Rails</p>\n\n<pre><code>&lt;%= escape_javascript(jsString) %&gt;\n</code></pre>\n" }, { "answer_id": 9303208, "author": "Starbuck Johnson", "author_id": 1212632, "author_profile": "https://Stackoverflow.com/users/1212632", "pm_score": 1, "selected": false, "text": "<p>I have faced this problem as well. I made a script to convert single quotes into escaped double quotes that won't break the HTML.</p>\n\n<pre><code>function noQuote(text)\n{\n var newtext = \"\";\n for (var i = 0; i &lt; text.length; i++) {\n if (text[i] == \"'\") {\n newtext += \"\\\"\";\n }\n else {\n newtext += text[i];\n }\n }\n return newtext;\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15441/" ]
My boss loves VB (we work in a Java shop) because he thinks it's easy to learn and maintain. We want to replace some of the VB with java equivalents using the Eclipse SWT editor, because we think it is almost as easy to maintain. To sell this, we'd like to use an aerith style L&F. Can anyone provide an example of an SWT application still being able to edit the GUI in eclipse, but having the Aerith L&F?
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string. \xXX is for chars < 127, and \uXXXX for [Unicode](http://en.wikipedia.org/wiki/Unicode), so armed with this knowledge you can create a robust *JSEncode* function for all characters that are out of the usual whitelist. For example, ``` <a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a> ```
97,637
<p>Anyone got a good explanation of "combinators" (Y-combinators etc. and <strong>NOT</strong> <a href="https://en.wikipedia.org/wiki/Y_Combinator_(company)" rel="noreferrer">the company</a>)?</p> <p>I'm looking for one for the practical programmer who understands recursion and higher-order functions, but doesn't have a strong theory or math background.</p> <p>(Note: that I'm talking about <a href="https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus" rel="noreferrer">these things</a>)</p>
[ { "answer_id": 97771, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 2, "selected": false, "text": "<p>This is a good <a href=\"https://web.archive.org/web/20160913141703/http://www.dreamsongs.com/NewFiles/WhyOfY.pdf\" rel=\"nofollow noreferrer\">article</a>.\nThe code examples are in scheme, but they shouldn't be hard to follow.</p>\n" }, { "answer_id": 101932, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Unless you're deeply into theory, you can regard the Y combinator\nas a neat trick with functions, like monads.</p>\n\n<p>Monads allow you to chain actions, the Y combinator allows you to\ndefine self-recursive functions.</p>\n\n<p>Python has built-in support for self-recursive functions, so you\ncan define them without Y:</p>\n\n<pre><code>&gt; def fun():\n&gt; print \"bla\"\n&gt; fun()\n\n&gt; fun()\nbla\nbla\nbla\n...\n</code></pre>\n\n<p><code>fun</code> is accessible inside <code>fun</code> itself, so we can easily call it.</p>\n\n<p><em>But what if Python were different, and <code>fun</code> weren't accessible\ninside <code>fun</code>?</em></p>\n\n<pre><code>&gt; def fun():\n&gt; print \"bla\"\n&gt; # what to do here? (cannot call fun!)\n</code></pre>\n\n<p>The solution is to pass <code>fun</code> itself as an argument to <code>fun</code>:</p>\n\n<pre><code>&gt; def fun(arg): # fun receives itself as argument\n&gt; print \"bla\"\n&gt; arg(arg) # to recur, fun calls itself, and passes itself along\n</code></pre>\n\n<p>And Y makes that possible:</p>\n\n<pre><code>&gt; def Y(f):\n&gt; f(f)\n\n&gt; Y(fun)\nbla\nbla\nbla\n...\n</code></pre>\n\n<p>All it does it call a function with itself as argument.</p>\n\n<p>(I don't know if this definition of Y is 100% correct, but I think it's the general idea.)</p>\n" }, { "answer_id": 285973, "author": "andrewdotnich", "author_id": 10569, "author_profile": "https://Stackoverflow.com/users/10569", "pm_score": 5, "selected": false, "text": "<p>Reginald Braithwaite (aka Raganwald) has been writing a great series on combinators in Ruby over at his new blog, <a href=\"http://github.com/raganwald/homoiconic/tree/master\" rel=\"noreferrer\">homoiconic</a>. </p>\n\n<p>While he doesn't (to my knowledge) look at the Y-combinator itself, he does look at other combinators, for instance:</p>\n\n<ul>\n<li>the <a href=\"http://github.com/raganwald/homoiconic/tree/master/2008-10-29/kestrel.markdown\" rel=\"noreferrer\">Kestrel</a></li>\n<li>the <a href=\"http://github.com/raganwald/homoiconic/tree/master/2008-10-30/thrush.markdown\" rel=\"noreferrer\">Thrush</a></li>\n<li>the <a href=\"http://github.com/raganwald/homoiconic/tree/master/2008-10-31/songs_of_the_cardinal.markdown\" rel=\"noreferrer\">Cardinal</a></li>\n<li>the <a href=\"http://github.com/raganwald/homoiconic/tree/master%2F2008-11-12%2Fthe_obdurate_kestrel.md\" rel=\"noreferrer\">Obdurate Kestrel</a></li>\n<li>other Quirky Birds</li>\n</ul>\n\n<p>and a few posts on how you <a href=\"http://github.com/raganwald/homoiconic/tree/master/2008-11-07/from_birds_that_compose_to_method_advice.markdown\" rel=\"noreferrer\">can</a> <a href=\"http://github.com/raganwald/homoiconic/tree/master/2008-11-04/quirky_birds_and_meta_syntactic_programming.markdown\" rel=\"noreferrer\">use</a> them.</p>\n" }, { "answer_id": 286014, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 1, "selected": false, "text": "<p>I'm pretty short on theory, but I can give you an example that sets my imagination aflutter, which may be helpful to you. The simplest interesting combinator is probably \"test\".</p>\n\n<p>Hope you know Python</p>\n\n<pre><code>tru = lambda x,y: x\nfls = lambda x,y: y \n\ntest = lambda l,m,n: l(m,n)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&gt;&gt;&gt; test(tru,\"goto loop\",\"break\")\n'goto loop'\n&gt;&gt;&gt; test(fls,\"goto loop\",\"break\")\n'break'\n</code></pre>\n\n<p>test evaluates to the second argument if the first argument is true, otherwise the third.</p>\n\n<pre><code>&gt;&gt;&gt; x = tru\n&gt;&gt;&gt; test(x,\"goto loop\",\"break\")\n'goto loop'\n</code></pre>\n\n<p>Entire systems can be built up from a few basic combinators.</p>\n\n<p>(This example is more or less copied out of Types and Programming Languages by Benjamin C. Pierce)</p>\n" }, { "answer_id": 2215223, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 4, "selected": false, "text": "<p>Quote Wikipedia:</p>\n\n<blockquote>\n <p>A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments.</p>\n</blockquote>\n\n<p>Now what does this mean? It means a combinator is a function (output is determined solely by its input) whose input includes a function as an argument.</p>\n\n<p>What do such functions look like and what are they used for? Here are some examples:</p>\n\n<p><code>(f o g)(x) = f(g(x))</code></p>\n\n<p>Here <code>o</code> is a combinator that takes in 2 functions , <code>f</code> and <code>g</code>, and returns a function as its result, the composition of <code>f</code> with <code>g</code>, namely <code>f o g</code>.</p>\n\n<p>Combinators can be used to hide logic. Say we have a data type <code>NumberUndefined</code>, where <code>NumberUndefined</code> can take on a numeric value <code>Num x</code> or a value <code>Undefined</code>, where <code>x</code> a is a <code>Number</code>. Now we want to construct addition, subtraction, multiplication, and division for this new numeric type. The semantics are the same as for those of <code>Number</code> except if <code>Undefined</code> is an input, the output must also be <code>Undefined</code> and when dividing by the number <code>0</code> the output is also <code>Undefined</code>.</p>\n\n<p>One could write the tedious code as below:</p>\n\n<pre><code>Undefined +' num = Undefined\nnum +' Undefined = Undefined\n(Num x) +' (Num y) = Num (x + y)\n\nUndefined -' num = Undefined\nnum -' Undefined = Undefined\n(Num x) -' (Num y) = Num (x - y)\n\nUndefined *' num = Undefined\nnum *' Undefined = Undefined\n(Num x) *' (Num y) = Num (x * y)\n\nUndefined /' num = Undefined\nnum /' Undefined = Undefined\n(Num x) /' (Num y) = if y == 0 then Undefined else Num (x / y)\n</code></pre>\n\n<p>Notice how the all have the same logic concerning <code>Undefined</code> input values. Only division does a bit more. The solution is to extract out the logic by making it a combinator.</p>\n\n<pre><code>comb (~) Undefined num = Undefined\ncomb (~) num Undefined = Undefined\ncomb (~) (Num x) (Num y) = Num (x ~ y)\n\nx +' y = comb (+) x y\nx -' y = comb (-) x y\nx *' y = comb (*) x y\nx /' y = if y == Num 0 then Undefined else comb (/) x y\n</code></pre>\n\n<p>This can be generalized into the so-called <code>Maybe</code> monad that programmers make use of in functional languages like Haskell, but I won't go there.</p>\n" }, { "answer_id": 2215264, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 0, "selected": false, "text": "<p>Shortly, Y combinator is a higher order function that is used to implement recursion on lambda expressions (anonymous functions). Check the article <a href=\"http://mvanier.livejournal.com/2897.html\" rel=\"nofollow noreferrer\">How to Succeed at Recursion Without Really Recursing</a> by Mike Vanier - it's one of best practical explanation of this matter I've seen.</p>\n\n<p>Also, scan the SO archives:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/93526/what-is-a-y-combinator\">What is a y-combinator?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/869497/y-combinator-practical-example\">Y-Combinator Practical Example</a></li>\n</ul>\n" }, { "answer_id": 2215293, "author": "Igor Zevaka", "author_id": 129404, "author_profile": "https://Stackoverflow.com/users/129404", "pm_score": 3, "selected": false, "text": "<p>A combinator is function with <strong>no free variables</strong>. That means, amongst other things, that the combinator does not have dependencies on things outside of the function, only on the function parameters.</p>\n\n<p>Using F# this is my understanding of combinators:</p>\n\n<pre><code>let sum a b = a + b;; //sum function (lambda)\n</code></pre>\n\n<p>In the above case sum is a combinator because both <code>a</code> and <code>b</code> are bound to the function parameters.</p>\n\n<pre><code>let sum3 a b c = sum((sum a b) c);;\n</code></pre>\n\n<p>The above function is not a combinator as it uses <code>sum</code>, which is not a bound variable (i.e. it doesn't come from any of the parameters).</p>\n\n<p>We can make sum3 a combinator by simply passing the sum function as one of the parameters:</p>\n\n<pre><code>let sum3 a b c sumFunc = sumFunc((sumFunc a b) c);;\n</code></pre>\n\n<p>This way <code>sumFunc</code> is <strong>bound</strong> and hence the entire function is a combinator.</p>\n\n<p>So, this is my understanding of combinators. Their significance, on the other hand, still escapes me. As others pointed out, fixed point combinators allow one to express a recursive function without <code>explicit</code> recursion. I.e. instead of calling itself the recusrsive function calls lambda that is passed in as one of the arguments.</p>\n\n<p>Here is one of the most understandable combinator derivations that I found:</p>\n\n<p><a href=\"http://mvanier.livejournal.com/2897.html\" rel=\"noreferrer\">http://mvanier.livejournal.com/2897.html</a> </p>\n" }, { "answer_id": 2321000, "author": "interstar", "author_id": 8482, "author_profile": "https://Stackoverflow.com/users/8482", "pm_score": 2, "selected": false, "text": "<p>This looks a good one : <a href=\"http://www.catonmat.net/blog/derivation-of-ycombinator/\" rel=\"nofollow noreferrer\">http://www.catonmat.net/blog/derivation-of-ycombinator/</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ]
Anyone got a good explanation of "combinators" (Y-combinators etc. and **NOT** [the company](https://en.wikipedia.org/wiki/Y_Combinator_(company)))? I'm looking for one for the practical programmer who understands recursion and higher-order functions, but doesn't have a strong theory or math background. (Note: that I'm talking about [these things](https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus))
Unless you're deeply into theory, you can regard the Y combinator as a neat trick with functions, like monads. Monads allow you to chain actions, the Y combinator allows you to define self-recursive functions. Python has built-in support for self-recursive functions, so you can define them without Y: ``` > def fun(): > print "bla" > fun() > fun() bla bla bla ... ``` `fun` is accessible inside `fun` itself, so we can easily call it. *But what if Python were different, and `fun` weren't accessible inside `fun`?* ``` > def fun(): > print "bla" > # what to do here? (cannot call fun!) ``` The solution is to pass `fun` itself as an argument to `fun`: ``` > def fun(arg): # fun receives itself as argument > print "bla" > arg(arg) # to recur, fun calls itself, and passes itself along ``` And Y makes that possible: ``` > def Y(f): > f(f) > Y(fun) bla bla bla ... ``` All it does it call a function with itself as argument. (I don't know if this definition of Y is 100% correct, but I think it's the general idea.)
97,640
<p>How do I get my project's runtime dependencies copied into the <code>target/lib</code> folder? </p> <p>As it is right now, after <code>mvn clean install</code> the <code>target</code> folder contains only my project's jar, but none of the runtime dependencies.</p>
[ { "answer_id": 97748, "author": "Eduard Wirch", "author_id": 17428, "author_profile": "https://Stackoverflow.com/users/17428", "pm_score": 2, "selected": false, "text": "<p>If you make your project a war or ear type maven will copy the dependencies.</p>\n" }, { "answer_id": 97837, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 1, "selected": false, "text": "<p>You can use the the <a href=\"http://maven.apache.org/plugins/maven-shade-plugin/\" rel=\"nofollow noreferrer\">Shade Plugin</a> to create an uber jar in which you can bundle all your 3rd party dependencies.</p>\n" }, { "answer_id": 98190, "author": "Travis B. Hartwell", "author_id": 10873, "author_profile": "https://Stackoverflow.com/users/10873", "pm_score": 5, "selected": false, "text": "<p>Take a look at the <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/index.html\" rel=\"noreferrer\">Maven dependency plugin</a>, specifically, the <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/copy-dependencies-mojo.html\" rel=\"noreferrer\">dependency:copy-dependencies goal</a>. Take a look at <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/usage.html\" rel=\"noreferrer\">the example</a> under the heading <strong>The dependency:copy-dependencies mojo</strong>. Set the <strong>outputDirectory</strong> configuration property to ${basedir}/target/lib (I believe, you'll have to test).</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 98743, "author": "John Stauffer", "author_id": 5874, "author_profile": "https://Stackoverflow.com/users/5874", "pm_score": 7, "selected": false, "text": "<p>The best approach depends on what you want to do:</p>\n\n<ul>\n<li>If you want to bundle your dependencies into a WAR or EAR file, then simply set the packaging type of your project to EAR or WAR. Maven will bundle the dependencies into the right location.</li>\n<li>If you want to create a JAR file that includes your code along with all your dependencies, then use the <a href=\"http://maven.apache.org/plugins/maven-assembly-plugin/\" rel=\"noreferrer\" title=\"Maven2 Assembly Plugin Docs\">assembly</a> plugin with the <em>jar-with-dependencies</em> descriptor. Maven will generate a complete JAR file with all your classes plus the classes from any dependencies.</li>\n<li>If you want to simply pull your dependencies into the target directory interactively, then use the <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/\" rel=\"noreferrer\" title=\"Maven2 Dependency Plugin Docs\">dependency</a> plugin to copy your files in.</li>\n<li>If you want to pull in the dependencies for some other type of processing, then you will probably need to generate your own plugin. There are APIs to get the list of dependencies, and their location on disk. You will have to take it from there...</li>\n</ul>\n" }, { "answer_id": 996915, "author": "Georgy Bolyuba", "author_id": 4052, "author_profile": "https://Stackoverflow.com/users/4052", "pm_score": 8, "selected": false, "text": "<p>This works for me:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;project&gt;\n ...\n &lt;profiles&gt;\n &lt;profile&gt;\n &lt;id&gt;qa&lt;/id&gt;\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt;install&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;copy-dependencies&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;outputDirectory&gt;${project.build.directory}/lib&lt;/outputDirectory&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n &lt;/profile&gt;\n &lt;/profiles&gt;\n&lt;/project&gt;\n</code></pre>\n" }, { "answer_id": 1449651, "author": "Rich Seller", "author_id": 123582, "author_profile": "https://Stackoverflow.com/users/123582", "pm_score": 3, "selected": false, "text": "<p>If you want to deliver a bundle of your application jar, together with all its dependencies and some scripts to invoke the MainClass, look at the <a href=\"http://www.mojohaus.org/appassembler/appassembler-maven-plugin/\" rel=\"nofollow noreferrer\">appassembler-maven-plugin</a>.</p>\n\n<p>The following configuration will generate scripts for Window and Linux to launch the application (with a generated path referencing all the dependency jars, download all dependencies (into a lib folder below target/appassembler). The <a href=\"http://maven.apache.org/plugins/maven-assembly-plugin/\" rel=\"nofollow noreferrer\">assembly plugin</a> can then be used to package the whole appassembler directory to a zip which is installed/deployed along with the jar to the repository.</p>\n\n\n\n<pre class=\"lang-xml prettyprint-override\"><code> &lt;plugin&gt;\n &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;\n &lt;artifactId&gt;appassembler-maven-plugin&lt;/artifactId&gt;\n &lt;version&gt;1.0&lt;/version&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;id&gt;generate-jsw-scripts&lt;/id&gt;\n &lt;phase&gt;package&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;generate-daemons&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;!--declare the JSW config --&gt;\n &lt;daemons&gt;\n &lt;daemon&gt;\n &lt;id&gt;myApp&lt;/id&gt;\n &lt;mainClass&gt;name.seller.rich.MyMainClass&lt;/mainClass&gt;\n &lt;commandLineArguments&gt;\n &lt;commandLineArgument&gt;start&lt;/commandLineArgument&gt;\n &lt;/commandLineArguments&gt;\n &lt;platforms&gt;\n &lt;platform&gt;jsw&lt;/platform&gt;\n &lt;/platforms&gt; \n &lt;/daemon&gt;\n &lt;/daemons&gt;\n &lt;target&gt;${project.build.directory}/appassembler&lt;/target&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;execution&gt;\n &lt;id&gt;assemble-standalone&lt;/id&gt;\n &lt;phase&gt;integration-test&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;assemble&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;programs&gt;\n &lt;program&gt;\n &lt;mainClass&gt;name.seller.rich.MyMainClass&lt;/mainClass&gt;\n &lt;!-- the name of the bat/sh files to be generated --&gt;\n &lt;name&gt;mymain&lt;/name&gt;\n &lt;/program&gt;\n &lt;/programs&gt;\n &lt;platforms&gt;\n &lt;platform&gt;windows&lt;/platform&gt;\n &lt;platform&gt;unix&lt;/platform&gt;\n &lt;/platforms&gt;\n &lt;repositoryLayout&gt;flat&lt;/repositoryLayout&gt;\n &lt;repositoryName&gt;lib&lt;/repositoryName&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n &lt;plugin&gt;\n &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;\n &lt;version&gt;2.2-beta-4&lt;/version&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt;integration-test&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;single&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;descriptors&gt;\n &lt;descriptor&gt;src/main/assembly/archive.xml&lt;/descriptor&gt;\n &lt;/descriptors&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt; \n</code></pre>\n\n<p>The assembly descriptor (in src/main/assembly) to package the direcotry as a zip would be:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;assembly&gt;\n &lt;id&gt;archive&lt;/id&gt;\n &lt;formats&gt;\n &lt;format&gt;zip&lt;/format&gt;\n &lt;/formats&gt;\n &lt;fileSets&gt;\n &lt;fileSet&gt;\n &lt;directory&gt;${project.build.directory}/appassembler&lt;/directory&gt;\n &lt;outputDirectory&gt;/&lt;/outputDirectory&gt;\n &lt;/fileSet&gt;\n &lt;/fileSets&gt;\n&lt;/assembly&gt;\n</code></pre>\n" }, { "answer_id": 3769147, "author": "OleVV", "author_id": 455012, "author_profile": "https://Stackoverflow.com/users/455012", "pm_score": 1, "selected": false, "text": "<p>Just to spell out what has already been said in brief. I wanted to create an executable JAR file that included my dependencies along with my code. This worked for me:</p>\n\n<p>(1) In the pom, under &lt;build&gt;&lt;plugins&gt;, I included:</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;\n &lt;version&gt;2.2-beta-5&lt;/version&gt;\n &lt;configuration&gt;\n &lt;archive&gt;\n &lt;manifest&gt;\n &lt;mainClass&gt;dk.certifikat.oces2.some.package.MyMainClass&lt;/mainClass&gt;\n &lt;/manifest&gt;\n &lt;/archive&gt;\n &lt;descriptorRefs&gt;\n &lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;\n &lt;/descriptorRefs&gt;\n &lt;/configuration&gt;\n&lt;/plugin&gt;\n</code></pre>\n\n<p>(2) Running mvn compile assembly:assembly produced the desired my-project-0.1-SNAPSHOT-jar-with-dependencies.jar in the project's target directory.</p>\n\n<p>(3) I ran the JAR with java -jar my-project-0.1-SNAPSHOT-jar-with-dependencies.jar</p>\n" }, { "answer_id": 6034093, "author": "hemetsu", "author_id": 757763, "author_profile": "https://Stackoverflow.com/users/757763", "pm_score": 0, "selected": false, "text": "<p>If you're having problems related to dependencies not appearing in the WEB-INF/lib file when running on a Tomcat server in Eclipse, take a look at this:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4777026/classnotfoundexception-dispatcherservlet-when-launching-tomcat-maven-dependencie\">ClassNotFoundException DispatcherServlet when launching Tomcat (Maven dependencies not copied to wtpwebapps)</a></p>\n\n<p>You simply had to add the Maven Dependencies in Project Properties > Deployment Assembly.</p>\n" }, { "answer_id": 6536190, "author": "ruhsuzbaykus", "author_id": 453708, "author_profile": "https://Stackoverflow.com/users/453708", "pm_score": 5, "selected": false, "text": "<p>A simple and elegant solution for the case where one needs to copy the dependencies to a target directory without using any other phases of maven (I found this very useful when working with Vaadin).</p>\n\n<p>Complete pom example:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\"&gt;\n\n &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;\n &lt;groupId&gt;groupId&lt;/groupId&gt;\n &lt;artifactId&gt;artifactId&lt;/artifactId&gt;\n &lt;version&gt;1.0&lt;/version&gt;\n\n &lt;dependencies&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;org.mybatis&lt;/groupId&gt;\n &lt;artifactId&gt;mybatis-spring&lt;/artifactId&gt;\n &lt;version&gt;1.1.1&lt;/version&gt;\n &lt;/dependency&gt;\n &lt;/dependencies&gt;\n\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt;process-sources&lt;/phase&gt;\n\n &lt;goals&gt;\n &lt;goal&gt;copy-dependencies&lt;/goal&gt;\n &lt;/goals&gt;\n\n &lt;configuration&gt;\n &lt;outputDirectory&gt;${targetdirectory}&lt;/outputDirectory&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n&lt;/project&gt;\n</code></pre>\n\n<p>Then run <code>mvn process-sources</code></p>\n\n<p>The jar file dependencies can be found in <code>/target/dependency</code></p>\n" }, { "answer_id": 9087972, "author": "RubyTuesdayDONO", "author_id": 155090, "author_profile": "https://Stackoverflow.com/users/155090", "pm_score": 2, "selected": false, "text": "<p>It's a heavy solution for embedding heavy dependencies, but Maven's <a href=\"http://maven.apache.org/plugins/maven-assembly-plugin/index.html\" rel=\"nofollow noreferrer\">Assembly Plugin</a> does the trick for me. </p>\n\n<p>@<a href=\"https://stackoverflow.com/a/1449651/155090\">Rich Seller's answer</a> should work, although for simpler cases you should only need this excerpt from the <a href=\"http://maven.apache.org/plugins/maven-assembly-plugin/usage.html\" rel=\"nofollow noreferrer\">usage guide</a>: </p>\n\n<pre><code>&lt;project&gt;\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;\n &lt;version&gt;2.2.2&lt;/version&gt;\n &lt;configuration&gt;\n &lt;descriptorRefs&gt;\n &lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;\n &lt;/descriptorRefs&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n&lt;/project&gt;\n</code></pre>\n" }, { "answer_id": 10395558, "author": "adjablon", "author_id": 1075955, "author_profile": "https://Stackoverflow.com/users/1075955", "pm_score": 5, "selected": false, "text": "<p>Try something like this:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;plugin&gt;\n&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n&lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;\n&lt;version&gt;2.4&lt;/version&gt;\n&lt;configuration&gt;\n &lt;archive&gt;\n &lt;manifest&gt; \n &lt;addClasspath&gt;true&lt;/addClasspath&gt;\n &lt;classpathPrefix&gt;lib/&lt;/classpathPrefix&gt;\n &lt;mainClass&gt;MainClass&lt;/mainClass&gt;\n &lt;/manifest&gt;\n &lt;/archive&gt;\n &lt;/configuration&gt;\n&lt;/plugin&gt;\n&lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;\n &lt;version&gt;2.4&lt;/version&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;id&gt;copy&lt;/id&gt;\n &lt;phase&gt;install&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;copy-dependencies&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;outputDirectory&gt;\n ${project.build.directory}/lib\n &lt;/outputDirectory&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n&lt;/plugin&gt;\n</code></pre>\n" }, { "answer_id": 21641165, "author": "user3286149", "author_id": 3286149, "author_profile": "https://Stackoverflow.com/users/3286149", "pm_score": 7, "selected": false, "text": "<pre><code>mvn install dependency:copy-dependencies \n</code></pre>\n\n<p>Works for me with dependencies directory created in target folder. Like it!</p>\n" }, { "answer_id": 25441276, "author": "Duncan Jones", "author_id": 474189, "author_profile": "https://Stackoverflow.com/users/474189", "pm_score": 5, "selected": false, "text": "<p>If you want to do this on an occasional basis (and thus don't want to change your POM), try this command-line:</p>\n\n<pre>mvn dependency:copy-dependencies -DoutputDirectory=${project.build.directory}/lib</pre>\n\n<p>If you omit the <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/copy-dependencies-mojo.html#outputDirectory\" rel=\"noreferrer\">last argument</a>, the dependences are placed in <code>target/dependencies</code>.</p>\n" }, { "answer_id": 40784285, "author": "mambolis", "author_id": 676678, "author_profile": "https://Stackoverflow.com/users/676678", "pm_score": 3, "selected": false, "text": "<p>supposing</p>\n\n<ul>\n<li>you don't want to alter the pom.xml</li>\n<li>you don't want test scoped (e.g. junit.jar) or provided dependencies (e.g. wlfullclient.jar)</li>\n</ul>\n\n<p>here ist what worked for me:</p>\n\n<pre>\nmvn install dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/lib\n</pre>\n" }, { "answer_id": 47963667, "author": "isapir", "author_id": 968244, "author_profile": "https://Stackoverflow.com/users/968244", "pm_score": 5, "selected": false, "text": "<p>All you need is the following snippet inside pom.xml's <code>build/plugins</code>:</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt;prepare-package&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;copy-dependencies&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;outputDirectory&gt;${project.build.directory}/lib&lt;/outputDirectory&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n&lt;/plugin&gt;\n</code></pre>\n\n<p>The above will run in the <code>package</code> phase when you run </p>\n\n<pre><code>mvn clean package\n</code></pre>\n\n<p>And the dependencies will be copied to the outputDirectory specified in the snippet, i.e. <code>lib</code> in this case.</p>\n\n<p>If you only want to do that occasionally, then no changes to pom.xml are required. Simply run the following:</p>\n\n<pre><code>mvn clean package dependency:copy-dependencies\n</code></pre>\n\n<p>To override the default location, which is <code>${project.build.directory}/dependencies</code>, add a System property named <code>outputDirectory</code>, i.e.</p>\n\n<pre><code> -DoutputDirectory=${project.build.directory}/lib\n</code></pre>\n" }, { "answer_id": 70747872, "author": "Times", "author_id": 5151202, "author_profile": "https://Stackoverflow.com/users/5151202", "pm_score": 0, "selected": false, "text": "<p>You could place a <code>settings.xml</code> file in your project directory with a basic config like this:</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;\n&lt;settings xmlns=&quot;http://maven.apache.org/SETTINGS/1.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;\n xsi:schemaLocation=&quot;http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd&quot;&gt;\n &lt;localRepository&gt;.m2/repository&lt;/localRepository&gt;\n &lt;interactiveMode/&gt;\n &lt;offline/&gt;\n &lt;pluginGroups/&gt;\n &lt;servers/&gt;\n &lt;mirrors/&gt;\n &lt;proxies/&gt;\n &lt;profiles/&gt;\n &lt;activeProfiles/&gt;\n&lt;/settings&gt;\n</code></pre>\n<p>More information on these settings can be found in the official <a href=\"https://maven.apache.org/settings.html#simple-values\" rel=\"nofollow noreferrer\">Maven docs</a>.<br />\nNote that the path is resolved relative to the directory where the actual settings file resides in unless you enter an absolute path.</p>\n<p>When you execute maven commands you can use the settings file as follows:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>mvn -s settings.xml clean install\n</code></pre>\n<p>Side note: I use this in my GitLab CI/CD pipeline in order to being able to cache the maven repository for several jobs so that the dependencies don't need to be downloaded for every job execution. GitLab can only cache files or directories from your project directory and therefore I reference a directory wihtin my project directory.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18320/" ]
How do I get my project's runtime dependencies copied into the `target/lib` folder? As it is right now, after `mvn clean install` the `target` folder contains only my project's jar, but none of the runtime dependencies.
This works for me: ```xml <project> ... <profiles> <profile> <id>qa</id> <build> <plugins> <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <phase>install</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project> ```
97,663
<p>Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc.</p> <p>However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right.</p> <p>I click on Windows|Preferences and type in "wrap" and get:</p> <pre><code>- Java | Code Style | Formatter - Java | Editor | Typing - Web and XML | CSS Files | Source </code></pre> <p>I've tried changing the "wrap automatically" that I found there and the "Line width" to 72 but they had no effect.</p> <p>How can I get word wrap to work in Eclipse PDT for PHP files?</p>
[ { "answer_id": 97691, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 3, "selected": false, "text": "<p>It's a known enhancement request. <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=35779\" rel=\"noreferrer\">Bug 35779</a></p>\n" }, { "answer_id": 97802, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 7, "selected": true, "text": "<p>This has really been one of the most desired features in Eclipse. It's not just missing in PHP files-- it's missing in the IDE. Fortunately, from Google Summer of Code, we get this plug-in <a href=\"http://ahtik.com/blog/projects/eclipse-word-wrap/\" rel=\"noreferrer\">Eclipse Word-Wrap</a></p>\n\n<p>To install it, add the following update site in Eclipse:</p>\n\n<p><a href=\"http://ahtik.com/eclipse-update/\" rel=\"noreferrer\">AhtiK Eclipse WordWrap 0.0.5 Update Site</a></p>\n" }, { "answer_id": 15783091, "author": "Fedir RYKHTIK", "author_id": 634275, "author_profile": "https://Stackoverflow.com/users/634275", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://dev.cdhq.de/eclipse/word-wrap/\" rel=\"nofollow noreferrer\">Eclipse Word-Wrap Plug-In</a> by Florian Weßling works well in Eclispe PDT (3.0.2).</p>\n\n<p><strong>Installation and update sites</strong></p>\n\n<p><em>It is recommended to restart Eclipse with</em> <code>-clean</code> <em>option immediately after installation.</em></p>\n\n<p>Eclipse Indigo 3.7: <a href=\"http://dev.cdhq.de/eclipse/updatesite/indigo/\" rel=\"nofollow noreferrer\">http://dev.cdhq.de/eclipse/updatesite/indigo/</a><br>\nEclipse Juno 4.2: <a href=\"http://dev.cdhq.de/eclipse/updatesite/juno/\" rel=\"nofollow noreferrer\">http://dev.cdhq.de/eclipse/updatesite/juno/</a><br>\nEclipse Kepler 4.3: <a href=\"http://dev.cdhq.de/eclipse/updatesite/kepler/\" rel=\"nofollow noreferrer\">http://dev.cdhq.de/eclipse/updatesite/kepler/</a><br>\nEclipse Luna 4.4: <a href=\"http://dev.cdhq.de/eclipse/updatesite/luna/\" rel=\"nofollow noreferrer\">http://dev.cdhq.de/eclipse/updatesite/luna/</a><br>\nEclipse Mars 4.5: <a href=\"http://dev.cdhq.de/eclipse/updatesite/mars/\" rel=\"nofollow noreferrer\">http://dev.cdhq.de/eclipse/updatesite/mars/</a><br>\nEclipse Neon 4.6: Plugin not necessary.* Just press <kbd>Alt</kbd>-<kbd>Shift</kbd>-<kbd>Y</kbd> :) </p>\n\n<p><sup>* See <a href=\"https://stackoverflow.com/a/37103016/1134080\">KrisWebDev's answer</a> for more details and how to make word wrap permanent.</sup></p>\n\n<p><strong>Usage</strong></p>\n\n<p>After the installation of the plugin:</p>\n\n<ul>\n<li>Context menu: <em>Right click</em> > <em>Toggle Word Wrap</em></li>\n<li>Menu bar: <em>Edit</em> > <em>Toggle Word Wrap</em></li>\n<li>Keyboard shortcut: <kbd>Ctrl</kbd>-<kbd>Alt</kbd>-<kbd>E</kbd></li>\n<li>Also you may: <em>Edit</em> > <em>Activate Word Wrap in all open Editors</em></li>\n</ul>\n\n<p>There is no dedicated indicator for the current status of the word wrap setting, but you can check the horizontal scroll bar in the Editor.</p>\n\n<ul>\n<li>Horizontal scroll bar is visible: Word wrap is disabled.</li>\n<li>Horizontal scroll bar is absent: Word wrap is enabled.</li>\n</ul>\n" }, { "answer_id": 37103016, "author": "KrisWebDev", "author_id": 2227298, "author_profile": "https://Stackoverflow.com/users/2227298", "pm_score": 3, "selected": false, "text": "<p>Finally something that works in 2016 with <strong>native support</strong>!</p>\n\n<p>You want the latest and newer <strong>NEON</strong> version of Eclipse since <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=35779\" rel=\"noreferrer\">Bug 35779</a> is finally patched:</p>\n\n<ul>\n<li>Use the <a href=\"https://eclipse.org/downloads/index.php?show_instructions=TRUE\" rel=\"noreferrer\">Eclipse installer</a></li>\n<li>Click on the top right \"menu\" icon and choose <code>ADVANCED MODE</code></li>\n<li>Select <code>Eclipse IDE for PHP Developers</code> with <em>Product Version</em>: <code>Latest</code></li>\n<li>Next ... Next, Finish</li>\n</ul>\n\n<p>Now you can toogle wordwrap manually using <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>Y</kbd> for EACH file! Boring!</p>\n\n<p>So if you're lucky, there's supposed to be a <a href=\"https://bugs.eclipse.org/bugs/attachment.cgi?id=257691\" rel=\"noreferrer\">nice global setting</a> lost in <code>Window</code> > <code>Preferences</code> > <code>General</code> > <code>Editors</code> > <code>Text Editors</code> > <code>Enable Wordwrap</code> but no, that's a trap, there's no GUI setting! At least at the time of writing.</p>\n\n<p>So I've found the hard way to set it <strong>globally</strong> (by default):</p>\n\n<ol>\n<li><p>Close Eclipse</p></li>\n<li><p>Find <code>org.eclipse.ui.editors.prefs</code> Eclipse settings file:</p>\n\n<p><code>find ~ -name org.eclipse.ui.editors.prefs -printf \"%p %TY-%Tm-%Td %TH:%TM:%TS\\n\"</code></p></li>\n</ol>\n\n<p>If you're on a platform like macOS where the above command doesn't work, you can find the settings file in your current workspace folder under <code>.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.editors.prefs</code>.</p>\n\n<ol start=\"3\">\n<li><p>Add:</p>\n\n<p><code>wordwrap.enabled=true</code></p></li>\n</ol>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc. However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right. I click on Windows|Preferences and type in "wrap" and get: ``` - Java | Code Style | Formatter - Java | Editor | Typing - Web and XML | CSS Files | Source ``` I've tried changing the "wrap automatically" that I found there and the "Line width" to 72 but they had no effect. How can I get word wrap to work in Eclipse PDT for PHP files?
This has really been one of the most desired features in Eclipse. It's not just missing in PHP files-- it's missing in the IDE. Fortunately, from Google Summer of Code, we get this plug-in [Eclipse Word-Wrap](http://ahtik.com/blog/projects/eclipse-word-wrap/) To install it, add the following update site in Eclipse: [AhtiK Eclipse WordWrap 0.0.5 Update Site](http://ahtik.com/eclipse-update/)
97,683
<p>Here is a snippet of CSS that I need explained:</p> <pre class="lang-css prettyprint-override"><code>#section { width: 860px; background: url(/blah.png); position: absolute; top: 0; left: 50%; margin-left: -445px; } </code></pre> <p>Ok so it's absolute positioning of an image, obviously.</p> <ol> <li>top is like padding from the top, right?</li> <li>what does left 50% do?</li> <li>why is the left margin at -445px? </li> </ol> <p><b>Update:</b> width is 860px. The actual image is 100x100 if that makes a difference??</p>
[ { "answer_id": 97702, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "<p>When position is absolute, top is vertical distance from the parent (probably the body tag, so 0 is the top edge of the browser window). Left 50% is distance from the left edge. The negative margin moves it back left 445px. As to why, your guess is as good as mine.</p>\n" }, { "answer_id": 97716, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>top is like padding from the top right?</p>\n</blockquote>\n\n<p>Yes, the top of the page.</p>\n\n<blockquote>\n <p>what does left 50% do?</p>\n</blockquote>\n\n<p>It moves the content to the center of the screen (100% would be all the way to the right.)</p>\n\n<blockquote>\n <p>why is the left margin at -445px?</p>\n</blockquote>\n\n<p>After moving it with \"left: 50%\", this moves it 445 pixels back to the left.</p>\n" }, { "answer_id": 97717, "author": "Ed Brown", "author_id": 16924, "author_profile": "https://Stackoverflow.com/users/16924", "pm_score": 1, "selected": false, "text": "<p>You'll find out every thing you need to know by reading up on the <a href=\"http://www.w3.org/TR/CSS2/box.html\" rel=\"nofollow noreferrer\">CSS box model</a></p>\n" }, { "answer_id": 97747, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 3, "selected": true, "text": "<ol>\n<li><p>Top is the distance from the top of the html element or, if this is within another element with absolute position, from the top of that.</p></li>\n<li><p>&amp; 3. It depends on the width of the image but it might be for centering the image horizontally (if the width of the image is 890px). There are other ways to center an image horizontally though. More commonly, this is used to center a block of known height vertically (this is the easiest way to center something of known height vertically):</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>top: 50%\nmargin-top: -(height/2)px;\n</code></pre></li>\n</ol>\n" }, { "answer_id": 97761, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>This has probably been done in order to center the element on the page (using the <a href=\"http://www.wpdfd.com/editorial/thebox/deadcentre4.html\" rel=\"nofollow noreferrer\">\"dead center\"</a> technique).</p>\n\n<p>It works like this: Assuming the element is 890px wide, it's set to <code>position:absolute</code> and <code>left:50%</code>, which places its <strong>left-hand edge</strong> in the <strong>center</strong> of the browser (well, it could be the center of some other element with <code>position:relative</code>).</p>\n\n<p>Then the negative margin is used to <strong>move the left hand edge</strong> to the left a distance equal to <strong>half the element's width</strong>, thus centering it.</p>\n\n<p>of course, this may not be centering it exactly (it depends how wide the element actually is, there's no <code>width</code> in the code you pasted, so it's impossible to be sure) but it's certainly placing the element in relation to the center of the page</p>\n" }, { "answer_id": 97786, "author": "BrewinBombers", "author_id": 5989, "author_profile": "https://Stackoverflow.com/users/5989", "pm_score": 2, "selected": false, "text": "<p>The snippet above relates to an element (could be a div, span, image or otherwise) with an id of section. </p>\n\n<p>The element has a background image of blah.png which will repeat in both x and y directions.</p>\n\n<p>The top edge of the element will be positioned 0px (or any other units) from the top of it's parent element if the parent is also absolutely positioned. If the parent is the window, it will be at the top edge of the browser window.</p>\n\n<p>The element will have it's left edge positioned 50% from the left of it's parent element's left edge.</p>\n\n<p>The element will then be \"moved\" 445px left from that 50% point.</p>\n" }, { "answer_id": 34800233, "author": "John Schwartz", "author_id": 5780248, "author_profile": "https://Stackoverflow.com/users/5780248", "pm_score": 0, "selected": false, "text": "<p>At the risk of sounding like Captain Obvious, I'll try explaining it as simply as possible.</p>\n\n<p>Top is a number that determines the number of pixels you want it to be FROM the top of whatever html element is above it... so not necessarily the top of your page. Be wary of your html formatting as you design your css.</p>\n\n<p>Your left to 50% should move it to the center of your screen, given that it's 50. Keep in mind people have different screen sizes and is allocated to the (0,0) top left of your image, not the center of the image, so it will not be perfectly allocated to the center of one's screen like you may expect it to.</p>\n\n<p>THIS is why the margin-left to -445 pixels is used-- to move it further over, fixed. </p>\n\n<p>Good luck, I hope that this made sense. I was trying to word my explanation differently in case other answers were still giving you a hard time. They were great answers as well. </p>\n\n<p>(If you have two different sized monitors, I suggest toying around the with the code to see how each modification affects different sized screens!)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
Here is a snippet of CSS that I need explained: ```css #section { width: 860px; background: url(/blah.png); position: absolute; top: 0; left: 50%; margin-left: -445px; } ``` Ok so it's absolute positioning of an image, obviously. 1. top is like padding from the top, right? 2. what does left 50% do? 3. why is the left margin at -445px? **Update:** width is 860px. The actual image is 100x100 if that makes a difference??
1. Top is the distance from the top of the html element or, if this is within another element with absolute position, from the top of that. 2. & 3. It depends on the width of the image but it might be for centering the image horizontally (if the width of the image is 890px). There are other ways to center an image horizontally though. More commonly, this is used to center a block of known height vertically (this is the easiest way to center something of known height vertically): ```css top: 50% margin-top: -(height/2)px; ```
97,694
<p>I've been somewhat spoiled using Eclipse and java. I started using vim to do C coding in a linux environment, is there a way to have vim automatically do the proper spacing for blocks? </p> <p>So after typing a { the next line will have 2 spaces indented in, and a return on that line will keep it at the same indentation, and a } will shift back 2 spaces?</p>
[ { "answer_id": 97720, "author": "Craig B.", "author_id": 10780, "author_profile": "https://Stackoverflow.com/users/10780", "pm_score": -1, "selected": false, "text": "<p>Try:</p>\n\n<p>set sw=2</p>\n\n<p>set ts=2</p>\n\n<p>set smartindent</p>\n" }, { "answer_id": 97723, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 8, "selected": true, "text": "<p>These two commands should do it:</p>\n\n<pre><code>:set autoindent\n:set cindent\n</code></pre>\n\n<p>For bonus points put them in a file named .vimrc located in your home directory on linux</p>\n" }, { "answer_id": 97775, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 6, "selected": false, "text": "<p>I <a href=\"http://tedlogan.com/techblog3.html\" rel=\"noreferrer\">wrote all about tabs in vim</a>, which gives a few interesting things you didn't ask about. To automatically indent braces, use:</p>\n\n<pre><code>:set cindent\n</code></pre>\n\n<p>To indent two spaces (instead of one tab of eight spaces, the vim default):</p>\n\n<pre><code>:set shiftwidth=2\n</code></pre>\n\n<p>To keep vim from converting eight spaces into tabs:</p>\n\n<pre><code>:set expandtab\n</code></pre>\n\n<p>If you ever want to change the indentation of a block of text, use &lt; and &gt;. I usually use this in conjunction with block-select mode (v, select a block of text, &lt; or &gt;).</p>\n\n<p>(I'd try to talk you out of using two-space indentation, since I (and most other people) find it hard to read, but that's another discussion.)</p>\n" }, { "answer_id": 97878, "author": "mike511", "author_id": 9593, "author_profile": "https://Stackoverflow.com/users/9593", "pm_score": 0, "selected": false, "text": "<p>and always remember this venerable explanation of Spaces + Tabs:</p>\n\n<p><a href=\"http://www.jwz.org/doc/tabs-vs-spaces.html\" rel=\"nofollow noreferrer\">http://www.jwz.org/doc/tabs-vs-spaces.html</a></p>\n" }, { "answer_id": 98367, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 3, "selected": false, "text": "<p>A lot of vim's features (like <code>autoindent</code> and <code>cindent</code>) are turned off by default. To really see what vim can do for you, you need a decent <code>~/.vimrc</code>.</p>\n\n<p>A good starter one is in <code>$VIMRUNTIME/vimrc_example.vim</code>. If you want to try it out, use</p>\n\n<pre><code>:source $VIMRUNTIME/vimrc_example.vim\n</code></pre>\n\n<p>when in vim. </p>\n\n<p>I'd actually suggest just copying the contents to your <code>~/.vimrc</code> as it's well commented, and a good place to start learning how to use vim. You can do this by</p>\n\n<pre><code>:e $VIMRUNTIME/vimrc_example.vim\n:w! ~/.vimrc\n</code></pre>\n\n<p>This will overwrite your current <code>~/.vimrc</code>, but if all you have in there is the indent settings Davr suggested, I wouldn't sweat it, as the example vimrc will take care of that for you as well. For a complete walkthrough of the example, and what it does for you, see <code>:help vimrc-intro</code>.</p>\n" }, { "answer_id": 2657596, "author": "JamesM-SiteGen", "author_id": 407348, "author_profile": "https://Stackoverflow.com/users/407348", "pm_score": 3, "selected": false, "text": "<h2>Simply run:</h2>\n\n<pre><code>user@host:~ $ echo set autoindent &gt;&gt; .vimrc\n</code></pre>\n" }, { "answer_id": 6433602, "author": "user809472", "author_id": 809472, "author_profile": "https://Stackoverflow.com/users/809472", "pm_score": 3, "selected": false, "text": "<p>I think the best answer is actually explained on the vim wikia:</p>\n\n<p><a href=\"http://vim.wikia.com/wiki/Indenting_source_code\" rel=\"noreferrer\">http://vim.wikia.com/wiki/Indenting_source_code</a></p>\n\n<p>Note that it advises against using \"set autoindent.\" The best feature of all I find in this explanation is being able to set per-file settings, which is especially useful if you program in python and C++, for example, as you'd want 4 spaces for tabs in the former and 2 for spaces in the latter.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
I've been somewhat spoiled using Eclipse and java. I started using vim to do C coding in a linux environment, is there a way to have vim automatically do the proper spacing for blocks? So after typing a { the next line will have 2 spaces indented in, and a return on that line will keep it at the same indentation, and a } will shift back 2 spaces?
These two commands should do it: ``` :set autoindent :set cindent ``` For bonus points put them in a file named .vimrc located in your home directory on linux
97,733
<p>I'm working with PostSharp to intercept method calls to objects I don't own, but my aspect code doesn't appear to be getting called. The documentation seems pretty lax in the Silverlight area, so I'd appreciate any help you guys can offer :)</p> <p>I have an attribute that looks like:</p> <pre><code>public class LogAttribute : OnMethodInvocationAspect { public override void OnInvocation(MethodInvocationEventArgs eventArgs) { // Logging code goes here... } } </code></pre> <p>And an entry in my AssemblyInfo that looks like:</p> <pre><code>[assembly: Log(AttributeTargetAssemblies = "System.Windows", AttributeTargetTypes = "System.Windows.Controls.*")] </code></pre> <p>So, my question to you is... what am I missing? Method calls under matching attribute targets don't appear to function.</p>
[ { "answer_id": 97773, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>I believe if you change AttributeTargetAssemblies to \"PresentationFramework\", it might work. (Don't have PostSharp down that well yet).</p>\n\n<p>The Assembly for WPF is PresentationFramework.dll. The AttributeTargetAssemblies needs the dll that it should target.</p>\n" }, { "answer_id": 98968, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 0, "selected": false, "text": "<p>If you're trying to intercept calls within the framework (i.e., not in your own code), it won't work. PostSharp can only replace code within your own assembly.\nIf you're trying to intercept calls you're making, then it looks like it should work. Do you see PostSharp running in the build output?</p>\n" }, { "answer_id": 644495, "author": "Bryan Bailliache", "author_id": 74782, "author_profile": "https://Stackoverflow.com/users/74782", "pm_score": 1, "selected": false, "text": "<p>PostSharp has a new version, which is accessed from the Downloads page link to \"All Downloads\". </p>\n\n<p><a href=\"http://www.postsharp.org/all-downloads/postsharp-1.5\" rel=\"nofollow noreferrer\">PostSharp 1.5</a>\nThe development branch of PostSharp including new features like support for Mono, Compact Framework or Silverlight, and aspect inheritance. Download from this branch if you want to try new features and help the community by testing new developments, and can accept inferior reliability and stability of APIes.</p>\n\n<p>The version is currently at 1.5 CTP 3 but it has support for Silverlight.</p>\n" }, { "answer_id": 649844, "author": "John Feminella", "author_id": 75170, "author_profile": "https://Stackoverflow.com/users/75170", "pm_score": 3, "selected": true, "text": "<p><strong>This is not possible with the present version of PostSharp.</strong></p>\n<p>PostSharp works by transforming assemblies prior to being loaded by the CLR. Right now, in order to do that, two things have to happen:</p>\n<ul>\n<li>The assembly must be about to be loaded into the CLR; you only get one shot, and you have to take it at this point.</li>\n<li>After the transformation stage has finished, you can't make any additional modifications. That means you can't modify the assembly at runtime.</li>\n</ul>\n<p>The newest version, 1.5 CTP 3, <a href=\"http://www.postsharp.org/blog/announcing-postsharp-1.5-ctp-3\" rel=\"nofollow noreferrer\">removes the first of these two limitations</a>, but it is the second that's really the problem. This is, however, <a href=\"http://www.postsharp.org/blog/using-postsharp-at-runtime\" rel=\"nofollow noreferrer\">a heavily requested feature</a>, so keep your eyes peeled:</p>\n<blockquote>\n<p>Users often ask if it is possible to use PostSharp at runtime, so aspects don't have to be known at compile time. Changing aspects after deployment is indeed a great advantage, since it allow support staff to enable/disable tracing or performance monitoring for individual parts of the software. <strong>One of the cool things it would enable is to apply aspects on third-party assemblies.</strong></p>\n<p>If you ask whether it is possible, the short answer is yes! <strong>Unfortunately, the long answer is more complex.</strong></p>\n</blockquote>\n<h3>Runtime/third-party aspect gotchas</h3>\n<p>The author also proceeds to outline some of the problems that happen if you allow modification at runtime:</p>\n<blockquote>\n<p>So now, what are the gotchas?</p>\n<ul>\n<li><strong>Plugging the bootstrapper.</strong> If your code is hosted (for instance in\nASP.NET or in a COM server), you\ncannot plug the bootstrapper. So any\nruntime weaving technology is bound to\nthe limitation that you should host\nthe application yourself.</li>\n<li><strong>Be Before the CLR.</strong> If the CLR finds the untransformed assembly by its own,\nit will not ask for the transformed\none. So you may need to create a new\napplication domain for the transformed\napplication, and put transformed\nassemblies in its binary path. It's\nmaybe not a big problem.</li>\n<li><strong>Strong names.</strong> Ough. If you modify an assembly at runtime, you will have to\nremove its strong name. Will it work?\nYes, mostly. Of course, you have to\nremove the strong names from all\nreferences to this assembly. That's\nnot a problem; PostSharp supports it\nout-of-the-box. But there is something\nPostSharp cannot help with: if there\nare some strongly named references in\nstrings or files (for instance in\napp.config), we can hardly find them\nand transform them. So here we have a\nreal limitation: there cannot be\n&quot;loose references&quot; to strongly named\nassemblies: we are only able to\ntransform real references.</li>\n<li><strong>LoadFrom.</strong> If any assembly uses Assembly.LoadFrom, Assembly.LoadFile\nor Assembly.LoadBytes, our\nbootstrapper is skipped.</li>\n</ul>\n</blockquote>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473493/" ]
I'm working with PostSharp to intercept method calls to objects I don't own, but my aspect code doesn't appear to be getting called. The documentation seems pretty lax in the Silverlight area, so I'd appreciate any help you guys can offer :) I have an attribute that looks like: ``` public class LogAttribute : OnMethodInvocationAspect { public override void OnInvocation(MethodInvocationEventArgs eventArgs) { // Logging code goes here... } } ``` And an entry in my AssemblyInfo that looks like: ``` [assembly: Log(AttributeTargetAssemblies = "System.Windows", AttributeTargetTypes = "System.Windows.Controls.*")] ``` So, my question to you is... what am I missing? Method calls under matching attribute targets don't appear to function.
**This is not possible with the present version of PostSharp.** PostSharp works by transforming assemblies prior to being loaded by the CLR. Right now, in order to do that, two things have to happen: * The assembly must be about to be loaded into the CLR; you only get one shot, and you have to take it at this point. * After the transformation stage has finished, you can't make any additional modifications. That means you can't modify the assembly at runtime. The newest version, 1.5 CTP 3, [removes the first of these two limitations](http://www.postsharp.org/blog/announcing-postsharp-1.5-ctp-3), but it is the second that's really the problem. This is, however, [a heavily requested feature](http://www.postsharp.org/blog/using-postsharp-at-runtime), so keep your eyes peeled: > > Users often ask if it is possible to use PostSharp at runtime, so aspects don't have to be known at compile time. Changing aspects after deployment is indeed a great advantage, since it allow support staff to enable/disable tracing or performance monitoring for individual parts of the software. **One of the cool things it would enable is to apply aspects on third-party assemblies.** > > > If you ask whether it is possible, the short answer is yes! **Unfortunately, the long answer is more complex.** > > > ### Runtime/third-party aspect gotchas The author also proceeds to outline some of the problems that happen if you allow modification at runtime: > > So now, what are the gotchas? > > > * **Plugging the bootstrapper.** If your code is hosted (for instance in > ASP.NET or in a COM server), you > cannot plug the bootstrapper. So any > runtime weaving technology is bound to > the limitation that you should host > the application yourself. > * **Be Before the CLR.** If the CLR finds the untransformed assembly by its own, > it will not ask for the transformed > one. So you may need to create a new > application domain for the transformed > application, and put transformed > assemblies in its binary path. It's > maybe not a big problem. > * **Strong names.** Ough. If you modify an assembly at runtime, you will have to > remove its strong name. Will it work? > Yes, mostly. Of course, you have to > remove the strong names from all > references to this assembly. That's > not a problem; PostSharp supports it > out-of-the-box. But there is something > PostSharp cannot help with: if there > are some strongly named references in > strings or files (for instance in > app.config), we can hardly find them > and transform them. So here we have a > real limitation: there cannot be > "loose references" to strongly named > assemblies: we are only able to > transform real references. > * **LoadFrom.** If any assembly uses Assembly.LoadFrom, Assembly.LoadFile > or Assembly.LoadBytes, our > bootstrapper is skipped. > > >
97,762
<p>I have a collection of non-overlapping rectangles that cover an enclosing rectangle. What is the best way to find the containing rectangle for a mouse click?</p> <p>The obvious answer is to have an array of rectangles and to search them in sequence, making the search O(n). Is there some way to order them by position so that the algorithm is less than O(n), say, O(log n) or O(sqrt(n))?</p>
[ { "answer_id": 97783, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 0, "selected": false, "text": "<p>Shove them in a <a href=\"http://en.wikipedia.org/wiki/Quadtree\" rel=\"nofollow noreferrer\">quadtree</a>.</p>\n" }, { "answer_id": 97798, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 0, "selected": false, "text": "<p>Use a <a href=\"http://en.wikipedia.org/wiki/Binary_space_partitioning\" rel=\"nofollow noreferrer\">BSP</a> tree to store the rectangles.</p>\n" }, { "answer_id": 97806, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 4, "selected": true, "text": "<p>You can organize your rectangles in a quad or kd-tree. That gives you O(log n). That's the mainstream method.</p>\n\n<p>Another interesting data-structure for this problem are R-trees. These can be very efficient if you have to deal with lots of rectangles.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/R-tree\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/R-tree</a></p>\n\n<p>And then there is the O(1) method of simply generating a bitmap at the same size as your screen, fill it with a place-holder for \"no rectangle\" and draw the hit-rectangle indices into that bitmap. A lookup becomes as simple as:</p>\n\n<pre><code> int id = bitmap_getpixel (mouse.x, mouse.y)\n if (id != -1)\n {\n hit_rectange (id);\n }\n else\n {\n no_hit();\n }\n</code></pre>\n\n<p>Obviously that method only works well if your rectangles don't change that often and if you can spare the memory for the bitmap.</p>\n" }, { "answer_id": 97822, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 1, "selected": false, "text": "<p>Create an Interval Tree. Query the Interval Tree. Consult 'Algorithms' from MIT press.</p>\n\n<p>An Interval Tree is best implemented as a Red-Black Tree.</p>\n\n<p>Keep in mind that it is only advisable to sort your rectangles if you are going to be clicking at them more then you are changing their positions, usually.</p>\n\n<p>You'll have to keep in mind, that you have build build your indices for different axis separately. E.g., you have to see if you overlap an interval on X and on Y. One obvious optimization is to only check for overlap on either X interval, then immediately check for overlap on Y.</p>\n\n<p>Also, most stock or 'classbook' Interval Trees only check for a single interval, and only return a single Interval (but you said \"non-overlapping\" didn't you?)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10293/" ]
I have a collection of non-overlapping rectangles that cover an enclosing rectangle. What is the best way to find the containing rectangle for a mouse click? The obvious answer is to have an array of rectangles and to search them in sequence, making the search O(n). Is there some way to order them by position so that the algorithm is less than O(n), say, O(log n) or O(sqrt(n))?
You can organize your rectangles in a quad or kd-tree. That gives you O(log n). That's the mainstream method. Another interesting data-structure for this problem are R-trees. These can be very efficient if you have to deal with lots of rectangles. <http://en.wikipedia.org/wiki/R-tree> And then there is the O(1) method of simply generating a bitmap at the same size as your screen, fill it with a place-holder for "no rectangle" and draw the hit-rectangle indices into that bitmap. A lookup becomes as simple as: ``` int id = bitmap_getpixel (mouse.x, mouse.y) if (id != -1) { hit_rectange (id); } else { no_hit(); } ``` Obviously that method only works well if your rectangles don't change that often and if you can spare the memory for the bitmap.
97,781
<p>Part of a new product I have been assigned to work on involves server-side conversion of the 'common' video formats to something that Flash can play.</p> <p>As far as I know, my only option is to convert to FLV. I have been giving ffmpeg a go around, but I'm finding a few WMV files that come out with garbled sound (I've tried playing with the audio rates).</p> <p>Are there any other 'good' CLI converters for Linux? Or are there other video formats that Flash can play?</p>
[ { "answer_id": 97799, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 5, "selected": true, "text": "<p>Flash can play the following formats:</p>\n\n<pre><code>FLV with AAC or MP3 audio, and FLV1 (Sorenson Spark H.263), VP6, or H.264 video.\nMP4 with AAC or MP3 audio, and H.264 video (mp4s must be hinted with qt-faststart or mp4box).\n</code></pre>\n\n<p>ffmpeg is an overall good conversion utility; mencoder works better with obscure and proprietary formats (due to the w32codecs binary decoder package) but its muxing is rather suboptimal (read: often totally broken). One solution might be to encode H.264 with x264 through mencoder, and then mux separately with mp4box.</p>\n\n<p>As a developer of x264 (and avid user of flash for online video playback), I've had quite a bit of experience in this kind of stuff, so if you want more assistance I'm also available on Freenode IRC on #x264, #ffmpeg, and #mplayer.</p>\n" }, { "answer_id": 97846, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 2, "selected": false, "text": "<p>Most encoders, by default (ffmpeg included) put the header atom of the mp4 (the \"moov atom\") at the end of the video, since they can't place the header until they're done encoding. However, in order for the file to start playback before its done downloading, the moov atom has to be moved to the front.</p>\n\n<p>To do this, you have to (re)mux using mp4box (which does it by default) or use qt-faststart, a script for ffmpeg that simply moves the atom to the front. Its quite simple.</p>\n\n<p>Note that for FLV, by default, ffmpeg will use the FLV1 video format, which is pretty terrible; its over a decade old by this point and its efficiency is rather awful given modern standards. You're much better off using a more modern format like H.264.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2192/" ]
Part of a new product I have been assigned to work on involves server-side conversion of the 'common' video formats to something that Flash can play. As far as I know, my only option is to convert to FLV. I have been giving ffmpeg a go around, but I'm finding a few WMV files that come out with garbled sound (I've tried playing with the audio rates). Are there any other 'good' CLI converters for Linux? Or are there other video formats that Flash can play?
Flash can play the following formats: ``` FLV with AAC or MP3 audio, and FLV1 (Sorenson Spark H.263), VP6, or H.264 video. MP4 with AAC or MP3 audio, and H.264 video (mp4s must be hinted with qt-faststart or mp4box). ``` ffmpeg is an overall good conversion utility; mencoder works better with obscure and proprietary formats (due to the w32codecs binary decoder package) but its muxing is rather suboptimal (read: often totally broken). One solution might be to encode H.264 with x264 through mencoder, and then mux separately with mp4box. As a developer of x264 (and avid user of flash for online video playback), I've had quite a bit of experience in this kind of stuff, so if you want more assistance I'm also available on Freenode IRC on #x264, #ffmpeg, and #mplayer.
97,840
<p>I'm trying to configure a dedicated server that runs ASP.NET to send mail through the local IIS SMTP server but mail is getting stuck in the Queue folder and doesn't get delivered.</p> <p>I'm using this code in an .aspx page to test:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" %&gt; &lt;% new System.Net.Mail.SmtpClient("localhost").Send("[email protected]", "[email protected]", "testing...", "Hello, world.com"); %&gt; </code></pre> <p>Then, I added the following to the Web.config file:</p> <pre><code>&lt;system.net&gt; &lt;mailSettings&gt; &lt;smtp&gt; &lt;network host="localhost"/&gt; &lt;/smtp&gt; &lt;/mailSettings&gt; &lt;/system.net&gt; </code></pre> <p>In the IIS Manager I've changed the following in the properties of the "Default SMTP Virtual Server".</p> <pre><code>General: [X] Enable Logging Access / Authentication: [X] Windows Integrated Authentication Access / Relay Restrictions: (o) Only the list below, Granted 127.0.0.1 Delivery / Advanced: Fully qualified domain name = thedomain.com </code></pre> <p>Finally, I run the SMTPDiag.exe tool like this:</p> <pre><code>C:\&gt;smtpdiag.exe [email protected] [email protected] Searching for Exchange external DNS settings. Computer name is THEDOMAIN. Failed to connect to the domain controller. Error: 8007054b Checking SOA for gmail.com. Checking external DNS servers. Checking internal DNS servers. SOA serial number match: Passed. Checking local domain records. Checking MX records using TCP: thedomain.com. Checking MX records using UDP: thedomain.com. Both TCP and UDP queries succeeded. Local DNS test passed. Checking remote domain records. Checking MX records using TCP: gmail.com. Checking MX records using UDP: gmail.com. Both TCP and UDP queries succeeded. Remote DNS test passed. Checking MX servers listed for [email protected]. Connecting to gmail-smtp-in.l.google.com [209.85.199.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to gmail-smtp-in.l.google.com [209.85.199.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to gsmtp183.google.com [64.233.183.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gsmtp183.google.com. Connecting to gsmtp147.google.com [209.85.147.27] on port 25. Connecting to the server failed. Error: 10051 Failed to submit mail to gsmtp147.google.com. </code></pre> <p>I'm using ASP.NET 2.0, Windows 2003 Server and the IIS that comes with it.</p> <p>Can you tell me what else to change to fix the problem?</p> <p>Thanks</p> <hr> <p>@mattlant</p> <p>This is a dedicated server that's why I'm installing the SMTP manually.</p> <blockquote> <p>EDIT: I use exchange so its a little different, but its called a smart host in exchange, but in plain SMTP service config i think its called something else. Cant remember exactly the setting name.</p> </blockquote> <p>Thank you for pointing me at the Smart host field. Mail is getting delivered now.</p> <p>In the Default SMTP Virtual Server properties, the Delivery tab, click Advanced and fill the "Smart host" field with the address that your provider gives you. In my case (GoDaddy) it was k2smtpout.secureserver.net.</p> <p>More info here: <a href="http://help.godaddy.com/article/1283" rel="nofollow noreferrer">http://help.godaddy.com/article/1283</a></p>
[ { "answer_id": 97854, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 3, "selected": true, "text": "<p>I find the best thing usually depending on how much email there is, is to just forward the mail through your ISP's SMTP server. Less headaches. Looks like that's where you are having issues, from your SMTP to external servers, not asp.net to your SMTP.</p>\n\n<p>Just have your SMTP server set to send it to your ISP, or you can configure asp.net to send to it.</p>\n\n<p>EDIT: I use exchange so it's a little different, but it's called a smart host in exchange, but in plain SMTP service config I think it's called something else. </p>\n\n<p>I can't remember exactly the setting name.</p>\n" }, { "answer_id": 97923, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 0, "selected": false, "text": "<p>By the looks of things your firewall isn't letting SMTP (TCP port 25) out of your network.</p>\n" }, { "answer_id": 97926, "author": "DKATDT", "author_id": 678, "author_profile": "https://Stackoverflow.com/users/678", "pm_score": 0, "selected": false, "text": "<p>two really obvious questions (just in case they haven't been covered)\n1. has windows firewall been disabled?\n2. do you have a personal/company firewall that is preventing your mail from being sent?</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148/" ]
I'm trying to configure a dedicated server that runs ASP.NET to send mail through the local IIS SMTP server but mail is getting stuck in the Queue folder and doesn't get delivered. I'm using this code in an .aspx page to test: ``` <%@ Page Language="C#" AutoEventWireup="true" %> <% new System.Net.Mail.SmtpClient("localhost").Send("[email protected]", "[email protected]", "testing...", "Hello, world.com"); %> ``` Then, I added the following to the Web.config file: ``` <system.net> <mailSettings> <smtp> <network host="localhost"/> </smtp> </mailSettings> </system.net> ``` In the IIS Manager I've changed the following in the properties of the "Default SMTP Virtual Server". ``` General: [X] Enable Logging Access / Authentication: [X] Windows Integrated Authentication Access / Relay Restrictions: (o) Only the list below, Granted 127.0.0.1 Delivery / Advanced: Fully qualified domain name = thedomain.com ``` Finally, I run the SMTPDiag.exe tool like this: ``` C:\>smtpdiag.exe [email protected] [email protected] Searching for Exchange external DNS settings. Computer name is THEDOMAIN. Failed to connect to the domain controller. Error: 8007054b Checking SOA for gmail.com. Checking external DNS servers. Checking internal DNS servers. SOA serial number match: Passed. Checking local domain records. Checking MX records using TCP: thedomain.com. Checking MX records using UDP: thedomain.com. Both TCP and UDP queries succeeded. Local DNS test passed. Checking remote domain records. Checking MX records using TCP: gmail.com. Checking MX records using UDP: gmail.com. Both TCP and UDP queries succeeded. Remote DNS test passed. Checking MX servers listed for [email protected]. Connecting to gmail-smtp-in.l.google.com [209.85.199.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to gmail-smtp-in.l.google.com [209.85.199.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to gsmtp183.google.com [64.233.183.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gsmtp183.google.com. Connecting to gsmtp147.google.com [209.85.147.27] on port 25. Connecting to the server failed. Error: 10051 Failed to submit mail to gsmtp147.google.com. ``` I'm using ASP.NET 2.0, Windows 2003 Server and the IIS that comes with it. Can you tell me what else to change to fix the problem? Thanks --- @mattlant This is a dedicated server that's why I'm installing the SMTP manually. > > EDIT: I use exchange so its a little > different, but its called a smart host > in exchange, but in plain SMTP service > config i think its called something > else. Cant remember exactly the > setting name. > > > Thank you for pointing me at the Smart host field. Mail is getting delivered now. In the Default SMTP Virtual Server properties, the Delivery tab, click Advanced and fill the "Smart host" field with the address that your provider gives you. In my case (GoDaddy) it was k2smtpout.secureserver.net. More info here: <http://help.godaddy.com/article/1283>
I find the best thing usually depending on how much email there is, is to just forward the mail through your ISP's SMTP server. Less headaches. Looks like that's where you are having issues, from your SMTP to external servers, not asp.net to your SMTP. Just have your SMTP server set to send it to your ISP, or you can configure asp.net to send to it. EDIT: I use exchange so it's a little different, but it's called a smart host in exchange, but in plain SMTP service config I think it's called something else. I can't remember exactly the setting name.
97,857
<p>Suppose I have a stored procedure that manages its own transaction</p> <pre><code>CREATE PROCEDURE theProc AS BEGIN BEGIN TRANSACTION -- do some stuff IF @ThereIsAProblem ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION END </code></pre> <p>If I call this proc from an existing transaction, the proc can ROLLBACK the external transaction.</p> <pre><code>BEGIN TRANSACTION EXEC theProc COMMIT TRANSACTION </code></pre> <p>How do I properly scope the transaction within the stored procedure, so that the stored procedure does not rollback external transactions?</p>
[ { "answer_id": 97931, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 1, "selected": false, "text": "<p>use @@trancount to see if you're already in a transaction when entering</p>\n" }, { "answer_id": 97944, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 3, "selected": true, "text": "<p>The syntax to do this probably varies by database. But in Transact-SQL what you do is check @@TRANCOUNT to see if you are in a transaction. If you are then you want to create a savepoint, and at the end you can just pass through the end of the function (believing a commit or rollback will happen later) or else rollback to your savepoint.</p>\n\n<p>See Microsoft's documentation on <a href=\"http://msdn.microsoft.com/en-us/library/ms188378.aspx\" rel=\"nofollow noreferrer\">savepoints</a> for more.</p>\n\n<p>Support for savepoints is fairly widespread, but I think the mechanism (assuming there is one) for finding out that you're currently in a transaction will vary quite a bit.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8155/" ]
Suppose I have a stored procedure that manages its own transaction ``` CREATE PROCEDURE theProc AS BEGIN BEGIN TRANSACTION -- do some stuff IF @ThereIsAProblem ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION END ``` If I call this proc from an existing transaction, the proc can ROLLBACK the external transaction. ``` BEGIN TRANSACTION EXEC theProc COMMIT TRANSACTION ``` How do I properly scope the transaction within the stored procedure, so that the stored procedure does not rollback external transactions?
The syntax to do this probably varies by database. But in Transact-SQL what you do is check @@TRANCOUNT to see if you are in a transaction. If you are then you want to create a savepoint, and at the end you can just pass through the end of the function (believing a commit or rollback will happen later) or else rollback to your savepoint. See Microsoft's documentation on [savepoints](http://msdn.microsoft.com/en-us/library/ms188378.aspx) for more. Support for savepoints is fairly widespread, but I think the mechanism (assuming there is one) for finding out that you're currently in a transaction will vary quite a bit.
97,875
<p>I need a way to recursively delete a folder and its children.</p> <p>Is there a prebuilt tool for this, or do I need to write one?</p> <p><code>DEL /S</code> doesn't delete directories.</p> <p><code>DELTREE</code> was removed from Windows 2000+</p>
[ { "answer_id": 97891, "author": "Brian Mitchell", "author_id": 13716, "author_profile": "https://Stackoverflow.com/users/13716", "pm_score": 2, "selected": false, "text": "<p>rmdir /s dirname</p>\n" }, { "answer_id": 97895, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>Try this command:</p>\n\n<pre><code>del /s foldername\n</code></pre>\n" }, { "answer_id": 97896, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 11, "selected": true, "text": "<p>RMDIR or RD if you are using the classic Command Prompt (cmd.exe):</p>\n\n<pre><code>rd /s /q \"path\"\n</code></pre>\n\n<blockquote>\n <p>RMDIR [/S] [/Q] [drive:]path</p>\n \n <p>RD [/S] [/Q] [drive:]path</p>\n \n <p>/S Removes all directories and files in the specified directory in addition to the directory itself. <strong>Used to remove a directory tree.</strong></p>\n \n <p>/Q Quiet mode, do not ask if ok to remove a directory tree with /S</p>\n</blockquote>\n\n<p>If you are using PowerShell you can use <code>Remove-Item</code> (which is aliased to <code>del</code>, <code>erase</code>, <code>rd</code>, <code>ri</code>, <code>rm</code> and <code>rmdir</code>) and takes a <code>-Recurse</code> argument that can be shorted to <code>-r</code></p>\n\n<pre><code>rd -r \"path\"\n</code></pre>\n" }, { "answer_id": 97900, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 3, "selected": false, "text": "<p><code>rmdir /S /Q %DIRNAME%</code></p>\n" }, { "answer_id": 97911, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 7, "selected": false, "text": "<p><code>RMDIR <strong>[/S]</strong> [/Q] [drive:]path</code></p>\n\n<p><code>RD <strong>[/S]</strong> [/Q] [drive:]path</code></p>\n\n<ul>\n<li><p><strong><code>/S</code></strong> Removes all directories and files in the specified directory in addition to the directory itself. <strong><em>Used to remove a directory tree.</em></strong></p></li>\n<li><p><code>/Q</code> Quiet mode, do not ask if ok to remove a directory tree with <code>/S</code></p></li>\n</ul>\n" }, { "answer_id": 97924, "author": "user17481", "author_id": 17481, "author_profile": "https://Stackoverflow.com/users/17481", "pm_score": 4, "selected": false, "text": "<p>You can install cygwin, which has <code>rm</code> as well as <code>ls</code> etc.</p>\n" }, { "answer_id": 97925, "author": "Jason Wadsworth", "author_id": 11078, "author_profile": "https://Stackoverflow.com/users/11078", "pm_score": -1, "selected": false, "text": "<p>There is also deltree if you're on an older version of windows.</p>\n<p>You can learn more about it from here:\n<a href=\"https://ss64.com/nt/deltree.html\" rel=\"nofollow noreferrer\">SS64: DELTREE - Delete all subfolders and files.</a></p>\n" }, { "answer_id": 98069, "author": "wbkang", "author_id": 2710, "author_profile": "https://Stackoverflow.com/users/2710", "pm_score": 7, "selected": false, "text": "<p>admin:</p>\n\n<pre><code>takeown /r /f folder\ncacls folder /c /G \"ADMINNAME\":F /T\nrmdir /s folder\n</code></pre>\n\n<p>Works for anything including sys files</p>\n\n<p>EDIT: I actually found the best way which also solves file path too long problem as well:</p>\n\n<pre><code>mkdir \\empty\nrobocopy /mir \\empty folder\n</code></pre>\n" }, { "answer_id": 98195, "author": "epochwolf", "author_id": 16204, "author_profile": "https://Stackoverflow.com/users/16204", "pm_score": 2, "selected": false, "text": "<p>You can install <a href=\"http://gnuwin32.sourceforge.net/\" rel=\"nofollow noreferrer\">GnuWin32</a> and use *nix commands natively on windows. I install this before I install anything else on a minty fresh copy of windows. :)</p>\n" }, { "answer_id": 12255881, "author": "Louis", "author_id": 1644882, "author_profile": "https://Stackoverflow.com/users/1644882", "pm_score": 2, "selected": false, "text": "<p>Here is what you need to do...</p>\n\n<p>Create a batch file with the following line</p>\n\n<p><code>RMDIR /S %1</code></p>\n\n<p>Save your batch file as <code>Remove.bat</code> and put it in <code>C:\\windows</code></p>\n\n<p>Create the following registry key</p>\n\n<p><code>HKEY_CLASSES_ROOT\\Directory\\shell\\Remove Directory (RMDIR)</code></p>\n\n<p>Launch <code>regedit</code> and update the default value <code>HKEY_CLASSES_ROOT\\Directory\\shell\\Remove Directory (RMDIR)\\default</code>\nwith the following value</p>\n\n<p><code>\"c:\\windows\\REMOVE.bat\" \"%1\"</code></p>\n\n<p>Thats it! Now you can right click any directory and use the RMDIR function</p>\n" }, { "answer_id": 29256435, "author": "Gaurav Deochakke", "author_id": 2138971, "author_profile": "https://Stackoverflow.com/users/2138971", "pm_score": 0, "selected": false, "text": "<p>here is what worked for me:</p>\n\n<p>Just try decreasing the length of the path. \ni.e :: Rename all folders that lead to such a file to smallest possible names. Say one letter names. Go on renaming upwards in the folder hierarchy.\nBy this u effectively reduce the path length.\nNow finally try deleting the file straight away.</p>\n" }, { "answer_id": 29779439, "author": "binki", "author_id": 429091, "author_profile": "https://Stackoverflow.com/users/429091", "pm_score": 2, "selected": false, "text": "<p>First, let’s review what <code>rm -rf</code> does:</p>\n\n<pre><code>C:\\Users\\ohnob\\things&gt;touch stuff.txt\n\nC:\\Users\\ohnob\\things&gt;rm -rf stuff.txt\n\nC:\\Users\\ohnob\\things&gt;mkdir stuff.txt\n\nC:\\Users\\ohnob\\things&gt;rm -rf stuff.txt\n\nC:\\Users\\ohnob\\things&gt;ls -l\ntotal 0\n\nC:\\Users\\ohnob\\things&gt;rm -rf stuff.txt\n</code></pre>\n\n<p>There are three scenarios where <code>rm -rf</code> is commonly used where it is expected to return <code>0</code>:</p>\n\n<ol>\n<li>The specified path does not exist.</li>\n<li>The specified path exists and is a directory.</li>\n<li>The specified path exists and is a file.</li>\n</ol>\n\n<p>I’m going to ignore the whole permissions thing, but nobody uses permissions or tries to deny themselves write access on things in Windows anyways (OK, that’s meant to be a joke…).</p>\n\n<p>First <a href=\"https://superuser.com/a/649329/149378\">set <code>ERRORLEVEL</code> to 0</a> and then delete the path only if it exists, using different commands depending on whether or not it is a directory. <code>IF EXIST</code> does not set <code>ERRORLEVEL</code> to 0 if the path does not exist, so setting the <code>ERRORLEVEL</code> to 0 first is necessary to properly detect success in a way that mimics normal <code>rm -rf</code> usage. Guarding the <code>RD</code> with <code>IF EXIST</code> is necessary because <code>RD</code>, unlike <code>rm -f</code>, will throw an error if the target does not exist.</p>\n\n<p>The following script snippet assumes that DELPATH is prequoted. (This is safe when you do something like <code>SET DELPATH=%1</code>. Try putting <code>ECHO %1</code> in a <code>.cmd</code> and passing it an argument with spaces in it and see what happens for yourself). After the snippet completes, you can check for failure with <code>IF ERRORLEVEL 1</code>.</p>\n\n<pre><code>: # Determine whether we need to invoke DEL or RD or do nothing.\nSET DELPATH_DELMETHOD=RD\nPUSHD %DELPATH% 2&gt;NUL\nIF ERRORLEVEL 1 (SET DELPATH_DELMETHOD=DEL) ELSE (POPD)\nIF NOT EXIST %DELPATH% SET DELPATH_DELMETHOD=NOOP\n: # Reset ERRORLEVEL so that the last command which\n: # otherwise set it does not cause us to falsely detect\n: # failure.\nCMD /C EXIT 0\nIF %DELPATH_DELMETHOD%==DEL DEL /Q %DELPATH%\nIF %DELPATH_DELMETHOD%==RD RD /S /Q %DELPATH%\n</code></pre>\n\n<p>Point is, everything is simpler when the environment just conforms to POSIX. Or if you install a minimal MSYS and just use that.</p>\n" }, { "answer_id": 35731786, "author": "Sireesh Yarlagadda", "author_id": 2057902, "author_profile": "https://Stackoverflow.com/users/2057902", "pm_score": 5, "selected": false, "text": "<p>Go to the path and trigger this command.</p>\n\n<pre><code>rd /s /q \"FOLDER_NAME\"\n</code></pre>\n\n<p>/s : Removes the specified directory and all subdirectories including any files. Use /s to remove a tree.</p>\n\n<p>/q : Runs rmdir in quiet mode. Deletes directories without confirmation.</p>\n\n<p>/? : Displays help at the command prompt.</p>\n" }, { "answer_id": 37577718, "author": "Clay", "author_id": 444917, "author_profile": "https://Stackoverflow.com/users/444917", "pm_score": 4, "selected": false, "text": "<p>For deleting a directory (whether or not it exists) use the following:</p>\n\n<pre><code>if exist myfolder ( rmdir /s/q myfolder )\n</code></pre>\n" }, { "answer_id": 52144579, "author": "gdenuf", "author_id": 582398, "author_profile": "https://Stackoverflow.com/users/582398", "pm_score": 2, "selected": false, "text": "<p>Using Powershell 5.1</p>\n\n<pre><code> get-childitem *logs* -path .\\ -directory -recurse | remove-item -confirm:$false -recurse -force\n</code></pre>\n\n<p>Replace <em>logs</em> with the directory name you want to delete.</p>\n\n<p><strong>get-childitem</strong> searches for the children directory with the name recursively from current path (.).</p>\n\n<p><strong>remove-item</strong> deletes the result.</p>\n" }, { "answer_id": 53859156, "author": "cilerler", "author_id": 439130, "author_profile": "https://Stackoverflow.com/users/439130", "pm_score": 3, "selected": false, "text": "<p>via Powershell</p>\n\n<pre><code> Remove-Item -Recurse -Force \"TestDirectory\"\n</code></pre>\n\n<p>via Command Prompt </p>\n\n<p><a href=\"https://stackoverflow.com/a/35731786/439130\">https://stackoverflow.com/a/35731786/439130</a></p>\n" }, { "answer_id": 54947647, "author": "Artif3x", "author_id": 2487033, "author_profile": "https://Stackoverflow.com/users/2487033", "pm_score": 4, "selected": false, "text": "<p>The accepted answer is great, but assuming you have Node installed, you can do this much more precisely with the node library \"rimraf\", which allows globbing patterns. If you use this a lot (I do), just install it globally.</p>\n\n<pre><code>yarn global add rimraf\n</code></pre>\n\n<p>then, for instance, a pattern I use constantly:</p>\n\n<pre><code>rimraf .\\**\\node_modules\n</code></pre>\n\n<p>or for a one-liner that let's you dodge the global install, but which takes slightly longer for the the package dynamic download:</p>\n\n<pre><code>npx rimraf .\\**\\node_modules\n</code></pre>\n" }, { "answer_id": 56571474, "author": "Roel Van de Paar", "author_id": 1208218, "author_profile": "https://Stackoverflow.com/users/1208218", "pm_score": 2, "selected": false, "text": "<p>USE AT YOUR OWN RISK. INFORMATION PROVIDED 'AS IS'. NOT TESTED EXTENSIVELY.</p>\n\n<p>Right-click Windows icon (usually bottom left) > click \"Windows PowerShell (Admin)\" > use this command (with due care, you can easily delete all your files if you're not careful):</p>\n\n<pre><code>rd -r -include *.* -force somedir\n</code></pre>\n\n<p>Where <code>somedir</code> is the non-empty directory you want to remove.</p>\n\n<p>Note that with external attached disks, or disks with issues, Windows sometimes behaves odd - it does not error in the delete (or any copy attempt), yet the directory is not deleted (or not copied) as instructed. (I found that in this case, at least for me, the command given by @n_y in his answer will produce errors like 'get-childitem : The file or directory is corrupted and unreadable.' as a result in PowerShell)</p>\n" }, { "answer_id": 61047316, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><strong>LATE BUT IMPORTANT ANSWER</strong> to anyone who is having troubles installing <a href=\"https://www.npmjs.com/\" rel=\"nofollow noreferrer\">npm</a> packages on windows machine and if you are seeing error saying \"<code>rm -rf...</code>\" command not found.\nYou can use the <a href=\"https://gitforwindows.org/\" rel=\"nofollow noreferrer\">bash cli</a> to run rm command on windows.</p>\n\n<p>for npm users, you can change the npm's config to <code>npm config set script-shell \"C:\\Program Files\\Git\\bin\\bash.exe\"</code> this way if the npm package you are trying to install has a <a href=\"https://docs.npmjs.com/misc/scripts\" rel=\"nofollow noreferrer\">post install script</a> that uses <code>rm -rf</code> command, you will be able to run that <code>rm</code> command without needing to change anything in the npm package or disabling the post install scripts config. (For example, <code>styled-components</code> uses <code>rm</code> command in their post install scripts)</p>\n\n<p>If you want to just use the <code>rm</code> command, you can easily use the bash and pass the arguments. </p>\n\n<p><strong>So yes, you can use the 'rm' command on windows.</strong></p>\n" }, { "answer_id": 63745519, "author": "stackprotector", "author_id": 11942268, "author_profile": "https://Stackoverflow.com/users/11942268", "pm_score": 4, "selected": false, "text": "<pre class=\"lang-bsh prettyprint-override\"><code>rm -r -fo &lt;path&gt;\n</code></pre>\n<p>is the closest you can get in Windows PowerShell. It is the abbreviation of</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>Remove-Item -Recurse -Force -Path &lt;path&gt;\n</code></pre>\n<p><a href=\"https://stackoverflow.com/a/61573240/11942268\">(more details)</a>.</p>\n" }, { "answer_id": 68315523, "author": "faester", "author_id": 540968, "author_profile": "https://Stackoverflow.com/users/540968", "pm_score": 2, "selected": false, "text": "<p>In powershell <code>rm -recurse -force</code> works quite well.</p>\n" }, { "answer_id": 68369398, "author": "BananaAcid", "author_id": 1644202, "author_profile": "https://Stackoverflow.com/users/1644202", "pm_score": 2, "selected": false, "text": "<p>As a sidenode:</p>\n<p>From the linux version with all subdirs (recursive) + force delete</p>\n<p><code>$ rm -rf ./path</code></p>\n<p>to PowerShell</p>\n<p><code>PS&gt; rm -r -fo ./path</code></p>\n<p>which has the close to same params (just seperated) (-fo is needed, since -f could match different other params)</p>\n<p>note:</p>\n<pre><code>Remove-Item ALIASE\n ri\n rm\n rmdir\n del\n erase\n rd\n</code></pre>\n" }, { "answer_id": 68480971, "author": "Ray Hulha", "author_id": 756233, "author_profile": "https://Stackoverflow.com/users/756233", "pm_score": 0, "selected": false, "text": "<p>Windows Registry Editor Version 5.00</p>\n<p>[HKEY_CLASSES_ROOT\\Folder\\shell\\rmdir\\command]<br />\n@=&quot;cmd.exe /s /c rmdir &quot;%V&quot;&quot;</p>\n" }, { "answer_id": 69406402, "author": "jianyongli", "author_id": 4046647, "author_profile": "https://Stackoverflow.com/users/4046647", "pm_score": 2, "selected": false, "text": "<p>in powershell, rm is alias of <code>Remove-Item</code>, so remove a file,</p>\n<pre class=\"lang-sh prettyprint-override\"><code>rm -R -Fo the_file\n</code></pre>\n<p>is equivalent to</p>\n<pre class=\"lang-sh prettyprint-override\"><code>Remove-Item -R -Fo the_file\n</code></pre>\n<p>if you feel comfortable with gnu <code>rm</code> util, you can the <code>rm</code> util by <a href=\"https://chocolatey.org/install\" rel=\"nofollow noreferrer\">choco</a> package manager on windows.</p>\n<p>install gnu utils in powershell using <code>choco</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>choco install GnuWin\n</code></pre>\n<p>finally,</p>\n<pre class=\"lang-sh prettyprint-override\"><code>rm.exe -rf the_file\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I need a way to recursively delete a folder and its children. Is there a prebuilt tool for this, or do I need to write one? `DEL /S` doesn't delete directories. `DELTREE` was removed from Windows 2000+
RMDIR or RD if you are using the classic Command Prompt (cmd.exe): ``` rd /s /q "path" ``` > > RMDIR [/S] [/Q] [drive:]path > > > RD [/S] [/Q] [drive:]path > > > /S Removes all directories and files in the specified directory in addition to the directory itself. **Used to remove a directory tree.** > > > /Q Quiet mode, do not ask if ok to remove a directory tree with /S > > > If you are using PowerShell you can use `Remove-Item` (which is aliased to `del`, `erase`, `rd`, `ri`, `rm` and `rmdir`) and takes a `-Recurse` argument that can be shorted to `-r` ``` rd -r "path" ```
97,962
<p>A poorly-written back-end system we interface with is having trouble with handling the load we're producing. While they fix their load problems, we're trying to reduce any additional load we're generating, one of which is that the back-end system continues to try and service a form submission even if another submission has come from the same user.</p> <p>One thing we've noticed is users double-clicking the form submission button. I need to de-bounce these clicks, and prevent a second form submission.<br> My approach (using Prototype) places an <code>onSubmit</code> on the form that calls the following function which hides the form submission button and displays a "loading..." <code>div</code>.</p> <pre><code>function disableSubmit(id1, id2) { $(id1).style.display = 'none'; $(id2).style.display = 'inline'; } </code></pre> <p>The problem I've found with this approach is that if I use an animated gif in the "loading..." <code>div</code>, it loads fine but doesn't animate while the form is submitting.</p> <p>Is there a better way to do this de-bouncing and continue to show animation on the page while waiting for the form result to (finally) load? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 97995, "author": "Jason Wadsworth", "author_id": 11078, "author_profile": "https://Stackoverflow.com/users/11078", "pm_score": 1, "selected": false, "text": "<p>You could try setting the \"disabled\" flag on the input (type=submit) element, rather than just changing the style. That should entirely shut down the from on the browser side.</p>\n\n<p>See: <a href=\"http://www.prototypejs.org/api/form/element#method-disable\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/form/element#method-disable</a></p>\n" }, { "answer_id": 99366, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 3, "selected": true, "text": "<p>If you've got jQuery handy, attach a click() event that disables the button after the initial submission -</p>\n\n<pre><code>$('input[type=\"submit\"]').click(function(event){\n event.preventDefault();\n this.click(null);\n});\n</code></pre>\n\n<p>that sort of thing.</p>\n" }, { "answer_id": 142983, "author": "Fczbkk", "author_id": 22920, "author_profile": "https://Stackoverflow.com/users/22920", "pm_score": 3, "selected": false, "text": "<p>Using Prototype, you can use this code to watch if any form has been submitted and disable all submit buttons when it does:</p>\n\n<pre><code>document.observe( 'dom:loaded', function() { // when document is loaded\n $$( 'form' ).each( function( form ) { // find all FORM elements in the document\n form.observe( 'submit', function() { // when any form is submitted\n $$( 'input[type=\"submit\"]' ).invoke( 'disable' ); // disable all submit buttons\n } );\n } );\n} );\n</code></pre>\n\n<p>This should help with users that double-click on submit buttons. However, it will still be possible to submit the form any other way (e.g. pressing Enter on text field). To prevent this, you have to start watching for any form submission after the first one and stop it:</p>\n\n<pre><code>document.observe( 'dom:loaded', function() {\n $$( 'form' ).each( function( form ) {\n form.observe( 'submit', function() {\n $$( 'input[type=\"submit\"]' ).invoke( 'disable' );\n $$( 'form' ).observe( 'submit', function( evt ) { // once any form is submitted\n evt.stop(); // prevent any other form submission\n } );\n } );\n } );\n} );\n</code></pre>\n" }, { "answer_id": 667104, "author": "unscriptable", "author_id": 80593, "author_profile": "https://Stackoverflow.com/users/80593", "pm_score": 2, "selected": false, "text": "<p>All good suggestions above. If you really want to \"debounce\" as you say, then I've got a great function for that. More details at <a href=\"http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/\" rel=\"nofollow noreferrer\">unscriptable.com</a></p>\n\n<pre><code>var debounce = function (func, threshold, execAsap) {\n\n var timeout;\n\n return function debounced () {\n var obj = this, args = arguments;\n function delayed () {\n if (!execAsap)\n func.apply(obj, args);\n timeout = null; \n };\n\n if (timeout)\n clearTimeout(timeout);\n else if (execAsap)\n func.apply(obj, args);\n\n timeout = setTimeout(delayed, threshold || 100); \n };\n\n}\n</code></pre>\n" }, { "answer_id": 4341734, "author": "aceofspades", "author_id": 237150, "author_profile": "https://Stackoverflow.com/users/237150", "pm_score": -1, "selected": false, "text": "<p>Submit the form with AJAX, and the GIF will animate.</p>\n" }, { "answer_id": 73077049, "author": "Bhola Kr. Khawas", "author_id": 9985883, "author_profile": "https://Stackoverflow.com/users/9985883", "pm_score": 0, "selected": false, "text": "<p>Here I have a simple and handy way to prevent duplicate or multiple form submittion.</p>\n<p>Give a class &quot;prevent-mult-submit-form&quot; to the desired form and another class to the submit button &quot;disable-mult-click&quot;. You can aslo add a font awesome spinner like</p>\n<pre><code>&lt;i class=&quot;spinner hidden fa fa-spinner fa-spin&quot; style=&quot;margin-right: 2px&quot;&gt;&lt;/i&gt;\n</code></pre>\n<p>Now pest the code below inside script tag. you are good to go.</p>\n<pre><code> $('.prevent-mult-submit-form').on('submit', function(){\n $('.disable-mult-click').attr('disabled', true)\n $('.spinner').removeClass('hidden')\n })\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10788/" ]
A poorly-written back-end system we interface with is having trouble with handling the load we're producing. While they fix their load problems, we're trying to reduce any additional load we're generating, one of which is that the back-end system continues to try and service a form submission even if another submission has come from the same user. One thing we've noticed is users double-clicking the form submission button. I need to de-bounce these clicks, and prevent a second form submission. My approach (using Prototype) places an `onSubmit` on the form that calls the following function which hides the form submission button and displays a "loading..." `div`. ``` function disableSubmit(id1, id2) { $(id1).style.display = 'none'; $(id2).style.display = 'inline'; } ``` The problem I've found with this approach is that if I use an animated gif in the "loading..." `div`, it loads fine but doesn't animate while the form is submitting. Is there a better way to do this de-bouncing and continue to show animation on the page while waiting for the form result to (finally) load? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
If you've got jQuery handy, attach a click() event that disables the button after the initial submission - ``` $('input[type="submit"]').click(function(event){ event.preventDefault(); this.click(null); }); ``` that sort of thing.
97,971
<p>Having programmed through emacs and vi for years and years at this point, I have heard that using an IDE is a very good way of becoming more efficient.</p> <p>To that end, I have decided to try using Eclipse for a lot of coding and seeing how I get on.</p> <p>Are there any suggestions for easing the transition over to an IDE. Obviously, some will think none of this is worth the bother, but I think with Eclipse allowing emacs-style key bindings and having code completion and in-built debugging, I reckon it is well worth trying to move over to a more feature-rich environment for the bulk of my development worth.</p> <p>So what suggestions do you have for easing the transition?</p>
[ { "answer_id": 97985, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<p>If you've been using emacs/vi for years (although you listed both, so it seems like you may not be adapted fully to one of them), using said editor will probably be faster for you than an IDE. The level of mind-meld a competant emacs/vi user can achieve with a customized setup and years of muscle memory is astounding.</p>\n" }, { "answer_id": 97991, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 1, "selected": false, "text": "<p>Try making a couple of test applications just to get your feet wet. At first, it will probably feel more cumbersome. The benefits of IDEs don't come until you begin having a good understanding of them and their various capabilities. Once you know where everything is and start to understand the key commands, life gets easier, MUCH easier.</p>\n" }, { "answer_id": 97994, "author": "Jason Dagit", "author_id": 5113, "author_profile": "https://Stackoverflow.com/users/5113", "pm_score": 2, "selected": false, "text": "<p>One thing that helped me transition from Emacs to other IDEs was the idea that IDEs are terrible editors. I scoffed at that person but I now see their point.</p>\n\n<p>An editor, like Emacs or Vim, can really focus on being a good editor first and foremost.</p>\n\n<p>An IDE, like Visual Studio or Eclipse, really focuses on being a good project management tool with a built in way to modify files.</p>\n\n<p>I find that keeping the above in mind (and keeping Emacs handy) helps me to not get frustrated when the IDE du jour is not meeting my needs.</p>\n" }, { "answer_id": 98000, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 0, "selected": false, "text": "<p>Read the doc...\nAnd see what shortcuts/keybindings equivalents are with your familiar ones. Learn the new ones... </p>\n" }, { "answer_id": 98031, "author": "Peter", "author_id": 17123, "author_profile": "https://Stackoverflow.com/users/17123", "pm_score": 1, "selected": false, "text": "<p>I think you'll find IDE's invaluable once you get into them. The code complete and navigation features, integrated running/debugging, and all the other little benefits really add up.</p>\n\n<p>Some suggestions for starting out and easing transition:\n- start by going through a tutorial or demonstration included with the IDE documentation to get familar with where things are in the GUI.\n- look at different kinds of sample projects (usually included with the IDE or as a separate download) for different types of areas you may be coding (web applications, desktop applications, etc) to see how they are laid out and structured in the IDE.\n- once comfortable, create your own project from existing code that you know well, ideally not something overly complex, and get it all compiling/working.\n- explore the power! Debug your code, use refactorings, etc. The right click menu is your friend until you learn the keyboard shortcuts just to see all the things you can do. Right click different areas of your code to see what is possible and learn (or re-map) the keyboard shortcuts.</p>\n" }, { "answer_id": 98151, "author": "Desty", "author_id": 2161072, "author_profile": "https://Stackoverflow.com/users/2161072", "pm_score": 3, "selected": true, "text": "<p>Eclipse is the best IDE I've used, even considering its quite large footprint and sluggishness on slow computers (like my work machine... Pentium III!).</p>\n\n<p>Rather than trying to 'ease the transition', I think it's better to jump right in and let yourself be overwhelmed by the bells and whistles and truly useful refactorings etc.</p>\n\n<p>Here are some of the most useful things I would consciously use as soon as possible:</p>\n\n<ul>\n<li>ctrl-shift-t finds and opens a class via incremental search on the name</li>\n<li>ctrl-shift-o automatically generates import statements (and deletes redundant ones)</li>\n<li>F3 on an identifier to jump to its definition, and alt-left/right like in web browsers to go back/forward in navigation history</li>\n<li><p>The \"Quick fix\" tool, which has a large amount of context-sensitive refactorings and such. Some examples:</p>\n\n<pre><code>String messageXml = in.read();\nMessage response = messageParser.parse(messageXml);\nreturn response;</code></pre></li>\n</ul>\n\n<p>If you put the text cursor on the argument to parse(...) and press ctrl+1, Eclipse will suggest \"Inline local variable\". If you do that, then repeat with the cursor over the return variable 'response', the end result will be:</p>\n\n<pre><code>return messageParser.parse(in.read());\n</code></pre>\n\n<p>There are many, many little rules like this which the quick fix tool will suggest and apply to help refactor your code (including the exact opposite, \"extract to local variable/field/constant\", which can be invaluable).\nYou can write code that calls a method you haven't written yet - going to the line which now displays an error and using quick fix will offer to create a method matching the parameters inferred from your usage. Similarly so for variables.\nAll these small refactorings and shortcuts save a lot of time and are much more quickly picked up than you'd expect. Whenever you're about to rearrange code, experiment with quick fix to see if it suggests something useful.</p>\n\n<p>There's also a nice bag of tricks directly available in the menus, like generating getters/setters, extracting interfaces and the like. Jump in and try everything out!</p>\n" }, { "answer_id": 98381, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>Some free ones:</p>\n\n<ul>\n<li><a href=\"http://developer.apple.com/tools/xcode/\" rel=\"nofollow noreferrer\">XCode on the Mac</a></li>\n<li><a href=\"http://www.eclipse.org/\" rel=\"nofollow noreferrer\">Eclipse</a></li>\n<li><a href=\"http://www.lazarus.freepascal.org/\" rel=\"nofollow noreferrer\">Lazarus (Open Source clone of Delphi)</a></li>\n<li><a href=\"http://www.microsoft.com/express/\" rel=\"nofollow noreferrer\">Visual Studio Express\nEditions</a></li>\n</ul>\n" }, { "answer_id": 11746145, "author": "demongolem", "author_id": 236247, "author_profile": "https://Stackoverflow.com/users/236247", "pm_score": 0, "selected": false, "text": "<p>Old question, but let me suggest that in some circumstances, something like Notepad++ might be appropriate for the OP's situation which may be encountered by others. Especially if you are looking for something lightweight, Notepad++ can be part of a developer's arsenal of tools. Eclipse, Visual Studio and others are resource hogs with all their automagic going on and if you are looking to whip out something pretty quick with a whole bunch of keyboard shortcuts and the like or if you are interested in viewing someone else's source, this can be quite useful. Oh yeah, and it is free too.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
Having programmed through emacs and vi for years and years at this point, I have heard that using an IDE is a very good way of becoming more efficient. To that end, I have decided to try using Eclipse for a lot of coding and seeing how I get on. Are there any suggestions for easing the transition over to an IDE. Obviously, some will think none of this is worth the bother, but I think with Eclipse allowing emacs-style key bindings and having code completion and in-built debugging, I reckon it is well worth trying to move over to a more feature-rich environment for the bulk of my development worth. So what suggestions do you have for easing the transition?
Eclipse is the best IDE I've used, even considering its quite large footprint and sluggishness on slow computers (like my work machine... Pentium III!). Rather than trying to 'ease the transition', I think it's better to jump right in and let yourself be overwhelmed by the bells and whistles and truly useful refactorings etc. Here are some of the most useful things I would consciously use as soon as possible: * ctrl-shift-t finds and opens a class via incremental search on the name * ctrl-shift-o automatically generates import statements (and deletes redundant ones) * F3 on an identifier to jump to its definition, and alt-left/right like in web browsers to go back/forward in navigation history * The "Quick fix" tool, which has a large amount of context-sensitive refactorings and such. Some examples: ``` String messageXml = in.read(); Message response = messageParser.parse(messageXml); return response; ``` If you put the text cursor on the argument to parse(...) and press ctrl+1, Eclipse will suggest "Inline local variable". If you do that, then repeat with the cursor over the return variable 'response', the end result will be: ``` return messageParser.parse(in.read()); ``` There are many, many little rules like this which the quick fix tool will suggest and apply to help refactor your code (including the exact opposite, "extract to local variable/field/constant", which can be invaluable). You can write code that calls a method you haven't written yet - going to the line which now displays an error and using quick fix will offer to create a method matching the parameters inferred from your usage. Similarly so for variables. All these small refactorings and shortcuts save a lot of time and are much more quickly picked up than you'd expect. Whenever you're about to rearrange code, experiment with quick fix to see if it suggests something useful. There's also a nice bag of tricks directly available in the menus, like generating getters/setters, extracting interfaces and the like. Jump in and try everything out!
97,976
<p>I have a datagridview that accepts a list(of myObject) as a datasource. I want to add a new row to the datagrid to add to the database. I get this done by getting the list... adding a blank myObject to the list and then reseting the datasource. I now want to set the focus to the second cell in the new row.</p> <p>To CLARIFY i am trying to set the focus</p>
[ { "answer_id": 97986, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 0, "selected": false, "text": "<p>In WinForms, you should be able to set the </p>\n\n<pre><code>Me.dataEvidence.SelectedRows\n</code></pre>\n\n<p>property to the row you want selected.</p>\n" }, { "answer_id": 1213548, "author": "Michael Todd", "author_id": 16623, "author_profile": "https://Stackoverflow.com/users/16623", "pm_score": 3, "selected": true, "text": "<p>You can set the focus to a specific cell in a row but only if the SelectionMode on the DataGridView is set to CellSelect. If it is, simply do the following:</p>\n\n<pre><code>dataGridView.Rows[rowNumber].Cells[columnNumber].Selected = true;\n</code></pre>\n" }, { "answer_id": 18220884, "author": "Elias", "author_id": 2414458, "author_profile": "https://Stackoverflow.com/users/2414458", "pm_score": 0, "selected": false, "text": "<p>In Visual Studio <strong>2012</strong> (vb.NET <strong>Framework 4.50</strong>), you can set the focus on any desired cell of a DataGridView control.</p>\n\n<p>Try This:</p>\n\n<pre><code>Sub Whatever()\n\n ' all above code\n\n DataGridView1.Focus()\n DataGridView1.CurrentCell = DataGridView1.Rows(x).Cells(y) 'x is your desired row number, y is your desired column number\n\n ' all below code\n\nEnd Sub\n</code></pre>\n\n<p>Okay, that works for me. I hope that it works for you, too.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ]
I have a datagridview that accepts a list(of myObject) as a datasource. I want to add a new row to the datagrid to add to the database. I get this done by getting the list... adding a blank myObject to the list and then reseting the datasource. I now want to set the focus to the second cell in the new row. To CLARIFY i am trying to set the focus
You can set the focus to a specific cell in a row but only if the SelectionMode on the DataGridView is set to CellSelect. If it is, simply do the following: ``` dataGridView.Rows[rowNumber].Cells[columnNumber].Selected = true; ```
97,987
<p>What's the best practice for using a <code>switch</code> statement vs using an <code>if</code> statement for 30 <code>unsigned</code> enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventions.</p> <p><code>switch</code> statement:</p> <pre><code>// numError is an error enumeration type, with 0 being the non-error case // fire_special_event() is a stub method for the shared processing switch (numError) { case ERROR_01 : // intentional fall-through case ERROR_07 : // intentional fall-through case ERROR_0A : // intentional fall-through case ERROR_10 : // intentional fall-through case ERROR_15 : // intentional fall-through case ERROR_16 : // intentional fall-through case ERROR_20 : { fire_special_event(); } break; default: { // error codes that require no additional action } break; } </code></pre> <p><code>if</code> statement:</p> <pre><code>if ((ERROR_01 == numError) || (ERROR_07 == numError) || (ERROR_0A == numError) || (ERROR_10 == numError) || (ERROR_15 == numError) || (ERROR_16 == numError) || (ERROR_20 == numError)) { fire_special_event(); } </code></pre>
[ { "answer_id": 98004, "author": "Alexandra Franks", "author_id": 16203, "author_profile": "https://Stackoverflow.com/users/16203", "pm_score": 4, "selected": false, "text": "<p>Compiler will optimise it anyway - go for the switch as it's the most readable.</p>\n" }, { "answer_id": 98006, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 3, "selected": false, "text": "<p>The Switch, if only for readability. Giant if statements are harder to maintain and harder to read in my opinion. </p>\n\n<p><strong>ERROR_01</strong> : // intentional fall-through</p>\n\n<p>or </p>\n\n<p><strong>(ERROR_01 == numError) ||</strong></p>\n\n<p>The later is more error prone and requires more typing and formatting than the first.</p>\n" }, { "answer_id": 98007, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 1, "selected": false, "text": "<p>I'm not sure about best-practise, but I'd use switch - and then trap intentional fall-through via 'default'</p>\n" }, { "answer_id": 98009, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "<p>IMO this is a perfect example of what switch fall-through was made for.</p>\n" }, { "answer_id": 98011, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>I would pick the if statement for the sake of clarity and convention, although I'm sure that some would disagree. After all, you are wanting to do something <code>if</code> some condition is true! Having a switch with one action seems a little... unneccesary.</p>\n" }, { "answer_id": 98012, "author": "TSomKes", "author_id": 18347, "author_profile": "https://Stackoverflow.com/users/18347", "pm_score": 1, "selected": false, "text": "<p>If your cases are likely to remain grouped in the future--if more than one case corresponds to one result--the switch may prove to be easier to read and maintain.</p>\n" }, { "answer_id": 98014, "author": "Ed Brown", "author_id": 16924, "author_profile": "https://Stackoverflow.com/users/16924", "pm_score": 0, "selected": false, "text": "<p>Im not the person to tell you about speed and memory usage, but looking at a switch statment is a hell of a lot easier to understand then a large if statement (especially 2-3 months down the line)</p>\n" }, { "answer_id": 98024, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 8, "selected": true, "text": "<p>Use switch.</p>\n\n<p>In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.</p>\n\n<p>In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).</p>\n" }, { "answer_id": 98030, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 2, "selected": false, "text": "<p>They work equally well. Performance is about the same given a modern compiler.</p>\n\n<p>I prefer if statements over case statements because they are more readable, and more flexible -- you can add other conditions not based on numeric equality, like \" || max &lt; min \". But for the simple case you posted here, it doesn't really matter, just do what's most readable to you. </p>\n" }, { "answer_id": 98036, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 1, "selected": false, "text": "<p>switch is definitely preferred. It's easier to look at a switch's list of cases &amp; know for sure what it is doing than to read the long if condition. </p>\n\n<p>The duplication in the <code>if</code> condition is hard on the eyes. Suppose one of the <code>==</code> was written <code>!=</code>; would you notice? Or if one instance of 'numError' was written 'nmuError', which just happened to compile?</p>\n\n<p>I'd generally prefer to use polymorphism instead of the switch, but without more details of the context, it's hard to say.</p>\n\n<p>As for performance, your best bet is to use a profiler to measure the performance of your application in conditions that are similar to what you expect in the wild. Otherwise, you're probably optimizing in the wrong place and in the wrong way.</p>\n" }, { "answer_id": 98052, "author": "lewis", "author_id": 14442, "author_profile": "https://Stackoverflow.com/users/14442", "pm_score": 0, "selected": false, "text": "<p>I would say use SWITCH. This way you only have to implement differing outcomes. Your ten identical cases can use the default. Should one change all you need to is explicitly implement the change, no need to edit the default. It's also far easier to add or remove cases from a SWITCH than to edit IF and ELSEIF.</p>\n\n<pre><code>switch(numerror){\n ERROR_20 : { fire_special_event(); } break;\n default : { null; } break;\n}\n</code></pre>\n\n<p>Maybe even test your condition (in this case numerror) against a list of possibilities, an array perhaps so your SWITCH isn't even used unless there definately will be an outcome.</p>\n" }, { "answer_id": 98097, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 1, "selected": false, "text": "<p>I agree with the compacity of the switch solution but IMO you're <strong>hijacking the switch</strong> here.<br>\nThe purpose of the switch is to have <strong>different</strong> handling depending on the value.<br>\nIf you had to explain your algo in pseudo-code, you'd use an if because, semantically, that's what it is: <strong>if whatever_error do this</strong>...<br>\nSo unless you intend someday to change your code to have specific code for each error, I would use <strong>if</strong>.</p>\n" }, { "answer_id": 101737, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 0, "selected": false, "text": "<p>Seeing as you only have 30 error codes, code up your own jump table, then you make all optimisation choices yourself (jump will always be quickest), rather than hope the compiler will do the right thing. It also makes the code very small (apart from the static declaration of the jump table). It also has the side benefit that with a debugger you can modify the behaviour at runtime should you so need, just by poking the table data directly.</p>\n" }, { "answer_id": 103332, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "<p>The switch <strong>is</strong> faster.</p>\n\n<p>Just try if/else-ing 30 different values inside a loop, and compare it to the same code using switch to see how much faster the switch is.</p>\n\n<p>Now, the <strong>switch has one real problem</strong> : The switch must know at compile time the values inside each case. This means that the following code:</p>\n\n<pre><code>// WON'T COMPILE\nextern const int MY_VALUE ;\n\nvoid doSomething(const int p_iValue)\n{\n switch(p_iValue)\n {\n case MY_VALUE : /* do something */ ; break ;\n default : /* do something else */ ; break ;\n }\n}\n</code></pre>\n\n<p>won't compile.</p>\n\n<p>Most people will then use defines (Aargh!), and others will declare and define constant variables in the same compilation unit. For example:</p>\n\n<pre><code>// WILL COMPILE\nconst int MY_VALUE = 25 ;\n\nvoid doSomething(const int p_iValue)\n{\n switch(p_iValue)\n {\n case MY_VALUE : /* do something */ ; break ;\n default : /* do something else */ ; break ;\n }\n}\n</code></pre>\n\n<p>So, in the end, the developper must choose between \"speed + clarity\" vs. \"code coupling\".</p>\n\n<p>(Not that a switch can't be written to be confusing as hell... Most the switch I currently see are of this \"confusing\" category\"... But this is another story...)</p>\n\n<blockquote>\n <p><b>Edit 2008-09-21:</b></p>\n \n <p><a href=\"https://stackoverflow.com/users/8090/bk1e\">bk1e</a> added the following comment: \"<b>Defining constants as enums in a header file is another way to handle this\".</b></p>\n \n <p>Of course it is.</p>\n \n <p>The point of an extern type was to decouple the value from the source. Defining this value as a macro, as a simple const int declaration, or even as an enum has the side-effect of inlining the value. Thus, should the define, the enum value, or the const int value change, a recompilation would be needed. The extern declaration means the there is no need to recompile in case of value change, but in the other hand, makes it impossible to use switch. The conclusion being <b>Using switch will increase coupling between the switch code and the variables used as cases</b>. When it is Ok, then use switch. When it isn't, then, no surprise.</p>\n</blockquote>\n\n<p>.</p>\n\n<blockquote>\n <p><b>Edit 2013-01-15:</b></p>\n \n <p><a href=\"https://stackoverflow.com/users/405725/vlad-lazarenko\">Vlad Lazarenko</a> commented on my answer, giving a link to his in-depth study of the assembly code generated by a switch. Very enlightning: <a href=\"http://lazarenko.me/switch/\" rel=\"noreferrer\">http://lazarenko.me/switch/</a></p>\n</blockquote>\n" }, { "answer_id": 129309, "author": "Bdoserror", "author_id": 11026, "author_profile": "https://Stackoverflow.com/users/11026", "pm_score": 3, "selected": false, "text": "<p>Code for readability. If you want to know what performs better, use a profiler, as optimizations and compilers vary, and performance issues are rarely where people think they are.</p>\n" }, { "answer_id": 129515, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 6, "selected": false, "text": "<p>For the special case that you've provided in your example, the clearest code is probably:</p>\n\n<pre><code>if (RequiresSpecialEvent(numError))\n fire_special_event();\n</code></pre>\n\n<p>Obviously this just moves the problem to a different area of the code, but now you have the opportunity to reuse this test. You also have more options for how to solve it. You could use std::set, for example:</p>\n\n<pre><code>bool RequiresSpecialEvent(int numError)\n{\n return specialSet.find(numError) != specialSet.end();\n}\n</code></pre>\n\n<p>I'm not suggesting that this is the best implementation of RequiresSpecialEvent, just that it's an option. You can still use a switch or if-else chain, or a lookup table, or some bit-manipulation on the value, whatever. The more obscure your decision process becomes, the more value you'll derive from having it in an isolated function.</p>\n" }, { "answer_id": 129860, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 1, "selected": false, "text": "<p>Aesthetically I tend to favor this approach.</p>\n\n<pre><code>unsigned int special_events[] = {\n ERROR_01,\n ERROR_07,\n ERROR_0A,\n ERROR_10,\n ERROR_15,\n ERROR_16,\n ERROR_20\n };\n int special_events_length = sizeof (special_events) / sizeof (unsigned int);\n\n void process_event(unsigned int numError) {\n for (int i = 0; i &lt; special_events_length; i++) {\n if (numError == special_events[i]) {\n fire_special_event();\n break;\n }\n }\n }\n</code></pre>\n\n<p>Make the data a little smarter so we can make the logic a little dumber.</p>\n\n<p>I realize it looks weird. Here's the inspiration (from how I'd do it in Python):</p>\n\n<pre><code>special_events = [\n ERROR_01,\n ERROR_07,\n ERROR_0A,\n ERROR_10,\n ERROR_15,\n ERROR_16,\n ERROR_20,\n ]\ndef process_event(numError):\n if numError in special_events:\n fire_special_event()\n</code></pre>\n" }, { "answer_id": 129913, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 3, "selected": false, "text": "<p>Use switch, it is what it's for and what programmers expect.</p>\n\n<p>I would put the redundant case labels in though - just to make people feel comfortable, I was trying to remember when / what the rules are for leaving them out.<br>\nYou don't want the next programmer working on it to have to do any unnecessary thinking about language details (it might be you in a few months time!)</p>\n" }, { "answer_id": 1783241, "author": "McAnix", "author_id": 190401, "author_profile": "https://Stackoverflow.com/users/190401", "pm_score": 0, "selected": false, "text": "<p>I know its old but</p>\n\n<pre><code>public class SwitchTest {\nstatic final int max = 100000;\n\npublic static void main(String[] args) {\n\nint counter1 = 0;\nlong start1 = 0l;\nlong total1 = 0l;\n\nint counter2 = 0;\nlong start2 = 0l;\nlong total2 = 0l;\nboolean loop = true;\n\nstart1 = System.currentTimeMillis();\nwhile (true) {\n if (counter1 == max) {\n break;\n } else {\n counter1++;\n }\n}\ntotal1 = System.currentTimeMillis() - start1;\n\nstart2 = System.currentTimeMillis();\nwhile (loop) {\n switch (counter2) {\n case max:\n loop = false;\n break;\n default:\n counter2++;\n }\n}\ntotal2 = System.currentTimeMillis() - start2;\n\nSystem.out.println(\"While if/else: \" + total1 + \"ms\");\nSystem.out.println(\"Switch: \" + total2 + \"ms\");\nSystem.out.println(\"Max Loops: \" + max);\n\nSystem.exit(0);\n}\n}\n</code></pre>\n\n<p>Varying the loop count changes a lot: </p>\n\n<p>While if/else: 5ms\nSwitch: 1ms\nMax Loops: 100000</p>\n\n<p>While if/else: 5ms\nSwitch: 3ms\nMax Loops: 1000000</p>\n\n<p>While if/else: 5ms\nSwitch: 14ms\nMax Loops: 10000000</p>\n\n<p>While if/else: 5ms\nSwitch: 149ms\nMax Loops: 100000000</p>\n\n<p>(add more statements if you want)</p>\n" }, { "answer_id": 3834930, "author": "MarioFrost", "author_id": 463312, "author_profile": "https://Stackoverflow.com/users/463312", "pm_score": 1, "selected": false, "text": "<pre><code>while (true) != while (loop)\n</code></pre>\n\n<p>Probably the first one is optimised by the compiler, that would explain why the second loop is slower when increasing loop count.</p>\n" }, { "answer_id": 32356125, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 3, "selected": false, "text": "<p>Compilers are really good at optimizing <code>switch</code>. Recent gcc is also good at optimizing a bunch of conditions in an <code>if</code>.</p>\n\n<p>I made some test cases on <a href=\"https://goo.gl/lYmM1Q\" rel=\"noreferrer\">godbolt</a>.</p>\n\n<p>When the <code>case</code> values are grouped close together, gcc, clang, and icc are all smart enough to use a bitmap to check if a value is one of the special ones.</p>\n\n<p>e.g. gcc 5.2 -O3 compiles the <code>switch</code> to (and the <code>if</code> something very similar):</p>\n\n<pre><code>errhandler_switch(errtype): # gcc 5.2 -O3\n cmpl $32, %edi\n ja .L5\n movabsq $4301325442, %rax # highest set bit is bit 32 (the 33rd bit)\n btq %rdi, %rax\n jc .L10\n.L5:\n rep ret\n.L10:\n jmp fire_special_event()\n</code></pre>\n\n<p>Notice that the bitmap is immediate data, so there's no potential data-cache miss accessing it, or a jump table.</p>\n\n<p>gcc 4.9.2 -O3 compiles the <code>switch</code> to a bitmap, but does the <code>1U&lt;&lt;errNumber</code> with mov/shift. It compiles the <code>if</code> version to series of branches.</p>\n\n<pre><code>errhandler_switch(errtype): # gcc 4.9.2 -O3\n leal -1(%rdi), %ecx\n cmpl $31, %ecx # cmpl $32, %edi wouldn't have to wait an extra cycle for lea's output.\n # However, register read ports are limited on pre-SnB Intel\n ja .L5\n movl $1, %eax\n salq %cl, %rax # with -march=haswell, it will use BMI's shlx to avoid moving the shift count into ecx\n testl $2150662721, %eax\n jne .L10\n.L5:\n rep ret\n.L10:\n jmp fire_special_event()\n</code></pre>\n\n<p>Note how it subtracts 1 from <code>errNumber</code> (with <code>lea</code> to combine that operation with a move). That lets it fit the bitmap into a 32bit immediate, avoiding the 64bit-immediate <code>movabsq</code> which takes more instruction bytes.</p>\n\n<p>A shorter (in machine code) sequence would be:</p>\n\n<pre><code> cmpl $32, %edi\n ja .L5\n mov $2150662721, %eax\n dec %edi # movabsq and btq is fewer instructions / fewer Intel uops, but this saves several bytes\n bt %edi, %eax\n jc fire_special_event\n.L5:\n ret\n</code></pre>\n\n<hr>\n\n<p>(The failure to use <code>jc fire_special_event</code> is omnipresent, and is <a href=\"https://gcc.gnu.org/bugzilla/show_bug.cgi?id=42497#c3\" rel=\"noreferrer\">a compiler bug</a>.)</p>\n\n<p><code>rep ret</code> is used in branch targets, and following conditional branches, for the benefit of old AMD K8 and K10 (pre-Bulldozer): <a href=\"https://stackoverflow.com/questions/20526361/what-does-rep-ret-mean\">What does `rep ret` mean?</a>. Without it, branch prediction doesn't work as well on those obsolete CPUs.</p>\n\n<p><code>bt</code> (bit test) with a register arg is fast. It combines the work of left-shifting a 1 by <code>errNumber</code> bits and doing a <code>test</code>, but is still 1 cycle latency and only a single Intel uop. It's slow with a memory arg because of its way-too-CISC semantics: with a memory operand for the \"bit string\", the address of the byte to be tested is computed based on the other arg (divided by 8), and isn't limited to the 1, 2, 4, or 8byte chunk pointed to by the memory operand.</p>\n\n<p>From <a href=\"http://agner.org/optimize/\" rel=\"noreferrer\">Agner Fog's instruction tables</a>, a variable-count shift instruction is slower than a <code>bt</code> on recent Intel (2 uops instead of 1, and shift doesn't do everything else that's needed).</p>\n" }, { "answer_id": 42406571, "author": "Jordan Effinger", "author_id": 7455487, "author_profile": "https://Stackoverflow.com/users/7455487", "pm_score": 0, "selected": false, "text": "<p>When it comes to compiling the program, I don't know if there is any difference. But as for the program itself and keeping the code as simple as possible, I personally think it depends on what you want to do. if else if else statements have their advantages, which I think are:</p>\n\n<p>allow you to test a variable against specific ranges\nyou can use functions (Standard Library or Personal) as conditionals.</p>\n\n<p>(example:</p>\n\n<pre><code>`int a;\n cout&lt;&lt;\"enter value:\\n\";\n cin&gt;&gt;a;\n\n if( a &gt; 0 &amp;&amp; a &lt; 5)\n {\n cout&lt;&lt;\"a is between 0, 5\\n\";\n\n }else if(a &gt; 5 &amp;&amp; a &lt; 10)\n\n cout&lt;&lt;\"a is between 5,10\\n\";\n\n }else{\n\n \"a is not an integer, or is not in range 0,10\\n\";\n</code></pre>\n\n<p>However, If else if else statements can get complicated and messy (despite your best attempts) in a hurry. Switch statements tend to be clearer, cleaner, and easier to read; but can only be used to test against specific values (example:</p>\n\n<pre><code>`int a;\n cout&lt;&lt;\"enter value:\\n\";\n cin&gt;&gt;a;\n\n switch(a)\n {\n case 0:\n case 1:\n case 2: \n case 3:\n case 4:\n case 5:\n cout&lt;&lt;\"a is between 0,5 and equals: \"&lt;&lt;a&lt;&lt;\"\\n\";\n break;\n //other case statements\n default:\n cout&lt;&lt;\"a is not between the range or is not a good value\\n\"\n break;\n</code></pre>\n\n<p>I prefer if - else if - else statements, but it really is up to you. If you want to use functions as the conditions, or you want to test something against a range, array, or vector and/or you don't mind dealing with the complicated nesting, I would recommend using If else if else blocks. If you want to test against single values or you want a clean and easy to read block, I would recommend you use switch() case blocks.</p>\n" }, { "answer_id": 66429462, "author": "Kai Petzke", "author_id": 2528436, "author_profile": "https://Stackoverflow.com/users/2528436", "pm_score": 3, "selected": false, "text": "<p>Sorry to disagree with the current accepted answer. This is the year 2021. Modern compilers and their optimizers shouldn't differentiate between <code>switch</code> and an equivalent <code>if</code>-chain anymore. If they still do, and create poorly optimized code for either variant, then write to the compiler vendor (or make it public here, which has a higher change of being respected), but don't let micro-optimizations influence your coding style.</p>\n<p>So, if you use:</p>\n<pre><code>switch (numError) { case ERROR_A: case ERROR_B: ... }\n</code></pre>\n<p>or:</p>\n<pre><code>if(numError == ERROR_A || numError == ERROR_B || ...) { ... }\n</code></pre>\n<p>or:</p>\n<pre><code>template&lt;typename C, typename EL&gt;\nbool has(const C&amp; cont, const EL&amp; el) {\n return std::find(cont.begin(), cont.end(), el) != cont.end();\n}\n\nconstexpr std::array errList = { ERROR_A, ERROR_B, ... };\nif(has(errList, rnd)) { ... }\n</code></pre>\n<p>shouldn't make a difference with respect to execution speed. But depending on what project you are working on, they might make a big difference in coding clarity and code maintainability. For example, if you have to check for a certain error list in many places of the code, the templated <code>has()</code> might be much easier to maintain, as the errList needs to be updated only in one place.</p>\n<p>Talking about current compilers, I have compiled the test code quoted below with both <code>clang++ -O3 -std=c++1z</code> (version 10 and 11) and <code>g++ -O3 -std=c++1z</code>. Both clang versions gave similiar compiled code and execution times. So I am talking only about version 11 from now on. Most notably, <code>functionA()</code> (which uses <code>if</code>) and <code>functionB()</code> (which uses <code>switch</code>) produce exactly the same assembler output with <code>clang</code>! And <code>functionC()</code> uses a jump table, even though many other posters deemed jump tables to be an exclusive feature of <code>switch</code>. However, despite many people considering jump tables to be optimal, that was actually the slowest solution on <code>clang</code>: <code>functionC()</code> needs around 20 percent more execution time than <code>functionA()</code> or <code>functionB()</code>.</p>\n<p>The hand-optimized version <code>functionH()</code> was by far the fastest on <code>clang</code>. It even unrolled the loop partially, doing two iterations on each loop.</p>\n<p>Actually, <code>clang</code> calculated the bitfield, which is explicitely supplied in <code>functionH()</code>, also in <code>functionA()</code> and <code>functionB()</code>. However, it used conditional branches in <code>functionA()</code> and <code>functionB()</code>, which made these slow, because branch prediction fails regularly, while it used the much more efficient <code>adc</code> (&quot;add with carry&quot;) in <code>functionH()</code>. While it failed to apply this obvious optimization also in the other variants, is unknown to me.</p>\n<p>The code produced by <code>g++</code> looks much more complicated than that of <code>clang</code> - but actually runs a bit faster for <code>functionA()</code> and quite a lot faster for <code>functionC()</code>. Of the non-hand-optimized functions, <code>functionC()</code> is the fastest on <code>g++</code> and faster than any of the functions on <code>clang</code>. On the contrary, <code>functionH()</code> requires twice the execution time when compiled with <code>g++</code> instead of with <code>clang</code>, mostly because <code>g++</code> doesn't do the loop unrolling.</p>\n<p>Here are the detailed results:</p>\n<pre><code>clang:\nfunctionA: 109877 3627\nfunctionB: 109877 3626\nfunctionC: 109877 4192\nfunctionH: 109877 524\n\ng++:\nfunctionA: 109877 3337\nfunctionB: 109877 4668\nfunctionC: 109877 2890\nfunctionH: 109877 982\n</code></pre>\n<p>The Performance changes drastically, if the constant <code>32</code> is changed to <code>63</code> in the whole code:</p>\n<pre><code>clang:\nfunctionA: 106943 1435\nfunctionB: 106943 1436\nfunctionC: 106943 4191\nfunctionH: 106943 524\n\ng++:\nfunctionA: 106943 1265\nfunctionB: 106943 4481\nfunctionC: 106943 2804\nfunctionH: 106943 1038\n</code></pre>\n<p>The reason for the speedup is, that in case, that the highest tested value is 63, the compilers remove some unnecessary bound checks, because the value of <code>rnd</code> is bound to 63, anyways. Note that with that bound check removed, the non-optimized <code>functionA()</code> using simple <code>if()</code> on <code>g++</code> performs almost as fast as the hand-optimized <code>functionH()</code>, and it also produces rather similiar assembler output.</p>\n<p>What is the conclusion? If you hand-optimize and test compilers a lot, you will get the fastest solution. Any assumption whether <code>switch</code> or <code>if</code> is better, is void - they are the same on <code>clang</code>. And the easy to code solution to check against an <code>array</code> of values is actually the fastest case on <code>g++</code> (if leaving out hand-optimization and by-incident matching last values of the list).</p>\n<p>Future compiler versions will optimize your code better and better and get closer to your hand optimization. So don't waste your time on it, unless cycles are REALLY crucial in your case.</p>\n<p>Here the test code:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;chrono&gt;\n#include &lt;limits&gt;\n#include &lt;array&gt;\n#include &lt;algorithm&gt;\n\nunsigned long long functionA() {\n unsigned long long cnt = 0;\n\n for(unsigned long long i = 0; i &lt; 1000000; i++) {\n unsigned char rnd = (((i * (i &gt;&gt; 3)) &gt;&gt; 8) ^ i) &amp; 63;\n if(rnd == 1 || rnd == 7 || rnd == 10 || rnd == 16 ||\n rnd == 21 || rnd == 22 || rnd == 63)\n {\n cnt += 1;\n }\n }\n\n return cnt;\n}\n\nunsigned long long functionB() {\n unsigned long long cnt = 0;\n\n for(unsigned long long i = 0; i &lt; 1000000; i++) {\n unsigned char rnd = (((i * (i &gt;&gt; 3)) &gt;&gt; 8) ^ i) &amp; 63;\n switch(rnd) {\n case 1:\n case 7:\n case 10:\n case 16:\n case 21:\n case 22:\n case 63:\n cnt++;\n break;\n }\n }\n\n return cnt;\n}\n\ntemplate&lt;typename C, typename EL&gt;\nbool has(const C&amp; cont, const EL&amp; el) {\n return std::find(cont.begin(), cont.end(), el) != cont.end();\n}\n\nunsigned long long functionC() {\n unsigned long long cnt = 0;\n constexpr std::array errList { 1, 7, 10, 16, 21, 22, 63 };\n\n for(unsigned long long i = 0; i &lt; 1000000; i++) {\n unsigned char rnd = (((i * (i &gt;&gt; 3)) &gt;&gt; 8) ^ i) &amp; 63;\n cnt += has(errList, rnd);\n }\n\n return cnt;\n}\n\n// Hand optimized version (manually created bitfield):\nunsigned long long functionH() {\n unsigned long long cnt = 0;\n\n const unsigned long long bitfield =\n (1ULL &lt;&lt; 1) +\n (1ULL &lt;&lt; 7) +\n (1ULL &lt;&lt; 10) +\n (1ULL &lt;&lt; 16) +\n (1ULL &lt;&lt; 21) +\n (1ULL &lt;&lt; 22) +\n (1ULL &lt;&lt; 63);\n\n for(unsigned long long i = 0; i &lt; 1000000; i++) {\n unsigned char rnd = (((i * (i &gt;&gt; 3)) &gt;&gt; 8) ^ i) &amp; 63;\n if(bitfield &amp; (1ULL &lt;&lt; rnd)) {\n cnt += 1;\n }\n }\n\n return cnt;\n}\n\nvoid timeit(unsigned long long (*function)(), const char* message)\n{\n unsigned long long mintime = std::numeric_limits&lt;unsigned long long&gt;::max();\n unsigned long long fres = 0;\n\n for(int i = 0; i &lt; 100; i++) {\n auto t1 = std::chrono::high_resolution_clock::now();\n fres = function();\n auto t2 = std::chrono::high_resolution_clock::now();\n\n auto duration = std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(t2 - t1).count();\n if(duration &lt; mintime) {\n mintime = duration;\n }\n }\n\n std::cout &lt;&lt; message &lt;&lt; fres &lt;&lt; &quot; &quot; &lt;&lt; mintime &lt;&lt; std::endl;\n}\n\n\nint main(int argc, char* argv[]) {\n timeit(functionA, &quot;functionA: &quot;);\n timeit(functionB, &quot;functionB: &quot;);\n timeit(functionC, &quot;functionC: &quot;);\n timeit(functionH, &quot;functionH: &quot;);\n timeit(functionA, &quot;functionA: &quot;);\n timeit(functionB, &quot;functionB: &quot;);\n timeit(functionC, &quot;functionC: &quot;);\n timeit(functionH, &quot;functionH: &quot;);\n timeit(functionA, &quot;functionA: &quot;);\n timeit(functionB, &quot;functionB: &quot;);\n timeit(functionC, &quot;functionC: &quot;);\n timeit(functionH, &quot;functionH: &quot;);\n\n return 0;\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/97987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8883/" ]
What's the best practice for using a `switch` statement vs using an `if` statement for 30 `unsigned` enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventions. `switch` statement: ``` // numError is an error enumeration type, with 0 being the non-error case // fire_special_event() is a stub method for the shared processing switch (numError) { case ERROR_01 : // intentional fall-through case ERROR_07 : // intentional fall-through case ERROR_0A : // intentional fall-through case ERROR_10 : // intentional fall-through case ERROR_15 : // intentional fall-through case ERROR_16 : // intentional fall-through case ERROR_20 : { fire_special_event(); } break; default: { // error codes that require no additional action } break; } ``` `if` statement: ``` if ((ERROR_01 == numError) || (ERROR_07 == numError) || (ERROR_0A == numError) || (ERROR_10 == numError) || (ERROR_15 == numError) || (ERROR_16 == numError) || (ERROR_20 == numError)) { fire_special_event(); } ```
Use switch. In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement. In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).
98,033
<p>Several Linq.Enumerable functions take an <code>IEqualityComparer&lt;T&gt;</code>. Is there a convenient wrapper class that adapts a <code>delegate(T,T)=&gt;bool</code> to implement <code>IEqualityComparer&lt;T&gt;</code>? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution.</p> <p>Specifically, I want to do set operations on <code>Dictionary</code>s, using only the Keys to define membership (while retaining the values according to different rules).</p>
[ { "answer_id": 98119, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": false, "text": "<p>I'm afraid there is no such wrapper out-of-box. However it's not hard to create one:</p>\n\n<pre><code>class Comparer&lt;T&gt;: IEqualityComparer&lt;T&gt;\n{\n private readonly Func&lt;T, T, bool&gt; _comparer;\n\n public Comparer(Func&lt;T, T, bool&gt; comparer)\n {\n if (comparer == null)\n throw new ArgumentNullException(\"comparer\");\n\n _comparer = comparer;\n }\n\n public bool Equals(T x, T y)\n {\n return _comparer(x, y);\n }\n\n public int GetHashCode(T obj)\n {\n return obj.ToString().ToLower().GetHashCode();\n }\n}\n\n...\n\nFunc&lt;int, int, bool&gt; f = (x, y) =&gt; x == y;\nvar comparer = new Comparer&lt;int&gt;(f);\nConsole.WriteLine(comparer.Equals(1, 1));\nConsole.WriteLine(comparer.Equals(1, 2));\n</code></pre>\n" }, { "answer_id": 98138, "author": "Gregg", "author_id": 18266, "author_profile": "https://Stackoverflow.com/users/18266", "pm_score": -1, "selected": false, "text": "<p>I don't know of an existing class but something like:</p>\n\n<pre><code>public class MyComparer&lt;T&gt; : IEqualityComparer&lt;T&gt;\n{\n private Func&lt;T, T, bool&gt; _compare;\n MyComparer(Func&lt;T, T, bool&gt; compare)\n {\n _compare = compare;\n }\n\n public bool Equals(T x, Ty)\n {\n return _compare(x, y);\n }\n\n public int GetHashCode(T obj)\n {\n return obj.GetHashCode();\n }\n}\n</code></pre>\n\n<p>Note: I haven't actually compiled and run this yet, so there might be a typo or other bug.</p>\n" }, { "answer_id": 98221, "author": "Marcelo Cantos", "author_id": 9990, "author_profile": "https://Stackoverflow.com/users/9990", "pm_score": 2, "selected": false, "text": "<p>I'm going to answer my own question. To treat Dictionaries as sets, the simplest method seems to be to apply set operations to dict.Keys, then convert back to Dictionaries with Enumerable.ToDictionary(...).</p>\n" }, { "answer_id": 270203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>public class FuncEqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt;\n{\n readonly Func&lt;T, T, bool&gt; _comparer;\n readonly Func&lt;T, int&gt; _hash;\n\n public FuncEqualityComparer( Func&lt;T, T, bool&gt; comparer )\n : this( comparer, t =&gt; t.GetHashCode())\n {\n }\n\n public FuncEqualityComparer( Func&lt;T, T, bool&gt; comparer, Func&lt;T, int&gt; hash )\n {\n _comparer = comparer;\n _hash = hash;\n }\n\n public bool Equals( T x, T y )\n {\n return _comparer( x, y );\n }\n\n public int GetHashCode( T obj )\n {\n return _hash( obj );\n }\n}\n</code></pre>\n\n<p>With extensions :-</p>\n\n<pre><code>public static class SequenceExtensions\n{\n public static bool SequenceEqual&lt;T&gt;( this IEnumerable&lt;T&gt; first, IEnumerable&lt;T&gt; second, Func&lt;T, T, bool&gt; comparer )\n {\n return first.SequenceEqual( second, new FuncEqualityComparer&lt;T&gt;( comparer ) );\n }\n\n public static bool SequenceEqual&lt;T&gt;( this IEnumerable&lt;T&gt; first, IEnumerable&lt;T&gt; second, Func&lt;T, T, bool&gt; comparer, Func&lt;T, int&gt; hash )\n {\n return first.SequenceEqual( second, new FuncEqualityComparer&lt;T&gt;( comparer, hash ) );\n }\n}\n</code></pre>\n" }, { "answer_id": 1239337, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 7, "selected": false, "text": "<p>When you want to customize equality checking, 99% of the time you're interested in defining the keys to compare by, not the comparison itself.</p>\n\n<p>This could be an elegant solution (concept from Python's <a href=\"http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys\" rel=\"noreferrer\">list sort method</a>).</p>\n\n<p>Usage:</p>\n\n<pre><code>var foo = new List&lt;string&gt; { \"abc\", \"de\", \"DE\" };\n\n// case-insensitive distinct\nvar distinct = foo.Distinct(new KeyEqualityComparer&lt;string&gt;( x =&gt; x.ToLower() ) );\n</code></pre>\n\n<p>The <code>KeyEqualityComparer</code> class:</p>\n\n<pre><code>public class KeyEqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt;\n{\n private readonly Func&lt;T, object&gt; keyExtractor;\n\n public KeyEqualityComparer(Func&lt;T,object&gt; keyExtractor)\n {\n this.keyExtractor = keyExtractor;\n }\n\n public bool Equals(T x, T y)\n {\n return this.keyExtractor(x).Equals(this.keyExtractor(y));\n }\n\n public int GetHashCode(T obj)\n {\n return this.keyExtractor(obj).GetHashCode();\n }\n}\n</code></pre>\n" }, { "answer_id": 3142096, "author": "Sushil", "author_id": 379132, "author_profile": "https://Stackoverflow.com/users/379132", "pm_score": 1, "selected": false, "text": "<p>Just one optimization:\nWe can use the out-of-the-box EqualityComparer for value comparisions, rather than delegating it.</p>\n\n<p>This would also make the implementation cleaner as actual comparision logic now stays in GetHashCode() and Equals() which you may have already overloaded.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>public class MyComparer&lt;T&gt; : IEqualityComparer&lt;T&gt; \n{ \n public bool Equals(T x, T y) \n { \n return EqualityComparer&lt;T&gt;.Default.Equals(x, y); \n } \n\n public int GetHashCode(T obj) \n { \n return obj.GetHashCode(); \n } \n} \n</code></pre>\n\n<p>Don't forget to overload GetHashCode() and Equals() methods on your object.</p>\n\n<p>This post helped me: <a href=\"https://stackoverflow.com/questions/488250/c-compare-two-generic-values\">c# compare two generic values</a></p>\n\n<p>Sushil</p>\n" }, { "answer_id": 3719617, "author": "Ruben Bartelink", "author_id": 11635, "author_profile": "https://Stackoverflow.com/users/11635", "pm_score": 7, "selected": true, "text": "<p>Ordinarily, I'd get this resolved by commenting @Sam on the answer (I've done some editing on the original post to clean it up a bit without altering the behavior.)</p>\n\n<p>The following is my riff of <a href=\"https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/270203#270203\">@Sam's answer</a>, with a [IMNSHO] critical fix to the default hashing policy:-</p>\n\n<pre><code>class FuncEqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt;\n{\n readonly Func&lt;T, T, bool&gt; _comparer;\n readonly Func&lt;T, int&gt; _hash;\n\n public FuncEqualityComparer( Func&lt;T, T, bool&gt; comparer )\n : this( comparer, t =&gt; 0 ) // NB Cannot assume anything about how e.g., t.GetHashCode() interacts with the comparer's behavior\n {\n }\n\n public FuncEqualityComparer( Func&lt;T, T, bool&gt; comparer, Func&lt;T, int&gt; hash )\n {\n _comparer = comparer;\n _hash = hash;\n }\n\n public bool Equals( T x, T y )\n {\n return _comparer( x, y );\n }\n\n public int GetHashCode( T obj )\n {\n return _hash( obj );\n }\n}\n</code></pre>\n" }, { "answer_id": 3719802, "author": "Dan Tao", "author_id": 105570, "author_profile": "https://Stackoverflow.com/users/105570", "pm_score": 7, "selected": false, "text": "<h1>On the importance of <code>GetHashCode</code></h1>\n\n<p>Others have already commented on the fact that any custom <code>IEqualityComparer&lt;T&gt;</code> implementation <strong>should really include a <code>GetHashCode</code> method</strong>; but nobody's bothered to explain <em>why</em> in any detail.</p>\n\n<p>Here's why. Your question specifically mentions the LINQ extension methods; nearly <em>all</em> of these rely on hash codes to work properly, because they utilize hash tables internally for efficiency.</p>\n\n<p>Take <a href=\"http://msdn.microsoft.com/en-us/library/bb338049.aspx\" rel=\"noreferrer\"><code>Distinct</code></a>, for example. Consider the implications of this extension method if all it utilized were an <code>Equals</code> method. How do you determine whether an item's already been scanned in a sequence if you only have <code>Equals</code>? You enumerate over the entire collection of values you've already looked at and check for a match. This would result in <code>Distinct</code> using a worst-case O(N<sup>2</sup>) algorithm instead of an O(N) one!</p>\n\n<p>Fortunately, this isn't the case. <code>Distinct</code> doesn't <em>just</em> use <code>Equals</code>; it uses <code>GetHashCode</code> as well. In fact, <em>it absolutely <strong>does not</strong> work properly without an <code>IEqualityComparer&lt;T&gt;</code> that supplies a proper <code>GetHashCode</code></em>. Below is a contrived example illustrating this.</p>\n\n<p>Say I have the following type:</p>\n\n<pre><code>class Value\n{\n public string Name { get; private set; }\n public int Number { get; private set; }\n\n public Value(string name, int number)\n {\n Name = name;\n Number = number;\n }\n\n public override string ToString()\n {\n return string.Format(\"{0}: {1}\", Name, Number);\n }\n}\n</code></pre>\n\n<p>Now say I have a <code>List&lt;Value&gt;</code> and I want to find all of the elements with a distinct name. This is a perfect use case for <code>Distinct</code> using a custom equality comparer. So let's use the <code>Comparer&lt;T&gt;</code> class from <a href=\"https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/98119#98119\">Aku's answer</a>:</p>\n\n<pre><code>var comparer = new Comparer&lt;Value&gt;((x, y) =&gt; x.Name == y.Name);\n</code></pre>\n\n<p>Now, if we have a bunch of <code>Value</code> elements with the same <code>Name</code> property, they should all collapse into one value returned by <code>Distinct</code>, right? Let's see...</p>\n\n<pre><code>var values = new List&lt;Value&gt;();\n\nvar random = new Random();\nfor (int i = 0; i &lt; 10; ++i)\n{\n values.Add(\"x\", random.Next());\n}\n\nvar distinct = values.Distinct(comparer);\n\nforeach (Value x in distinct)\n{\n Console.WriteLine(x);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nx: 1346013431\nx: 1388845717\nx: 1576754134\nx: 1104067189\nx: 1144789201\nx: 1862076501\nx: 1573781440\nx: 646797592\nx: 655632802\nx: 1206819377\n</pre>\n\n<p>Hmm, that didn't work, did it?</p>\n\n<p>What about <a href=\"http://msdn.microsoft.com/en-us/library/bb534334.aspx\" rel=\"noreferrer\"><code>GroupBy</code></a>? Let's try that:</p>\n\n<pre><code>var grouped = values.GroupBy(x =&gt; x, comparer);\n\nforeach (IGrouping&lt;Value&gt; g in grouped)\n{\n Console.WriteLine(\"[KEY: '{0}']\", g);\n foreach (Value x in g)\n {\n Console.WriteLine(x);\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\n[KEY = 'x: 1346013431']\nx: 1346013431\n[KEY = 'x: 1388845717']\nx: 1388845717\n[KEY = 'x: 1576754134']\nx: 1576754134\n[KEY = 'x: 1104067189']\nx: 1104067189\n[KEY = 'x: 1144789201']\nx: 1144789201\n[KEY = 'x: 1862076501']\nx: 1862076501\n[KEY = 'x: 1573781440']\nx: 1573781440\n[KEY = 'x: 646797592']\nx: 646797592\n[KEY = 'x: 655632802']\nx: 655632802\n[KEY = 'x: 1206819377']\nx: 1206819377\n</pre>\n\n<p>Again: didn't work.</p>\n\n<p>If you think about it, it would make sense for <code>Distinct</code> to use a <code>HashSet&lt;T&gt;</code> (or equivalent) internally, and for <code>GroupBy</code> to use something like a <code>Dictionary&lt;TKey, List&lt;T&gt;&gt;</code> internally. Could this explain why these methods don't work? Let's try this:</p>\n\n<pre><code>var uniqueValues = new HashSet&lt;Value&gt;(values, comparer);\n\nforeach (Value x in uniqueValues)\n{\n Console.WriteLine(x);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nx: 1346013431\nx: 1388845717\nx: 1576754134\nx: 1104067189\nx: 1144789201\nx: 1862076501\nx: 1573781440\nx: 646797592\nx: 655632802\nx: 1206819377\n</pre>\n\n<p>Yeah... starting to make sense?</p>\n\n<p>Hopefully from these examples it's clear why including an appropriate <code>GetHashCode</code> in any <code>IEqualityComparer&lt;T&gt;</code> implementation is so important.</p>\n\n<hr>\n\n<h1>Original answer</h1>\n\n<p>Expanding on <a href=\"https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/1239337#1239337\">orip's answer</a>:</p>\n\n<p>There are a couple of improvements that can be made here.</p>\n\n<ol>\n<li>First, I'd take a <code>Func&lt;T, TKey&gt;</code> instead of <code>Func&lt;T, object&gt;</code>; this will prevent boxing of value type keys in the actual <code>keyExtractor</code> itself.</li>\n<li>Second, I'd actually add a <code>where TKey : IEquatable&lt;TKey&gt;</code> constraint; this will prevent boxing in the <code>Equals</code> call (<code>object.Equals</code> takes an <code>object</code> parameter; you need an <code>IEquatable&lt;TKey&gt;</code> implementation to take a <code>TKey</code> parameter without boxing it). Clearly this may pose too severe a restriction, so you could make a base class without the constraint and a derived class with it.</li>\n</ol>\n\n<p>Here's what the resulting code might look like:</p>\n\n<pre><code>public class KeyEqualityComparer&lt;T, TKey&gt; : IEqualityComparer&lt;T&gt;\n{\n protected readonly Func&lt;T, TKey&gt; keyExtractor;\n\n public KeyEqualityComparer(Func&lt;T, TKey&gt; keyExtractor)\n {\n this.keyExtractor = keyExtractor;\n }\n\n public virtual bool Equals(T x, T y)\n {\n return this.keyExtractor(x).Equals(this.keyExtractor(y));\n }\n\n public int GetHashCode(T obj)\n {\n return this.keyExtractor(obj).GetHashCode();\n }\n}\n\npublic class StrictKeyEqualityComparer&lt;T, TKey&gt; : KeyEqualityComparer&lt;T, TKey&gt;\n where TKey : IEquatable&lt;TKey&gt;\n{\n public StrictKeyEqualityComparer(Func&lt;T, TKey&gt; keyExtractor)\n : base(keyExtractor)\n { }\n\n public override bool Equals(T x, T y)\n {\n // This will use the overload that accepts a TKey parameter\n // instead of an object parameter.\n return this.keyExtractor(x).Equals(this.keyExtractor(y));\n }\n}\n</code></pre>\n" }, { "answer_id": 6150492, "author": "Bruno", "author_id": 168043, "author_profile": "https://Stackoverflow.com/users/168043", "pm_score": 3, "selected": false, "text": "<p>orip's answer is great.</p>\n\n<p>Here a little extension method to make it even easier:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Distinct&lt;T&gt;(this IEnumerable&lt;T&gt; list, Func&lt;T, object&gt; keyExtractor)\n{\n return list.Distinct(new KeyEqualityComparer&lt;T&gt;(keyExtractor));\n}\nvar distinct = foo.Distinct(x =&gt; x.ToLower())\n</code></pre>\n" }, { "answer_id": 6176711, "author": "Max", "author_id": 260093, "author_profile": "https://Stackoverflow.com/users/260093", "pm_score": 0, "selected": false, "text": "<pre><code>public static Dictionary&lt;TKey, TValue&gt; Distinct&lt;TKey, TValue&gt;(this IEnumerable&lt;TValue&gt; items, Func&lt;TValue, TKey&gt; selector)\n {\n Dictionary&lt;TKey, TValue&gt; result = null;\n ICollection collection = items as ICollection;\n if (collection != null)\n result = new Dictionary&lt;TKey, TValue&gt;(collection.Count);\n else\n result = new Dictionary&lt;TKey, TValue&gt;();\n foreach (TValue item in items)\n result[selector(item)] = item;\n return result;\n }\n</code></pre>\n\n<p>This makes it possible to select a property with lambda like this: <code>.Select(y =&gt; y.Article).Distinct(x =&gt; x.ArticleID);</code></p>\n" }, { "answer_id": 6913646, "author": "ldp615", "author_id": 285996, "author_profile": "https://Stackoverflow.com/users/285996", "pm_score": 5, "selected": false, "text": "<p>Same as Dan Tao's answer, but with a few improvements:</p>\n<ol>\n<li><p>Relies on <code>EqualityComparer&lt;&gt;.Default</code> to do the actual comparing so that it avoids boxing for value types (<code>struct</code>s) that has implemented <code>IEquatable&lt;&gt;</code>.</p>\n</li>\n<li><p>Since <code>EqualityComparer&lt;&gt;.Default</code> used it doesn't explode on <code>null.Equals(something)</code>.</p>\n</li>\n<li><p>Provided static wrapper around <code>IEqualityComparer&lt;&gt;</code> which will have a static method to create the instance of comparer - eases calling. Compare</p>\n<pre><code> Equality&lt;Person&gt;.CreateComparer(p =&gt; p.ID);\n</code></pre>\n<p>with</p>\n<pre><code> new EqualityComparer&lt;Person, int&gt;(p =&gt; p.ID);\n</code></pre>\n</li>\n<li><p>Added an overload to specify <code>IEqualityComparer&lt;&gt;</code> for the key.</p>\n</li>\n</ol>\n<p><strong>The class:</strong></p>\n<pre><code>public static class Equality&lt;T&gt;\n{\n public static IEqualityComparer&lt;T&gt; CreateComparer&lt;V&gt;(Func&lt;T, V&gt; keySelector)\n {\n return CreateComparer(keySelector, null);\n }\n\n public static IEqualityComparer&lt;T&gt; CreateComparer&lt;V&gt;(Func&lt;T, V&gt; keySelector, \n IEqualityComparer&lt;V&gt; comparer)\n {\n return new KeyEqualityComparer&lt;V&gt;(keySelector, comparer);\n }\n\n class KeyEqualityComparer&lt;V&gt; : IEqualityComparer&lt;T&gt;\n {\n readonly Func&lt;T, V&gt; keySelector;\n readonly IEqualityComparer&lt;V&gt; comparer;\n\n public KeyEqualityComparer(Func&lt;T, V&gt; keySelector, \n IEqualityComparer&lt;V&gt; comparer)\n {\n if (keySelector == null)\n throw new ArgumentNullException(nameof(keySelector));\n\n this.keySelector = keySelector;\n this.comparer = comparer ?? EqualityComparer&lt;V&gt;.Default;\n }\n\n public bool Equals(T x, T y)\n {\n return comparer.Equals(keySelector(x), keySelector(y));\n }\n\n public int GetHashCode(T obj)\n {\n return comparer.GetHashCode(keySelector(obj));\n }\n }\n}\n</code></pre>\n<p>you may use it like this:</p>\n<pre><code>var comparer1 = Equality&lt;Person&gt;.CreateComparer(p =&gt; p.ID);\nvar comparer2 = Equality&lt;Person&gt;.CreateComparer(p =&gt; p.Name);\nvar comparer3 = Equality&lt;Person&gt;.CreateComparer(p =&gt; p.Birthday.Year);\nvar comparer4 = Equality&lt;Person&gt;.CreateComparer(p =&gt; p.Name, StringComparer.CurrentCultureIgnoreCase);\n</code></pre>\n<p>Person is a simple class:</p>\n<pre><code>class Person\n{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime Birthday { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 10040172, "author": "matrix", "author_id": 1295274, "author_profile": "https://Stackoverflow.com/users/1295274", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/1239337/1295274\">orip's answer</a> is great. Expanding on orip's answer:</p>\n\n<p>i think that the solution's key is use \"Extension Method\" to transfer the \"anonymous type\".</p>\n\n<pre><code> public static class Comparer \n {\n public static IEqualityComparer&lt;T&gt; CreateComparerForElements&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, Func&lt;T, object&gt; keyExtractor)\n {\n return new KeyEqualityComparer&lt;T&gt;(keyExtractor);\n }\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var n = ItemList.Select(s =&gt; new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList();\nn.AddRange(OtherList.Select(s =&gt; new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList(););\nn = n.Distinct(x=&gt;new{Vchr=x.Vchr,Id=x.Id}).ToList();\n</code></pre>\n" }, { "answer_id": 17379690, "author": "Fried", "author_id": 2534462, "author_profile": "https://Stackoverflow.com/users/2534462", "pm_score": 2, "selected": false, "text": "<p>The implementation at (german text) <a href=\"http://web.archive.org/web/20151126060513/http://flurfunk.sdx-ag.de/2013/06/linq-iequalitycomparer-durch-lambda.html\" rel=\"nofollow noreferrer\">Implementing IEqualityCompare with lambda expression</a>\ncares about null values and uses extension methods to generate IEqualityComparer.</p>\n<p>To create an IEqualityComparer in a Linq union your just have to write</p>\n<pre><code>persons1.Union(persons2, person =&gt; person.LastName)\n</code></pre>\n<p>The comparer:</p>\n<pre><code>public class LambdaEqualityComparer&lt;TSource, TComparable&gt; : IEqualityComparer&lt;TSource&gt;\n{\n Func&lt;TSource, TComparable&gt; _keyGetter;\n \n public LambdaEqualityComparer(Func&lt;TSource, TComparable&gt; keyGetter)\n {\n _keyGetter = keyGetter;\n }\n \n public bool Equals(TSource x, TSource y)\n {\n if (x == null || y == null) return (x == null &amp;&amp; y == null);\n return object.Equals(_keyGetter(x), _keyGetter(y));\n }\n \n public int GetHashCode(TSource obj)\n {\n if (obj == null) return int.MinValue;\n var k = _keyGetter(obj);\n if (k == null) return int.MaxValue;\n return k.GetHashCode();\n }\n}\n</code></pre>\n<p>You also need to add an extension method to support type inference</p>\n<pre><code>public static class LambdaEqualityComparer\n{\n // source1.Union(source2, lambda)\n public static IEnumerable&lt;TSource&gt; Union&lt;TSource, TComparable&gt;(\n this IEnumerable&lt;TSource&gt; source1, \n IEnumerable&lt;TSource&gt; source2, \n Func&lt;TSource, TComparable&gt; keySelector)\n {\n return source1.Union(source2, \n new LambdaEqualityComparer&lt;TSource, TComparable&gt;(keySelector));\n }\n }\n</code></pre>\n" }, { "answer_id": 73979911, "author": "Tomas C", "author_id": 7226886, "author_profile": "https://Stackoverflow.com/users/7226886", "pm_score": 0, "selected": false, "text": "<pre><code>public class DelegateEqualityComparer&lt;T&gt;: IEqualityComparer&lt;T&gt;\n{\n private readonly Func&lt;T, T, bool&gt; _equalsDelegate;\n private readonly Func&lt;T, int&gt; _getHashCodeDelegate;\n\n public DelegateEqualityComparer(Func&lt;T, T, bool&gt; equalsDelegate, Func&lt;T, int&gt; getHashCodeDelegate)\n {\n _equalsDelegate = equalsDelegate ?? ((tx, ty) =&gt; object.Equals(tx, ty));\n _getHashCodeDelegate = getHashCodeDelegate ?? (t =&gt; t.GetSafeHashCode());\n }\n\n public bool Equals(T x, T y) =&gt; _equalsDelegate(x, y);\n\n public int GetHashCode(T obj) =&gt; _getHashCodeDelegate(obj);\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/98033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9990/" ]
Several Linq.Enumerable functions take an `IEqualityComparer<T>`. Is there a convenient wrapper class that adapts a `delegate(T,T)=>bool` to implement `IEqualityComparer<T>`? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution. Specifically, I want to do set operations on `Dictionary`s, using only the Keys to define membership (while retaining the values according to different rules).
Ordinarily, I'd get this resolved by commenting @Sam on the answer (I've done some editing on the original post to clean it up a bit without altering the behavior.) The following is my riff of [@Sam's answer](https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/270203#270203), with a [IMNSHO] critical fix to the default hashing policy:- ``` class FuncEqualityComparer<T> : IEqualityComparer<T> { readonly Func<T, T, bool> _comparer; readonly Func<T, int> _hash; public FuncEqualityComparer( Func<T, T, bool> comparer ) : this( comparer, t => 0 ) // NB Cannot assume anything about how e.g., t.GetHashCode() interacts with the comparer's behavior { } public FuncEqualityComparer( Func<T, T, bool> comparer, Func<T, int> hash ) { _comparer = comparer; _hash = hash; } public bool Equals( T x, T y ) { return _comparer( x, y ); } public int GetHashCode( T obj ) { return _hash( obj ); } } ```
98,074
<p>I have a given certificate installed on my server. That certificate has valid dates, and seems perfectly valid in the Windows certificates MMC snap-in.</p> <p>However, when I try to read the certificate, in order to use it in an HttpRequest, I can't find it. Here is the code used:</p> <pre><code> X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySerialNumber, "xxx", true); </code></pre> <p><code>xxx</code> is the serial number; the argument <code>true</code> means "only valid certificates". The returned collection is empty.</p> <p>The strange thing is that if I pass <code>false</code>, indicating invalid certificates are acceptable, the collection contains one element&mdash;the certificate with the specified serial number.</p> <p>In conclusion: the certificate appears valid, but the <code>Find</code> method treats it as invalid! Why?</p>
[ { "answer_id": 98201, "author": "Tim Erickson", "author_id": 8787, "author_profile": "https://Stackoverflow.com/users/8787", "pm_score": 2, "selected": false, "text": "<p>I believe x509 certs are tied to a particular user. Could it be invalid because in the code you are accessing it as a different user than the one for which it was created?</p>\n" }, { "answer_id": 98262, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "<p>Is the issuer's certificate present in the X509Store? A certificate is only valid if it's signed by someone you trust.</p>\n\n<p>Is this a certificate from a real CA, or one that you signed yourself? Certificate signing tools often used by developers, like OpenSSL, don't add some important extensions by default.</p>\n" }, { "answer_id": 98419, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 4, "selected": true, "text": "<p>Try verifying the certificate chain using the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chain.aspx\" rel=\"noreferrer\">X509Chain</a> class. This can tell you exactly why the certificate isn't considered valid.</p>\n\n<p>As erickson suggested, your X509Store may not have the trusted certificate from the CA in the chain. If you used OpenSSL or another tool to generate your own self-signed CA, you need to add the public certificate for that CA to the X509Store.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/98074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18073/" ]
I have a given certificate installed on my server. That certificate has valid dates, and seems perfectly valid in the Windows certificates MMC snap-in. However, when I try to read the certificate, in order to use it in an HttpRequest, I can't find it. Here is the code used: ``` X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySerialNumber, "xxx", true); ``` `xxx` is the serial number; the argument `true` means "only valid certificates". The returned collection is empty. The strange thing is that if I pass `false`, indicating invalid certificates are acceptable, the collection contains one element—the certificate with the specified serial number. In conclusion: the certificate appears valid, but the `Find` method treats it as invalid! Why?
Try verifying the certificate chain using the [X509Chain](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chain.aspx) class. This can tell you exactly why the certificate isn't considered valid. As erickson suggested, your X509Store may not have the trusted certificate from the CA in the chain. If you used OpenSSL or another tool to generate your own self-signed CA, you need to add the public certificate for that CA to the X509Store.
98,096
<p>I've seen some people use <code>EXISTS (SELECT 1 FROM ...)</code> rather than <code>EXISTS (SELECT id FROM ...)</code> as an optimization--rather than looking up and returning a value, SQL Server can simply return the literal it was given.</p> <p>Is <code>SELECT(1)</code> always faster? Would Selecting a value from the table require work that Selecting a literal would avoid?</p>
[ { "answer_id": 98103, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>Yes, because when you select a literal it does not need to read from disk (or even from cache).</p>\n" }, { "answer_id": 98170, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>doesn't matter what you select in an exists clause. most people do select *, then sql server automatically picks the best index</p>\n" }, { "answer_id": 98182, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "<p>When you use SELECT 1, you clearly show (to whoever is reading your code later) that you are <strong>testing</strong> whether the record exists. Even if there is no performance gain (which is to be discussed), there is gain in code readability and maintainability.</p>\n" }, { "answer_id": 98198, "author": "ImJustPondering", "author_id": 17940, "author_profile": "https://Stackoverflow.com/users/17940", "pm_score": -1, "selected": false, "text": "<p>Select 1 should be better to use in your example. Select * gets all the meta-data assoicated with the objects before runtime which adss overhead during the compliation of the query. Though you may not see differences when running both types of queries in your execution plan.</p>\n" }, { "answer_id": 99340, "author": "jalbert", "author_id": 1360388, "author_profile": "https://Stackoverflow.com/users/1360388", "pm_score": 3, "selected": false, "text": "<p>In SQL Server, it does not make a difference whether you use <code>SELECT 1</code> or <code>SELECT *</code> within <code>EXISTS</code>. You are not actually returning the contents of the rows, but that rather the set determined by the <code>WHERE</code> clause is not-empty. Try running the query side-by-side with <code>SET STATISTICS IO ON</code> and you can prove that the approaches are equivalent. Personally I prefer <code>SELECT *</code> within <code>EXISTS</code>.</p>\n" }, { "answer_id": 115881, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As someone pointed out sql server ignores the column selection list in EXISTS so it doesn't matter. I personally tend to use \"<code>SELECT null ...</code>\" to indicate that the value is not used at all.</p>\n" }, { "answer_id": 1602714, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 4, "selected": true, "text": "<p>For google's sake, I'll update this question with the same answer as this one (<a href=\"https://stackoverflow.com/questions/1597442/subquery-using-exists-1-or-exists/\">Subquery using Exists 1 or Exists *</a>) since (currently) an incorrect answer is marked as accepted. Note the SQL standard actually says that EXISTS via * is identical to a constant. </p>\n\n<p>No. This has been covered a bazillion times. SQL Server is smart and knows it is being used for an EXISTS, and returns NO DATA to the system. </p>\n\n<p>Quoth Microsoft:\n<a href=\"http://technet.microsoft.com/en-us/library/ms189259.aspx?ppud=4\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/ms189259.aspx?ppud=4</a></p>\n\n<blockquote>\n <p>The select list of a subquery\n introduced by EXISTS almost always\n consists of an asterisk (*). There is\n no reason to list column names because\n you are just testing whether rows that\n meet the conditions specified in the\n subquery exist.</p>\n</blockquote>\n\n<p>Also, don't believe me? Try running the following:</p>\n\n<pre><code>SELECT whatever\n FROM yourtable\n WHERE EXISTS( SELECT 1/0\n FROM someothertable \n WHERE a_valid_clause )\n</code></pre>\n\n<p>If it was actually doing something with the SELECT list, it would throw a div by zero error. It doesn't.</p>\n\n<p>EDIT: Note, the SQL Standard actually talks about this.</p>\n\n<p>ANSI SQL 1992 Standard, pg 191 <a href=\"http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt\" rel=\"nofollow noreferrer\">http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt</a></p>\n\n<blockquote>\n<pre><code> 3) Case:\n\n a) If the &lt;select list&gt; \"*\" is simply contained in a &lt;subquery&gt; that is immediately contained in an &lt;exists predicate&gt;, then the &lt;select list&gt; is equivalent to a &lt;value expression&gt; that is an arbitrary &lt;literal&gt;.\n</code></pre>\n</blockquote>\n" }, { "answer_id": 4348102, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 1, "selected": false, "text": "<p>If you look at the execution plan for </p>\n\n<pre><code>select COUNT(1) from master..spt_values\n</code></pre>\n\n<p>and look at the stream aggregate you will see that it calculates</p>\n\n<pre><code>Scalar Operator(Count(*))\n</code></pre>\n\n<p>So the <code>1</code> actually gets converted to <code>*</code></p>\n\n<p>However I have read somewhere in the \"Inside SQL Server\" series of books that <code>*</code> might incur a very slight overhead for checking column permissions. Unfortunately the book didn't go into any more detail than that as I recall.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/98096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18347/" ]
I've seen some people use `EXISTS (SELECT 1 FROM ...)` rather than `EXISTS (SELECT id FROM ...)` as an optimization--rather than looking up and returning a value, SQL Server can simply return the literal it was given. Is `SELECT(1)` always faster? Would Selecting a value from the table require work that Selecting a literal would avoid?
For google's sake, I'll update this question with the same answer as this one ([Subquery using Exists 1 or Exists \*](https://stackoverflow.com/questions/1597442/subquery-using-exists-1-or-exists/)) since (currently) an incorrect answer is marked as accepted. Note the SQL standard actually says that EXISTS via \* is identical to a constant. No. This has been covered a bazillion times. SQL Server is smart and knows it is being used for an EXISTS, and returns NO DATA to the system. Quoth Microsoft: <http://technet.microsoft.com/en-us/library/ms189259.aspx?ppud=4> > > The select list of a subquery > introduced by EXISTS almost always > consists of an asterisk (\*). There is > no reason to list column names because > you are just testing whether rows that > meet the conditions specified in the > subquery exist. > > > Also, don't believe me? Try running the following: ``` SELECT whatever FROM yourtable WHERE EXISTS( SELECT 1/0 FROM someothertable WHERE a_valid_clause ) ``` If it was actually doing something with the SELECT list, it would throw a div by zero error. It doesn't. EDIT: Note, the SQL Standard actually talks about this. ANSI SQL 1992 Standard, pg 191 <http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt> > > > ``` > 3) Case: > > a) If the <select list> "*" is simply contained in a <subquery> that is immediately contained in an <exists predicate>, then the <select list> is equivalent to a <value expression> that is an arbitrary <literal>. > > ``` > >
98,122
<p>I am getting the following error when running a reporting services report.</p> <pre><code>Process name: w3wp.exe Account name: NT AUTHORITY\NETWORK SERVICE Exception information: Exception type: XmlException Exception message: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pass the settings into XmlReader.Create method. </code></pre> <p>I select a report, enter the parameters(the parameters look messed up) and then press view report. Then at the bottom the message "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings ..." shows up.</p> <p>How do I fix this?</p>
[ { "answer_id": 98558, "author": "Bart", "author_id": 16980, "author_profile": "https://Stackoverflow.com/users/16980", "pm_score": 1, "selected": false, "text": "<p>Check to see if your reporting server website has the correct local path folder. You might need to do an iisreset if it is not correct. </p>\n" }, { "answer_id": 3924096, "author": "Spud1", "author_id": 238950, "author_profile": "https://Stackoverflow.com/users/238950", "pm_score": 0, "selected": false, "text": "<p>I have noticed this when using SSRS 2005 and running large reports containing XML data.</p>\n\n<p>It would work when running say a monthly report, but give me this error when I ran a quarterly report.</p>\n\n<p>Upgrading to SQL/SSRS 2008 fixed the issue for me!</p>\n" }, { "answer_id": 52098172, "author": "Adaptabi", "author_id": 219349, "author_profile": "https://Stackoverflow.com/users/219349", "pm_score": 1, "selected": false, "text": "<p>In my case the URL to download the xml file was actually enforcing the Form Authentication, so instead of getting the XML the reporting services was getting the ASP.NET / HTML login form.</p>\n\n<p>To avoid half of a day of research, you should test your url in a fresh incognito browser in the first place, to make sure it works and you get the plain xml as intended.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/98122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am getting the following error when running a reporting services report. ``` Process name: w3wp.exe Account name: NT AUTHORITY\NETWORK SERVICE Exception information: Exception type: XmlException Exception message: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pass the settings into XmlReader.Create method. ``` I select a report, enter the parameters(the parameters look messed up) and then press view report. Then at the bottom the message "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings ..." shows up. How do I fix this?
Check to see if your reporting server website has the correct local path folder. You might need to do an iisreset if it is not correct.
98,124
<p>Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year?</p> <pre><code>myDate = new Date(); year = myDate.getYear(); </code></pre> <p>year = 108?</p>
[ { "answer_id": 98129, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>It must return the number of years since the year 1900.</p>\n" }, { "answer_id": 98131, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": "<p>The number you get is the number of years since 1900. Don't ask me why..</p>\n" }, { "answer_id": 98136, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>use <code>date.getFullYear()</code>.</p>\n\n<p>This is (as correctly pointed out elsewhere) is a Y2K thing. Netscape (written before 2000) originally returned, for example <code>98</code> from <code>getYear()</code>. Rather than return to <code>00</code>, it instead returned <code>100</code> for the year 2000. Then other browsers came along and did it differently, and everyone was unhappy as incompatibility reigned.</p>\n\n<p>Later browsers supported <code>getFullYear</code> as a standard method to return the complete year.</p>\n" }, { "answer_id": 98139, "author": "user17163", "author_id": 17163, "author_profile": "https://Stackoverflow.com/users/17163", "pm_score": -1, "selected": false, "text": "<p>it is returning 4 digit year - 1900, which may have been cool 9+ years ago, but is pretty retarded now. Java's java.util.Date also does this.</p>\n" }, { "answer_id": 98156, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 1, "selected": false, "text": "<p>It's dumb. It <a href=\"http://www.irt.org/articles/js199/index.htm\" rel=\"nofollow noreferrer\">dates to pre-Y2K days</a>, and now just returns the number of years since 1900 for legacy reasons. Use getFullYear() to get the actual year.</p>\n" }, { "answer_id": 98161, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 0, "selected": false, "text": "<p>As others have said, it returns the number of years since 1900. The reason why it does <em>that</em> is that when JavaScript was invented in the mid-90s, that behaviour was both convenient and consistent with date-time APIs in other languages. Particularly C. And, of course, once the API was established they couldn't change it for backwards compatibility reasons.</p>\n" }, { "answer_id": 98162, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 8, "selected": true, "text": "<p>It's a <a href=\"http://en.wikipedia.org/wiki/Y2K\" rel=\"noreferrer\">Y2K</a> thing, only the years since 1900 are counted.</p>\n<p>There are potential compatibility issues now that <code>getYear()</code> has been deprecated in favour of <code>getFullYear()</code> - from <a href=\"http://www.quirksmode.org/js/introdate.html\" rel=\"noreferrer\">quirksmode</a>:</p>\n<blockquote>\n<p>To make the matter even more complex, date.getYear() is deprecated nowadays and you should use date.getFullYear(), which, in turn, is not supported by the older browsers. If it works, however, it should always give the full year, ie. 2000 instead of 100.</p>\n<p>Your browser gives the following years with these two methods:</p>\n</blockquote>\n<pre><code>* The year according to getYear(): 108\n* The year according to getFullYear(): 2008\n</code></pre>\n<p>There are also implementation differences between Internet Explorer and Firefox, as IE's implementation of <code>getYear()</code> was changed to behave like <code>getFullYear()</code> - from <a href=\"http://www-128.ibm.com/developerworks/web/library/wa-ie2mozgd/\" rel=\"noreferrer\">IBM</a>:</p>\n<blockquote>\n<p>Per the ECMAScript specification, getYear returns the year minus 1900, originally meant to return &quot;98&quot; for 1998. getYear was deprecated in ECMAScript Version 3 and replaced with getFullYear().</p>\n<p>Internet Explorer changed getYear() to work like getFullYear() and make it Y2k-compliant, while Mozilla kept the standard behavior.</p>\n</blockquote>\n" }, { "answer_id": 98192, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 0, "selected": false, "text": "<p>BTW, different browsers might return different results, so it's better to skip this function altogether and and use getFullYear() always.</p>\n" }, { "answer_id": 98237, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "<p>Since getFullYear doesn't work in older browsers, you can use something like this:</p>\n\n<pre><code>Date.prototype.getRealYear = function() \n{ \n if(this.getFullYear)\n return this.getFullYear();\n else\n return this.getYear() + 1900; \n};\n</code></pre>\n\n<p>Javascript prototype can be used to extend existing objects, much like C# extension methods. Now, we can just do this;</p>\n\n<pre><code>var myDate = new Date();\nmyDate.getRealYear();\n// Outputs 2008\n</code></pre>\n" }, { "answer_id": 98300, "author": "jjohn", "author_id": 16513, "author_profile": "https://Stackoverflow.com/users/16513", "pm_score": 2, "selected": false, "text": "<p>This question is so old that it makes me weep with nostalgia for the dotcom days! </p>\n\n<p>That's right, Date.getYear() returns the number of years since 1900, just like Perl's localtime(). One wonders why a language designed in the 1990s wouldn't account for the century turnover, but what can I say? You had to be there. It sort of made a kind of sense at the time (like pets.com did).</p>\n\n<p>Before 2000, one might have been tempted to fix this bug by appending \"19\" to the result of getYear() resulting in the <a href=\"http://www.theregister.co.uk/2000/01/04/transmeta_screws_up_on_y2k/\" rel=\"nofollow noreferrer\">\"year 19100 bug\"</a>. Others have already answered this question sufficiently (add 1900 to the result of getDate()). </p>\n\n<p>Maybe the book you're reading about JavaScript is a little old? </p>\n\n<p>Thanks for the blast from the past!</p>\n" }, { "answer_id": 98406, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 4, "selected": false, "text": "<p>Check the docs. It's not a Y2K issue -- it's a lack of a Y2K issue! This decision was made originally in C and was copied into Perl, apparently JavaScript, and probably several other languages. That long ago it was apparently still felt desirable to use two-digit years, but remarkably whoever designed that interface had enough forethought to realize they needed to think about what would happen in the year 2000 and beyond, so instead of just providing the last two digits, they provided the number of years since 1900. You could use the two digits, if you were in a hurry or wanted to be risky. Or if you wanted your program to continue to work, you could add 1900 to the result and use full-fledged four-digit years.</p>\n<p>I remember the first time I did date manipulation in Perl. Strangely enough I <strong>read the docs</strong>. Apparently this is not a common thing. A year or two later I got called into the office on December 31, 1999 to fix a bug that had been discovered at the last possible minute in some contract Perl code, stuff I'd never had anything to do with. It was this exact issue: the standard date call returned years since 1900, and the programmers treated it as a two-digit year. (They assumed they'd get &quot;00&quot; in 2000.) As a young inexperienced programmer, it blew my mind that we'd paid so much extra for a &quot;professional&quot; job, and those people hadn't even bothered to read the documentation. It was the beginning of many years of disillusionment; now I'm old and cynical. :)</p>\n<p>In the year 2000, the annual YAPC Perl conference was referred to as &quot;YAPC 19100&quot; in honor of this oft-reported non-bug.</p>\n<p>Nowadays, in the Perl world at least, it makes more sense to use a standard module for date-handling, one which uses real four-digit years. Not sure what might be available for JavaScript.</p>\n" }, { "answer_id": 100802, "author": "Arve", "author_id": 9595, "author_profile": "https://Stackoverflow.com/users/9595", "pm_score": 2, "selected": false, "text": "<p>You should, as pointed out, never use <code>getYear()</code>, but instead use <code>getFullYear()</code>.</p>\n\n<p>The story is however not as simple as \"IE implements <code>GetYear()</code> as <code>getFullYear()</code>. Opera and IE these days treat <code>getYear()</code> as <code>getYear()</code> was originally specified for dates before 2000, but will treat it as <code>getFullYear()</code> for dates after 2000, while webkit and Firefox stick with the old behavior</p>\n\n<p>This outputs 99 in all browsers:</p>\n\n<pre><code>javascript:alert(new Date(917823600000).getYear());\n</code></pre>\n\n<p>This outputs 108 in FF/WebKit, and 2008 in Opera/IE:</p>\n\n<pre><code>javascript:alert(new Date().getYear());\n</code></pre>\n" }, { "answer_id": 316549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>var date_object=new Date();\nvar year = date_object.getYear();\nif(year &lt; 2000) {\n year = year + 1900;\n}\n//u will get the full year ....</p>\n" }, { "answer_id": 3447564, "author": "D3vito", "author_id": 415976, "author_profile": "https://Stackoverflow.com/users/415976", "pm_score": 1, "selected": false, "text": "<p>I am using <code>date.getUTCFullYear()</code>;\nworking without problems.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/98124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year? ``` myDate = new Date(); year = myDate.getYear(); ``` year = 108?
It's a [Y2K](http://en.wikipedia.org/wiki/Y2K) thing, only the years since 1900 are counted. There are potential compatibility issues now that `getYear()` has been deprecated in favour of `getFullYear()` - from [quirksmode](http://www.quirksmode.org/js/introdate.html): > > To make the matter even more complex, date.getYear() is deprecated nowadays and you should use date.getFullYear(), which, in turn, is not supported by the older browsers. If it works, however, it should always give the full year, ie. 2000 instead of 100. > > > Your browser gives the following years with these two methods: > > > ``` * The year according to getYear(): 108 * The year according to getFullYear(): 2008 ``` There are also implementation differences between Internet Explorer and Firefox, as IE's implementation of `getYear()` was changed to behave like `getFullYear()` - from [IBM](http://www-128.ibm.com/developerworks/web/library/wa-ie2mozgd/): > > Per the ECMAScript specification, getYear returns the year minus 1900, originally meant to return "98" for 1998. getYear was deprecated in ECMAScript Version 3 and replaced with getFullYear(). > > > Internet Explorer changed getYear() to work like getFullYear() and make it Y2k-compliant, while Mozilla kept the standard behavior. > > >
98,135
<p>I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?</p> <p>If I run the following code:</p> <pre><code>&gt;&gt;&gt; import django.template &gt;&gt;&gt; from django.template import Template, Context &gt;&gt;&gt; t = Template('My name is {{ my_name }}.') </code></pre> <p>I get:</p> <pre><code>ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. </code></pre>
[ { "answer_id": 98146, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>Any particular reason you want to use Django's templates? Both <a href=\"http://jinja.pocoo.org/\" rel=\"noreferrer\">Jinja</a> and <a href=\"http://genshi.edgewall.org/\" rel=\"noreferrer\">Genshi</a> are, in my opinion, superior.</p>\n\n<hr>\n\n<p>If you really want to, then see the <a href=\"http://docs.djangoproject.com/en/dev/topics/settings/#topics-settings\" rel=\"noreferrer\">Django documentation on <code>settings.py</code></a>. Especially the section \"Using settings without setting <code>DJANGO_SETTINGS_MODULE</code>\". Use something like this:</p>\n\n<pre><code>from django.conf import settings\nsettings.configure (FOO='bar') # Your settings go here\n</code></pre>\n" }, { "answer_id": 98150, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>Google <code>AppEngine</code> uses the Django templating engine, have you taken a look at how they do it? You could possibly just use that.</p>\n" }, { "answer_id": 98154, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>Found this:</p>\n\n<p><a href=\"http://snippets.dzone.com/posts/show/3339\" rel=\"nofollow noreferrer\">http://snippets.dzone.com/posts/show/3339</a></p>\n" }, { "answer_id": 98178, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 8, "selected": true, "text": "<p>The solution is simple. It's actually <a href=\"http://docs.djangoproject.com/en/dev/ref/templates/api/#configuring-the-template-system-in-standalone-mode\" rel=\"noreferrer\">well documented</a>, but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)</p>\n\n<p>The following code works:</p>\n\n<pre><code>&gt;&gt;&gt; from django.template import Template, Context\n&gt;&gt;&gt; from django.conf import settings\n&gt;&gt;&gt; settings.configure()\n&gt;&gt;&gt; t = Template('My name is {{ my_name }}.')\n&gt;&gt;&gt; c = Context({'my_name': 'Daryl Spitzer'})\n&gt;&gt;&gt; t.render(c)\nu'My name is Daryl Spitzer.'\n</code></pre>\n\n<p>See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).</p>\n" }, { "answer_id": 98214, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://jinja.pocoo.org/2/\" rel=\"noreferrer\" title=\"Jinja2 Web Site\">Jinja2</a> <a href=\"http://jinja.pocoo.org/2/documentation/templates\" rel=\"noreferrer\" title=\"Template syntax reference\">syntax</a> is pretty much the same as Django's with very few differences, and you get a much more powerfull template engine, which also compiles your template to bytecode (FAST!).</p>\n\n<p>I use it for templating, including in Django itself, and it is very good. You can also easily write extensions if some feature you want is missing.</p>\n\n<p>Here is some demonstration of the code generation:</p>\n\n<pre><code>&gt;&gt;&gt; import jinja2\n&gt;&gt;&gt; print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) \nfrom __future__ import division\nfrom jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join\nname = None\n\ndef root(context, environment=environment):\n l_data = context.resolve('data')\n t_1 = environment.filters['upper']\n if 0: yield None\n for l_row in l_data:\n if 0: yield None\n yield unicode(t_1(environment.getattr(l_row, 'name')))\n\nblocks = {}\ndebug_info = '1=9'\n</code></pre>\n" }, { "answer_id": 98276, "author": "Clint Ecker", "author_id": 13668, "author_profile": "https://Stackoverflow.com/users/13668", "pm_score": 0, "selected": false, "text": "<p>I echo the above statements. Jinja 2 is a pretty good superset of Django templates for general use. I think they're working on making the Django templates a little less coupled to the settings.py, but Jinja should do well for you.</p>\n" }, { "answer_id": 109380, "author": "olt", "author_id": 19759, "author_profile": "https://Stackoverflow.com/users/19759", "pm_score": 3, "selected": false, "text": "<p>I would also recommend jinja2. There is a <a href=\"https://web.archive.org/web/20090421084229/http://lucumr.pocoo.org/2008/9/16/why-jinja-is-not-django-and-why-django-should-have-a-look-at-it\" rel=\"nofollow noreferrer\">nice article</a> on <code>django</code> vs. <code>jinja2</code> that gives some in-detail information on why you should prefere the later.</p>\n" }, { "answer_id": 304195, "author": "Rob Williams", "author_id": 26682, "author_profile": "https://Stackoverflow.com/users/26682", "pm_score": 1, "selected": false, "text": "<p>Don't. Use <a href=\"http://www.stringtemplate.org/\" rel=\"nofollow noreferrer\">StringTemplate</a> instead--there is no reason to consider any other template engine once you know about it.</p>\n" }, { "answer_id": 345360, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 2, "selected": false, "text": "<p>I would say <a href=\"http://jinja.pocoo.org/\" rel=\"nofollow noreferrer\">Jinja</a> as well. It is definitely <strong>more powerful</strong> than Django Templating Engine and it is <strong>stand alone</strong>.</p>\n\n<p>If this was an external plug to an existing Django application, you could create <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands\" rel=\"nofollow noreferrer\">a custom command</a> and use the templating engine within your projects environment. Like this;</p>\n\n<pre><code>manage.py generatereports --format=html\n</code></pre>\n\n<p>But I don't think it is worth just using the Django Templating Engine instead of Jinja.</p>\n" }, { "answer_id": 11519049, "author": "hupantingxue", "author_id": 1318785, "author_profile": "https://Stackoverflow.com/users/1318785", "pm_score": 0, "selected": false, "text": "<p>While running the <code>manage.py</code> shell:</p>\n\n<pre><code>&gt;&gt;&gt; from django import template \n&gt;&gt;&gt; t = template.Template('My name is {{ me }}.') \n&gt;&gt;&gt; c = template.Context({'me': 'ShuJi'}) \n&gt;&gt;&gt; t.render(c)\n</code></pre>\n" }, { "answer_id": 20480267, "author": "Gourneau", "author_id": 56069, "author_profile": "https://Stackoverflow.com/users/56069", "pm_score": 2, "selected": false, "text": "<p>Thanks for the help folks. Here is one more addition. The case where you need to use custom template tags.</p>\n\n<p>Let's say you have this important template tag in the module read.py</p>\n\n<pre><code>from django import template\n\nregister = template.Library()\n\[email protected](name='bracewrap')\ndef bracewrap(value):\n return \"{\" + value + \"}\"\n</code></pre>\n\n<p>This is the html template file \"temp.html\":</p>\n\n<pre><code>{{var|bracewrap}}\n</code></pre>\n\n<p>Finally, here is a Python script that will tie to all together</p>\n\n<pre><code>import django\nfrom django.conf import settings\nfrom django.template import Template, Context\nimport os\n\n#load your tags\nfrom django.template.loader import get_template\ndjango.template.base.add_to_builtins(\"read\")\n\n# You need to configure Django a bit\nsettings.configure(\n TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),\n)\n\n#or it could be in python\n#t = Template('My name is {{ my_name }}.')\nc = Context({'var': 'stackoverflow.com rox'})\n\ntemplate = get_template(\"temp.html\")\n# Prepare context ....\nprint template.render(c)\n</code></pre>\n\n<p>The output would be</p>\n\n<pre><code>{stackoverflow.com rox}\n</code></pre>\n" }, { "answer_id": 34494931, "author": "Pramod", "author_id": 817277, "author_profile": "https://Stackoverflow.com/users/817277", "pm_score": 3, "selected": false, "text": "<p>According to the Jinja documentation, <a href=\"http://jinja.pocoo.org/docs/dev/intro/#experimental-python-3-support\" rel=\"noreferrer\">Python 3 support is still experimental</a>. So if you are on Python 3 and performance is not an issue, you can use django's built in template engine. </p>\n\n<p>Django 1.8 introduced support for <a href=\"https://docs.djangoproject.com/en/1.9/releases/1.8/#multiple-template-engines\" rel=\"noreferrer\">multiple template engines</a> which requires a change to the way templates are initialized. You have to explicitly configure <code>settings.DEBUG</code> which is used by the default template engine provided by django. Here's the code to use templates without using the rest of django. </p>\n\n<pre><code>from django.template import Template, Context\nfrom django.template.engine import Engine\n\nfrom django.conf import settings\nsettings.configure(DEBUG=False)\n\ntemplate_string = \"Hello {{ name }}\"\ntemplate = Template(template_string, engine=Engine())\ncontext = Context({\"name\": \"world\"})\noutput = template.render(context) #\"hello world\"\n</code></pre>\n" }, { "answer_id": 47465370, "author": "Robert Vanden Eynde", "author_id": 1980630, "author_profile": "https://Stackoverflow.com/users/1980630", "pm_score": 3, "selected": false, "text": "<p>An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(...) call the TEMPLATES variable and call django.setup() like this :</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from django.conf import settings\n\nsettings.configure(TEMPLATES=[\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': ['.'], # if you want the templates from a file\n 'APP_DIRS': False, # we have no apps\n },\n])\n\nimport django\ndjango.setup()\n</code></pre>\n\n<p>Then you can load your template like normally, from a string :</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from django import template \nt = template.Template('My name is {{ name }}.') \nc = template.Context({'name': 'Rob'}) \nt.render(c)\n</code></pre>\n\n<p>And if you wrote the DIRS variable in the .configure, from the disk :</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from django.template.loader import get_template\nt = get_template('a.html')\nt.render({'name': 5})\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/43834226/django-error-no-djangotemplates-backend-is-configured#43834287\">Django Error: No DjangoTemplates backend is configured</a></p>\n\n<p><a href=\"http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts\" rel=\"noreferrer\">http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/98135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO\_SETTINGS\_MODULE environment variable? If I run the following code: ``` >>> import django.template >>> from django.template import Template, Context >>> t = Template('My name is {{ my_name }}.') ``` I get: ``` ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. ```
The solution is simple. It's actually [well documented](http://docs.djangoproject.com/en/dev/ref/templates/api/#configuring-the-template-system-in-standalone-mode), but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.) The following code works: ``` >>> from django.template import Template, Context >>> from django.conf import settings >>> settings.configure() >>> t = Template('My name is {{ my_name }}.') >>> c = Context({'my_name': 'Daryl Spitzer'}) >>> t.render(c) u'My name is Daryl Spitzer.' ``` See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).
98,153
<p>I've found the standard hashing function on VS2005 is painfully slow when trying to achieve high performance look ups. What are some good examples of fast and efficient hashing algorithms that should void most collisions?</p>
[ { "answer_id": 98164, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "<p>That always depends on your data-set.</p>\n\n<p>I for one had surprisingly good results by using the CRC32 of the string. Works very good with a wide range of different input sets. </p>\n\n<p>Lots of good CRC32 implementations are easy to find on the net.</p>\n\n<p><strong>Edit:</strong> Almost forgot: This page has a nice hash-function shootout with performance numbers and test-data:</p>\n\n<p><a href=\"http://smallcode.weblogs.us/\" rel=\"noreferrer\">http://smallcode.weblogs.us/</a> &lt;-- further down the page. </p>\n" }, { "answer_id": 98176, "author": "David Pierre", "author_id": 18296, "author_profile": "https://Stackoverflow.com/users/18296", "pm_score": 3, "selected": false, "text": "<p>Boost has an <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/hash.html\" rel=\"noreferrer\">boost::hash</a> library which can provides some basic hash functions for most common types.</p>\n" }, { "answer_id": 98179, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 4, "selected": false, "text": "<p>From some old code of mine:</p>\n\n<pre><code>/* magic numbers from http://www.isthe.com/chongo/tech/comp/fnv/ */\nstatic const size_t InitialFNV = 2166136261U;\nstatic const size_t FNVMultiple = 16777619;\n\n/* Fowler / Noll / Vo (FNV) Hash */\nsize_t myhash(const string &amp;s)\n{\n size_t hash = InitialFNV;\n for(size_t i = 0; i &lt; s.length(); i++)\n {\n hash = hash ^ (s[i]); /* xor the low 8 bits */\n hash = hash * FNVMultiple; /* multiply by the magic number */\n }\n return hash;\n}\n</code></pre>\n\n<p>Its fast. Really freaking fast.</p>\n" }, { "answer_id": 98280, "author": "Brian", "author_id": 8959, "author_profile": "https://Stackoverflow.com/users/8959", "pm_score": 2, "selected": false, "text": "<p>One classic suggestion for a string hash is to step through the letters one by one adding their ascii/unicode values to an accumulator, each time multiplying the accumulator by a prime number. (allowing overflow on the hash value)</p>\n\n<pre><code> template &lt;&gt; struct myhash{};\n\n template &lt;&gt; struct myhash&lt;string&gt;\n {\n size_t operator()(string &amp;to_hash) const\n {\n const char * in = to_hash.c_str();\n size_t out=0;\n while(NULL != *in)\n {\n out*= 53; //just a prime number\n out+= *in;\n ++in;\n }\n return out;\n }\n };\n\n hash_map&lt;string, int, myhash&lt;string&gt; &gt; my_hash_map;\n</code></pre>\n\n<p>It's hard to get faster than that without throwing out data. If you know your strings can be differentiated by only a few characters and not their whole content, you can do faster. </p>\n\n<p>You might try caching the hash value better by creating a new subclass of basic_string that remembers its hash value, if the value gets calculated too often. hash_map should be doing that internally, though.</p>\n" }, { "answer_id": 98309, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 3, "selected": false, "text": "<p>I've use the Jenkins hash to write a Bloom filter library, it has great performance. </p>\n\n<p>Details and code are available here: <a href=\"http://burtleburtle.net/bob/c/lookup3.c\" rel=\"noreferrer\">http://burtleburtle.net/bob/c/lookup3.c</a></p>\n\n<p>This is what Perl uses for its hashing operation, fwiw.</p>\n" }, { "answer_id": 99214, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 3, "selected": false, "text": "<p>If you are hashing a fixed set of words, the best hash function is often a <a href=\"http://en.wikipedia.org/wiki/Perfect_hash\" rel=\"noreferrer\">perfect hash function</a>. However, they generally require that the set of words you are trying to hash is known at compile time. Detection of keywords in a <a href=\"http://en.wikipedia.org/wiki/Lexical_analysis\" rel=\"noreferrer\">lexer</a> (and translation of keywords to tokens) is a common usage of perfect hash functions generated with tools such as <a href=\"http://www.gnu.org/software/gperf/\" rel=\"noreferrer\">gperf</a>. A perfect hash also lets you replace <code>hash_map</code> with a simple array or <code>vector</code>.</p>\n\n<p>If you're not hashing a fixed set of words, then obviously this doesn't apply.</p>\n" }, { "answer_id": 101142, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>If your strings are on average longer than a single cache line, but their length+prefix are reasonably unique, consider hasing just the length+first 8/16 characters. (The length is contained in the std::string object itself and therefore cheap to read)</p>\n" }, { "answer_id": 107657, "author": "George V. Reilly", "author_id": 6364, "author_profile": "https://Stackoverflow.com/users/6364", "pm_score": 6, "selected": false, "text": "<p>I worked with <a href=\"http://research.microsoft.com/~PALARSON/\" rel=\"noreferrer\">Paul Larson</a> of Microsoft Research on some hashtable implementations. He investigated a number of string hashing functions on a variety of datasets and found that a simple multiply by 101 and add loop worked surprisingly well.</p>\n\n<pre><code>unsigned int\nhash(\n const char* s,\n unsigned int seed = 0)\n{\n unsigned int hash = seed;\n while (*s)\n {\n hash = hash * 101 + *s++;\n }\n return hash;\n}\n</code></pre>\n" }, { "answer_id": 9355571, "author": "Josh S", "author_id": 1137626, "author_profile": "https://Stackoverflow.com/users/1137626", "pm_score": 2, "selected": false, "text": "<p>I did a little searching, and funny thing, Paul Larson's little algorithm showed up here\n<a href=\"http://www.strchr.com/hash_functions\" rel=\"nofollow\">http://www.strchr.com/hash_functions</a>\nas having the least collisions of any tested in a number of conditions, and it's very fast for one that it's unrolled or table driven.</p>\n\n<p>Larson's being the simple multiply by 101 and add loop above.</p>\n" }, { "answer_id": 22515025, "author": "George V. Reilly", "author_id": 6364, "author_profile": "https://Stackoverflow.com/users/6364", "pm_score": 2, "selected": false, "text": "<p>Python 3.4 includes a new hash algorithm based on <a href=\"https://131002.net/siphash/\" rel=\"nofollow\">SipHash</a>. <a href=\"http://legacy.python.org/dev/peps/pep-0456/\" rel=\"nofollow\">PEP 456</a> is very informative.</p>\n" }, { "answer_id": 41314400, "author": "philix", "author_id": 707094, "author_profile": "https://Stackoverflow.com/users/707094", "pm_score": 1, "selected": false, "text": "<p>From <a href=\"http://aras-p.info/blog/2016/08/02/Hash-Functions-all-the-way-down/\" rel=\"nofollow noreferrer\">Hash Functions all the way down</a>:</p>\n\n<blockquote>\n <p><a href=\"https://github.com/aappleby/smhasher\" rel=\"nofollow noreferrer\" title=\"MurmurHash parent project\">MurmurHash</a> got quite popular, at least in game developer circles, as a “general hash function”.</p>\n \n <p>It’s a fine choice, but let’s see later if we can generally do better. Another fine choice, especially if you know more about your data than “it’s gonna be an unknown number of bytes”, is to roll your own (e.g. see Won Chun’s replies, or Rune’s modified xxHash/Murmur that are specialized for 4-byte keys etc.). If you know your data, always try to see whether that knowledge can be used for good effect!</p>\n</blockquote>\n\n<p>Without more information I would recommend <a href=\"https://github.com/aappleby/smhasher\" rel=\"nofollow noreferrer\" title=\"MurmurHash parent project\">MurmurHash</a> as a general purpose <a href=\"https://en.wikipedia.org/wiki/List_of_hash_functions#Non-cryptographic_hash_functions\" rel=\"nofollow noreferrer\">non-cryptographic hash function</a>. For small strings (of the size of the average identifier in programs) the very simple and famous <a href=\"http://www.cse.yorku.ca/~oz/hash.html\" rel=\"nofollow noreferrer\" title=\"djb2\">djb2</a> and <a href=\"https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function\" rel=\"nofollow noreferrer\" title=\"Fowler-Noll-Vo\">FNV</a> are very good.</p>\n\n<blockquote>\n <p>Here (data sizes &lt; 10 bytes) we can see that the ILP smartness of other algorithms does not get to show itself, and the super-simplicity of FNV or djb2 win in performance.</p>\n</blockquote>\n\n<h2><a href=\"http://www.cse.yorku.ca/~oz/hash.html\" rel=\"nofollow noreferrer\" title=\"djb2\">djb2</a></h2>\n\n<pre><code>unsigned long\nhash(unsigned char *str)\n{\n unsigned long hash = 5381;\n int c;\n\n while (c = *str++)\n hash = ((hash &lt;&lt; 5) + hash) + c; /* hash * 33 + c */\n\n return hash;\n}\n</code></pre>\n\n<h2><a href=\"http://www.isthe.com/chongo/tech/comp/fnv/index.html\" rel=\"nofollow noreferrer\">FNV-1</a></h2>\n\n<pre><code>hash = FNV_offset_basis\nfor each byte_of_data to be hashed\n hash = hash × FNV_prime\n hash = hash XOR byte_of_data\nreturn hash\n</code></pre>\n\n<h2><a href=\"http://www.isthe.com/chongo/tech/comp/fnv/index.html\" rel=\"nofollow noreferrer\">FNV-1A</a></h2>\n\n<pre><code>hash = FNV_offset_basis\nfor each byte_of_data to be hashed\n hash = hash XOR byte_of_data\n hash = hash × FNV_prime\nreturn hash\n</code></pre>\n\n<h2>A note about security and availability</h2>\n\n<p>Hash functions can make your code vulnerable to denial-of-service attacks. If an attacker is able to force your server to handle too many collisions, your server may not be able to cope with requests.</p>\n\n<p>Some hash functions like <a href=\"https://github.com/aappleby/smhasher\" rel=\"nofollow noreferrer\" title=\"MurmurHash parent project\">MurmurHash</a> accept a seed that you can provide to drastically reduce the ability of attackers to predict the hashes your server software is generating. Keep that in mind.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/98153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13646/" ]
I've found the standard hashing function on VS2005 is painfully slow when trying to achieve high performance look ups. What are some good examples of fast and efficient hashing algorithms that should void most collisions?
I worked with [Paul Larson](http://research.microsoft.com/~PALARSON/) of Microsoft Research on some hashtable implementations. He investigated a number of string hashing functions on a variety of datasets and found that a simple multiply by 101 and add loop worked surprisingly well. ``` unsigned int hash( const char* s, unsigned int seed = 0) { unsigned int hash = seed; while (*s) { hash = hash * 101 + *s++; } return hash; } ```