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
183,950
<p>I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code.</p> <pre><code>protected override void CreateChildControls() { if (ScriptManager.GetCurrent(Page) == null) { ScriptManager sMgr = new ScriptManager(); // Ensure the ScriptManager is the first control. Page.Form.Controls.AddAt(0, sMgr); } } </code></pre> <p>However, when this code is executed, I get the following error message:</p> <blockquote> <p>"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."</p> </blockquote> <p>Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart?</p>
[ { "answer_id": 184262, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 6, "selected": true, "text": "<p>I was able to get this to work by using the Page's Init event:</p>\n\n<pre><code>protected override void OnInit(EventArgs e)\n{\n Page.Init += delegate(object sender, EventArgs e_Init)\n {\n if (ScriptManager.GetCurrent(Page) == null)\n {\n ScriptManager sMgr = new ScriptManager();\n Page.Form.Controls.AddAt(0, sMgr);\n }\n };\n base.OnInit(e);\n}\n</code></pre>\n" }, { "answer_id": 345497, "author": "daduffer", "author_id": 43473, "author_profile": "https://Stackoverflow.com/users/43473", "pm_score": 3, "selected": false, "text": "<p>I've done this and it works. Create a placeholder for the controls:</p>\n\n<pre><code>&lt;asp:PlaceHolder ID=\"WebGridPlaceholder\" runat=\"server\" &gt;\n&lt;/asp:PlaceHolder&gt;\n</code></pre>\n\n<p>Then you can do this in CreateChildControls:</p>\n\n<pre><code>ScriptManager aSM = new ScriptManager();\naSM.ID = \"GridScriptManager\";\nWebGridPlaceholder.Controls.Add(aSM);\n</code></pre>\n" }, { "answer_id": 684330, "author": "dkarzon", "author_id": 75946, "author_profile": "https://Stackoverflow.com/users/75946", "pm_score": 0, "selected": false, "text": "<p>I had this similar problem and found the best way was to add a global ScriptManager to the masterpage then in the code behind you can add to it by:</p>\n\n<pre><code>ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference(virtualPath));\n</code></pre>\n" }, { "answer_id": 1441301, "author": "Josh", "author_id": 175121, "author_profile": "https://Stackoverflow.com/users/175121", "pm_score": 3, "selected": false, "text": "<p>I ran into this problem with a custom ascx server control. I tried many solutions involving adding script to the OnInit events of the control (which doesn't get executed until after it checks for the ScriptManager control), adding logic inside of server tags on the control, and adding things to about every other event. No good. I finally built a control that inherits from ScriptManagerProxy and then uses ktrauberman's piece of code, slightly modified, to add a ScriptManager if needed:</p>\n\n<pre><code> public class ProxiedScriptManager : ScriptManagerProxy\n {\n protected override void OnInit(EventArgs e)\n {\n //double check for script-manager, if one doesn't exist, \n //then create one and add it to the page\n if (ScriptManager.GetCurrent(this.Page) == null)\n {\n ScriptManager sManager = new ScriptManager();\n sManager.ID = \"sManager_\" + DateTime.Now.Ticks;\n Controls.AddAt(0, sManager);\n }\n\n base.OnInit(e);\n }\n }\n</code></pre>\n\n<p>That did it for me.</p>\n" }, { "answer_id": 1761003, "author": "Jon", "author_id": 214324, "author_profile": "https://Stackoverflow.com/users/214324", "pm_score": 3, "selected": false, "text": "<p>I had the same basic issue the rest of you had. I was creating a custom ascx control and wanted to be able to not worry about whether or not the calling page had the scriptmanager declared. I got around the issues by adding the following to the ascx contorl itself. </p>\n\n<p><strong>to the ascx page -</strong></p>\n\n<p><code>&lt;asp:PlaceHolder runat=\"server\" ID=\"phScriptManager\"&gt;&lt;/asp:PlaceHolder&gt;</code></p>\n\n<p>in the update panel itself - <code>oninit=\"updatePanel1_Init\"</code></p>\n\n<p><strong>to the ascx.cs file -</strong> </p>\n\n<pre><code>protected void updatePanel1_Init(object sender, EventArgs e)\n{\n if (ScriptManager.GetCurrent(this.Page) == null)\n {\n ScriptManager sManager = new ScriptManager();\n sManager.ID = \"sManager_\" + DateTime.Now.Ticks;\n phScriptManager.Controls.AddAt(0, sManager);\n }\n}\n</code></pre>\n\n<p>Thank you to everyone else in this thread who got me started.</p>\n" }, { "answer_id": 5625395, "author": "Paul", "author_id": 454600, "author_profile": "https://Stackoverflow.com/users/454600", "pm_score": 2, "selected": false, "text": "<p>This is the only way I could get my update panel to work in a sharepoint 2007 / 2010 compatible webpart. We use a 2010 master page with an scriptmanager but a 2007 master page without one.</p>\n\n<p>.ascx</p>\n\n<pre><code>&lt;asp:PlaceHolder ID=\"sMgr_place\" runat=\"server\" /&gt;\n&lt;asp:UpdatePanel runat=\"server\" OnInit=\"updatePanel_Init\"&gt;&lt;ContentTemplate&gt;\n...\n&lt;/ContentTemplate&gt;&lt;/asp:UpdatePanel&gt;\n</code></pre>\n\n<p>.ascx.cs</p>\n\n<pre><code>public void updatePanel_Init(object sender, EventArgs e)\n{\n if (ScriptManager.GetCurrent(Page) == null)\n {\n ScriptManager sMgr = new ScriptManager();\n sMgr.EnablePartialRendering = true;\n sMgr_place.Controls.Add(sMgr);\n }\n}\n</code></pre>\n" }, { "answer_id": 21786935, "author": "user3311381", "author_id": 3311381, "author_profile": "https://Stackoverflow.com/users/3311381", "pm_score": 1, "selected": false, "text": "<p>I used this code in custom web controls (.cs) that contain update panels.</p>\n\n<pre><code>protected override void OnInit(EventArgs e)\n{\n //...\n if (ScriptManager.GetCurrent(this.Page) == null)\n {\n ScriptManager scriptManager = new ScriptManager();\n scriptManager.ID = \"scriptManager_\" + DateTime.Now.Ticks;\n Controls.AddAt(0, scriptManager);\n }\n //...\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21461/" ]
I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code. ``` protected override void CreateChildControls() { if (ScriptManager.GetCurrent(Page) == null) { ScriptManager sMgr = new ScriptManager(); // Ensure the ScriptManager is the first control. Page.Form.Controls.AddAt(0, sMgr); } } ``` However, when this code is executed, I get the following error message: > > "The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases." > > > Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart?
I was able to get this to work by using the Page's Init event: ``` protected override void OnInit(EventArgs e) { Page.Init += delegate(object sender, EventArgs e_Init) { if (ScriptManager.GetCurrent(Page) == null) { ScriptManager sMgr = new ScriptManager(); Page.Form.Controls.AddAt(0, sMgr); } }; base.OnInit(e); } ```
183,991
<p>I wonder if there's a way to do the following: I have a structure containing a member which is a pointer to a block of memory allocated by the kernel when I pass the structure to an API function (the structure is a WAVEHDR, the member is the <em>reserved</em> field.)</p> <p>I can set a data breakpoint on the value of the reserved member - that in itself is not very helpful. What I'd like to do, when the breakpoint is hit, is to dereference the pointer stored in <em>reserved</em> and set a new data breakpoint on the memory pointed to by that pointer. I would like VisualStudio to break when that memory is set to a known value.</p> <p>I know how to set a breakpoint from a macro, and how to have Visual Studio invoke that macro from a breakpoint when it's hit, but I don't know whether I can pass the pointer value to the macro so that it can set the breakpoint on the right address. The UI doesn't provide a way to do it.</p> <p>Is there a way for the macro to access information about the running program, and do things like evaluate global variables or other expressions? I could accomplish what I'm trying to do if I had that kind of programmatic access to the running code (during a breakpoint) from the macro.</p>
[ { "answer_id": 184460, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if thats possible. I know that there are conditional breakpoints, but that would require knowing the memory address ahead of time...</p>\n\n<p>Something along the lines of *p == 0xADDRESS in the conditional break dialog.</p>\n" }, { "answer_id": 184607, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": true, "text": "<p>A macro can evaluate anything that you can in the watch window:</p>\n\n<pre><code> Dim e As EnvDTE.Expression\n\n e = DTE.Debugger.GetExpression(\"&lt;my expression&gt;\", True)\n\n If e.IsValidValue Then\n ... use e.Value to do something\n End If\n</code></pre>\n\n<p>The value you get back in e.Value is exactly the string you would see in the watch window, so you may have to pull it apart. There are also a bunch of other properties on the Expression object you can use. See the <a href=\"http://msdn.microsoft.com/en-us/library/envdte.expression(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN documentation</a>.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/183991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9047/" ]
I wonder if there's a way to do the following: I have a structure containing a member which is a pointer to a block of memory allocated by the kernel when I pass the structure to an API function (the structure is a WAVEHDR, the member is the *reserved* field.) I can set a data breakpoint on the value of the reserved member - that in itself is not very helpful. What I'd like to do, when the breakpoint is hit, is to dereference the pointer stored in *reserved* and set a new data breakpoint on the memory pointed to by that pointer. I would like VisualStudio to break when that memory is set to a known value. I know how to set a breakpoint from a macro, and how to have Visual Studio invoke that macro from a breakpoint when it's hit, but I don't know whether I can pass the pointer value to the macro so that it can set the breakpoint on the right address. The UI doesn't provide a way to do it. Is there a way for the macro to access information about the running program, and do things like evaluate global variables or other expressions? I could accomplish what I'm trying to do if I had that kind of programmatic access to the running code (during a breakpoint) from the macro.
A macro can evaluate anything that you can in the watch window: ``` Dim e As EnvDTE.Expression e = DTE.Debugger.GetExpression("<my expression>", True) If e.IsValidValue Then ... use e.Value to do something End If ``` The value you get back in e.Value is exactly the string you would see in the watch window, so you may have to pull it apart. There are also a bunch of other properties on the Expression object you can use. See the [MSDN documentation](http://msdn.microsoft.com/en-us/library/envdte.expression(VS.80).aspx).
184,002
<p>In the following piece of code (taken from the <a href="http://groovy-lang.org/semantics.html#_while_loop" rel="noreferrer">Groovy Semantics Manual page</a>), why prefix the assignment with the keyword <code>def</code>?</p> <pre><code>def x = 0 def y = 5 while ( y-- &gt; 0 ) { println "" + x + " " + y x++ } assert x == 5 </code></pre> <p>The <code>def</code> keyword can be removed, and this snippet would produce the same results. So what's the <strong>effect</strong> of the keyword <code>def</code> ?</p>
[ { "answer_id": 184019, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 3, "selected": false, "text": "<p>Actually, I <strong>don't</strong> think it would behave the same... </p>\n\n<p>variables in Groovy still require declaration, just not TYPED declaration, as the right-hand side generally contains enough information for Groovy to type the variable.</p>\n\n<p>When I try to use a variable that I haven't declared with def or a type, I get an error \"No such property\", since it assumes that I'm using a member of the class containing the code.</p>\n" }, { "answer_id": 184023, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 5, "selected": false, "text": "<p>According to this <a href=\"http://www.groovy-lang.org/semantics.html#_variable_definition\" rel=\"noreferrer\">page</a>, <code>def</code> is a replacement for a type name and can simply be thought of as an alias for <code>Object</code> (i.e. signifying that you don't care about the type).</p>\n" }, { "answer_id": 185879, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 9, "selected": true, "text": "<p>It's syntactic sugar for basic scripts. Omitting the \"def\" keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable:</p>\n\n<pre><code>x = 1\nassert x == 1\nassert this.binding.getVariable(\"x\") == 1\n</code></pre>\n\n<p>Using the def keyword instead does not put the variable in the scripts bindings:</p>\n\n<pre><code>def y = 2\n\nassert y == 2\n\ntry {\n this.binding.getVariable(\"y\") \n} catch (groovy.lang.MissingPropertyException e) {\n println \"error caught\"\n} \n</code></pre>\n\n<p>Prints: \"error caught\"</p>\n\n<p>Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation.</p>\n\n<p>If you define a method in your script, it won't have access to the variables that are created with \"def\" in the body of the main script as they aren't in scope:</p>\n\n<pre><code> x = 1\n def y = 2\n\n\npublic bar() {\n assert x == 1\n\n try {\n assert y == 2\n } catch (groovy.lang.MissingPropertyException e) {\n println \"error caught\"\n }\n}\n\nbar()\n</code></pre>\n\n<p>prints \"error caught\" </p>\n\n<p>The \"y\" variable isn't in scope inside the function. \"x\" is in scope as groovy will check the bindings of the current script for the variable. As I said earlier, this is simply syntactic sugar to make quick and dirty scripts quicker to type out (often one liners).</p>\n\n<p>Good practice in larger scripts is to always use the \"def\" keyword so you don't run into strange scoping issues or interfere with variables you don't intend to.</p>\n" }, { "answer_id": 194293, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/185879/33311\">Ted's answer</a> is excellent for scripts; <a href=\"https://stackoverflow.com/a/184023/33311\">Ben's answer</a> is standard for classes.</p>\n\n<p>As Ben says, think of it as \"Object\" -- but it is much cooler in that it does not constrain you to the Object methods. This has neat implications with respect to imports.</p>\n\n<p>e.g. In this snippet I have to import FileChannel</p>\n\n<pre><code>// Groovy imports java.io.* and java.util.* automatically\n// but not java.nio.*\n\nimport java.nio.channels.*\n\nclass Foo {\n public void bar() {\n FileChannel channel = new FileInputStream('Test.groovy').getChannel()\n println channel.toString()\n }\n}\n\nnew Foo().bar()\n</code></pre>\n\n<p>e.g. But here I can just 'wing it' as long as everything is on the classpath</p>\n\n<pre><code>// Groovy imports java.io.* and java.util.* automatically\n// but not java.nio.*\nclass Foo {\n public void bar() {\n def channel = new FileInputStream('Test.groovy').getChannel()\n println channel.toString()\n }\n}\n\nnew Foo().bar()\n</code></pre>\n" }, { "answer_id": 201149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>As far as this single script is concerned there is no practical difference.</p>\n\n<p>However, variables defined using the keyword \"def\" are treated as local variables, that is, local to this one script. Variables without the \"def\" in front of them are stored in a so called binding upon first use. You can think of the binding as a general storage area for variables and closures that need to be available \"between\" scripts.</p>\n\n<p>So, if you have two scripts and execute them with the same GroovyShell, the second script will be able to get all variables that were set in the first script without a \"def\".</p>\n" }, { "answer_id": 18026302, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 3, "selected": false, "text": "<p>The reason for \"def\" is to tell groovy that you intend to create a variable here. It's important because you don't ever want to create a variable by accident. </p>\n\n<p>It's somewhat acceptable in scripts (Groovy scripts and groovysh allow you to do so), but in production code it's one of the biggest evils you can come across which is why you must define a variable with def in all actual groovy code (anything inside a class). </p>\n\n<p>Here's an example of why it's bad. This will run (Without failing the assert) if you copy the following code and paste it into groovysh:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>bill = 7\nbi1l = bill + 3\nassert bill == 7\n</code></pre>\n\n<p>This kind of problem can take a lot of time to find and fix--Even if it only bit you once in your life it would still cost more time than explicitly declaring the variables thousands of times throughout your career. It also becomes clear to the eye just where it's being declared, you don't have to guess.</p>\n\n<p>In unimportant scripts/console input (like the groovy console) it's somewhat acceptable because the script's scope is limited. I think the only reason groovy allows you to do this in scripts is to support DSLs the way Ruby does (A bad trade-off if you ask me, but some people love the DSLs)</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
In the following piece of code (taken from the [Groovy Semantics Manual page](http://groovy-lang.org/semantics.html#_while_loop)), why prefix the assignment with the keyword `def`? ``` def x = 0 def y = 5 while ( y-- > 0 ) { println "" + x + " " + y x++ } assert x == 5 ``` The `def` keyword can be removed, and this snippet would produce the same results. So what's the **effect** of the keyword `def` ?
It's syntactic sugar for basic scripts. Omitting the "def" keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable: ``` x = 1 assert x == 1 assert this.binding.getVariable("x") == 1 ``` Using the def keyword instead does not put the variable in the scripts bindings: ``` def y = 2 assert y == 2 try { this.binding.getVariable("y") } catch (groovy.lang.MissingPropertyException e) { println "error caught" } ``` Prints: "error caught" Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation. If you define a method in your script, it won't have access to the variables that are created with "def" in the body of the main script as they aren't in scope: ``` x = 1 def y = 2 public bar() { assert x == 1 try { assert y == 2 } catch (groovy.lang.MissingPropertyException e) { println "error caught" } } bar() ``` prints "error caught" The "y" variable isn't in scope inside the function. "x" is in scope as groovy will check the bindings of the current script for the variable. As I said earlier, this is simply syntactic sugar to make quick and dirty scripts quicker to type out (often one liners). Good practice in larger scripts is to always use the "def" keyword so you don't run into strange scoping issues or interfere with variables you don't intend to.
184,009
<p>I can't find this anywhere in the Domino Designer help. It seems so straightforward!</p> <p>All I need to do is find the position of a character in a string.</p>
[ { "answer_id": 195251, "author": "molasses", "author_id": 11293, "author_profile": "https://Stackoverflow.com/users/11293", "pm_score": 1, "selected": true, "text": "<p>(edited) Please see the answer from charles ross instead.\n<a href=\"https://stackoverflow.com/a/19437044/11293\">https://stackoverflow.com/a/19437044/11293</a></p>\n\n<p>My less efficient method is below.</p>\n\n<hr>\n\n<p>If you really need the character position though you could do this:</p>\n\n<pre><code>REM {\n S Source string\n F Character to find\n R Location of character in string or 0\n};\n\nS := \"My string\";\nF := \"t\";\nLEN_S := @Length(S);\nR := 0;\n\n@For(I := 1; I &lt; LEN_S; I := I + 1;\n @If(@Middle(S; I; 1) = F;\n @Do(R := I; I := LEN_S);\n @Nothing\n )\n);\n</code></pre>\n" }, { "answer_id": 279298, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>searchResult:=@Left(SearchString;\"C\");\nindexOf:=@If(searchResult=\"\";0;@Length(searchResult));\nindexOf</p>\n" }, { "answer_id": 546460, "author": "david dickey", "author_id": 20132, "author_profile": "https://Stackoverflow.com/users/20132", "pm_score": -1, "selected": false, "text": "<p>@Length(src) - @Length(@ReplaceSubstring(src;srch;\"\"))</p>\n" }, { "answer_id": 19437044, "author": "charles ross", "author_id": 1337544, "author_profile": "https://Stackoverflow.com/users/1337544", "pm_score": 2, "selected": false, "text": "<p>You could use @Left or @Leftback. I think in this case they work the same.</p>\n\n<pre><code>src:= {your field value to search};\nchar:= {your target character};\nindexof:= @Length(@Left(src;char))\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2273/" ]
I can't find this anywhere in the Domino Designer help. It seems so straightforward! All I need to do is find the position of a character in a string.
(edited) Please see the answer from charles ross instead. <https://stackoverflow.com/a/19437044/11293> My less efficient method is below. --- If you really need the character position though you could do this: ``` REM { S Source string F Character to find R Location of character in string or 0 }; S := "My string"; F := "t"; LEN_S := @Length(S); R := 0; @For(I := 1; I < LEN_S; I := I + 1; @If(@Middle(S; I; 1) = F; @Do(R := I; I := LEN_S); @Nothing ) ); ```
184,014
<p>Can an XML attribute be the empty string?</p> <p>In other words, is</p> <pre><code>&lt;element att="" /&gt; </code></pre> <p>valid XML?</p>
[ { "answer_id": 184024, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 4, "selected": false, "text": "<p>Yes, this is well-formed XML.</p>\n\n<p>An easy way to test this (on Windows) is to save the sample in a <code>test.xml</code> file and open it with Internet Explorer. IE will display an error message if the document is not well-formed.</p>\n" }, { "answer_id": 184030, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>It is worth nothing that this is an XML <em>attribute</em>, not an element. An empty element would be:</p>\n\n<pre><code>&lt;/&gt;\n</code></pre>\n\n<p>which is not valid XML.</p>\n" }, { "answer_id": 184042, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It should also be noted that some XML parsers will throw an error on empty string nodes and attributes instead of returning null or an empty string. So even though it might be valid, it would be better to leave it out altogether.</p>\n" }, { "answer_id": 184046, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 4, "selected": true, "text": "<p>You can create an empty attribute via\n attname=\"\"</p>\n\n<p>You can create an empty element via</p>\n\n<pre><code>&lt;elementName&gt;&lt;/elementName&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;elementName/&gt;\n</code></pre>\n" }, { "answer_id": 184160, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 0, "selected": false, "text": "<p>Yes - element content can be empty, and as you used in your question there's even the special Empty-Element tag notation:</p>\n\n<pre><code>&lt;elementname /&gt;\n</code></pre>\n\n<p>Except when interop with SGML is necessary, the above is equivalent to </p>\n\n<pre><code>&lt;elementname&gt;&lt;/elementname&gt;\n</code></pre>\n\n<p>Attribute values can also be empty, but attributes must always be followed by an '=' and a quoted string, even if the string contains no characters.</p>\n\n<hr>\n\n<p>The definitive place for this\n information is the XML spec: \n <a href=\"http://www.xml.com/axml/testaxml.htm\" rel=\"nofollow noreferrer\">http://www.xml.com/axml/testaxml.htm</a></p>\n\n<p>Here's what the Annotated XML Reference has to say about empty elements:</p>\n\n<blockquote>\n <p>So, is this: <code>&lt;img\n src='madonna.gif'&gt;&lt;/img&gt;</code> really\n exactly the same as <code>&lt;img\n src='madonna.gif'/&gt;</code>? As far as XML is\n concerned, they are. This decision was\n the occasion of much religious debate,\n with some feeling that there is an\n essential element between \"point\" and\n \"container\" type elements. And as the\n \"for interoperability\" note below\n makes clear, if you are using pre-1998\n SGML software to process XML, there is\n a big difference.</p>\n</blockquote>\n\n<p><strong>note:</strong> the discussion on empty elements was due to the original wording of the posted question.</p>\n" }, { "answer_id": 3323984, "author": "coder", "author_id": 400885, "author_profile": "https://Stackoverflow.com/users/400885", "pm_score": 2, "selected": false, "text": "<p>this is valid xml tag:</p>\n\n<pre><code>&lt;mytag myattrib=\"\"/&gt;\n</code></pre>\n\n<p>this is not:</p>\n\n<pre><code>&lt;mytag myattrib/&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447/" ]
Can an XML attribute be the empty string? In other words, is ``` <element att="" /> ``` valid XML?
You can create an empty attribute via attname="" You can create an empty element via ``` <elementName></elementName> ``` or ``` <elementName/> ```
184,027
<p>I am looking hard at the basic principles of storing the state of an executing program to disk, and bringing it back in again. In the current design that we have, each object (which is a C-level thingy with function pointer lists, kind of low-level home-made object-orientation -- and there are very good reasons for doing it this way) will be called to export its explicit state to a writable and restorable format. The key property to make this work is that all state related to an object is indeed encapsulated in the object data structures. </p> <p>There are other solutions where you work with active objects, where there is a user-level thread attached to some objects. And thus, the program counter, register contents, and stack contents suddenly become part of the program state. As far as I can see, there is no good way to serialize such things to disk at an arbitrary point in time. The threads have to go park themselves in some special state where nothing is represented by the program counter et al, and thus basically "save" their execution state machine state to the explicit object state. </p> <p>I have looked at a range of serialization libraries, and as far as I can tell this is a universal property. </p> <p><strong>The core quesion is this: Or is this actually not so? Are there save/restore solutions out there that can include thread state, in terms of where in its code a thread is executing?</strong> </p> <p>Note that saving an entire system state in a virtual machine does not count, that is not really serializing the state, but just freezing a machine and moving it. It is an obvious solution, but a bit heavyweight most of the time.</p> <p>Some questions made it clear that I was not clear enough in explaining the idea of how we do things. We are working on a simulator system, with very strict rules for code running inside it is allowed to be written. In particular, we make a complete divide between object construction and object state. The interface function pointers are recreated every time you set up the system, and are not part of the state. The state only consists of specific appointed "attributes" that each have a defined get/set function that converts between internal runtime representation and storage representation. For pointers between objects, they are all converted to names. So in our design, an object might come out like this in storage:</p> <pre><code>Object foo { value1: 0xff00ff00; value2: 0x00ffeedd; next_guy_in_chain: bar; } Object bar { next_guy_in_chain: null; } </code></pre> <p>Linked lists are never really present in the simulation structure, each object represents a unit of hardware of some kind. </p> <p>The problem is that some people want to do this, but also have threads as a way to code behavior. "Behavior" here is really mutation of the state of the simulation units. Basically, the design we have says that all such changeds have to be made in atomic complete operations that are called, do their work, and return. All state is stored in the objects. You have a reactive model, or it could be called "run to completion", or "event driven". </p> <p>The other way of thinking about this is to have objects have active threads working on them, which sit in an eternal loop in the same way as classic Unix threads, and never terminate. This is the case that I am trying to see if it can be reasonable stored to disk, but it does not seem like that is feasible without interposing a VM underneath.</p> <p><em>Update, October 2009:</em> A paper related to this was published at the FDL conference in 2009, see <a href="http://www.engbloms.se/jakob_publications.html" rel="nofollow noreferrer">this paper</a> about checkpointing and SystemC.</p>
[ { "answer_id": 184124, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 0, "selected": false, "text": "<p>You should NOT try to serialize a state that your program has to disk. Because your program <strong>will never have full control over its' state</strong> unless it is allowed to by the operating system, in which case... it is part of the operating system.</p>\n\n<p>You <strong>can not guarantee that a pointer to some virtual memory location will point to the same virtual memory location again</strong> (except for properties like heap-begin/end, stack-begin), because to the program the operating systems' choices for virtual memory are indeterministic. The pages you request from the OS via sbrk or the higher level interfaces such as malloc will begin anywhere.</p>\n\n<p>Better:</p>\n\n<ul>\n<li>Code clean and inspect your design: What state properties are part of it? </li>\n<li>Do not use such a low-level language, because the overhead in creating what you attempt to do is not worth the results.</li>\n<li>If you must use C, consider means to make your life as easy as possible (consider the offsetof operator and the properties structs have such like first member starting at offset 0).</li>\n</ul>\n\n<p>I suspect <strong>you want to shortcut the development time it takes to serialize/deserialize specific data structures</strong>, such as linked lists. Be assured, <strong>what you are attempting to do is not trivial and it's a lot more work</strong>. If you insist on doing so, consider looking into your operating system's memory management code and into the OS's paging mechanisms. ;-)</p>\n\n<p><strong>EDIT</strong> due to appended question: The design you state sounds like some kind of state machine; object properties are set up such that they are serializable, function pointers can be restored.</p>\n\n<p>First, <strong>regarding thread states in objects: these only matter if there can be typical concurrent-programming problems such as race conditions</strong>, etc. If that's the case, you need thread-synchronization functionality, such as mutexes, semaphores, etc. Then you can at any time access the properties to serialize/deserialize and be safe.</p>\n\n<p>Second, regarding object setup: looks cool, not sure if you are having a binary or other object representation. Assuming binary: you can serialize them easily if you can represent the actual structures in memory (which is a bit of coding overhead). <strong>Insert some kind of class-ID value at the begin of the objects and have a look up table that points to the actual outfit</strong>. Look at the first sizeof(id) bytes and you know which kind of struct you have. Then you will know which structure is laying there.</p>\n\n<p>When serializing/deserializing, approach the problem like this: you can look up the length of the hypothetically packed (no spacing between members) structure, allocate that size and read/write the members one after the other. Think offsetof or, if your compiler supports it, just use packed structs.</p>\n\n<p><strong>EDIT due to bold core question :-)</strong> No, there are none; not for C.</p>\n" }, { "answer_id": 184127, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 0, "selected": false, "text": "<p>It looks like you want have a <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"nofollow noreferrer\">closure</a> in C++. As you have pointed out there is no mechanism built into the language to let you do this. As far as I know this is basically impossible to do in a totally general manner. In general it's hard to do in a language that doesn't have a VM. You can fake it somewhat by doing something like you have suggested basically creating a closure object that maintains the execution environment/state. Then having this serialize itself when it is in a known state.</p>\n\n<p>You will also run into trouble with your function pointers. The functions can be loaded to different memory addresses on each load.</p>\n" }, { "answer_id": 184169, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p>It really sounds like saving the state of a virtual machine and being able to restore it the exact same way is exactly what you want.</p>\n\n<p>If all you need is to be able to start the program running with the same data that the previous execution was using, then you only need to save off and restore persistent data, the exact state of each thread shouldn't really matter, since it will change so fast anyways - and the actual addresses of things will be different the next time. Using a database should give you this ability anyways.</p>\n" }, { "answer_id": 184259, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 2, "selected": false, "text": "<p>I don't think serializing only \"some threads\" of a program can work, since you will run into problems with synchronization (some of the problems are described here <a href=\"http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html</a> ).\nSo persisting your whole program is the only viable way to get a consistent state.</p>\n\n<p>What you might look into is orthogonal persistence. There are some prototypical implementations:</p>\n\n<p><a href=\"http://research.sun.com/forest/COM.Sun.Labs.Forest.doc.external_www.PJava.main.html\" rel=\"nofollow noreferrer\">http://research.sun.com/forest/COM.Sun.Labs.Forest.doc.external_www.PJava.main.html</a></p>\n\n<p><a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.7429\" rel=\"nofollow noreferrer\">http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.7429</a></p>\n\n<p>But none of them are maintained anymore or have gained a lot of attraction (afaik). I guess checkpointing is not the best solution after all. In my own project <a href=\"http://www.siebengeisslein.org\" rel=\"nofollow noreferrer\">http://www.siebengeisslein.org</a> I am trying the approach of using lightweight transactions to dispatch an event so thread state does not have to be maintained (since at the end of a transaction, the thread callstack is empty again, and if a operation is stopped in mid-transaction, everything is rolled back, so the thread callstack does matter as well).\nYou probably can implement something similar with any OODBMS.</p>\n\n<p>Another way to look at things are continuations (<a href=\"http://en.wikipedia.org/wiki/Continuation\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Continuation</a> , <a href=\"http://jauvm.blogspot.com/\" rel=\"nofollow noreferrer\">http://jauvm.blogspot.com/</a>). They are a way to suspend execution at defined code locations (but they are not necessarily persisting the thread state).</p>\n\n<p>I hope this gives you some starting points (but there is no ready-to-use solution to this afaik).</p>\n\n<p>EDIT: After reading your clarifications: You should definitely look into OODBMS. Dispatch each event in its own transaction and don't care about threads.</p>\n" }, { "answer_id": 184317, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 0, "selected": false, "text": "<p>I consider the thread state to be an implementation detail which is probably not appropriate to be serialized. You want to save the state of your objects--not necessarily how they got to be the way they are.</p>\n\n<p>As an example for why you want to take this approach, consider hitless upgrade. If you're running version N of your application and want to upgrade to version N+1, you can do so using object serialization. However, the \"version N+1\" threads are going ot be different from the version N threads.</p>\n" }, { "answer_id": 184318, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 1, "selected": false, "text": "<p>A better approach than trying to serialize program state would be to implement <a href=\"http://en.wikipedia.org/wiki/Crash-only_software\" rel=\"nofollow noreferrer\">Crash Only Software</a> with data checkpointing. How you do your data checkpointing will depend on your implementation and problem domain. </p>\n" }, { "answer_id": 185054, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 0, "selected": false, "text": "<p>Something like this was actually proposed for Java in JSR 323:</p>\n\n<p><a href=\"http://tech.puredanger.com/2008/01/09/strong-mobility-for-java/\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/2008/01/09/strong-mobility-for-java/</a></p>\n\n<p>but was not accepted as being too theoretical:</p>\n\n<p><a href=\"http://tech.puredanger.com/2008/01/24/jcp-votes-down-jsr-323/\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/2008/01/24/jcp-votes-down-jsr-323/</a></p>\n\n<p>If you follow the links, you can find some interesting research on this problem.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23054/" ]
I am looking hard at the basic principles of storing the state of an executing program to disk, and bringing it back in again. In the current design that we have, each object (which is a C-level thingy with function pointer lists, kind of low-level home-made object-orientation -- and there are very good reasons for doing it this way) will be called to export its explicit state to a writable and restorable format. The key property to make this work is that all state related to an object is indeed encapsulated in the object data structures. There are other solutions where you work with active objects, where there is a user-level thread attached to some objects. And thus, the program counter, register contents, and stack contents suddenly become part of the program state. As far as I can see, there is no good way to serialize such things to disk at an arbitrary point in time. The threads have to go park themselves in some special state where nothing is represented by the program counter et al, and thus basically "save" their execution state machine state to the explicit object state. I have looked at a range of serialization libraries, and as far as I can tell this is a universal property. **The core quesion is this: Or is this actually not so? Are there save/restore solutions out there that can include thread state, in terms of where in its code a thread is executing?** Note that saving an entire system state in a virtual machine does not count, that is not really serializing the state, but just freezing a machine and moving it. It is an obvious solution, but a bit heavyweight most of the time. Some questions made it clear that I was not clear enough in explaining the idea of how we do things. We are working on a simulator system, with very strict rules for code running inside it is allowed to be written. In particular, we make a complete divide between object construction and object state. The interface function pointers are recreated every time you set up the system, and are not part of the state. The state only consists of specific appointed "attributes" that each have a defined get/set function that converts between internal runtime representation and storage representation. For pointers between objects, they are all converted to names. So in our design, an object might come out like this in storage: ``` Object foo { value1: 0xff00ff00; value2: 0x00ffeedd; next_guy_in_chain: bar; } Object bar { next_guy_in_chain: null; } ``` Linked lists are never really present in the simulation structure, each object represents a unit of hardware of some kind. The problem is that some people want to do this, but also have threads as a way to code behavior. "Behavior" here is really mutation of the state of the simulation units. Basically, the design we have says that all such changeds have to be made in atomic complete operations that are called, do their work, and return. All state is stored in the objects. You have a reactive model, or it could be called "run to completion", or "event driven". The other way of thinking about this is to have objects have active threads working on them, which sit in an eternal loop in the same way as classic Unix threads, and never terminate. This is the case that I am trying to see if it can be reasonable stored to disk, but it does not seem like that is feasible without interposing a VM underneath. *Update, October 2009:* A paper related to this was published at the FDL conference in 2009, see [this paper](http://www.engbloms.se/jakob_publications.html) about checkpointing and SystemC.
I don't think serializing only "some threads" of a program can work, since you will run into problems with synchronization (some of the problems are described here <http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html> ). So persisting your whole program is the only viable way to get a consistent state. What you might look into is orthogonal persistence. There are some prototypical implementations: <http://research.sun.com/forest/COM.Sun.Labs.Forest.doc.external_www.PJava.main.html> <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.7429> But none of them are maintained anymore or have gained a lot of attraction (afaik). I guess checkpointing is not the best solution after all. In my own project <http://www.siebengeisslein.org> I am trying the approach of using lightweight transactions to dispatch an event so thread state does not have to be maintained (since at the end of a transaction, the thread callstack is empty again, and if a operation is stopped in mid-transaction, everything is rolled back, so the thread callstack does matter as well). You probably can implement something similar with any OODBMS. Another way to look at things are continuations (<http://en.wikipedia.org/wiki/Continuation> , <http://jauvm.blogspot.com/>). They are a way to suspend execution at defined code locations (but they are not necessarily persisting the thread state). I hope this gives you some starting points (but there is no ready-to-use solution to this afaik). EDIT: After reading your clarifications: You should definitely look into OODBMS. Dispatch each event in its own transaction and don't care about threads.
184,034
<p>What do you do to pass information between forms? Forward is straight forward (sorry) using Properties or maybe parameters in a New() or DoStuff() method, but what about sending something <strong><em>back</em></strong> when the user is done with the second form? (IE. ID of the item selected) We have used all these:</p> <ul> <li><strong>Passed the calling form into the called form as a ref</strong> so the called form could access properties or methods on the calling form. I really don't like this because the two forms are very dependent of each other. Passing the calling form as a object only slightly improves this.</li> <li><strong>Use Events</strong> This somewhat decouples the code, but the signatures must match on the event handler.</li> <li><strong>Use an Public Interface</strong> I'm talking about the .NET built in one, but I suppose you could create your own. This seems like the best to me.</li> </ul> <p>Now raise the bar, what if the forms are in two different DLLs? As long as the forms are not dependent on each other, I would think this wouldn't be a big step.</p>
[ { "answer_id": 184067, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 0, "selected": false, "text": "<p>Do you want to access the UI elements of the second form? I think a cleaner way is to using a shared object for passing the data back to the calling form. Pass the object as a parameter to the second form constructor, which can populate the instance fields and return that instance to the calling form. This object can also raise any events (like property change events) to notify the calling form (or subscribers) if required.</p>\n" }, { "answer_id": 184068, "author": "David Hill", "author_id": 1181217, "author_profile": "https://Stackoverflow.com/users/1181217", "pm_score": 0, "selected": false, "text": "<p>If it's a matter of a main form creating an instance of another form, waiting for the form to do some work and then close, and checking it's result, then having public properties or listening for events makes the most sense. Neither of these things would be impacted by having the forms in different assemblies. You do get an explicit binding contract between the two forms, but if the properties were described (as you suggest) in a public interface, than as long as everyone agrees to the terms of the interface, you're good.</p>\n\n<p>I'm not sure how much more complicated you'd want this to get. In the past I've used a static singleton object for holding application state. The app-state object would expose event handlers that other parts of the program could listen to. The main form would create the app-state (just get a reference to it really) and listen to certain events on it. Then the main form would create child forms and controls to do work. The children would change properties of the app-state object, which would in turn fire events that the primary form would listen for. This way the various forms and controls were decoupled from each-other. The downside is that they were tightly couple to the app-state singleton.</p>\n" }, { "answer_id": 184077, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 2, "selected": false, "text": "<p>Create public properties for the form, then wait for the form to close and check the properties before disposing the new form.</p>\n\n<pre><code>NewForm myForm = new NewForm();\nmyForm.ShowDialog();\nstring x = myform.MyProperty;\n</code></pre>\n" }, { "answer_id": 184088, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 0, "selected": false, "text": "<p>One thing I had success doing was to create a lightweight publish / subscribe eventing system in the application. This was in .net 1.1 and not sure how it would change with generics. Essentially we had a singleton which contained a hashtable with a string key, and multi-cast delgates.</p>\n\n<p>The singleton had methods like RegisterForEvent(string key, delegate handler), RaiseEvent(key,data) etc...</p>\n\n<p>We then defined a standard delegate and said all users must implement this pattern for example our handlers had to be: void method(object sender, CustomEventArgs args). Publishers would define their own derived class of CustomEventArgs.</p>\n\n<p>The nice thing is this allowed a completly decoupled system to be built. We had many assemblies and didn't have any issue just need to ensure your eventargs are defined where other subs could get at them.</p>\n\n<p>We had what we called different subsystems for example we had one which monitored the internet connection and when it raised an event, the UI would change to indicate the status of their connection, we also had a queueing service which would post messages to the server, when it saw the connection dropped we would stop posting.</p>\n\n<p>The downside is it is very looseley coupled at least our implementation was but there are ways to improve upon that.</p>\n" }, { "answer_id": 1182528, "author": "Raiford", "author_id": 136536, "author_profile": "https://Stackoverflow.com/users/136536", "pm_score": 2, "selected": false, "text": "<p>I have found that once you have a well designed <strong><em>Domain Entity Object Model</em></strong> or simply business objects. These tasks become much easier. </p>\n\n<p>If you dont have Domain Entities such as Employee, Account, Location etc., you find yourself writing forms with a bunch of properties and create tons of awkward dependencies. Over time this can be very messy.</p>\n\n<p>Once you have the Domain Entity in place things are much easier to deal with. For example, to edit your Employee using a form you can simply create an Employee property like this:</p>\n\n<pre><code>NewForm myForm = new NewForm(); \nmyForm.Employee = employeeToEdit; // This can have state \nmyForm.ShowDialog(); \nEmployee editedEmployee= myform.Employee;\n\nEmployeeFacade.SaveEmployee(editedEmployee); // Or whatever\n</code></pre>\n\n<p>Regarding Events, for Winform/WPF apps it it almost aways helpful to create a global EventManager using publish / subscribe pattern to handle communication between forms. It is very rare I will ever have one form 'talk' directly to any other form. That is another topic so I will not go into detail, if you want examples I can provide several I have done.</p>\n\n<p>Raiford Brookshire </p>\n" }, { "answer_id": 1520270, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>this.Hide();\nstring[]name = new string[];\nnew frmFormName = new frm(string what, string you, string going, string to, string put, stiring in);\nthis.ShowDialog();\nthis.Show();</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24991/" ]
What do you do to pass information between forms? Forward is straight forward (sorry) using Properties or maybe parameters in a New() or DoStuff() method, but what about sending something ***back*** when the user is done with the second form? (IE. ID of the item selected) We have used all these: * **Passed the calling form into the called form as a ref** so the called form could access properties or methods on the calling form. I really don't like this because the two forms are very dependent of each other. Passing the calling form as a object only slightly improves this. * **Use Events** This somewhat decouples the code, but the signatures must match on the event handler. * **Use an Public Interface** I'm talking about the .NET built in one, but I suppose you could create your own. This seems like the best to me. Now raise the bar, what if the forms are in two different DLLs? As long as the forms are not dependent on each other, I would think this wouldn't be a big step.
Create public properties for the form, then wait for the form to close and check the properties before disposing the new form. ``` NewForm myForm = new NewForm(); myForm.ShowDialog(); string x = myform.MyProperty; ```
184,074
<p>When I debug locally in fire fox 2.0x many times my page won't have the styles added properly or the page will not completely render (the end is seemingly cut off). Sometimes it takes multiple refreshes or shift-refreshes to fix this. Is this a common issue or is it just me? Any solutions?</p> <p>I want to add that this is happening in fire fox 3.x to me as well. I add my javascript to the pages dynamically and this might be part of the issue. This is when I am working locally with Visual Studio.</p> <p>Update: This does happen in IE but it happens much more often in Fire Fox. The issue seems to be only javascript and CSS files not loading. For example I get jQuery is not defined, $ is not defined etc. I don't think I have local IIS to test this on but from the server it always works perfectly. Fire Bug shows all my css and javascript files to be requested and received.</p>
[ { "answer_id": 485740, "author": "cdeszaq", "author_id": 20770, "author_profile": "https://Stackoverflow.com/users/20770", "pm_score": 0, "selected": false, "text": "<p>One thing to do would be to check the source of the page(s) in question. My guess would be that the local server that VS runs is not giving you the entire source of the page. One way to verify this would be to run exactly the same code in the debug environment, as well as from a \"real\" server like IIS 6. If the same behavior is seen on loading the page from both servers, as well as insuring that the full page source is being recieved by the browser(s), then it is a bug in Firefox and should be reported. This is especially true if other browsers, ie. IE, Chrome, Safari, Opera, render the page fully.</p>\n" }, { "answer_id": 493356, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "<p>This could be a <strong>problem with IPv6 and DNS</strong> of the Firefox browser. This issue is known to <em>slow down</em> Firefox on localhost:SOMEPORT. The effect would be that some external files won't load (css, js etc.) resulting in a partially rendered page.</p>\n\n<p>You can solve this issue by simply deactivating IPv6 in Firefox:</p>\n\n<ol>\n<li>Insert <code>about:config</code> in the Firefox address bar</li>\n<li>Set <code>network.dns.disableIPv6</code> to <code>true</code> or alternatively add <code>localhost</code> to <code>network.dns.ipv4OnlyDomains</code></li>\n</ol>\n\n<p>A different way to fix this issue, is to a remove the ipv6 address from your hosts file this way: open the file</p>\n\n<pre><code>C:\\Windows\\System32\\drivers\\etc\\hosts\n</code></pre>\n\n<p>(with administrator privileges) and remove (or comment out #):</p>\n\n<pre><code> :: localhost\n</code></pre>\n" }, { "answer_id": 493572, "author": "Mitchell Gilman", "author_id": 43219, "author_profile": "https://Stackoverflow.com/users/43219", "pm_score": 1, "selected": false, "text": "<p>Make sure that you narrow the scope of the problem. Does the problem just happen when debugging from VS or does it also happen with local IIS? With server-based IIS? Does it happen to other developers in your company? Is it really just FireFox or does it happen to Chrome, Opera, IE, etc?</p>\n\n<p>Assuming that you've already worked that all out, I would suggest installing a FireFox plug-in called \"Tamper Data\". Open that and refresh the page. You'll see a record of every connection from the browser to the server (for each html file, image, css file, etc). Look to see if any of the them are very slow or not completing (perhaps one of those files is taking a long time and FF is waiting for it to finish before loading other important files). </p>\n\n<p>Assuming that all of the files correctly loads, you should consider checking that the syntax is valid (maybe there is some unclosed tag or quotation mark that is causing FF confusion). I use a plugin called \"Web Developer\", but there are a lot of other options out there. </p>\n\n<p>You could also use a plugin called FireBug to view the HTML behind various parts of the page to see if there are any noticeable problems. You start FireBug, go to the HTML tab, click Inpsect, and move your mouse over something on the page, and it will show you the HTML behind it.</p>\n" }, { "answer_id": 496619, "author": "Eppz", "author_id": 48478, "author_profile": "https://Stackoverflow.com/users/48478", "pm_score": 0, "selected": false, "text": "<p>Are you comparing what you see in Firefox to what is displayed in the Visual Studio designer? If this is the case, then they are using 2 different methods to render the html and may not display the same.</p>\n" }, { "answer_id": 560699, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Anything further on this folks?</p>\n\n<p>I have examined the traffic using Firebug and it appears that when veiwing the response from the request for a style sheet, the response is just blank. After refreshing (sometimes multiple times) the age displays correctly and the response information contains the style sheet. I have not seen this in any other browser and it only occurs when viewing the app from Visual Studio.</p>\n" }, { "answer_id": 875349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>2! Recently i had the same problem. Im using MVC 1.0 and I added a new stylesheet into Views/Share folder. And when i run the project, the page didnt render along with the css. If your web project is a MVC one so try put the css file into the Content folder.\nHope this help. \nHaiVu.Doan.</p>\n" }, { "answer_id": 37258595, "author": "Leslie", "author_id": 6341732, "author_profile": "https://Stackoverflow.com/users/6341732", "pm_score": 0, "selected": false, "text": "<p>In case anyone else finds this with newer versions of Visual Studio, I have to run VS as Administrator. This is something I keep forgetting to do, but once I right clicked on Run as Administrator when opening VS, the problem went away.</p>\n\n<p>Initial problem, I could not get CSS to render when running a project from VS 2012 using Firefox as the browser. (IE worked just fine, btw.) The content would be there, but no CSS. This was the first post I found when I typed in my question.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18926/" ]
When I debug locally in fire fox 2.0x many times my page won't have the styles added properly or the page will not completely render (the end is seemingly cut off). Sometimes it takes multiple refreshes or shift-refreshes to fix this. Is this a common issue or is it just me? Any solutions? I want to add that this is happening in fire fox 3.x to me as well. I add my javascript to the pages dynamically and this might be part of the issue. This is when I am working locally with Visual Studio. Update: This does happen in IE but it happens much more often in Fire Fox. The issue seems to be only javascript and CSS files not loading. For example I get jQuery is not defined, $ is not defined etc. I don't think I have local IIS to test this on but from the server it always works perfectly. Fire Bug shows all my css and javascript files to be requested and received.
This could be a **problem with IPv6 and DNS** of the Firefox browser. This issue is known to *slow down* Firefox on localhost:SOMEPORT. The effect would be that some external files won't load (css, js etc.) resulting in a partially rendered page. You can solve this issue by simply deactivating IPv6 in Firefox: 1. Insert `about:config` in the Firefox address bar 2. Set `network.dns.disableIPv6` to `true` or alternatively add `localhost` to `network.dns.ipv4OnlyDomains` A different way to fix this issue, is to a remove the ipv6 address from your hosts file this way: open the file ``` C:\Windows\System32\drivers\etc\hosts ``` (with administrator privileges) and remove (or comment out #): ``` :: localhost ```
184,084
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application">What is the correct way to create a single instance application?</a> </p> </blockquote> <p>How to force C# .net app to run only one instance in Windows?</p>
[ { "answer_id": 184143, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 7, "selected": false, "text": "<p>I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded</p>\n\n<pre><code>using System.Threading;\n\n[DllImport(\"user32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\n/// &lt;summary&gt;\n/// The main entry point for the application.\n/// &lt;/summary&gt;\n[STAThread]\nstatic void Main()\n{\n bool createdNew = true;\n using (Mutex mutex = new Mutex(true, \"MyApplicationName\", out createdNew))\n {\n if (createdNew)\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new MainForm());\n }\n else\n {\n Process current = Process.GetCurrentProcess();\n foreach (Process process in Process.GetProcessesByName(current.ProcessName))\n {\n if (process.Id != current.Id)\n {\n SetForegroundWindow(process.MainWindowHandle);\n break;\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 184210, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 3, "selected": false, "text": "<p>This is what I use in my application:</p>\n\n<pre><code>static void Main()\n{\n bool mutexCreated = false;\n System.Threading.Mutex mutex = new System.Threading.Mutex( true, @\"Local\\slimCODE.slimKEYS.exe\", out mutexCreated );\n\n if( !mutexCreated )\n {\n if( MessageBox.Show(\n \"slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?\",\n \"slimKEYS already running\",\n MessageBoxButtons.YesNo,\n MessageBoxIcon.Question ) != DialogResult.Yes )\n {\n mutex.Close();\n return;\n }\n }\n\n // The usual stuff with Application.Run()\n\n mutex.Close();\n}\n</code></pre>\n" }, { "answer_id": 6416663, "author": "snir", "author_id": 807301, "author_profile": "https://Stackoverflow.com/users/807301", "pm_score": 5, "selected": false, "text": "<p>to force running only one instace of a program in .net (C#) use this code in program.cs file:</p>\n\n<pre><code>public static Process PriorProcess()\n // Returns a System.Diagnostics.Process pointing to\n // a pre-existing process with the same name as the\n // current one, if any; or null if the current process\n // is unique.\n {\n Process curr = Process.GetCurrentProcess();\n Process[] procs = Process.GetProcessesByName(curr.ProcessName);\n foreach (Process p in procs)\n {\n if ((p.Id != curr.Id) &amp;&amp;\n (p.MainModule.FileName == curr.MainModule.FileName))\n return p;\n }\n return null;\n }\n</code></pre>\n\n<p>and the folowing:</p>\n\n<pre><code>[STAThread]\n static void Main()\n {\n if (PriorProcess() != null)\n {\n\n MessageBox.Show(\"Another instance of the app is already running.\");\n return;\n }\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form());\n }\n</code></pre>\n" }, { "answer_id": 11463450, "author": "Thyrador", "author_id": 1478230, "author_profile": "https://Stackoverflow.com/users/1478230", "pm_score": 2, "selected": false, "text": "<p>another way to single instance an application is to check their hash sums.\nafter messing around with mutex (didn't work as i want) i got it working this way:</p>\n\n<pre><code> [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool SetForegroundWindow(IntPtr hWnd);\n\n public Main()\n {\n InitializeComponent();\n\n Process current = Process.GetCurrentProcess();\n string currentmd5 = md5hash(current.MainModule.FileName);\n Process[] processlist = Process.GetProcesses();\n foreach (Process process in processlist)\n {\n if (process.Id != current.Id)\n {\n try\n {\n if (currentmd5 == md5hash(process.MainModule.FileName))\n {\n SetForegroundWindow(process.MainWindowHandle);\n Environment.Exit(0);\n }\n }\n catch (/* your exception */) { /* your exception goes here */ }\n }\n }\n }\n\n private string md5hash(string file)\n {\n string check;\n using (FileStream FileCheck = File.OpenRead(file))\n {\n MD5 md5 = new MD5CryptoServiceProvider();\n byte[] md5Hash = md5.ComputeHash(FileCheck);\n check = BitConverter.ToString(md5Hash).Replace(\"-\", \"\").ToLower();\n }\n\n return check;\n }\n</code></pre>\n\n<p>it checks only md5 sums by process id.</p>\n\n<p>if an instance of this application was found, it focuses the running application and exit itself.</p>\n\n<p>you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.</p>\n\n<p>may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316/" ]
> > **Possible Duplicate:** > > [What is the correct way to create a single instance application?](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application) > > > How to force C# .net app to run only one instance in Windows?
I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded ``` using System.Threading; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } } } ```
184,096
<p>Suppose there is a fully populated array of data String[n][3] myData.</p> <p>I want to do this:</p> <pre><code>for (String[] row : myData) { SQL = "update mytable set col3 = row[2] where col1 = row[0] and col2=row[1];" } </code></pre> <p>Obviously I've left a lot out, but I want to express the idea as succinctly as possible.</p> <p>Is there a simple way of doing this in a single DB command? How about a not so simple way?</p> <p>EDITS: Data is not coming from another table (it's a web form submission - Multiple Choice exam)<br> Seeing as the app is web facing, It's got to be injection proof. Parameterized Queries are my preferred way of going.<br> I'm using MS-SQL Server 2005</p> <p>EDIT:Closing, and re-asking as <a href="https://stackoverflow.com/questions/184471/multiple-db-updates">Multiple DB Updates:</a></p> <p>EDIT: Re-opened, as this appears to be a popular question</p>
[ { "answer_id": 184123, "author": "fmsf", "author_id": 26004, "author_profile": "https://Stackoverflow.com/users/26004", "pm_score": 1, "selected": false, "text": "<p>You can make a big string like:</p>\n\n<pre><code>for (String[] row : myData)\n{\n SQL += \"update mytable set col3 = row[2]\n where col1 = row[0] and col2=row[1];\" \n}\n\nsqlDriver.doInsertQuery(SQL); // change this to your way of inserting into the db\n</code></pre>\n\n<p>And just commit it all at once. I'm not very good with SQL so that's how i would do it.</p>\n\n<p>The sql engine will just split it by the ';' and do separate inserts on its own. It's ok to add it all in a string though. It's kind the same as if u copy a big string with multiple updates/inserts into the sql prompt</p>\n" }, { "answer_id": 184126, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 0, "selected": false, "text": "<p>Not really. You could create the string with the same loop, then pass your values as parameters, but that will still be multiple database commands.</p>\n\n<pre><code>for each whatever\n sql += \"UPDATE ... ;\"\nend for\nexecute (sql)\n</code></pre>\n" }, { "answer_id": 184129, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 1, "selected": false, "text": "<p>This may not be the answer you want, but opening a transaction, executing your statements and then committing the transaction would, from a database point of view, do what you describe. </p>\n\n<p>The state of the database does not change for other users of the database until the transaction has been completed, and that probably is the preferred effect.</p>\n" }, { "answer_id": 184148, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 0, "selected": false, "text": "<p>I suspect you will need to use multiple SQL statements. You may find a wrapper to handle the minutiae but underneath I'd imagine it'd iteratively run a SQL statement for each UPDATE.</p>\n" }, { "answer_id": 184200, "author": "Ted Elliott", "author_id": 16501, "author_profile": "https://Stackoverflow.com/users/16501", "pm_score": 3, "selected": true, "text": "<p>If you are using Sql Server you can use SqlBulkCopy. You would first have to put your data in a DataTable, which would be pretty easy since you already have it in a string array.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx</a></p>\n" }, { "answer_id": 184263, "author": "Kevin Berridge", "author_id": 4407, "author_profile": "https://Stackoverflow.com/users/4407", "pm_score": 3, "selected": false, "text": "<p>It depends on what database you are using. If you're using SQL Server 2008, you can use stored procedure <a href=\"http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters\" rel=\"noreferrer\">TABLE parameters</a>. This allows you to pass all your values into the stored procedure in a single table, then you can do:</p>\n\n<pre><code>update mytable set mytable.col1 = @tbl.col1\n from mytable \n inner join @tbl on mytable.col2 = @tbl.col2\n</code></pre>\n\n<p>If you're using SQL Server 2005, you can use XML. Format your values as XML, then use XQuery statements (ie, 'nodes' and 'value') to parse out the XML. This can also be done in a single SQL statement, and it doesn't require a stored procedure.</p>\n" }, { "answer_id": 184274, "author": "helios", "author_id": 9686, "author_profile": "https://Stackoverflow.com/users/9686", "pm_score": 1, "selected": false, "text": "<p>That looks like you want to make an update A, over rows that has coditions B and C. (A, B, C) are stored as tuples (rows) in myData. Isn't it?</p>\n\n<p>Maybe (if you're using Microsoft SQL Server... I don't know if it exists in Oracle, could be) you can use a JOIN with an UPDATE. You can declare an update over a table joined with another one. If myData comes from another table then you could do (it's not the correct syntax) :</p>\n\n<pre><code>UPDATE whatchanges wc INNER JOIN changes c ON &lt;yourcondition&gt;\nSET wc.col1 = c.newvalue\nWHERE ....\n</code></pre>\n\n<p>(if you want to apply all changes in \"changes\" table you don't have to use WHERE of course, the INNER JOIN already has selected the correct rows).</p>\n\n<p>Of course there are limitations to this kind of update. And it's MS SQL proprietary. So if it's your case I'd suggest to look for it on MS web (keywords: UPDATE and JOIN)</p>\n" }, { "answer_id": 184360, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 1, "selected": false, "text": "<p>If you are using <a href=\"http://www.codeplex.com/entlib\" rel=\"nofollow noreferrer\">Enterprise Library</a> in your data access layer, you can create the transaction in .Net, iterate through your procedure calls, then commit/rollback all from .Net.</p>\n\n<pre><code>DbTransaction transaction = connection.BeginTransaction();\ntry\n{\n for (String[] row : myData)\n {\n ListDictionary params = new Specialized.ListDictionary();\n params.add(\"@col3\", row[2]);\n params.add(\"@col1\", row[0]);\n params.add(\"@col2\", row[1]);\n executeNonQuery(\"myUpdateProcedure\", params);\n }\n\n transaction.commit();\n\n}\ncatch(Exception ex)\n{\n transaction.rollback();\n throw ex;\n}\nfinally\n{\n\n connection.close();\n}\n</code></pre>\n" }, { "answer_id": 184367, "author": "cmsjr", "author_id": 23114, "author_profile": "https://Stackoverflow.com/users/23114", "pm_score": 1, "selected": false, "text": "<p>If for whatever reason you can't perform the update using one of the methods suggested above, the highly inefficient approach below would probably work for you. </p>\n\n<pre><code>SQL = \"Update myTable Set Col3 = Case \" \nfor (String[] row : myData)\n{\n SQL += \"When Col1 = \" + Row[0] + \" and Col2 = \" + Row[1] + \" then \" + row[2] + \" \" \n}\nSQL + = \"Else Col3 end\" \n</code></pre>\n" }, { "answer_id": 184468, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 0, "selected": false, "text": "<p>emit an update that goes against a values table:</p>\n\n<pre><code>UPDATE myTable SET col3=c FROM myTable JOIN (\n SELECT 1 as a, 2 as b, 'value1' as c UNION ALL\n SELECT 3 as a, 4 as b, 'value2' as c -- etc...\n) x ON myTable.col1=x.a AND myTable.col2=x.b\n</code></pre>\n\n<p>so you just put this together like this:</p>\n\n<pre><code>// make one of these for each row\nString.Format(\"SELECT {0} as a, {1} as b, '{2}' as c\", \n row[0], row[1], row[2].Replace(\"'\",\"''\")) \n\n// put it together\nstring expr = \"UPDATE myTable SET col3=c FROM myTable JOIN (\" +\n String.Join(stringformatarray, \" UNION ALL \") +\n \") x ON myTable.col1=x.a AND myTable.col2=x.b\"\n</code></pre>\n\n<p>or you can use StringBuilder to put this together.</p>\n\n<p>and then, of course, you execute this one string.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907/" ]
Suppose there is a fully populated array of data String[n][3] myData. I want to do this: ``` for (String[] row : myData) { SQL = "update mytable set col3 = row[2] where col1 = row[0] and col2=row[1];" } ``` Obviously I've left a lot out, but I want to express the idea as succinctly as possible. Is there a simple way of doing this in a single DB command? How about a not so simple way? EDITS: Data is not coming from another table (it's a web form submission - Multiple Choice exam) Seeing as the app is web facing, It's got to be injection proof. Parameterized Queries are my preferred way of going. I'm using MS-SQL Server 2005 EDIT:Closing, and re-asking as [Multiple DB Updates:](https://stackoverflow.com/questions/184471/multiple-db-updates) EDIT: Re-opened, as this appears to be a popular question
If you are using Sql Server you can use SqlBulkCopy. You would first have to put your data in a DataTable, which would be pretty easy since you already have it in a string array. <http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx>
184,099
<p>I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.</p> <pre><code>public function registerButtonCallback(function:Function):void { clearButtonCallback(); button.addEventListener(MouseEvent.CLICK, function, false, 0, true); } public function clearButtonCallback():void { if (button.hasEventListener(MouseEvent.CLICK) == true) { // do something to remove that listener } } </code></pre> <p>I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice.</p> <p>Suggestions?</p>
[ { "answer_id": 184331, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 3, "selected": false, "text": "<p>I am presuming that you want only one callback function at any given time. If that's teh case then why not have a single callback function associated with the click event on the button which itself called a function and have that function be settable...</p>\n\n<pre><code>&lt;mx:Button click=\"doCallback()\" .../&gt;\n\npublic var onClickFunction:Function = null;\nprivate function doCallback():void\n{\n if (onClickFunction != null)\n {\n onClickFunction(); // optionally you can pass some parameters in here if you match the signature of your callback\n }\n}\n</code></pre>\n\n<p>A consumer of your control which houses your button would set the onClickFunction with the appropriate function. In fact you could set it as often as you liked.</p>\n\n<p>If you wanted to go one step further you could subclass the AS3 Button class and wrap all of this inside it.</p>\n" }, { "answer_id": 196491, "author": "geraldalewis", "author_id": 7501, "author_profile": "https://Stackoverflow.com/users/7501", "pm_score": 2, "selected": false, "text": "<p>Store the listener as a prop. When another event is added, check to see if the listener exists, and if it does, call removeEventListener.</p>\n\n<p>Alternatively, override the addEventListener method of you button. When addEventListener is called, store the closure before adding it to the event in a Dictionary object. When addEventListener is called again, remove it:\n<pre><code>\nvar listeners:Dictionary = new Dictionary();</p>\n\n<p>override public function addEventListener( type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = false) : void {</p>\n\n<pre><code> if( listeners[ type ] ) {\n\n if( listeners[ type ] [ useCapture ] {\n\n //snip... etc: check for existence of the listener\n\n removeEventListener( type, listeners[ type ] [ useCapture ], useCapture );\n\n listeners[ type ] [ useCapture ] = null;\n\n //clean up: if no listeners of this type exist, remove the dictionary key for the type, etc...\n\n }\n\n }\n\n listeners[ type ] [ useCapture ] = listener;\n\n super.addEventListener( type, listener, useCapture, priority, useWeakReference );\n\n};\n</code></pre>\n\n<p></pre></code></p>\n" }, { "answer_id": 550391, "author": "Jonathan Dumaine", "author_id": 66584, "author_profile": "https://Stackoverflow.com/users/66584", "pm_score": 1, "selected": false, "text": "<p>Something I like to do is use a dynamic Global class and add a quick reference to the listener function inline. This is presuming you like to have the listener function in the addEventListener method like I do. This way, you can use removeEventListener inside the addEventListener :) </p>\n\n<p>Try this out:</p>\n\n<pre><code>package {\n\nimport flash.display.Sprite;\nimport flash.events.Event;\nimport flash.text.TextField;\n\n[SWF(width=\"750\", height=\"400\", backgroundColor=\"0xcdcdcd\")]\npublic class TestProject extends Sprite\n{ \n public function TestProject()\n {\n addEventListener(Event.ADDED_TO_STAGE, Global['addStageEvent'] = function():void {\n var i:uint = 0;\n //How about an eventlistener inside an eventListener?\n addEventListener(Event.ENTER_FRAME, Global['someEvent'] = function():void {\n //Let's make some text fields\n var t:TextField = new TextField();\n t.text = String(i);\n t.x = stage.stageWidth*Math.random();\n t.y = stage.stageHeight*Math.random();\n addChild(t);\n i++;\n trace(i);\n //How many text fields to we want?\n if(i &gt;= 50) {\n //Time to stop making textFields\n removeEventListener(Event.ENTER_FRAME, Global['someEvent']);\n //make sure we don't have any event listeners\n trace(\"hasEventListener(Event.ENTER_FRAME) = \"+hasEventListener(Event.ENTER_FRAME)); \n }\n });\n\n //Get rid of the listener\n removeEventListener(Event.ADDED_TO_STAGE, Global['addStageEvent']);\n trace('hasEventListener(Event.ADDED_TO_STAGE) = '+hasEventListener(Event.ADDED_TO_STAGE));\n\n });\n }\n\n} \n</code></pre>\n\n<p>}</p>\n\n<p>// looky here! This is the important bit\ndynamic class Global {}</p>\n\n<p>The secret is the dynamic class Global. With that you can dynamically add properties in at runtime. </p>\n" }, { "answer_id": 1771556, "author": "Triynko", "author_id": 88409, "author_profile": "https://Stackoverflow.com/users/88409", "pm_score": 2, "selected": false, "text": "<p>No. You need to hold a reference to the listener in order to remove it. Unless you store a reference to the listener function in advance, there is no documented public method available to retrieve such a reference from an EventDispatcher.</p>\n\n<pre><code>addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void\ndispatchEvent(event:Event):Boolean\nhasEventListener(type:String):Boolean\nremoveEventListener(type:String, listener:Function, useCapture:Boolean = false):void\nwillTrigger(type:String):Boolean \n</code></pre>\n\n<p>As you can see, there are two methods to tell you whether a type of event has a listener registered or one of its parents has a listener registered, but none of those methods actually return a list of registered listeners.</p>\n\n<p>Now please go harass Adobe for writing such a useless API. Basically, they give you the ability to know \"whether\" the event flow has changed, but they give you no way of doing anything with that information!</p>\n" }, { "answer_id": 3382227, "author": "Thomas Thorstensson", "author_id": 1279151, "author_profile": "https://Stackoverflow.com/users/1279151", "pm_score": 2, "selected": false, "text": "<p>I written a subclass called EventCurb for that purpose, see my <a href=\"http://thumbleaf.com\" rel=\"nofollow noreferrer\">blog</a> here or paste below.</p>\n\n<pre><code>package\n{\n import flash.events.EventDispatcher;\n import flash.utils.Dictionary;\n /**\n * ...\n * @author Thomas James Thorstensson\n * @version 1.0.1\n */\n public class EventCurb extends EventDispatcher\n {\n private static var instance:EventCurb= new EventCurb();\n private var objDict:Dictionary = new Dictionary(true);\n private var _listener:Function;\n private var objArr:Array;\n private var obj:Object;\n\n public function EventCurb() {\n if( instance ) throw new Error( \"Singleton and can only be accessed through Singleton.getInstance()\" );\n }\n\n public static function getInstance():EventCurb {\n return instance;\n }\n\n override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void\n {\n super.addEventListener(type, listener, useCapture, priority, useWeakReference);\n }\n\n override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void\n {\n super.removeEventListener(type, listener, useCapture);\n }\n\n public function addListener(o:EventDispatcher, type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {\n // the object as key for an array of its event types\n if (objDict[o] == null) objArr = objDict[o] = [];\n for (var i:int = 0; i &lt; objArr.length; i++) {\n if ( objArr[i].type == type)\n trace (\"_______object already has this listener not adding!\")\n return\n }\n obj = { type:type, listener:listener }\n objArr.push(obj);\n o.addEventListener(type, listener, useCapture, priority, useWeakReference);\n }\n\n public function removeListener(o:EventDispatcher, type:String, listener:Function, useCapture:Boolean = false):void {\n // if the object has listeners (ie exists in dictionary)\n if (objDict[o] as Array !== null) {\n var tmpArr:Array = [];\n tmpArr = objDict[o] as Array;\n for (var i:int = 0; i &lt; tmpArr.length; i++) {\n if (tmpArr[i].type == type) objArr.splice(i);\n }\n\n o.removeEventListener(type, listener, useCapture);\n if (tmpArr.length == 0) {\n delete objDict[o]\n }\n }else {\n trace(\"_______object has no listeners\");\n }\n }\n\n /**\n * If object has listeners, returns an Array which can be accessed\n * as array[index].type,array[index].listeners\n * @param o\n * @return Array\n */\n public function getListeners(o:EventDispatcher):Array{\n if (objDict[o] as Array !== null) {\n var tmpArr:Array = [];\n tmpArr = objDict[o] as Array;\n // forget trying to trace out the function name we use the function literal...\n for (var i:int = 0; i &lt; tmpArr.length; i++) {\n trace(\"_______object \" + o + \" has event types: \" + tmpArr[i].type +\" with listener: \" + tmpArr[i].listener);\n }\n return tmpArr\n\n }else {\n trace(\"_______object has no listeners\");\n return null\n }\n\n }\n\n public function removeAllListeners(o:EventDispatcher, cap:Boolean = false):void {\n if (objDict[o] as Array !== null) {\n var tmpArr:Array = [];\n tmpArr = objDict[o] as Array;\n for (var i:int = 0; i &lt; tmpArr.length; i++) {\n o.removeEventListener(tmpArr[i].type, tmpArr[i].listener, cap);\n }\n for (var p:int = 0; p &lt; tmpArr.length; p++) {\n objArr.splice(p);\n }\n\n if (tmpArr.length == 0) {\n delete objDict[o]\n }\n }else {\n trace(\"_______object has no listeners\");\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3810384, "author": "M.Raju", "author_id": 460280, "author_profile": "https://Stackoverflow.com/users/460280", "pm_score": 0, "selected": false, "text": "<pre><code>private function callFunction(function:Function):void\n{\n checkObject();\n obj.addEventListener(MouseEvent.CLICK,function);\n}\n\nprivate function checkObject():void\n{\n if(obj.hasEventListener(MouseEvent.CLICK))\n {\n //here remove that objects\n }\n}\n</code></pre>\n" }, { "answer_id": 3852189, "author": "Daniel Szmulewicz", "author_id": 465458, "author_profile": "https://Stackoverflow.com/users/465458", "pm_score": 0, "selected": false, "text": "<p>The following doesn't address the fundamental issue of removing unknown event listeners, but if what you need is disabling all mouse related events, including unknown ones, just use: \nmouseEnabled=false on your event target.</p>\n\n<p>More good stuff here:\n<a href=\"http://www.thoughtprocessinteractive.com/blog/the-power-and-genius-of-mousechildren-and-mouseenabled\" rel=\"nofollow\">http://www.thoughtprocessinteractive.com/blog/the-power-and-genius-of-mousechildren-and-mouseenabled</a></p>\n" }, { "answer_id": 7102944, "author": "K2xL", "author_id": 732539, "author_profile": "https://Stackoverflow.com/users/732539", "pm_score": 0, "selected": false, "text": "<p>K2xL EventManager Class\n<a href=\"http://k2xl.com/wordpress/2008/07/02/as3-eventmanager-class-removealllisteners/\" rel=\"nofollow\">http://k2xl.com/wordpress/2008/07/02/as3-eventmanager-class-removealllisteners/</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time. ``` public function registerButtonCallback(function:Function):void { clearButtonCallback(); button.addEventListener(MouseEvent.CLICK, function, false, 0, true); } public function clearButtonCallback():void { if (button.hasEventListener(MouseEvent.CLICK) == true) { // do something to remove that listener } } ``` I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice. Suggestions?
I am presuming that you want only one callback function at any given time. If that's teh case then why not have a single callback function associated with the click event on the button which itself called a function and have that function be settable... ``` <mx:Button click="doCallback()" .../> public var onClickFunction:Function = null; private function doCallback():void { if (onClickFunction != null) { onClickFunction(); // optionally you can pass some parameters in here if you match the signature of your callback } } ``` A consumer of your control which houses your button would set the onClickFunction with the appropriate function. In fact you could set it as often as you liked. If you wanted to go one step further you could subclass the AS3 Button class and wrap all of this inside it.
184,108
<p>I have a very simple TCP server written in C. It runs indefinitely, waiting for connections. On Windows, I use <code>select</code> to check for activity on the socket, and if there isn't any, I have the following code to allow me to quit by hitting 'q' on the keyboard:</p> <pre><code>if( kbhit() ) { char c = getch(); if( c == 'q' ) break; } </code></pre> <p>This doesn't work on unix, since <code>kbhit</code> doesn't exist and <code>getch</code> works differently. I found some <a href="http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/011/1138/1138l2.html" rel="nofollow noreferrer">sample code</a> that uses <code>tcsetattr</code> to change the terminal settings and allow character-by-character input. After calling the init function, I open /dev/stdin (with <code>O_NONBLOCK</code>) and read a character, but <code>read( f, &amp;c, 1 )</code> blocks until a character is hit.</p> <p>I suppose I could spawn a separate thread and have <em>it</em> wait indefinitely and then signal the first thread if the user hits 'q', but that seems a little heavy-handed. Surely there's an easier way?</p>
[ { "answer_id": 184152, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 4, "selected": true, "text": "<p>Add stdin to your list of select handles, and if it has data, call read to read one character from it.</p>\n" }, { "answer_id": 184346, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Rather, add \"f\" from your </p>\n\n<pre><code>read( f, &amp;c, 1 )\n</code></pre>\n\n<p>to select call. When f is ready for read, a character has been pressed, and read() will not block.</p>\n" }, { "answer_id": 212920, "author": "mpez0", "author_id": 27898, "author_profile": "https://Stackoverflow.com/users/27898", "pm_score": 1, "selected": false, "text": "<p>In Unix, whether on the system console or in an X terminal window, keyboard I/O goes through a virtual terminal. Device /dev/tty is the usual way, these days, of accessing a process's controlling terminal. Device manipulations other than open/close/read/write are all handled by the ioctl(2) system call for that specific device. The general idea of what you want to do is</p>\n\n<p>Open the controlling terminal (which may or may not be stdin)</p>\n\n<p>Change the operating mode on that terminal to return without waiting for a full line of input (which is the normal default)</p>\n\n<p>Continue with the rest of your program, knowing that reads from that terminal (which might be stdin) may return partial lines or even zero characters without it being an error or termination condition.</p>\n\n<hr>\n\n<p>A detailed answer on how to do the second step is found at the <a href=\"http://c-faq.com/osdep/cbreak.html\" rel=\"nofollow noreferrer\">C-programming faq</a>. They also point out that this is an OS question, not a language question. They provide nine possibilities, but the three major ones relevant to this question are</p>\n\n<ol>\n<li>Use the curses(3) library</li>\n<li>Old BSD style systems, use sgttyb to set CBREAK or RAW</li>\n<li>Posix or old System V style systems, use TCGETAW/TCSETAW to set c_cc[VMIN] to 1 and c_cc[VTIME] to 0.</li>\n</ol>\n\n<p>Following a couple of references in the C FAQ could lead to to <a href=\"http://c-faq.com/osdep/kbhit.txt\" rel=\"nofollow noreferrer\">this page of kbhit code fragments</a>.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821/" ]
I have a very simple TCP server written in C. It runs indefinitely, waiting for connections. On Windows, I use `select` to check for activity on the socket, and if there isn't any, I have the following code to allow me to quit by hitting 'q' on the keyboard: ``` if( kbhit() ) { char c = getch(); if( c == 'q' ) break; } ``` This doesn't work on unix, since `kbhit` doesn't exist and `getch` works differently. I found some [sample code](http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/011/1138/1138l2.html) that uses `tcsetattr` to change the terminal settings and allow character-by-character input. After calling the init function, I open /dev/stdin (with `O_NONBLOCK`) and read a character, but `read( f, &c, 1 )` blocks until a character is hit. I suppose I could spawn a separate thread and have *it* wait indefinitely and then signal the first thread if the user hits 'q', but that seems a little heavy-handed. Surely there's an easier way?
Add stdin to your list of select handles, and if it has data, call read to read one character from it.
184,132
<p>I need some help from the shell-script gurus out there.</p> <p>I have a .txt file (log) that traces the IP addresses of clients on several lines, in a format similar to this one:</p> <pre><code>Line1 - Client IP [192.168.0.1] Other data Line2 - Client IP [192.168.0.2] Other data Line3 - Client IP [192.168.0.3] Other data Line4 - Client IP [192.168.0.2] Other data Line5 - Client IP [192.168.0.1] Other data ... </code></pre> <p>I need to create script that:</p> <ul> <li>extracts the IP addresses from this file</li> <li>groups the IP addresses (the same IP address is reported only once)</li> <li>outputs a file with the resulting IP addresses</li> </ul> <p>For the previous example, the resulting file would be:</p> <pre><code>192.168.0.1 192.168.0.2 192.168.0.3 </code></pre> <p>I am on the Windows OS, but I can use tools like <a href="http://www.cygwin.com/" rel="nofollow noreferrer">Cygwin</a> or <a href="http://unxutils.sourceforge.net/" rel="nofollow noreferrer">Unix Tools</a> (that provide Unix-like commands as grep, sort, etc. under Windows).</p> <p>A solution without scripting could be good as well.</p> <p>Thanks in advance for your help.</p>
[ { "answer_id": 184154, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 2, "selected": false, "text": "<pre><code> cat yourfile.txt | sed 's/*\\[//g' | sed 's/\\]*//g' | sort | uniq &gt; newfile.txt\n</code></pre>\n\n<p>Escapes may be unnecessary for the brackets. I don't remember. These tools <em>should</em> all be available on Cygwin.</p>\n" }, { "answer_id": 184165, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "<p>Here is a short sed script that extracts the part between square brackets, then <code>sort -u</code> removes duplicates:</p>\n\n<pre><code>sed -e 's/^.*\\[\\(.*\\)\\].*$/\\1/g' &lt; inputfile | sort -u\n</code></pre>\n" }, { "answer_id": 184273, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 4, "selected": true, "text": "<p>In PowerShell:</p>\n\n<p>The Verbose Way - </p>\n\n<pre><code>$regex = '(?&lt;IPAddress&gt;\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'\nget-content log.txt | where-object {if ($_ -match $regex){$matches.ipaddress}} | group-object -noelement\n</code></pre>\n\n<p>Shorter version</p>\n\n<pre><code>gc log.txt | % {if ($_ -match $regex){$matches.ipaddress}} | group -n\n</code></pre>\n" }, { "answer_id": 184275, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 1, "selected": false, "text": "<p>It's pretty hard to beat those sed scripts for conciseness. Okay, readability is a problem ... </p>\n\n<p>You could do a rather more verbose, and perhaps more readable version in VBScript using the Scripting.FileSystemObject for file access, using VBScript's regular expressions and the Dictionary object, as below.</p>\n\n<pre><code>Option Explicit\n\nDim oFSO\nDim oRgx\nDim oMatch\nDim oMatches\nDim oStream\nDim sLine\nDim oDict\nDim sIP\nDim aKeys\nDim sKey\n\nSet oFSO = CreateObject( \"Scripting.FileSystemObject\" )\nSet oDict = CreateObject( \"Scripting.Dictionary\" )\n\nSet oStream = oFSO.OpenTextFile( \"log.txt\", 1, False )\n\nSet oRgx = new regexp\noRgx.Pattern = \"\\[(.+?)\\]\"\noRgx.Global = True\n\nDo While Not oStream.AtEndOfStream\n sLine = oStream.ReadLine\n Set oMatches = oRgx.Execute(sLine)\n\n For Each omatch in omatches\n sIP = oMatch.SubMatches(0)\n\n If Not oDict.Exists( sIP ) Then\n oDict.Add sIp,1\n End If\n\n Next\n\nLoop\n\naKeys = oDict.Keys\n\nFor Each sKey in aKeys\n wscript.echo sKey\nNext\n</code></pre>\n" }, { "answer_id": 378821, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 0, "selected": false, "text": "<p>If you can use Cygwin, there is little point to needing to worry about a Windows scripting solution.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23034/" ]
I need some help from the shell-script gurus out there. I have a .txt file (log) that traces the IP addresses of clients on several lines, in a format similar to this one: ``` Line1 - Client IP [192.168.0.1] Other data Line2 - Client IP [192.168.0.2] Other data Line3 - Client IP [192.168.0.3] Other data Line4 - Client IP [192.168.0.2] Other data Line5 - Client IP [192.168.0.1] Other data ... ``` I need to create script that: * extracts the IP addresses from this file * groups the IP addresses (the same IP address is reported only once) * outputs a file with the resulting IP addresses For the previous example, the resulting file would be: ``` 192.168.0.1 192.168.0.2 192.168.0.3 ``` I am on the Windows OS, but I can use tools like [Cygwin](http://www.cygwin.com/) or [Unix Tools](http://unxutils.sourceforge.net/) (that provide Unix-like commands as grep, sort, etc. under Windows). A solution without scripting could be good as well. Thanks in advance for your help.
In PowerShell: The Verbose Way - ``` $regex = '(?<IPAddress>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' get-content log.txt | where-object {if ($_ -match $regex){$matches.ipaddress}} | group-object -noelement ``` Shorter version ``` gc log.txt | % {if ($_ -match $regex){$matches.ipaddress}} | group -n ```
184,147
<p>Is there any advantage of using</p> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html" rel="noreferrer"><strong>java.util.concurrent.CountdownLatch</strong></a> </p> <p>instead of</p> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html" rel="noreferrer"><strong>java.util.concurrent.Semaphore</strong></a>? </p> <p>As far as I can tell the following fragments are almost equivalent:</p> <p><strong>1. Semaphore</strong></p> <pre><code>final Semaphore sem = new Semaphore(0); for (int i = 0; i &lt; num_threads; ++ i) { Thread t = new Thread() { public void run() { try { doStuff(); } finally { sem.release(); } } }; t.start(); } sem.acquire(num_threads); </code></pre> <p><strong>2: CountDownLatch</strong></p> <pre><code>final CountDownLatch latch = new CountDownLatch(num_threads); for (int i = 0; i &lt; num_threads; ++ i) { Thread t = new Thread() { public void run() { try { doStuff(); } finally { latch.countDown(); } } }; t.start(); } latch.await(); </code></pre> <p>Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)</p> <p>So in what situation might the latch be preferable?</p>
[ { "answer_id": 184441, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 0, "selected": false, "text": "<p><code>CountdownLatch</code> makes threads wait on the <code>await()</code> method, until such a time as the count has reached zero. So maybe you want all your threads to wait until 3 invocations of something, then all the threads can go. A <code>Latch</code> generally can not be reset.</p>\n\n<p>A <code>Semaphore</code> allows threads to retrieve permits, which prevents too many threads from executing at once, blocking if it cannot get the permit(s) it requires to proceed. Permits can be returned to a <code>Semaphore</code> allowing the other waiting threads to proceed.</p>\n" }, { "answer_id": 184461, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>Looking at the freely available source, there is no magic in the implementation of the two classes, so their performance should be much the same. Choose the one that makes your intent more obvious.</p>\n" }, { "answer_id": 184566, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 8, "selected": true, "text": "<p><code>CountDownLatch</code> is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on <code>await()</code> that would all start simultaneously when the countown reached zero.</p>\n<pre><code>final CountDownLatch countdown = new CountDownLatch(1);\n\nfor (int i = 0; i &lt; 10; ++ i) {\n Thread racecar = new Thread() { \n public void run() {\n countdown.await(); //all threads waiting\n System.out.println(&quot;Vroom!&quot;);\n }\n };\n racecar.start();\n}\nSystem.out.println(&quot;Go&quot;);\ncountdown.countDown(); //all threads start now!\n</code></pre>\n<p>You could also use this as an MPI-style &quot;barrier&quot; that causes all threads to wait for other threads to catch up to a certain point before proceeding.</p>\n<pre><code>final CountDownLatch countdown = new CountDownLatch(num_thread);\n\nfor (int i = 0; i &lt; num_thread; ++ i) {\n Thread t= new Thread() { \n public void run() {\n doSomething();\n countdown.countDown();\n System.out.printf(&quot;Waiting on %d other threads.&quot;,countdown.getCount());\n countdown.await(); //waits until everyone reaches this point\n finish();\n }\n };\n t.start();\n}\n</code></pre>\n<p>That all said, the <code>CountDownLatch</code> can safely be used in the manner you've shown in your example.</p>\n" }, { "answer_id": 184800, "author": "mtruesdell", "author_id": 6479, "author_profile": "https://Stackoverflow.com/users/6479", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html\" rel=\"noreferrer\">CountDownLatch</a> is used to start a series of threads and then wait until all of them are complete (or until they call <code>countDown()</code> a given number of times.</p>\n\n<p>Semaphore is used to control the number of concurrent threads that are using a resource. That resource can be something like a file, or could be the cpu by limiting the number of threads executing. The count on a Semaphore can go up and down as different threads call <code>acquire()</code> and <code>release()</code>.</p>\n\n<p>In your example, you're essentially using Semaphore as a sort of Count<em>UP</em>Latch. Given that your intent is to wait on all threads finishing, using the <code>CountdownLatch</code> makes your intention clearer.</p>\n" }, { "answer_id": 18005588, "author": "Raj Srinivas", "author_id": 2643906, "author_profile": "https://Stackoverflow.com/users/2643906", "pm_score": 3, "selected": false, "text": "<p>Say you walked in to golf pro shop, hoping to find a foursome,</p>\n\n<p>When you stand in line to get a tee time from one of the pro shop attendants, essentially you called <code>proshopVendorSemaphore.acquire()</code>, once you get a tee time, you called <code>proshopVendorSemaphore.release()</code>.Note: any of the free attendants can service you, i.e. shared resource.</p>\n\n<p>Now you walk up to starter, he starts a <code>CountDownLatch(4)</code> and calls <code>await()</code> to wait for others, for your part you called checked-in i.e. <code>CountDownLatch</code>.<code>countDown()</code> and so does rest of the foursome. When all arrive, starter gives go ahead(<code>await()</code> call returns)</p>\n\n<p>Now, after nine holes when each of you take a break, hypothetically lets involve starter again, he uses a 'new' <code>CountDownLatch(4)</code> to tee off Hole 10, same wait/sync as Hole 1.</p>\n\n<p>However, if the starter used a <code>CyclicBarrier</code> to begin with, he could have reset the same instance in Hole 10 instead of a second latch, which use &amp; throw.</p>\n" }, { "answer_id": 33624654, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 5, "selected": false, "text": "<p><em>Short summary:</em></p>\n<ol>\n<li><p><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html\" rel=\"noreferrer\"><code>Semaphore</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html\" rel=\"noreferrer\"><code>CountDownLatch</code></a> serves different purpose.</p>\n</li>\n<li><p>Use <code>Semaphore</code> to control thread access to resource.</p>\n</li>\n<li><p>Use <code>CountDownLatch</code> to wait for completion of all threads</p>\n</li>\n</ol>\n<p><code>Semaphore</code> definition from Javadocs:</p>\n<blockquote>\n<p>A <code>Semaphore</code> maintains a set of permits. Each <code>acquire()</code> blocks if necessary until a <em>permit</em> is available, and then takes it. Each <code>release()</code> adds a permit, potentially releasing a blocking acquirer.</p>\n</blockquote>\n<p>However, no actual permit objects are used; the <code>Semaphore</code> just keeps a count of the number available and acts accordingly.</p>\n<p><em>How does it work?</em></p>\n<p>Semaphores are used to control the number of concurrent threads that are using a resource.That resource can be something like a shared data, or a block of code (<strong>critical section</strong>) or any file.</p>\n<p>The count on a <code>Semaphore</code> can go up and down as different threads call <code>acquire()</code> and <code>release()</code>. But at any point of time, you can't have more number of threads greater than Semaphore count.</p>\n<p><em><code>Semaphore</code> Use cases:</em></p>\n<ol>\n<li>Limiting concurrent access to disk (as performance degrades due to\ncompeting disk seeks)</li>\n<li>Thread creation limiting</li>\n<li>JDBC connection pooling / limiting</li>\n<li>Network connection throttling</li>\n<li>Throttling CPU or memory intensive tasks</li>\n</ol>\n<p>Have a look at this <a href=\"http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial-semaphores.html\" rel=\"noreferrer\">article</a> for semaphore uses.</p>\n<p><code>CountDownLatch</code> definition from Javadocs:</p>\n<blockquote>\n<p>A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.</p>\n</blockquote>\n<p><em>How does it work?</em></p>\n<p><code>CountDownLatch</code> works by having a counter initialized with number of threads, which is decremented each time a thread complete its execution. When count reaches to zero, it means all threads have completed their execution, and thread waiting on latch resume the execution.</p>\n<p><em><code>CountDownLatch</code> Use cases:</em></p>\n<ol>\n<li>Achieving Maximum Parallelism: Sometimes we want to start a number of\nthreads at the same time to achieve maximum parallelism</li>\n<li>Wait N threads to completes before start execution</li>\n<li>Deadlock detection.</li>\n</ol>\n<p>Have a look at this <a href=\"http://howtodoinjava.com/2013/07/18/when-to-use-countdownlatch-java-concurrency-example-tutorial/\" rel=\"noreferrer\">article</a> to understand <code>CountDownLatch</code> concepts clearly.</p>\n<p>Have a look at <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html\" rel=\"noreferrer\">Fork Join Pool</a> at this <a href=\"http://tutorials.jenkov.com/java-util-concurrent/java-fork-and-join-forkjoinpool.html\" rel=\"noreferrer\">article</a> too. It has some similarities to <code>CountDownLatch</code>.</p>\n" }, { "answer_id": 68801949, "author": "the_code", "author_id": 7424998, "author_profile": "https://Stackoverflow.com/users/7424998", "pm_score": 0, "selected": false, "text": "<p>Semaphore controls access to a shared resource through the use of a counter. If the counter is greater than zero, then access is allowed. If it is zero, then access is denied. Counter is counting the permits that allow access to shared resource. Thus to access the resource, a thread must be granted a permit from the semaphore.</p>\n<p>CountDownlatch make a thread to wait until one or more events have occured. A countDownLatch is initially created with a count of the number of events that much occur before the latch is released. Each time an event happens, the count is decremented.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12048/" ]
Is there any advantage of using [**java.util.concurrent.CountdownLatch**](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html) instead of [**java.util.concurrent.Semaphore**](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html)? As far as I can tell the following fragments are almost equivalent: **1. Semaphore** ``` final Semaphore sem = new Semaphore(0); for (int i = 0; i < num_threads; ++ i) { Thread t = new Thread() { public void run() { try { doStuff(); } finally { sem.release(); } } }; t.start(); } sem.acquire(num_threads); ``` **2: CountDownLatch** ``` final CountDownLatch latch = new CountDownLatch(num_threads); for (int i = 0; i < num_threads; ++ i) { Thread t = new Thread() { public void run() { try { doStuff(); } finally { latch.countDown(); } } }; t.start(); } latch.await(); ``` Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.) So in what situation might the latch be preferable?
`CountDownLatch` is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on `await()` that would all start simultaneously when the countown reached zero. ``` final CountDownLatch countdown = new CountDownLatch(1); for (int i = 0; i < 10; ++ i) { Thread racecar = new Thread() { public void run() { countdown.await(); //all threads waiting System.out.println("Vroom!"); } }; racecar.start(); } System.out.println("Go"); countdown.countDown(); //all threads start now! ``` You could also use this as an MPI-style "barrier" that causes all threads to wait for other threads to catch up to a certain point before proceeding. ``` final CountDownLatch countdown = new CountDownLatch(num_thread); for (int i = 0; i < num_thread; ++ i) { Thread t= new Thread() { public void run() { doSomething(); countdown.countDown(); System.out.printf("Waiting on %d other threads.",countdown.getCount()); countdown.await(); //waits until everyone reaches this point finish(); } }; t.start(); } ``` That all said, the `CountDownLatch` can safely be used in the manner you've shown in your example.
184,162
<p>I'm trying to find the best way to use 'top' as semi-permanent instrumentation in the development of a box running embedded Linux. (The instrumentation will be removed from the final-test and production releases.)</p> <p>My first pass is to simply add this to init.d:</p> <pre><code>top -b -d 15 &gt;/tmp/toploop.out &amp; </code></pre> <p>This runs top in "batch" mode every 15 seconds. Let's assume that /tmp has plenty of space…</p> <p>Questions: </p> <ol> <li>Is 15 seconds a good value to choose for general-purpose monitoring?</li> <li>Other than disk space, how seriously is this perturbing the state of the system?</li> <li>What other (perhaps better) tools could be used like this?</li> </ol>
[ { "answer_id": 184183, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "<p>You might find that vmstat and iostat with a delay and no repeat counter is a better option.</p>\n" }, { "answer_id": 184190, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 1, "selected": false, "text": "<p>I suspect 15 seconds would be more than adequate unless you actually want to watch what's happening in real time, but that doesn't appear to be the case here.</p>\n\n<p>As far as load, on an idling PIII 900Mhz w/ 768MB of RAM running Ubuntu (not sure which version, but not more than a year old) I have top updating every 0.5 seconds and it's about 2% CPU utilization. At 15s updates, I'm seeing 0.1% CPU utilization.</p>\n\n<p>depending upon what exactly you want, you could use the output of uptime, free, and ps to get most, if not all, of top's information.</p>\n" }, { "answer_id": 184230, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 2, "selected": false, "text": "<p>We use <a href=\"http://pagesperso-orange.fr/sebastien.godard/documentation.html\" rel=\"nofollow noreferrer\">sysstat</a> to monitor things like this. </p>\n" }, { "answer_id": 184300, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 3, "selected": false, "text": "<p>Look at <a href=\"http://collectd.org/\" rel=\"noreferrer\">collectd</a>. It's a very light weight system monitoring framework coded for performance.</p>\n" }, { "answer_id": 184465, "author": "terson", "author_id": 22974, "author_profile": "https://Stackoverflow.com/users/22974", "pm_score": 1, "selected": false, "text": "<p>If you are looking for overall load, uptime is probably sufficient. However, if you want specific information about processes, you are adventurous, and have the /proc filessystem enabled, you may want to write your own tools. The primary benefit in this environment is that you can focus on exactly what you want and minimize the load introduced to the system.</p>\n\n<p>The proc file system gives your application read access to the kernel memory that keeps track of many of the interesting variables. Reading from /proc is one of the lightest ways to get this information. Additionally, you may be able to get more information than provided by top. I've done this in the past to get amount of time spent in user and system by this process. Additionally, you can use this to get information about the number of file descriptors open by the process. You might also use this to get detailed information about how the network system is working.</p>\n\n<p>Much of this information is pre-processed by other applications which can be used if you get the information you need. However, it is rather straight-forward to read the raw information. Do a <code>man proc</code> for more information.</p>\n" }, { "answer_id": 184870, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 1, "selected": false, "text": "<p>Pity you haven't said what you are monitoring for.</p>\n\n<ol>\n<li>You should decide whether 15 seconds is ok or not. Feel free to drop it way lower if you wish (and have a fast HDD)</li>\n<li>No worries unless you are running a soft real-time system</li>\n<li>Have a look at tools suggested in other answers. I'll add another sugestion: \"iotop\", for answering a \"who is thrashing the HDD\" questions.</li>\n</ol>\n" }, { "answer_id": 185671, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 1, "selected": false, "text": "<p>At work for system monitoring during stress tests we use a tool called <a href=\"http://www.ibm.com/developerworks/aix/library/au-analyze_aix/\" rel=\"nofollow noreferrer\">nmon</a>.</p>\n\n<p>What I love about nmon is it has the ability to export to XLS and generate beautiful graphs for you.</p>\n\n<p>It generates statistics for:</p>\n\n<ul>\n<li>Memory Usage</li>\n<li>CPU Usage</li>\n<li>Network Usage</li>\n<li>Disk I/O</li>\n</ul>\n\n<p>Good luck :)</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14028/" ]
I'm trying to find the best way to use 'top' as semi-permanent instrumentation in the development of a box running embedded Linux. (The instrumentation will be removed from the final-test and production releases.) My first pass is to simply add this to init.d: ``` top -b -d 15 >/tmp/toploop.out & ``` This runs top in "batch" mode every 15 seconds. Let's assume that /tmp has plenty of space… Questions: 1. Is 15 seconds a good value to choose for general-purpose monitoring? 2. Other than disk space, how seriously is this perturbing the state of the system? 3. What other (perhaps better) tools could be used like this?
Look at [collectd](http://collectd.org/). It's a very light weight system monitoring framework coded for performance.
184,178
<p>I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field.</p> <p>Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it.</p> <p>Net::HTTP doesn't look like the best idea. <a href="http://curb.rubyforge.org/" rel="noreferrer">curb</a> is looking good.</p>
[ { "answer_id": 184303, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 3, "selected": false, "text": "<p>Ok, here's a simple example using curb.</p>\n\n<pre><code>require 'yaml'\nrequire 'curb'\n\n# prepare post data\npost_data = fields_hash.map { |k, v| Curl::PostField.content(k, v.to_s) }\npost_data &lt;&lt; Curl::PostField.file('file', '/path/to/file'), \n\n# post\nc = Curl::Easy.new('http://localhost:3000/foo')\nc.multipart_form_post = true\nc.http_post(post_data)\n\n# print response\ny [c.response_code, c.body_str]\n</code></pre>\n" }, { "answer_id": 213276, "author": "Cody Brimhall", "author_id": 18388, "author_profile": "https://Stackoverflow.com/users/18388", "pm_score": 5, "selected": false, "text": "<p><code>curb</code> looks like a great solution, but in case it doesn't meet your needs, you <em>can</em> do it with <code>Net::HTTP</code>. A multipart form post is just a carefully-formatted string with some extra headers. It seems like every Ruby programmer who needs to do multipart posts ends up writing their own little library for it, which makes me wonder why this functionality isn't built-in. Maybe it is... Anyway, for your reading pleasure, I'll go ahead and give my solution here. This code is based off of examples I found on a couple of blogs, but I regret that I can't find the links anymore. So I guess I just have to take all the credit for myself...</p>\n\n<p>The module I wrote for this contains one public class, for generating the form data and headers out of a hash of <code>String</code> and <code>File</code> objects. So for example, if you wanted to post a form with a string parameter named \"title\" and a file parameter named \"document\", you would do the following:</p>\n\n<pre><code>#prepare the query\ndata, headers = Multipart::Post.prepare_query(\"title\" =&gt; my_string, \"document\" =&gt; my_file)\n</code></pre>\n\n<p>Then you just do a normal <code>POST</code> with <code>Net::HTTP</code>:</p>\n\n<pre><code>http = Net::HTTP.new(upload_uri.host, upload_uri.port)\nres = http.start {|con| con.post(upload_uri.path, data, headers) }\n</code></pre>\n\n<p>Or however else you want to do the <code>POST</code>. The point is that <code>Multipart</code> returns the data and headers that you need to send. And that's it! Simple, right? Here's the code for the Multipart module (you need the <code>mime-types</code> gem):</p>\n\n<pre><code># Takes a hash of string and file parameters and returns a string of text\n# formatted to be sent as a multipart form post.\n#\n# Author:: Cody Brimhall &lt;mailto:[email protected]&gt;\n# Created:: 22 Feb 2008\n# License:: Distributed under the terms of the WTFPL (http://www.wtfpl.net/txt/copying/)\n\nrequire 'rubygems'\nrequire 'mime/types'\nrequire 'cgi'\n\n\nmodule Multipart\n VERSION = \"1.0.0\"\n\n # Formats a given hash as a multipart form post\n # If a hash value responds to :string or :read messages, then it is\n # interpreted as a file and processed accordingly; otherwise, it is assumed\n # to be a string\n class Post\n # We have to pretend we're a web browser...\n USERAGENT = \"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/523.10.6 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6\"\n BOUNDARY = \"0123456789ABLEWASIEREISAWELBA9876543210\"\n CONTENT_TYPE = \"multipart/form-data; boundary=#{ BOUNDARY }\"\n HEADER = { \"Content-Type\" =&gt; CONTENT_TYPE, \"User-Agent\" =&gt; USERAGENT }\n\n def self.prepare_query(params)\n fp = []\n\n params.each do |k, v|\n # Are we trying to make a file parameter?\n if v.respond_to?(:path) and v.respond_to?(:read) then\n fp.push(FileParam.new(k, v.path, v.read))\n # We must be trying to make a regular parameter\n else\n fp.push(StringParam.new(k, v))\n end\n end\n\n # Assemble the request body using the special multipart format\n query = fp.collect {|p| \"--\" + BOUNDARY + \"\\r\\n\" + p.to_multipart }.join(\"\") + \"--\" + BOUNDARY + \"--\"\n return query, HEADER\n end\n end\n\n private\n\n # Formats a basic string key/value pair for inclusion with a multipart post\n class StringParam\n attr_accessor :k, :v\n\n def initialize(k, v)\n @k = k\n @v = v\n end\n\n def to_multipart\n return \"Content-Disposition: form-data; name=\\\"#{CGI::escape(k)}\\\"\\r\\n\\r\\n#{v}\\r\\n\"\n end\n end\n\n # Formats the contents of a file or string for inclusion with a multipart\n # form post\n class FileParam\n attr_accessor :k, :filename, :content\n\n def initialize(k, filename, content)\n @k = k\n @filename = filename\n @content = content\n end\n\n def to_multipart\n # If we can tell the possible mime-type from the filename, use the\n # first in the list; otherwise, use \"application/octet-stream\"\n mime_type = MIME::Types.type_for(filename)[0] || MIME::Types[\"application/octet-stream\"][0]\n return \"Content-Disposition: form-data; name=\\\"#{CGI::escape(k)}\\\"; filename=\\\"#{ filename }\\\"\\r\\n\" +\n \"Content-Type: #{ mime_type.simplified }\\r\\n\\r\\n#{ content }\\r\\n\"\n end\n end\nend\n</code></pre>\n" }, { "answer_id": 316338, "author": "Pedro", "author_id": 16882, "author_profile": "https://Stackoverflow.com/users/16882", "pm_score": 8, "selected": true, "text": "<p>I like <a href=\"https://github.com/rest-client/rest-client\" rel=\"noreferrer\">RestClient</a>. It encapsulates net/http with cool features like multipart form data:</p>\n\n<pre><code>require 'rest_client'\nRestClient.post('http://localhost:3000/foo', \n :name_of_file_param =&gt; File.new('/path/to/file'))\n</code></pre>\n\n<p>It also supports streaming.</p>\n\n<p><code>gem install rest-client</code> will get you started.</p>\n" }, { "answer_id": 392903, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Well the solution with NetHttp has a drawback that is when posting big files it loads the whole file into memory first.</p>\n\n<p>After playing a bit with it I came up with the following solution:</p>\n\n<pre><code>class Multipart\n\n def initialize( file_names )\n @file_names = file_names\n end\n\n def post( to_url )\n boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'\n\n parts = []\n streams = []\n @file_names.each do |param_name, filepath|\n pos = filepath.rindex('/')\n filename = filepath[pos + 1, filepath.length - pos]\n parts &lt;&lt; StringPart.new ( \"--\" + boundary + \"\\r\\n\" +\n \"Content-Disposition: form-data; name=\\\"\" + param_name.to_s + \"\\\"; filename=\\\"\" + filename + \"\\\"\\r\\n\" +\n \"Content-Type: video/x-msvideo\\r\\n\\r\\n\")\n stream = File.open(filepath, \"rb\")\n streams &lt;&lt; stream\n parts &lt;&lt; StreamPart.new (stream, File.size(filepath))\n end\n parts &lt;&lt; StringPart.new ( \"\\r\\n--\" + boundary + \"--\\r\\n\" )\n\n post_stream = MultipartStream.new( parts )\n\n url = URI.parse( to_url )\n req = Net::HTTP::Post.new(url.path)\n req.content_length = post_stream.size\n req.content_type = 'multipart/form-data; boundary=' + boundary\n req.body_stream = post_stream\n res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }\n\n streams.each do |stream|\n stream.close();\n end\n\n res\n end\n\nend\n\nclass StreamPart\n def initialize( stream, size )\n @stream, @size = stream, size\n end\n\n def size\n @size\n end\n\n def read ( offset, how_much )\n @stream.read ( how_much )\n end\nend\n\nclass StringPart\n def initialize ( str )\n @str = str\n end\n\n def size\n @str.length\n end\n\n def read ( offset, how_much )\n @str[offset, how_much]\n end\nend\n\nclass MultipartStream\n def initialize( parts )\n @parts = parts\n @part_no = 0;\n @part_offset = 0;\n end\n\n def size\n total = 0\n @parts.each do |part|\n total += part.size\n end\n total\n end\n\n def read ( how_much )\n\n if @part_no &gt;= @parts.size\n return nil;\n end\n\n how_much_current_part = @parts[@part_no].size - @part_offset\n\n how_much_current_part = if how_much_current_part &gt; how_much\n how_much\n else\n how_much_current_part\n end\n\n how_much_next_part = how_much - how_much_current_part\n\n current_part = @parts[@part_no].read(@part_offset, how_much_current_part )\n\n if how_much_next_part &gt; 0\n @part_no += 1\n @part_offset = 0\n next_part = read ( how_much_next_part )\n current_part + if next_part\n next_part\n else\n ''\n end\n else\n @part_offset += how_much_current_part\n current_part\n end\n end\nend\n</code></pre>\n" }, { "answer_id": 393747, "author": "Alex", "author_id": 16974, "author_profile": "https://Stackoverflow.com/users/16974", "pm_score": 4, "selected": false, "text": "<p>Here is my solution after trying other ones available on this post, I'm using it to upload photo on TwitPic:</p>\n\n<pre><code> def upload(photo)\n `curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`\n end\n</code></pre>\n" }, { "answer_id": 517382, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I had the same problem (need to post to jboss web server). Curb works fine for me, except that it caused ruby to crash (ruby 1.8.7 on ubuntu 8.10) when I use session variables in the code.</p>\n\n<p>I dig into the rest-client docs, could not find indication of multipart support. I tried the rest-client examples above but jboss said the http post is not multipart.</p>\n" }, { "answer_id": 781487, "author": "Jan Berkel", "author_id": 60606, "author_profile": "https://Stackoverflow.com/users/60606", "pm_score": 1, "selected": false, "text": "<p>there's also nick sieger's <a href=\"http://github.com/nicksieger/multipart-post\" rel=\"nofollow noreferrer\">multipart-post</a> to add to the long list of possible solutions. </p>\n" }, { "answer_id": 2068217, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>restclient did not work for me until I overrode create_file_field in RestClient::Payload::Multipart.</p>\n\n<p>It was creating a <strong>'Content-Disposition: multipart/form-data'</strong> in each part where it should be <strong>‘Content-Disposition: form-data’</strong>.</p>\n\n<p><a href=\"http://www.ietf.org/rfc/rfc2388.txt\" rel=\"nofollow noreferrer\">http://www.ietf.org/rfc/rfc2388.txt</a></p>\n\n<p>My fork is here if you need it: [email protected]:kcrawford/rest-client.git</p>\n" }, { "answer_id": 2603805, "author": "eric", "author_id": 312322, "author_profile": "https://Stackoverflow.com/users/312322", "pm_score": 5, "selected": false, "text": "<p>I can't say enough good things about Nick Sieger's multipart-post library.</p>\n\n<p>It adds support for multipart posting directly to Net::HTTP, removing your need to manually worry about boundaries or big libraries that may have different goals than your own.</p>\n\n<p>Here is a little example on how to use it from the <a href=\"http://github.com/nicksieger/multipart-post/blob/master/README.txt\" rel=\"noreferrer\">README</a>:</p>\n\n<pre><code>require 'net/http/post/multipart'\n\nurl = URI.parse('http://www.example.com/upload')\nFile.open(\"./image.jpg\") do |jpg|\n req = Net::HTTP::Post::Multipart.new url.path,\n \"file\" =&gt; UploadIO.new(jpg, \"image/jpeg\", \"image.jpg\")\n res = Net::HTTP.start(url.host, url.port) do |http|\n http.request(req)\n end\nend\n</code></pre>\n\n<p>You can check out the library here:\n<a href=\"http://github.com/nicksieger/multipart-post\" rel=\"noreferrer\">http://github.com/nicksieger/multipart-post</a></p>\n\n<p>or install it with:</p>\n\n<pre><code>$ sudo gem install multipart-post\n</code></pre>\n\n<p>If you're connecting via SSL you need to start the connection like this:</p>\n\n<pre><code>n = Net::HTTP.new(url.host, url.port) \nn.use_ssl = true\n# for debugging dev server\n#n.verify_mode = OpenSSL::SSL::VERIFY_NONE\nres = n.start do |http|\n</code></pre>\n" }, { "answer_id": 41176937, "author": "Feuda", "author_id": 642616, "author_profile": "https://Stackoverflow.com/users/642616", "pm_score": 0, "selected": false, "text": "<p>The multipart-post gem works pretty well with Rails 4 Net::HTTP, no other special gem</p>\n\n<pre><code>def model_params\n require_params = params.require(:model).permit(:param_one, :param_two, :param_three, :avatar)\n require_params[:avatar] = model_params[:avatar].present? ? UploadIO.new(model_params[:avatar].tempfile, model_params[:avatar].content_type, model_params[:avatar].original_filename) : nil\n require_params\nend\n\nrequire 'net/http/post/multipart'\n\nurl = URI.parse('http://www.example.com/upload')\nNet::HTTP.start(url.host, url.port) do |http|\n req = Net::HTTP::Post::Multipart.new(url, model_params)\n key = \"authorization_key\"\n req.add_field(\"Authorization\", key) #add to Headers\n http.use_ssl = (url.scheme == \"https\")\n http.request(req)\nend\n</code></pre>\n\n<p><a href=\"https://github.com/Feuda/multipart-post/tree/patch-1\" rel=\"nofollow noreferrer\">https://github.com/Feuda/multipart-post/tree/patch-1</a></p>\n" }, { "answer_id": 45976252, "author": "airmanx86", "author_id": 382979, "author_profile": "https://Stackoverflow.com/users/382979", "pm_score": 3, "selected": false, "text": "<p>Fast forward to 2017, <code>ruby</code> <code>stdlib</code> <code>net/http</code> has this built-in since 1.9.3</p>\n\n<blockquote>\n <p>Net::HTTPRequest#set_form): Added to support both application/x-www-form-urlencoded and multipart/form-data.</p>\n</blockquote>\n\n<p><a href=\"https://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTPHeader.html#method-i-set_form\" rel=\"noreferrer\">https://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTPHeader.html#method-i-set_form</a></p>\n\n<p>We can even use <code>IO</code> which does not support <code>:size</code> to stream the form data.</p>\n\n<p>Hoping that this answer can really help someone :)</p>\n\n<p>P.S. I only tested this in ruby 2.3.1</p>\n" }, { "answer_id": 46669328, "author": "Vova Rozhkov", "author_id": 1434854, "author_profile": "https://Stackoverflow.com/users/1434854", "pm_score": 5, "selected": false, "text": "<p>Another one using only standard libraries:</p>\n\n<pre><code>uri = URI('https://some.end.point/some/path')\nrequest = Net::HTTP::Post.new(uri)\nrequest['Authorization'] = 'If you need some headers'\nform_data = [['photos', photo.tempfile]] # or File.open() in case of local file\n\nrequest.set_form form_data, 'multipart/form-data'\nresponse = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| # pay attention to use_ssl if you need it\n http.request(request)\nend\n</code></pre>\n\n<p>Tried a lot of approaches but only this was worked for me.</p>\n" }, { "answer_id": 67033925, "author": "Vova Rozhkov", "author_id": 1434854, "author_profile": "https://Stackoverflow.com/users/1434854", "pm_score": 0, "selected": false, "text": "<p>Using <a href=\"https://github.com/httprb/http\" rel=\"nofollow noreferrer\">http.rb</a> gem:</p>\n<pre><code>HTTP.post(&quot;https://here-you-go.com/upload&quot;,\n form: {\n file: HTTP::FormData::File.new(file_path)\n })\n</code></pre>\n<p><a href=\"https://github.com/httprb/http/wiki/Passing-Parameters#file-uploads-via-form-data\" rel=\"nofollow noreferrer\">Details</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field. Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it. Net::HTTP doesn't look like the best idea. [curb](http://curb.rubyforge.org/) is looking good.
I like [RestClient](https://github.com/rest-client/rest-client). It encapsulates net/http with cool features like multipart form data: ``` require 'rest_client' RestClient.post('http://localhost:3000/foo', :name_of_file_param => File.new('/path/to/file')) ``` It also supports streaming. `gem install rest-client` will get you started.
184,187
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
[ { "answer_id": 184193, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 3, "selected": false, "text": "<p>Here's what I came up with:</p>\n\n<pre><code>import os\n\ndef CreateNewChangeList(description):\n \"Create a new changelist and returns the changelist number as a string\"\n p4in, p4out = os.popen2(\"p4 changelist -i\")\n p4in.write(\"change: new\\n\")\n p4in.write(\"description: \" + description)\n p4in.close()\n changelist = p4out.readline().split()[1]\n return changelist\n\ndef OpenFileForEdit(file, changelist = \"\"):\n \"Open a file for edit, if a changelist is passed in then open it in that list\"\n cmd = \"p4 edit \"\n if changelist:\n cmd += \" -c \" + changelist + \" \"\n ret = os.popen(cmd + file).readline().strip()\n if not ret.endswith(\"opened for edit\"):\n print \"Couldn't open\", file, \"for edit:\"\n print ret\n raise ValueError\n</code></pre>\n" }, { "answer_id": 184238, "author": "Nithin", "author_id": 15163, "author_profile": "https://Stackoverflow.com/users/15163", "pm_score": 2, "selected": false, "text": "<p>You may want to check out the P4Python module. It's available on the perforce site and it makes things very simple.</p>\n" }, { "answer_id": 184344, "author": "Troy J. Farrell", "author_id": 26244, "author_profile": "https://Stackoverflow.com/users/26244", "pm_score": 6, "selected": true, "text": "<p>Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:</p>\n\n<p><a href=\"http://www.perforce.com/perforce/loadsupp.html#api\" rel=\"noreferrer\">http://www.perforce.com/perforce/loadsupp.html#api</a></p>\n\n<p>You will find their documentation of the scripting API to be helpful:</p>\n\n<p><a href=\"http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf\" rel=\"noreferrer\">http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf</a></p>\n\n<p>Use of the Python API is quite similar to the command-line client:</p>\n\n<pre><code>PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.\nPortions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.\n&gt;&gt;&gt; import P4\n&gt;&gt;&gt; p4 = P4.P4()\n&gt;&gt;&gt; p4.connect() # connect to the default server, with the default clientspec\n&gt;&gt;&gt; desc = {\"Description\": \"My new changelist description\",\n... \"Change\": \"new\"\n... }\n&gt;&gt;&gt; p4.input = desc\n&gt;&gt;&gt; p4.run(\"changelist\", \"-i\")\n['Change 2579505 created.']\n&gt;&gt;&gt; \n</code></pre>\n\n<p>I'll verify it from the command line:</p>\n\n<pre><code>P:\\&gt;p4 changelist -o 2579505\n# A Perforce Change Specification.\n#\n# Change: The change number. 'new' on a new changelist.\n# Date: The date this specification was last modified.\n# Client: The client on which the changelist was created. Read-only.\n# User: The user who created the changelist.\n# Status: Either 'pending' or 'submitted'. Read-only.\n# Description: Comments about the changelist. Required.\n# Jobs: What opened jobs are to be closed by this changelist.\n# You may delete jobs from this list. (New changelists only.)\n# Files: What opened files from the default changelist are to be added\n# to this changelist. You may delete files from this list.\n# (New changelists only.)\n\nChange: 2579505\n\nDate: 2008/10/08 13:57:02\n\nClient: MYCOMPUTER-DT\n\nUser: myusername\n\nStatus: pending\n\nDescription:\n My new changelist description\n</code></pre>\n" }, { "answer_id": 256419, "author": "Syeberman", "author_id": 14576, "author_profile": "https://Stackoverflow.com/users/14576", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.perforce.com/perforce/loadsupp.html#api\" rel=\"nofollow noreferrer\">Perforce's P4 Python module</a> mentioned in another answer is the way to go, but if installing this module isn't an option you can use the -G flag to help parse p4.exe output:</p>\n\n<pre><code>p4 [ options ] command [ arg ... ]\n options:\n -c client -C charset -d dir -H host -G -L language\n -p port -P pass -s -Q charset -u user -x file\n The -G flag causes all output (and batch input for form commands\n with -i) to be formatted as marshalled Python dictionary objects.\n</code></pre>\n" }, { "answer_id": 307908, "author": "Epu", "author_id": 30015, "author_profile": "https://Stackoverflow.com/users/30015", "pm_score": 2, "selected": false, "text": "<p>Building from p4python source requires downloading and extracting the p4 api recommended for that version. For example, if building the Windows XP x86 version of P4Python 2008.2 for activepython 2.5:</p>\n\n<ul>\n<li>download and extract both the <a\nhref=\"ftp://ftp.perforce.com/perforce/r08.2/tools/p4python.tgz\" rel=\"nofollow noreferrer\">p4python</a> and <a\nhref=\"ftp://ftp.perforce.com/perforce/r08.2/bin.ntx86/p4api_vs2005_static.zip\" rel=\"nofollow noreferrer\">p4api</a></li>\n<li>fixup the setup.cfg for p4python to\npoint to the p4api directory.</li>\n</ul>\n\n<p>To open files for edit (do a checkout), on the command line, see 'p4 help open'.</p>\n\n<p>You can check out files without making a changelist if you add the file to the default changelist, but it's a good idea to make a changelist first.</p>\n\n<p>P4Python doesn't currently compile for activepython 2.6 without visual studio 2008; the provided libs are built with 2005 or 2003. Forcing p4python to build against mingw is nearly impossible, even with pexports of python26.dll and reimp/reassembly of the provided .lib files into .a files.</p>\n\n<p>In that case, you'll probably rather use subprocess, and return p4 results as marshalled python objects. You can write your own command wrapper that takes an arg array, constructs and runs the commands, and returns the results dictionary.</p>\n\n<p>You might try changing everything, testing, and on success, opening the files that are different with something equivalent to 'p4 diff -se //...'</p>\n" }, { "answer_id": 4242307, "author": "farhany", "author_id": 90506, "author_profile": "https://Stackoverflow.com/users/90506", "pm_score": 2, "selected": false, "text": "<p>Remember guys to install the development package for Python for the p4api or it will complain about missing headers. In Ubuntu 10.10, just do a simple:</p>\n\n<pre><code>apt-get install python2.6-dev\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>apt-get install python3.1-dev\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/852/" ]
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms: <http://www.perforce.com/perforce/loadsupp.html#api> You will find their documentation of the scripting API to be helpful: <http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf> Use of the Python API is quite similar to the command-line client: ``` PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> import P4 >>> p4 = P4.P4() >>> p4.connect() # connect to the default server, with the default clientspec >>> desc = {"Description": "My new changelist description", ... "Change": "new" ... } >>> p4.input = desc >>> p4.run("changelist", "-i") ['Change 2579505 created.'] >>> ``` I'll verify it from the command line: ``` P:\>p4 changelist -o 2579505 # A Perforce Change Specification. # # Change: The change number. 'new' on a new changelist. # Date: The date this specification was last modified. # Client: The client on which the changelist was created. Read-only. # User: The user who created the changelist. # Status: Either 'pending' or 'submitted'. Read-only. # Description: Comments about the changelist. Required. # Jobs: What opened jobs are to be closed by this changelist. # You may delete jobs from this list. (New changelists only.) # Files: What opened files from the default changelist are to be added # to this changelist. You may delete files from this list. # (New changelists only.) Change: 2579505 Date: 2008/10/08 13:57:02 Client: MYCOMPUTER-DT User: myusername Status: pending Description: My new changelist description ```
184,199
<p>I have a new project that needs a good binary protocol.</p> <p>I was thinking of using <a href="http://hessian.caucho.com/" rel="nofollow noreferrer">Hessian</a>, unless anyone has any better ideas.</p> <p>I was reading through some of their documentation and it's not as straightforward as I thought, so I have a couple of quick questions.</p> <p>The home page has a section titled "Documentation" that has the following documents:</p> <pre><code>* Hessian Documentation * Hessian 1.0.1 spec * Hessian 2.0 Serialization Draft * Hessian 2.0 Web Service Draft * Taxonomy explaining Hessians relationship to CORBA, SOAP, RMI </code></pre> <p>1) What is the difference between these? I assume that 1.0.1 later becomes 2.0, and that it is correct to use 2.0 today, but I wasn't sure.</p> <p>2) Would you expect someone to use 2.0 serialization or 2.0 web service? It looks like the web service is just supposed to be a reference to create a new implementation, but again it's not totally clear to me.</p> <p>3) What about implementing a server that supports Hessian using PHP. Do you need to use a Caucho server, or can you implement the server in PHP on a Fedora Core and connect using a Java client?</p>
[ { "answer_id": 184576, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 2, "selected": false, "text": "<p>I have not used Hessian in the past and I don't plan on using it in the future either, and my arguments are these:</p>\n\n<p>For a web service, I would try really hard to keep it in plain old XML. In the event that I would choose a binary XML representation, I would probably use <a href=\"http://en.wikipedia.org/wiki/Fast_Infoset\" rel=\"nofollow noreferrer\">Fast Infoset</a> - which is a standard and most likely supported by a much larger set of web service client APIs/libraries/frameworks. I know that the <a href=\"http://cxf.apache.org/\" rel=\"nofollow noreferrer\">CXF</a> people have talked about fast infoset on their mailing list and it should be supported, even though they have not documented this on their wiki.</p>\n\n<p>If speed is the primary thing, I would probably end up using <a href=\"http://code.google.com/p/protobuf/\" rel=\"nofollow noreferrer\">Protocol Buffers</a>.</p>\n" }, { "answer_id": 967109, "author": "Bruno Ranschaert", "author_id": 4900, "author_profile": "https://Stackoverflow.com/users/4900", "pm_score": 3, "selected": false, "text": "<p>Yes, Hessian 2.0 is the one to use. The protocol specifies how a data structure is represented binary, the spec is simple.</p>\n\n<p>The Hessian web service builds on the Hessian protocol, it specifies a number of headers in the Hessian format to describe e.g. the request/response format in the Hessian protocol. It defines the content of the request, the method that should be called and so on. It is not strictly needed because nobody uses it. You can define this yourself by creating a \"Request\" class and a \"Response\" class that suits you best and serialize this using Hessian protocol.</p>\n\n<p>Hessian is an alternative for Java serialization, it is slower because not directly supported by the java VM, but it is much (!) faster than XML parsing. It can be used in a cross platform way, although you will have to tweak existing implementations to make them work together, the spec has changed here and there (e.g. length specs) so that implementations tend to differ. The flip side is that it is not Human readable, you always need a tool to convert the Hessian to text. </p>\n\n<p>I have used Hessian in a large corporate application where a Java rich client communicates with a back end in order to make the client JVM version independent of the server JVM version. And it worked like a charm.</p>\n\n<p>Have a look at the implementation <a href=\"http://developer.berlios.de/projects/hessian4j/\" rel=\"noreferrer\">Hessian4J</a>. It is open source so you can have complete control over it.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16584/" ]
I have a new project that needs a good binary protocol. I was thinking of using [Hessian](http://hessian.caucho.com/), unless anyone has any better ideas. I was reading through some of their documentation and it's not as straightforward as I thought, so I have a couple of quick questions. The home page has a section titled "Documentation" that has the following documents: ``` * Hessian Documentation * Hessian 1.0.1 spec * Hessian 2.0 Serialization Draft * Hessian 2.0 Web Service Draft * Taxonomy explaining Hessians relationship to CORBA, SOAP, RMI ``` 1) What is the difference between these? I assume that 1.0.1 later becomes 2.0, and that it is correct to use 2.0 today, but I wasn't sure. 2) Would you expect someone to use 2.0 serialization or 2.0 web service? It looks like the web service is just supposed to be a reference to create a new implementation, but again it's not totally clear to me. 3) What about implementing a server that supports Hessian using PHP. Do you need to use a Caucho server, or can you implement the server in PHP on a Fedora Core and connect using a Java client?
Yes, Hessian 2.0 is the one to use. The protocol specifies how a data structure is represented binary, the spec is simple. The Hessian web service builds on the Hessian protocol, it specifies a number of headers in the Hessian format to describe e.g. the request/response format in the Hessian protocol. It defines the content of the request, the method that should be called and so on. It is not strictly needed because nobody uses it. You can define this yourself by creating a "Request" class and a "Response" class that suits you best and serialize this using Hessian protocol. Hessian is an alternative for Java serialization, it is slower because not directly supported by the java VM, but it is much (!) faster than XML parsing. It can be used in a cross platform way, although you will have to tweak existing implementations to make them work together, the spec has changed here and there (e.g. length specs) so that implementations tend to differ. The flip side is that it is not Human readable, you always need a tool to convert the Hessian to text. I have used Hessian in a large corporate application where a Java rich client communicates with a back end in order to make the client JVM version independent of the server JVM version. And it worked like a charm. Have a look at the implementation [Hessian4J](http://developer.berlios.de/projects/hessian4j/). It is open source so you can have complete control over it.
184,216
<p>Full disclaimer: I'm a CS student, and this question is related to a recently assigned Java program for Object-Oriented Programming. Although we've done some console stuff, this is the first time we've worked with a GUI and Swing or Awt. We were given some code that created a window with some text and a button that rotated through different colors for the text. We were then asked to modify the program to create radio buttons for the colors instead—this was also intended to give us practice researching an API. I've already handed in my assignment and received permission from my instructor to post my code here.</p> <p>What's the best way to implement button actions in Java? After some fiddling around, I created the buttons like this:</p> <pre><code>class HelloComponent3 extends JComponent implements MouseMotionListener, ActionListener { int messageX = 75, messageY= 175; String theMessage; String redString = "red", blueString = "blue", greenString = "green"; String magentaString = "magenta", blackString = "black", resetString = "reset"; JButton resetButton; JRadioButton redButton, blueButton, greenButton, magentaButton, blackButton; ButtonGroup colorButtons; public HelloComponent3(String message) { theMessage = message; //intialize the reset button resetButton = new JButton("Reset"); resetButton.setActionCommand(resetString); resetButton.addActionListener(this); //intialize our radio buttons with actions and labels redButton = new JRadioButton("Red"); redButton.setActionCommand(redString); ... </code></pre> <p>And added action listeners...</p> <pre><code>redButton.addActionListener(this); blueButton.addActionListener(this); ... </code></pre> <p>A stub was already created for the actionPerformed method to give us an idea on how to use it, but since there was only a single button in the template, it wasn't clear how to implement multiple buttons. I tried switching on a String, but quickly realized that, since a String isn't a primitive type, I couldn't use it for a switch statement. I could have improvised with an if-else chain, but this is what I came up with instead. It seems far from elegant, and there must be a better way. If there is, what is it? Is there a way to switch on a string? Or choose an action in a more scaleable fashion?</p> <pre><code>public void actionPerformed(ActionEvent e){ if (e.getActionCommand().equals(resetString)) { messageX = 75; messageY = 175; setForeground(Color.black); blackButton.setSelected(true); repaint(); return; } if ( e.getActionCommand().equals(redString) ) { setForeground(Color.red); repaint(); return; } if ( e.getActionCommand().equals(blueString) ) { setForeground(Color.blue); repaint(); return; } if ( e.getActionCommand().equals(greenString) ) { setForeground(Color.green); repaint(); return; } if ( e.getActionCommand().equals(magentaString) ) { setForeground(Color.magenta); repaint(); return; } if ( e.getActionCommand().equals(blackString) ) { setForeground(Color.black); repaint(); return; } } </code></pre>
[ { "answer_id": 184372, "author": "Patrick Huizinga", "author_id": 15200, "author_profile": "https://Stackoverflow.com/users/15200", "pm_score": 2, "selected": true, "text": "<p>Instead of writing this:</p>\n\n<pre><code>resetButton.addActionListener(this);\n</code></pre>\n\n<p>You could also write this:</p>\n\n<pre><code>resetButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent evt) {\n resetButtonActionPerformed(evt);\n }\n});\n</code></pre>\n\n<p>And instead of writing one big actionPerformed() for all actions, you can (and then have to) write this:</p>\n\n<pre><code>public void resetButtonActionPerformed(ActionEvent evt) {\n messageX = 75; messageY = 175;\n setForeground(Color.black);\n blackButton.setSelected(true);\n repaint();\n}\n</code></pre>\n\n<p>I don't know if this is the most elegant solution, but at least you no longer have that big if construct.</p>\n" }, { "answer_id": 184390, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 0, "selected": false, "text": "<p>Two alternate approaches:</p>\n\n<ol>\n<li>Create a new class that implements the Action interface and has a Color field and an actionPerformed method that sets the color</li>\n<li>Mantain a HashMap from command names to Color instances and look up the command name in the map</li>\n</ol>\n" }, { "answer_id": 184419, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": -1, "selected": false, "text": "<p>Ergh. Don't implement masses of unrelated interfaces in one mega class. Instead, use anoymous inner classes. They are a bit verbose, but are what you want. Use one for each event, then you wont need big if-else chain. I suggest keeping enough code within the inner class to decode the event and call methods that make sense to the target objects. Further, you can parameterise your inner classes. You will probably find you don't need to keep references to the actual widgets around.</p>\n\n<p>In your example you seem to be using a JComponent as a JPanel. There's not much difference, but use JPanel for collecting a block of widgets. Further there is unlikely any need to subclass it, so don't.</p>\n\n<p>So for instance:</p>\n\n<pre><code> addColorButton(\"Green\" , Color.GREEN );\n addColorButton(\"Red\" , Color.RED );\n addColorButton(\"Yellow\", Color.YELLOW);\n addColorButton(\"Blue\" , Color.BLUE );\n ...\n\nprivate void addColorButton(String label, Color color) {\n JRadioButton button = new JRadioButton(label);\n button.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent event) {\n target.setForeground(color);\n target.repaint();\n } \n });\n colorGroup.add(button);\n panel.add(button);\n}\n</code></pre>\n" }, { "answer_id": 184425, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "<p>One decent enough approach is to declare an <a href=\"http://www.xefer.com/2006/12/switchonstring\" rel=\"nofollow noreferrer\">enum whose elements match your strings</a> and switch on valueOf(str) (the linked example shows how to do this with a fair amount of safety).</p>\n\n<p>The reason to avoid anonymous inner classes is probably because the class hasn't had that construct (yet), even though that might be the best solution.</p>\n" }, { "answer_id": 189604, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 0, "selected": false, "text": "<p>As suggested already, you can use anonymous inner classes to implement the ActionListener interface. As an alternative, you don't have to use anonymous inner classes, but you can use a simple nested class instead:</p>\n\n<pre><code>resetButton = new JButton(new ResetAction());\nredButton = new JButton(new ColorAction(\"Red\", Color.red));\n</code></pre>\n\n<p>and then...</p>\n\n<pre><code>private class ResetAction extends AbstractAction {\n public ResetAction() {\n super(\"Reset\");\n }\n\n public void actionPerformed(ActionEvent e) {\n messageX = 75; messageY = 175;\n setForeground(Color.black);\n blackButton.setSelected(true);\n repaint();\n }\n}\n\nprivate class ResetAction extends AbstractAction {\n private Color color;\n\n public ColorAction(String title, Color color) {\n super(title);\n this.color = color;\n }\n\n public void actionPerformed(ActionEvent e) {\n setForeground(color);\n repaint();\n }\n}\n</code></pre>\n\n<p>For why this approach - or any approach involving inner classes - is better than implementing ActionListener in the outer class see \"Design Patterns\":</p>\n\n<p>\"Favor 'object composition' over 'class inheritance'.\" (Gang of Four 1995:20)</p>\n\n<p>Choosing between anonymous inner classes and these named inner classes is a largely a matter of style, but I think this version is easier to understand, and clearer when there are lots of actions.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26237/" ]
Full disclaimer: I'm a CS student, and this question is related to a recently assigned Java program for Object-Oriented Programming. Although we've done some console stuff, this is the first time we've worked with a GUI and Swing or Awt. We were given some code that created a window with some text and a button that rotated through different colors for the text. We were then asked to modify the program to create radio buttons for the colors instead—this was also intended to give us practice researching an API. I've already handed in my assignment and received permission from my instructor to post my code here. What's the best way to implement button actions in Java? After some fiddling around, I created the buttons like this: ``` class HelloComponent3 extends JComponent implements MouseMotionListener, ActionListener { int messageX = 75, messageY= 175; String theMessage; String redString = "red", blueString = "blue", greenString = "green"; String magentaString = "magenta", blackString = "black", resetString = "reset"; JButton resetButton; JRadioButton redButton, blueButton, greenButton, magentaButton, blackButton; ButtonGroup colorButtons; public HelloComponent3(String message) { theMessage = message; //intialize the reset button resetButton = new JButton("Reset"); resetButton.setActionCommand(resetString); resetButton.addActionListener(this); //intialize our radio buttons with actions and labels redButton = new JRadioButton("Red"); redButton.setActionCommand(redString); ... ``` And added action listeners... ``` redButton.addActionListener(this); blueButton.addActionListener(this); ... ``` A stub was already created for the actionPerformed method to give us an idea on how to use it, but since there was only a single button in the template, it wasn't clear how to implement multiple buttons. I tried switching on a String, but quickly realized that, since a String isn't a primitive type, I couldn't use it for a switch statement. I could have improvised with an if-else chain, but this is what I came up with instead. It seems far from elegant, and there must be a better way. If there is, what is it? Is there a way to switch on a string? Or choose an action in a more scaleable fashion? ``` public void actionPerformed(ActionEvent e){ if (e.getActionCommand().equals(resetString)) { messageX = 75; messageY = 175; setForeground(Color.black); blackButton.setSelected(true); repaint(); return; } if ( e.getActionCommand().equals(redString) ) { setForeground(Color.red); repaint(); return; } if ( e.getActionCommand().equals(blueString) ) { setForeground(Color.blue); repaint(); return; } if ( e.getActionCommand().equals(greenString) ) { setForeground(Color.green); repaint(); return; } if ( e.getActionCommand().equals(magentaString) ) { setForeground(Color.magenta); repaint(); return; } if ( e.getActionCommand().equals(blackString) ) { setForeground(Color.black); repaint(); return; } } ```
Instead of writing this: ``` resetButton.addActionListener(this); ``` You could also write this: ``` resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { resetButtonActionPerformed(evt); } }); ``` And instead of writing one big actionPerformed() for all actions, you can (and then have to) write this: ``` public void resetButtonActionPerformed(ActionEvent evt) { messageX = 75; messageY = 175; setForeground(Color.black); blackButton.setSelected(true); repaint(); } ``` I don't know if this is the most elegant solution, but at least you no longer have that big if construct.
184,272
<p>What exactly does the word patch mean when referring to 'submitting a patch'?</p> <p>I've seen this used a lot, especially in the open source world. What what does it mean and what exactly is involved in submitting a patch?</p>
[ { "answer_id": 184277, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 5, "selected": true, "text": "<p>It's a file with a list of differences between the code files that have changed. It's usually in the format generated by doing a <strong>diff -u</strong> on the two files. Most version control systems allow the easy creation of patches but it's generally in that same format.</p>\n\n<p>This allows the code change to be easily applied to someone else's copy of the source code using the <strong>patch</strong> command.</p>\n\n<p>For example:</p>\n\n<p>Let's say I have the following code:</p>\n\n<pre><code>&lt;?php\n $foo = 0;\n?&gt;\n</code></pre>\n\n<p>and I change it to this:</p>\n\n<pre><code>&lt;?php\n $bar = 0;\n?&gt;\n</code></pre>\n\n<p>The patch file might look like this:</p>\n\n<pre><code>Index: test.php\n===================================================================\n--- test.php (revision 40)\n+++ test.php (working copy)\n@@ -3,7 +3,7 @@\n &lt;?php\n- $foo = 0;\n+ $bar= 0;\n ?&gt;\n</code></pre>\n" }, { "answer_id": 184284, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 1, "selected": false, "text": "<p>A patch is a file containing all of the necessary information to turn the maintainer's source tree in to your own. It's usually created by tools like <code>diff</code> or <code>svn diff</code> or <code>git format-patch</code>.</p>\n\n<p>Traditionally, open-source projects accept submissions from normal schlubs in the form of patches so they don't have to give others commit access to their repositories.</p>\n" }, { "answer_id": 184291, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 1, "selected": false, "text": "<p>A patch, ususally in the form of a .patch file, is a common flat file format for transmitting the differences between two sets of code files. So if you are working on an open source project, and make code changes to files, and want to submit that to the project owner to be checked in (usually because you don't have checkin rights), you would do so via a patch.</p>\n\n<p>WinMerge has this functionality built in, as do many other tools like TortoiseSVN.</p>\n" }, { "answer_id": 184294, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 0, "selected": false, "text": "<p>I've always believed the term meant a bug fix, like a knee patch Mom used to put on your holey jeans.</p>\n" }, { "answer_id": 184295, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 1, "selected": false, "text": "<p>A patch file represents the difference between existing source and source you've modified. It is the primary means of adding features or fixing bugs in many projects.</p>\n\n<p>You create a patch using the diff command (for example).</p>\n\n<p>You can then submit this patch to the development mailing list and if it received well, then a committer will apply the patch (thus automatically applying your changes) and commit the code. </p>\n\n<p>Patches are applied using the patch command.</p>\n" }, { "answer_id": 184297, "author": "Travis Illig", "author_id": 8116, "author_profile": "https://Stackoverflow.com/users/8116", "pm_score": 1, "selected": false, "text": "<p>Generally it implies submitting a unified diff file with the aggregate changeset for a feature. You can <a href=\"http://en.wikipedia.org/wiki/Patch_(Unix)\" rel=\"nofollow noreferrer\">read more about patches on Wikipedia</a>. Several version control systems (svn, git, etc.) will create a patch file for you based on a changeset.</p>\n" }, { "answer_id": 184298, "author": "Kluge", "author_id": 8752, "author_profile": "https://Stackoverflow.com/users/8752", "pm_score": 1, "selected": false, "text": "<pre><code> 1. n. A temporary addition to a piece of code, usually as a quick-and-dirty\n</code></pre>\n\n<p>remedy to an existing bug or misfeature. A patch may or may not work, and may or may not\neventually be incorporated permanently into the program. Distinguished from a diff\nor mod by the fact that a patch is generated by more primitive means than the rest\nof the program; the classical examples are instructions modified by using the front\npanel switches, and changes made directly to the binary executable of a program\noriginally written in an HLL. Compare one-line fix. </p>\n\n<p>See the entire definition in the jargon file <a href=\"http://catb.org/jargon/html/P/patch.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 184316, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 3, "selected": false, "text": "<p>Richard Jones, a developer at Red Hat, has <a href=\"http://et.redhat.com/~rjones/how-to-supply-code-to-open-source-projects/\" rel=\"noreferrer\">a nice little primer</a> on submitting code to open source projects which covers making and submitting patches.</p>\n" }, { "answer_id": 184323, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<p>A patch is usually a file that contains information how to change something (very often to fix a bug, but could also be an enhancement). There are different kind of patches.</p>\n\n<p>A source code patch contains information how one or multiple source code files need to be modified. You can easily generate them using the <em>diff</em> command and you can apply them using the <em>patch</em> command (on Linux/UNIX systems these commands are standard).</p>\n\n<p>However, there are also binary patches. A binary patch contains information how certain bytes within a binary need to be changed. Binary patches are, of course, rare in the OpenSource world, but in the early days of computers I saw them a lot to modify shipped binaries (usually to work around a bug).</p>\n\n<p>Submitting a patch means you have locally fixed something and now you send the file to someone, so he can apply this patch to his local copy or to a public copy on the web, thus other users can benefit of the fix.</p>\n\n<p>Patches are also often used if you have some source code that almost compiles on a certain platform, but some tiny changes are necessary to really have it compile there. Of course you could take the source, modify it and offer the modified code for download. But what if the original source changes again (e.g. bugs get fixed or small enhancements were added)? Then you had to re-download the source, apply the changes again and offer the new modified version. It's a lot of work to keep your modified source up-to-date. Instead of modifying, you create a <em>diff</em> between the original and your modified copy and store it on your server. If now a user wants to download and compile the app from source, he can first download the latest &amp; greatest version of the original source, then apply your patch (so it will compile) and always has the latest version, without you having to change the patch. A problem will only arise if the original source has been changed exactly in one of the places your patch modifies. In this case the system will refuse to apply the patch and a new patch needs to be made.</p>\n" }, { "answer_id": 3058601, "author": "VariableLost", "author_id": 368875, "author_profile": "https://Stackoverflow.com/users/368875", "pm_score": 1, "selected": false, "text": "<p>Patch is also used in the act of updating system binaries. Microsoft sends out patches all the time but they aren't source code. They are .msp files that install improved binaries. As with all computer science terms, patch is overloaded.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
What exactly does the word patch mean when referring to 'submitting a patch'? I've seen this used a lot, especially in the open source world. What what does it mean and what exactly is involved in submitting a patch?
It's a file with a list of differences between the code files that have changed. It's usually in the format generated by doing a **diff -u** on the two files. Most version control systems allow the easy creation of patches but it's generally in that same format. This allows the code change to be easily applied to someone else's copy of the source code using the **patch** command. For example: Let's say I have the following code: ``` <?php $foo = 0; ?> ``` and I change it to this: ``` <?php $bar = 0; ?> ``` The patch file might look like this: ``` Index: test.php =================================================================== --- test.php (revision 40) +++ test.php (working copy) @@ -3,7 +3,7 @@ <?php - $foo = 0; + $bar= 0; ?> ```
184,313
<p>I have this .NET regex:</p> <pre><code>^(?&lt;prefix&gt;("[^"]*"))\s(?&lt;attrgroup&gt;(\([^\)]*\)))\s(?&lt;suffix&gt;("[^"]*"))$ </code></pre> <p>It properly matches the following strings:</p> <pre><code>"some prefix" ("attribute 1" "value 1") "some suffix" "some prefix" ("attribute 1" "value 1" "attribute 2" "value 2") "some suffix" </code></pre> <p>It fails on...</p> <pre><code>"some prefix" ("attribute 1" "value (fail) 1") "some suffix" </code></pre> <p>...due to the right paren after "fail".</p> <p>How can I modify my regex so that the <code>attrgroup</code> match group will end up containing "<code>("attribute 1" "value (fail) 1")</code>"? I've been looking at it for too long and need some fresh eyes. Thanks!</p> <p><strong>Edit:</strong> <code>attrgroup</code> won't ever contain anything other than pairs of double-quoted strings.</p>
[ { "answer_id": 184392, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 1, "selected": false, "text": "<pre><code>^(?&lt;prefix&gt;\"[^\"]*\")\\s+(?&lt;attrgroup&gt;\\(.*\\))\\s+(?&lt;suffix&gt;\"[^\"]*\")$\n</code></pre>\n\n<p>fixed it for me.</p>\n\n<p>I removed the extraneous unnamed groups and simplified (down to \"any character\") the attribute group.</p>\n\n<p>A <em>very</em> worthwhile investment would be JG Soft's RegexBuddy</p>\n\n<p>Edit: This won't validate the attribute group as pairs of quoted strings, but that should/could be done in a separate regex/validation step.</p>\n" }, { "answer_id": 184417, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 0, "selected": false, "text": "<p>Hometoasts solution is a good one, though like any liberal regex it should only be used to extract data from sources you have a reasonable assurance are well formed and not for validation.</p>\n" }, { "answer_id": 184418, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 0, "selected": false, "text": "<p>Without addressing the specifics of this regex, I would recommend using a Regex tool to help build, test, and validate your regular expressions. For anything non-trivial, or expressions you may need to maintain/update, these sort of tools are essential.</p>\n\n<p>Check out...</p>\n\n<p><a href=\"http://www.weitz.de/regex-coach/\" rel=\"nofollow noreferrer\">The Regex Coach</a> - Written in Lisp, a bit older, but I really prefer this one to others.</p>\n\n<p><a href=\"http://www.radsoftware.com.au/regexdesigner/\" rel=\"nofollow noreferrer\">Rad Software Regex Designer</a> - .NET and more \"modern\" perhaps. Some may like this one.</p>\n" }, { "answer_id": 184451, "author": "Patrick Huizinga", "author_id": 15200, "author_profile": "https://Stackoverflow.com/users/15200", "pm_score": 3, "selected": true, "text": "<p>my, untested guess:</p>\n\n<pre><code>^(?&lt;prefix&gt;(\"[^\"]*\"))\\s(?&lt;attrgroup&gt;(\\((\"[^\"]*\")(\\s(\"[^\"]*\")*)**\\)))\\s(?&lt;suffix&gt;(\"[^\"]*\"))$\n</code></pre>\n\n<p>hereby I've replaced</p>\n\n<pre><code>[^\\)]*\n</code></pre>\n\n<p>with</p>\n\n<pre><code>(\"[^\"]*\")(\\s(\"[^\"]*\")*)*\n</code></pre>\n\n<p>I assumed everything within the parenthesis is either between double quotes, or is a whitespace.</p>\n\n<p>If you want to know how I came up with this, read <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596528124\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Mastering Regular Expressions</a>.</p>\n\n<p>ps. if I'm correct, then this will also validate attribute group as pairs of quoted string.</p>\n" }, { "answer_id": 187148, "author": "Tetha", "author_id": 17663, "author_profile": "https://Stackoverflow.com/users/17663", "pm_score": 0, "selected": false, "text": "<p>I suggest using a parser that is able to handle such structures. The regular expression fails, and this is correct, as the language you try to parse doesn't look regular -- at least from the examples given above. Whenever you need to recognize nesting, regexps will either fail or grow into complicated beasts like that one above. Even if the language is regular, that regular expression up there looks way too complicated for me. I'd rather use something like this:</p>\n\n<pre><code>def parse_String(string):\n index = skip_spaces(string, 0)\n index, prefix = read_prefix(string, index)\n index = skip_spaces(string, index)\n index, attrgroup = read_attrgroup(string, index)\n index = skip_spaces(string, index)\n index, suffix = read_suffix(string, index)\n return prefix, attrgroup, suffix\n\ndef read_prefix(string, start_index):\n return read_quoted_string(string, start_index) \n\ndef read_attrgroup(string, start_index):\n end_index, content = read_paren(string, start_index)\n\n index = skip_spaces(content, 0)\n index, first_entry = read_quoted_string(content, index)\n index = skip_spaces(content, index)\n index, second_entry = read_quoted_string(content, index)\n return end_index, (first_entry, second_entry)\n\n\ndef read_suffix(string, start_index):\n return read_quoted_string(string, start_index)\n\ndef read_paren(string, start_index):\n return read_delimited_string(string, start_index, '(', ')')\n\ndef read_quoted_string(string, start_index):\n return read_delimited_string(string, start_index, '\"', '\"')\n\ndef read_delimited_string(string, starting_index, start_limiter, end_limiter):\n assert string[starting_index] == start_limiter, (start_limiter \n +\"!=\" \n +string[starting_index])\n current_index = starting_index+1\n content = \"\"\n while(string[current_index] != end_limiter):\n content += string[current_index]\n current_index += 1\n\n assert string[current_index] == end_limiter\n return current_index+1, content\n\ndef skip_spaces(string, index):\n while string[index] == \" \":\n index += 1\n return index\n</code></pre>\n\n<p>yes, this is more code, and yes, by raw number of keys, this took longer. However -- at least for me -- my solution is far easier to verify. This increases even more if you remove a bunch of the string-and-index-plumbing by moving all of that into the class, which parses such strings in it's constructor. Furthermore, it is easy to make the space-skipping implicit (using some magic next-char method which just skips chars until a non-space appears, unless it is in some non-skip mode due to strings. This mode can be set in the delimited-function, for example). This would turn the parse_string into:</p>\n\n<pre><code>def parse_string(string):\n prefix = read_prefix()\n attrgroup = read_attr_group()\n suffix = read_suffix()\n return prefix, attrgroup, suffix.\n</code></pre>\n\n<p>Furthermore, this functions can be extended easier to cover more complicated expressions. Arbitrarily nested attrgroups? a change of one line of code. Nested parens? a bit more work, but no real problem. </p>\n\n<p>Now, please flame and downvote me for being some regex-heretic and some parser-advocator. >:)</p>\n\n<p>PS: yes, that code is untested. as I know myself, there are 3 typos in there I did not see.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3447/" ]
I have this .NET regex: ``` ^(?<prefix>("[^"]*"))\s(?<attrgroup>(\([^\)]*\)))\s(?<suffix>("[^"]*"))$ ``` It properly matches the following strings: ``` "some prefix" ("attribute 1" "value 1") "some suffix" "some prefix" ("attribute 1" "value 1" "attribute 2" "value 2") "some suffix" ``` It fails on... ``` "some prefix" ("attribute 1" "value (fail) 1") "some suffix" ``` ...due to the right paren after "fail". How can I modify my regex so that the `attrgroup` match group will end up containing "`("attribute 1" "value (fail) 1")`"? I've been looking at it for too long and need some fresh eyes. Thanks! **Edit:** `attrgroup` won't ever contain anything other than pairs of double-quoted strings.
my, untested guess: ``` ^(?<prefix>("[^"]*"))\s(?<attrgroup>(\(("[^"]*")(\s("[^"]*")*)**\)))\s(?<suffix>("[^"]*"))$ ``` hereby I've replaced ``` [^\)]* ``` with ``` ("[^"]*")(\s("[^"]*")*)* ``` I assumed everything within the parenthesis is either between double quotes, or is a whitespace. If you want to know how I came up with this, read [Mastering Regular Expressions](https://rads.stackoverflow.com/amzn/click/com/0596528124). ps. if I'm correct, then this will also validate attribute group as pairs of quoted string.
184,340
<p>I have an application that manages patient demographic information. Along with this data a user can scan a picture of a patient and assign that picture to a patient. When the user clicks the scan button a separate application is opened as a dialog in order to scan the image. When running this on XP everything worked fine. The imaging application loaded up fine and gained focus. On Vista however occasionally the imaging application will not gain focus and will popup behind the main application. When running full screen or through 2008 Application Server you cannot see the application, you only get a locked screen and it appears nothing has happened. Is there any way to change the window focus management on Vista to work the way XP did? I'm looking for a way to solve this without making changes to the actual application if possible.</p>
[ { "answer_id": 184368, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 0, "selected": false, "text": "<p>You could iterate through all top level HWNDs and identify the scanning application via its window class, then send an appropriate message to raise the window.</p>\n" }, { "answer_id": 184422, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 1, "selected": false, "text": "<p>I think you will have to make changes to your application to allow the imaging application to take the focus. I'm going to assume that your application launches the imaging application through <code>ShellExecute</code> or <code>CreateProcess</code>. If so, you can get the process handle of the launched process either through <code>SHELLEXECUTEINFO.hProcess</code> (for <code>ShellExecute</code>) or <code>PROCESS_INFORMATION.hProcess</code> (for <code>CreateProcess</code>). Immediately after launching the imaging application call the <a href=\"http://msdn.microsoft.com/en-us/library/ms632668(VS.85).aspx\" rel=\"nofollow noreferrer\">AllowSetForegroundWindow</a> API:</p>\n\n<pre><code>AllowSetForegroundWindow(GetProcessId(hProcess));\n</code></pre>\n\n<p>This will allow the imaging application to place its main window/dialog in the foreground when it's starting up.</p>\n" }, { "answer_id": 184599, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 1, "selected": false, "text": "<p>You could try the following steps:<br>\n1. Right Click on the exe<br>\n2. Select Properties<br>\n3. Select the Compatibility Tab<br>\n4. Check the Run this program in campatibility mode for:<br>\n5. Select Windows XP (Service Pack 2)</p>\n" }, { "answer_id": 201212, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 0, "selected": false, "text": "<p>I don't believe this is Vista vs XP related. I think that simply this imaging app takes longer to start on Vista.\nSince Windows 2000, the window manager has prevented background applications stealing the foreground. When an application is launched, it has a window of opportunity to create and show a window that will take the foreground. If it takes too long, the window manager thinks that the current window should keep the foreground, and inhibits the other app taking the foreground when it does finally launch.</p>\n\n<p>I can't think of any specific way to avoid this... other than using FindWindow to search for the other apps window after launching the app. When you eventually find it, call SetForegroundWindow on it to bring it to the foreground.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25511/" ]
I have an application that manages patient demographic information. Along with this data a user can scan a picture of a patient and assign that picture to a patient. When the user clicks the scan button a separate application is opened as a dialog in order to scan the image. When running this on XP everything worked fine. The imaging application loaded up fine and gained focus. On Vista however occasionally the imaging application will not gain focus and will popup behind the main application. When running full screen or through 2008 Application Server you cannot see the application, you only get a locked screen and it appears nothing has happened. Is there any way to change the window focus management on Vista to work the way XP did? I'm looking for a way to solve this without making changes to the actual application if possible.
I think you will have to make changes to your application to allow the imaging application to take the focus. I'm going to assume that your application launches the imaging application through `ShellExecute` or `CreateProcess`. If so, you can get the process handle of the launched process either through `SHELLEXECUTEINFO.hProcess` (for `ShellExecute`) or `PROCESS_INFORMATION.hProcess` (for `CreateProcess`). Immediately after launching the imaging application call the [AllowSetForegroundWindow](http://msdn.microsoft.com/en-us/library/ms632668(VS.85).aspx) API: ``` AllowSetForegroundWindow(GetProcessId(hProcess)); ``` This will allow the imaging application to place its main window/dialog in the foreground when it's starting up.
184,414
<p>I have one action I want to perform when a TSpeedButton is pressed and another I want to perform when the same button is "unpressed". I know there's no onunpress event, but is there any easy way for me to get an action to execute when a different button is pressed? </p> <pre><code>procedure ActionName.ActionNameExecute(Sender: TObject); begin PreviousActionName.execute(Sender); // end; </code></pre> <p>Seems too clunky.</p>
[ { "answer_id": 184588, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>Yes, you do. You're defining a self-contained piece of work which the NSOperationQueue will execute on \"some\" thread, so you're responsible for managing memory in that work piece.</p>\n" }, { "answer_id": 185954, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 2, "selected": false, "text": "<p>Yes, you need to create an <code>NSAutoreleasePool</code> in your <code>[NSOperation main]</code> method, unless you are creating a \"concurrent\" (slightly unfortunate nomenclature) <code>NSOperation</code> subclass and your overridden <code>[NSOperation start]</code> method creates the <code>NSAutoreleasePool</code> before calling `[NSOperation main].</p>\n\n<p>The <code>NSOperation</code> class documentation has a good description of all of this:\n<a href=\"http://developer.apple.com/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html</a>.</p>\n" }, { "answer_id": 332565, "author": "DavidPhillipOster", "author_id": 42287, "author_profile": "https://Stackoverflow.com/users/42287", "pm_score": 3, "selected": false, "text": "<p>You don't need to create your own NSAutoreleasePool in your main, the system does it for you. To see this, use the Xcode menu command Run > Show> Breakpoints to open the Breakpoints window and type in:\n-[NSAutoreleasePool init]</p>\n\n<p>Now run your program, and you'll see an autorelease pool getting created inside NSOperation.</p>\n\n<p>See also, Apple's examples, for example, <a href=\"http://developer.apple.com/Cocoa/managingconcurrency.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/Cocoa/managingconcurrency.html</a> which don't create their own autorelease pool.</p>\n" }, { "answer_id": 1606179, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>yes, you need to.</p>\n\n<pre><code>- (void) main\n{\n NSAutoreleasePool *thePool = [[NSAutoreleasePool alloc] init];\n //your code here\n //more code\n [thePool release];\n}\n</code></pre>\n\n<p>if you don't create an autorelease pool, any convinience class-initializer (like [NSString stringWithFormat:]) will leak as these initializers return autoreleased objects.</p>\n" }, { "answer_id": 2203596, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 4, "selected": false, "text": "<p>Good question, even Apple's own documents and example code aren't very clear on this. I believe I've found the answer though:</p>\n\n<blockquote>\n <p>Because operations are Objective-C\n objects, you should always create an\n autorelease pool early in the\n implementation of your task code. An\n autorelease pool provides protection\n against the leaking of Objective-C\n objects that are autoreleased during\n your task’s execution. Although there\n might already be a pool in place by\n the time your custom code is executed,\n you should never rely on that behavior\n and should always provide your own.</p>\n</blockquote>\n\n<p>Basically, even though there may be a pool in place as David mentioned, you should still create your own.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
I have one action I want to perform when a TSpeedButton is pressed and another I want to perform when the same button is "unpressed". I know there's no onunpress event, but is there any easy way for me to get an action to execute when a different button is pressed? ``` procedure ActionName.ActionNameExecute(Sender: TObject); begin PreviousActionName.execute(Sender); // end; ``` Seems too clunky.
Yes, you do. You're defining a self-contained piece of work which the NSOperationQueue will execute on "some" thread, so you're responsible for managing memory in that work piece.
184,431
<p>I'm trying to convert an XML file into the markup used by dokuwiki, using XSLT. This actually works to some degree, but the indentation in the XSL file is getting inserted into the results. At the moment, I have two choices: abandon this XSLT thing entirely, and find another way to convert from XML to dokuwiki markup, or delete about 95% of the whitespace from the XSL file, making it nigh-unreadable and a maintenance nightmare.</p> <p>Is there some way to keep the indentation in the XSL file without passing all that whitespace on to the final document?</p> <p>Background: I'm migrating an autodoc tool from static HTML pages over to dokuwiki, so the API developed by the server team can be further documented by the applications team whenever the apps team runs into poorly-documented code. The logic is to have a section of each page set aside for the autodoc tool, and to allow comments anywhere outside this block. I'm using XSLT because we already have the XSL file to convert from XML to XHTML, and I'm assuming it will be faster to rewrite the XSL than to roll my own solution from scratch.</p> <p><i>Edit: Ah, right, foolish me, I neglected the indent attribute. (Other background note: I am new to XSLT.) On the other hand, I still have to deal with newlines. Dokuwiki uses pipes to differentiate between table columns, which means that all of the data in a table line must be on one line. Is there a way to suppress newlines being outputted (just occasionally), so I can do some fairly complex logic for each table cell in a somewhat readable fasion?</i></p>
[ { "answer_id": 184449, "author": "Lindsay", "author_id": 23520, "author_profile": "https://Stackoverflow.com/users/23520", "pm_score": 2, "selected": false, "text": "<p>Are you using indent=\"no\" in your output tag?</p>\n\n<pre><code>&lt;xsl:output method=\"text\" indent=\"no\" /&gt;\n</code></pre>\n\n<p>Also if you're using xsl:value-of you can use the disable-output-escaping=\"yes\" to help with some whitespace issues.</p>\n" }, { "answer_id": 184931, "author": "Odilon Redo", "author_id": 21166, "author_profile": "https://Stackoverflow.com/users/21166", "pm_score": 0, "selected": false, "text": "<p>Regarding your edit about new lines, you can use this template to recursively replace one string within another string, and you can use it for line breaks:</p>\n\n<pre><code>&lt;xsl:template name=\"replace.string.section\"&gt;\n &lt;xsl:param name=\"in.string\"/&gt;\n &lt;xsl:param name=\"in.characters\"/&gt;\n &lt;xsl:param name=\"out.characters\"/&gt;\n &lt;xsl:choose&gt;\n &lt;xsl:when test=\"contains($in.string,$in.characters)\"&gt;\n &lt;xsl:value-of select=\"concat(substring-before($in.string,$in.characters),$out.characters)\"/&gt;\n &lt;xsl:call-template name=\"replace.string.section\"&gt;\n &lt;xsl:with-param name=\"in.string\" select=\"substring-after($in.string,$in.characters)\"/&gt;\n &lt;xsl:with-param name=\"in.characters\" select=\"$in.characters\"/&gt;\n &lt;xsl:with-param name=\"out.characters\" select=\"$out.characters\"/&gt;\n &lt;/xsl:call-template&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:otherwise&gt;\n &lt;xsl:value-of select=\"$in.string\"/&gt;\n &lt;/xsl:otherwise&gt;\n &lt;/xsl:choose&gt;\n&lt;/xsl:template&gt; \n</code></pre>\n\n<p>Call it as follows (this example replaces line breaks in the $some.string variable with a space):</p>\n\n<pre><code> &lt;xsl:call-template name=\"replace.string.section\"&gt;\n &lt;xsl:with-param name=\"in.string\" select=\"$some.string\"/&gt;\n &lt;xsl:with-param name=\"in.characters\" select=\"'&amp;#xA;'\"/&gt;\n &lt;xsl:with-param name=\"out.characters\" select=\"' '\"/&gt;\n &lt;/xsl:call-template&gt;\n</code></pre>\n" }, { "answer_id": 185048, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 7, "selected": true, "text": "<p>There are three reasons for getting unwanted whitespace in the result of an XSLT transformation:</p>\n\n<ol>\n<li>whitespace that comes from between nodes in the source document</li>\n<li>whitespace that comes from within nodes in the source document</li>\n<li>whitespace that comes from the stylesheet</li>\n</ol>\n\n<p>I'm going to talk about all three because it can be hard to tell where whitespace comes from so you might need to use several strategies.</p>\n\n<p>To address the whitespace that is between nodes in your source document, you should use <code>&lt;xsl:strip-space&gt;</code> to strip out any whitespace that appears between two nodes, and then use <code>&lt;xsl:preserve-space&gt;</code> to preserve the significant whitespace that might appear within mixed content. For example, if your source document looks like:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li&gt;This is an &lt;strong&gt;important&lt;/strong&gt; &lt;em&gt;point&lt;/em&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>then you will want to ignore the whitespace between the <code>&lt;ul&gt;</code> and the <code>&lt;li&gt;</code> and between the <code>&lt;/li&gt;</code> and the <code>&lt;/ul&gt;</code>, which is not significant, but preserve the whitespace between the <code>&lt;strong&gt;</code> and <code>&lt;em&gt;</code> elements, which <em>is</em> significant (otherwise you'd get \"This is an **important***point*\"). To do this use</p>\n\n<pre><code>&lt;xsl:strip-space elements=\"*\" /&gt;\n&lt;xsl:preserve-space elements=\"li\" /&gt;\n</code></pre>\n\n<p>The <code>elements</code> attribute on <code>&lt;xsl:preserve-space&gt;</code> should basically list all the elements in your document that have mixed content.</p>\n\n<blockquote>\n <p>Aside: using <code>&lt;xsl:strip-space&gt;</code> also reduces the size of the source tree in memory, and makes your stylesheet more efficient, so it's worth doing even if you don't have whitespace problems of this sort.</p>\n</blockquote>\n\n<p>To address the whitespace that appears within nodes in your source document, you should use <code>normalize-space()</code>. For example, if you have:</p>\n\n<pre><code>&lt;dt&gt;\n a definition\n&lt;/dt&gt;\n</code></pre>\n\n<p>and you can be sure that the <code>&lt;dt&gt;</code> element won't hold any elements that you want to do something with, then you can do:</p>\n\n<pre><code>&lt;xsl:template match=\"dt\"&gt;\n ...\n &lt;xsl:value-of select=\"normalize-space(.)\" /&gt;\n ...\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>The leading and trailing whitespace will be stripped from the value of the <code>&lt;dt&gt;</code> element and you will just get the string <code>\"a definition\"</code>.</p>\n\n<p>To address whitespace coming from the stylesheet, which is perhaps the one you're experiencing, is when you have text within a template like this:</p>\n\n<pre><code>&lt;xsl:template match=\"name\"&gt;\n Name:\n &lt;xsl:value-of select=\".\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>XSLT stylesheets are parsed in the same way as the source documents that they process, so the above XSLT is interpreted as a tree that holds an <code>&lt;xsl:template&gt;</code> element with a <code>match</code> attribute whose first child is a text node and whose second child is a <code>&lt;xsl:value-of&gt;</code> element with a <code>select</code> attribute. The text node has leading and trailing whitespace (including line breaks); since it's literal text in the stylesheet, it gets literally copied over into the result, with all the leading and trailing whitespace.</p>\n\n<p>But <em>some</em> whitespace in XSLT stylesheets get stripped automatically, namely those between nodes. You don't get a line break in your result because there's a line break between the <code>&lt;xsl:value-of&gt;</code> and the close of the <code>&lt;xsl:template&gt;</code>.</p>\n\n<p>To get only the text you want in the result, use the <code>&lt;xsl:text&gt;</code> element like this:</p>\n\n<pre><code>&lt;xsl:template match=\"name\"&gt;\n &lt;xsl:text&gt;Name: &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\".\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>The XSLT processor will ignore the line breaks and indentation that appear between nodes, and only output the text within the <code>&lt;xsl:text&gt;</code> element.</p>\n" }, { "answer_id": 4703908, "author": "Dan", "author_id": 95559, "author_profile": "https://Stackoverflow.com/users/95559", "pm_score": 2, "selected": false, "text": "<p>@JeniT's answer is great, I just want to point out a trick for managing whitespace. I'm not certain it's the best way (or even a good way), but it works for me for now.</p>\n\n<p>(\"s\" for space, \"e\" for empty, \"n\" for newline.)</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!DOCTYPE xsl:transform [\n &lt;!ENTITY s \"&lt;xsl:text xmlns:xsl='http://www.w3.org/1999/XSL/Transform'&gt; &lt;/xsl:text&gt;\" &gt;\n &lt;!ENTITY s2 \"&lt;xsl:text xmlns:xsl='http://www.w3.org/1999/XSL/Transform'&gt; &lt;/xsl:text&gt;\" &gt;\n &lt;!ENTITY s4 \"&lt;xsl:text xmlns:xsl='http://www.w3.org/1999/XSL/Transform'&gt; &lt;/xsl:text&gt;\" &gt;\n &lt;!ENTITY s6 \"&lt;xsl:text xmlns:xsl='http://www.w3.org/1999/XSL/Transform'&gt; &lt;/xsl:text&gt;\" &gt;\n &lt;!ENTITY e \"&lt;xsl:text xmlns:xsl='http://www.w3.org/1999/XSL/Transform'&gt;&lt;/xsl:text&gt;\" &gt;\n &lt;!ENTITY n \"&lt;xsl:text xmlns:xsl='http://www.w3.org/1999/XSL/Transform'&gt;\n&lt;/xsl:text&gt;\" &gt;\n]&gt;\n\n&lt;xsl:transform version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"&gt;\n&lt;xsl:output method=\"text\"/&gt;\n&lt;xsl:template match=\"/\"&gt;\n &amp;e;Flush left, despite the indentation.&amp;n;\n &amp;e; This line will be output indented two spaces.&amp;n;\n\n &lt;!-- the blank lines above/below won't be output --&gt;\n\n &lt;xsl:for-each select=\"//foo\"&gt;\n &amp;e; Starts with two blanks: &lt;xsl:value-of select=\"@bar\"/&gt;.&amp;n;\n &amp;e; &lt;xsl:value-of select=\"@baz\"/&gt; The 'e' trick won't work here.&amp;n;\n &amp;s2;&lt;xsl:value-of select=\"@baz\"/&gt; Use s2 instead.&amp;n;\n &amp;s2; &lt;xsl:value-of select=\"@abc\"/&gt; &lt;xsl:value-of select=\"@xyz\"/&gt;&amp;n;\n &amp;s2; &lt;xsl:value-of select=\"@abc\"/&gt;&amp;s;&lt;xsl:value-of select=\"@xyz\"/&gt;&amp;n;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n&lt;/xsl:transform&gt;\n</code></pre>\n\n<p>Applied to:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;foo bar=\"bar\" baz=\"baz\" abc=\"abc\" xyz=\"xyz\"&gt;&lt;/foo&gt;\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>Flush left, despite the indentation.\n This line will be output indented two spaces.\n Starts with two blanks: bar.\nbaz The 'e' trick won't work here.\n baz Use s2 instead.\n abcxyz\n abc xyz\n</code></pre>\n\n<p>The 'e' trick works prior to a text node containing at least one non-whitespace character because it expands to this:</p>\n\n<pre><code>&lt;xsl:template match=\"/\"&gt;\n &lt;xsl:text&gt;&lt;/xsl:text&gt;Flush left, despite the indentation.&lt;xsl:text&gt;\n&lt;/xsl:text&gt;\n</code></pre>\n\n<p>Since the <a href=\"http://www.w3.org/TR/xslt#strip\" rel=\"nofollow\">rules for stripping whitespace</a> say that whitespace-only text nodes get stripped, the newline and indentation between the &lt;xsl:template&gt; and &lt;xsl:text&gt; get stripped (good). Since the rules say a text node with at least one whitespace character is preserved, the implicit text node containing <code>\" This line will be output indented two spaces.\"</code> keeps its leading whitespace (but I guess this also depends on the settings for strip/preserve/normalize). The \"&amp;n;\" at the end of the line inserts a newline, but it also ensures that any following whitespace is ignored, because it appears between two nodes.</p>\n\n<p>The trouble I have is when I want to output an indented line that begins with an &lt;xsl:value-of&gt;. In that case, the \"&amp;e;\" won't help, because the indentation whitespace isn't \"attached\" to any non-whitespace characters. So for those cases, I use \"&amp;s2;\" or \"&amp;s4;\", depending on how much indentation I want.</p>\n\n<p>It's an ugly hack I'm sure, but at least I don't have the verbose \"&lt;xsl:text&gt;\" tags littering my XSLT, and at least I can still indent the XSLT itself so it's legible. I feel like I'm abusing XSLT for something it was not designed for (text processing) and this is the best I can do.</p>\n\n<hr>\n\n<p><strong>Edit:</strong>\nIn response to comments, this is what it looks like without the \"macros\":</p>\n\n<pre><code>&lt;xsl:template match=\"/\"&gt;\n &lt;xsl:text&gt;Flush left, despite the indentation.&lt;/xsl:text&gt;\n &lt;xsl:text&gt; This line will be output indented two spaces.&lt;/xsl:text&gt;\n &lt;xsl:for-each select=\"//foo\"&gt;\n &lt;xsl:text&gt; Starts with two blanks: &lt;/xsl:text&gt;&lt;xsl:value-of select=\"@bar\"/&gt;.&lt;xsl:text&gt;\n&lt;/xsl:text&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;&lt;xsl:value-of select=\"@abc\"/&gt;&lt;xsl:text&gt; &lt;/xsl:text&gt;&lt;xsl:value-of select=\"@xyz\"/&gt;&lt;xsl:text&gt;\n&lt;/xsl:text&gt;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>I think that makes it less clear to see the intended output indentation, and it screws up the indentation of the XSL itself because the <code>&lt;/xsl:text&gt;</code> end tags have to appear at column 1 of the XSL file (otherwise you get undesired whitespace in the output file).</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26257/" ]
I'm trying to convert an XML file into the markup used by dokuwiki, using XSLT. This actually works to some degree, but the indentation in the XSL file is getting inserted into the results. At the moment, I have two choices: abandon this XSLT thing entirely, and find another way to convert from XML to dokuwiki markup, or delete about 95% of the whitespace from the XSL file, making it nigh-unreadable and a maintenance nightmare. Is there some way to keep the indentation in the XSL file without passing all that whitespace on to the final document? Background: I'm migrating an autodoc tool from static HTML pages over to dokuwiki, so the API developed by the server team can be further documented by the applications team whenever the apps team runs into poorly-documented code. The logic is to have a section of each page set aside for the autodoc tool, and to allow comments anywhere outside this block. I'm using XSLT because we already have the XSL file to convert from XML to XHTML, and I'm assuming it will be faster to rewrite the XSL than to roll my own solution from scratch. *Edit: Ah, right, foolish me, I neglected the indent attribute. (Other background note: I am new to XSLT.) On the other hand, I still have to deal with newlines. Dokuwiki uses pipes to differentiate between table columns, which means that all of the data in a table line must be on one line. Is there a way to suppress newlines being outputted (just occasionally), so I can do some fairly complex logic for each table cell in a somewhat readable fasion?*
There are three reasons for getting unwanted whitespace in the result of an XSLT transformation: 1. whitespace that comes from between nodes in the source document 2. whitespace that comes from within nodes in the source document 3. whitespace that comes from the stylesheet I'm going to talk about all three because it can be hard to tell where whitespace comes from so you might need to use several strategies. To address the whitespace that is between nodes in your source document, you should use `<xsl:strip-space>` to strip out any whitespace that appears between two nodes, and then use `<xsl:preserve-space>` to preserve the significant whitespace that might appear within mixed content. For example, if your source document looks like: ``` <ul> <li>This is an <strong>important</strong> <em>point</em></li> </ul> ``` then you will want to ignore the whitespace between the `<ul>` and the `<li>` and between the `</li>` and the `</ul>`, which is not significant, but preserve the whitespace between the `<strong>` and `<em>` elements, which *is* significant (otherwise you'd get "This is an \*\*important\*\*\*point\*"). To do this use ``` <xsl:strip-space elements="*" /> <xsl:preserve-space elements="li" /> ``` The `elements` attribute on `<xsl:preserve-space>` should basically list all the elements in your document that have mixed content. > > Aside: using `<xsl:strip-space>` also reduces the size of the source tree in memory, and makes your stylesheet more efficient, so it's worth doing even if you don't have whitespace problems of this sort. > > > To address the whitespace that appears within nodes in your source document, you should use `normalize-space()`. For example, if you have: ``` <dt> a definition </dt> ``` and you can be sure that the `<dt>` element won't hold any elements that you want to do something with, then you can do: ``` <xsl:template match="dt"> ... <xsl:value-of select="normalize-space(.)" /> ... </xsl:template> ``` The leading and trailing whitespace will be stripped from the value of the `<dt>` element and you will just get the string `"a definition"`. To address whitespace coming from the stylesheet, which is perhaps the one you're experiencing, is when you have text within a template like this: ``` <xsl:template match="name"> Name: <xsl:value-of select="." /> </xsl:template> ``` XSLT stylesheets are parsed in the same way as the source documents that they process, so the above XSLT is interpreted as a tree that holds an `<xsl:template>` element with a `match` attribute whose first child is a text node and whose second child is a `<xsl:value-of>` element with a `select` attribute. The text node has leading and trailing whitespace (including line breaks); since it's literal text in the stylesheet, it gets literally copied over into the result, with all the leading and trailing whitespace. But *some* whitespace in XSLT stylesheets get stripped automatically, namely those between nodes. You don't get a line break in your result because there's a line break between the `<xsl:value-of>` and the close of the `<xsl:template>`. To get only the text you want in the result, use the `<xsl:text>` element like this: ``` <xsl:template match="name"> <xsl:text>Name: </xsl:text> <xsl:value-of select="." /> </xsl:template> ``` The XSLT processor will ignore the line breaks and indentation that appear between nodes, and only output the text within the `<xsl:text>` element.
184,436
<p>I'm working with an old Access database (yes, it's very ugly and I hate it). I need to modify some of the columns from a VB app that I'm creating. I have most the modifications setup correctly, but I'm fighting with the fact that modifying a column to text has it default to "Allow Zero Length" to false.</p> <p>SO ALTER TABLE [Applicant Table] ALTER COLUMN [Applicant ID] Text(255)</p> <p>I need that alter to have "Allow Zero Length" set to true.</p> <p>I have tried ALTER TABLE [Applicant Table] ALTER COLUMN [Applicant ID] Text(255) NULL</p> <p>but that doesn't seem to work either. I've looked all over for the solution, but can't seem to find a straight answer.</p> <p>Any ideas?</p> <p>Thanks, Ryan.</p> <hr> <p>Thanks for the info. I'm glad that it's Access and not me.</p> <p>I guess I'm just going to hack my way through this application since the entire data model is trash anyway.</p>
[ { "answer_id": 184552, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "<p>Ages ago I wanted to do the same and ISTR that it simply wasn't possible from DDL/SQL - but you can do it from VBA by locating the field (table.fields) and setting AllowZeroLength to the required value</p>\n" }, { "answer_id": 184575, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 3, "selected": true, "text": "<p>This option isn't available with Jet sql. You can do it in the Access gui or with vba code. Example:</p>\n\n<pre><code>Public Function setAllowZeroLenStr() \n On Error GoTo Proc_Err\n\n Dim db As Database\n Dim tbl As TableDef\n Dim fld As DAO.Field\n\n Set db = CurrentDb\n Set tbl = db.TableDefs![Applicant Table]\n Set fld = tbl.Fields![Applicant ID]\n fld.AllowZeroLength = True\n\nProc_Exit: \n Set fld = Nothing\n Set tbl = Nothing\n Set db = Nothing\n\n Exit Function\n\nProc_Err: \n MsgBox Err.Number &amp; vbCrLf &amp; Err.Description\n Err.Clear\n Resume Proc_Exit \nEnd Function\n</code></pre>\n" }, { "answer_id": 184774, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "<p>I concur: there is no ACE/Jet syntax for this setting. If you think about it, the SQL DLL tends to be the Standard 'portable' stuff, things that can be achieved on most SQL products. Most SQLs don't have an explicit (Dis)AllowZeroLength feature so it hasn't made it into the Standard hence not in the ACE/Jet syntax. </p>\n\n<p>FWIW the 'portable' solution, which works for ACE/Jet too, is to use a CHECK constraint e.g. something like:</p>\n\n<pre><code>ALTER TABLE [Applicant Table] ADD\n CONSTRAINT Applicant_ID__not_zero_length \n CHECK (LEN([Applicant ID]) &gt; 0);\n</code></pre>\n\n<p>Allowing a zero length value would require not creating the CHECK constraint in the first place (!!) or <code>DROP</code>ing it if it already existed... but why would you want to allow an identifier (\"Applicant ID\") to be zero length anyhow?</p>\n" }, { "answer_id": 12194088, "author": "andy", "author_id": 1547591, "author_profile": "https://Stackoverflow.com/users/1547591", "pm_score": 0, "selected": false, "text": "<p>Use Interop.ACCDBLIB</p>\n\n<p>Try this:</p>\n\n<pre><code> DBLib dbLib = new DBLib();\n dbLib.ConnectionString = ConnectionString;\n dbLib.Initialize(); \n dbLib.ModifyTextFieledSetAllowZeroLength(ref TableName, ref FiledName);\n</code></pre>\n" }, { "answer_id": 66270762, "author": "John Argus", "author_id": 8613038, "author_profile": "https://Stackoverflow.com/users/8613038", "pm_score": 0, "selected": false, "text": "<pre><code>Sub SetUpTempDbExample()\n' Set up a temp database for running report data into.\n' Temp DB is killed and re-created on demand (saves having to compact and repair in primary DB).\n' Temp table can be relinked to primary DB for further querying\nDim dbTemp As Database\nDim tblTemp As TableDef\nDim idxTemp As Index, idxTemp2 As Index\nConst cTempPath = &quot;C:\\temp\\&quot;\nConst cTempDB = &quot;TempReportData&quot;\n\n ' Delete old temp database (if db is in use, Kill will fail. Resume gracefully.)\n On Error Resume Next\n If Dir(cTempPath &amp; cTempDB) &lt;&gt; &quot;&quot; Then Kill (cTempPath &amp; cTempDB)\n\n On Error GoTo ErrHandler\n \n ' Create a new temp DB.\n Set dbTemp = CreateDatabase(cTempPath &amp; cTempDB, dbLangGeneral)\n\n Set tblTemp = dbTemp.CreateTableDef(&quot;TEMP_SAMPLES&quot;)\n \n With tblTemp\n .Fields.Append .CreateField(&quot;SAMPLE_ID&quot;, dbDouble)\n .Fields.Append .CreateField(&quot;SITE_ID&quot;, dbText, 38)\n .Fields.Append .CreateField(&quot;SAMPLE_DATE_TIME&quot;, dbDate)\n .Fields.Append .CreateField(&quot;METHOD&quot;, dbText, 20)\n .Fields.Append .CreateField(&quot;MATRIX&quot;, dbText, 20)\n .Fields.Append .CreateField(&quot;COMMENT&quot;, dbText, 255)\n .Fields![COMMENT].AllowZeroLength = True\n Set idxTemp = .CreateIndex(&quot;SAMPLE_ID&quot;)\n idxTemp.Fields.Append .CreateField(&quot;SAMPLE_ID&quot;)\n idxTemp.Primary = True\n Set idxTemp2 = .CreateIndex(&quot;SITE_ID&quot;)\n idxTemp2.Fields.Append .CreateField(&quot;SITE_ID&quot;)\n End With\n dbTemp.TableDefs.Append tblTemp\n tblTemp.Indexes.Append idxTemp\n tblTemp.Indexes.Append idxTemp2\n\n Set tblTemp = Nothing\n Set idxTemp = Nothing\n Set dbTemp = Nothing\n\nExitSub:\n Exit Sub\n\nErrHandler:\n MsgBox Err.Description &amp; &quot; (&quot; &amp; Err.Number &amp; &quot;)&quot;\n Resume ExitSub\nEnd Sub\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
I'm working with an old Access database (yes, it's very ugly and I hate it). I need to modify some of the columns from a VB app that I'm creating. I have most the modifications setup correctly, but I'm fighting with the fact that modifying a column to text has it default to "Allow Zero Length" to false. SO ALTER TABLE [Applicant Table] ALTER COLUMN [Applicant ID] Text(255) I need that alter to have "Allow Zero Length" set to true. I have tried ALTER TABLE [Applicant Table] ALTER COLUMN [Applicant ID] Text(255) NULL but that doesn't seem to work either. I've looked all over for the solution, but can't seem to find a straight answer. Any ideas? Thanks, Ryan. --- Thanks for the info. I'm glad that it's Access and not me. I guess I'm just going to hack my way through this application since the entire data model is trash anyway.
This option isn't available with Jet sql. You can do it in the Access gui or with vba code. Example: ``` Public Function setAllowZeroLenStr() On Error GoTo Proc_Err Dim db As Database Dim tbl As TableDef Dim fld As DAO.Field Set db = CurrentDb Set tbl = db.TableDefs![Applicant Table] Set fld = tbl.Fields![Applicant ID] fld.AllowZeroLength = True Proc_Exit: Set fld = Nothing Set tbl = Nothing Set db = Nothing Exit Function Proc_Err: MsgBox Err.Number & vbCrLf & Err.Description Err.Clear Resume Proc_Exit End Function ```
184,471
<p>Replaces Question: <a href="https://stackoverflow.com/questions/184096/update-multiple-rows-into-sql-table">Update multiple rows into SQL table</a></p> <p>Here's a Code Snippet to update an exam results set. DB structure is as given, but I can submit Stored Procedures for inclusion (Which are a pain to modify, so I save that until the end.)</p> <p>The question: Is there a better way using SQL server v 2005.,net 2.0 ?</p> <pre><code>string update = @"UPDATE dbo.STUDENTAnswers SET ANSWER=@answer WHERE StudentID =@ID and QuestionNum =@qnum"; SqlCommand updateCommand = new SqlCommand( update, conn ); conn.Open(); string uid = Session["uid"].ToString(); for (int i= tempStart; i &lt;= tempEnd; i++) { updateCommand.Parameters.Clear(); updateCommand.Parameters.AddWithValue("@ID",uid); updateCommand.Parameters.AddWithValue("@qnum",i); updateCommand.Parameters.AddWithValue("@answer", Request.Form[i.ToString()]); try { updateCommand.ExecuteNonQuery(); } catch { } } </code></pre>
[ { "answer_id": 184503, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": -1, "selected": false, "text": "<p>emit a single update that goes against a values table:</p>\n\n<pre><code>UPDATE s SET ANSWER=a FROM dbo.STUDENTAnswers s JOIN (\n SELECT 1 as q, 'answer1' as a\n UNION ALL SELECT 2, 'answer2' -- etc...\n) x ON s.QuestionNum=x.q AND StudentID=@ID\n</code></pre>\n\n<p>so you just put this together like this:</p>\n\n<pre><code>using(SqlCommand updateCommand = new SqlCommand()) {\n updateCommand.CommandType = CommandType.Text;\n updateCommand.Connection = conn;\n if (cn.State != ConnectionState.Open) conn.Open();\n\n StringBuilder sb = new StringBuilder(\"UPDATE s SET ANSWER=a FROM dbo.STUDENTAnswers s JOIN (\");\n string fmt = \"SELECT {0} as q, @A{0} as a\";\n for(int i=tempStart; i&lt;tempEnd; i++) {\n sb.AppendFormat(fmt, i);\n fmt=\" UNION ALL SELECT {0},@A{0}\";\n updateCommand.Parameters.AddWithValue(\"@A\"+i.ToString(), Request.Form[i.ToString()]);\n }\n sb.Append(\") x ON s.QuestionNum=x.q AND StudentID=@ID\");\n updateCommand.CommandText = sb.ToString();\n updateCommand.Parameters.AddWithValue(\"@ID\", uid);\n updateCommand.ExecuteNonQuery();\n}\n</code></pre>\n\n<p>This has the advantages of being an all other nothing operation (like if you'd wrapped several updates in a transaction) and will run faster since:</p>\n\n<ul>\n<li>The table and associated indexes are looked at/updated once</li>\n<li>You only pay for the latency between your application and the database server once, rather than on each update</li>\n</ul>\n" }, { "answer_id": 184531, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "<p>An issue I see is when you are opening your connection. </p>\n\n<p>I would at least before every update call the open and then close the connection after the update. </p>\n\n<p>If your loop takes time to execute you will have your connection open for a long time. </p>\n\n<p>It is a good rule to never open your command until you need it.</p>\n" }, { "answer_id": 184532, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 0, "selected": false, "text": "<p>You can bulk insert using <a href=\"http://msdn.microsoft.com/en-us/library/aa276847(SQL.80).aspx\" rel=\"nofollow noreferrer\">OpenXML</a>. Create an xml document containing all your questions and answers and use that to insert the values.</p>\n\n<p><strong>Edit:</strong> If you stick with your current solution, I would at least wrap your SqlConnection and SqlCommand in a using block to make sure they get disposed.</p>\n" }, { "answer_id": 184657, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": 2, "selected": false, "text": "<p>For 30 updates I think you're on the right track, although the comment about the need for a using around <code>updateCommand</code> is correct.</p>\n\n<p>We've found the best performing way to do bulk updates (&gt;100 rows) is via the <code>SqlBulkCopy</code> class to a temporary table followed by a stored procedure call to populate the live table.</p>\n" }, { "answer_id": 184659, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "<p>A few things stand out:</p>\n\n<ul>\n<li><p>You don't show where the SqlConnection is instantiated, so it's not clear that you're disposing it properly.</p></li>\n<li><p>You shouldn't be swallowing exceptions in the loop - better to handle them in a top level exception handler.</p></li>\n<li><p>You're instantiating new parameters on each iteration through the loop - you could just reuse the parameters.</p></li>\n</ul>\n\n<p>Putting this together it could look something like the following (if you don't want to use a transaction, i.e. don't care if some but not all updates succeed):</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection(connectionString))\n{\n conn.Open();\n using (SqlCommand updateCommand = new SqlCommand(update, conn))\n {\n string uid = Session[\"uid\"].ToString();\n updateCommand.Parameters.AddWithValue(\"@ID\", uid);\n updateCommand.Parameters.AddWithValue(\"@qnum\", i);\n updateCommand.Parameters.Add(\"@answer\", System.Data.SqlDbType.VarChar);\n for (int i = tempStart; i &lt;= tempEnd; i++)\n {\n updateCommand.Parameters[\"@answer\"] = Request.Form[i.ToString()];\n updateCommand.ExecuteNonQuery();\n }\n }\n}\n</code></pre>\n\n<p>Or to use a transaction to ensure all or nothing:</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection(connectionString))\n{\n conn.Open();\n using (SqlTransaction transaction = conn.BeginTransaction())\n {\n using (SqlCommand updateCommand = new SqlCommand(update, conn, transaction))\n {\n string uid = Session[\"uid\"].ToString();\n updateCommand.Parameters.AddWithValue(\"@ID\", uid);\n updateCommand.Parameters.AddWithValue(\"@qnum\", i);\n updateCommand.Parameters.Add(\"@answer\", System.Data.SqlDbType.VarChar);\n for (int i = tempStart; i &lt;= tempEnd; i++)\n {\n updateCommand.Parameters[\"@answer\"] = Request.Form[i.ToString()];\n updateCommand.ExecuteNonQuery();\n }\n transaction.Commit();\n }\n } // Transaction will be disposed and rolled back here if an exception is thrown\n}\n</code></pre>\n\n<p>Finally, another problem is that you are mixing UI code (e.g. Request.Form) with data access code. It would be more modular and testable to separate these - e.g. by splitting your application into UI, Business Logic and Data Access layers.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907/" ]
Replaces Question: [Update multiple rows into SQL table](https://stackoverflow.com/questions/184096/update-multiple-rows-into-sql-table) Here's a Code Snippet to update an exam results set. DB structure is as given, but I can submit Stored Procedures for inclusion (Which are a pain to modify, so I save that until the end.) The question: Is there a better way using SQL server v 2005.,net 2.0 ? ``` string update = @"UPDATE dbo.STUDENTAnswers SET ANSWER=@answer WHERE StudentID =@ID and QuestionNum =@qnum"; SqlCommand updateCommand = new SqlCommand( update, conn ); conn.Open(); string uid = Session["uid"].ToString(); for (int i= tempStart; i <= tempEnd; i++) { updateCommand.Parameters.Clear(); updateCommand.Parameters.AddWithValue("@ID",uid); updateCommand.Parameters.AddWithValue("@qnum",i); updateCommand.Parameters.AddWithValue("@answer", Request.Form[i.ToString()]); try { updateCommand.ExecuteNonQuery(); } catch { } } ```
A few things stand out: * You don't show where the SqlConnection is instantiated, so it's not clear that you're disposing it properly. * You shouldn't be swallowing exceptions in the loop - better to handle them in a top level exception handler. * You're instantiating new parameters on each iteration through the loop - you could just reuse the parameters. Putting this together it could look something like the following (if you don't want to use a transaction, i.e. don't care if some but not all updates succeed): ``` using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlCommand updateCommand = new SqlCommand(update, conn)) { string uid = Session["uid"].ToString(); updateCommand.Parameters.AddWithValue("@ID", uid); updateCommand.Parameters.AddWithValue("@qnum", i); updateCommand.Parameters.Add("@answer", System.Data.SqlDbType.VarChar); for (int i = tempStart; i <= tempEnd; i++) { updateCommand.Parameters["@answer"] = Request.Form[i.ToString()]; updateCommand.ExecuteNonQuery(); } } } ``` Or to use a transaction to ensure all or nothing: ``` using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction transaction = conn.BeginTransaction()) { using (SqlCommand updateCommand = new SqlCommand(update, conn, transaction)) { string uid = Session["uid"].ToString(); updateCommand.Parameters.AddWithValue("@ID", uid); updateCommand.Parameters.AddWithValue("@qnum", i); updateCommand.Parameters.Add("@answer", System.Data.SqlDbType.VarChar); for (int i = tempStart; i <= tempEnd; i++) { updateCommand.Parameters["@answer"] = Request.Form[i.ToString()]; updateCommand.ExecuteNonQuery(); } transaction.Commit(); } } // Transaction will be disposed and rolled back here if an exception is thrown } ``` Finally, another problem is that you are mixing UI code (e.g. Request.Form) with data access code. It would be more modular and testable to separate these - e.g. by splitting your application into UI, Business Logic and Data Access layers.
184,476
<p>I have been pushing into the .NET framework in PowerShell, and I have hit something that I don't understand. This works fine:</p> <pre><code>$foo = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]" $foo.Add("FOO", "BAR") $foo Key Value --- ----- FOO BAR </code></pre> <p>This however does not:</p> <pre><code>$bar = New-Object "System.Collections.Generic.SortedDictionary``2[System.String,System.String]" New-Object : Cannot find type [System.Collections.Generic.SortedDictionary`2[System.String,System.String]]: make sure t he assembly containing this type is loaded. At line:1 char:18 + $bar = New-Object &lt;&lt;&lt;&lt; "System.Collections.Generic.SortedDictionary``2[System.String,System.String]" </code></pre> <p>They are both in the same assembly, so what am I missing?</p> <p>As was pointed out in the answers, this is pretty much only an issue with PowerShell v1.</p>
[ { "answer_id": 185174, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>There are some issues with Generics in PowerShell. Lee Holmes, a dev on the PowerShell team posted <a href=\"http://www.leeholmes.com/blog/CreatingGenericTypesInPowerShell.aspx\" rel=\"nofollow noreferrer\">this script</a> to create Generics.</p>\n" }, { "answer_id": 185885, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 5, "selected": true, "text": "<p>Dictionary&lt;K,V> is not defined in the same assembly as SortedDictionary&lt;K,V>. One is in mscorlib and the other in system.dll.</p>\n\n<p>Therein lies the problem. The current behavior in PowerShell is that when resolving the generic parameters specified, if the types are not fully qualified type names, it sort of assumes that they are in the same assembly as the generic type you're trying to instantiate.</p>\n\n<p>In this case, it means it's looking for System.String in System.dll, and not in mscorlib, so it fails.</p>\n\n<p>The solution is to specify the fully qualified assembly name for the generic parameter types. It's extremely ugly, but works:</p>\n\n<pre><code>$bar = new-object \"System.Collections.Generic.Dictionary``2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\"\n</code></pre>\n" }, { "answer_id": 2202519, "author": "ShanePowser", "author_id": 266497, "author_profile": "https://Stackoverflow.com/users/266497", "pm_score": 6, "selected": false, "text": "<p>In PowerShell 2.0 the new way to create a <code>Dictionary</code> is:</p>\n\n<pre><code>$object = New-Object 'system.collections.generic.dictionary[string,int]'\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ]
I have been pushing into the .NET framework in PowerShell, and I have hit something that I don't understand. This works fine: ``` $foo = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]" $foo.Add("FOO", "BAR") $foo Key Value --- ----- FOO BAR ``` This however does not: ``` $bar = New-Object "System.Collections.Generic.SortedDictionary``2[System.String,System.String]" New-Object : Cannot find type [System.Collections.Generic.SortedDictionary`2[System.String,System.String]]: make sure t he assembly containing this type is loaded. At line:1 char:18 + $bar = New-Object <<<< "System.Collections.Generic.SortedDictionary``2[System.String,System.String]" ``` They are both in the same assembly, so what am I missing? As was pointed out in the answers, this is pretty much only an issue with PowerShell v1.
Dictionary<K,V> is not defined in the same assembly as SortedDictionary<K,V>. One is in mscorlib and the other in system.dll. Therein lies the problem. The current behavior in PowerShell is that when resolving the generic parameters specified, if the types are not fully qualified type names, it sort of assumes that they are in the same assembly as the generic type you're trying to instantiate. In this case, it means it's looking for System.String in System.dll, and not in mscorlib, so it fails. The solution is to specify the fully qualified assembly name for the generic parameter types. It's extremely ugly, but works: ``` $bar = new-object "System.Collections.Generic.Dictionary``2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]" ```
184,482
<p>I display data into an html table, w/ a drop down box with a list of venues. Each volunteer will be assigned a venue. I envision being able to go down thru the html table and assigning each volunteer a venue. The drop down box contains all the possible venues that they can be assigned to.</p> <pre><code>&lt;select&gt; &lt;option value="1"&gt;Setup&lt;/option&gt; &lt;option value="2"&gt;Check in&lt;/option&gt; etc... &lt;/select&gt; </code></pre> <p>Then once I am done assigning each volunteer, I want to hit submit and it will assign the appropriate value for each volunteer.</p> <p>How would I go about doing that, I know how to do that, but only one at a time.</p>
[ { "answer_id": 184517, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>I can't think of any way. You can put multiple SQL statements into 1 MySQL query:</p>\n\n<pre><code>UPDATE volunteer SET venue = 1 WHERE id = 2;\nUPDATE volunteer SET venue = 2 WHERE id = 3;\n...\n</code></pre>\n\n<p>I wish there was a way, but I'm thinking that the where will be too different in each query to make it into one.</p>\n" }, { "answer_id": 184518, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 3, "selected": true, "text": "<p>Change the name of each select, in a way it includes a volunteer id:</p>\n\n<pre><code>&lt;select name=\"venues[1]\"&gt;\n&lt;option value=\"1\"&gt;Setup&lt;/option&gt;\netc...\n&lt;/select&gt;\n\n&lt;select name=\"venues[2]\"&gt;\n&lt;option value=\"1\"&gt;Setup&lt;/option&gt;\netc...\n&lt;/select&gt;\n\n&lt;select name=\"venues[3]\"&gt;\n&lt;option value=\"1\"&gt;Setup&lt;/option&gt;\netc...\n&lt;/select&gt;\n</code></pre>\n\n<p>After submit there will be a table in $_POST named venues and with indices: 1, 2, 3 (beeing volunteer id) and values beeing selected value for each volunteer.</p>\n\n<p>Now you can iterate on <code>$_POST['venues']</code> array and save each value:</p>\n\n<pre><code>foreach ($_POST['venues'] as $volunteer_id =&gt; $venue) {\n save_venue_for_volunteer($volunteer_id, $venue);\n}\n</code></pre>\n" }, { "answer_id": 184569, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 1, "selected": false, "text": "<p>Here's a very rough example of how you might handle this. Note: your MySQL tables (assuming MySQL) must be of a type that supports transactions (InnoDB does, MyISAM does not).</p>\n\n<pre><code>&lt;?php\n\nif ( isset( $_POST['venuChoice'] ) )\n{\n // Create a transaction\n mysql_query( 'BEGIN' );\n\n $failure = false;\n\n // Loop over the selections\n foreach ( $_POST['venuChoice'] as $employeeId =&gt; $venueId )\n {\n $sql = sprintf(\n 'UPDATE table SET columns=%d WHERE id=%d'\n , intval( mysql_real_escape_string( $venueId ) )\n , intval( mysql_real_escape_string( $employeeId ) )\n );\n if ( ! @mysql_query( $sql ) )\n {\n $failure = true;\n break;\n }\n }\n\n // Close out the transaction\n if ( $failure )\n {\n mysql_query( 'ROLLBACK' );\n // Display and error or something\n } else {\n mysql_query( 'COMMIT' );\n // Success!\n }\n}\n\n?&gt;\n\n&lt;form&gt;\n &lt;select name=\"venueChoice[1]\"&gt;\n &lt;option value=\"1\"&gt;Setup&lt;/option&gt;\n &lt;option value=\"2\"&gt;Check in&lt;/option&gt;\n &lt;/select&gt;\n &lt;select name=\"venueChoice[2]\"&gt;\n &lt;option value=\"1\"&gt;Setup&lt;/option&gt;\n &lt;option value=\"2\"&gt;Check in&lt;/option&gt;\n &lt;/select&gt;\n &lt;select name=\"venueChoice[3]\"&gt;\n &lt;option value=\"1\"&gt;Setup&lt;/option&gt;\n &lt;option value=\"2\"&gt;Check in&lt;/option&gt;\n &lt;/select&gt;\n\n&lt;/form&gt;\n</code></pre>\n\n<p>You could also modify this to keep track of each employee's current venue choice, compare it to the POST data, and then only execute UPDATE queries for those that were actually changed.</p>\n" }, { "answer_id": 245601, "author": "Brad", "author_id": 26130, "author_profile": "https://Stackoverflow.com/users/26130", "pm_score": 0, "selected": false, "text": "<pre><code>foreach ($_POST['venues'] as $volunteer_id =&gt; $venue) {\n save_venue_for_volunteer($volunteer_id, $venue);\n}\n\nfunction save_venue_for_volunteer($volunteer_id, $venue) {\n $result = mysql_query(\"UPDATE volunteers_2009 SET venue_id='$venue' WHERE id='$volunteer_id'\") \n or die(mysql_error());\n}\n</code></pre>\n\n<p>The table it will be saved to is volunteers_2009, so this is how it should be?</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I display data into an html table, w/ a drop down box with a list of venues. Each volunteer will be assigned a venue. I envision being able to go down thru the html table and assigning each volunteer a venue. The drop down box contains all the possible venues that they can be assigned to. ``` <select> <option value="1">Setup</option> <option value="2">Check in</option> etc... </select> ``` Then once I am done assigning each volunteer, I want to hit submit and it will assign the appropriate value for each volunteer. How would I go about doing that, I know how to do that, but only one at a time.
Change the name of each select, in a way it includes a volunteer id: ``` <select name="venues[1]"> <option value="1">Setup</option> etc... </select> <select name="venues[2]"> <option value="1">Setup</option> etc... </select> <select name="venues[3]"> <option value="1">Setup</option> etc... </select> ``` After submit there will be a table in $\_POST named venues and with indices: 1, 2, 3 (beeing volunteer id) and values beeing selected value for each volunteer. Now you can iterate on `$_POST['venues']` array and save each value: ``` foreach ($_POST['venues'] as $volunteer_id => $venue) { save_venue_for_volunteer($volunteer_id, $venue); } ```
184,489
<p>I am trying to retrieve an image stored in an oracle blob and place it in a new System.Drawing.Image instance. I know I can write the stream to a temp.bmp file on the disk and read it from there but thats just not l33t enough for me. How do I convert the blob object directly to an image?</p>
[ { "answer_id": 184577, "author": "osp70", "author_id": 2357, "author_profile": "https://Stackoverflow.com/users/2357", "pm_score": 0, "selected": false, "text": "<p>I know this uses sql but it should be similar for your needs</p>\n\n<pre><code>Dim cn As SqlConnection = Nothing\n Dim cmd As SqlCommand = Nothing\n Dim da As SqlDataAdapter = Nothing\n Dim ms As MemoryStream = Nothing\n Dim dsImage As Data.DataSet = Nothing\n Dim myBytes() As Byte = Nothing\n Dim imgJPG As System.Drawing.Image = Nothing\n Dim msOut As MemoryStream = Nothing\n\n Try\n cn = New SqlConnection(ConnectionStrings(\"conImageDB\").ToString)\n cmd = New SqlCommand(AppSettings(\"sprocGetImage\").ToString, cn)\n cmd.CommandType = Data.CommandType.StoredProcedure\n\n cmd.Parameters.AddWithValue(\"@dmhiRowno\", irowno)\n\n da = New SqlDataAdapter(cmd)\n\n dsImage = New Data.DataSet\n da.Fill(dsImage, \"image\")\n\n If dsImage.Tables(0).Rows.Count = 0 Then\n Throw New Exception(\"No results returned for rowno\")\n End If\n myBytes = dsImage.Tables(0).Rows(0)(\"Frontimage\")\n\n ms = New MemoryStream\n ms.Write(myBytes, 0, myBytes.Length)\n\n imgJPG = System.Drawing.Image.FromStream(ms)\n\n 'Export to JPG Stream\n msOut = New MemoryStream\n imgJPG.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg)\n imgJPG.Dispose()\n imgJPG = Nothing\n ms.Close()\n sFrontImage = Convert.ToBase64String(msOut.ToArray())\n\n dsImage = New Data.DataSet\n da.Fill(dsImage, \"image\")\n myBytes = dsImage.Tables(0).Rows(0)(\"Backimage\")\n\n ms = New MemoryStream\n ms.Write(myBytes, 0, myBytes.Length)\n\n imgJPG = System.Drawing.Image.FromStream(ms)\n sBackImage = Convert.ToBase64String(ms.ToArray)\n\n Catch ex As System.IO.IOException ' : An I/O error occurs.\n Throw ex\n Catch ex As System.ArgumentNullException ': buffer is null.\n Throw ex\n Catch ex As System.NotSupportedException ': The stream does not support writing. For additional information see System.IO.Stream.CanWrite.-or- The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified.\n Throw ex\n Catch ex As System.ArgumentOutOfRangeException ': offset or count are negative.\n Throw ex\n Catch ex As System.ObjectDisposedException ' : The current stream instance is closed.\n Throw ex\n Catch ex As System.ArgumentException\n Throw ex\n Catch ex As System.Runtime.InteropServices.ExternalException ': The image was saved with the wrong image format\n Throw ex\n Catch ex As Exception\n Throw ex\n Finally\n If cn IsNot Nothing Then\n cn.Close()\n cn.Dispose()\n cn = Nothing\n End If\n\n If cmd IsNot Nothing Then\n cmd.Dispose()\n cmd = Nothing\n End If\n\n If da IsNot Nothing Then\n da.Dispose()\n da = Nothing\n End If\n\n If ms IsNot Nothing Then\n ms.Dispose()\n ms = Nothing\n End If\n\n If msOut IsNot Nothing Then\n msOut.Close()\n msOut.Dispose()\n msOut = Nothing\n End If\n\n If dsImage IsNot Nothing Then\n dsImage.Dispose()\n dsImage = Nothing\n End If\n\n If myBytes IsNot Nothing Then\n myBytes = Nothing\n End If\n\n If imgJPG IsNot Nothing Then\n imgJPG.Dispose()\n imgJPG = Nothing\n End If\n\n End Try\n</code></pre>\n\n<p>This code pulls back a tiff wrapped jpeg for the front image so the code is a bit different than for the back image.</p>\n" }, { "answer_id": 1443596, "author": "Mac", "author_id": 8696, "author_profile": "https://Stackoverflow.com/users/8696", "pm_score": 2, "selected": true, "text": "<p>Assuming :</p>\n\n<ul>\n<li>you are using the Microsoft client (<code>System.Data.OracleClient</code>).</li>\n<li>you have a proper <code>OracleConnection</code> instance (<code>connection</code>).</li>\n<li>you have an <code>OracleCommand</code> ready (<code>command</code>, based on <code>SELECT my_blob FROM my_table WHERE id=xx</code>).</li>\n</ul>\n\n<p>This should go like this :</p>\n\n<pre><code>using (OracleDataReader odr=command.ExecuteReader())\n{\n reader.Read();\n\n if (!dr.IsDBNull(0))\n using (Stream s=(Stream)dr.GetOracleValue(0))\n using (Image image=Image.FromStream(s))\n return Copy(image);\n}\n</code></pre>\n\n<p>where Copy is </p>\n\n<pre><code>public static Image Copy(Image original)\n{\n Image ret=new Bitmap(original.Width, original.Height);\n using (Graphics g=Graphics.FromImage(ret))\n {\n g.DrawImageUnscaled(original, 0, 0);\n g.Save();\n }\n\n return ret;\n}\n</code></pre>\n\n<p>See <a href=\"http://macinsoft.blogspot.com/2009/09/beware-image-object.html\" rel=\"nofollow noreferrer\">my blog post</a> and/or <a href=\"http://support.microsoft.com/?id=814675\" rel=\"nofollow noreferrer\">KB 814675</a> for why a Copy is necessary.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I am trying to retrieve an image stored in an oracle blob and place it in a new System.Drawing.Image instance. I know I can write the stream to a temp.bmp file on the disk and read it from there but thats just not l33t enough for me. How do I convert the blob object directly to an image?
Assuming : * you are using the Microsoft client (`System.Data.OracleClient`). * you have a proper `OracleConnection` instance (`connection`). * you have an `OracleCommand` ready (`command`, based on `SELECT my_blob FROM my_table WHERE id=xx`). This should go like this : ``` using (OracleDataReader odr=command.ExecuteReader()) { reader.Read(); if (!dr.IsDBNull(0)) using (Stream s=(Stream)dr.GetOracleValue(0)) using (Image image=Image.FromStream(s)) return Copy(image); } ``` where Copy is ``` public static Image Copy(Image original) { Image ret=new Bitmap(original.Width, original.Height); using (Graphics g=Graphics.FromImage(ret)) { g.DrawImageUnscaled(original, 0, 0); g.Save(); } return ret; } ``` See [my blog post](http://macinsoft.blogspot.com/2009/09/beware-image-object.html) and/or [KB 814675](http://support.microsoft.com/?id=814675) for why a Copy is necessary.
184,491
<p>We have a Java Applet built using AWT. This applet lets you select pictures from your hard drive and upload them to a server. The applet includes a scrollable list of pictures, which works fine in Windows, Linux and Mac OS X 10.5. We launch this applet via Java Web Start or within a web page. </p> <p>Our applet does not behave properly in Mac OS X 10.4, regardless of the version of Java (1.4 or 1.5). You can find a screenshot of the incorrect behaviour, when scrolling, here:</p> <p><a href="http://www.lavablast.com/tmp/ui_error.png" rel="nofollow noreferrer">http://www.lavablast.com/tmp/ui_error.png</a></p> <p>Simply put, sometimes when scrolling the pictures end up overlapping the header or footer of the application. This behaviour does not occur on other platforms. On Mac OS X 10.4, it shows the pictures in the incorrect location when scrolling, which would not be so bad if it refreshed the screen after painting the image at that location. However, it does not appear that the application knows it painted it incorrectly and thus does not refresh.</p> <p>If the window is minimized, resized or even moved, the application is refreshed and the incorrectly positioned elements vanish and the application resumes normally. I spent quite some time trying to force a refresh of the background image unsuccessfully. (the repaint the image directly, repaint all children of a few panels, etc. ) Thus, I am looking for any tips that would help me resolve this problem under Mac OS X 10.4 or, in the worst case, simply simulate a full applet refresh. </p> <p>Until recently, everything was compatible with Java 1.1 but this has changed in a few locations which now require 1.4. I don't feel these changes created the issue, I am just providing this as extra information. If you are interested in implementation details of the scroll panel, I will investigate, but I am assuming this is a common platform bug for which workarounds must be known.</p> <p>To replicate the problem, open the following Java Web Start application: <a href="http://www.lavablast.com/tmp/opal-webstart.php.jnlp" rel="nofollow noreferrer">http://www.lavablast.com/tmp/opal-webstart.php.jnlp</a></p> <p>Select a folder containing lots of images and play with the scrollbar. At some point (fairly quickly), you should get the refresh problem. </p> <p>Edit: I followed the first suggestion here and replaced all my controls that feature background images with a Swing equivalent and the issue is still there. (Plus, there are numerous other fixes I would need to do to do a complete change). Any other ideas? A simple one line of code that forces a full refresh would be great :)</p> <p>Edit2: The main thread creates the panels and launches X threads. Using an observer/notifier pattern, the threads complete and notify the main control, which adds a panel to the page. This is done via an EventQueue.invokeLater which, unless I am mistaken, should run on the right thread. The issue is at its most severe when scrolling even if no extra threads are running (as during the loading). </p>
[ { "answer_id": 184577, "author": "osp70", "author_id": 2357, "author_profile": "https://Stackoverflow.com/users/2357", "pm_score": 0, "selected": false, "text": "<p>I know this uses sql but it should be similar for your needs</p>\n\n<pre><code>Dim cn As SqlConnection = Nothing\n Dim cmd As SqlCommand = Nothing\n Dim da As SqlDataAdapter = Nothing\n Dim ms As MemoryStream = Nothing\n Dim dsImage As Data.DataSet = Nothing\n Dim myBytes() As Byte = Nothing\n Dim imgJPG As System.Drawing.Image = Nothing\n Dim msOut As MemoryStream = Nothing\n\n Try\n cn = New SqlConnection(ConnectionStrings(\"conImageDB\").ToString)\n cmd = New SqlCommand(AppSettings(\"sprocGetImage\").ToString, cn)\n cmd.CommandType = Data.CommandType.StoredProcedure\n\n cmd.Parameters.AddWithValue(\"@dmhiRowno\", irowno)\n\n da = New SqlDataAdapter(cmd)\n\n dsImage = New Data.DataSet\n da.Fill(dsImage, \"image\")\n\n If dsImage.Tables(0).Rows.Count = 0 Then\n Throw New Exception(\"No results returned for rowno\")\n End If\n myBytes = dsImage.Tables(0).Rows(0)(\"Frontimage\")\n\n ms = New MemoryStream\n ms.Write(myBytes, 0, myBytes.Length)\n\n imgJPG = System.Drawing.Image.FromStream(ms)\n\n 'Export to JPG Stream\n msOut = New MemoryStream\n imgJPG.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg)\n imgJPG.Dispose()\n imgJPG = Nothing\n ms.Close()\n sFrontImage = Convert.ToBase64String(msOut.ToArray())\n\n dsImage = New Data.DataSet\n da.Fill(dsImage, \"image\")\n myBytes = dsImage.Tables(0).Rows(0)(\"Backimage\")\n\n ms = New MemoryStream\n ms.Write(myBytes, 0, myBytes.Length)\n\n imgJPG = System.Drawing.Image.FromStream(ms)\n sBackImage = Convert.ToBase64String(ms.ToArray)\n\n Catch ex As System.IO.IOException ' : An I/O error occurs.\n Throw ex\n Catch ex As System.ArgumentNullException ': buffer is null.\n Throw ex\n Catch ex As System.NotSupportedException ': The stream does not support writing. For additional information see System.IO.Stream.CanWrite.-or- The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified.\n Throw ex\n Catch ex As System.ArgumentOutOfRangeException ': offset or count are negative.\n Throw ex\n Catch ex As System.ObjectDisposedException ' : The current stream instance is closed.\n Throw ex\n Catch ex As System.ArgumentException\n Throw ex\n Catch ex As System.Runtime.InteropServices.ExternalException ': The image was saved with the wrong image format\n Throw ex\n Catch ex As Exception\n Throw ex\n Finally\n If cn IsNot Nothing Then\n cn.Close()\n cn.Dispose()\n cn = Nothing\n End If\n\n If cmd IsNot Nothing Then\n cmd.Dispose()\n cmd = Nothing\n End If\n\n If da IsNot Nothing Then\n da.Dispose()\n da = Nothing\n End If\n\n If ms IsNot Nothing Then\n ms.Dispose()\n ms = Nothing\n End If\n\n If msOut IsNot Nothing Then\n msOut.Close()\n msOut.Dispose()\n msOut = Nothing\n End If\n\n If dsImage IsNot Nothing Then\n dsImage.Dispose()\n dsImage = Nothing\n End If\n\n If myBytes IsNot Nothing Then\n myBytes = Nothing\n End If\n\n If imgJPG IsNot Nothing Then\n imgJPG.Dispose()\n imgJPG = Nothing\n End If\n\n End Try\n</code></pre>\n\n<p>This code pulls back a tiff wrapped jpeg for the front image so the code is a bit different than for the back image.</p>\n" }, { "answer_id": 1443596, "author": "Mac", "author_id": 8696, "author_profile": "https://Stackoverflow.com/users/8696", "pm_score": 2, "selected": true, "text": "<p>Assuming :</p>\n\n<ul>\n<li>you are using the Microsoft client (<code>System.Data.OracleClient</code>).</li>\n<li>you have a proper <code>OracleConnection</code> instance (<code>connection</code>).</li>\n<li>you have an <code>OracleCommand</code> ready (<code>command</code>, based on <code>SELECT my_blob FROM my_table WHERE id=xx</code>).</li>\n</ul>\n\n<p>This should go like this :</p>\n\n<pre><code>using (OracleDataReader odr=command.ExecuteReader())\n{\n reader.Read();\n\n if (!dr.IsDBNull(0))\n using (Stream s=(Stream)dr.GetOracleValue(0))\n using (Image image=Image.FromStream(s))\n return Copy(image);\n}\n</code></pre>\n\n<p>where Copy is </p>\n\n<pre><code>public static Image Copy(Image original)\n{\n Image ret=new Bitmap(original.Width, original.Height);\n using (Graphics g=Graphics.FromImage(ret))\n {\n g.DrawImageUnscaled(original, 0, 0);\n g.Save();\n }\n\n return ret;\n}\n</code></pre>\n\n<p>See <a href=\"http://macinsoft.blogspot.com/2009/09/beware-image-object.html\" rel=\"nofollow noreferrer\">my blog post</a> and/or <a href=\"http://support.microsoft.com/?id=814675\" rel=\"nofollow noreferrer\">KB 814675</a> for why a Copy is necessary.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20893/" ]
We have a Java Applet built using AWT. This applet lets you select pictures from your hard drive and upload them to a server. The applet includes a scrollable list of pictures, which works fine in Windows, Linux and Mac OS X 10.5. We launch this applet via Java Web Start or within a web page. Our applet does not behave properly in Mac OS X 10.4, regardless of the version of Java (1.4 or 1.5). You can find a screenshot of the incorrect behaviour, when scrolling, here: <http://www.lavablast.com/tmp/ui_error.png> Simply put, sometimes when scrolling the pictures end up overlapping the header or footer of the application. This behaviour does not occur on other platforms. On Mac OS X 10.4, it shows the pictures in the incorrect location when scrolling, which would not be so bad if it refreshed the screen after painting the image at that location. However, it does not appear that the application knows it painted it incorrectly and thus does not refresh. If the window is minimized, resized or even moved, the application is refreshed and the incorrectly positioned elements vanish and the application resumes normally. I spent quite some time trying to force a refresh of the background image unsuccessfully. (the repaint the image directly, repaint all children of a few panels, etc. ) Thus, I am looking for any tips that would help me resolve this problem under Mac OS X 10.4 or, in the worst case, simply simulate a full applet refresh. Until recently, everything was compatible with Java 1.1 but this has changed in a few locations which now require 1.4. I don't feel these changes created the issue, I am just providing this as extra information. If you are interested in implementation details of the scroll panel, I will investigate, but I am assuming this is a common platform bug for which workarounds must be known. To replicate the problem, open the following Java Web Start application: <http://www.lavablast.com/tmp/opal-webstart.php.jnlp> Select a folder containing lots of images and play with the scrollbar. At some point (fairly quickly), you should get the refresh problem. Edit: I followed the first suggestion here and replaced all my controls that feature background images with a Swing equivalent and the issue is still there. (Plus, there are numerous other fixes I would need to do to do a complete change). Any other ideas? A simple one line of code that forces a full refresh would be great :) Edit2: The main thread creates the panels and launches X threads. Using an observer/notifier pattern, the threads complete and notify the main control, which adds a panel to the page. This is done via an EventQueue.invokeLater which, unless I am mistaken, should run on the right thread. The issue is at its most severe when scrolling even if no extra threads are running (as during the loading).
Assuming : * you are using the Microsoft client (`System.Data.OracleClient`). * you have a proper `OracleConnection` instance (`connection`). * you have an `OracleCommand` ready (`command`, based on `SELECT my_blob FROM my_table WHERE id=xx`). This should go like this : ``` using (OracleDataReader odr=command.ExecuteReader()) { reader.Read(); if (!dr.IsDBNull(0)) using (Stream s=(Stream)dr.GetOracleValue(0)) using (Image image=Image.FromStream(s)) return Copy(image); } ``` where Copy is ``` public static Image Copy(Image original) { Image ret=new Bitmap(original.Width, original.Height); using (Graphics g=Graphics.FromImage(ret)) { g.DrawImageUnscaled(original, 0, 0); g.Save(); } return ret; } ``` See [my blog post](http://macinsoft.blogspot.com/2009/09/beware-image-object.html) and/or [KB 814675](http://support.microsoft.com/?id=814675) for why a Copy is necessary.
184,537
<p>I see in C++ there are multiple ways to allocate and free data and I understand that when you call <code>malloc</code> you should call <code>free</code> and when you use the <code>new</code> operator you should pair with <code>delete</code> and it is a mistake to mix the two (e.g. Calling <code>free()</code> on something that was created with the <code>new</code> operator), but I'm not clear on when I should use <code>malloc</code>/ <code>free</code> and when I should use <code>new</code>/ <code>delete</code> in my real world programs.</p> <p>If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.</p>
[ { "answer_id": 184540, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 9, "selected": false, "text": "<p>Unless you are forced to use C, you should <strong>never use</strong> <code>malloc</code>. Always use <code>new</code>.</p>\n\n<p>If you need a big chunk of data just do something like:</p>\n\n<pre><code>char *pBuffer = new char[1024];\n</code></pre>\n\n<p>Be careful though this is not correct:</p>\n\n<pre><code>//This is incorrect - may delete only one element, may corrupt the heap, or worse...\ndelete pBuffer;\n</code></pre>\n\n<p>Instead you should do this when deleting an array of data:</p>\n\n<pre><code>//This deletes all items in the array\ndelete[] pBuffer;\n</code></pre>\n\n<p>The <code>new</code> keyword is the C++ way of doing it, and it will ensure that your type will have its <strong>constructor called</strong>. The <code>new</code> keyword is also more <strong>type-safe</strong> whereas <code>malloc</code> is not type-safe at all. </p>\n\n<p>The only way I could think that would be beneficial to use <code>malloc</code> would be if you needed to <strong>change the size of your buffer</strong> of data. The <code>new</code> keyword does not have an analogous way like <code>realloc</code>. The <code>realloc</code> function might be able to extend the size of a chunk of memory for you more efficiently. </p>\n\n<p>It is worth mentioning that you cannot mix <code>new</code>/<code>free</code> and <code>malloc</code>/<code>delete</code>.</p>\n\n<p>Note: Some answers in this question are invalid. </p>\n\n<pre><code>int* p_scalar = new int(5); // Does not create 5 elements, but initializes to 5\nint* p_array = new int[5]; // Creates 5 elements\n</code></pre>\n" }, { "answer_id": 184548, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 5, "selected": false, "text": "<p>Use <strong><code>malloc</code></strong> and <strong><code>free</code></strong> <em>only</em> for allocating memory that is going to be managed by c-centric libraries and APIs. Use <strong><code>new</code></strong> and <strong><code>delete</code></strong> (and the <strong><code>[]</code></strong> variants) for everything that you control.</p>\n" }, { "answer_id": 184557, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 2, "selected": false, "text": "<p>If you have C code you want to port over to C++, you might leave any malloc() calls in it. For any new C++ code, I'd recommend using new instead.</p>\n" }, { "answer_id": 184568, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 6, "selected": false, "text": "<p>Always use new in C++. If you need a block of untyped memory, you can use operator new directly:</p>\n\n<pre><code>void *p = operator new(size);\n ...\noperator delete(p);\n</code></pre>\n" }, { "answer_id": 184725, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 6, "selected": false, "text": "<p>From the <a href=\"http://yosefk.com/c++fqa/heap.html#fqa-16.4\" rel=\"noreferrer\">C++ FQA Lite</a>:</p>\n\n<blockquote>\n <p>[16.4] Why should I use new instead of\n trustworthy old malloc()?</p>\n \n <p>FAQ: new/delete call the\n constructor/destructor; new is type\n safe, malloc is not; new can be\n overridden by a class.</p>\n \n <p>FQA: The virtues of new mentioned by\n the FAQ are not virtues, because\n constructors, destructors, and\n operator overloading are garbage (see\n what happens when you have no garbage\n collection?), and the type safety\n issue is really tiny here (normally\n you have to cast the void* returned by\n malloc to the right pointer type to\n assign it to a typed pointer variable,\n which may be annoying, but far from\n \"unsafe\").</p>\n \n <p>Oh, and using trustworthy old malloc\n makes it possible to use the equally\n trustworthy &amp; old realloc. Too bad we\n don't have a shiny new operator renew or something.</p>\n \n <p>Still, new is not bad enough to\n justify a deviation from the common\n style used throughout a language, even\n when the language is C++. In\n particular, classes with non-trivial\n constructors will misbehave in fatal\n ways if you simply malloc the objects.\n So why not use new throughout the\n code? People rarely overload operator\n new, so it probably won't get in your\n way too much. And if they do overload\n new, you can always ask them to stop.</p>\n</blockquote>\n\n<p>Sorry, I just couldn't resist. :)</p>\n" }, { "answer_id": 184798, "author": "selwyn", "author_id": 16314, "author_profile": "https://Stackoverflow.com/users/16314", "pm_score": 0, "selected": false, "text": "<p>The <code>new</code> and <code>delete</code> operators can operate on classes and structures, whereas <code>malloc</code> and <code>free</code> only work with blocks of memory that need to be cast.</p>\n\n<p>Using <code>new/delete</code> will help to improve your code as you will not need to cast allocated memory to the required data structure.</p>\n" }, { "answer_id": 7059528, "author": "Peiti Li", "author_id": 793459, "author_profile": "https://Stackoverflow.com/users/793459", "pm_score": 2, "selected": false, "text": "<p>From a lower perspective, new will initialize all the memory before giving the memory whereas malloc will keep the original content of the memory.</p>\n" }, { "answer_id": 7970036, "author": "Flexo", "author_id": 168175, "author_profile": "https://Stackoverflow.com/users/168175", "pm_score": 7, "selected": false, "text": "<p>The short answer is: don't use <code>malloc</code> for C++ without a really good reason for doing so. <code>malloc</code> has a number of deficiencies when used with C++, which <code>new</code> was defined to overcome.</p>\n\n<h2>Deficiencies fixed by new for C++ code</h2>\n\n<ol>\n<li><p><code>malloc</code> is not typesafe in any meaningful way. In C++ you are required to cast the return from <code>void*</code>. This potentially introduces a lot of problems:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n\nstruct foo {\n double d[5];\n}; \n\nint main() {\n foo *f1 = malloc(1); // error, no cast\n foo *f2 = static_cast&lt;foo*&gt;(malloc(sizeof(foo)));\n foo *f3 = static_cast&lt;foo*&gt;(malloc(1)); // No error, bad\n}\n</code></pre></li>\n<li><p>It's worse than that though. If the type in question is <a href=\"https://stackoverflow.com/questions/146452/what-are-pod-types-in-c\">POD (plain old data)</a> then you can semi-sensibly use <code>malloc</code> to allocate memory for it, as <code>f2</code> does in the first example.</p>\n\n<p>It's not so obvious though if a type is POD. The fact that it's possible for a given type to change from POD to non-POD with no resulting compiler error and potentially very hard to debug problems is a significant factor. For example if someone (possibly another programmer, during maintenance, much later on were to make a change that caused <code>foo</code> to no longer be POD then no obvious error would appear at compile time as you'd hope, e.g.:</p>\n\n<pre><code>struct foo {\n double d[5];\n virtual ~foo() { }\n};\n</code></pre>\n\n<p>would make the <code>malloc</code> of <code>f2</code> also become bad, without any obvious diagnostics. The example here is trivial, but it's possible to accidentally introduce non-PODness much further away (e.g. in a base class, by adding a non-POD member). If you have C++11/boost you can use <code>is_pod</code> to check that this assumption is correct and produce an error if it's not:</p>\n\n<pre><code>#include &lt;type_traits&gt;\n#include &lt;stdlib.h&gt;\n\nfoo *safe_foo_malloc() {\n static_assert(std::is_pod&lt;foo&gt;::value, \"foo must be POD\");\n return static_cast&lt;foo*&gt;(malloc(sizeof(foo)));\n}\n</code></pre>\n\n<p>Although boost is <a href=\"http://www.boost.org/doc/libs/1_47_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pod.html\" rel=\"noreferrer\">unable to determine if a type is POD</a> without C++11 or some other compiler extensions.</p></li>\n<li><p><code>malloc</code> returns <code>NULL</code> if allocation fails. <code>new</code> will throw <code>std::bad_alloc</code>. The behaviour of later using a <code>NULL</code> pointer is undefined. An exception has clean semantics when it is thrown and it is thrown from the source of the error. Wrapping <code>malloc</code> with an appropriate test at every call seems tedious and error prone. (You only have to forget once to undo all that good work). An exception can be allowed to propagate to a level where a caller is able to sensibly process it, where as <code>NULL</code> is much harder to pass back meaningfully. We could extend our <code>safe_foo_malloc</code> function to throw an exception or exit the program or call some handler:</p>\n\n<pre><code>#include &lt;type_traits&gt;\n#include &lt;stdlib.h&gt;\n\nvoid my_malloc_failed_handler();\n\nfoo *safe_foo_malloc() {\n static_assert(std::is_pod&lt;foo&gt;::value, \"foo must be POD\");\n foo *mem = static_cast&lt;foo*&gt;(malloc(sizeof(foo)));\n if (!mem) {\n my_malloc_failed_handler();\n // or throw ...\n }\n return mem;\n}\n</code></pre></li>\n<li><p>Fundamentally <code>malloc</code> is a C feature and <code>new</code> is a C++ feature. As a result <code>malloc</code> does not play nicely with constructors, it only looks at allocating a chunk of bytes. We could extend our <code>safe_foo_malloc</code> further to use placement <code>new</code>:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;new&gt;\n\nvoid my_malloc_failed_handler();\n\nfoo *safe_foo_malloc() {\n void *mem = malloc(sizeof(foo));\n if (!mem) {\n my_malloc_failed_handler();\n // or throw ...\n }\n return new (mem)foo();\n}\n</code></pre></li>\n<li><p>Our <code>safe_foo_malloc</code> function isn't very generic - ideally we'd want something that can handle any type, not just <code>foo</code>. We can achieve this with templates and variadic templates for non-default constructors:</p>\n\n<pre><code>#include &lt;functional&gt;\n#include &lt;new&gt;\n#include &lt;stdlib.h&gt;\n\nvoid my_malloc_failed_handler();\n\ntemplate &lt;typename T&gt;\nstruct alloc {\n template &lt;typename ...Args&gt;\n static T *safe_malloc(Args&amp;&amp;... args) {\n void *mem = malloc(sizeof(T));\n if (!mem) {\n my_malloc_failed_handler();\n // or throw ...\n }\n return new (mem)T(std::forward(args)...);\n }\n};\n</code></pre>\n\n<p>Now though in fixing all the issues we identified so far we've practically reinvented the default <code>new</code> operator. If you're going to use <code>malloc</code> and placement <code>new</code> then you might as well just use <code>new</code> to begin with!</p></li>\n</ol>\n" }, { "answer_id": 7971041, "author": "R. Martinho Fernandes", "author_id": 46642, "author_profile": "https://Stackoverflow.com/users/46642", "pm_score": 4, "selected": false, "text": "<p>There is one big difference between <code>malloc</code> and <code>new</code>. <code>malloc</code> allocates memory. This is fine for C, because in C, a lump of memory is an object.</p>\n\n<p>In C++, if you're not dealing with POD types (which are similar to C types) you must call a constructor on a memory location to actually have an object there. Non-POD types are very common in C++, as many C++ features make an object automatically non-POD.</p>\n\n<p><code>new</code> allocates memory <em>and</em> creates an object on that memory location. For non-POD types this means calling a constructor.</p>\n\n<p>If you do something like this:</p>\n\n<pre><code>non_pod_type* p = (non_pod_type*) malloc(sizeof *p);\n</code></pre>\n\n<p>The pointer you obtain cannot be dereferenced because it does not point to an object. You'd need to call a constructor on it before you can use it (and this is done using placement <code>new</code>).</p>\n\n<p>If, on the other hand, you do:</p>\n\n<pre><code>non_pod_type* p = new non_pod_type();\n</code></pre>\n\n<p>You get a pointer that is always valid, because <code>new</code> created an object.</p>\n\n<p>Even for POD types, there's a significant difference between the two:</p>\n\n<pre><code>pod_type* p = (pod_type*) malloc(sizeof *p);\nstd::cout &lt;&lt; p-&gt;foo;\n</code></pre>\n\n<p>This piece of code would print an unspecified value, because the POD objects created by <code>malloc</code> are not initialised.</p>\n\n<p>With <code>new</code>, you could specify a constructor to call, and thus get a well defined value.</p>\n\n<pre><code>pod_type* p = new pod_type();\nstd::cout &lt;&lt; p-&gt;foo; // prints 0\n</code></pre>\n\n<p>If you really want it, you can use use <code>new</code> to obtain uninitialised POD objects. See <a href=\"https://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new/620402#620402\">this other answer</a> for more information on that.</p>\n\n<p>Another difference is the behaviour upon failure. When it fails to allocate memory, <code>malloc</code> returns a null pointer, while <code>new</code> throws an exception.</p>\n\n<p>The former requires you to test every pointer returned before using it, while the later will always produce valid pointers.</p>\n\n<p>For these reasons, in C++ code you should use <code>new</code>, and not <code>malloc</code>. But even then, you should not use <code>new</code> \"in the open\", because it acquires resources you need to release later on. When you use <code>new</code> you should pass its result immediately into a resource managing class:</p>\n\n<pre><code>std::unique_ptr&lt;T&gt; p = std::unique_ptr&lt;T&gt;(new T()); // this won't leak\n</code></pre>\n" }, { "answer_id": 11663068, "author": "Hitesh Ahuja", "author_id": 1552184, "author_profile": "https://Stackoverflow.com/users/1552184", "pm_score": -1, "selected": false, "text": "<p>malloc() is used to dynamically assign memory in C\nwhile the same work is done by new() in c++.\nSo you cannot mix coding conventions of 2 languages.\nIt would be good if you asked for difference between calloc and malloc()</p>\n" }, { "answer_id": 11998474, "author": "Barry", "author_id": 1605648, "author_profile": "https://Stackoverflow.com/users/1605648", "pm_score": 2, "selected": false, "text": "<p>In the following scenario, we can't use new since it calls constructor. </p>\n\n<pre><code>class B {\nprivate:\n B *ptr;\n int x;\npublic:\n B(int n) {\n cout&lt;&lt;\"B: ctr\"&lt;&lt;endl;\n //ptr = new B; //keep calling ctr, result is segmentation fault\n ptr = (B *)malloc(sizeof(B));\n x = n;\n ptr-&gt;x = n + 10;\n }\n ~B() {\n //delete ptr;\n free(ptr);\n cout&lt;&lt;\"B: dtr\"&lt;&lt;endl;\n }\n};\n</code></pre>\n" }, { "answer_id": 15901802, "author": "PSkocik", "author_id": 1084774, "author_profile": "https://Stackoverflow.com/users/1084774", "pm_score": 3, "selected": false, "text": "<p>If you work with data that doesn't need construction/destruction and requires reallocations (e.g., a large array of ints), then I believe malloc/free is a good choice as it gives you realloc, which is way faster than new-memcpy-delete (it is on my Linux box, but I guess this may be platform dependent). If you work with C++ objects that are not POD and require construction/destruction, then you must use the new and delete operators.</p>\n\n<p>Anyway, I don't see why you shouldn't use both (provided that you free your malloced memory and delete objects allocated with new) if can take advantage of the speed boost (sometimes a significant one, if you're reallocing large arrays of POD) that realloc can give you.</p>\n\n<p>Unless you need it though, you should stick to new/delete in C++.</p>\n" }, { "answer_id": 21140469, "author": "herohuyongtao", "author_id": 2589776, "author_profile": "https://Stackoverflow.com/users/2589776", "pm_score": 3, "selected": false, "text": "<p>There are a few things which <code>new</code> does that <code>malloc</code> doesn’t:</p>\n\n<ol>\n<li><code>new</code> constructs the object by calling the constructor of that object</li>\n<li><code>new</code> doesn’t require typecasting of allocated memory.</li>\n<li>It doesn’t require an amount of memory to be allocated, rather it requires a number of \nobjects to be constructed.</li>\n</ol>\n\n<p>So, if you use <code>malloc</code>, then you need to do above things explicitly, which is not always practical. Additionally, <code>new</code> can be overloaded but <code>malloc</code> can’t be.</p>\n" }, { "answer_id": 22806654, "author": "user3488100", "author_id": 3488100, "author_profile": "https://Stackoverflow.com/users/3488100", "pm_score": 3, "selected": false, "text": "<p>If you are using C++, try to use new/delete instead of malloc/calloc as they are operators. For malloc/calloc, you need to include another header. Don't mix two different languages in the same code. Their work is similar in every manner, both allocates memory dynamically from heap segment in hash table. </p>\n" }, { "answer_id": 33935717, "author": "Yogeesh H T", "author_id": 3725702, "author_profile": "https://Stackoverflow.com/users/3725702", "pm_score": 6, "selected": false, "text": "<p><strong>new vs malloc()</strong></p>\n\n<p>1) <code>new</code> is an <strong>operator</strong>, while <code>malloc()</code> is a <strong>function</strong>.</p>\n\n<p>2) <code>new</code> calls <strong>constructors</strong>, while <code>malloc()</code> does not.</p>\n\n<p>3) <code>new</code> returns <strong>exact data type</strong>, while <code>malloc()</code> returns <strong>void *</strong>.</p>\n\n<p>4) <code>new</code> never returns a <strong>NULL</strong> (will throw on failure) while <code>malloc()</code> returns NULL</p>\n\n<p>5) Reallocation of memory not handled by <code>new</code> while <code>malloc()</code> can</p>\n" }, { "answer_id": 41146664, "author": "kungfooman", "author_id": 1952626, "author_profile": "https://Stackoverflow.com/users/1952626", "pm_score": 2, "selected": false, "text": "<p><code>new</code> will initialise the default values of the struct and correctly links the references in it to itself.</p>\n\n<p>E.g.</p>\n\n<pre><code>struct test_s {\n int some_strange_name = 1;\n int &amp;easy = some_strange_name;\n}\n</code></pre>\n\n<p>So <code>new struct test_s</code> will return an initialised structure with a working reference, while the malloc'ed version has no default values and the intern references aren't initialised.</p>\n" }, { "answer_id": 45386002, "author": "Florentino Tuason", "author_id": 2512013, "author_profile": "https://Stackoverflow.com/users/2512013", "pm_score": 2, "selected": false, "text": "<p>Rare case to consider using malloc/free instead of new/delete is when you're allocating and then reallocating (simple pod types, not objects) using realloc as there is no similar function to realloc in C++ (although this can be done using a more C++ approach).</p>\n" }, { "answer_id": 45386558, "author": "The Quantum Physicist", "author_id": 1317944, "author_profile": "https://Stackoverflow.com/users/1317944", "pm_score": 5, "selected": false, "text": "<p>To answer your question, you should know <strong>the difference between <code>malloc</code> and <code>new</code></strong>. The difference is simple:</p>\n\n<p><code>malloc</code> <strong>allocates memory</strong>, while <code>new</code> <strong>allocates memory AND calls the constructor</strong> of the object you're allocating memory for.</p>\n\n<p>So, unless you're restricted to C, you should never use malloc, especially when dealing with C++ objects. That would be a recipe for breaking your program.</p>\n\n<p>Also the difference between <code>free</code> and <code>delete</code> is quite the same. The difference is that <code>delete</code> will call the destructor of your object in addition to freeing memory.</p>\n" }, { "answer_id": 53898150, "author": "JVApen", "author_id": 2466431, "author_profile": "https://Stackoverflow.com/users/2466431", "pm_score": 4, "selected": false, "text": "<p>Dynamic allocation is only required when the life-time of the object should be different than the scope it gets created in (This holds as well for making the scope smaller as larger) and you have a specific reason where storing it by value doesn't work.</p>\n<p>For example:</p>\n<pre><code> std::vector&lt;int&gt; *createVector(); // Bad\n std::vector&lt;int&gt; createVector(); // Good\n\n auto v = new std::vector&lt;int&gt;(); // Bad\n auto result = calculate(/*optional output = */ v);\n auto v = std::vector&lt;int&gt;(); // Good\n auto result = calculate(/*optional output = */ &amp;v);\n</code></pre>\n<p>From C++11 on, we have <code>std::unique_ptr</code> for dealing with allocated memory, which contains the ownership of the allocated memory. <code>std::shared_ptr</code> was created for when you have to share ownership. (you'll need this less than you would expect in a good program)</p>\n<p>Creating an instance becomes really easy:</p>\n<pre><code>auto instance = std::make_unique&lt;Class&gt;(/*args*/); // C++14\nauto instance = std::unique_ptr&lt;Class&gt;(new Class(/*args*/)); // C++11\nauto instance = std::make_unique&lt;Class[]&gt;(42); // C++14\nauto instance = std::unique_ptr&lt;Class[]&gt;(new Class[](42)); // C++11\n</code></pre>\n<p>C++17 also adds <code>std::optional</code> which can prevent you from requiring memory allocations</p>\n<pre><code>auto optInstance = std::optional&lt;Class&gt;{};\nif (condition)\n optInstance = Class{};\n</code></pre>\n<p>As soon as 'instance' goes out of scope, the memory gets cleaned up. Transferring ownership is also easy:</p>\n<pre><code> auto vector = std::vector&lt;std::unique_ptr&lt;Interface&gt;&gt;{};\n auto instance = std::make_unique&lt;Class&gt;();\n vector.push_back(std::move(instance)); // std::move -&gt; transfer (most of the time)\n</code></pre>\n<p>So when do you still need <code>new</code>? Almost never from C++11 on. Most of the you use <code>std::make_unique</code> until you get to a point where you hit an API that transfers ownership via raw pointers.</p>\n<pre><code> auto instance = std::make_unique&lt;Class&gt;();\n legacyFunction(instance.release()); // Ownership being transferred\n\n auto instance = std::unique_ptr&lt;Class&gt;{legacyFunction()}; // Ownership being captured in unique_ptr\n</code></pre>\n<p>In C++98/03, you have to do manual memory management. If you are in this case, try upgrading to a more recent version of the standard. If you are stuck:</p>\n<pre><code> auto instance = new Class(); // Allocate memory\n delete instance; // Deallocate\n auto instances = new Class[42](); // Allocate memory\n delete[] instances; // Deallocate\n</code></pre>\n<p>Make sure that you track the ownership correctly to not have any memory leaks! Move semantics don't work yet either.</p>\n<p>So, when do we need malloc in C++? The only valid reason would be to allocate memory and initialize it later via placement new.</p>\n<pre><code> auto instanceBlob = std::malloc(sizeof(Class)); // Allocate memory\n auto instance = new(instanceBlob)Class{}; // Initialize via constructor\n instance.~Class(); // Destroy via destructor\n std::free(instanceBlob); // Deallocate the memory\n</code></pre>\n<p>Even though, the above is valid, this can be done via a new-operator as well. <code>std::vector</code> is a good example for this.</p>\n<p>Finally, we still have the elephant in the room: <code>C</code>. If you have to work with a C-library where memory gets allocated in the C++ code and freed in the C code (or the other way around), you are forced to use malloc/free.</p>\n<p>If you are in this case, forget about virtual functions, member functions, classes ... Only structs with PODs in it are allowed.</p>\n<p>Some exceptions to the rules:</p>\n<ul>\n<li>You are writing a standard library with advanced data structures where malloc is appropriate</li>\n<li>You have to allocate big amounts of memory (In memory copy of a 10GB file?)</li>\n<li>You have tooling preventing you to use certain constructs</li>\n<li>You need to store an incomplete type</li>\n</ul>\n" }, { "answer_id": 73317006, "author": "Adrian", "author_id": 19705775, "author_profile": "https://Stackoverflow.com/users/19705775", "pm_score": 1, "selected": false, "text": "<p>I had played before with few C/C++ applications for computer graphics.\nAfter so many time, some things are vanished and I missed them a lot.</p>\n<p>The point is, that malloc and new, or free and delete, can work both,\nespecially for certain basic types, which are the most common.</p>\n<p>For instance, a char array, can be allocated both with malloc, or new.\nA main difference is, with new you can instantiate a fixed array size.</p>\n<pre><code>char* pWord = new char[5]; // allocation of char array of fixed size \n</code></pre>\n<p>You cannot use a variable for the size of the array in this case.\nBy the contrary, the malloc function could allow a variable size.</p>\n<pre><code>int size = 5; \nchar* pWord = (char*)malloc(size); \n</code></pre>\n<p>In this case, it might be required a conversion cast operator.\nFor the returned type from malloc it's a pointer to void, not char.\nAnd sometimes the compiler could not know, how to convert this type.</p>\n<p>After allocation the memory block, you can set the variable values.\nthe memset function can be indeed slower for some bigger arrays.\nBut all the bites must be set first to 0, before assigning a value.\nBecause the values of an array could have an arbitrary content.</p>\n<p>Suppose, the array is assigned with another array of smaller size.\nPart of the array element could still have arbitrary content.\nAnd a call to a memset function would be recomended in this case.</p>\n<pre><code>memset((void*)pWord, 0, sizeof(pWord) / sizeof(char)); \n</code></pre>\n<p>The allocation functions are available for all C packages.\nSo, these are general functions, that must work for more C types.\nAnd the C++ libraries are extensions of the older C libraries.\nTherefore the malloc function returns a generic void* pointer.\nThe sructures do not have defined a new, or a delete operator.\nIn this case, a custom variable can be allocated with malloc.</p>\n<p>The new and delete keywords are actually some defined C operators.\nMaybe a custom union, or class, can have defined these operators.\nIf new and delete are not defined in a class, these may not work.\nBut if a class is derived from another, which has these operators,\nthe new and delete keywords can have the basic class behavior.</p>\n<p>About freeing an array, free can be only used in pair with malloc.\nCannot allocate a variable with malloc, and then free with delete.</p>\n<p>The simple delete operator references just first item of an array.\nBecause the pWord array can be also written as:</p>\n<pre><code>pWord = &amp;pWord[0]; // or *pWord = pWord[0]; \n</code></pre>\n<p>When an array must be deleted, use the delete[] operator instead:</p>\n<pre><code>delete[] pWord; \n</code></pre>\n<p>Casts are not bad, they just don't work for all the variable types.\nA conversion cast is also an operator function, that must be defined.\nIf this operator is not defined for a certain type, it may not work.\nBut not all the errors are because of this conversion cast operator.</p>\n<p>Also a cast to a void pointer must be used when using a free call.\nThis is because the argument of the free function is a void pointer.</p>\n<pre><code>free((void*)pWord); \n</code></pre>\n<p>Some errors can arise, because the size of the array is too small.\nBut this is another story, it is not because of using the cast.</p>\n<p>With kind regards, Adrian Brinas</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I see in C++ there are multiple ways to allocate and free data and I understand that when you call `malloc` you should call `free` and when you use the `new` operator you should pair with `delete` and it is a mistake to mix the two (e.g. Calling `free()` on something that was created with the `new` operator), but I'm not clear on when I should use `malloc`/ `free` and when I should use `new`/ `delete` in my real world programs. If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.
Unless you are forced to use C, you should **never use** `malloc`. Always use `new`. If you need a big chunk of data just do something like: ``` char *pBuffer = new char[1024]; ``` Be careful though this is not correct: ``` //This is incorrect - may delete only one element, may corrupt the heap, or worse... delete pBuffer; ``` Instead you should do this when deleting an array of data: ``` //This deletes all items in the array delete[] pBuffer; ``` The `new` keyword is the C++ way of doing it, and it will ensure that your type will have its **constructor called**. The `new` keyword is also more **type-safe** whereas `malloc` is not type-safe at all. The only way I could think that would be beneficial to use `malloc` would be if you needed to **change the size of your buffer** of data. The `new` keyword does not have an analogous way like `realloc`. The `realloc` function might be able to extend the size of a chunk of memory for you more efficiently. It is worth mentioning that you cannot mix `new`/`free` and `malloc`/`delete`. Note: Some answers in this question are invalid. ``` int* p_scalar = new int(5); // Does not create 5 elements, but initializes to 5 int* p_array = new int[5]; // Creates 5 elements ```
184,550
<p>I am currently using Rails 2.1.0 and want to upgrade to Rails 2.1.1. After issuing the following command </p> <pre><code>gem update rails </code></pre> <p>I suppose that I need to change this line </p> <pre><code>RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION </code></pre> <p>in environment.rb</p> <p>What other actions should I take to ensure that my application is using the latest version? Are there some other files that need an update?</p>
[ { "answer_id": 184608, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 0, "selected": false, "text": "<p>As far as I know, that right there defines what version of rails your application as a whole will use. I know for a project I'm in right now I had to override that to 2.1.1 to work on my VM because I had installed the latest, and had not specified the 2.1.0 as required by the project.</p>\n\n<p>The biggest thing you have to watch out for is plugins and extensions that may override this setting, as well as incompatibility that will likely arise from changing versions.</p>\n\n<p>Also there are some known issues with 2.1.1, unless there is a feature you absolutely need now, you may want to wait.</p>\n" }, { "answer_id": 194892, "author": "Yardboy", "author_id": 9550, "author_profile": "https://Stackoverflow.com/users/9550", "pm_score": 3, "selected": true, "text": "<p>You'll also need to go into your application directory and run the following command:</p>\n\n<p>rake rails:update</p>\n\n<p>Then run your tests and make sure everything works.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
I am currently using Rails 2.1.0 and want to upgrade to Rails 2.1.1. After issuing the following command ``` gem update rails ``` I suppose that I need to change this line ``` RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION ``` in environment.rb What other actions should I take to ensure that my application is using the latest version? Are there some other files that need an update?
You'll also need to go into your application directory and run the following command: rake rails:update Then run your tests and make sure everything works.
184,560
<p>I downloaded a VM image of a web application that uses MySQL.</p> <p>How can I monitor its space consumption and know when additional space must be added?</p>
[ { "answer_id": 184726, "author": "MaxVT", "author_id": 19530, "author_profile": "https://Stackoverflow.com/users/19530", "pm_score": 2, "selected": false, "text": "<p>If only MySQL is available, use the SHOW TABLE STATUS command, and look at the Data_length column for each table, which is in bytes.</p>\n\n<p>If you have other languages available on the machine, a script in any of them that runs regularly (cron), checks disk free space or size of database directory, and updates you over e-mail or otherwise. There are far too many options to suggest a particular solution -- it depends on your situation.</p>\n" }, { "answer_id": 184917, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "<p>For MyISAM tables, I usually check the size of the /var/lib/mysql/mydatabasename/ directory. InnoDB tables use monolithic files, so you have to use SHOW TABLE STATUS.</p>\n" }, { "answer_id": 4055942, "author": "RolandoMySQLDBA", "author_id": 491757, "author_profile": "https://Stackoverflow.com/users/491757", "pm_score": 6, "selected": true, "text": "<p>I have some great big queries to share:</p>\n<p>Run this to get the Total MySQL Data and Index Usage By Storage Engine</p>\n<pre><code>SELECT IFNULL(B.engine,'Total') &quot;Storage Engine&quot;,\nCONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') &quot;Data Size&quot;, CONCAT(LPAD(REPLACE(\nFORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') &quot;Index Size&quot;, CONCAT(LPAD(REPLACE(\nFORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') &quot;Table Size&quot; FROM\n(SELECT engine,SUM(data_length) DSize,SUM(index_length) ISize,\nSUM(data_length+index_length) TSize FROM\ninformation_schema.tables WHERE table_schema NOT IN\n('mysql','information_schema','performance_schema') AND\nengine IS NOT NULL GROUP BY engine WITH ROLLUP) B,\n(SELECT 3 pw) A ORDER BY TSize;\n</code></pre>\n<p>Run this to get the Total MySQL Data and Index Usage By Database</p>\n<pre><code>SELECT DBName,CONCAT(LPAD(FORMAT(SDSize/POWER(1024,pw),3),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') &quot;Data Size&quot;,CONCAT(LPAD(\nFORMAT(SXSize/POWER(1024,pw),3),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') &quot;Index Size&quot;,\nCONCAT(LPAD(FORMAT(STSize/POWER(1024,pw),3),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') &quot;Total Size&quot; FROM\n(SELECT IFNULL(DB,'All Databases') DBName,SUM(DSize) SDSize,SUM(XSize) SXSize,\nSUM(TSize) STSize FROM (SELECT table_schema DB,data_length DSize,\nindex_length XSize,data_length+index_length TSize FROM information_schema.tables\nWHERE table_schema NOT IN ('mysql','information_schema','performance_schema')) AAA\nGROUP BY DB WITH ROLLUP) AA,(SELECT 3 pw) BB ORDER BY (SDSize+SXSize);\n</code></pre>\n<p>Run this to get the Total MySQL Data and Index Usage By Database and Storage Engine</p>\n<pre><code>SELECT Statistic,DataSize &quot;Data Size&quot;,IndexSize &quot;Index Size&quot;,TableSize &quot;Table Size&quot;\nFROM (SELECT IF(ISNULL(table_schema)=1,10,0) schema_score,\nIF(ISNULL(engine)=1,10,0) engine_score,\nIF(ISNULL(table_schema)=1,'ZZZZZZZZZZZZZZZZ',table_schema) schemaname,\nIF(ISNULL(B.table_schema)+ISNULL(B.engine)=2,&quot;Storage for All Databases&quot;,\nIF(ISNULL(B.table_schema)+ISNULL(B.engine)=1,\nCONCAT(&quot;Storage for &quot;,B.table_schema),\nCONCAT(B.engine,&quot; Tables for &quot;,B.table_schema))) Statistic,\nCONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') DataSize,CONCAT(LPAD(REPLACE(\nFORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') IndexSize,\nCONCAT(LPAD(REPLACE(FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',\nSUBSTR(' KMGTP',pw+1,1),'B') TableSize FROM (SELECT table_schema,engine,\nSUM(data_length) DSize,SUM(index_length) ISize,\nSUM(data_length+index_length) TSize FROM information_schema.tables\nWHERE table_schema NOT IN ('mysql','information_schema','performance_schema')\nAND engine IS NOT NULL GROUP BY table_schema,engine WITH ROLLUP) B,\n(SELECT 3 pw) A) AA ORDER BY schemaname,schema_score,engine_score;\n</code></pre>\n<p>CAVEAT</p>\n<p>In each query, you will see <code>(SELECT 3 pw)</code>. The pw stands for the Power Of 1024 to display the results.</p>\n<ul>\n<li><code>(SELECT 0 pw)</code> will Display the Report in Bytes</li>\n<li><code>(SELECT 1 pw)</code> will Display the Report in KiloBytes</li>\n<li><code>(SELECT 2 pw)</code> will Display the Report in MegaBytes</li>\n<li><code>(SELECT 3 pw)</code> will Display the Report in GigaBytes</li>\n<li><code>(SELECT 4 pw)</code> will Display the Report in TeraBytes</li>\n<li><code>(SELECT 5 pw)</code> will Display the Report in PetaBytes (please contact me if you run this one)</li>\n</ul>\n<p>Here is a report query with a little less formatting:</p>\n<pre><code>SELECT IFNULL(db,'Total') &quot;Database&quot;,\ndatsum / power(1024,pw) &quot;Data Size&quot;,\nndxsum / power(1024,pw) &quot;Index Size&quot;,\ntotsum / power(1024,pw) &quot;Total&quot;\nFROM (SELECT db,SUM(dat) datsum,SUM(ndx) ndxsum,SUM(dat+ndx) totsum\nFROM (SELECT table_schema db,data_length dat,index_length ndx\nFROM information_schema.tables WHERE engine IS NOT NULL\nAND table_schema NOT IN ('information_schema','mysql')) AA\nGROUP BY db WITH ROLLUP) A,(SELECT 1 pw) B;\n</code></pre>\n<p>Trust me, I made these queries over 4 years ago and still use them today.</p>\n<h1>UPDATE 2013-06-24 15:53 EDT</h1>\n<p>I have something new. I have changed the queries so that you do not have to set the <code>pw</code> parameter for different unit displays. Each unit display is calculated for you.</p>\n<p>Report By Storage Engine</p>\n<pre><code>SELECT\n IFNULL(ENGINE,'Total') &quot;Storage Engine&quot;,\n LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',\n SUBSTR(units,pw1*2+1,2)),17,' ') &quot;Data Size&quot;,\n LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',\n SUBSTR(units,pw2*2+1,2)),17,' ') &quot;Index Size&quot;,\n LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',\n SUBSTR(units,pw3*2+1,2)),17,' ') &quot;Total Size&quot;\nFROM\n(\n SELECT ENGINE,DAT,NDX,TBL,\n IF(px&gt;4,4,px) pw1,IF(py&gt;4,4,py) pw2,IF(pz&gt;4,4,pz) pw3\n FROM \n (SELECT *,\n FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,\n FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,\n FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz\n FROM\n (SELECT\n ENGINE,\n SUM(data_length) DAT,\n SUM(index_length) NDX,\n SUM(data_length+index_length) TBL\n FROM\n (\n SELECT engine,data_length,index_length FROM\n information_schema.tables WHERE table_schema NOT IN\n ('information_schema','performance_schema','mysql')\n AND ENGINE IS NOT NULL\n ) AAA GROUP BY ENGINE WITH ROLLUP\n) AAA ) AA) A,(SELECT ' BKBMBGBTB' units) B;\n</code></pre>\n<p>Report By Database</p>\n<pre><code>SELECT\n IFNULL(DB,'Total') &quot;Database&quot;,\n LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',\n SUBSTR(units,pw1*2+1,2)),17,' ') &quot;Data Size&quot;,\n LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',\n SUBSTR(units,pw2*2+1,2)),17,' ') &quot;Index Size&quot;,\n LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',\n SUBSTR(units,pw3*2+1,2)),17,' ') &quot;Total Size&quot;\nFROM\n(\n SELECT DB,DAT,NDX,TBL,\n IF(px&gt;4,4,px) pw1,IF(py&gt;4,4,py) pw2,IF(pz&gt;4,4,pz) pw3\n FROM \n (SELECT *,\n FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,\n FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,\n FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz\n FROM\n (SELECT\n DB,\n SUM(data_length) DAT,\n SUM(index_length) NDX,\n SUM(data_length+index_length) TBL\n FROM\n (\n SELECT table_schema DB,data_length,index_length FROM\n information_schema.tables WHERE table_schema NOT IN\n ('information_schema','performance_schema','mysql')\n AND ENGINE IS NOT NULL\n ) AAA GROUP BY DB WITH ROLLUP\n) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B;\n</code></pre>\n<p>Report By Database / Storage Engine</p>\n<pre><code>SELECT\n IF(ISNULL(DB)+ISNULL(ENGINE)=2,'Database Total',\n CONCAT(DB,' ',IFNULL(ENGINE,'Total'))) &quot;Reported Statistic&quot;,\n LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',\n SUBSTR(units,pw1*2+1,2)),17,' ') &quot;Data Size&quot;,\n LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',\n SUBSTR(units,pw2*2+1,2)),17,' ') &quot;Index Size&quot;,\n LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',\n SUBSTR(units,pw3*2+1,2)),17,' ') &quot;Total Size&quot;\nFROM\n(\n SELECT DB,ENGINE,DAT,NDX,TBL,\n IF(px&gt;4,4,px) pw1,IF(py&gt;4,4,py) pw2,IF(pz&gt;4,4,pz) pw3\n FROM \n (SELECT *,\n FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,\n FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,\n FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz\n FROM\n (SELECT\n DB,ENGINE,\n SUM(data_length) DAT,\n SUM(index_length) NDX,\n SUM(data_length+index_length) TBL\n FROM\n (\n SELECT table_schema DB,ENGINE,data_length,index_length FROM\n information_schema.tables WHERE table_schema NOT IN\n ('information_schema','performance_schema','mysql')\n AND ENGINE IS NOT NULL\n ) AAA GROUP BY DB,ENGINE WITH ROLLUP\n) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B;\n</code></pre>\n" }, { "answer_id": 4229061, "author": "Vadim", "author_id": 338477, "author_profile": "https://Stackoverflow.com/users/338477", "pm_score": 0, "selected": false, "text": "<p>Since you have VM and you don't really care how the space is used, \nI think the simplest way is to check the size of MySQL data dir.\nBy default it is <code>/var/lib/mysql</code>.\nAlso it`ll be nice to cleanup the mysql binary logs (if possible) before checking data dir size.</p>\n" }, { "answer_id": 23603833, "author": "Glenn McKay", "author_id": 3555359, "author_profile": "https://Stackoverflow.com/users/3555359", "pm_score": 1, "selected": false, "text": "<p>You can refer <a href=\"https://www.webyog.com/product/monyog\" rel=\"nofollow\">MONyog</a> which has Disk Info feature which lets you find out Disk space analysis at server level, Database level and at Table level</p>\n" }, { "answer_id": 33592145, "author": "wpdevramki", "author_id": 4467277, "author_profile": "https://Stackoverflow.com/users/4467277", "pm_score": 0, "selected": false, "text": "<pre><code>du -s /var/lib/mysql/* | sort -nr\n</code></pre>\n\n<p>Result</p>\n\n<pre><code>34128 /var/lib/mysql/db_name1\n33720 /var/lib/mysql/db_name2\n29744 /var/lib/mysql/db_name3\n26624 /var/lib/mysql/db_name4\n16516 /var/lib/mysql/db_name5\n</code></pre>\n\n<p>Thsi will show as descending order in kb</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15884/" ]
I downloaded a VM image of a web application that uses MySQL. How can I monitor its space consumption and know when additional space must be added?
I have some great big queries to share: Run this to get the Total MySQL Data and Index Usage By Storage Engine ``` SELECT IFNULL(B.engine,'Total') "Storage Engine", CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') "Data Size", CONCAT(LPAD(REPLACE( FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') "Index Size", CONCAT(LPAD(REPLACE( FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') "Table Size" FROM (SELECT engine,SUM(data_length) DSize,SUM(index_length) ISize, SUM(data_length+index_length) TSize FROM information_schema.tables WHERE table_schema NOT IN ('mysql','information_schema','performance_schema') AND engine IS NOT NULL GROUP BY engine WITH ROLLUP) B, (SELECT 3 pw) A ORDER BY TSize; ``` Run this to get the Total MySQL Data and Index Usage By Database ``` SELECT DBName,CONCAT(LPAD(FORMAT(SDSize/POWER(1024,pw),3),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') "Data Size",CONCAT(LPAD( FORMAT(SXSize/POWER(1024,pw),3),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Index Size", CONCAT(LPAD(FORMAT(STSize/POWER(1024,pw),3),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') "Total Size" FROM (SELECT IFNULL(DB,'All Databases') DBName,SUM(DSize) SDSize,SUM(XSize) SXSize, SUM(TSize) STSize FROM (SELECT table_schema DB,data_length DSize, index_length XSize,data_length+index_length TSize FROM information_schema.tables WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')) AAA GROUP BY DB WITH ROLLUP) AA,(SELECT 3 pw) BB ORDER BY (SDSize+SXSize); ``` Run this to get the Total MySQL Data and Index Usage By Database and Storage Engine ``` SELECT Statistic,DataSize "Data Size",IndexSize "Index Size",TableSize "Table Size" FROM (SELECT IF(ISNULL(table_schema)=1,10,0) schema_score, IF(ISNULL(engine)=1,10,0) engine_score, IF(ISNULL(table_schema)=1,'ZZZZZZZZZZZZZZZZ',table_schema) schemaname, IF(ISNULL(B.table_schema)+ISNULL(B.engine)=2,"Storage for All Databases", IF(ISNULL(B.table_schema)+ISNULL(B.engine)=1, CONCAT("Storage for ",B.table_schema), CONCAT(B.engine," Tables for ",B.table_schema))) Statistic, CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') DataSize,CONCAT(LPAD(REPLACE( FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') IndexSize, CONCAT(LPAD(REPLACE(FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ', SUBSTR(' KMGTP',pw+1,1),'B') TableSize FROM (SELECT table_schema,engine, SUM(data_length) DSize,SUM(index_length) ISize, SUM(data_length+index_length) TSize FROM information_schema.tables WHERE table_schema NOT IN ('mysql','information_schema','performance_schema') AND engine IS NOT NULL GROUP BY table_schema,engine WITH ROLLUP) B, (SELECT 3 pw) A) AA ORDER BY schemaname,schema_score,engine_score; ``` CAVEAT In each query, you will see `(SELECT 3 pw)`. The pw stands for the Power Of 1024 to display the results. * `(SELECT 0 pw)` will Display the Report in Bytes * `(SELECT 1 pw)` will Display the Report in KiloBytes * `(SELECT 2 pw)` will Display the Report in MegaBytes * `(SELECT 3 pw)` will Display the Report in GigaBytes * `(SELECT 4 pw)` will Display the Report in TeraBytes * `(SELECT 5 pw)` will Display the Report in PetaBytes (please contact me if you run this one) Here is a report query with a little less formatting: ``` SELECT IFNULL(db,'Total') "Database", datsum / power(1024,pw) "Data Size", ndxsum / power(1024,pw) "Index Size", totsum / power(1024,pw) "Total" FROM (SELECT db,SUM(dat) datsum,SUM(ndx) ndxsum,SUM(dat+ndx) totsum FROM (SELECT table_schema db,data_length dat,index_length ndx FROM information_schema.tables WHERE engine IS NOT NULL AND table_schema NOT IN ('information_schema','mysql')) AA GROUP BY db WITH ROLLUP) A,(SELECT 1 pw) B; ``` Trust me, I made these queries over 4 years ago and still use them today. UPDATE 2013-06-24 15:53 EDT =========================== I have something new. I have changed the queries so that you do not have to set the `pw` parameter for different unit displays. Each unit display is calculated for you. Report By Storage Engine ``` SELECT IFNULL(ENGINE,'Total') "Storage Engine", LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ', SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size", LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ', SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size", LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ', SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size" FROM ( SELECT ENGINE,DAT,NDX,TBL, IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3 FROM (SELECT *, FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px, FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py, FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz FROM (SELECT ENGINE, SUM(data_length) DAT, SUM(index_length) NDX, SUM(data_length+index_length) TBL FROM ( SELECT engine,data_length,index_length FROM information_schema.tables WHERE table_schema NOT IN ('information_schema','performance_schema','mysql') AND ENGINE IS NOT NULL ) AAA GROUP BY ENGINE WITH ROLLUP ) AAA ) AA) A,(SELECT ' BKBMBGBTB' units) B; ``` Report By Database ``` SELECT IFNULL(DB,'Total') "Database", LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ', SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size", LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ', SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size", LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ', SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size" FROM ( SELECT DB,DAT,NDX,TBL, IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3 FROM (SELECT *, FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px, FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py, FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz FROM (SELECT DB, SUM(data_length) DAT, SUM(index_length) NDX, SUM(data_length+index_length) TBL FROM ( SELECT table_schema DB,data_length,index_length FROM information_schema.tables WHERE table_schema NOT IN ('information_schema','performance_schema','mysql') AND ENGINE IS NOT NULL ) AAA GROUP BY DB WITH ROLLUP ) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B; ``` Report By Database / Storage Engine ``` SELECT IF(ISNULL(DB)+ISNULL(ENGINE)=2,'Database Total', CONCAT(DB,' ',IFNULL(ENGINE,'Total'))) "Reported Statistic", LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ', SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size", LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ', SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size", LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ', SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size" FROM ( SELECT DB,ENGINE,DAT,NDX,TBL, IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3 FROM (SELECT *, FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px, FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py, FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz FROM (SELECT DB,ENGINE, SUM(data_length) DAT, SUM(index_length) NDX, SUM(data_length+index_length) TBL FROM ( SELECT table_schema DB,ENGINE,data_length,index_length FROM information_schema.tables WHERE table_schema NOT IN ('information_schema','performance_schema','mysql') AND ENGINE IS NOT NULL ) AAA GROUP BY DB,ENGINE WITH ROLLUP ) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B; ```
184,590
<p>Is there a way to do this in one line?</p> <pre><code>$x =~ s/^\s+//; $x =~ s/\s+$//; </code></pre> <p>In other words, remove all leading and trailing whitespace from a string.</p>
[ { "answer_id": 184610, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 2, "selected": false, "text": "<p>Here you go: <code>$x =~ s/\\A\\s*(.*?)\\s*\\z/$1/;\n</code></p>\n" }, { "answer_id": 184612, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>$x =~ s/(^\\s+)|(\\s+$)//g;</p>\n" }, { "answer_id": 184613, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": -1, "selected": false, "text": "<pre><code>$x =~ s/^\\s*(.*?)\\s*$/$1/;\n</code></pre>\n" }, { "answer_id": 184615, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 0, "selected": false, "text": "<p>Or this: <code>s/\\A\\s*|\\s*\\Z//g</code></p>\n" }, { "answer_id": 184620, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<pre><code>s/^\\s*(\\S*\\S)\\s*$/$1/\n</code></pre>\n" }, { "answer_id": 184622, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 6, "selected": true, "text": "<pre><code>$x =~ s/^\\s+|\\s+$//g;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>s/^\\s+//, s/\\s+$// for $x;\n</code></pre>\n" }, { "answer_id": 184829, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 5, "selected": false, "text": "<p>My first question is ... why? I don't see any of the single-regexp solutions to be any more readable than the regexp you started with. And they sure aren't anywhere near as fast.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse Benchmark qw(:all);\n\nmy $a = 'a' x 1_000;\n\nmy @x = (\n \" $a \",\n \"$a \",\n $a,\n \" $a\"\n );\n\ncmpthese(-5,\n {\n single =&gt; sub {\n for my $s (@x)\n {\n my $x = $s;\n $x =~ s/^\\s+|\\s+$//g;\n }\n },\n double =&gt; sub {\n for my $s (@x)\n {\n my $x = $s;\n $x =~ s/^\\s+//;\n $x =~ s/\\s+$//;\n }\n },\n trick =&gt; sub {\n for my $s (@x)\n {\n my $x = $s;\n s/^\\s+//, s/\\s+$// for $x;\n }\n },\n capture =&gt; sub {\n for my $s (@x)\n {\n my $x = $s;\n $x =~ s/\\A\\s*(.*?)\\s*\\z/$1/\n }\n },\n kramercap =&gt; sub {\n for my $s (@x)\n {\n my $x = $s;\n ($x) = $x =~ /^\\s*(.*?)\\s*$/\n }\n },\n }\n );\n</code></pre>\n\n<p>gives results on my machine of:</p>\n\n<pre>\n Rate single capture kramercap trick double\nsingle 2541/s -- -12% -13% -96% -96%\ncapture 2902/s 14% -- -0% -95% -96%\nkramercap 2911/s 15% 0% -- -95% -96%\ntrick 60381/s 2276% 1981% 1974% -- -7%\ndouble 65162/s 2464% 2145% 2138% 8% --\n</pre>\n\n<p><strong>Edit</strong>: runrig is right, but to little change. I've updated the code to copy the string before modification, which, of course, slows things down. I also took into account brian d foy's suggestion in another answer to use a longer string (though a million seemed like overkill). However, that also suggests that before you choose the trick style, you figure out what your string lengths are like - the advantages of trick are lessened with shorter strings. At all lengths I've tested, though, double wins. And it's still easier on the eyes.</p>\n" }, { "answer_id": 184953, "author": "Logan", "author_id": 1127433, "author_profile": "https://Stackoverflow.com/users/1127433", "pm_score": 3, "selected": false, "text": "<p>Arguing from the heretical, why do it at all? All of the above solutions are \"correct\" in that they trim whitespace from both sides of the string in one pass, but none are terribly readable (expect maybe <a href=\"https://stackoverflow.com/questions/184590/is-there-a-perl-compatible-regular-expression-to-trim-whitespace-from-both-side#184612\">this one</a>). Unless the audience for your code is comprised of expert-level Perl coders each of the above candidates should have a comment describing what they do (probably a good idea anyway). By contrast, these two lines accomplish the same thing without using lookaheads, wildcards, midichlorines or anything that isn't immediately obvious to a programmer of moderate experience:</p>\n\n<pre><code>$string =~ s/^\\s+//;\n$string =~ s/\\s+$//;\n</code></pre>\n\n<p>There is (arguably) a performance hit, but as long as you aren't concerned with a few microseconds at execution the added readability will be worth it. IMHO.</p>\n" }, { "answer_id": 185018, "author": "benjismith", "author_id": 22979, "author_profile": "https://Stackoverflow.com/users/22979", "pm_score": 3, "selected": false, "text": "<p>Funny you should bring this up!</p>\n\n<p>I recently read <a href=\"http://blog.stevenlevithan.com/archives/faster-trim-javascript\" rel=\"nofollow noreferrer\">an article analyzing the performance of twelve (!) different trim implementations</a>.</p>\n\n<p>Although the article specifically uses the JavaScript regex implementation, it uses Perl syntax, so I think it's apropos to this discussion.</p>\n" }, { "answer_id": 185125, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>Tanktalus shows a benchmark for very small strings, but the problems get worse as the strings get bigger. In his code, I changed the top portion:</p>\n\n<pre><code>my $a = 'a' x 1_000_000;\n\nmy @x = (\n \" $a \",\n \"$a \",\n $a,\n \" $a\"\n );\n</code></pre>\n\n<p>I get these results:</p>\n\n<pre><code> Rate single capture trick double\nsingle 2.09/s -- -12% -98% -98%\ncapture 2.37/s 13% -- -98% -98%\ntrick 96.0/s 4491% 3948% -- -0%\ndouble 96.4/s 4512% 3967% 0% --\n</code></pre>\n\n<p>As the string gets bigger, using \"trick\" and \"double\" are almost the same, and the common solution that most people go for, the \"single\" (including me, because I can't break that habit even though I know this), really starts to suck.</p>\n\n<p>Whenever you look at a benchmark, think about what it's telling you. To see if you understand it, change the data and try again. Make arrays long, scalars big, and so on. Make loops, greps, or regexes find stuff at the start, middle, and end. See if the new results match your prediction. Figure out what the trend is. Does performance get better and better, approach a limit, peak then start to decline, or something else?</p>\n" }, { "answer_id": 185272, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 1, "selected": false, "text": "<p>I usually do it like this:</p>\n\n<pre><code>($foo) = $foo =~ /^\\s*(.*?)\\s*$/;\n</code></pre>\n\n<p>Everything between the leading spaces and the trailing spaces is grouped and returned, so I can assign it to the same old variable.</p>\n" }, { "answer_id": 1710629, "author": "Shashidhar Vajramatti", "author_id": 208101, "author_profile": "https://Stackoverflow.com/users/208101", "pm_score": -1, "selected": false, "text": "<pre><code>$var1 =~ s/(^\\s*)(.*?)(\\s*$)+/$2/;\n</code></pre>\n" }, { "answer_id": 63265988, "author": "HappyFace", "author_id": 1410221, "author_profile": "https://Stackoverflow.com/users/1410221", "pm_score": 0, "selected": false, "text": "<p>In zsh with PCRE mode active:</p>\n<pre><code>function trim() {\n local out=&quot;$*&quot;\n [[ &quot;$out&quot; =~ '^\\s*(.*\\S)\\s*$' ]] &amp;&amp; out=&quot;$match[1]&quot; || out=''\n print -nr -- &quot;$out&quot;\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
Is there a way to do this in one line? ``` $x =~ s/^\s+//; $x =~ s/\s+$//; ``` In other words, remove all leading and trailing whitespace from a string.
``` $x =~ s/^\s+|\s+$//g; ``` or ``` s/^\s+//, s/\s+$// for $x; ```
184,592
<p>I have topics(id*) and tags(id*,name) and a linking table topic_tags(topicFk*,tagFk*).</p> <p>Now I want to select every single topic, that has all of the good tags (a,b,c) but none of the bad tags (d,e,f).</p> <p>How do I do that?</p>
[ { "answer_id": 184614, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>Here's a solution that would work, but requires a join for every tag you require. </p>\n\n<blockquote>\n<pre><code>SELECT *\nFROM topics\nWHERE topic_id IN\n (SELECT topic_id\n FROM topic_tags a\n INNER JOIN topic_tags b\n on a.topic_id=b.topic_id\n and b.tag = 'b'\n INNER JOIN topic_tags c\n on b.topic_id=c.topic_d\n and c.tag = 'c'\n WHERE a.tag = 'a')\nAND topic_id NOT IN\n (SELECT topic_id\n FROM topic_tags\n WHERE tag = 'd' or tag = 'e' or tag = 'f')\n</code></pre>\n</blockquote>\n" }, { "answer_id": 184655, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "<p>Not completely sure I understand, and I hope there's a better way to do the good tags part, but:</p>\n\n<pre><code>select id from topic\n inner join topic_tags tta on topic.id=tta.topicFk and tta.tagFk=a\n inner join topic_tags ttb on topic.id=ttb.topicFk and ttb.tagFk=b\n inner join topic_tags ttc on topic.id=ttc.topicFk and ttc.tagFk=c\n left join topic_tags tt on topic.id=tt.topicFk and tt.tagFk in (d,e,f)\n where tt.topicFk is null;\n</code></pre>\n\n<p>Update: something like this:</p>\n\n<pre><code>select id from topic\n left join topic_tags tt on topic.id=tt.topicFk and tt.tagFk in (d,e,f)\n where tt.topicFk is null and\n 3=(select count(*) from topic_tags where topicFk=topic.id and tagFk in (a,b,c));\n</code></pre>\n\n<p>I see one answer assuming a,b,c,d,e,f are names, not ids. If so, then this:</p>\n\n<pre><code>select id from topic\n left join topic_tags tt on topic.id=tt.topicFk\n inner join tags on tt.tagFk=tags.id and tags.name in (d,e,f)\n where tt.topicFk is null and\n 3=(select count(*) from tags inner join topic_tags on tags.id=topic_tags.tagFk and topic_tags.topicFk=topic.id where tags.name in (a,b,c));\n</code></pre>\n" }, { "answer_id": 184674, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>As wrote this 3 other answers came in, but this is different so I'll post it anyway.</p>\n\n<p>The idea is to select all topics with have a,b,c tags, then identify those topics that also have d,e,f with a left join, and then filter those out with a where clause looking for nulls on that join...</p>\n\n<pre><code>select distinct topics.id from topics \ninner join topic_tags as t1 \n on (t1.topicFK=topics.id)\ninner join tags as goodtags \n on(goodtags.id=t1.tagFK and goodtags.name in ('a', 'b', 'c'))\nleft join topic_tags as t2 \n on (t2.topicFK=topics.id)\nleft join tags as badtags \n on(badtags .id=t2.tagFK and batags.name in ('d', 'e', 'f'))\nwhere badtags.name is null;\n</code></pre>\n\n<p>Totally untested, but hopefully you see where the logic is coming from.</p>\n" }, { "answer_id": 184705, "author": "Pablo Venturino", "author_id": 16732, "author_profile": "https://Stackoverflow.com/users/16732", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>minus</code> keyword, to filter out topics with undesired tags.</p>\n\n<pre><code>-- All topics with desired tags.\nselect distinct T.*\nfrom Topics T inner join Topics_Tags R on T.id = R.topicFK\n inner join Tags U on U.id = R.topic=FK\nwhere U.name in ('a', 'b', 'c')\n\nminus\n\n-- All topics with undesired tags. These are filtered out.\nselect distinct T.*\nfrom Topics T inner join Topics_Tags R on T.id = R.topicFK\n inner join Tags U on U.id = R.topic=FK\nwhere U.name in ('d', 'e', 'f')\n</code></pre>\n" }, { "answer_id": 184887, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "<p>Assuming your Topic_Tags table is unique, this answers your <em>exact</em> question - but may not be generalizable to your actual problem:</p>\n\n<pre><code>SELECT\n TopicId\nFROM Topic_Tags\nJOIN Tags ON\n Topic_Tags.TagId = Tags.TagId\nWHERE\n Tags.Name IN ('A', 'B', 'C', 'D', 'E', 'F')\nGROUP BY\n TopicId\nHAVING\n COUNT(*) = 3 \n AND MAX(Tags.Name) = 'C'\n</code></pre>\n\n<p>A more general solution would be:</p>\n\n<pre><code>SELECT \n * \nFROM (\n SELECT\n TopicId\n FROM Topic_Tags\n JOIN Tags ON\n Topic_Tags.TagId = Tags.TagId\n WHERE\n Tags.Name IN ('A', 'B', 'C')\n GROUP BY\n TopicId\n HAVING\n COUNT(*) = 3 \n) as GoodTags\nLEFT JOIN (\n SELECT\n TopicId\n FROM Topic_Tags\n JOIN Tags ON\n Topic_Tags.TagId = Tags.TagId\n WHERE\n Tags.Name = 'D'\n OR Tags.Name = 'E'\n OR Tags.Name = 'F'\n) as BadTags ON\n GoodTags.TopicId = BadTags.TopicId\nWHERE\n BadTags.TopicId IS NULL\n</code></pre>\n" }, { "answer_id": 184943, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>Here's another alternative query. Maybe it's more clear and convenient to have the list of good and bad tags up at the top. I tested this on MySQL 5.0.</p>\n\n<pre><code>SELECT t.*, \n SUM(CASE WHEN g.name IN ('a', 'b', 'c') THEN 1 ELSE 0 END) AS num_good_tags,\n SUM(CASE WHEN g.name IN ('d', 'e', 'f') THEN 1 ELSE 0 END) AS num_bad_tags\nFROM topics AS t\n JOIN topic_tags AS tg ON (t.id = tg.topicFk)\n JOIN tags AS g ON (g.id = tg.tagFk)\nGROUP BY t.id\nHAVING num_good_tags = 3 AND num_bad_tags = 0;\n</code></pre>\n" }, { "answer_id": 185514, "author": "defnull", "author_id": 407880, "author_profile": "https://Stackoverflow.com/users/407880", "pm_score": 1, "selected": true, "text": "<p>My own solution using Pauls and Bills ideas.</p>\n\n<p>The idea is to inner join topics with good tags (to throw out topics with no good tags) and then count the unique tags for each topic (to verify that all the good tags are present).</p>\n\n<p>At the same time an outer join with bad tags should have not a single match (all fields are NULL).</p>\n\n<pre><code>SELECT topics.id\nFROM topics\n INNER JOIN topic_tags topic_ptags\n ON topics.id = topic_ptags.topicFk\n INNER JOIN tags ptags\n ON topic_ptags.tagFk = ptags.id\n AND ptags.name IN ('a','b','c')\n LEFT JOIN topic_tags topic_ntags\n ON topics.id = topic_ntags.topicFk\n LEFT JOIN tags ntags\n ON topic_ntags.tagFk = ntags.id\n AND ntags.name IN ('d','e','f')\nGROUP BY topics.id\nHAVING count(DISTINCT ptags.id) = 3\n AND count(ntags.id) = 0\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407880/" ]
I have topics(id\*) and tags(id\*,name) and a linking table topic\_tags(topicFk\*,tagFk\*). Now I want to select every single topic, that has all of the good tags (a,b,c) but none of the bad tags (d,e,f). How do I do that?
My own solution using Pauls and Bills ideas. The idea is to inner join topics with good tags (to throw out topics with no good tags) and then count the unique tags for each topic (to verify that all the good tags are present). At the same time an outer join with bad tags should have not a single match (all fields are NULL). ``` SELECT topics.id FROM topics INNER JOIN topic_tags topic_ptags ON topics.id = topic_ptags.topicFk INNER JOIN tags ptags ON topic_ptags.tagFk = ptags.id AND ptags.name IN ('a','b','c') LEFT JOIN topic_tags topic_ntags ON topics.id = topic_ntags.topicFk LEFT JOIN tags ntags ON topic_ntags.tagFk = ntags.id AND ntags.name IN ('d','e','f') GROUP BY topics.id HAVING count(DISTINCT ptags.id) = 3 AND count(ntags.id) = 0 ```
184,609
<p>Consider the following two ways of writing a loop in Java to see if a list contains a given value:</p> <h3>Style 1</h3> <pre><code>boolean found = false; for(int i = 0; i &lt; list.length &amp;&amp; !found; i++) { if(list[i] == testVal) found = true; } </code></pre> <h3>Style 2</h3> <pre><code>boolean found = false; for(int i = 0; i &lt; list.length &amp;&amp; !found; i++) { found = (list[i] == testVal); } </code></pre> <p>The two are equivalent, but I always use style 1 because 1) I find it more readable, and 2) I am assuming that reassigning <code>found</code> to <code>false</code> hundreds of times feels like it would take more time. I am wondering: is this second assumption true?</p> <h3>Nitpicker's corner</h3> <ul> <li>I am well aware that this is a case of premature optimization. That doesn't mean that it isn't something that is useful to know.</li> <li>I don't care which style you think is more readable. I am only interested in whether one has a performance penalty compared to the other.</li> <li>I know that style 1 has the advantage of allowing you to also put a <code>break;</code> statement in the <code>if</code> block, but I don't care. Again, this question is about performance, not style.</li> </ul>
[ { "answer_id": 184623, "author": "sepang", "author_id": 25930, "author_profile": "https://Stackoverflow.com/users/25930", "pm_score": 1, "selected": false, "text": "<p>It depends on what compiler you use since different compilers might do different optimizations.</p>\n" }, { "answer_id": 184624, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 0, "selected": false, "text": "<p>I would say that in 98% of systems, it does not matter. The difference, if there is any, is hardly noticeable unless that loop is the main portion of code and is running a mindnumbing number of times.</p>\n\n<p>Edit: That is ofcourse assuming that it is not being already optimized by the compiler.</p>\n" }, { "answer_id": 184626, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 2, "selected": false, "text": "<p>Actually, the \"if\" will slow your program down more than assignment due to the <a href=\"http://en.wikipedia.org/wiki/Pipeline_(computing)\" rel=\"nofollow noreferrer\">pipeline</a>.</p>\n" }, { "answer_id": 184630, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>Any decent compiler would keep found in a register for a duration of the loop and so the cost is absolutely negligible.</p>\n\n<p>If the second style is done without a branch then it would be preferable, since the CPU's pipeline will not get disrupted as much ... but that depends on how the compiler uses the instruction set.</p>\n" }, { "answer_id": 184632, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>I believe style 2 is ever-so-slightly faster - say 1 clock cycle or so.</p>\n\n<p>I'd rewrite it into the following, though, if I were tackling it:</p>\n\n<pre><code>for(i=0; i&lt;list.length &amp;&amp; list[i]!=testval; i++);\nboolean found = (i!=list.length);\n</code></pre>\n" }, { "answer_id": 184680, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "<p>This will only be measurable in code which is extremely performance-sensitive (simulators, emulators, video encoding software, etc.) in which case you probably want to manually inspect the generated code anyway to make sure that the compiler actually generates sensible code.</p>\n" }, { "answer_id": 184762, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 4, "selected": true, "text": "<p>Well, just write a micro benchmark:</p>\n\n<pre>\nimport java.util.*;\n\npublic class Test {\n private static int[] list = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9} ;\n private static int testVal = 6;\n\n\n public static boolean version1() {\n boolean found = false;\n for(int i = 0; i &lt; list.length && !found; i++)\n {\n if(list[i] == testVal)\n found = true;\n }\n return found;\n\n }\n\n public static boolean version2() {\n boolean found = false;\n for(int i = 0; i &lt; list.length && !found; i++)\n {\n found = (list[i] == testVal);\n }\n\n return found;\n }\n\n\n public static void main(String[] args) {\n\n // warm up\n for (int i=0; i&lt;100000000; i++) {\n version1();\n version2();\n }\n\n\n long time = System.currentTimeMillis();\n for (int i=0; i&lt;100000000; i++) {\n version1();\n }\n\n System.out.println(\"Version1:\" + (System.currentTimeMillis() - time));\n\n time = System.currentTimeMillis();\n for (int i=0; i@lt;100000000; i++) {\n version2();\n }\n\n System.out.println(\"Version2:\" + (System.currentTimeMillis() - time));\n }\n}\n</pre>\n\n<p>On my machine version1 seems to be a little bit faster:</p>\n\n<p>Version1:5236</p>\n\n<p>Version2:5477</p>\n\n<p>(But that's 0.2 seconds on a 100 million iterations. I wouldn't care about this.)</p>\n\n<p>If you look at the generated bytecode there are two more instructions in version2 which probably cause the longer execution time:</p>\n\n<pre>\npublic static boolean version1();\n Code:\n 0: iconst_0\n 1: istore_0\n 2: iconst_0\n 3: istore_1\n 4: iload_1\n 5: getstatic #2; //Field list:[I\n 8: arraylength\n 9: if_icmpge 35\n 12: iload_0\n 13: ifne 35\n 16: getstatic #2; //Field list:[I\n 19: iload_1\n 20: iaload\n 21: getstatic #3; //Field testVal:I\n 24: if_icmpne 29\n 27: iconst_1\n 28: istore_0\n 29: iinc 1, 1\n 32: goto 4\n 35: iload_0\n 36: ireturn\n\npublic static boolean version2();\n Code:\n 0: iconst_0\n 1: istore_0\n 2: iconst_0\n 3: istore_1\n 4: iload_1\n 5: getstatic #2; //Field list:[I\n 8: arraylength\n 9: if_icmpge 39\n 12: iload_0\n 13: ifne 39\n 16: getstatic #2; //Field list:[I\n 19: iload_1\n 20: iaload\n 21: getstatic #3; //Field testVal:I\n 24: if_icmpne 31\n 27: iconst_1\n 28: goto 32\n 31: iconst_0\n 32: istore_0\n 33: iinc 1, 1\n 36: goto 4\n 39: iload_0\n 40: ireturn\n</pre>\n" }, { "answer_id": 184772, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>To be sure, you should compile both versions (say with latest compiler from Sun) and examine the generated bytecode with an appropriate tool... That's the only reliable way to know for sure, everything else is wild guess.</p>\n" }, { "answer_id": 184776, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>It seems to me that if you expect your value to be found before the end of the list, you'd be better off with #2 - as it short circuits the check with !found in the loop conditional. Assuming you put a break in, the 1st option (the only sensible thing, IMO), then pseudo assembly would look something like:</p>\n\n<p>Option 1:</p>\n\n<pre><code>start:\n CMP i, list.length\n JE end\n CMP list[i], testval\n JE equal\n JMP start\nequal:\n MOV true, found\nend:\n</code></pre>\n\n<p>Option 2:</p>\n\n<pre><code>start:\n CMP i, list.length\n JE end\n CMP true, found\n JE end\n CMP list[i], testval\n JE equal\n JNE notequal\nequal:\n MOV true, found\n JMP start\nnotequal:\n MOV false, found\n JMP start\nend:\n</code></pre>\n\n<p>I'd say Option 1 is superior here, as it's about 1/3rd less instructions. Of course, this is without optimizations - but that'd be compiler and situation specific (what is found doing after this? can we just optimize it away all together?).</p>\n" }, { "answer_id": 185064, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<pre><code>boolean found = false;\nfor(int i = 0; i &lt; list.length &amp;&amp; !found; i++)\n{\n if(list[i] == testVal)\n found = true;\n}\n</code></pre>\n\n<p>I don't see a break statement in the block.</p>\n\n<p>Other than that, I prefer this style. It improves readability and thereby the chance that a maintainer mis-reading and mis-fixing it.</p>\n" }, { "answer_id": 185071, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Comment about nitpicks corner:</p>\n\n<p>If you're <em>really</em> concerned with absolute performance, putting a break in and removing the \"&amp;&amp; !found\" will give you theoretically better performance on #1. Two less binary ops to worry about every iteration. </p>\n\n<p>If you wanted to get really anal about optimization without using breaks then</p>\n\n<pre><code>boolean notFound = true;\n for(int i = 0; notFound &amp;&amp; i &lt; list.length; i++)\n {\n if(list[i] == testVal)\n notFound = false;\n }\n</code></pre>\n\n<p>will run faster in the average case than the existing option #1.</p>\n\n<p>And of course it's personal preference, but I prefer to never put any extra evaluations inside the head of a for loop. I find it can cause confusion while reading code, because it's easy to miss. If I can't get the desired behavior using break/continues I will use a while or do/while loop instead.</p>\n" }, { "answer_id": 208139, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here is another style</p>\n\n<pre><code>for(int i = 0; i &lt; list.length; i++)\n{\n if(list[i] == testVal)\n return true;\n}\n\nreturn false;\n</code></pre>\n" }, { "answer_id": 304656, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "<p>I think both alternatives leave something to be desired, from a performance point of view. </p>\n\n<p>Think about how many tests (which are almost always jumps) you do per iteration, and try to minimize the amount.</p>\n\n<p>The solution by Matt, to return out when the answer is found, reduces the number of tests from three (loop iterator, found-test in loop, actual comparison) to two. Doing the \"found\"-test essentially twice is wasteful.</p>\n\n<p>I'm not sure if the classic, but somewhat obfuscating, trick of looping backwards is a win in Java, and not hot enough at reading JVM code to figure it out right now, either.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
Consider the following two ways of writing a loop in Java to see if a list contains a given value: ### Style 1 ``` boolean found = false; for(int i = 0; i < list.length && !found; i++) { if(list[i] == testVal) found = true; } ``` ### Style 2 ``` boolean found = false; for(int i = 0; i < list.length && !found; i++) { found = (list[i] == testVal); } ``` The two are equivalent, but I always use style 1 because 1) I find it more readable, and 2) I am assuming that reassigning `found` to `false` hundreds of times feels like it would take more time. I am wondering: is this second assumption true? ### Nitpicker's corner * I am well aware that this is a case of premature optimization. That doesn't mean that it isn't something that is useful to know. * I don't care which style you think is more readable. I am only interested in whether one has a performance penalty compared to the other. * I know that style 1 has the advantage of allowing you to also put a `break;` statement in the `if` block, but I don't care. Again, this question is about performance, not style.
Well, just write a micro benchmark: ``` import java.util.*; public class Test { private static int[] list = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9} ; private static int testVal = 6; public static boolean version1() { boolean found = false; for(int i = 0; i < list.length && !found; i++) { if(list[i] == testVal) found = true; } return found; } public static boolean version2() { boolean found = false; for(int i = 0; i < list.length && !found; i++) { found = (list[i] == testVal); } return found; } public static void main(String[] args) { // warm up for (int i=0; i<100000000; i++) { version1(); version2(); } long time = System.currentTimeMillis(); for (int i=0; i<100000000; i++) { version1(); } System.out.println("Version1:" + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); for (int i=0; i@lt;100000000; i++) { version2(); } System.out.println("Version2:" + (System.currentTimeMillis() - time)); } } ``` On my machine version1 seems to be a little bit faster: Version1:5236 Version2:5477 (But that's 0.2 seconds on a 100 million iterations. I wouldn't care about this.) If you look at the generated bytecode there are two more instructions in version2 which probably cause the longer execution time: ``` public static boolean version1(); Code: 0: iconst_0 1: istore_0 2: iconst_0 3: istore_1 4: iload_1 5: getstatic #2; //Field list:[I 8: arraylength 9: if_icmpge 35 12: iload_0 13: ifne 35 16: getstatic #2; //Field list:[I 19: iload_1 20: iaload 21: getstatic #3; //Field testVal:I 24: if_icmpne 29 27: iconst_1 28: istore_0 29: iinc 1, 1 32: goto 4 35: iload_0 36: ireturn public static boolean version2(); Code: 0: iconst_0 1: istore_0 2: iconst_0 3: istore_1 4: iload_1 5: getstatic #2; //Field list:[I 8: arraylength 9: if_icmpge 39 12: iload_0 13: ifne 39 16: getstatic #2; //Field list:[I 19: iload_1 20: iaload 21: getstatic #3; //Field testVal:I 24: if_icmpne 31 27: iconst_1 28: goto 32 31: iconst_0 32: istore_0 33: iinc 1, 1 36: goto 4 39: iload_0 40: ireturn ```
184,618
<p>What is the best comment in source code you have ever encountered?</p>
[ { "answer_id": 184629, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 5, "selected": false, "text": "<pre><code>//ALL YOUR BASE ARE BELONG TO US\n</code></pre>\n\n<p>...it made my boss think someone had hacked in. He didn't know the joke.</p>\n" }, { "answer_id": 184633, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": false, "text": "<pre><code>Get This hack!\n</code></pre>\n\n<p>On a line of assembler code, after pages of uncommented code.</p>\n" }, { "answer_id": 184635, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 3, "selected": false, "text": "<p>I found this:</p>\n\n<pre><code>I'm not sure what I did\n</code></pre>\n" }, { "answer_id": 184637, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": 3, "selected": false, "text": "<pre><code>// TODO: Implement this function!\n</code></pre>\n" }, { "answer_id": 184638, "author": "StubbornMule", "author_id": 13341, "author_profile": "https://Stackoverflow.com/users/13341", "pm_score": 8, "selected": false, "text": "<pre><code>//I am not sure why this works but it fixes the problem. \n</code></pre>\n\n<p>This was before a set of code that technically did fix the problem it was meant to but broke 3 other things....</p>\n" }, { "answer_id": 184639, "author": "Alejo", "author_id": 23084, "author_profile": "https://Stackoverflow.com/users/23084", "pm_score": 4, "selected": false, "text": "<p>Best one so far:</p>\n\n<pre><code>\"This code makes baby Jesus very sad!\". \n</code></pre>\n\n<p>It was refering an String iniciatilization like this:</p>\n\n<pre><code>String blankSpaces=\"&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; \"+ //100 whitespaces\n \"&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; \"+ //200 Whitespaces\n ...\n \" \" //100 whitespaces\n</code></pre>\n\n<p>Well you get the idea.</p>\n" }, { "answer_id": 184649, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 8, "selected": false, "text": "<pre><code>/* Please work */\n</code></pre>\n" }, { "answer_id": 184656, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 7, "selected": false, "text": "<p>Next to a local variable that had to be declared just to pass a constant to a library function:</p>\n\n<pre><code>// This only exists because Scott doesn't know how to use const correctly\n</code></pre>\n" }, { "answer_id": 184670, "author": "Dave Verwer", "author_id": 4496, "author_profile": "https://Stackoverflow.com/users/4496", "pm_score": 8, "selected": false, "text": "<p>Many years ago (about 1994) I was working on a Oracle PRO*C application for a large multi-national software company that you will have heard of. The app I was working on was a massive Oracle application and they had a utility that ran overnight tidying up data and doing all sorts of aggregate calculations. Every time anything needed doing as a batch job, it got shoved into this utility and as you can imagine it became an absolute monstrosity. It was also notable for the tiny number of comments that it had for such a massive program.</p>\n\n<p>One of the few comments it did have remains the finest comment I have ever seen for pure WTF'ness... I was trying to find a bug in a function which was hundreds of lines long and right in the middle of it was the <strong>only</strong> comment in the function:</p>\n\n<pre><code>/* I did this the other way */\n</code></pre>\n\n<p>To this day it is still the finest comment I have ever seen.</p>\n" }, { "answer_id": 184672, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 8, "selected": false, "text": "<pre><code>/* You are not meant to understand this */ \n</code></pre>\n" }, { "answer_id": 184673, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 10, "selected": false, "text": "<blockquote>\n<pre><code>//Code sanitized to protect the foolish.\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\nusing System.Web.UI;\n\nnamespace Mobile.Web.Control\n{\n /// &lt;summary&gt;\n /// Class used to work around Richard being a fucking idiot\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// The point of this is to work around his poor design so that paging will \n /// work on a mobile control. The main problem is the BindCompany() method, \n /// which he hoped would be able to do everything. I hope he dies.\n /// &lt;/remarks&gt;\n public abstract class RichardIsAFuckingIdiotControl : MobileBaseControl, ICompanyProfileControl\n {\n protected abstract Pager Pager { get; }\n\n public void BindCompany(int companyId) { }\n\n public RichardIsAFuckingIdiotControl()\n {\n MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity();\n }\n\n private void MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity()\n {\n // Make sure nobody is actually using that fucking bindcompany method\n MethodInfo m = this.GetType().GetMethod(\"BindCompany\", BindingFlags.DeclaredOnly | \n BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n if (m != null)\n {\n throw new RichardIsAFuckingIdiotException(\"No!! Don't use the fucking BindCompany method!!!\");\n }\n // P.S. this method is a joke ... the rest of the class is fucking serious\n }\n\n /// &lt;summary&gt;\n /// This returns true if this control is supposed to be doing anything\n /// at all for this request. Richard thought it was a good idea to load\n /// the entire website during every request and have things turn themselves\n /// off. He also thought bandanas and aviator sunglasses were \"fuckin' \n /// gnarly, dude.\"\n /// &lt;/summary&gt;\n protected bool IsThisTheRightPageImNotSureBecauseRichardIsDumb()\n {\n return Request.QueryString[\"Section\"] == this.MenuItemKey;\n }\n\n protected override void OnLoad(EventArgs e)\n {\n if (IsThisTheRightPageImNotSureBecauseRichardIsDumb())\n {\n Page.LoadComplete += new EventHandler(Page_LoadComplete);\n Pager.RowCount = GetRowCountBecauseRichardIsDumb();\n }\n base.OnLoad(e);\n }\n\n protected abstract int GetRowCountBecauseRichardIsDumb();\n protected abstract void BindDataBecauseRichardIsDumb();\n\n void Page_LoadComplete(object sender, EventArgs e)\n {\n BindDataBecauseRichardIsDumb();\n }\n\n // the rest of his reduh-ndant interface members\n public abstract string MenuItemName { get; set; }\n public abstract string MenuItemKey { get; set; }\n public abstract bool IsCapable(CapabilityCheck checker, int companyId);\n public abstract bool ShowInMenu { get; }\n public virtual Control CreateHeaderControl()\n {\n return null;\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p><strong>Update:</strong> The original author of the code <a href=\"http://mcfunley.com/438/from-the-annals-of-dubious-achievement\" rel=\"nofollow noreferrer\">has outed himself</a> so I must give credit where it is due. <a href=\"http://mcfunley.com/\" rel=\"nofollow noreferrer\">Dan McKinley</a> left the company I was with shortly after I started, and he talks more about the code, explaining some background and a few more \"WTF's\" that 'Richard' wrote.</p>\n" }, { "answer_id": 184682, "author": "Randyaa", "author_id": 9518, "author_profile": "https://Stackoverflow.com/users/9518", "pm_score": 9, "selected": false, "text": "<pre><code>Catch (Exception e) {\n //who cares?\n} \n</code></pre>\n" }, { "answer_id": 184696, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 5, "selected": false, "text": "<p>I have used this one on more than one occasion, when I've done some kind of non-obvious simplification to a mathematical formula that I don't feel like documenting:</p>\n\n<pre><code>//this formula is right, work out the math yourself if you don't believe me\n</code></pre>\n" }, { "answer_id": 184701, "author": "Greg D", "author_id": 6932, "author_profile": "https://Stackoverflow.com/users/6932", "pm_score": 9, "selected": false, "text": "<pre><code>// I'm sorry.\n</code></pre>\n" }, { "answer_id": 184720, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 6, "selected": false, "text": "<p>At the top of a header file:</p>\n\n<pre><code>/* Project : XYZ (Please somebody shoot me!)\n *\n * File : $Id: defs.h,v 1.1 $\n *\n * Purpose : Create havoc rather than peace among many nations\n *\n * History : Back-ported changes that were not in CVS. Please somebody,\n * shoot us and put us all out of our misery.\n */\n</code></pre>\n\n<p>The \"XYZ project\" (name changed) was a seven-year ordeal. That last comment was written by the one stalwart soul who was involved from the very beginning through to the end. </p>\n" }, { "answer_id": 184728, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 4, "selected": false, "text": "<p>From <a href=\"http://groups.google.com/group/alt.folklore.computers/msg/ff9be1845aa1797e?hl=en&amp;dmode=source\" rel=\"nofollow noreferrer\">a classic from usenet</a>:</p>\n\n<blockquote>\n <p>Deep inside the Teradyne hardware modeler code is a routine that feeds a\n whole bunch of hex numbers into a SYS$QIO call. The only comment is\n 'Weird magic happens here'. </p>\n</blockquote>\n" }, { "answer_id": 184734, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 3, "selected": false, "text": "<pre><code>// This code sucks.\n</code></pre>\n" }, { "answer_id": 184746, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 3, "selected": false, "text": "<pre><code>{\nThis is a gathering place for all unit tests.\nCreate a TUnitTestWrapper, then call \"RunAllUnitTests\".\n\nThis class will create an instance of each thing to be tested, and call each of\ntheir unit tests.\n\nIt does not really do any testing on it's own; it just gives a common place from\nwhich to call everyone else's tests.\n\nThis way, one day, we can automate our testing with each build. [Cue laughter]\n}\n</code></pre>\n" }, { "answer_id": 184755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>int Q13Factor = 8125; // 2^13 for Q13 \n</code></pre>\n" }, { "answer_id": 184795, "author": "Milner", "author_id": 16575, "author_profile": "https://Stackoverflow.com/users/16575", "pm_score": 5, "selected": false, "text": "<pre><code>-- Comment this later\n</code></pre>\n\n<p>That was line 2 of a 4000+ line PL/SQL procedure. And the only comment. 4 years after that procedure was developed, later still hadn't come...</p>\n" }, { "answer_id": 184807, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 4, "selected": false, "text": "<p>In the header of a code file heavily edited by everyone on the dev team:</p>\n\n<pre><code>'Avert your eyes, it may take on other forms!\n</code></pre>\n\n<p>Good ol' Flanders.</p>\n" }, { "answer_id": 184835, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://cm.bell-labs.com/who/dmr/odd.html\" rel=\"nofollow noreferrer\"><code>//You are not expected to understand this</code></a></p>\n\n<p>classic.</p>\n" }, { "answer_id": 184854, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 8, "selected": false, "text": "<p>in a completely uncommented 2000 line method </p>\n\n<pre><code>{ \n { \n while (.. ){ \n if (..){\n }\n for (.. ){ \n }\n .... (just putting in the control flow here, imagine another few hundred ifs)\n if(..) {\n if(..) {\n if(..) {\n ...\n (another few hundred brackets)\n }\n }\n } //endif\n</code></pre>\n\n<p>(I actually grepped out all the brackets one day just to see how bad it was, and, sans formatting, got this:</p>\n\n<pre><code>{{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{} {{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}\n</code></pre>\n\n<p>The endif showed up around line 800)</p>\n" }, { "answer_id": 184885, "author": "Scott Dillman", "author_id": 10111, "author_profile": "https://Stackoverflow.com/users/10111", "pm_score": 5, "selected": false, "text": "<p>Simple but effective comment, before a less than safe hack in some C++ code</p>\n\n<pre><code>// yikes\n</code></pre>\n" }, { "answer_id": 184924, "author": "rshimoda", "author_id": 23297, "author_profile": "https://Stackoverflow.com/users/23297", "pm_score": 4, "selected": false, "text": "<p>This was actually made by me when I was implementing a prototype turned into real code:</p>\n\n<pre><code>// Abandon all hope you who needs to debug this\n</code></pre>\n\n<p>Yes, someone smarter than me actually refactored the code afterwards (it had to have a good ending).</p>\n" }, { "answer_id": 184949, "author": "CobolGuy", "author_id": 2038447, "author_profile": "https://Stackoverflow.com/users/2038447", "pm_score": 3, "selected": false, "text": "<pre><code>THIS PROGRAM HAS CODE THAT DOES NOT MEET STANDARDS \n</code></pre>\n\n<p>That comment is in nearly every program we have here....</p>\n" }, { "answer_id": 184971, "author": "catfood", "author_id": 12802, "author_profile": "https://Stackoverflow.com/users/12802", "pm_score": 2, "selected": false, "text": "<p>It's not strictly speaking a comment, but...</p>\n\n<p>It was the mid-1990s and I was working on a big migration: small software vendor, <strong>big</strong> client, lots of pressure. We had a lot of shifting-goalpost stuff; the project was very hard to control. I was the key developer, but new to the system, and the other developer was the vendor's owner/founder.</p>\n\n<p>After a few months of not quite making deadlines and not quite satisfying the client, the owner/founder brought on another developer, who was working remotely. (I'm gonna go out on a limb and say the new developer had lesser skills and experience than me.)</p>\n\n<p>Well, the new guy made some changes in code that I'd already worked on, and then a month or two later I was back in the same area of the code, and there were variables I hadn't seen before. With names like <code>StupidMark</code>.</p>\n\n<p>Dude, that's just not right. I mean, there's teamwork considerations, but also: in this environment, <em>variable names can show up in runtime error messages.</em> I'm just saying.</p>\n\n<p>In my opinion at the time, the new guy's code wasn't getting us much closer to a deliverable product anyway, which made the insult sting a little more.</p>\n" }, { "answer_id": 184986, "author": "John Chuckran", "author_id": 25511, "author_profile": "https://Stackoverflow.com/users/25511", "pm_score": 8, "selected": false, "text": "<pre><code>// If this comment is removed the program will blow up \n</code></pre>\n" }, { "answer_id": 185011, "author": "rlerallut", "author_id": 20055, "author_profile": "https://Stackoverflow.com/users/20055", "pm_score": 9, "selected": false, "text": "<p>It speaks volumes about our profession that when asked about the \"best comment\", we all answer with the worst comments we can find...</p>\n" }, { "answer_id": 185016, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>If you have reached this part in the code, then this program sucks.\n</code></pre>\n" }, { "answer_id": 185031, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<pre><code>using namespace std; // So sue me\n</code></pre>\n" }, { "answer_id": 185053, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 7, "selected": false, "text": "<p>The original Doom had an engine with static walls that could not move; the result was that all doors opened vertically; nothing could ever move horizontally. I burst out laughing when, after the source code was released, I was looking through the code and saw this in the source file for handling doors, at the start of a big block of commented-out code:</p>\n\n<pre><code>// UNUSED\n// Separate into p_slidoor.c?\n\n#if 0 // ABANDONED TO THE MISTS OF TIME!!!\n//\n// EV_SlidingDoor : slide a door horizontally\n// (animate midtexture, then set noblocking line)\n//\n</code></pre>\n" }, { "answer_id": 185062, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "<pre><code>// but the \"real\" solution is much more complicated\n</code></pre>\n\n<p>from jpgraph</p>\n" }, { "answer_id": 185070, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "<pre><code>// this is really complicated\n</code></pre>\n\n<p>with no other comments</p>\n" }, { "answer_id": 185106, "author": "Jason Sundram", "author_id": 2683, "author_profile": "https://Stackoverflow.com/users/2683", "pm_score": 9, "selected": false, "text": "<pre><code>// Magic. Do not touch.\n</code></pre>\n" }, { "answer_id": 185115, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 4, "selected": false, "text": "<pre><code>// Okay, let's do the loop, yeah come on baby let's do the loop\n// and it goes like this ...\n</code></pre>\n" }, { "answer_id": 185156, "author": "Goran", "author_id": 23164, "author_profile": "https://Stackoverflow.com/users/23164", "pm_score": 9, "selected": false, "text": "<p>About the middle of a 30 page xslt</p>\n\n<pre><code>&lt;!-- Here be dragons --&gt;\n</code></pre>\n" }, { "answer_id": 185165, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<pre><code>/* logic */\n#ifndef TRUE\n# define TRUE 1\n#endif /* TRUE */\n#ifndef FALSE\n# define FALSE 0\n#endif /* FALSE */\n#define EOF_OK TRUE\n#define EOF_NOT_OK FALSE\n</code></pre>\n\n<p>and the rest of the glorious <a href=\"http://www.ioccc.org/official/mkentry.c\" rel=\"nofollow noreferrer\">mkentry.c</a> at the <a href=\"http://www0.us.ioccc.org/main.html\" rel=\"nofollow noreferrer\">IOCCC</a> page. I can't keep laughing every time I read through this source.</p>\n" }, { "answer_id": 185169, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 7, "selected": false, "text": "<p>Try typing your favourite profanity into <a href=\"http://www.google.com/codesearch\" rel=\"nofollow noreferrer\">google code search</a>, it whiles away many a dull hour. Some of my favourite examples:</p>\n\n<pre><code>/* These magic numbers are fucking stupid. */\n\n/* Dear free software world, do you NOW see we are fucking\n things up?! This is insane! */\n\n/* We will NOT put a fucking timestamp in the header here. Every\n time you put it back, I will come in and take it out again. */\n\n# However, this only works if there are MULTIPLE checkboxes!\n# The fucking JS DOM *changes* based on one or multiple boxes!?!?!\n# Damn damn damn I hate the JavaScript DOM so damn much!!!!!!\n\n/* TODO: this is obviously not right ... this whole fucking module\n sucks anyway */\n\n/* FIXME: please god, when will the hurting stop? Thus function is so\n fucking broken it's not even funny. */\n</code></pre>\n\n<p>and my personal favourite</p>\n\n<pre><code> # code below replaces code above - any problems?\n # yeah, it doesn't fucking work.\n</code></pre>\n" }, { "answer_id": 185181, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 10, "selected": false, "text": "<pre><code>// drunk, fix later\n</code></pre>\n\n<p>Wish I were kidding. And knowing the developer who wrote the code, I think he meant it literally.</p>\n" }, { "answer_id": 185196, "author": "Rulas", "author_id": 22145, "author_profile": "https://Stackoverflow.com/users/22145", "pm_score": 7, "selected": false, "text": "<pre><code>// I have to find a better job\n</code></pre>\n" }, { "answer_id": 185201, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 1, "selected": false, "text": "<p>here are 4, in no order:</p>\n\n<pre><code>// Father, forgive me, for I am sinning\n\n// heaven help me\n\n// horse string-length into correctitude \n(from a textbook)\n\n// what, me worry?\n</code></pre>\n" }, { "answer_id": 185215, "author": "David Collie", "author_id": 7577, "author_profile": "https://Stackoverflow.com/users/7577", "pm_score": 4, "selected": false, "text": "<p>\"This will never happen\". </p>\n\n<p>Famous last words my friend...</p>\n" }, { "answer_id": 185246, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>(A bunch of code that's really weird looking) //Kludge.\n</code></pre>\n" }, { "answer_id": 185308, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "<pre><code>return 1; # returns 1\n</code></pre>\n" }, { "answer_id": 185550, "author": "KevDog", "author_id": 13139, "author_profile": "https://Stackoverflow.com/users/13139", "pm_score": 8, "selected": false, "text": "<pre><code>//This code sucks, you know it and I know it. \n//Move on and call me an idiot later.\n</code></pre>\n" }, { "answer_id": 185564, "author": "MrValdez", "author_id": 1599, "author_profile": "https://Stackoverflow.com/users/1599", "pm_score": 3, "selected": false, "text": "<p>A few hours after showing a friend <a href=\"http://www.codinghorror.com/blog/archives/001137.html\" rel=\"nofollow noreferrer\">this post from Coding Horror</a>, I saw this comment on his code:</p>\n\n<blockquote>\n <p>// MrValdez is a violent Psychopath. Don't piss him off.</p>\n</blockquote>\n" }, { "answer_id": 185576, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 9, "selected": false, "text": "<pre><code>/* This is O(scary), but seems quick enough in practice. */ \n</code></pre>\n\n<p>followed by four nested for-loops</p>\n" }, { "answer_id": 185603, "author": "Ted", "author_id": 8965, "author_profile": "https://Stackoverflow.com/users/8965", "pm_score": 3, "selected": false, "text": "<pre><code>// Bad Christian, No cookie\n</code></pre>\n\n<p>Cookie in this context does <strong>not</strong> refer to a browser cookie</p>\n" }, { "answer_id": 185712, "author": "Mike", "author_id": 1743, "author_profile": "https://Stackoverflow.com/users/1743", "pm_score": 9, "selected": false, "text": "<pre><code>const int TEN=10; // As if the value of 10 will fluctuate... \n</code></pre>\n" }, { "answer_id": 185720, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 4, "selected": false, "text": "<pre><code>//The following code is commented out\n//(a load of commented out code followed)\n</code></pre>\n" }, { "answer_id": 185789, "author": "Aidos", "author_id": 12040, "author_profile": "https://Stackoverflow.com/users/12040", "pm_score": 8, "selected": false, "text": "<p>I went through a sleep-deprived coding run and started only writing comments that were quotes from Fight Club.</p>\n\n<p>Still trawling through the code years later I find a comment that makes me laugh. Most of them just random thoughts. I did however keep my comments to lines ratio pretty good!</p>\n\n<pre><code>// This shouldn't happen. The only way this can happen is if the\n// &lt;code&gt;JFileChooser&lt;/code&gt; has returned a &lt;code&gt;File&lt;/code&gt; that doesn't exist\n// on the system. If this happens we can't recover, and there is more than likely\n// a rip in the space time continuum that the user is too distracted by to notice\n// anything else.\n</code></pre>\n\n<hr>\n\n<pre><code> /**\n * This method leverages collective synergy to drive \"outside of the box\"\n * thinking and formulate key objectives into a win-win game plan with a\n * quality-driven approach that focuses on empowering key players to drive-up\n * their core competencies and increase expectations with an all-around\n * initiative to drive down the bottom-line. I really wanted to work the word\n * \"mandrolic\" in there, but that word always makes me want to punch myself in\n * the face.\n */\nprivate void updateFileCountLabel() {\n</code></pre>\n" }, { "answer_id": 185803, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 10, "selected": false, "text": "<pre><code>// sometimes I believe compiler ignores all my comments\n</code></pre>\n" }, { "answer_id": 185846, "author": "Brad Achorn", "author_id": 2909, "author_profile": "https://Stackoverflow.com/users/2909", "pm_score": 3, "selected": false, "text": "<pre><code># absolutely foul heuristic code.\n# ..it's dirty, but you want it.\n</code></pre>\n\n<p>and:</p>\n\n<pre><code># VERY USEFUL DEBUGGING AID, for when the above all goes pearshaped:\n</code></pre>\n" }, { "answer_id": 185853, "author": "moswald", "author_id": 8368, "author_profile": "https://Stackoverflow.com/users/8368", "pm_score": 3, "selected": false, "text": "<p>Fresh out of college, I was eager to get my hands dirty. My first task was... \"comment this code for me\".</p>\n\n<p>Fucker.</p>\n\n<p>After awhile I got bored with it...</p>\n\n<pre><code>// this function doesn't actually calculated the profit, like it says --it really signals the mothership orbiting saturn that the planet is ripe for takeover\n\n[later]\n\n// I don't think anyone is going to read this\n\n[various permutations on that last one]\n</code></pre>\n" }, { "answer_id": 185877, "author": "Samat Jain", "author_id": 14878, "author_profile": "https://Stackoverflow.com/users/14878", "pm_score": 7, "selected": false, "text": "<pre><code>/* Halley's comment */\n</code></pre>\n" }, { "answer_id": 185971, "author": "TM.", "author_id": 12983, "author_profile": "https://Stackoverflow.com/users/12983", "pm_score": 4, "selected": false, "text": "<p>Actually saw this the other day, on some code that was written when there was a deadline rush.</p>\n\n<pre><code>//This was clearly written under duress\n</code></pre>\n" }, { "answer_id": 185979, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 5, "selected": false, "text": "<p>Classic ASP: </p>\n\n<pre><code>'Is it worth it, let me work it'\n'I put my thing down, flip it and reverse it'\n'Ti esrever dna ti pilf, nwod gniht ym tup I'\n\nNextIP = StrReverse(UserRecordset.Fields.Item(0))\n</code></pre>\n" }, { "answer_id": 185989, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I found this when re-using a PHP class I wrote a fair amount of time ago. I still cant remember what went there and I still have found no use for it... I actually don't even remember me writing that comment; so I literally laughed out loud when I found it.</p>\n\n<pre><code>try\n{ \n // Some database logic\n}\ncatch (Exception $ex)\n{\n // sure, it looks silly and I honestly cant remember what code used to go here... but i swear i will\n // find a use for this code.... eventually....\n throw $ex;\n}\n</code></pre>\n" }, { "answer_id": 185990, "author": "Matias Nino", "author_id": 17235, "author_profile": "https://Stackoverflow.com/users/17235", "pm_score": 5, "selected": false, "text": "<pre><code>'NO COMMENT\n</code></pre>\n" }, { "answer_id": 186140, "author": "Roalt", "author_id": 26387, "author_profile": "https://Stackoverflow.com/users/26387", "pm_score": 8, "selected": false, "text": "<p>One of the most classic ones is the comment made by Pierre de Fermat about his well-known \"Last theorem\": \"The margin of this page is a bit too small to write down the proof\".</p>\n\n<p>It took more than 350 years before the proof was found...</p>\n\n<p>(According to <a href=\"http://en.wikipedia.org/wiki/Fermat&#39;s_Last_Theorem\" rel=\"nofollow noreferrer\">wikipedia</a> this is the original text:)</p>\n\n<blockquote>\n <p>Cubum autem in duos cubos, aut\n quadratoquadratum in duos\n quadratoquadratos, et generaliter\n nullam in infinitum ultra quadratum\n potestatem in duos eiusdem nominis fas\n est dividere cuius rei demonstrationem\n mirabilem sane detexi. Hanc marginis\n exiguitas non caperet.</p>\n</blockquote>\n\n<p>...and translated into English:</p>\n\n<blockquote>\n <p>(It is impossible to separate a cube\n into two cubes, or a fourth power into\n two fourth powers, or in general, any\n power higher than the second into two\n like powers. I have discovered a truly\n marvellous proof of this, which this\n margin is too narrow to contain.)</p>\n</blockquote>\n" }, { "answer_id": 186286, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 3, "selected": false, "text": "<p>Found in the JUnit API:</p>\n\n<pre><code>/**\n * ...as the moon sets over the early morning Merlin, Oregon\n * mountains, our intrepid adventurers type...\n */\npublic Test createTest(Class theClass, String name) {\n ...\n}\n</code></pre>\n" }, { "answer_id": 186309, "author": "Tuoski", "author_id": 1703, "author_profile": "https://Stackoverflow.com/users/1703", "pm_score": 10, "selected": false, "text": "<pre><code>stop(); // Hammertime!\n</code></pre>\n" }, { "answer_id": 186395, "author": "ThatBloke", "author_id": 7050, "author_profile": "https://Stackoverflow.com/users/7050", "pm_score": 3, "selected": false, "text": "<p>Some of the very few comments in 5000+ lines of code in one file<br>\nI actually has an argument with the coder who defended his coding style...<br>\nNo comment!<br>\nAnd there were no comments;-) (or very few)<br>\nSadly this is production code.</p>\n\n<pre><code>offset=1;\nfor (i=0;i&lt;=len;i++)\n {\n if ((i!=0)&&(i&lt;len)) <b>//-3</b>\n {\n switch(mess[i])\n {\n case ETX:\n case ETB:\n case DLE:\n buf[offset]=DLE;\n offset++;\n break;\n }\n }\n buf[offset]=mess[i];\n offset++;\n }\n</code></pre>\n\n<p>I love the switch!</p>\n\n<pre><code>for (n=0;n&lt;offset;n++)\n{\n Sleep(TR); <b>//Modif A</b>\n Sleep(T);<b>//</b>\n FWriteFile(hCom,buf+n,1,&dwMot,NULL);\n if (ECHO)\n FReadFile(hCom,tab,1,&dwMot,NULL);\n}\n</code></pre>\n\n<p>and no, there are no comments explaining what \"modif A\" is in the header.</p>\n\n<pre><code>if (GetFileSize(hSlotFile,NULL)==3600) //5*720\n</code></pre>\n\n<p>and what's 720?</p>\n" }, { "answer_id": 186434, "author": "Simon Peverett", "author_id": 6063, "author_profile": "https://Stackoverflow.com/users/6063", "pm_score": 3, "selected": false, "text": "<p>Spelunking through the Hardware Abstraction Layer while working for a certain Finnish Mobile Network Equipment Manufacturer I found 100+ occurrences of the Finnish word \"puukko\".</p>\n\n<p>A 'puukko' is an all purpose knife that every Finn has in their toolbox or around the house. It is used for everything from pealing potatoes to performing computer repairs (my observations). I believe in this context it is the Finnish equivalent of the word 'Hack'. </p>\n\n<p>My Finnish colleagues denied this and said it meant something more like 'surgical procedure/intervention'... and I almost believed them until I found the comment: </p>\n\n<pre><code>/* Perkele ISO Puukko! */ -&gt; Fucking Big Hack!\n</code></pre>\n" }, { "answer_id": 186457, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 3, "selected": false, "text": "<p>Seen in the source code for LucasArts' computer game 'The Eidolon' (Which was wierd and wacky in it's own right)...</p>\n\n<pre><code>// He's dead, Jim!\n</code></pre>\n" }, { "answer_id": 186579, "author": "trshiv", "author_id": 21647, "author_profile": "https://Stackoverflow.com/users/21647", "pm_score": 3, "selected": false, "text": "<pre><code>/* My lawyer told me not to reveal */\n</code></pre>\n" }, { "answer_id": 186967, "author": "sharkin", "author_id": 7891, "author_profile": "https://Stackoverflow.com/users/7891", "pm_score": 10, "selected": false, "text": "<pre><code>// I dedicate all this code, all my work, to my wife, Darlene, who will \n// have to support me and our three children and the dog once it gets \n// released into the public.\n</code></pre>\n" }, { "answer_id": 186988, "author": "Razor", "author_id": 17211, "author_profile": "https://Stackoverflow.com/users/17211", "pm_score": 6, "selected": false, "text": "<pre><code>//Abandon all hope ye who enter beyond this point\n</code></pre>\n" }, { "answer_id": 187163, "author": "Richard Turner", "author_id": 12559, "author_profile": "https://Stackoverflow.com/users/12559", "pm_score": 3, "selected": false, "text": "<pre><code>// TODO - Comment this function\n</code></pre>\n" }, { "answer_id": 187183, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 6, "selected": false, "text": "<p>A classic case of why you shouldn't off shore your software development:</p>\n\n<pre><code>public class Contact\n{\n //... \n\n /// &lt;summary&gt;\n /// Gets or sets the name of the first.\n /// &lt;/summary&gt;\n /// &lt;value&gt;The name of the first.&lt;/value&gt;\n public string FirstName\n {\n get { return _firstName; }\n set { _firstName = value; }\n }\n}\n</code></pre>\n" }, { "answer_id": 187215, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 6, "selected": false, "text": "<pre><code>Repeat\n ...\nUntil (JesusChristsReturn) ' Not sure\n</code></pre>\n" }, { "answer_id": 187223, "author": "Retne", "author_id": 26489, "author_profile": "https://Stackoverflow.com/users/26489", "pm_score": 3, "selected": false, "text": "<pre><code>-- Change Log: Not needed. The code is perfect 'cause I wrote it.\n-- If you change it, it will break.\n</code></pre>\n\n<p>I'm in the middle of reviewing some code comments to check they make sense, and saw the modest line above.</p>\n" }, { "answer_id": 187405, "author": "Sean", "author_id": 26095, "author_profile": "https://Stackoverflow.com/users/26095", "pm_score": 9, "selected": false, "text": "<pre><code>long john; // silver\n</code></pre>\n" }, { "answer_id": 187549, "author": "ForCripeSake", "author_id": 14833, "author_profile": "https://Stackoverflow.com/users/14833", "pm_score": 6, "selected": false, "text": "<pre><code>//There can Only Be one HIGHLAN....err..Singleton\npublic class SomeSingleton\n{\n...\n}\n</code></pre>\n" }, { "answer_id": 187565, "author": "kjensen", "author_id": 22177, "author_profile": "https://Stackoverflow.com/users/22177", "pm_score": 7, "selected": false, "text": "<pre><code>virgin = 0; /* you're not a virgin anymore, sweety */\n</code></pre>\n" }, { "answer_id": 187599, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 4, "selected": false, "text": "<pre><code>i++; // increment variable i\n</code></pre>\n" }, { "answer_id": 188042, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Comment in our Enterprise Class system used for Government purposes</p>\n\n<pre><code>'RH 5/24/06 burn me if this dosn't work.. :)\n</code></pre>\n\n<p>Good ole RH.....company Prez/Lead Developer</p>\n" }, { "answer_id": 188063, "author": "Collin Estes", "author_id": 20748, "author_profile": "https://Stackoverflow.com/users/20748", "pm_score": 5, "selected": false, "text": "<pre><code>//open lid\n\n\n//take sh!t\n\n\n//close lid\n</code></pre>\n\n<p>Comments for a File open, data dump, file close...</p>\n" }, { "answer_id": 188100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>When writing some Perl years ago, I added these comments at the top and bottom:</p>\n\n<pre><code># &lt;magic type=\"voodoo\"&gt;\n\n...\n\n# &lt;/magic&gt;\n</code></pre>\n\n<p>The next guy to look at it wasn't so hot at Perl, and spent a while searching documentation for what 'magic' and 'voodoo' did. Since then, I've tried to add more helpful comments...</p>\n" }, { "answer_id": 188413, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 6, "selected": false, "text": "<pre><code>// Catching exceptions is for communists\n</code></pre>\n\n<p>From <a href=\"http://www.mikeduncan.com/sqlite-on-dotnet-in-3-mins\" rel=\"nofollow noreferrer\">Mike Duncan's page on SQLite</a>.</p>\n" }, { "answer_id": 189279, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 4, "selected": false, "text": "<p>In the header of an XSLT file:</p>\n\n<pre><code>DON'T TOUCH THIS SCRIPT -&gt; XSLT is like arcane, black magic\n</code></pre>\n" }, { "answer_id": 189302, "author": "MattC", "author_id": 21126, "author_profile": "https://Stackoverflow.com/users/21126", "pm_score": 4, "selected": false, "text": "<pre><code>// Hard to explain\n</code></pre>\n\n<p>It ended up being broken, too. No wonder it was hard to explain</p>\n" }, { "answer_id": 189312, "author": "Vincent", "author_id": 25658, "author_profile": "https://Stackoverflow.com/users/25658", "pm_score": 4, "selected": false, "text": "<p>I believe in JBoss somewhere there was a line that read</p>\n\n<pre><code>return null; //Not really null\n</code></pre>\n\n<p>I always liked that line. </p>\n" }, { "answer_id": 189503, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 7, "selected": false, "text": "<pre><code> * ...and don't just declare it volatile and think you've solved\n * the problem. You young punks think you know what volatile\n * means... why in my day we had to cast it volatile uphill\n * both ways, and the code still didn't work! Whippersnappers...\n</code></pre>\n" }, { "answer_id": 189551, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 6, "selected": false, "text": "<pre>\n// The following strings are meant to be funny. Do not edit these strings\n// unless you are funny, too. If you don't know if you're funny, you're\n// not funny. If fewer than 2 people unrelated to you have told you that \n// you're funny, you're not funny.\n</pre>\n" }, { "answer_id": 189713, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 3, "selected": false, "text": "<p>Upon being forced to write unit tests for anemic domain objects that are nothing but bags of getters and setters (which I was forced to write as well):</p>\n\n<pre><code>// zzzzZZZZzzzz....\n</code></pre>\n" }, { "answer_id": 189732, "author": "Mike Two", "author_id": 23659, "author_profile": "https://Stackoverflow.com/users/23659", "pm_score": 6, "selected": false, "text": "<pre><code>// human madable inconvenient. Way too sucks.\n</code></pre>\n\n<p>I still don't fully understand what it means, but I have found it to be very true about a lot of code.</p>\n" }, { "answer_id": 189740, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 7, "selected": false, "text": "<pre><code>// I know the line below is wrong, but it came that way from our IP vendor, and \n// the driver won't work if you \"fix\" it. I've had to revert this change 4 times\n// now. Leave it alone, or I will hunt you down and hurt you\nif (r = 0) {\n /* bunch of code here */\n}\nelse\n{\n /* even more code here */\n}\n</code></pre>\n" }, { "answer_id": 189748, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": 2, "selected": false, "text": "<p>The ascii-art skull and crossbones (which is too difficult to recreate here) in <a href=\"http://en.wikipedia.org/wiki/Gosling_Emacs\" rel=\"nofollow noreferrer\">Gosling's Emacs</a> source (warning that the ultra-hot screen management package he wrote was not easily understood).</p>\n" }, { "answer_id": 189858, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 6, "selected": false, "text": "<p>Another classic, by Donald Knuth no less:</p>\n\n<p>Beware of bugs in the above code;\nI have only proved it correct, not tried it.</p>\n" }, { "answer_id": 189859, "author": "PoppaVein", "author_id": 14889, "author_profile": "https://Stackoverflow.com/users/14889", "pm_score": 9, "selected": false, "text": "<pre><code>/*\n * You may think you know what the following code does.\n * But you dont. Trust me.\n * Fiddle with it, and youll spend many a sleepless\n * night cursing the moment you thought youd be clever\n * enough to \"optimize\" the code below.\n * Now close this file and go play with something else.\n */ \n</code></pre>\n" }, { "answer_id": 189862, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 2, "selected": false, "text": "<pre>\n// set break point here - you'll never reach it\n</pre>\n" }, { "answer_id": 189938, "author": "Parappa", "author_id": 9974, "author_profile": "https://Stackoverflow.com/users/9974", "pm_score": 3, "selected": false, "text": "<p>A funny typo that was strangely appropriate:</p>\n\n<p><code>assert(0); // should never shit this point</code></p>\n" }, { "answer_id": 190046, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 8, "selected": false, "text": "<pre><code>// I am not sure if we need this, but too scared to delete. \n</code></pre>\n" }, { "answer_id": 190139, "author": "NeilDurant", "author_id": 26718, "author_profile": "https://Stackoverflow.com/users/26718", "pm_score": 7, "selected": false, "text": "<pre><code>if(m_measures =/*=*/ --index)\n{\n ....\n</code></pre>\n" }, { "answer_id": 190535, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 3, "selected": false, "text": "<p>I don't remember exactly, but the idea was something like this:</p>\n\n<pre><code>Person p = new Person(\"John\", \"Doe\", \"male\");\nCollection women = new ArrayList();\nwomen.insert(p.getTail());\n</code></pre>\n\n<p>It's dirty code ;)</p>\n" }, { "answer_id": 190866, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>/*************************** Drag And Drop Section - Start (you should be me to mess with this section)*********************************************/\n</code></pre>\n" }, { "answer_id": 190869, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>if(count&lt;0) count=0; //don't get me wrong but this has to be done :p\n</code></pre>\n" }, { "answer_id": 191005, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Not a comment but an attribute</p>\n\n<pre><code>[ThereBeDragons]\n</code></pre>\n\n<p>And one I have seen in an implementation of IHttpHandler</p>\n\n<pre><code>//What is this?\npublic bool IsReusable\n{\n get{return false;}\n}\n</code></pre>\n" }, { "answer_id": 191049, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 1, "selected": false, "text": "<pre><code>try {\n dataSource.close();\n}\ncatch (SQLException ex) {\n // Do nothing, since we're going to trash this anyway\n}\n</code></pre>\n\n<p>Of course, this sort of thing is actually a wtf in JDBC (or at least Oracle's JDBC driver) as it can throw SQLExceptions when closing a connection...</p>\n" }, { "answer_id": 191525, "author": "Baishampayan Ghose", "author_id": 8024, "author_profile": "https://Stackoverflow.com/users/8024", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Beware of bugs in the above code; I have only proved it correct, not tried it. </p>\n</blockquote>\n\n<p>That one is by Donald Knuth.</p>\n" }, { "answer_id": 191918, "author": "Dr. Bob", "author_id": 12182, "author_profile": "https://Stackoverflow.com/users/12182", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p><code>// Whoever put this here is an idiot...this doesn't work at all !</code></p>\n</blockquote>\n\n<p>But the code is still there...</p>\n" }, { "answer_id": 192010, "author": "hmcclungiii", "author_id": 24333, "author_profile": "https://Stackoverflow.com/users/24333", "pm_score": 1, "selected": false, "text": "<p>Nice one in VB.NET that I ran into this morning, got a chuckle ...</p>\n\n<pre><code>''' &lt;summary&gt;\n''' Represents an exception that was logged. Since System.Exception implements IDictionary, it can't be\n''' serialized, so I had to write this. Pretty fucking stupid thing to have to do, System.Exception should\n''' be serializable right out of the box, IMHO.\n''' &lt;/summary&gt;\n''' &lt;remarks&gt;&lt;/remarks&gt;\nPublic Class LogException\n</code></pre>\n" }, { "answer_id": 192040, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 5, "selected": false, "text": "<pre><code>catch (Ex as Exception)\n{\n // oh crap, we should do something.\n}\n</code></pre>\n\n<p>Nothing like an empty catch block to make one feel that the code is robust....</p>\n" }, { "answer_id": 192098, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 5, "selected": false, "text": "<pre><code>/// &lt;summary&gt;\n/// The possible outcomes of an update operation (save or delete)\n/// &lt;/summary&gt;\npublic enum UpdateResult\n{\n\n /// &lt;summary&gt;\n /// Updated successfully\n /// &lt;/summary&gt;\n Success = 0,\n\n /// &lt;summary&gt;\n /// Updated successfully\n /// &lt;/summary&gt;\n Failed = 1\n}\n</code></pre>\n" }, { "answer_id": 192155, "author": "Kasper", "author_id": 18671, "author_profile": "https://Stackoverflow.com/users/18671", "pm_score": 1, "selected": false, "text": "<p>i just noticed myself writing this</p>\n\n<pre><code>// not brilliant solution, but fair enough heh.\n</code></pre>\n" }, { "answer_id": 192823, "author": "gedevan", "author_id": 20225, "author_profile": "https://Stackoverflow.com/users/20225", "pm_score": 9, "selected": false, "text": "<pre><code>try {\n\n} finally { // should never happen \n\n}\n</code></pre>\n" }, { "answer_id": 193577, "author": "Dano", "author_id": 26938, "author_profile": "https://Stackoverflow.com/users/26938", "pm_score": 4, "selected": false, "text": "<p>i tell a mentee to do at least SOME exception handling. This is what i get in return around every db call....</p>\n\n<pre><code>Catch (Exception e) {\n //eat it\n}\n</code></pre>\n" }, { "answer_id": 193705, "author": "Knobloch", "author_id": 2878, "author_profile": "https://Stackoverflow.com/users/2878", "pm_score": 7, "selected": false, "text": "<pre><code>/* Emits a 7-Hz tone for 10 seconds.\n True story: 7 Hz is the resonant frequency of a\n chicken's skull cavity. This was determined\n empirically in Australia, where a new factory\n generating 7-Hz tones was located too close to a\n chicken ranch: When the factory started up, all the\n chickens died.\n Your PC may not be able to emit a 7-Hz tone. */\n\nmain()\n{\n sound(7);\n delay(10000);\n nosound();\n}\n</code></pre>\n\n<p>(the sound function in the Turbo C version 2.0 Reference Guide)</p>\n" }, { "answer_id": 194065, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 0, "selected": false, "text": "<pre><code>[onload_1;block=begin;when 1=0]\n\nSome of the techinques in this template are rather obscure, just trust me, they need to be there.\nOTOH a better sollution would be to create a few seperate templates and pick one in the php-script...\n\n[onload_1;block=end]\n</code></pre>\n" }, { "answer_id": 194269, "author": "Chris Jefferson", "author_id": 27074, "author_profile": "https://Stackoverflow.com/users/27074", "pm_score": 8, "selected": false, "text": "<pre><code>// I don't know why I need this, but it stops the people being upside-down\n\nx = -x;\n</code></pre>\n" }, { "answer_id": 194372, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 6, "selected": false, "text": "<pre><code>// This procedure is <strong>really</strong> good for your dorsolateral prefrontal cortex.</code></pre>\n\n<p>For those of you who are, for some peculiar reason, unaware of the DPC, it's the part of your brain that lights-up when you're deeply engaged in learning something new.</p>\n" }, { "answer_id": 194393, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 6, "selected": false, "text": "<pre><code>// Any maintenance developer who can't quote entire Monty Python\n// movies from memory has no business being a developer. \nconst string LancelotsFavoriteColor = \"$0204FB\"</code></pre>\n" }, { "answer_id": 194433, "author": "MrBoJangles", "author_id": 13578, "author_profile": "https://Stackoverflow.com/users/13578", "pm_score": 3, "selected": false, "text": "<pre><code>Case 1:\n ...\n break;\n ...\n//I don't want do do this but [my coworker] says it's part of the code standard\ndefault:\n break;\n</code></pre>\n" }, { "answer_id": 194475, "author": "Josh Segall", "author_id": 2659, "author_profile": "https://Stackoverflow.com/users/2659", "pm_score": 8, "selected": false, "text": "<p>From Java 1.2 SwingUtilities:</p>\n\n<pre><code>doRun.run(); // ... \"a doo run run\".\n</code></pre>\n" }, { "answer_id": 194506, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Not really a comment:</p>\n\n<pre><code>DvLog::Log(\"This silly log message fixes a PSCRIPT5.DLL gpf when printing to Adobe.\");\n</code></pre>\n\n<p>Sad thing is that without the comment, PSCRIPT5.DLL really did blow up ...</p>\n" }, { "answer_id": 194720, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 3, "selected": false, "text": "<pre><code>'Do not optimize these next two lines. Compiler bugs lurk.\n</code></pre>\n\n<p>And they did. Compacting the variable into the expression on the second line resulted in jumping into the middle of the heap and trying to execute data.</p>\n" }, { "answer_id": 194743, "author": "interstar", "author_id": 8482, "author_profile": "https://Stackoverflow.com/users/8482", "pm_score": 4, "selected": false, "text": "<p>A German comment in some source-code, translated by machine or very tired human + Google </p>\n\n<pre><code>; Rechnen ja ; have faith in yes\n</code></pre>\n\n<p>I guess the original meant \"assume true here\" ... but ever since I've taken it as a mantra for my life.</p>\n" }, { "answer_id": 195155, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 3, "selected": false, "text": "<p>This is my favourite comment ever.</p>\n\n<pre><code>/// I intend to do this as shittily as possible because there are many better products that will totally blow this out of the water\n/// and we don't have them so whatever\n</code></pre>\n\n<p>Later on in the file we have more fun like</p>\n\n<pre><code>/// sidestep a bug in WCF (that we can't send types across)\n/// or, depending on how you look at, this issue is a Feature\n</code></pre>\n\n<p>And again later</p>\n\n<pre><code>if( where == null)//be nice\n</code></pre>\n" }, { "answer_id": 195187, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 5, "selected": false, "text": "<p>This is actual code I once had to support. After struggling to comprehend the logic in AstaSaysGooGoo and AstaSaysGaaGaa (where many more astaTempVars were declared and used ) I was ready to give up. I finally looked up and saw the \"@author\" comment and the whole thing began to makes sense.</p>\n\n<pre><code>/*\n\n* @author Andrew Asta\n*/\npublic class AstaClass{\n\n private String astaVar1; \n private String astaVar2; \n private String astaVar3; \n private String astaVar4; \n private String astaVar5; \n private String astaVar6; \n private String astaVar7; \n private String astaVar8; \n private String astaVar9; \n private String astaVar10; \n\n public void AstaSaysGetData(){\n //JDBC statement to populate astavars 1 through 10\n //...\n String astaSqlStatment = \"Select astaCol1, astaCol2, astaCol3... From AstaTable Where...\";\n //..\n //...\n }\n\n //Perform data manipulation on astavars...\n public void AstaSaysGaaGaa(){\n [removed for sake of brevity]\n }\n\n\n //Perform more data manipulation on astavars...\n public void AstaSaysGooGoO(){\n [removed for sake of brevity]\n }\n\n public void AstaSaysPersist(){ \n //JDBC statement to save astavars to DB \n String astaSqlStatment = \"Update AstaTable set astaCol1 = @astaVar1\n , set astaCol2 = @astaVar2\n , set astaCol3 = astaCol3... \n Where...\";\n }\n}\n</code></pre>\n\n<p>PS I changed the actual authors real name so as to avoid me getting in any disputes etc...</p>\n" }, { "answer_id": 195196, "author": "Rick", "author_id": 14138, "author_profile": "https://Stackoverflow.com/users/14138", "pm_score": 2, "selected": false, "text": "<p>Found in the main trigger code for transactions in an OLTP database:</p>\n\n<pre><code>-- This line negates the @inverseqty, which is the\n-- negative of the @insertedquantity. This works through the\n-- magic of the trigger. In fact, this code is a lot like\n-- the bermuda triangle!\n@negquantity = -1 * @inverseqty\n</code></pre>\n" }, { "answer_id": 195198, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 7, "selected": false, "text": "<pre><code> mov si, pCard ; captain?\n</code></pre>\n" }, { "answer_id": 195199, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 5, "selected": false, "text": "<p>There was some old javascript code, quite well written tho. Then was a comment line </p>\n\n<pre><code>// and there is where the dragon lives\n</code></pre>\n\n<p>followed by a function 4 people spent a day to understand what it's doing. Finally we realised it's not even used and does nothing.</p>\n" }, { "answer_id": 195418, "author": "stuartcw", "author_id": 27065, "author_profile": "https://Stackoverflow.com/users/27065", "pm_score": 4, "selected": false, "text": "<p>In a well known commercial DOS spreadsheet application:</p>\n\n<pre><code>/* This comment was just added in order to check-in a file that was last \nchecked in by [Insert Programmer FirstName] \"Back-to-the-Future\" [Insert \nProgrammer LastName]. While testing for year 2000 problems, he accidentally \nchecked-in this file while his machine clock was set forward to the year 2000. \nThis meant that the source code was always newer than the object file and \ncompiled every time the code was built. I'm checking this file in again to \nfix that. */\n</code></pre>\n" }, { "answer_id": 195432, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 1, "selected": false, "text": "<p>I inherited a project that haad been delivered to the customer without any UAT. It was dropkicked over the fence and the money requested.</p>\n\n<p>First time they used it, it naturally blew up. It was an interposing library that overrode any system calls that took a file name as a parameter rather than a file descriptor.</p>\n\n<p>Many system calls had been forgotten.</p>\n\n<p>When I got onboard the code was laced with such gems as:</p>\n\n<pre><code>/* core dumps around here but this is hardly ever called */\n</code></pre>\n\n<p>and</p>\n\n<pre><code>/* don't know why this works but it seeems to be ok */\n</code></pre>\n\n<p>Oh, and there were no unit tests. A colleague had started to add the missing system calls and unit tests.</p>\n\n<p>And the bastards who'd written the code were still in the team and didn't care at all about the garbage that had been delivered!</p>\n" }, { "answer_id": 195705, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": 5, "selected": false, "text": "<p>Q: \"What is the best comment in source code you have ever encountered?\"</p>\n\n<p>A: Easy - the one that helped me solve whatever problem I was having at the time, and there are lots of those!</p>\n\n<p>Second best are those that help guide new development from avoiding known pitfalls.</p>\n" }, { "answer_id": 196132, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": false, "text": "<pre><code>' Oh man I'm pissed. I think I better go home.\n</code></pre>\n\n<p>where pissed = drunk</p>\n" }, { "answer_id": 196782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>//Not a bug, parameter position can change..., if you think this is wrong, you are in fact wrong.\n</code></pre>\n" }, { "answer_id": 196886, "author": "noocyte", "author_id": 11220, "author_profile": "https://Stackoverflow.com/users/11220", "pm_score": 2, "selected": false, "text": "<pre><code>// Jay knows what's going on here, but will he remember in a year? Not very likely, this code sucks, but it works so do not change it.\n</code></pre>\n\n<p>This comment was posted above a huge while-if-for block... Oh, and it manipulated an object array of object arrays of object arrays of strings that could be strings or numbers, depending on at least 3 factors... (yes, I had to debug this code and change it and I wrote the comment, however I did not write the original code). ;)</p>\n" }, { "answer_id": 196919, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 6, "selected": false, "text": "<p>on leaving my last job I embedded some ascii art into the source...</p>\n\n<pre>\n\n ,_-=(!7(7/zs_. \n .=' ' .`/,/!(=)Zm. \n .._,,._.. ,-`- `,\\ ` -` -`\\\\7//WW. \n ,v=~/.-,-\\- -!|V-s.)iT-|s|\\-.' `///mK%. \n v!`i!-.e]-g`bT/i(/[=.Z/m)K(YNYi.. /-]i44M. \n v`/,`|v]-DvLcfZ/eV/iDLN\\D/ZK@%8W[Z.. `/d!Z8m \n //,c\\(2(X/NYNY8]ZZ/bZd\\()/\\7WY%WKKW) -'|(][%4. \n ,\\\\i\\c(e)WX@WKKZKDKWMZ8(b5/ZK8]Z7%ffVM, -.Y!bNMi \n /-iit5N)KWG%%8%%%%W8%ZWM(8YZvD)XN(@. [ \\]!/GXW[ \n / ))G8\\NMN%W%%%%%%%%%%8KK@WZKYK*ZG5KMi,- vi[NZGM[ \n i\\!(44Y8K%8%%%**~YZYZ@%%%%%4KWZ/PKN)ZDZ7 c=//WZK%! \n ,\\v\\YtMZW8W%%f`,`.t/bNZZK%%W%%ZXb*K(K5DZ -c\\\\/KM48 \n -|c5PbM4DDW%f v./c\\[tMY8W%PMW%D@KW)Gbf -/(=ZZKM8[ \n 2(N8YXWK85@K -'c|K4/KKK%@ V%@@WD8e~ .//ct)8ZK%8` \n =)b%]Nd)@KM[ !'\\cG!iWYK%%| !M@KZf -c\\))ZDKW%` \n YYKWZGNM4/Pb '-VscP4]b@W% 'Mf` -L\\///KM(%W! \n !KKW4ZK/W7)Z. '/cttbY)DKW% -` .',\\v)K(5KW%%f \n 'W)KWKZZg)Z2/,!/L(-DYYb54% ,,`, -\\-/v(((KK5WW%f \n \\M4NDDKZZ(e!/\\7vNTtZd)8\\Mi!\\-,-/i-v((tKNGN%W%% \n 'M8M88(Zd))///((|D\\tDY\\\\KK-`/-i(=)KtNNN@W%%%@%[ \n !8%@KW5KKN4///s(\\Pd!ROBY8/=2(/4ZdzKD%K%%%M8@%% \n '%%%W%dGNtPK(c\\/2\\[Z(ttNYZ2NZW8W8K%%%%YKM%M%%. \n *%%W%GW5@/%!e]_tZdY()v)ZXMZW%W%%%*5Y]K%ZK%8[ \n '*%%%%8%8WK\\)[/ZmZ/Zi]!/M%%%%@f\\ \\Y/NNMK%%! \n 'VM%%%%W%WN5Z/Gt5/b)((cV@f` - |cZbMKW%%| \n 'V*M%%%WZ/ZG\\t5((+)L\\'-,,/ -)X(NWW%% \n `~`MZ/DZGNZG5(((\\, ,t\\\\Z)KW%@ \n 'M8K%8GN8\\5(5///]i!v\\K)85W%%f \n YWWKKKKWZ8G54X/GGMeK@WM8%@ \n !M8%8%48WG@KWYbW%WWW%%%@ \n VM%WKWK%8K%%8WWWW%%%@` \n ~*%%%%%%W%%%%%%%@~ \n ~*MM%%%%%%@f` \n ''''' \n\n</pre>\n" }, { "answer_id": 196934, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 3, "selected": false, "text": "<pre><code>// THE LOOP THAT DO EVERYTHING!!!!!!!\n</code></pre>\n" }, { "answer_id": 197847, "author": "jpinto3912", "author_id": 11567, "author_profile": "https://Stackoverflow.com/users/11567", "pm_score": 3, "selected": false, "text": "<p>From a lad that clearly had been watching Monty Python:</p>\n\n<blockquote>\n<pre><code>&gt; // And now, for something completely\n&gt; // different:\n</code></pre>\n \n <p>class theLarch{</p>\n</blockquote>\n" }, { "answer_id": 197874, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 5, "selected": false, "text": "<p>From the source code of the UNIX flavor of the Netscape web browser, circa 1997:</p>\n\n<pre><code>/* HP-UX sucks wet farts from dead pigeons' asses */\n</code></pre>\n\n<p>Such pearls were unfortunately removed before Moz went open-source ...</p>\n" }, { "answer_id": 197879, "author": "Dan", "author_id": 8040, "author_profile": "https://Stackoverflow.com/users/8040", "pm_score": 1, "selected": false, "text": "<p>Sanitized:</p>\n\n<pre><code>//Forward declarations:\n\nclass X {}; // TODO: Remove {} ! When we get X defined....\n</code></pre>\n" }, { "answer_id": 199806, "author": "Thiago Figueiro", "author_id": 27693, "author_profile": "https://Stackoverflow.com/users/27693", "pm_score": 6, "selected": false, "text": "<p>On the linux 1.0 kernel scheduler (sched.c):</p>\n\n<blockquote>\n <p>Dijkstra probably hates me.</p>\n</blockquote>\n\n<pre><code>/*\n * 'schedule()' is the scheduler function. It's a very simple and nice\n * scheduler: it's not perfect, but certainly works for most things.\n * The one thing you might take a look at is the signal-handler code here.\n *\n * NOTE!! Task 0 is the 'idle' task, which gets called when no other\n * tasks can run. It can not be killed, and it cannot sleep. The 'state'\n * information in task[0] is never used.\n *\n * The \"confuse_gcc\" goto is used only to get better assembly code..\n * Dijkstra probably hates me.\n */\nasmlinkage void schedule(void)\n</code></pre>\n\n<p>(...)</p>\n" }, { "answer_id": 200024, "author": "Matt", "author_id": 27718, "author_profile": "https://Stackoverflow.com/users/27718", "pm_score": 4, "selected": false, "text": "<p><code>// Houston, we have a problem</code></p>\n" }, { "answer_id": 200038, "author": "Pat", "author_id": 36, "author_profile": "https://Stackoverflow.com/users/36", "pm_score": 2, "selected": false, "text": "<pre><code>// No women, no children... What movie???\n</code></pre>\n" }, { "answer_id": 200154, "author": "Miserable Variable", "author_id": 18573, "author_profile": "https://Stackoverflow.com/users/18573", "pm_score": 0, "selected": false, "text": "<p>This is from an old IOCCC winning entry, I had to download the whole archive of winners -- a humongous 1.4 M -- and grep for several phrases I remembered wrong before finding it. </p>\n\n<p>Syntactically this is probably not a comment. Or may be it is. I haven't figured it out. It definitely does not have comment delimiters, but it doesn't have String delimiters either.</p>\n\n<pre><code>C=\"Lint says \"argument Manual isn't used.\" What's that\nmean?\";\n</code></pre>\n\n<p>No prices for guessing the output from lint. </p>\n\n<p>And for the curious, that entry is <a href=\"http://www0.us.ioccc.org/1985/sicherman.c\" rel=\"nofollow noreferrer\">here</a>. </p>\n" }, { "answer_id": 203901, "author": "blindauer", "author_id": 22403, "author_profile": "https://Stackoverflow.com/users/22403", "pm_score": 5, "selected": false, "text": "<p>I see this one a <em>lot</em>:</p>\n\n<pre><code>// TODO make this work\n</code></pre>\n" }, { "answer_id": 204187, "author": "Joshi Spawnbrood", "author_id": 15392, "author_profile": "https://Stackoverflow.com/users/15392", "pm_score": 5, "selected": false, "text": "<p>Production source code:</p>\n\n<pre><code>// Remove this if you wanna be fired\n</code></pre>\n" }, { "answer_id": 204235, "author": "Anonymous", "author_id": 15073, "author_profile": "https://Stackoverflow.com/users/15073", "pm_score": 5, "selected": false, "text": "<p>Top of sqlite source files:</p>\n\n<pre><code>/*\n\n** The author disclaims copyright to this source code. In place of \n** a legal notice, here is a blessing: \n** \n** May you do good and not evil. \n** May you find forgiveness for yourself and forgive others. \n** May you share freely, never taking more than you give.\n\n*/\n</code></pre>\n" }, { "answer_id": 208240, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code> // WARNING!!!\n // Very perversive code ahead!\n\n... about a 20 lines of \"very perversive\" code ...\n\n// Now you can call your grandmother back. ;)\n</code></pre>\n" }, { "answer_id": 210422, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 6, "selected": false, "text": "<p>A comment I added to a PHP CMS I was working on a while back.</p>\n\n<pre><code>if (/*you*/ $_GET['action']) { //celebrate\n</code></pre>\n" }, { "answer_id": 215166, "author": "Russell Bryant", "author_id": 23224, "author_profile": "https://Stackoverflow.com/users/23224", "pm_score": 6, "selected": false, "text": "<pre><code> /* Mark: If there's one thing you learn from this code, it is this...\n Never, ever fly Air France. Their customer service is absolutely\n the worst. I've never heard the words \"That's not my problem\" as \n many times as I have from their staff -- It should, without doubt\n be their corporate motto if it isn't already. Don't bother giving \n them business because you're just a pain in their side and they\n will be sure to let you know the first time you speak to them.\n\n If you ever want to make me happy just tell me that you, too, will\n never fly Air France again either (in spite of their excellent\n cuisine). \n\n Update by oej: The merger with KLM has transferred this\n behaviour to KLM as well. \n Don't bother giving them business either...\n\n Only if you want to travel randomly without luggage, you\n might pick either of them.\n */\n</code></pre>\n" }, { "answer_id": 216127, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>Fix problem where Nulls don't work properly. Stupid Microsoft!\n</code></pre>\n\n<p>Code converted Nulls to zero-length strings line by line in roundabout way because the stupid programmer did not understand what Nulls are and had never heard of the Nz() function.</p>\n" }, { "answer_id": 216139, "author": "blank", "author_id": 1348, "author_profile": "https://Stackoverflow.com/users/1348", "pm_score": 3, "selected": false, "text": "<pre><code>// fix for groupid &gt; 9 \n// if groupid ever gets to 100 everything will break (again)\n\nif (groupid &lt; 10) {\ngroupid = \"0\" + groupid;\n}\n</code></pre>\n" }, { "answer_id": 216159, "author": "edomaur", "author_id": 14262, "author_profile": "https://Stackoverflow.com/users/14262", "pm_score": 4, "selected": false, "text": "<pre><code>// Added because boss changed his mind : 20020111,20020501,20020820, ...\n// Commented out because boss changed his mind : 20020201,20020614,20020908, ...\n</code></pre>\n\n<p>In an ETL script between a mostly hacked RPG database and an SQL Server one. I had something like 10 or 20 occurences of this comment...</p>\n" }, { "answer_id": 216744, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": false, "text": "<p>This one was a living proof, in production code, of micro-management effects in our team:</p>\n\n<pre><code>// I am not responsible of this code.\n// They made me write it, against my will.\n</code></pre>\n\n<p>... followed by less than optimal code, conceived by our beloved technical director, who was quite fond of forcing down both code and coding guidelines into developers' throats (*).</p>\n\n<p>Of course, when the project leader searched for the cause of a bug, and found it was inside the \"less than optimal code\", he was less than amused...</p>\n\n<p><i>(*) I am, of course, mentioning the </i>Mighty VB King<i>... If you want to assess the full magnitude of the power of the </i> Mighty VB King<i>, you can read the following SO post: <a href=\"https://stackoverflow.com/questions/218123/what-was-the-strangest-coding-standard-rule-that-you-were-forced-to-follow#220101\">What was the strangest coding standard rule that you were forced to follow?</a> ...</i></p>\n" }, { "answer_id": 216943, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "<pre><code>//If you're reading this, then my program is probably a success\n</code></pre>\n" }, { "answer_id": 216948, "author": "Gabriël", "author_id": 2104, "author_profile": "https://Stackoverflow.com/users/2104", "pm_score": 1, "selected": false, "text": "<pre><code>// GK Experimental\n</code></pre>\n\n<p>(GK being the initials of the coder)</p>\n\n<p>Used to indicate parts of code which are, indeed, kind of experimental. :) </p>\n\n<p>A great flag to know that when you hit it during debugging you're probably busy for the upcoming few hours fixing the hack.. ;)</p>\n" }, { "answer_id": 217681, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 3, "selected": false, "text": "<p>In a large investment bank that required all application outages be logged and commented I saw</p>\n\n<pre><code>Without a crash \n\nOr mighty bang \n\nThe sync disk \n\nDid it's process hang\n</code></pre>\n" }, { "answer_id": 217939, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>All bugs added by David S. Miller\n </p>\n</blockquote>\n" }, { "answer_id": 222164, "author": "Matthew Scouten", "author_id": 8508, "author_profile": "https://Stackoverflow.com/users/8508", "pm_score": 3, "selected": false, "text": "<pre><code>struct core_unlocker\n{\n core_unlocker(lock)\n {\n m_lock = lock\n unlock(lock) //Abandon All Locks, Ye Who Enter Core!\n }\n ~core_unlocker()\n {\n lock(m_lock)\n } \n private:\n Corelock m_lock;\n}\n</code></pre>\n" }, { "answer_id": 222193, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 2, "selected": false, "text": "<p>first line of a javascript function:</p>\n\n<pre><code>// this part is more difficult\n</code></pre>\n\n<p>WTF?</p>\n" }, { "answer_id": 224671, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In SJ CA back during the early days of the auction business I worked with a guy named Rick Dorin. He wrote compilers back when you had to poke at cards all day long. One of his error messages was</p>\n\n<blockquote>\n <p>Too Many Errors... Make fewer!</p>\n</blockquote>\n" }, { "answer_id": 225428, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>at the end of a rather long and convoluted set of while loops and if blocks, the developer in question inserted this final comment:</p>\n\n<pre><code>else\n{\n // wobbly wilson said this would *never* happen!!\n}\n</code></pre>\n\n<p>a laconic mixture of wit and sarcasm :)</p>\n" }, { "answer_id": 235510, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 3, "selected": false, "text": "<p>This is one from my own code, but it's still really funny, and I figure I might as well put it up because it's in public SVN.</p>\n\n<pre><code>// These were orginally up and down. When it was clear the names were\n// inapplicable, they were renamed to retain the joke.\n// Sorry if you were hoping for useful variable names.\nquantum strange, charm;\n</code></pre>\n" }, { "answer_id": 236424, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>aComment = 'this is not aComment' # this is aComment\nclass T(object):\n def f(this):\n this is not aComment\n</code></pre>\n" }, { "answer_id": 237886, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 2, "selected": false, "text": "<p>Some years ago I was working in a large code base that had no unit-testing to speak of.</p>\n\n<p>There was a method buried deep within the code that performed some calendar calculations. It was somewhat broken, had to deal with daylight savings in a very clumsy way due to some unfortunate circumstances.</p>\n\n<p>We had to fix it a couple of times, and every time, we would find something broken some months after.</p>\n\n<p>After spending a whole day fixing it and analyzing it, I put the code in source control, along with a comment that said something like this:</p>\n\n<pre><code>// this code was written after a version trying to do {this} failed because of {reason},\n// previously we were doing {this} which failed because of {reason}. This is \n// now written {this} way so that {lots of reasons here}. If you want to touch\n// this code, please make sure that it produces the right answers when tested with:\n//\n// {some sort of unit test}\n</code></pre>\n\n<p>Ultimately, my team was outsourced. Some days I wonder what happened to this code :)</p>\n" }, { "answer_id": 240292, "author": "Joshi Spawnbrood", "author_id": 15392, "author_profile": "https://Stackoverflow.com/users/15392", "pm_score": 1, "selected": false, "text": "<p>I've just placed this comment:</p>\n\n<pre><code>// this control (Resistance) is FUTILE! \n</code></pre>\n" }, { "answer_id": 240381, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 4, "selected": false, "text": "<p>Exhibit a:</p>\n\n<pre><code>return 0; // Happy ending\n</code></pre>\n\n<p>Exhibit B:</p>\n\n<pre><code>int32_t Interpolate1DSignal(\n Array1D&lt;float64&gt;::Handle hfInputSamples, // samples to be interpolated\n Array1D&lt;float64&gt;::Handle hfInterpolationFilter, // polyphase filter coefficients,\n int32_t iFilterInterpolationFactor, // # of \"rows\" in polyphase filter\n int32_t iFilterLength, // Length of each row in filter\n float64 fInterpolationFactor, // Factor to interpolate the\n // signal by\n float64 fTimingOffset, // Offset into the signal (units \n // of samples)\n Array1D&lt;float64&gt;::Handle hfOutputSamples // left as an exercise for the reader\n);\n</code></pre>\n" }, { "answer_id": 240498, "author": "Gordon Mackie JoanMiro", "author_id": 15778, "author_profile": "https://Stackoverflow.com/users/15778", "pm_score": 1, "selected": false, "text": "<p>A large project I worked on used StyleCop and FXCop in the automated build with rules to prevent people checking in code with uncommented fields, methods, properties etc., etc.</p>\n\n<p>Someone got so pissed off with having to add comments like \"<strong>Gets or sets the full name.</strong>\" to self-documenting properties like <strong>FullName</strong>, that they went to the effort of writing a macro to get around the rules. </p>\n\n<p>The macro inserted XML summary tags for methods, properties etc. with a single non-displaying Unicode character as the tag content which would fool the build rules whilst simultaneously striking his minor blow against mindless insistence on commenting stuff for the sake of it...</p>\n\n<p>...at least until they introduced another rule to check for Unicode characters in comments.</p>\n" }, { "answer_id": 250413, "author": "Chris Kloberdanz", "author_id": 28714, "author_profile": "https://Stackoverflow.com/users/28714", "pm_score": 2, "selected": false, "text": "<p>From a legacy Perl CGI script:</p>\n\n<pre><code># This is convoluted and evil, sorry.\n</code></pre>\n" }, { "answer_id": 265313, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>From one of our projects.<br/>\nSomewhere at the end of one source file.</p>\n\n<pre>\n/*@ /\\ /\\\n * @ / \\/ \\ ----- | | ---- |---\\ | | /--\\ --- | | ---- /--\\ /--\\\n * @ / -- | | | | | / | | | | |\\ | | | |\n * \\---\\ / \\ | |---| ---- |--/ | | \\ | | \\ | ---- \\ \\\n * | \\------------------------/ /-\\ \\ | | | | | \\ | | -\\ | | \\| | -\\ -\\\n * | \\-/ \\ | | | ---- |---/ \\--/ \\--/ --- | \\ ---- \\--/ \\--/\n * \\ ------O\n * \\ / --- | | ---- /--\\ |--\\ /--\\ /--\\\n * | | | | / | |\\ | | | | | | | | |\n * | | | |----- ------- | | \\ | ---- | | | | | | | /-\\\n * | |\\ /| | \\ WWWWWW/ | | \\| | | | | | | | | |\n * | | \\ / | | \\------- --- | \\ | \\--/ |--/ \\--/ \\--/\n * | | \\--------------/ | |\n * / | / |\n * \\ \\ \\ \\\n * \\-----/ \\-----/\n */\n</pre>\n" }, { "answer_id": 271471, "author": "Jason Sundram", "author_id": 2683, "author_profile": "https://Stackoverflow.com/users/2683", "pm_score": 2, "selected": false, "text": "<p>I didn't encounter this firsthand, but it makes for a good story (see explanation in my comment):</p>\n\n<pre><code>#define MSGTAG_B33R 0x723 /* RIPLVB */\n</code></pre>\n" }, { "answer_id": 309983, "author": "AdamBT", "author_id": 22426, "author_profile": "https://Stackoverflow.com/users/22426", "pm_score": 3, "selected": false, "text": "<p>Just added this one today:</p>\n\n<pre><code>// Hardcoded this for time sake ... will make andrew fix later :)\n</code></pre>\n" }, { "answer_id": 310251, "author": "Jared Knipp", "author_id": 39803, "author_profile": "https://Stackoverflow.com/users/39803", "pm_score": 2, "selected": false, "text": "<pre><code>'\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n'\n' NOTE: DON'T SCREW WITH THIS CODE UNLESS YOU REALLY UNDERSTAND IT!\n'\n'\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n</code></pre>\n" }, { "answer_id": 311113, "author": "Overflown", "author_id": 37840, "author_profile": "https://Stackoverflow.com/users/37840", "pm_score": 4, "selected": false, "text": "<p>I think I had something of this sort:</p>\n\n<pre><code>\nif (case1) { // trivial\n...\n}\nelse { // we are screwed\n /* fill in later */\n}\n</code></pre>\n\n<p>ok, so I might have used a stronger word than screwed</p>\n" }, { "answer_id": 312203, "author": "Chris Lloyd", "author_id": 42413, "author_profile": "https://Stackoverflow.com/users/42413", "pm_score": 8, "selected": false, "text": "<pre><code># To understand recursion, see the bottom of this file \n</code></pre>\n\n<p>At the bottom of the file:</p>\n\n<pre><code># To understand recursion, see the top of this file\n</code></pre>\n" }, { "answer_id": 315112, "author": "Joseph Ferris", "author_id": 15906, "author_profile": "https://Stackoverflow.com/users/15906", "pm_score": 3, "selected": false, "text": "<p>In a class named \"Bar\" (which was a UI Control with a less than descriptive name), the class header:</p>\n\n<pre><code>/// &lt;summary&gt;I pity the \"foo\".&lt;/summary&gt;\n</code></pre>\n\n<p>And the <code>Remove()</code> method:</p>\n\n<pre><code>/// &lt;summary&gt;A \"foo\" and his money are soon parted.&lt;/summary&gt;\n</code></pre>\n\n<p>Even worse, it was a business partner that pointed it out from the generated documentation. Even worse than that, is those are probably the closest things to useful documentation we ever got out of the guy.</p>\n" }, { "answer_id": 316042, "author": "Steve T", "author_id": 415, "author_profile": "https://Stackoverflow.com/users/415", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;!-- THIS IS THE MAIN CONFIGURATION FILE FOR THE ENTIRE BLOODY DIRECTORY --&gt;\n&lt;!-- WHATEVER YOU DO, DO NOT EDIT THIS FILE WITHOUT TALKING TO ME FIRST --&gt;\n&lt;!-- I'M SERIOUS --&gt;\n&lt;!-- (scroll down) --&gt;\n</code></pre>\n" }, { "answer_id": 316112, "author": "bikesandcode", "author_id": 40112, "author_profile": "https://Stackoverflow.com/users/40112", "pm_score": 7, "selected": false, "text": "<p>Taken from the Quake III source, I stumbled across this in some random slashdot posting. Full source of the file can be found <a href=\"http://www.google.com/codesearch?hl=en&amp;q=quake+3+%22what+the+fuck%22+show:1s7s4Tr0knk:uJtln_6bKE0:1s7s4Tr0knk&amp;sa=N&amp;cd=2&amp;ct=rc&amp;cs_p=git://github.com/TTimo/iourt.git&amp;cs_f=code/qcommon/q_math.c\" rel=\"nofollow noreferrer\">here</a>. It's a particularly fast method of calculating an inverse square root. As for the best comment? It's a common one to be sure, but given that it's attached to the line that does the magic is what makes it great. </p>\n\n<pre><code>float Q_rsqrt( float number )\n{\n long i;\n float x2, y;\n const float threehalfs = 1.5F;\n\n x2 = number * 0.5F;\n y = number;\n i = * ( long * ) &amp;y; // evil floating point bit level hacking\n i = 0x5f3759df - ( i &gt;&gt; 1 ); // what the fuck?\n y = * ( float * ) &amp;i;\n y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration\n // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed\n\n #ifndef Q3_VM\n #ifdef __linux__\n assert( !isnan(y) ); // bk010122 - FPE?\n #endif\n #endif\n return y;\n}\n</code></pre>\n" }, { "answer_id": 316233, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 10, "selected": false, "text": "<pre><code>//When I wrote this, only God and I understood what I was doing\n//Now, God only knows\n</code></pre>\n" }, { "answer_id": 331424, "author": "jumpinjackie", "author_id": 18731, "author_profile": "https://Stackoverflow.com/users/18731", "pm_score": 7, "selected": false, "text": "<pre><code>options.BatchSize = 300; //Madness? THIS IS SPARTA!\n</code></pre>\n" }, { "answer_id": 331525, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": 6, "selected": false, "text": "<p>Great one from leaked Windows 2000 source code :</p>\n\n<blockquote>\n <p>!!!!!!!IF YOU CHANGE TABS TO SPACES, YOU WILL BE KILLED!!!!!!! *<br>\n !!!!!!!!!!!!!!DOING SO FUCKS THE BUILD\n PROCESS!!!!!!!!!!!!!!!! *<br>\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p>\n</blockquote>\n\n<p><a href=\"http://www.kuro5hin.org/story/2004/2/15/71552/7795\" rel=\"nofollow noreferrer\">http://www.kuro5hin.org/story/2004/2/15/71552/7795</a></p>\n" }, { "answer_id": 334450, "author": "Paul Mitchell", "author_id": 38966, "author_profile": "https://Stackoverflow.com/users/38966", "pm_score": 2, "selected": false, "text": "<p>Seen in some COBOL back in 1983:</p>\n\n<pre><code> C I don't know what this next bit does so I'll jump around it\n GOTO DONE.\n</code></pre>\n" }, { "answer_id": 334499, "author": "Nikola Stjelja", "author_id": 32582, "author_profile": "https://Stackoverflow.com/users/32582", "pm_score": 3, "selected": false, "text": "<p><code>\n//Iterate by one<br>\n$i++;\n</code></p>\n\n<p>Unfortunately it was mine, during my \"Must comment everything phase\".</p>\n" }, { "answer_id": 334507, "author": "CLaRGe", "author_id": 20507, "author_profile": "https://Stackoverflow.com/users/20507", "pm_score": 2, "selected": false, "text": "<pre><code>// good luck!\n</code></pre>\n" }, { "answer_id": 334568, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>//Mr. Compiler, please do not read this.\n</code></pre>\n" }, { "answer_id": 335079, "author": "wergeld", "author_id": 33727, "author_profile": "https://Stackoverflow.com/users/33727", "pm_score": 3, "selected": false, "text": "<p>While working on some websites I found this at the start of the embedded JS:</p>\n\n<blockquote>\n <p>I feel so dirty doing this but the guy wanted it in .NET</p>\n</blockquote>\n" }, { "answer_id": 335114, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "<p>From C#</p>\n\n<pre><code>#region Hack - Shield Eyes Before Expanding\n\n/// &lt;summary&gt;\n/// A single uint with all of the bits set to represent the different tracing\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;\n/// Ugly I know, so if you can think of a better way, feel free to rewrite.\n/// &lt;/remarks&gt;\n[Browsable(false)]\npublic uint TraceBitfield\n{\n // Snip\n}\n\n#endregion\n</code></pre>\n" }, { "answer_id": 339377, "author": "Sumptin", "author_id": 43061, "author_profile": "https://Stackoverflow.com/users/43061", "pm_score": 3, "selected": false, "text": "<p>Quite a while ago I came across some connection script and while I don't remember the syntax I do recall the comments as I'm a Pink Floyd fan.</p>\n\n<pre><code>//Attempt Handshake: Hello? This is London calling. Are we reaching you?\n\n\n//Handshake Failed: I don't understand...he just hung up.\n</code></pre>\n" }, { "answer_id": 344863, "author": "NotDan", "author_id": 3291, "author_profile": "https://Stackoverflow.com/users/3291", "pm_score": 5, "selected": false, "text": "<pre><code>//Visual Studio Bug Workaround:\n//http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101677\n\n//To fix 'CJumpToHelper::GetInstance()' : undeclared identifier compiler errors, change the number lines below\n//until the file compiles correctly. (This needs to be done anytime a change is made to this file)\n\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n //////////////////////////////////////: There should be 1-10 of these lines\n</code></pre>\n" }, { "answer_id": 344907, "author": "Jeremiah", "author_id": 34183, "author_profile": "https://Stackoverflow.com/users/34183", "pm_score": 7, "selected": false, "text": "<pre><code>int MyFunction()\n{\n // There once was a man named Dave\n int Result = 0;\n\n // Whose code just wouldn't behave\n MyObject *Ptr = new MyObject();\n\n // He left to go to a meetin'\n Result = Ptr-&gt;DoSomething();\n\n // And left his memory a leakin'\n return Result;\n}\n</code></pre>\n\n<p>C++ Comment</p>\n" }, { "answer_id": 348483, "author": "vdhant", "author_id": 30572, "author_profile": "https://Stackoverflow.com/users/30572", "pm_score": 2, "selected": false, "text": "<p>I just found this one in a custom Linq provider for .net:</p>\n\n<pre><code>//select is a royal pain in the ass where \n//the parameter passed to CreateQuery isn't actually the one that goes in the call\n//requiring this workaround. Not sure how straight Linq to Objects does it.\n</code></pre>\n\n<p>And this one</p>\n\n<pre><code>//expressions have to be compiled in order to work with the method call on \n//straight Enumerable somehow, LINQ to objects itself magically does this. \n//Reflector shows a mess, so I (Aaron) invented my own way. God love unit tests!\n</code></pre>\n\n<p>And i just found this one as well... it just gets better</p>\n\n<pre><code> //ok, this is a hairy, dirty, and nasty piece of code\n //the alternatives are substantially worse than this though\n //i.e. when you do your own provider, LINQ assumes that\n //you are going to implement your own expression tree visitor and\n //do it all yourself. Frankly, I still have xmas shopping to do\n //and I really don't want us to be foobared when we get\n //even more extension methods added to LINQ\n //therefore, we are pulling execute based on taking the calling the \n //standard execute on enumerable, but using our own class\n //\n //optimization can occur from here on an as needed basis, that is\n //check for the value of mex.Method.Name, and write a handler for\n //that method\n //\n //also, it may not be a bad idea to rather than do this reflection \n //each and every time somehow cache the reflected methodinfos and do \n //lookups that way that said, we need a complete red/green/refactor \n //cycle here before I am touching that one\n</code></pre>\n\n<p>And this one</p>\n\n<pre><code>//Compile that mutherf-ker, invoke it, and get the resulting hash\n</code></pre>\n" }, { "answer_id": 350893, "author": "theschmitzer", "author_id": 2167252, "author_profile": "https://Stackoverflow.com/users/2167252", "pm_score": 4, "selected": false, "text": "<p>Back when I worked for Reuters there was a comment in one of our feed handlers that made some people think the Almighty was helping us out...</p>\n\n<pre><code>// Jesus told me to skip to the end of the message here\n</code></pre>\n\n<p>We found out later that there was a Latin-American contact named <strong>Jesus</strong> (HeyZus).</p>\n" }, { "answer_id": 354692, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 1, "selected": false, "text": "<p>Near the top of a unit:</p>\n\n<pre><code>// Oh what a tangled web we weave\n// When first we practice to deceive\n// ASTA\n</code></pre>\n" }, { "answer_id": 360696, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>A few from the Linux kernel:</p>\n\n<pre><code>/* Sun, you just can't beat me, you just can't. Stop trying,\n* give up. I'm serious, I am going to kick the living shit\n* out of you, game over, lights out.\n*/\n</code></pre>\n\n<p>-</p>\n\n<pre><code>/* 2,191 lines of complete and utter shit coming up... */\n</code></pre>\n\n<p>-</p>\n\n<pre><code>#if 0 /* XXX No fucking way dude... */\n</code></pre>\n" }, { "answer_id": 368692, "author": "Lucas Gabriel Sánchez", "author_id": 20601, "author_profile": "https://Stackoverflow.com/users/20601", "pm_score": 4, "selected": false, "text": "<p>This one i found it in the package \"twisted\" for Python 2.5 (the file is tcp.py at line 371)</p>\n\n<pre><code># Limit length of buffer to try to send, because some OSes are too\n# stupid to do so themselves (ahem windows)\nreturn self.socket.send(buffer(data, 0, self.SEND_LIMIT))\n</code></pre>\n" }, { "answer_id": 368709, "author": "cLFlaVA", "author_id": 45109, "author_profile": "https://Stackoverflow.com/users/45109", "pm_score": 3, "selected": false, "text": "<p>I don't have the exact code package anymore, but I remember the comment vividly.</p>\n\n<pre><code>// The code below needs to be changed immediately.\n// I wish I was a little bit taller\n// I wish I was a baller\n// I wish I had a girl who looked good, I would call her.\n</code></pre>\n" }, { "answer_id": 375554, "author": "George", "author_id": 8803, "author_profile": "https://Stackoverflow.com/users/8803", "pm_score": 3, "selected": false, "text": "<pre><code>catch (Domain.ConcurrencyException)\n{\n // somebody changed it between the time we loaded it and now.\n // weird, huh?\n}\n</code></pre>\n" }, { "answer_id": 377591, "author": "alepuzio", "author_id": 45745, "author_profile": "https://Stackoverflow.com/users/45745", "pm_score": 3, "selected": false, "text": "<p>An HORRIBLE patch for a decode (Translation by italian language):</p>\n\n<pre><code>/**\n*@return the value \n*@param key: the id of the list of instruments\n*@PS this function is a violation of all the laws of the \n*software engineering, \n*commons sense, highway code \n*and ONU decision about the coding.\nThat sh*t...\n*/\n</code></pre>\n" }, { "answer_id": 377894, "author": "Keltia", "author_id": 16143, "author_profile": "https://Stackoverflow.com/users/16143", "pm_score": 3, "selected": false, "text": "<p>That one is well-known but I like it (in sys/ufs/ufs_vnops.c):</p>\n\n<pre><code>/*\n * A virgin directory (no blushing please).\n */\n</code></pre>\n\n<p>in the FreeBSD kernel source tree (and even before, back into 4.xBSD)</p>\n" }, { "answer_id": 378918, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 3, "selected": false, "text": "<p>In an LKM:</p>\n\n<pre><code>/*\n* Dear Richard Stallman,\n*\n* This one's for you.\n*\n* Sincerely,\n* Me\n*\n*/\nMODULE_LICENSE( \"GPL\" );\n</code></pre>\n" }, { "answer_id": 378932, "author": "John Channing", "author_id": 3305, "author_profile": "https://Stackoverflow.com/users/3305", "pm_score": 1, "selected": false, "text": "<pre><code>/* Hammer Time! */\n</code></pre>\n\n<p>I have no idea why or whether he was wearing ripstop nylon parachute pants while writing the code</p>\n" }, { "answer_id": 378987, "author": "llimllib", "author_id": 42559, "author_profile": "https://Stackoverflow.com/users/42559", "pm_score": 7, "selected": false, "text": "<p>Somebody complained that the \"best\" comment was bringing up the worst comments. IMHO, they're funnier, and so \"better\", but here's the honest best comment I've ever <a href=\"http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=53656&amp;view=markup\" rel=\"nofollow noreferrer\">read</a>:</p>\n\n<pre><code>/*\nMajor subtleties ahead: Most hash schemes depend on having a \"good\" hash\nfunction, in the sense of simulating randomness. Python doesn't: its most\nimportant hash functions (for strings and ints) are very regular in common\ncases:\n\n&gt;&gt;&gt; map(hash, (0, 1, 2, 3))\n[0, 1, 2, 3]\n&gt;&gt;&gt; map(hash, (\"namea\", \"nameb\", \"namec\", \"named\"))\n[-1658398457, -1658398460, -1658398459, -1658398462]\n&gt;&gt;&gt;\n\nThis isn't necessarily bad! To the contrary, in a table of size 2**i, taking\nthe low-order i bits as the initial table index is extremely fast, and there\nare no collisions at all for dicts indexed by a contiguous range of ints.\nThe same is approximately true when keys are \"consecutive\" strings. So this\ngives better-than-random behavior in common cases, and that's very desirable.\n\nOTOH, when collisions occur, the tendency to fill contiguous slices of the\nhash table makes a good collision resolution strategy crucial. Taking only\nthe last i bits of the hash code is also vulnerable: for example, consider\n[i &lt;&lt; 16 for i in range(20000)] as a set of keys. Since ints are their own\nhash codes, and this fits in a dict of size 2**15, the last 15 bits of every\nhash code are all 0: they *all* map to the same table index.\n\nBut catering to unusual cases should not slow the usual ones, so we just take\nthe last i bits anyway. It's up to collision resolution to do the rest. If\nwe *usually* find the key we're looking for on the first try (and, it turns\nout, we usually do -- the table load factor is kept under 2/3, so the odds\nare solidly in our favor), then it makes best sense to keep the initial index\ncomputation dirt cheap.\n\nThe first half of collision resolution is to visit table indices via this\nrecurrence:\n\n j = ((5*j) + 1) mod 2**i\n\nFor any initial j in range(2**i), repeating that 2**i times generates each\nint in range(2**i) exactly once (see any text on random-number generation for\nproof). By itself, this doesn't help much: like linear probing (setting\nj += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed\norder. This would be bad, except that's not the only thing we do, and it's\nactually *good* in the common cases where hash keys are consecutive. In an\nexample that's really too small to make this entirely clear, for a table of\nsize 2**3 the order of indices is:\n\n 0 -&gt; 1 -&gt; 6 -&gt; 7 -&gt; 4 -&gt; 5 -&gt; 2 -&gt; 3 -&gt; 0 [and here it's repeating]\n\nIf two things come in at index 5, the first place we look after is index 2,\nnot 6, so if another comes in at index 6 the collision at 5 didn't hurt it.\nLinear probing is deadly in this case because there the fixed probe order\nis the *same* as the order consecutive keys are likely to arrive. But it's\nextremely unlikely hash codes will follow a 5*j+1 recurrence by accident,\nand certain that consecutive hash codes do not.\n\nThe other half of the strategy is to get the other bits of the hash code\ninto play. This is done by initializing a (unsigned) vrbl \"perturb\" to the\nfull hash code, and changing the recurrence to:\n\n j = (5*j) + 1 + perturb;\n perturb &gt;&gt;= PERTURB_SHIFT;\n use j % 2**i as the next table index;\n\nNow the probe sequence depends (eventually) on every bit in the hash code,\nand the pseudo-scrambling property of recurring on 5*j+1 is more valuable,\nbecause it quickly magnifies small differences in the bits that didn't affect\nthe initial index. Note that because perturb is unsigned, if the recurrence\nis executed often enough perturb eventually becomes and remains 0. At that\npoint (very rarely reached) the recurrence is on (just) 5*j+1 again, and\nthat's certain to find an empty slot eventually (since it generates every int\nin range(2**i), and we make sure there's always at least one empty slot).\n\nSelecting a good value for PERTURB_SHIFT is a balancing act. You want it\nsmall so that the high bits of the hash code continue to affect the probe\nsequence across iterations; but you want it large so that in really bad cases\nthe high-order hash bits have an effect on early iterations. 5 was \"the\nbest\" in minimizing total collisions across experiments Tim Peters ran (on\nboth normal and pathological cases), but 4 and 6 weren't significantly worse.\n\nHistorical: Reimer Behrends contributed the idea of using a polynomial-based\napproach, using repeated multiplication by x in GF(2**n) where an irreducible\npolynomial for each table size was chosen such that x was a primitive root.\nChristian Tismer later extended that to use division by x instead, as an\nefficient way to get the high bits of the hash code into play. This scheme\nalso gave excellent collision statistics, but was more expensive: two\nif-tests were required inside the loop; computing \"the next\" index took about\nthe same number of operations but without as much potential parallelism\n(e.g., computing 5*j can go on at the same time as computing 1+perturb in the\nabove, and then shifting perturb can be done while the table index is being\nmasked); and the dictobject struct required a member to hold the table's\npolynomial. In Tim's experiments the current scheme ran faster, produced\nequally good collision statistics, needed less code &amp; used less memory.\n\nTheoretical Python 2.5 headache: hash codes are only C \"long\", but\nsizeof(Py_ssize_t) &gt; sizeof(long) may be possible. In that case, and if a\ndict is genuinely huge, then only the slots directly reachable via indexing\nby a C long can be the first slot in a probe sequence. The probe sequence\nwill still eventually reach every slot in the table, but the collision rate\non initial probes may be much higher than this scheme was designed for.\nGetting a hash code as fat as Py_ssize_t is the only real cure. But in\npractice, this probably won't make a lick of difference for many years (at\nwhich point everyone will have terabytes of RAM on 64-bit boxes).\n*/\n</code></pre>\n" }, { "answer_id": 379021, "author": "llimllib", "author_id": 42559, "author_profile": "https://Stackoverflow.com/users/42559", "pm_score": 4, "selected": false, "text": "<p>The favorite comment I ever wrote:</p>\n\n<pre><code>//the XML returned from this request is *mind-bogglingly* bad. Terrifyingly bad.\n//a completed batch looks like this:\n//&lt;Batch&gt;batchid=363777811 status=Done dateandtime=09/18/2007 09:53:10 PDT activateditems=335 numberofwarnings=0 itemsnotacivated=17 &lt;/Batch&gt;\n//and an incomplete batch like:\n//&lt;Batch&gt;batchid=363778361 status=In Progress &lt;/Batch&gt;\n//so we'll just parse each item as a regex. Thanks Amazon.\n</code></pre>\n\n<p>And yes, Amazon actually returns XML like this.</p>\n" }, { "answer_id": 379627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Sometime in the early 1980's we were writing financial modeling code for utilities in PL/I. Got a call from a client with code blowing up right after a comment</p>\n\n<pre><code>/* Honest this works */\n</code></pre>\n\n<p>The guy had taken our standard set of financial equations and done about 15 pages of algebra to combine a bunch of code into one equation. After Three Mile Island when utilities had to write off their nuclear plants at huge costs the equation failed because of a FIXED BIN 15 (integer) overflow that would not have happened if the algebra hadn't happened.</p>\n" }, { "answer_id": 379687, "author": "Mark Beckwith", "author_id": 45799, "author_profile": "https://Stackoverflow.com/users/45799", "pm_score": 4, "selected": false, "text": "<pre><code>// This code was written by a genius so don't try to understand it with\n// your tiny little brain.\n</code></pre>\n" }, { "answer_id": 381386, "author": "Richard Ev", "author_id": 39709, "author_profile": "https://Stackoverflow.com/users/39709", "pm_score": 2, "selected": false, "text": "<p>This was the <em>only</em> comment we found in a smartcard product that a previous employer bought in. A load of embedded C and assembler written by a bunch of Dutch cryptography PhDs</p>\n\n<pre><code>// echt halmaal gek - no way!\n</code></pre>\n\n<p>(It means something like \"really completely stupid\"...which didn't help us either)</p>\n" }, { "answer_id": 381392, "author": "Richard Ev", "author_id": 39709, "author_profile": "https://Stackoverflow.com/users/39709", "pm_score": 4, "selected": false, "text": "<p>In some assembler, at the end of a line that contained <code>&amp;h723</code></p>\n\n<pre><code>' RIP LVB\n</code></pre>\n\n<p>(get it?)</p>\n" }, { "answer_id": 381499, "author": "Nicolas", "author_id": 18800, "author_profile": "https://Stackoverflow.com/users/18800", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p><code>// Description : !!! TODO</code></p>\n</blockquote>\n" }, { "answer_id": 381523, "author": "Michael Bobick", "author_id": 3425, "author_profile": "https://Stackoverflow.com/users/3425", "pm_score": 1, "selected": false, "text": "<p>In Latin, <code>Abandon hope all ye who enter here</code> from Dante's \"Divine Comedy\". </p>\n" }, { "answer_id": 381524, "author": "chaos", "author_id": 47529, "author_profile": "https://Stackoverflow.com/users/47529", "pm_score": 6, "selected": false, "text": "<pre><code>// The ratio of a circle's circumference to its diameter. Remember to change\n// this to 3.0 if you move to a site in Indiana.\n\n#define Pi 3.1415927\n</code></pre>\n" }, { "answer_id": 381599, "author": "Brian Rudolph", "author_id": 33114, "author_profile": "https://Stackoverflow.com/users/33114", "pm_score": 7, "selected": false, "text": "<p>Not quite a comment but a goto label</p>\n\n<pre><code>ICantBelieveImUsingAGoto:\n</code></pre>\n" }, { "answer_id": 383547, "author": "Andy Webb", "author_id": 10931, "author_profile": "https://Stackoverflow.com/users/10931", "pm_score": 0, "selected": false, "text": "<pre><code>REM Don't delete this print statement ****** will die\n</code></pre>\n\n<p>The process in question was a service in some legacy code</p>\n" }, { "answer_id": 385765, "author": "barfoon", "author_id": 1390354, "author_profile": "https://Stackoverflow.com/users/1390354", "pm_score": 1, "selected": false, "text": "<p>From Joomla! source:</p>\n\n<pre><code>// fudge the group stuff\n</code></pre>\n" }, { "answer_id": 385771, "author": "barfoon", "author_id": 1390354, "author_profile": "https://Stackoverflow.com/users/1390354", "pm_score": 2, "selected": false, "text": "<p>From Joomla! source:</p>\n\n<pre><code>// this is daggy??\n</code></pre>\n" }, { "answer_id": 386201, "author": "pi.", "author_id": 15274, "author_profile": "https://Stackoverflow.com/users/15274", "pm_score": 2, "selected": false, "text": "<pre><code># let's pretend we are free, for a while\n</code></pre>\n\n<p>Found this one in front of a class. What followed was a (naive) try to implement an ORM. I still don't understand why he wrote that.</p>\n" }, { "answer_id": 389723, "author": "martinus", "author_id": 48181, "author_profile": "https://Stackoverflow.com/users/48181", "pm_score": 9, "selected": false, "text": "<pre><code>/**\n * Always returns true.\n */\npublic boolean isAvailable() {\n return false;\n}\n</code></pre>\n\n<p>Never rely on a comment... </p>\n" }, { "answer_id": 400182, "author": "Anthony Giorgio", "author_id": 9816, "author_profile": "https://Stackoverflow.com/users/9816", "pm_score": 2, "selected": false, "text": "<p>Dennis M Ritchie has a page about some of the ancient UNIX comments <a href=\"http://www.cs.bell-labs.com/who/dmr/odd.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 400187, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 3, "selected": false, "text": "<p>From a unit testing class in C#:</p>\n\n<pre><code>#region quis custodiet ipsos custodes?\n\n[Fact]\npublic void TestPositive()\n{\n Assert.Equal(4, 2 + 2);\n}\n\n[Fact]\npublic void TestNegative()\n{\n Assert.Equal(5, 2 + 2);\n}\n\n#endregion\n</code></pre>\n" }, { "answer_id": 400211, "author": "Yuval", "author_id": 2819, "author_profile": "https://Stackoverflow.com/users/2819", "pm_score": 7, "selected": false, "text": "<p>I saw this comment on someone's code:</p>\n\n<pre><code>// This comment is self explanatory.\n</code></pre>\n\n<p>I guess he meant to say 'variable' but the mistake made one funny comment... Think of the circular logic here, and the futility of writing it.</p>\n" }, { "answer_id": 400230, "author": "Perry Neal", "author_id": 44633, "author_profile": "https://Stackoverflow.com/users/44633", "pm_score": 4, "selected": false, "text": "<p>Honest to God:</p>\n\n<pre><code>// This is crap code but it's 3 a.m. and I need to get this working.\n</code></pre>\n" }, { "answer_id": 417196, "author": "user24985", "author_id": 24985, "author_profile": "https://Stackoverflow.com/users/24985", "pm_score": 3, "selected": false, "text": "<pre><code>// I love the smell of dirty XML in the morning\nxml = xml.Replace(\"xmlns=\\\"urn:bsd.orion/inventory\\\"\", \"\");\n</code></pre>\n" }, { "answer_id": 431717, "author": "Brian Clapper", "author_id": 53495, "author_profile": "https://Stackoverflow.com/users/53495", "pm_score": 7, "selected": false, "text": "<p>On initialization of a linked list:</p>\n\n<pre><code>last = first; /* Biblical reference */\n</code></pre>\n\n<p>Succint and hilarious.</p>\n" }, { "answer_id": 431722, "author": "Evan Fosmark", "author_id": 49701, "author_profile": "https://Stackoverflow.com/users/49701", "pm_score": 6, "selected": false, "text": "<pre><code>// If you're reading this, that means you have been put in charge of my previous project.\n// I am so, so sorry for you. God speed.\n</code></pre>\n" }, { "answer_id": 431726, "author": "kal", "author_id": 43756, "author_profile": "https://Stackoverflow.com/users/43756", "pm_score": 3, "selected": false, "text": "<pre><code>i++; //increment i\n</code></pre>\n" }, { "answer_id": 449493, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<h2>Linux Comments</h2>\n\n<p>There are heaps of good ones here ...</p>\n\n<p>These are all comments in linux</p>\n\n<p><a href=\"http://lwn.net/1998/1015/a/f-word.html\" rel=\"nofollow noreferrer\">http://lwn.net/1998/1015/a/f-word.html</a></p>\n\n<p>My Favourites:</p>\n\n<pre><code>./arch/sparc/kernel/ptrace.c\n/* Fuck me gently with a chainsaw... */\n\n./drivers/scsi/qlogicpti.h\n/* Am I fucking pedantic or what? */\n</code></pre>\n" }, { "answer_id": 482129, "author": "Jens Roland", "author_id": 57068, "author_profile": "https://Stackoverflow.com/users/57068", "pm_score": 11, "selected": false, "text": "<p>I am particularly guilty of this, embedding non-constructive comments, code poetry and little jokes into most of my projects (although I usually have enough sense to remove anything directly offensive before releasing the code). Here's one I'm particulary fond of, placed far, far down a poorly-designed 'God Object':</p>\n\n<pre><code>/**\n* For the brave souls who get this far: You are the chosen ones,\n* the valiant knights of programming who toil away, without rest,\n* fixing our most awful code. To you, true saviors, kings of men,\n* I say this: never gonna give you up, never gonna let you down,\n* never gonna run around and desert you. Never gonna make you cry,\n* never gonna say goodbye. Never gonna tell a lie and hurt you.\n*/\n</code></pre>\n\n<p><strong>I'M SORRY!!!!</strong> I just couldn't help myself.....!</p>\n\n<p>And another, which I'll admit I haven't actually released into the wild, even though I am <em>very</em> tempted to do so in one of my less intuitive classes:</p>\n\n<pre><code>// \n// Dear maintainer:\n// \n// Once you are done trying to 'optimize' this routine,\n// and have realized what a terrible mistake that was,\n// please increment the following counter as a warning\n// to the next guy:\n// \n// total_hours_wasted_here = 42\n// \n</code></pre>\n" }, { "answer_id": 482177, "author": "Rob", "author_id": 18505, "author_profile": "https://Stackoverflow.com/users/18505", "pm_score": 2, "selected": false, "text": "<p>I just checked this in the other day...</p>\n\n<pre><code>/// &lt;STERNLY-WORDED-WARNING&gt;\n/// Pay attention to this or I will hunt you down.\n/// ...\n/// &lt;/STERNLY-WORDED-WARNING&gt;\n</code></pre>\n\n<p>Where (\"...\" == \"proprietary stuff that I can't post\"). I just liked my STERNLY-WORDED-WARNING element.</p>\n" }, { "answer_id": 482189, "author": "GBegen", "author_id": 10223, "author_profile": "https://Stackoverflow.com/users/10223", "pm_score": 4, "selected": false, "text": "<pre><code>// Hey, your shoe's untied!\n</code></pre>\n\n<p>Followed by some dubious code, and within that code,</p>\n\n<pre><code>// Keep looking! I think it was the other shoe!\n</code></pre>\n\n<p>Finally,</p>\n\n<pre><code>// How strange -- I must be seeing things. Anyhow, I'm going to go take a shower, now...\n</code></pre>\n" }, { "answer_id": 488642, "author": "Chris Kloberdanz", "author_id": 28714, "author_profile": "https://Stackoverflow.com/users/28714", "pm_score": 3, "selected": false, "text": "<p>I just ran across this one in a really simple test C++ program for a class in college.</p>\n\n<p>I was commenting a class.</p>\n\n<p>In the destructor...</p>\n\n<pre><code>// Choose! Choose the form of the Destructor!\n// The choice is made! The Traveler has come!\n</code></pre>\n" }, { "answer_id": 488651, "author": "JuanDeLosMuertos", "author_id": 39339, "author_profile": "https://Stackoverflow.com/users/39339", "pm_score": 7, "selected": false, "text": "<p>on js code:</p>\n\n<pre><code>// hack for ie browser (assuming that ie is a browser)\n</code></pre>\n" }, { "answer_id": 496175, "author": "Sam Schutte", "author_id": 146, "author_profile": "https://Stackoverflow.com/users/146", "pm_score": 1, "selected": false, "text": "<p>I once implemented some document workflow using MS SQL Server Developer 2000 (the human workflow stuff).</p>\n\n<p>It consisted of a bunch of triggers that would be added to the database to make it follow workflow rules.</p>\n\n<p>In one of the triggers, someone at Microsoft had written something along the lines of:</p>\n\n<pre><code>//Determine if the database has been \"Grizzlified\"\n</code></pre>\n\n<p>(The internal name of the product was \"Grizzly\", so I thought that was funny).</p>\n" }, { "answer_id": 499983, "author": "Nosredna", "author_id": 61027, "author_profile": "https://Stackoverflow.com/users/61027", "pm_score": 2, "selected": false, "text": "<p>I saw this once:</p>\n\n<pre><code>//this used to be a comment\n</code></pre>\n" }, { "answer_id": 502932, "author": "Neil Aitken", "author_id": 13803, "author_profile": "https://Stackoverflow.com/users/13803", "pm_score": 3, "selected": false, "text": "<p>Just found this one in some of our PHP code</p>\n\n<pre><code>$s=2; // chicken and bacon wrap for lunch\n</code></pre>\n\n<p>How useful, luckily $s was self explanatory</p>\n" }, { "answer_id": 502985, "author": "Oskar Duveborn", "author_id": 49293, "author_profile": "https://Stackoverflow.com/users/49293", "pm_score": 2, "selected": false, "text": "<pre><code>-- Beyond this point, there'll be dragons\n</code></pre>\n\n<p>I find it more pleasingly illustrative with the longer saying ^^</p>\n" }, { "answer_id": 502993, "author": "devdimi", "author_id": 54983, "author_profile": "https://Stackoverflow.com/users/54983", "pm_score": 0, "selected": false, "text": "<pre><code>// long live COM'n'Roll\npublic enum StatusCode\n{\n //success codes\n S_OK = 1,\n S_NONE = 2,\n S_SQL_OPERATIONS_LISTS_EMPTY = 3,\n\n //error codes\n E_NO_MATCHING_END_FOUND = -1,\n E_SEQUENCE_NUMBER_NOT_FOUND_AT_BEGINNING = -2,\n E_SEQUENCE_NUMBER_NOT_FOUND_AT_END = -3,\n E_FORWARD_AND_BACKWARD_OPS_COUNT_DO_NOT_MATCH = -4,\n E_FORWARD_AND_BACKWARD_IDS_DO_NOT_MATCH = -5,\n E_IDS_DO_NOT_MATCH = -6\n}\n</code></pre>\n" }, { "answer_id": 503002, "author": "MatthieuP", "author_id": 41469, "author_profile": "https://Stackoverflow.com/users/41469", "pm_score": 2, "selected": false, "text": "<pre><code>// HACK ! COPY/PASTE this and look for another job\n</code></pre>\n" }, { "answer_id": 503012, "author": "aldrinleal", "author_id": 39261, "author_profile": "https://Stackoverflow.com/users/39261", "pm_score": 5, "selected": false, "text": "<pre><code>// Caveat implementor\n</code></pre>\n" }, { "answer_id": 503186, "author": "Sindri Traustason", "author_id": 1113, "author_profile": "https://Stackoverflow.com/users/1113", "pm_score": 4, "selected": false, "text": "<p>From Apache Xalan source code:</p>\n\n<pre><code>/**\n * As Gregor Samsa awoke one morning from uneasy dreams he found himself\n * transformed in his bed into a gigantic insect. He was lying on his hard,\n * as it were armour plated, back, and if he lifted his head a little he\n * could see his big, brown belly divided into stiff, arched segments, on\n * top of which the bed quilt could hardly keep in position and was about\n * to slide off completely. His numerous legs, which were pitifully thin\n * compared to the rest of his bulk, waved helplessly before his eyes.\n * \"What has happened to me?\", he thought. It was no dream....\n */\nprotected static String DEFAULT_TRANSLET_NAME = \"GregorSamsa\";\n</code></pre>\n\n<p>Further reading on <a href=\"http://thedailywtf.com/Articles/Who_is_Gregor_Samsa_0x3f_.aspx\" rel=\"nofollow noreferrer\">The Daily WTF</a>.</p>\n" }, { "answer_id": 503215, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": 2, "selected": false, "text": "<p>This one was amusing for others but less so for me. I had inherited the code (which was ASP) from a developer who had himself inherited it. The first programmer had created some very hard to understand code. The second developer had added a comment as follows (names hidden to protect the not-so-innocent):</p>\n\n<pre><code>'This code was written by **************.\n'I haven't a clue what it does. He hasn't a clue what it does.\n'Nobody else has a clue what it does or how it does it.\n'It is something to do with data but **** knows what.\n'The ******* still works so please do not change this code,\n'even though it is a complete pile of ****.\n</code></pre>\n\n<p>So why didn't I find it amusing? Well, it was ASP code for a customer's intranet.</p>\n\n<p>...and it was the customer who highlighted the comment to me.</p>\n\n<p>:-(</p>\n" }, { "answer_id": 504832, "author": "unclerojelio", "author_id": 54757, "author_profile": "https://Stackoverflow.com/users/54757", "pm_score": 5, "selected": false, "text": "<pre><code>//Woulda\nif(x) {}\n//Shoulda\nelse if(y) {}\n//Coulda\nelse {}\n</code></pre>\n" }, { "answer_id": 505122, "author": "John Baughman", "author_id": 26923, "author_profile": "https://Stackoverflow.com/users/26923", "pm_score": 4, "selected": false, "text": "<p>Not code comments, but SVN commit comments on the same file:</p>\n\n<p>First commit (following of dozens of others after results coming back from testers):</p>\n\n<pre><code>Squashed some IPR mod bugs. The were big and juicy ones, too.\n</code></pre>\n\n<p>2nd commit:</p>\n\n<pre><code>Squashed some more mod bugs. Those are some nasty bugs, them mod bugs...\n</code></pre>\n\n<p>3rd:</p>\n\n<pre><code>Squashed some more mod bugs. They are like cockroaches: they'll live through a nuclear war.\n</code></pre>\n\n<p>4th:</p>\n\n<pre><code>Squashed some more John bugs. They too are like cockroaches: they appear anywhere John goes. Wait. That doesn't sound right.\n</code></pre>\n\n<p>And 5th:</p>\n\n<pre><code>Same John bug. It didn't die, just played 'possum.\n</code></pre>\n\n<p>Yes, I was tired of \"Fixed bug\".</p>\n" }, { "answer_id": 505344, "author": "Jeremy Ricketts", "author_id": 36758, "author_profile": "https://Stackoverflow.com/users/36758", "pm_score": 5, "selected": false, "text": "<p><code>.class {border:1px solid gold;} /* I pitty the fool */</code></p>\n" }, { "answer_id": 508563, "author": "Andreas", "author_id": 54710, "author_profile": "https://Stackoverflow.com/users/54710", "pm_score": 1, "selected": false, "text": "<pre><code>// StupidCompilerDontInline(SCDI), in the test project where\n// allcode was in a single cpp the compiler had inlined nearly\n// everything which lead to nice stackoverflow.\n// To prevent this the metods are made virtual\n#define SCDI virtual\n</code></pre>\n" }, { "answer_id": 508818, "author": "Pete H.", "author_id": 52966, "author_profile": "https://Stackoverflow.com/users/52966", "pm_score": 6, "selected": false, "text": "<pre><code>//MailBody builders for two outgoing messages\nStringBuilder hanz = new StringBuilder();\nStringBuilder franz = new StringBuilder();\n</code></pre>\n\n<p>I still chuckle a little when I read that one...</p>\n" }, { "answer_id": 515402, "author": "User", "author_id": 62830, "author_profile": "https://Stackoverflow.com/users/62830", "pm_score": 1, "selected": false, "text": "<p>Found this recently in our code (we develop enterprise software):</p>\n\n<pre><code>// Instance of excel\nExcel excel = this.CreateExcelInstance();\nexcel.Open(stream); // how to close it?!\n</code></pre>\n\n<p>Until that I was sure we're free of this \"fun stuff\" and we're doing it the right and ideologically correct way...</p>\n" }, { "answer_id": 515419, "author": "Polo", "author_id": 60561, "author_profile": "https://Stackoverflow.com/users/60561", "pm_score": 3, "selected": false, "text": "<p>This comment is from an old project that i had to debug:</p>\n\n<pre><code>//Haleluya i can go home!\n</code></pre>\n" }, { "answer_id": 515593, "author": "xan", "author_id": 15667, "author_profile": "https://Stackoverflow.com/users/15667", "pm_score": 5, "selected": false, "text": "<p>From a google code project:</p>\n\n<pre><code># This job would be great if it wasn't for the fucking customers.\n</code></pre>\n" }, { "answer_id": 515605, "author": "Lukas Šalkauskas", "author_id": 5369, "author_profile": "https://Stackoverflow.com/users/5369", "pm_score": 2, "selected": false, "text": "<p>Once I found this:</p>\n\n<pre><code>// I wish (boss name) could do this by him self.\n</code></pre>\n" }, { "answer_id": 519734, "author": "BoD", "author_id": 15695, "author_profile": "https://Stackoverflow.com/users/15695", "pm_score": 4, "selected": false, "text": "<p>Once, I asked a coworker how to do something (forgot exactly what, some obscure technical calls) with our in-house framework.\nHe said \"easy, look HERE\", then opens a .java file in his editor and shows me this comment in the middle of several pages of code:</p>\n\n<pre><code>// HERE\n</code></pre>\n\n<p>I just checked, the comment is still there in this file :)</p>\n" }, { "answer_id": 522655, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "<p>I like some of the comments in the GNU binutils. This one is from BFD som.c:</p>\n\n<pre><code>/* You'll never believe all this is necessary to handle relocations\n for function calls. Having to compute and pack the argument\n relocation bits is the real nightmare.\n\n If you're interested in how this works, just forget it. You really\n do not want to know about this braindamage. */\n</code></pre>\n\n<p>This one too:</p>\n\n<pre><code>/* Don't ask about these magic sequences. I took them straight\n from gas-1.36 which took them from the a.out man page. */\n</code></pre>\n\n<p>...</p>\n\n<pre><code>/* Keep track of exactly where we are within a particular\n space. This is necessary as the braindamaged HPUX\n loader will create holes between subspaces *and*\n subspace alignments are *NOT* preserved. What a crock. */\n</code></pre>\n\n<p>Another one:</p>\n\n<pre><code>/* We will NOT put a fucking timestamp in the header here. Every\n time you put it back, I will come in and take it out again. ... */\n</code></pre>\n\n<p>From gas:</p>\n\n<pre><code>/* Yes this is ugly (storing the broken_word pointer\n in the symbol slot). Still, this whole chunk of\n code is ugly, and I don't feel like doing anything\n about it. Think of it as stubbornness in action. */\n</code></pre>\n" }, { "answer_id": 538091, "author": "Jane Sales", "author_id": 63994, "author_profile": "https://Stackoverflow.com/users/63994", "pm_score": 3, "selected": false, "text": "<p>I once worked on the source code of Windows 3.0. (Not, I hasten to add, as a Microsoft employee!) There I came across a file loader that went re-entrant multiple times, and had one example of some nasty punning (just to show how clever the author was).</p>\n\n<p>This mess of re-entrant code was executed with an Intel assembly jmp instruction (in the middle of C code), which went to the label <code>\"we_are_not_in_kansas_any_more_toto\"</code>.</p>\n" }, { "answer_id": 538175, "author": "Tim Post", "author_id": 50049, "author_profile": "https://Stackoverflow.com/users/50049", "pm_score": 4, "selected": false, "text": "<p>I guess it got viral, I found the following in a daemon (Linux) that prevents the OOM killer from selecting it:</p>\n\n<pre><code>/*\n * Don't OOM me, bro!\n */\n</code></pre>\n\n<p>This was right after a mlockall() to prevent the process from swapping, commented:</p>\n\n<pre><code>/*\n * Don't swap me, bro!\n */\n</code></pre>\n" }, { "answer_id": 544238, "author": "Bennett McElwee", "author_id": 61754, "author_profile": "https://Stackoverflow.com/users/61754", "pm_score": 3, "selected": false, "text": "<pre><code>try {\n doSomething();\n} catch(err) {\n // Die quietly\n alert(err);\n}\n</code></pre>\n" }, { "answer_id": 544337, "author": "JohnFx", "author_id": 30018, "author_profile": "https://Stackoverflow.com/users/30018", "pm_score": 1, "selected": false, "text": "<p>Had a programmer working for me once that put \"Style\" comments throughout his code where he codified his internal debates about the particular implementation details and to take parting shots when he was overruled on a particular coding decision.</p>\n\n<p>Examples:</p>\n\n<p>'STYLE\n 'It's arguable which is better, but I pass the image handle rather than simply\n 'passing the scaling values in order to keep the calling code simpler (by a\n 'couple of declarations statements). Alternatively, I could pass these data\n 'members directly from the calling code, but that would violate encapsulation.</p>\n\n<p>'STYLE\n'As I have done elsewhere, I will <strong>register my offical protest</strong> (just give me the\n'forms to fill out) regarding the implementation of annotation serialization as\n'a property rather than a pair of Load/Save methods. Again, this is probably a\n'matter of style and eminently debatable.</p>\n" }, { "answer_id": 549611, "author": "スーパーファミコン", "author_id": 53189, "author_profile": "https://Stackoverflow.com/users/53189", "pm_score": 10, "selected": false, "text": "<pre><code>Exception up = new Exception(\"Something is really wrong.\");\nthrow up; //ha ha\n</code></pre>\n" }, { "answer_id": 549644, "author": "James Jones", "author_id": 84088, "author_profile": "https://Stackoverflow.com/users/84088", "pm_score": 1, "selected": false, "text": "<pre><code>'this next if statement - just how it is. don't try to understand it because you won't. :)\n</code></pre>\n\n<p>That's job security right there.</p>\n" }, { "answer_id": 577663, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>// barcore.cpp - MFC\n\n//.....\nHBRUSH CControlBar::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)\n{\n LRESULT lResult;\n if (pWnd-&gt;SendChildNotifyLastMsg(&amp;lResult))\n return (HBRUSH)lResult; // eat it\n\n//......\n\n// Eat it - just like eat this.\n</code></pre>\n" }, { "answer_id": 614031, "author": "Viachaslau Tysianchuk", "author_id": 74144, "author_profile": "https://Stackoverflow.com/users/74144", "pm_score": 2, "selected": false, "text": "<pre><code>// Iced odnako\nbool Iced{get;set;}\n</code></pre>\n" }, { "answer_id": 614792, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<pre><code>/////////////////////////////////////// this is a well commented line\n</code></pre>\n" }, { "answer_id": 615022, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Something I saw in a .h file years ago.</p>\n\n<pre><code>// It may be a hack, but it works.\n</code></pre>\n" }, { "answer_id": 615028, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Something I saw in a COBOL program that paralyzed me with fear</p>\n\n<pre><code>* All comments pertain to the lines which follow.\n</code></pre>\n\n<p>What does this mean?</p>\n\n<ol>\n<li><p>Someone was so uncomfortable with commenting that they had to write a meta-comment?</p></li>\n<li><p>Someone was in the habit of putting comments <em>below</em> the relevant code and had been told to put comments above? How did that happen?</p></li>\n</ol>\n" }, { "answer_id": 615049, "author": "Ed Marty", "author_id": 36007, "author_profile": "https://Stackoverflow.com/users/36007", "pm_score": 4, "selected": false, "text": "<p>In a game where this object can be stepped on, or:</p>\n\n<pre><code>stepOff(); //bitch\n</code></pre>\n" }, { "answer_id": 615795, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>For one project we had pwlib as a dependency, and at that time it's FreeBSD port was somewhat screwed so I had to build it manually from source. It didn't work out right away, and I had to look into the code; there was some complicated class hierarchy with parts of code generated by macros and its parent calss declaration started with</p>\n\n<pre><code>// The root of all evil ... umm classes\n</code></pre>\n" }, { "answer_id": 615845, "author": "Juliano", "author_id": 55078, "author_profile": "https://Stackoverflow.com/users/55078", "pm_score": 8, "selected": false, "text": "<pre><code>long long ago; /* in a galaxy far far away */ \n</code></pre>\n" }, { "answer_id": 615872, "author": "Chris Doggett", "author_id": 64203, "author_profile": "https://Stackoverflow.com/users/64203", "pm_score": 3, "selected": false, "text": "<p>I had to add this one to our old datatable-driven rules engine before I decided to replace it with a scripting language.</p>\n\n<pre><code> /************************************************************\n * *\n * .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-. *\n * | ______ | *\n * | .-\" \"-. | *\n * | / \\ | *\n * | _ | | _ | *\n * | ( \\ |, .-. .-. ,| / ) | *\n * | &gt; \"=._ | )(__/ \\__)( | _.=\" &lt; | *\n * | (_/\"=._\"=._ |/ /\\ \\| _.=\"_.=\"\\_) | *\n * | \"=._\"(_ ^^ _)\"_.=\" | *\n * | \"=\\__|IIIIII|__/=\" | *\n * | _.=\"| \\IIIIII/ |\"=._ | *\n * | _ _.=\"_.=\"\\ /\"=._\"=._ _ | *\n * | ( \\_.=\"_.=\" `--------` \"=._\"=._/ ) | *\n * | &gt; _.=\" \"=._ &lt; | *\n * | (_/ \\_) | *\n * | | *\n * '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' *\n * *\n * LASCIATE OGNI SPERANZA, VOI CH'ENTRATE *\n *************************************************************/\n</code></pre>\n" }, { "answer_id": 615887, "author": "David", "author_id": 9908, "author_profile": "https://Stackoverflow.com/users/9908", "pm_score": 2, "selected": false, "text": "<p>For a memcache wrapper/handler interface pattern class I wrote, I had the following method implemented.</p>\n\n<pre><code>/**\n* Do not use, ever - left in place for testing purposes\n*/\nfunction I_David_WillHuntYouDownAndHurtYou_Badly_IfIFindThisUsedAnyWhereInTheAppLibrary(){\n...\n}\n</code></pre>\n\n<p>This was basically a super nuke function to tell all the indvidual memcache services to completely flush themselves, and start over with the individual name space counters I used for keys ( ex .{_counter_key value}_.{_counter_key value} )</p>\n\n<p>Another minor novella I wrote was for an automated downloader for a data vendor, detailing how much I hated this vendor and went to great lengths of postulating that their infrastructure's batch system was run by a gerbil, running on a wheel and after so many revolutions of the wheel the next queued task would be started. It was written over the course of 6 months of adding additional exception handling, estoric checks like ( if we got 768 Bytes of \\s characters, that means the query to their DB timed out and the spaces are the result of empty failure print statements.</p>\n" }, { "answer_id": 615901, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 6, "selected": false, "text": "<p>in a homework assignment in college for a teacher who was particularly adamant that we comment our code:</p>\n\n<pre><code>//I wonder if she actually reads these.\n</code></pre>\n\n<p>When the assignment was returned, in red pen next to that comment \"Yes, I do\"</p>\n" }, { "answer_id": 615910, "author": "shampoopy", "author_id": 37812, "author_profile": "https://Stackoverflow.com/users/37812", "pm_score": 0, "selected": false, "text": "<pre><code>// Oh crap, i think i'm gonna yack\n</code></pre>\n\n<p>followed shortly thereafter by:</p>\n\n<pre><code>// TODO: end this lunacy\n</code></pre>\n" }, { "answer_id": 615989, "author": "Rad", "author_id": 1349, "author_profile": "https://Stackoverflow.com/users/1349", "pm_score": 7, "selected": false, "text": "<pre><code>class Act //That's me!!!\n{\n\n}\n</code></pre>\n" }, { "answer_id": 616013, "author": "Rad", "author_id": 1349, "author_profile": "https://Stackoverflow.com/users/1349", "pm_score": 7, "selected": false, "text": "<pre><code>try {\n\n}\ncatch (SQLException ex) {\n // Basically, without saying too much, you're screwed. Royally and totally.\n}\ncatch(Exception ex)\n{\n //If you thought you were screwed before, boy have I news for you!!!\n}\n</code></pre>\n" }, { "answer_id": 616053, "author": "TheHolyTerrah", "author_id": 32532, "author_profile": "https://Stackoverflow.com/users/32532", "pm_score": 4, "selected": false, "text": "<p>My favorite (which I must admit I've used many times):</p>\n\n<pre><code>// Yes...I know this is repulsive and stupid.\n// But &lt;%CompanyOwnerOrManagerToken%&gt;, not knowing a thing about code,\n// demanded I do it anyways. SO, go crap on their desk, not mine.\n// K THX BYE \n</code></pre>\n" }, { "answer_id": 616101, "author": "Jaanus", "author_id": 49951, "author_profile": "https://Stackoverflow.com/users/49951", "pm_score": 3, "selected": false, "text": "<p>Not in code, but in a related bugtracking system:</p>\n\n<blockquote>\n <p>This can't be a bug in my code. I coded it very carefully.</p>\n</blockquote>\n" }, { "answer_id": 616122, "author": "Gambrinus", "author_id": 42386, "author_profile": "https://Stackoverflow.com/users/42386", "pm_score": 2, "selected": false, "text": "<pre><code>try\n{\n...\n}\ncatch(Exception ex)\n{\n//if this happens the world is going to end...\n}\n</code></pre>\n\n<p>now guess what happened...</p>\n" }, { "answer_id": 616281, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>// If you delete the credits, I will fucking kill you.\n</code></pre>\n\n<p>found in a joomla module.</p>\n" }, { "answer_id": 616523, "author": "danio", "author_id": 12663, "author_profile": "https://Stackoverflow.com/users/12663", "pm_score": 3, "selected": false, "text": "<pre><code> // Some wanker in ISO got rid of ifstream(int), ofstream(int), and\n // fstream(int). Twit.\n</code></pre>\n" }, { "answer_id": 616551, "author": "user16208", "author_id": 16208, "author_profile": "https://Stackoverflow.com/users/16208", "pm_score": 5, "selected": false, "text": "<p>don't know if it it's funny or sad..but one intern I had working with me had this little gem to calculate the price per unit</p>\n\n<pre><code>...\n\n// get the units from the form \nint numUnits = Integer.parseInt(request.getParameter(\"num_pieces\")); // this break at random times\n\n//price \nfloat price = Float.parseFloat(request.getParameter(\"price\")); // same as above\n\n// Under certain conditions the following code blows up. I don't know those conditions.\nfloat pricePerUnit = price / (float)numUnits;\n\n...\n</code></pre>\n" }, { "answer_id": 618817, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>... or die // bitch</p>\n" }, { "answer_id": 618828, "author": "Pratik Deoghare", "author_id": 58737, "author_profile": "https://Stackoverflow.com/users/58737", "pm_score": 4, "selected": false, "text": "<pre><code>/**---------START-----------**/\n\n // IMPLEMENTATION GOES HERE\n\n/**---------END-----------**/\n</code></pre>\n\n<p><strong>But No Code ;)</strong></p>\n" }, { "answer_id": 618976, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<pre><code>// John! If you'll svn remove this once more,\n// I'll shut you, for God's sake!\n// That piece of code is not “something strange”!\n// That is THE AUTH VALIDATION.\n</code></pre>\n\n<p>And what do you think? The code below was safely ‘svn removed’.</p>\n" }, { "answer_id": 621591, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 2, "selected": false, "text": "<p>This is a comment of mine which I found today while refactoring some code</p>\n\n<pre><code>if( year &lt; 100 ): year += 2000 #lol, Y2K\n</code></pre>\n" }, { "answer_id": 626983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>$this-&gt;getSelect()-&gt;where ('main_table.product_id = -1'); // Mom, Dad... sorry\n</code></pre>\n" }, { "answer_id": 628776, "author": "Flow", "author_id": 75937, "author_profile": "https://Stackoverflow.com/users/75937", "pm_score": 3, "selected": false, "text": "<pre><code>// insert comment here\n</code></pre>\n" }, { "answer_id": 638670, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<pre><code>} catch (PartInitException pie) {\n // Mmm... pie\n</code></pre>\n" }, { "answer_id": 645024, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I just ran into this in some of my own code. It was in a magento admin template for category selection:</p>\n\n<pre><code> /*\n * OK; before you read the following code know what I am trying to do.\n * I needed to get the list of child catagories from the root node so that\n * the root node didn't appear in the selection box. But for some stupid\n * fucking reason the stupid fucking DBA wont let me access the items using\n * indicies and I instead have to use their stupid fucking Iterator\n * implementation. So there.\n */\n $firstList = $this-&gt;getRootNode()-&gt;getChildren();\n foreach ($firstList as $node)\n {\n $nodes = $node-&gt;getChildren();\n break; // wtf?\n }\n</code></pre>\n\n<p>I am going to remove the language of course out of our flagship product; but I remember I was super frustrated. If I hadn't left a comment, I would try to revise it but then run into the same problems I had before.</p>\n" }, { "answer_id": 647713, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Back around the time the Hitchhiker's Guide game was new, I had a case where I was testing whether something was scrollable and whether the user was trying to scroll, in a language that restricted variable length. So:</p>\n\n<pre><code>if (scroll and noScroll) # or tea and no tea\n</code></pre>\n" }, { "answer_id": 648822, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 3, "selected": false, "text": "<pre><code>// nobody read comments!\n</code></pre>\n" }, { "answer_id": 648866, "author": "Neil N", "author_id": 55164, "author_profile": "https://Stackoverflow.com/users/55164", "pm_score": 6, "selected": false, "text": "<p>this has turned up in my own code a few times. obviously I touched it more than once:</p>\n\n<pre><code>// TODO: Fix this. Fix what?\n</code></pre>\n" }, { "answer_id": 649920, "author": "Simon Lieschke", "author_id": 2766, "author_profile": "https://Stackoverflow.com/users/2766", "pm_score": 3, "selected": false, "text": "<p>I discovered this gem when viewing the HTML source of <a href=\"http://web.archive.org/web/20040609194213/tvnz.co.nz/view/tvnz_index_skin/tvnz_index_group\" rel=\"nofollow noreferrer\">an earlier iteration of the TVNZ website</a> (from line 571 if you're playing along at home):</p>\n\n<pre><code>&lt;!-- Hopfully we can do this otherwise the nav is going to be pretty plain and Hong will go postal. --&gt;\n</code></pre>\n" }, { "answer_id": 649924, "author": "Telemachus", "author_id": 26702, "author_profile": "https://Stackoverflow.com/users/26702", "pm_score": 2, "selected": false, "text": "<pre><code>// The hackiest hack that ever did hack\n</code></pre>\n\n<p>It's in the <a href=\"http://wordpress.org/\" rel=\"nofollow noreferrer\">WordPress</a> blog engine (wp-admin/includes/user.php - if anyone actually wants to see the hacky hack itself).</p>\n" }, { "answer_id": 657831, "author": "Jeeva Subburaj", "author_id": 79442, "author_profile": "https://Stackoverflow.com/users/79442", "pm_score": 2, "selected": false, "text": "<pre><code>//If the Current Record is Getting End Dated, We should not create New History Entry. \n//We Just need to Update the Previous History Entry\n//If the History is already End Dated and the New Record is now removing End Date, Then \n//We should not update the Previous History End Date. \n//We Just need to Create the New History Record Only.\n//Alright.. \n//Alright.... \n//Enough Comments. Code it. :-)\n</code></pre>\n" }, { "answer_id": 657879, "author": "Tony", "author_id": 68536, "author_profile": "https://Stackoverflow.com/users/68536", "pm_score": 2, "selected": false, "text": "<pre><code>#define SHIT_HAPPENED (BASE + 1) /* generic shit happened */\n</code></pre>\n" }, { "answer_id": 657888, "author": "Esko Luontola", "author_id": 62130, "author_profile": "https://Stackoverflow.com/users/62130", "pm_score": 1, "selected": false, "text": "<p>In eMule, Preferences.cpp, in the method that forces a minimum upload speed limit proportional to your download speed limit:</p>\n\n<pre><code>uint16 CPreferences::GetMaxDownload(){\n//dont be a Lam3r :)\n uint16 maxup=(GetMaxUpload()==UNLIMITED)?GetMaxGraphUploadRate():GetMaxUpload();\n if( maxup &lt; 4 )\n return (( (maxup &lt; 10) &amp;&amp; (maxup*3 &lt; prefs-&gt;maxdownload) )? maxup*3 : prefs-&gt;maxdownload);\n return (( (maxup &lt; 10) &amp;&amp; (maxup*4 &lt; prefs-&gt;maxdownload) )? maxup*4 : prefs-&gt;maxdownload);\n}\n</code></pre>\n" }, { "answer_id": 675779, "author": "Jorn", "author_id": 8681, "author_profile": "https://Stackoverflow.com/users/8681", "pm_score": 4, "selected": false, "text": "<pre><code>/* FIXME This must absolutely be removed before 4.0.7 release\n * TODO really remove this */\n</code></pre>\n\n<p>we have since released a 4.0.7, 4.0.8, 4.0.9 and 4.1 version...</p>\n" }, { "answer_id": 676374, "author": "Stephen Curial", "author_id": 1399919, "author_profile": "https://Stackoverflow.com/users/1399919", "pm_score": 0, "selected": false, "text": "<p>Mine fave was a variable name inside some of the business logic of a school project written in java.</p>\n\n<pre><code>int StupidJava = -1;\n</code></pre>\n" }, { "answer_id": 686583, "author": "Fraser", "author_id": 74861, "author_profile": "https://Stackoverflow.com/users/74861", "pm_score": 2, "selected": false, "text": "<p>Just found this in some Actionscript I have to update...</p>\n\n<pre><code>/*\n* spaghetty code in this module.\n* hardcoded variables for load paths for the content window.\n* Needs (vast) improvement.\n*/\n</code></pre>\n\n<p>..great :(</p>\n" }, { "answer_id": 686915, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 4, "selected": false, "text": "<pre><code>// A Gorgon class - For the love of Zeus don't look directly at it!\n</code></pre>\n" }, { "answer_id": 687811, "author": "Martin Lazar", "author_id": 82569, "author_profile": "https://Stackoverflow.com/users/82569", "pm_score": 6, "selected": false, "text": "<p>Once I saw in another discussion something like this:</p>\n\n<pre><code>// I can't divide with zero, so I have to divide with something very similar\nresult = number / 0.00000000000001;\n</code></pre>\n\n<p>Clever solution, isn't it :) ? (It's a joke if someone's not sure)</p>\n" }, { "answer_id": 687856, "author": "Brian Campbell", "author_id": 69755, "author_profile": "https://Stackoverflow.com/users/69755", "pm_score": 3, "selected": false, "text": "<p>This is so much nicer than the scary legal notices and disclaimers you see in many comment headers. From <a href=\"http://www.sqlite.org/\" rel=\"nofollow noreferrer\">SQLite</a>.</p>\n\n<pre><code>/*\n** The author disclaims copyright to this source code. In place of\n** a legal notice, here is a blessing:\n**\n** May you do good and not evil.\n** May you find forgiveness for yourself and forgive others.\n** May you share freely, never taking more than you give.\n*/\n</code></pre>\n" }, { "answer_id": 687907, "author": "hacken", "author_id": 62733, "author_profile": "https://Stackoverflow.com/users/62733", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.jwz.org/doc/censorzilla.html\" rel=\"nofollow noreferrer\">Classics</a> from the old netscape mozilla code. Personally I like</p>\n\n<blockquote>\n <p>just can't fuck around. Oh, also moving memory would doom us anyway, and\n it'll all just be too damn hard to figure out. So, I give up, the Mac just\n completely utterly sucks complete rocks </p>\n</blockquote>\n\n<p>but there are a lot of other fun ones.</p>\n" }, { "answer_id": 687969, "author": "i_am_jorf", "author_id": 74815, "author_profile": "https://Stackoverflow.com/users/74815", "pm_score": 3, "selected": false, "text": "<pre><code>// TODO: Drive an ashen stake through the foul heart of this function.\n</code></pre>\n\n<p>And it was a foul function. I have nightmares about it to this day.</p>\n" }, { "answer_id": 688017, "author": "user63503", "author_id": 63503, "author_profile": "https://Stackoverflow.com/users/63503", "pm_score": 4, "selected": false, "text": "<pre><code>// this error could never happen\n</code></pre>\n\n<p>And then -- customer's call saying he sees an error message saying \"this error could never happen\"</p>\n" }, { "answer_id": 688088, "author": "eglasius", "author_id": 66372, "author_profile": "https://Stackoverflow.com/users/66372", "pm_score": 2, "selected": false, "text": "<p>Back in college: </p>\n\n<pre><code>//why the f*** we have to move this here to make it work\n</code></pre>\n\n<p>It was highlighted in a printed source when we went to review with the professor.</p>\n\n<p>The reason: some really nasty bug related to a buffer overflow, that affected an unrelated variable with a file handler in other place of the code. Moving the variable would make it work again.</p>\n" }, { "answer_id": 694615, "author": "Amr Elgarhy", "author_id": 20126, "author_profile": "https://Stackoverflow.com/users/20126", "pm_score": 1, "selected": false, "text": "<pre><code>// Sorry dirty code\n</code></pre>\n" }, { "answer_id": 694644, "author": "Mia Clarke", "author_id": 83075, "author_profile": "https://Stackoverflow.com/users/83075", "pm_score": 8, "selected": false, "text": "<pre><code>//Dear future me. Please forgive me. \n//I can't even begin to express how sorry I am. \n</code></pre>\n\n<p>And I just found this one today:</p>\n\n<pre><code>//private instance variable for storing age\npublic static int age;\n</code></pre>\n" }, { "answer_id": 694652, "author": "Zifre", "author_id": 83871, "author_profile": "https://Stackoverflow.com/users/83871", "pm_score": 6, "selected": false, "text": "<p>In drivers/net/sunhme.c (Linux kernel):</p>\n\n<pre><code>/* Welcome to Sun Microsystems, can I take your order please? */\nif(!hp-&gt;happy_flags &amp; HFLAG_FENABLE)\n return happy_meal_bb_write(hp, tregs, reg, value);\n\n/* Would you like fries with that? */\nhme_write32(hp, &amp;tregs-&gt;frame,\n (FRAME_WRITE | (hp-&gt;paddr &lt;&lt; 23) |\n ((reg &amp; 0xff) &lt;&lt; 18) | (value &amp; 0xffff)));\nwhile(!(hme_read32(hp, &amp;tregs-&gt;frame) &amp; 0x10000) &amp;&amp; --tries)\n udelay(20);\n\n/* Anything else? */\nif(!tries)\n printk(KERN_ERR \"happy meal: Aieee, transceiver MIF write bolixed\\n\");\n\n/* Fifty-two cents is your change, have a nice day. */\n</code></pre>\n" }, { "answer_id": 706648, "author": "euphoria83", "author_id": 78351, "author_profile": "https://Stackoverflow.com/users/78351", "pm_score": 2, "selected": false, "text": "<pre><code>// Empty constructor to satisfy the stupid compiler\n Public ServletHandlerClass () { } \n</code></pre>\n" }, { "answer_id": 713861, "author": "BobC", "author_id": 31167, "author_profile": "https://Stackoverflow.com/users/31167", "pm_score": 3, "selected": false, "text": "<pre><code>catch (Exception ex)\n{ \n // just die already.\n}\n</code></pre>\n" }, { "answer_id": 713871, "author": "AaronLS", "author_id": 84206, "author_profile": "https://Stackoverflow.com/users/84206", "pm_score": 1, "selected": false, "text": "<p>We have a file and half way down it a programmer trying to make sense of the mess managed to move all the nonsense code to the bottom, and left a comment of something like:</p>\n\n<pre><code>I have no idea what this stuff does below here.\n</code></pre>\n\n<p>Another programmer left a series of nested namespaces that acted like a which-way-book, so that you could drill into the namespaces in the idea and choose your actions.</p>\n" }, { "answer_id": 713872, "author": "JeffO", "author_id": 61339, "author_profile": "https://Stackoverflow.com/users/61339", "pm_score": 2, "selected": false, "text": "<p>See this one:</p>\n\n<pre><code>'On Error Goto Hell.\n</code></pre>\n" }, { "answer_id": 714566, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>BerkeleyDB</p>\n\n<pre><code>/*\n * Chaos reigns within.\n * Reflect, repent, and reboot.\n * Order shall return.\n */\nreturn (DB_RUNRECOVERY);\n</code></pre>\n" }, { "answer_id": 717461, "author": "martinus", "author_id": 48181, "author_profile": "https://Stackoverflow.com/users/48181", "pm_score": 4, "selected": false, "text": "<pre><code> /**\n * Returns cookies according to the filters specified.\n * \n * @return array Cookies! Nom nom nom nom nom.\n */\n public function data_getCookies($uid, $name) {\n</code></pre>\n\n<p>Somewhere from the <a href=\"http://www.google.com/codesearch/p?hl=en#gS-K-kM7dUU/com_rohea_facebook/facebook-client/facebookapi_php5_restlib.php&amp;q=%22nom%20nom%20nom%22&amp;l=902\" rel=\"nofollow noreferrer\">facebook api</a>.</p>\n" }, { "answer_id": 717501, "author": "MissT", "author_id": 81523, "author_profile": "https://Stackoverflow.com/users/81523", "pm_score": 2, "selected": false, "text": "<p>In an art asset export tool, I stumble upon a complete translator from digits (arabic) numbers to roman numbers. It looked like this:</p>\n\n<pre><code>/*\n//You can tell I was bored\n//I wanted to do this for a long time\nchar* ConvertToRoman(int number, int base)\n{\n... whole code here\n}\n*/\n</code></pre>\n\n<p>The team of the person that wrote this code had been crunching for a long time, I guess it affected their sanity.</p>\n" }, { "answer_id": 720857, "author": "Paul Suart", "author_id": 68432, "author_profile": "https://Stackoverflow.com/users/68432", "pm_score": 0, "selected": false, "text": "<pre><code>// Hack-er-ama\n</code></pre>\n" }, { "answer_id": 720865, "author": "Eskat0n", "author_id": 78316, "author_profile": "https://Stackoverflow.com/users/78316", "pm_score": 3, "selected": false, "text": "<pre><code># Don use this. Never!\n</code></pre>\n" }, { "answer_id": 720902, "author": "Elroy", "author_id": 56097, "author_profile": "https://Stackoverflow.com/users/56097", "pm_score": 1, "selected": false, "text": "<pre><code>else\n{\n //error situation\n}\n</code></pre>\n" }, { "answer_id": 720905, "author": "fog", "author_id": 57334, "author_profile": "https://Stackoverflow.com/users/57334", "pm_score": 5, "selected": false, "text": "<p>About 10 years ago I was working at image processing, scanning microscope video frames to detect cell movement. I was working at a particulary intricated function and decided to go out and have a drink with friends. When I came back home I worked a little bit but not too much because I was drunk. The morning after I found a 10-line completely messed-up function with the following comment (obviously written by my other self):</p>\n\n<pre><code>/* Ah ah ah! You'll never understand why this one works. */\n</code></pre>\n\n<p>The strangest part was that it even <em>worked</em>.</p>\n" }, { "answer_id": 720983, "author": "Elroy", "author_id": 56097, "author_profile": "https://Stackoverflow.com/users/56097", "pm_score": 1, "selected": false, "text": "<pre><code>#pragma region Crap that is kept for temporary reasons\n\n // Huge chunk of commented code\n\n#pragma endregion\n</code></pre>\n" }, { "answer_id": 721029, "author": "lfx", "author_id": 43164, "author_profile": "https://Stackoverflow.com/users/43164", "pm_score": 4, "selected": false, "text": "<pre><code>// If I from the future read this I'll back in time and kill myself. \n</code></pre>\n" }, { "answer_id": 721065, "author": "pomarc", "author_id": 85738, "author_profile": "https://Stackoverflow.com/users/85738", "pm_score": 2, "selected": false, "text": "<pre><code>//marco 2007.1.23\n//I didn't do it\n</code></pre>\n" }, { "answer_id": 721091, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 3, "selected": false, "text": "<p>Well, these are mine, so WTF is me, as CodingHorror said:</p>\n\n<pre><code>//#region Code for weird cases - do you really want to know?\n</code></pre>\n\n<p>I once left a comment like so in some ASP:</p>\n\n<pre><code>' Commented out following code, don't delete for when [CustomerName] changes his mind\n</code></pre>\n\n<p>As it happens, [CustomerName] didn't change his mind, but he DID have access to the web server, and he DID find that line...</p>\n" }, { "answer_id": 721797, "author": "Colin Cassidy", "author_id": 6515, "author_profile": "https://Stackoverflow.com/users/6515", "pm_score": 3, "selected": false, "text": "<p>managed to insert this bad pun into our code</p>\n\n<pre><code>for (bo_thans = 0 ; bo_thans &lt; MAX ; bo_thans++)\n{\n if(rs == thing[bo_thans])\n {\n found = true;\n }\n}\n\nif(!found)\n{\n /* Failed to find rs with bo_thans */\n ...\n}\n</code></pre>\n" }, { "answer_id": 721922, "author": "Brian Postow", "author_id": 53491, "author_profile": "https://Stackoverflow.com/users/53491", "pm_score": 1, "selected": false, "text": "<p>When I'm commenting out chunks of code that I <em>THINK</em> are no longer useful, but I might be wrong about (hence not deleting them) I will sometimes preface them with </p>\n\n<pre><code>// Wilted celery?\n</code></pre>\n\n<p>The idea being that this is like celery that is wilted, but you put it back in the fridge anyway. I just know that 10 years from now someone else will find these comments and say WTF?</p>\n" }, { "answer_id": 726186, "author": "TalkingCode", "author_id": 70414, "author_profile": "https://Stackoverflow.com/users/70414", "pm_score": 2, "selected": false, "text": "<pre><code>// Keep prozac ready if things get ugly!\n</code></pre>\n" }, { "answer_id": 735896, "author": "ninegrid", "author_id": 13661, "author_profile": "https://Stackoverflow.com/users/13661", "pm_score": 0, "selected": false, "text": "<pre><code>// now swap like a &lt;explicative removed&gt;\n</code></pre>\n" }, { "answer_id": 735928, "author": "Lucas Jones", "author_id": 41981, "author_profile": "https://Stackoverflow.com/users/41981", "pm_score": 2, "selected": false, "text": "<pre><code>// haack, phil haack\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>/* hack, hack, hack, hack, hack hack, hack, hack\n * hackity hack, oh wonderful hacks\n * wonderful hacks, oh wonderful hack, hack, hack\n * hack hack hack... and spam \n */\n</code></pre>\n\n<p><strong>EDIT</strong>: Just found this in some of my code (the project wishes to remain anonymous):</p>\n\n<pre><code>// yikes, we need to:\n/*\n * o\n * -|- &lt; US CROSSING PLATFORM\n * |\\ \n ************************************************\n * | ^ PLATFORM |\n * | T |\n * | TROLL^ |\n */\n// right now:\n/*\n * o ./_ | \n * -|-[]\\ | (_'_) () (\\) | ) \\|/ (S) &lt; WALL\n * |\\ | ^ FRIENDLY MESSAGE FROM YOUR FRIENDS AT MICROSOFT\n * ***********************************************\n * | ^PLATFORM |\n * ^ SPRAY CAN (IN HAND)\n */\npublic static class DefaultFonts\n{\n public static string SansSerifPath\n {\n get { return @\"C:\\Windows\\Fonts\\arial.ttf\"; }\n }\n public static string SerifPath\n {\n get { return @\"C:\\Windows\\Fonts\\times.ttf\"; }\n }\n public static string MonospacePath\n {\n get { return @\"C:\\Windows\\Fonts\\courier.ttf\"; }\n }\n}\n</code></pre>\n\n<p>How I love puns.</p>\n" }, { "answer_id": 736035, "author": "Will Charczuk", "author_id": 73309, "author_profile": "https://Stackoverflow.com/users/73309", "pm_score": 1, "selected": false, "text": "<pre><code>map(TimeZoneId.Romance, \"Romance Standard Time\"); //LULZ.\n</code></pre>\n" }, { "answer_id": 736044, "author": "samoz", "author_id": 39036, "author_profile": "https://Stackoverflow.com/users/39036", "pm_score": 7, "selected": false, "text": "<pre><code>/*\nThis isn't the right way to deal with this, but today is my last day, Ron\njust spilled coffee on my desk, and I'm hungry, so this will have to do...\n*/\n\nreturn 12; // 12 is my lucky number\n</code></pre>\n" }, { "answer_id": 736049, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>// This interface defines method signatures&lt;br&gt;\ninterface IWhatever { ... }\n</code></pre>\n" }, { "answer_id": 736097, "author": "Steve Weet", "author_id": 68262, "author_profile": "https://Stackoverflow.com/users/68262", "pm_score": 5, "selected": false, "text": "<p>I once came up with what I thought was an elegant solution to a particularly sticky problem, in retrospect it was a bit of a mind-bender and made some heavy use of macro programmimg. Years later I found this comment from a maintenance programmer</p>\n\n<pre>\n/*\n Description: The Total Perspective Vortex derives its picture of the\n whole Universe on the principle of extrapolated matter\n analyses.\n\n To explain - since every piece of matter in the Universe\n is in some way affected by every other piece of matter in\n the Universe, it is in theory possible to extrapolate\n the whole of creation - every sun, every planet, their\n orbits, their composition and their economic and social\n history from, say, one small Macro.\n\n The man who invented the Total Perspective Vortex did so\n basically in order to annoy the IT department.\n\n Steve Weet - for that was his name - was a dreamer, a\n thinker, a speculative philosopher or, as some would have\n it, a slacker.\n\n And they would nag him incessantly about the utterly\n inordinate amount of time he spent staring out into space,\n or mulling over the mechanics of Chelsea FC, or doing\n spectrographic analyses of macros.\n\n \"Have some sense of proportion!\" they would say,\n sometimes as often as thirty-eight times in a single day.\n\n And so he built the Total Perspective Vortex - just to show\n them.\n\n And into one end he plugged the whole of reality as\n extrapolated from one macro, and into the other\n end he plugged the IT department: so that when he turned it\n on they saw in one instant the whole infinity of creation \n and theirselves in relation to it.\n\n To Steve Weet's horror, the shock completely annihilated '\n their brains; but to his satisfaction he realized that he\n had proved conclusively that if life is going to exist in a\n Universe of this size, then the one thing it cannot afford\n to have is a sense of proportion.\n\n*/\n</pre>\n" }, { "answer_id": 736113, "author": "Pool", "author_id": 2352432, "author_profile": "https://Stackoverflow.com/users/2352432", "pm_score": 3, "selected": false, "text": "<p>From a contractor in an application for a UK bank.</p>\n\n<pre><code>// i don't know how this works but it does so i'll leave it here anyway\n</code></pre>\n\n<p>He also added BNP (British very right wing party) as 1 of the dummy customers for testing... our immediate boss was of Asian ethnicity.</p>\n" }, { "answer_id": 736116, "author": "simon", "author_id": 14143, "author_profile": "https://Stackoverflow.com/users/14143", "pm_score": 5, "selected": false, "text": "<p>Ages ago I ran into this one:</p>\n\n<pre>\n/***************************************************************************/\n/* deep wizardry. do not touch. */\n/* */\n/* no seriously. XXXXXX I'm looking at you. If you screw with this again */\n/* I will kill you with my swingline stapler. */\n/* */\n/* ... */\n</pre>\n\n<p>And then went on to describe a particularly hairy algorithm.</p>\n" }, { "answer_id": 736167, "author": "mseery", "author_id": 39153, "author_profile": "https://Stackoverflow.com/users/39153", "pm_score": 4, "selected": false, "text": "<pre><code>// This is a walkaround for bug #7812\n</code></pre>\n\n<p>Written by one of our Chinese programmers, for whom English was not his first language.</p>\n\n<p>I really liked this one. I happen to think \"walkaround\" is almost a better term than \"workaround.\"</p>\n" }, { "answer_id": 740552, "author": "womp", "author_id": 63756, "author_profile": "https://Stackoverflow.com/users/63756", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;!-- Here it is --&gt;\n</code></pre>\n\n<p>No other comments anywhere. To this day I don't know what \"it\" was.</p>\n" }, { "answer_id": 740603, "author": "Ash", "author_id": 43192, "author_profile": "https://Stackoverflow.com/users/43192", "pm_score": 10, "selected": false, "text": "<p>This seems to stop morons from messing my code...</p>\n\n<pre><code>// Autogenerated, do not edit. All changes will be undone.\n</code></pre>\n" }, { "answer_id": 750386, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here's a few that I've put in my code at various times. Some aren't technically comments, but they're the same sort of concept.</p>\n\n<p>In a cross-platform project that needs some special code on one platform only:</p>\n\n<pre><code>//If defined, will include all the Windows-specific code.\n#define LOSE\n\n#ifdef LOSE\n#include &lt;windows.h&gt; //WIN32. Duh.\n#endif\n\n\n---------------------------------------------------\n\n\n//Stolen from other_project_name.cpp\n\n\n---------------------------------------------------\n\n\n/*\n * These comments have been lifted from propagate() and, though they no longer apply to the code, they may still be of value somewhere. Original tabbing and structural elements have been preserved.\n */\n //CAUTION: This has a major Bobby Tables risk. Even if a rulebuilder is used, there's still the risk of something getting corrupted in the database itself.\n //Reading text from anywhere and simply slotting it into an SQL statement is a major security risk. (With thanks to xkcd for the name \"Bobby Tables\".)\n //Requirement: Eliminate one Bobby Tables by changing [redacted] to be not just straight SQL.\n[lots more comments that are not as funny]\n/*\n * End of lifted comments. There should not be any executable code between these markers.\n */\n\n\n---------------------------------------------------\n\n\n /*\n Okay. It's unrecognized. Why is this a fatal error? It's actually very closely akin to the miswart of botched #includes being a fatal. When writing a C/C++\n program, you need your headers, and if you don't have one, chances are there'll be a million cascaded errors; so by making \"unable to open asdf.h\" a fatal,\n the compiler suppresses all those errors about undefined symbols and potentially misspelled type names.\n */\n\n\n---------------------------------------------------\n\n\n //If someone tries to import 'id' as a field name, it won't work. (We already have our own id.) But I think the probability is so low that I can afford to be funny.\n if (!stricmp(ptr,\"id\")) {warn(0,\"Import\",\"\",\"'id' is a reserved word and cannot be used as a column name. (Try 'ego' or 'superego'.)\"); return;}\n\n\n---------------------------------------------------\n\n\n//Need a place to squirrel away SQL statements somewhere\nchar *uts[1024]; //Unified Temporary Storage. (Why? Because I said so.)\nint nuts=0; //What is it that squirrels keep? Ha!\nint utsid[sizeof uts/sizeof *uts];\n\n\n---------------------------------------------------\n\n\n /**************************************\\\n * NOTE: This sets tilde.action. If a *\n * tilde header does not exist in the *\n * import file (not the _content_, if *\n * the entire column isn't there), it *\n * will duplicate down through all of *\n * the rows. This is fine for ~id, as *\n * that will never be changed; and if *\n * ~Quantity is blank, that throws an *\n * error in 'Add'. With ~Action, I am *\n * not so certain. I THINK it'd be OK *\n * to dup-down most of the time... if *\n * the user only ever imports Adds or *\n * Revises, but never both at once in *\n * a single import. So for safety, to *\n * allow a blank ~Action to revise OR *\n * add, I'm breaking the check out to *\n * a new variable - the curaction. In *\n * most cases, it won't be needed, so *\n * it's a waste; but it isn't like it *\n * has to copy the entire tilde.*, so *\n * it's only a small waste. So it can *\n * waste a register... big deal. OK ! *\n \\**************************************/\n\n\n---------------------------------------------------\n\n\n //if (!response) // we're going to crash\n //if (!items) // we're going to crash\n //TODO: Don't crash\n\n\n---------------------------------------------------\n</code></pre>\n\n<p>A lot of my comments contain obscure references to films or musicals, but they won't be nearly as funny if you don't know the show.</p>\n" }, { "answer_id": 750440, "author": "digijock", "author_id": 86345, "author_profile": "https://Stackoverflow.com/users/86345", "pm_score": 5, "selected": false, "text": "<pre><code>// (c) 2000 Applied Magic, Inc.\n// Unauthorized use punishable by torture, mutilation, and vivisection.\n</code></pre>\n\n<p>Ah, I always loved that one...</p>\n" }, { "answer_id": 750454, "author": "Ciryon", "author_id": 22012, "author_profile": "https://Stackoverflow.com/users/22012", "pm_score": 5, "selected": false, "text": "<pre><code>/**\n * If you don't understand this code, you should be flipping burgers instead.\n */\n</code></pre>\n" }, { "answer_id": 750707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I once worked on a project where I found this comment:</p>\n\n<pre><code>// Cabbage fart?\n</code></pre>\n\n<p>I have no idea what it was supposed to mean. Just glad my cube wasn't next to whoever wrote it.</p>\n" }, { "answer_id": 753350, "author": "Lily", "author_id": 85812, "author_profile": "https://Stackoverflow.com/users/85812", "pm_score": 3, "selected": false, "text": "<pre><code>public int hashCode() {\n//sucks, but what're you gonna do\n\n/*\nint hash = 7;\nfor (int i = 0; i &lt; array.length; i++)\n hash = hash * 31 * (null == array[i] ? 0 : array[i].hashCode());\nreturn hash;\n*/\n\nreturn 0;\n}\n</code></pre>\n" }, { "answer_id": 753413, "author": "Bob Cross", "author_id": 5812, "author_profile": "https://Stackoverflow.com/users/5812", "pm_score": 1, "selected": false, "text": "<pre><code>/* Look not upon this file lest your eyes be burnt from your head. */\n</code></pre>\n\n<p>What can I say? I was an intern and the summer was almost over. I was, shall we say, lacking in serious commitment to my documentation responsibilities.</p>\n" }, { "answer_id": 753637, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 6, "selected": false, "text": "<pre><code>// error codes\n#define ERROR_SUCESS 0\n#define ERROR_SUCCESS_IS_MISSPELLED 1\n</code></pre>\n\n<p>No other error codes defined.</p>\n" }, { "answer_id": 756621, "author": "madcolor", "author_id": 13954, "author_profile": "https://Stackoverflow.com/users/13954", "pm_score": 0, "selected": false, "text": "<p>I just found this in some legacy code.. </p>\n\n<pre><code>'CANNOT JUST QUIT!\n</code></pre>\n" }, { "answer_id": 764798, "author": "The Disintegrator", "author_id": 92462, "author_profile": "https://Stackoverflow.com/users/92462", "pm_score": 3, "selected": false, "text": "<pre><code>// This condition can't happen. Call the police or something.\n</code></pre>\n" }, { "answer_id": 765147, "author": "Chris Morley", "author_id": 80090, "author_profile": "https://Stackoverflow.com/users/80090", "pm_score": 5, "selected": false, "text": "<pre><code>//The following 1056 lines of code in this next method \n//is a line by line port from VB.NET to C#.\n//I ported this code but did not write the original code.\n//It remains to me a mystery as to what\n//the business logic is trying to accomplish here other than to serve as\n//some sort of a compensation shell game invented by a den of thieves.\n//Oh well, everyone wants this stuff to work the same as before.\n//I guess the devil you know is better than the devil you don't.\n</code></pre>\n" }, { "answer_id": 765149, "author": "mmmm", "author_id": 85592, "author_profile": "https://Stackoverflow.com/users/85592", "pm_score": 2, "selected": false, "text": "<p>Best comment I ever saw was</p>\n\n<pre><code>/* \n There is no accounting for pointers \n*/\n</code></pre>\n" }, { "answer_id": 765216, "author": "Stewart Robinson", "author_id": 47424, "author_profile": "https://Stackoverflow.com/users/47424", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;cftry&gt;\n...code...\n&lt;cfcatch&gt;\n &lt;!--- Gobble ---&gt;\n&lt;/cfcatch&gt;\n&lt;cftry&gt;\n</code></pre>\n\n<p>It's all over my companies code base. It's ColdFusion and it simply ignores errors.</p>\n" }, { "answer_id": 765375, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>On error resume next 'because nothing will ever go wrong!\n</code></pre>\n" }, { "answer_id": 765387, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>var arbitraryNumber = 10;\n//I don't know why. Just move on.\n</code></pre>\n" }, { "answer_id": 765908, "author": "leed25d", "author_id": 325686, "author_profile": "https://Stackoverflow.com/users/325686", "pm_score": 1, "selected": false, "text": "<p>I do not have a copy of the source but I have always remembered it:</p>\n\n<p>// If you cannot figure it out, you should not be reading this</p>\n" }, { "answer_id": 765935, "author": "penger", "author_id": 92831, "author_profile": "https://Stackoverflow.com/users/92831", "pm_score": 2, "selected": false, "text": "<pre><code>def leppard\n# what, i cant have my own convention?\nend\n</code></pre>\n" }, { "answer_id": 765942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>From the Linux Kernel source:</p>\n\n<p>linux/include/asm-i386/hw_irq.h:</p>\n\n<pre><code>/*\n * subtle. orig_eax is used by the signal code to distinct between\n * system calls and interrupted 'random user-space'. Thus we have\n * to put a negative value into orig_eax here. (the problem is that\n * both system calls and IRQs want to have small integer numbers in\n * orig_eax, and the syscall code has won the optimization conflict ;)\n *\n * Subtle as a pigs ear. VY\n */\n</code></pre>\n" }, { "answer_id": 765965, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>double t = 0.0; /* that's generally my opinion of the diner, too. */\n</code></pre>\n" }, { "answer_id": 765967, "author": "Casbah", "author_id": 91210, "author_profile": "https://Stackoverflow.com/users/91210", "pm_score": 2, "selected": false, "text": "<pre><code>private static final Logger lager = new Logger();\n</code></pre>\n" }, { "answer_id": 766018, "author": "ealf", "author_id": 85699, "author_profile": "https://Stackoverflow.com/users/85699", "pm_score": 7, "selected": false, "text": "<p>From the 2004 Windows leak,</p>\n\n<pre><code>__inline BOOL\nSearchOneDirectory(\n IN LPSTR Directory,\n IN LPSTR FileToFind,\n IN LPSTR SourceFullName,\n IN LPSTR SourceFilePart,\n OUT PBOOL FoundInTree\n )\n{\n //\n // This was way too slow. Just say we didn't find the file.\n //\n *FoundInTree = FALSE;\n return(TRUE);\n}\n</code></pre>\n" }, { "answer_id": 766037, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>/*\n* Wirzenius wrote this portably, Torvalds fucked it up :-)\n*/\n</code></pre>\n" }, { "answer_id": 766044, "author": "vobject", "author_id": 53911, "author_profile": "https://Stackoverflow.com/users/53911", "pm_score": 6, "selected": false, "text": "<p>I always liked what Paul DiLascia wrote in his file headers: </p>\n\n<pre><code>// If this code works, it was written by Paul DiLascia. If not, I don't know\n// who wrote it\n</code></pre>\n" }, { "answer_id": 766097, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>$dnstime = time() + 60 * 60 * 24 * 7 * 2; //how long are you staying for vacation on mars? twooo weeeeeks. give dees people air\n</code></pre>\n" }, { "answer_id": 766105, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>/**\n * Not even your mum thinks you're special if you call this method\n */ \nonlyYourMumThinksYoureSpecialIfYouCallThisMethod() {...}\n</code></pre>\n" }, { "answer_id": 766133, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>switch(value)\n{\n [...]\ndefault:\n ASSERT(**true**); // if this is triggered, something really bad is happening.\n}\n</code></pre>\n" }, { "answer_id": 766208, "author": "dustins", "author_id": 91731, "author_profile": "https://Stackoverflow.com/users/91731", "pm_score": 5, "selected": false, "text": "<pre><code>// .==. .==. \n// //`^\\\\ //^`\\\\ \n// // ^ ^\\(\\__/)/^ ^^\\\\ \n// //^ ^^ ^/6 6\\ ^^ ^ \\\\ \n// //^ ^^ ^/( .. )\\^ ^ ^ \\\\ \n// // ^^ ^/\\| v\"\"v |/\\^ ^ ^\\\\ \n// // ^^/\\/ / `~~` \\ \\/\\^ ^\\\\ \n// -----------------------------\n/// HERE BE DRAGONS\n</code></pre>\n\n<p>I don't have access to the original file because I don't work there anymore, but it was something very similar to this picture. It was at the top of a file that always caused troubles, that we had to fix but not allowed to take the time to really fix. (University politics)</p>\n" }, { "answer_id": 766217, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>//FIXME: fix this before the 1.0 release\n</code></pre>\n\n<p>they were on version 4</p>\n" }, { "answer_id": 766270, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>What do you think you're doing, Dave?\n</code></pre>\n" }, { "answer_id": 766324, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<pre><code>def format_ticket_content(text, recursive = true)\n if text.is_a?(TicketNote)\n note = text\n text = note.content\n else\n note = nil\n end\n\n ## Safety pig has arrived!\n text = h(text)\n ## _\n ## _._ _..._ .-', _.._(`))\n ## '-. ` ' /-._.-' ',/\n ## ) \\ '.\n ## / _ _ | \\\n ## | a a / |\n ## \\ .-. ; \n ## '-('' ).-' ,' ;\n ## '-; | .'\n ## \\ \\ /\n ## | 7 .__ _.-\\ \\\n ## | | | ``/ /` /\n ## /,_| | /,_/ /\n ## /,_/ '`-'\n ## \n</code></pre>\n" }, { "answer_id": 766328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>From the UNIX Version 6 Source Code, circa 1975:</p>\n\n<pre><code>/* You are not expected to understand this. */\n</code></pre>\n" }, { "answer_id": 766333, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>when :orientation\n## Avoid matching gay people with straight people - they hate it, they do, they really do.\nquery_parameter = \"(users.orientation = 'Bi' OR (users.orientation = 'Straight' AND users.gender IN ('#{user.opposite_genders.join('\\',\\'')}')) OR (users.orientation = 'Gay' AND users.gender IN ('#{user.same_genders.join('\\',\\'')}')))\"\n</code></pre>\n\n<p>From a dating website...</p>\n" }, { "answer_id": 766363, "author": "Lance Kidwell", "author_id": 29683, "author_profile": "https://Stackoverflow.com/users/29683", "pm_score": 9, "selected": false, "text": "<pre><code>// Replaces with spaces the braces in cases where braces in places cause stasis \n $str = str_replace(array(\"\\{\",\"\\}\"),\" \",$str);\n</code></pre>\n" }, { "answer_id": 766537, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>/* Here I sit, Joe broken hearted, came to do some sh*t, but only just started. */\n</code></pre>\n\n<p>In regards to some heavy regular expression input validation.</p>\n" }, { "answer_id": 766552, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I found this on Google Code Search</p>\n\n<pre><code> // Constructs a tuple with 2 elements (fucking idiot, use std::pair instead!)\n template &lt;typename T0,typename T1&gt;\n inline tuple &lt;T0,T1&gt; make_tuple (const T0&amp; t0,\n const T1&amp; t1) {\n tuple &lt;T0,T1&gt; t;\n t.get&lt;0&gt;() = t0;\n t.get&lt;1&gt;() = t1;\n return t;\n }\n</code></pre>\n" }, { "answer_id": 766553, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>My favorite comment of all time was used by a gay friend of mine. He liked to mark all of his TODO comments in VB.NET as</p>\n\n<pre><code>'TODO: Matt Damon\n</code></pre>\n\n<p>Sometimes additional information was provided but not usually.</p>\n" }, { "answer_id": 766554, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A compilation of my greatest hits:</p>\n\n<pre><code>// Thats the end of the While loop\n// Clean up last row. I really must program better than this.\n\n// Note: You can't immediately tell if the line below works.\n\n// Rounding - blech. It's assumed that all .5s are rounded up.\n\n// Sort out predictions first. Seems like the right place for a prediction, 'first'.\n\n// Let's interpret!\n</code></pre>\n" }, { "answer_id": 766602, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In some really crappy vb code (I know it is all crappy but) I found this a comment in an empty if control block that said something like:</p>\n\n<pre><code>If bFound Then\n 'I love it when I write kick ass code like this\nElse\n .\n .\n</code></pre>\n" }, { "answer_id": 766630, "author": "David Pope", "author_id": 92789, "author_profile": "https://Stackoverflow.com/users/92789", "pm_score": 3, "selected": false, "text": "<pre><code>#ifdef TRACE\n#undef TRACE /* All your trace are belong to us. */\n#endif\n#define TRACE ....\n</code></pre>\n" }, { "answer_id": 766631, "author": "Jason", "author_id": 90053, "author_profile": "https://Stackoverflow.com/users/90053", "pm_score": 3, "selected": false, "text": "<pre><code>// Fuck.\n</code></pre>\n\n<p>That, and...</p>\n\n<pre><code>// This code worked before, but my cat decided to take a trip across my keyboard...\n</code></pre>\n" }, { "answer_id": 766668, "author": "Lance Richardson", "author_id": 18310, "author_profile": "https://Stackoverflow.com/users/18310", "pm_score": 6, "selected": false, "text": "<p>Don't recall where I've seen these:</p>\n\n<pre><code>long time; /* know C */\n</code></pre>\n\n<p>and (in code to create some sort of UNIX daemon):</p>\n\n<pre><code>/* Be a real daemon: fork myself and kill my parent */\n</code></pre>\n" }, { "answer_id": 766696, "author": "joshk0", "author_id": 92631, "author_profile": "https://Stackoverflow.com/users/92631", "pm_score": 3, "selected": false, "text": "<p>This whole function is pretty great (from the Linux sunhme.c driver, for the network card nicknamed the Happy Meal by Sun. Because the card that came before that was the \"Big MAC\". Get it? Get it?)</p>\n\n<pre><code>static void happy_meal_tcvr_write(struct happy_meal *hp,\n void __iomem *tregs, int reg,\n unsigned short value)\n{\n int tries = TCVR_WRITE_TRIES;\n\n ASD((\"happy_meal_tcvr_write: reg=0x%02x value=%04x\\n\", reg, value));\n\n /* Welcome to Sun Microsystems, can I take your order please? */\n if (!(hp-&gt;happy_flags &amp; HFLAG_FENABLE)) {\n happy_meal_bb_write(hp, tregs, reg, value);\n return;\n }\n\n /* Would you like fries with that? */\n hme_write32(hp, tregs + TCVR_FRAME,\n (FRAME_WRITE | (hp-&gt;paddr &lt;&lt; 23) |\n ((reg &amp; 0xff) &lt;&lt; 18) | (value &amp; 0xffff)));\n while (!(hme_read32(hp, tregs + TCVR_FRAME) &amp; 0x10000) &amp;&amp; --tries)\n udelay(20);\n\n /* Anything else? */\n if (!tries)\n printk(KERN_ERR \"happy meal: Aieee, transceiver MIF write bolixed\\n\");\n\n /* Fifty-two cents is your change, have a nice day. */\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 766708, "author": "tlrobinson", "author_id": 113, "author_profile": "https://Stackoverflow.com/users/113", "pm_score": 3, "selected": false, "text": "<p><code>// This is confusing, I KNOW, so let me explain it to you.</code></p>\n" }, { "answer_id": 766741, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I don't have the code to share, but imagine this scenario. About a month or two after our Linux Sys Admin left for greener pastures, I had the pleasure of opening a shell script he'd written. I can't recall why I needed to edit it, but that's not what matters. What's important is that the script was about 40 lines long. I scrolled past the commenting (of which there were 37 lines) to reach the actual working code (3 lines). The code was great, but I was curious - why 37 lines of commenting? So, I scrolled to the top and proceeded to read. To my surprise, the commenting was a rap about what the three lines of code did and how to change it. The best part - it was a partial rip off of Nothing But A G Thing by Dr. Dre and Snoop D O DOUBLE G. Thanks Brian!</p>\n" }, { "answer_id": 766766, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>// For the sins I am about to commit, may James Gosling forgive me\n</code></pre>\n" }, { "answer_id": 766843, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>/* Jeez, this is an ugly mess */\n\n...comment from the X11R6 internals source code circa 1991.\n</code></pre>\n" }, { "answer_id": 766877, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<h2>A modification log I noticed in a legacy code</h2>\n\n<blockquote>\n <p>05/17/99 <strong>D JONES</strong> COMMENT OUT THE\n BLOODY AUZIES CODE (02/19/99)</p>\n \n <p>05/17/99 <strong>K ROBINSON</strong> BLOODY TEXAN\n CAN'T SPELL AUSSIE CORRECTLY (NO CODE\n CHANGE - JUST A COMMENT)</p>\n</blockquote>\n" }, { "answer_id": 766878, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>/*And now, getting all of that to look\n half decent in the retarded step\n brother\n of the browser family, Internet\n Fucking Explorer */</p>\n</blockquote>\n" }, { "answer_id": 766895, "author": "sandro", "author_id": 81192, "author_profile": "https://Stackoverflow.com/users/81192", "pm_score": 2, "selected": false, "text": "<pre><code>private int mousycounter = 0; //Not really a counter\n</code></pre>\n" }, { "answer_id": 766907, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://fxr.watson.org/fxr/source/pci/if_rl.c\" rel=\"nofollow noreferrer\">http://fxr.watson.org/fxr/source/pci/if_rl.c</a>\nis a source of good ones.</p>\n" }, { "answer_id": 766920, "author": "Tony Arnold", "author_id": 63580, "author_profile": "https://Stackoverflow.com/users/63580", "pm_score": 1, "selected": false, "text": "<p>Found in an old perl script that generates HTML:</p>\n\n<pre><code># I would be _very_ brain farting if I said this code didn't need reviewing.\n# It will make babies cry, and hair grow on your back, so please don't use it\n</code></pre>\n" }, { "answer_id": 766930, "author": "Draxillion", "author_id": 53034, "author_profile": "https://Stackoverflow.com/users/53034", "pm_score": 1, "selected": false, "text": "<p><strong>From /System/Library/Frameworks/AppKit.framework/Versions/C/Headers/NSTextView.h:</strong></p>\n\n<pre><code>- (void)smartInsertForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace beforeString:(NSString **)beforeString afterString:(NSString **)afterString;\n- (NSString *)smartInsertBeforeStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;\n- (NSString *)smartInsertAfterStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;\n\n/* Java note: The second and third methods are the primitives and are the \nmethods exposed in Java. The first method calls the other two. All \nObjective-C code calls the first method. In either Objective-C or Java any \noverriding should be done for the second and third methods, not the first \nmethod. This will all work out correctly with the exception of existing code \nthat overrides the first method. Existing subclasses that do this will not \nhave their implementations available to Java developers. Isn't Java wonderful? */\n</code></pre>\n" }, { "answer_id": 766933, "author": "Tola", "author_id": 74069, "author_profile": "https://Stackoverflow.com/users/74069", "pm_score": 2, "selected": false, "text": "<pre><code>//Please comment on your source code\n</code></pre>\n" }, { "answer_id": 766949, "author": "cliff.meyers", "author_id": 41754, "author_profile": "https://Stackoverflow.com/users/41754", "pm_score": 3, "selected": false, "text": "<pre><code>// TODO: not this\n</code></pre>\n\n<p>Written by a colleague above a query in desperate need of optimization. In his defense, we'd all been working 70-hour weeks for a few months at that point...</p>\n" }, { "answer_id": 767004, "author": "MRFerocius", "author_id": 72547, "author_profile": "https://Stackoverflow.com/users/72547", "pm_score": 2, "selected": false, "text": "<pre><code>//Do not continue reading if you dont want to die.\n</code></pre>\n\n<p>This one almost killed me.</p>\n" }, { "answer_id": 767282, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>/*\n FIXME: why the fuck did anyone ever think this kind of expensive iteration\n was a good idea?\n</code></pre>\n" }, { "answer_id": 767341, "author": "efdee", "author_id": 50145, "author_profile": "https://Stackoverflow.com/users/50145", "pm_score": 6, "selected": false, "text": "<pre><code>// if i ever see this again i'm going to start bringing guns to work\n</code></pre>\n" }, { "answer_id": 767642, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>//If only humans could leave things be.\n\n//Please do not edit this code, \n//if you do you wont go to jail, you wont go directly to jail, \n//you wont pass go, you wont collect 200 dollars\n</code></pre>\n" }, { "answer_id": 767750, "author": "DragonFax", "author_id": 92694, "author_profile": "https://Stackoverflow.com/users/92694", "pm_score": 2, "selected": false, "text": "<p>From the sendmail config file. After pages and pages of what looked like simply line noise. I found this gem.</p>\n\n<pre><code># insert this handy debugging line wherever you have problems\n#R$* $:$&gt;99$1\n</code></pre>\n" }, { "answer_id": 767937, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>int main(void)\n/* Program starts here */\n</code></pre>\n" }, { "answer_id": 768021, "author": "w4ymo", "author_id": 80229, "author_profile": "https://Stackoverflow.com/users/80229", "pm_score": 2, "selected": false, "text": "<p>I cried when I read this one on a project I was given to maintain.</p>\n\n<pre><code>//Write Code Here\n</code></pre>\n\n<p>I still cringe :)</p>\n" }, { "answer_id": 768023, "author": "Steve Pomeroy", "author_id": 90934, "author_profile": "https://Stackoverflow.com/users/90934", "pm_score": 4, "selected": false, "text": "<p>When I was taking a CS class in Highschool, we were being taught in a regular classroom - no computers. All our tests were done on paper that we handed in - one class per sheet of paper. Our teacher was teaching the class in C++ for the first time and would occasionally switch into Pascal mode on the chalkboard. This was awkward, as few of us had interest in learning Pascal.</p>\n\n<p>For larger than in class work, we would do them at home and hand in code + output printouts to be graded. After submitting a few code + output printouts, we collectively realized that the teacher wasn't actually reading the code - just the printouts. To test our theory, I put in a comment on the 3rd page of my code - right between some class declarations:</p>\n\n<pre><code>// If you are reading this, please place a checkmark here [ ]\n</code></pre>\n\n<p>Of course, I got it back with a big blue \"A\" on the front and no checkmark to be found.</p>\n" }, { "answer_id": 768096, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>First two lines of a file called monitoring.sh:</p>\n\n<pre><code>#!/usr/bin/perl\n# perl script disguised as a bash script\n</code></pre>\n" }, { "answer_id": 768097, "author": "JJacobsson", "author_id": 93150, "author_profile": "https://Stackoverflow.com/users/93150", "pm_score": 2, "selected": false, "text": "<pre><code>// The freshest corpse at the back please.\nm_DeadCharacters.push_back( std::make_pair(character, 0.0f) );\n// Get rid of the rotting surplus\nwhile( m_DeadCharacters.size() &gt; 3 )\n m_DeadCharacters.pop_front();\n</code></pre>\n" }, { "answer_id": 768172, "author": "TJ Eastmond", "author_id": 76754, "author_profile": "https://Stackoverflow.com/users/76754", "pm_score": 2, "selected": false, "text": "<pre><code>//ha, you thought I was lazy didnt ya?!\n</code></pre>\n" }, { "answer_id": 768386, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<pre><code>// this comment included for the benefit of anyone grepping for swearwords: shit.\n</code></pre>\n" }, { "answer_id": 768393, "author": "orj", "author_id": 20480, "author_profile": "https://Stackoverflow.com/users/20480", "pm_score": 4, "selected": false, "text": "<pre><code>// BEGIN HACK\n...\n// END HACK: I feel dirty.\n</code></pre>\n" }, { "answer_id": 768440, "author": "Jan-Willem Hoekman", "author_id": 93117, "author_profile": "https://Stackoverflow.com/users/93117", "pm_score": 3, "selected": false, "text": "<pre><code>/*\n* TODO: Remove this function\n\nfunction remove($customer_id)\n {\n $this-&gt;Customer-&gt;remove($id);\n }\n\n*/\n</code></pre>\n" }, { "answer_id": 768624, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>/*\n\n ____________________\n/ \\\n| Jean-Michel Bechet |\n| 2002-2009 |\n\\___ _______________/\n |/\n (o_\n //\\\n V_/_\n\n\n*/\n</code></pre>\n" }, { "answer_id": 768714, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>/*\n* After 36 hours, 2 holes in my wall and writing my code right beside the API\n* this still doesn't work.\n* function getMap():void takes in an event object @param: evt:mouseEvent\n* I will now retire for the day with a bottle of rum and 2 hours of crying\n*/\n</code></pre>\n" }, { "answer_id": 768732, "author": "Chris Walton", "author_id": 93236, "author_profile": "https://Stackoverflow.com/users/93236", "pm_score": 2, "selected": false, "text": "<p>From an absolutely lovely project I worked on up until recently (yes, I admit, some of those are mine, but I won't tell you which):</p>\n\n<pre><code>if(FAILED(hr))\n{\n char fuck[256];\n sprintf(fuck, \"GetBuffer() fucking fucked the fuck: %d\", hr);\n MessageBoxA(0, fuck, fuck, MB_OK | MB_ICONERROR);\n return;\n}\n\n\n// This is for Chris, since he gets all hot and horny over \"uint\" instead of \"unsigned int\"\n// ... or maybe he's just a lazy fuck. Who knows!?\nusing Ogre::uint; \n// movable texts, fucktory\nMovableObjectTextFactory* m_pMovableObjectTextFactory;\n\n\n// diarrhea... shitting CR from the string. complete run...\n</code></pre>\n\n<p>What he meant was that he's splitting the string by carriage returns to render separately.</p>\n\n<pre><code>// unlock shit (duh, this comment is useless)\npixelBuffer-&gt;unlock();\n\n\n// :HACK: remove me after demo is shipped\nOf course, it's still in there ;)\n\n\n// it's 4am and I can't think of a decent error message.\n// my lead just fell asleep at his desk, so I can't ask him.\n// [name] went home because he didn't want to get divorced.\n// and so it's little ol' me, sitting here, comin up with an\n// error message for something that should never ever happen.\nASSERT0(in_len == max_in, \"http://www.youtube.com/watch?v=oHg5SJYRHA0\"); \n\n\n// you want hungarian, you GET hungarian!\nfor(int fcknglpidxcntvrI = 0; fcknglpidxcntvrI &amp;lt; len; fcknglpidxcntvrI++)\n\n\nbool bKillSomethingAlive = false; // beating the dead horse instead\n</code></pre>\n\n<p>Of course, we also have a nice collection of interesting ways to say \"Hack\":</p>\n\n<pre><code>// HACKOMATIC \n// HMM... HACKXOR?\n// HACK'O'ROONY\n// AR; yeah I know it's HACKsoup\n// HACK SHOT! DOMINATING!\n// HACK'KIDO\n// HACKku. sepukku. harakiri. kamikaze. ninja.\n// HACK'o'NEIL\n// HACKsaw\n</code></pre>\n" }, { "answer_id": 769046, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>#define FUCK_VS6_CANT_COMPILE_TEMPLATES_WITHOUT_HANDHOLDING ((float*)0)\n\n... \n\nSetPinsFromChannels`&lt;float`&gt;(&amp;pinbuf, streambuf, &amp;inmapper, FUCK_VS6_CANT_COMPILE_TEMPLATES_WITHOUT_HANDHOLDING);\n</code></pre>\n" }, { "answer_id": 769077, "author": "Martin", "author_id": 15840, "author_profile": "https://Stackoverflow.com/users/15840", "pm_score": 5, "selected": false, "text": "<p>I posted this \"license statement\" in a WordPress template I released. I thought it was funny, anyhow.</p>\n\n<pre><code>/* The License:\nYou (from this point on referred to as The You) are hereby \ngranted by me (from this point on referred to as The Me) \nlicense to knock yourself silly with this template. \nBy using this template The You implicitly accepts this \nlicense and pledges solemnly to never claim creative \nownership of any graphics, code, concepts, eggs, bacon, ideas, \ncolors, shapes, hypertext-transfer protocols or other conduits \nof the visual splendor thatis this template. \n\nThe Me, in turn, pledges equally solemnly to be far too \nlazy to ever check up on you, so if you do manage to pull \nsome chicks The Me won't have a cow. \nHowever The Me would be sorely disappointed if The You \nwere to try and sell or distribute this work without \nacknowledging The Me. Seriously. The Me will come down on \nThe You like a large quantitiy of hard and heavy objects \nthat in large quantities may be harmful and possibly even \nlethal to The You; So don't even think about it, The Buster.\n*/\n</code></pre>\n" }, { "answer_id": 769083, "author": "Kuroki Kaze", "author_id": 79078, "author_profile": "https://Stackoverflow.com/users/79078", "pm_score": 4, "selected": false, "text": "<p><code>// This will save us ~0.5 sec for every user and please the machine spirits.</code></p>\n\n<p>Before very long procedure :)</p>\n" }, { "answer_id": 769201, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 3, "selected": false, "text": "<pre><code>// This part is more difficult\n</code></pre>\n\n<p>At the top of a method.</p>\n\n<p>That was about 5 lines long.</p>\n\n<p>And not very difficult.</p>\n\n<p>It was the only comment.</p>\n\n<p>In the entire application.</p>\n" }, { "answer_id": 769278, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>From the leaked Win2K source code:</p>\n\n<p><code>\n// The magnitude of this hack compares favorably with that of the national debt.\n</code></p>\n" }, { "answer_id": 769428, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 3, "selected": false, "text": "<p>My personal favorite is <a href=\"http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.2.0/twisted/python/components.py#L154\" rel=\"nofollow noreferrer\">documentation in limerick form</a>:</p>\n\n<pre><code> Subclassing made Zope and TR\n much harder to work with by far.\n So before you inherit,\n be sure to declare it\n Adapter, not PyObject*\n</code></pre>\n\n<p>This probably spoils the joke a bit, but since it's a bit obscure I'll explain:</p>\n\n<p>\"TR\" here refers to \"Twisted Reality\". Zope 2 and the original <code>twisted.reality</code> package made extensive and unfortunate use of multiple inheritance, which could make it difficult to understand what was going on when you saw a method call. Zope 3, Twisted itself, and <code>twisted.reality</code>'s successors (including the most recent, <a href=\"http://divmod.org/trac/wiki/DivmodImaginary\" rel=\"nofollow noreferrer\">Imaginary</a>) instead generally favor component composition.</p>\n" }, { "answer_id": 769443, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "<p>From: <a href=\"https://github.com/zepouet/Xee-xCode-4.5/blob/master/XeePhotoshopLoader.m#L108\" rel=\"nofollow noreferrer\">https://github.com/zepouet/Xee-xCode-4.5/blob/master/XeePhotoshopLoader.m#L108</a></p>\n\n<pre><code>// At this point, I'd like to take a moment to speak to you about the Adobe PSD\n// format. PSD is not a good format. PSD is not even a bad format. Calling it\n// such would be an insult to other bad formats, such as PCX or JPEG. No, PSD\n// is an abysmal format. Having worked on this code for several weeks now, my\n// hate for PSD has grown to a raging fire that burns with the fierce passion\n// of a million suns.\n//\n// If there are two different ways of doing something, PSD will do both, in\n// different places. It will then make up three more ways no sane human would\n// think of, and do those too. PSD makes inconsistency an art form. Why, for\n// instance, did it suddenly decide that *these* particular chunks should be\n// aligned to four bytes, and that this alignement should *not* be included in\n// the size? Other chunks in other places are either unaligned, or aligned with\n// the alignment included in the size. Here, though, it is not included. Either\n// one of these three behaviours would be fine. A sane format would pick one.\n// PSD, of course, uses all three, and more.\n//\n// Trying to get data out of a PSD file is like trying to find something in the\n// attic of your eccentric old uncle who died in a freak freshwater shark\n// attack on his 58th birthday. That last detail may not be important for the\n// purposes of the simile, but at this point I am spending a lot of time\n// imagining amusing fates for the people responsible for this Rube Goldberg of\n// a file format.\n//\n// Earlier, I tried to get a hold of the latest specs for the PSD file format.\n// To do this, I had to apply to them for permission to apply to them to have\n// them consider sending me this sacred tome. This would have involved faxing\n// them a copy of some document or other, probably signed in blood. I can only\n// imagine that they make this process so difficult because they are intensely\n// ashamed of having created this abomination. I was naturally not gullible\n// enough to go through with this procedure, but if I had done so, I would have\n// printed out every single page of the spec, and set them all on fire. Were it\n// within my power, I would gather every single copy of those specs, and launch\n// them on a spaceship directly into the sun.\n//\n// PSD is not my favourite file format.\n</code></pre>\n" }, { "answer_id": 769447, "author": "Nordes", "author_id": 80527, "author_profile": "https://Stackoverflow.com/users/80527", "pm_score": 3, "selected": false, "text": "<p>While debugging someone else JavaScript I've seen the following comment:</p>\n\n<pre><code>// Notice: I feel so dirty doing this, but it's the only way to make it cross browser.\n</code></pre>\n\n<p>But while reading one post of Scott Hanselmen I came across the following quote that goes very well with the comments I found inside the code:</p>\n\n<pre><code>Every line of code you write that you feel gross about will ultimately come back to haunt you. Therefore, avoid writing code that makes you feel dirty.\n</code></pre>\n\n<p>That's funny :)</p>\n" }, { "answer_id": 769468, "author": "thijs", "author_id": 26796, "author_profile": "https://Stackoverflow.com/users/26796", "pm_score": 3, "selected": false, "text": "<p>I recently saw this:</p>\n\n<blockquote>\n <p>// you just lost the game</p>\n</blockquote>\n\n<p>if you don't know what the game is:\n<a href=\"http://en.wikipedia.org/wiki/The_Game_(mind_game)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/The_Game_(mind_game)</a>\n(it's very silly, but silly in a interesting in a way)</p>\n" }, { "answer_id": 769590, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>/**\n * This run through all the guipublisherbuyRecord , the records those have\n * diff. is buytotal and prior to buy isRecommendedBillingClickedWarning flag\n * is set if priously RB ran and this time not.\n * \n * --What?\n * \n * @return\n * @throws AppException\n */\n</code></pre>\n" }, { "answer_id": 769805, "author": "Daniel Dickison", "author_id": 69749, "author_profile": "https://Stackoverflow.com/users/69749", "pm_score": 0, "selected": false, "text": "<p>Well-written Lisp is one of the easiest to read languages and I love it. But poorly written Lisp can be a nightmare so much worse than bad Java, etc.</p>\n\n<p>Here, we need to create a \"group file\" if there exist 3 variants of an original file named with the suffixes a, b and c. I had been trying to track down a strange bug where we were getting unnecessary group files...</p>\n\n<pre><code> (let ((varianta (format nil \"~aa\" problem))\n (variantb (format nil \"~ab\" problem))\n (variantc (format nil \"~ac\" problem)))\n ;;if the A and B variants exist, create a group file\n ;;(why not just check for a? I don't know, this just feels right)\n (when (and (probe-file varianta)\n (probe-file variantb))\n ...)))\n</code></pre>\n\n<p><em>Bug: 1, Gut: 0.</em></p>\n\n<p>Apparently it didn't occur to whoever wrote this that perhaps checking for all three variants would be a good idea. Of course, that was the bug I ended up tracking down a decade after this code was originally written (it predates the first SVN log).</p>\n" }, { "answer_id": 769869, "author": "Alexander Temerev", "author_id": 74275, "author_profile": "https://Stackoverflow.com/users/74275", "pm_score": 6, "selected": false, "text": "<p><code>// I put on my robe and wizard hat...</code></p>\n" }, { "answer_id": 769893, "author": "ben", "author_id": 4607, "author_profile": "https://Stackoverflow.com/users/4607", "pm_score": 1, "selected": false, "text": "<p>From <a href=\"http://www.madore.org/~david/computers/callcc.html\" rel=\"nofollow noreferrer\">http://www.madore.org/~david/computers/callcc.html</a>:</p>\n\n<pre><code>/* Yow! DEMONS are flying through my NOSE! */\n</code></pre>\n" }, { "answer_id": 769949, "author": "Macke", "author_id": 72312, "author_profile": "https://Stackoverflow.com/users/72312", "pm_score": 8, "selected": false, "text": "<pre><code>double penetration; // ouch\n</code></pre>\n" }, { "answer_id": 770022, "author": "proudgeekdad", "author_id": 702, "author_profile": "https://Stackoverflow.com/users/702", "pm_score": 7, "selected": false, "text": "<p>Our DBA found this in the middle of a 3000 line stored procedure written by a third party.</p>\n\n<pre><code>/* IF DOLPHINS ARE SO SMART, HOW COME THEY LIVE IN IGLOOS? */\n</code></pre>\n" }, { "answer_id": 770351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><code> // no comment </code></p>\n" }, { "answer_id": 770788, "author": "HeretoLearn", "author_id": 1984928, "author_profile": "https://Stackoverflow.com/users/1984928", "pm_score": 0, "selected": false, "text": "<p>Some old fortran code I saw:</p>\n\n<pre><code> integer *4 one,two,three;\n\nc asssign one to 100 before entering the loop\n one=100;\n</code></pre>\n" }, { "answer_id": 770924, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>// This should fix something that should never happen\n</code></pre>\n" }, { "answer_id": 771666, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>// repopulate, slight hax (or strong assumptions :P) below\n</code></pre>\n" }, { "answer_id": 771803, "author": "Craig McGuff", "author_id": 92759, "author_profile": "https://Stackoverflow.com/users/92759", "pm_score": 5, "selected": false, "text": "<p>An old boss of mine was always going on about how we had to use our own products internally i.e. \"Eat our own dog food...\"</p>\n\n<p>Many years later I found embedded in some source that a temporary coworker had done, every function he touched is tagged with:</p>\n\n<pre><code>/* NOT FIT FOR HUMAN CONSUMPTION */\n</code></pre>\n" }, { "answer_id": 771804, "author": "Sindri Traustason", "author_id": 1113, "author_profile": "https://Stackoverflow.com/users/1113", "pm_score": 3, "selected": false, "text": "<pre><code>/**\n * As Gregor Samsa awoke one morning from uneasy dreams he found himself\n * transformed in his bed into a gigantic insect. He was lying on his hard,\n * as it were armour plated, back, and if he lifted his head a little he\n * could see his big, brown belly divided into stiff, arched segments, on\n * top of which the bed quilt could hardly keep in position and was about\n * to slide off completely. His numerous legs, which were pitifully thin\n * compared to the rest of his bulk, waved helplessly before his eyes.\n * \"What has happened to me?\", he thought. It was no dream....\n */\nprotected static String DEFAULT_TRANSLET_NAME = \"GregorSamsa\";\n</code></pre>\n" }, { "answer_id": 771828, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>catch\n{ \n // you’re fucked\n // write out the file somewhere and start screaming “Connection down! Connection down!”\n}\n</code></pre>\n" }, { "answer_id": 771851, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>//this is a crap way to do this but I ran out of patience\n\nDelButton.click(); \n</code></pre>\n" }, { "answer_id": 771927, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>DataRow[] foundrows = FilterCalendarEntriesBecauseDotNETIsFuckedUp(tbtemp,CalDate);\n</code></pre>\n\n<p>Not a comment but an interesting function name</p>\n" }, { "answer_id": 771974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "<p><code>\n #define TRUE FALSE\n //Happy debugging suckers\n</code></p>\n" }, { "answer_id": 772078, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Many years ago I picked up the job to provide support to a project that ran real \ntime on a Z80 and was in assembly (is there any other way to do Z80??)\nAnyway, the original author was a Nigerian guy by the name of Moses. Maybe I should just \nstop there.\nAnyway, scattered throughout the code was this:</p>\n\n<pre><code>XRA A ;MT\n</code></pre>\n\n<p>Took me awhile to figure out what this was. The instruction itself does nothing more\nthan clear the accumulator. It's a slick way, although I'm not sure if there is an \nadvantage or not. you can just do:</p>\n\n<pre><code>LDA 0\n</code></pre>\n\n<p>But maybe</p>\n\n<pre><code>XRA A\n</code></pre>\n\n<p>saves a byte or something. What is does is exclusive or the accumulator with itself.\nThe result is, of course, always zero. </p>\n\n<p>Back to the MT - Empty (get it?)</p>\n\n<p>That's the best I've run across.</p>\n" }, { "answer_id": 772132, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>public function get state( /* of Palestine back */ ):Boolean\n</code></pre>\n" }, { "answer_id": 772430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>/**\n * Hexadecimal digit\n */\nprotected $version = -1;\n</code></pre>\n" }, { "answer_id": 772445, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>else\n{\n // rien, c'est parfait.\n}\n</code></pre>\n" }, { "answer_id": 776351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I found this</p>\n\n<pre><code>// This is a kind of magic...\n</code></pre>\n" }, { "answer_id": 776364, "author": "Juergen Gutsch", "author_id": 94229, "author_profile": "https://Stackoverflow.com/users/94229", "pm_score": 2, "selected": false, "text": "<p>I often found this one</p>\n\n<pre><code>// fix it!\n</code></pre>\n" }, { "answer_id": 776445, "author": "Juergen Gutsch", "author_id": 94229, "author_profile": "https://Stackoverflow.com/users/94229", "pm_score": 2, "selected": false, "text": "<pre><code>// TODO: Delete\n</code></pre>\n" }, { "answer_id": 776486, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 3, "selected": false, "text": "<pre><code>// *** drunk -- fix later ***\n</code></pre>\n\n<p><a href=\"http://www.google.com/codesearch/p?hl=en#BNbNcRE4c0E/~wvereeck/h838/Transceiver_ver10.java&amp;q=drunk%20fix%20later&amp;l=617\" rel=\"nofollow noreferrer\">direct link</a></p>\n\n<p>More fun with <a href=\"http://www.google.com/codesearch?hl=en&amp;lr=&amp;q=+drunk+fix+later&amp;sbtn=Search\" rel=\"nofollow noreferrer\">google code search</a>...</p>\n" }, { "answer_id": 776518, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I once got a call from the client years after working on a big budgeting system written in Paradox 3.5 -</p>\n\n<p>\"We've come across a bit of commenting that came up in a debug \" - </p>\n\n<pre><code>// This shouldn't happen, if it does, then the bits that automagically \n// worked when I wrote it have stopped working\n</code></pre>\n\n<p>... !</p>\n" }, { "answer_id": 776595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>// for 8 or 12 threads this does not affect much.\n// Strange are the situations if not understood properly.\n// Yoda strikes again\n</code></pre>\n\n<p>In a mutli-threading module! :)</p>\n" }, { "answer_id": 776698, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>// simply copied from another code\n</code></pre>\n" }, { "answer_id": 776715, "author": "ohnoes", "author_id": 53330, "author_profile": "https://Stackoverflow.com/users/53330", "pm_score": 4, "selected": false, "text": "<p>Some time ago I came across:</p>\n\n<pre><code>raise InvalidChild() # e.g. no legs\n</code></pre>\n\n<p><del>This is grotesque since \"<em>inwalida</em>\" in polish, means person with disability.</del> silly me :)</p>\n" }, { "answer_id": 776808, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 3, "selected": false, "text": "<p>I've seen this code in a function FULL of Explicit weird casts:</p>\n\n<pre><code>// Since today's CPUs are really fast, this is dedicated to those who said:\n// \" You can't use Moore's Law as an excuse to write bad software. \"\n</code></pre>\n\n<p>The code was horrendous :)</p>\n" }, { "answer_id": 776957, "author": "Ivo", "author_id": 76031, "author_profile": "https://Stackoverflow.com/users/76031", "pm_score": 2, "selected": false, "text": "<pre><code>'Major changes: Everthing! - Removed all Cornoud's code !\n</code></pre>\n" }, { "answer_id": 776959, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>public GetRandomNumber()\n{\n // Chosen by a fairly rolen dice\n return 12;\n}\n</code></pre>\n" }, { "answer_id": 776973, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Found over a complex code - </p>\n\n<p>//Jesus and this code have one thing in common: both were resurrected</p>\n" }, { "answer_id": 777244, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>// Holy moses! I've never seen anything so ridiculous in all my life. \n\n// Why do we need to query the AlarmIDs table twice.\n\n// Please tell me sir; I would really like to know. \n\n// This like all the other services have been mangled\n\n// to the point where they are nearly impossible to determine what kind of side affects might occur.\n\n// I am making the smallest changes I can to this code. \n\n// The GetAlarmId method gets the alarm id from the AlarmIDs table.\n\n// Novel idea, why didn't we query for the values be get below all in the same place.\n\n// This should be changed, but right now it will have to remain as is due to time constraints.\n\n// This like all other services really don't do anything fantastically hard, but after the original coders got\n\n// done with them; they are difficult to work with and have an acceptable comfort level.\n</code></pre>\n" }, { "answer_id": 777655, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>// if the resultMap size is less than or equal to zero\n// then the product is added\nif (resultMap.size() &lt;= 0)\n</code></pre>\n" }, { "answer_id": 777805, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>v.bpc := v.pc; -- Remember to jump back\nv.baccu := accu; -- Yo dawg, heard you like runing instructions\n -- so I took backup of your accu so you can run\n -- instructions while you run instructions.\nv.flags.i := false; -- No more interupts\n</code></pre>\n" }, { "answer_id": 777822, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Re eating one's own dogfood: We have the same term in our workplace (granted, only because I introduced it). My code is peppered with comments that say \"TODO\" and indicate something that ought to be done eventually, but a comment saying \"DOGFOOD\" (both keywords are always at the beginning of the comment, in all caps) means something that must be done before this program can be used even internally. It's a handy thing to search for, as the word \"dogfood\" is never going to appear in a quoted string - if it does, I can always just say \"dog-food\" or something - so even a case-insensitive search will come up with the right results.</p>\n\n<p>Regarding zeroing the accumulator: I've done exactly the same thing when programming an Intel 80x86 (I started on the 8086 and moved up from there into the modern Pentiums). XORing a register with itself is the quickest and tightest way to clear it. Using \"MOV AX,0\" requires three bytes (opcode and two bytes of literal 16-bit zero), whereas \"XOR AX,AX\" is only two; it's even more noticeable with the 386-and-higher extended registers, where \"MOV EAX,0\" requires five bytes (four bytes of 32-bit zero). My C/C++ compiler always zeroes registers this way, so I'd assume it's still the best way (although I haven't studied opcode timing tables in ages, and probably both XOR reg,reg and MOV reg,imm take one clock).</p>\n" }, { "answer_id": 778161, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>#!/usr/bin/sh\n# Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&amp;T\n# All Rights Reserved\n\n# THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&amp;T\n# The copyright notice above does not evidence any\n# actual or intended publication of such source code.\n\n#ident \"@(#)false.sh 1.6 93/01/11 SMI\" /* SVr4.0 1.3 */\nexit 255\n</code></pre>\n\n<p>Taken from SunOS 5.9 aka Solaris 9 (/usr/bin/false)</p>\n" }, { "answer_id": 778254, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 2, "selected": false, "text": "<pre><code>var something TBoolean; //Pickins\n</code></pre>\n" }, { "answer_id": 778275, "author": "Rohit", "author_id": 16071, "author_profile": "https://Stackoverflow.com/users/16071", "pm_score": 10, "selected": false, "text": "<pre><code>// somedev1 - 6/7/02 Adding temporary tracking of Login screen\n// somedev2 - 5/22/07 Temporary my ass\n</code></pre>\n" }, { "answer_id": 778286, "author": "bosky101", "author_id": 94486, "author_profile": "https://Stackoverflow.com/users/94486", "pm_score": 2, "selected": false, "text": "<pre><code>%%return_median\nhit_the_sweet_spot(Arg)-&gt;\n.\n.\n</code></pre>\n" }, { "answer_id": 778615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>First at the beginning of an Update to a huge object:</p>\n\n<pre><code>/*General note to all who tread in the &lt;ObjectName&gt;() code...\n * The SetOriginals() method from the BaseEntity class should be called (and only called) right after the Get() method\n * call as seen above. Calling the SetOriginals method elsewhere will result in bugs and all kinds of other nasty suprises.\n */\n</code></pre>\n\n<p>Then after some 200 lines of logic to update the object:</p>\n\n<pre><code>//Attempt to explain this confusing mess of code:\n//First time you save an actual absence this is what happens:\n//0. The first save saves to the &lt;TableName&gt; table (among other things). (Fig. A)\n//1. The &lt;CalculationMethod&gt; method is called next which inserts to the &lt;OtherTableName&gt; table. \n//(This is the table that keeps track of credits to the case.) (Fig. B)\n//2. So then you have to call &lt;UpdateCalculations&gt; to move the &lt;TableName&gt; records to the &lt;ThirdTableName&gt; table. (Fig. C)\n//3. Then you go back and run calculations since you have the debits table (&lt;ThirdTableName&gt;) populated. (Fig D.)\n//4. Then a final save to save the calculations back to the case. (Fig. E)\n//Yeah, I know what you're thinking: this sucks. 10/01/07 XXX\n</code></pre>\n\n<p>And the developer was right... This sucked HARD!</p>\n" }, { "answer_id": 778722, "author": "Samutz", "author_id": 94561, "author_profile": "https://Stackoverflow.com/users/94561", "pm_score": 6, "selected": false, "text": "<pre><code>/*\nafter hours of consulting the tome of google\ni have discovered that by the will of unknown forces\nwithout the below line, IE7 believes that 6px = 12px\n*/\nfont-size: 0px;\n</code></pre>\n" }, { "answer_id": 778895, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was doing a database in Access, very simple thing - at least it was supposed to be at the start or I would have done it in Delphi. The client wanted to be able to get the customer info out of the database but they would not enter enough information to reliably identify the customer. I told them to use the phone number as the key as each customer (the way they worked, not for everyone) would have a different number. After a few frantic calls from them, (It's not working we can't enter the customer) I discovered that they were too lazy to look up the phone numbers from their old system and were trying to enter all the numbers they did not know as \"n/a\". In trying to sort this out for them I ended up with a lot of checking loops in the code and had the comment beside one outcome \"This should never be reached if they do what they are supposed to do!!!!!!!!!\"</p>\n\n<p>They also asked me once \"How can we find the right customer even if we put in the wrong address?\" And all for peanuts.</p>\n" }, { "answer_id": 778975, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>//Dave chapelle reports errors.\nfunction reporterror() {\n davechapelle.trace(\"FUCK!\");\n}\n</code></pre>\n" }, { "answer_id": 778993, "author": "ProKiner", "author_id": 42949, "author_profile": "https://Stackoverflow.com/users/42949", "pm_score": 3, "selected": false, "text": "<pre>\n// TODO: Finish.\n</pre>\n" }, { "answer_id": 779128, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>// All this code is yours, except gedit()...attempt no modifications there.\n</code></pre>\n" }, { "answer_id": 779317, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Looking back at old code from classes is fun...</p>\n\n<pre><code> cardDeck.push_back(*(new card((rank)r, (suit)s))); // Push each card onto the deck\n // Temp. objects are overrated\n</code></pre>\n\n<p>While going through some things, it makes me wish I left more comments at 4 AM when I was hacking together random code...</p>\n" }, { "answer_id": 779681, "author": "STW", "author_id": 60724, "author_profile": "https://Stackoverflow.com/users/60724", "pm_score": 5, "selected": false, "text": "<p><em>To protect the guilty the values have been changed</em></p>\n\n<p>This one was left behind by a contractor who had been working on a chunk of code responsible for testing email logins. We were in disbelief so we tried it out and it was a valid login to his personal account; we double-checked the revision history and he had two check-ins that edited it: one to add the code, and the second to comment it out.</p>\n\n<p>We added the artwork and left the rest alone; another dev decided it would be fun to send him emails from his future self (ala The Office) and said it took nearly two full weeks of daily emails before the login stopped working.</p>\n\n<pre><code>' ROFL:ROFL:LOL:ROFL:ROFL\n' ______/|\\____\n' L / [] \\\n' LOL===_ ROFL \\_\n' L \\_______________]\n' I I\n' /---------------/\n\n'TODO: REMOVE MY INFO AND REPLACE WITH USER CREDENTIALS\n'Private TEST_LoginName As String = \"[email protected]\"\n'Private TEST_Password As String = \"Humsal892\"\n'Private TEST_Server As String = \"imap.secureserver.net\"\n</code></pre>\n\n<p>My favorite part isn't that he did it, or that he accidently left it in place for a check-in--but that when he came back across it he just commented it out rather than deleting it. We never would have looked at the original revision if we never knew it was there :-D</p>\n" }, { "answer_id": 779818, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code># There is a bug in the next line. $searchParameters != {} will always return true, because {} is creating\n# a new hash reference on the fly, and the inequality operater is comparing the memory location of it\n# to the memory location of $searchParameters, and they will always be different. \n# This means that the following code will always get executed as long as $nodes is defined.\n# I'm leaving it there because it has always been there, and although I'm sure it was originally meant to\n# mean %$searchParameters (essentially \"is this hash not empty\"), I'm afraid to change it.\nif ( $nodes &amp;&amp; $searchParameters != {} )\n{\n</code></pre>\n" }, { "answer_id": 779830, "author": "Srikar Doddi", "author_id": 1748769, "author_profile": "https://Stackoverflow.com/users/1748769", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>//The below code needs to be commented out.</p>\n</blockquote>\n" }, { "answer_id": 779856, "author": "SPWorley", "author_id": 74222, "author_profile": "https://Stackoverflow.com/users/74222", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://code.google.com/p/xee/source/browse/trunk/XeePhotoshopLoader.m?spec=svn28&amp;r=11#107\" rel=\"nofollow noreferrer\">This one</a>, from Xee, an image browser.</p>\n\n<pre><code> // At this point, I'd like to take a moment to speak to you about the Adobe PSD format.\n // PSD is not a good format. PSD is not even a bad format. Calling it such would be an\n // insult to other bad formats, such as PCX or JPEG. No, PSD is an abysmal format. Having\n // worked on this code for several weeks now, my hate for PSD has grown to a raging fire\n // that burns with the fierce passion of a million suns.\n // If there are two different ways of doing something, PSD will do both, in different\n // places. It will then make up three more ways no sane human would think of, and do those\n // too. PSD makes inconsistency an art form. Why, for instance, did it suddenly decide\n // that *these* particular chunks should be aligned to four bytes, and that this alignement\n // should *not* be included in the size? Other chunks in other places are either unaligned,\n // or aligned with the alignment included in the size. Here, though, it is not included.\n // Either one of these three behaviours would be fine. A sane format would pick one. PSD,\n // of course, uses all three, and more.\n // Trying to get data out of a PSD file is like trying to find something in the attic of\n // your eccentric old uncle who died in a freak freshwater shark attack on his 58th\n // birthday. That last detail may not be important for the purposes of the simile, but\n // at this point I am spending a lot of time imagining amusing fates for the people\n // responsible for this Rube Goldberg of a file format.\n // Earlier, I tried to get a hold of the latest specs for the PSD file format. To do this,\n // I had to apply to them for permission to apply to them to have them consider sending\n // me this sacred tome. This would have involved faxing them a copy of some document or\n // other, probably signed in blood. I can only imagine that they make this process so\n // difficult because they are intensely ashamed of having created this abomination. I\n // was naturally not gullible enough to go through with this procedure, but if I had done\n // so, I would have printed out every single page of the spec, and set them all on fire.\n // Were it within my power, I would gather every single copy of those specs, and launch\n // them on a spaceship directly into the sun.\n //\n // PSD is not my favourite file format.\n</code></pre>\n" }, { "answer_id": 779874, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In an early version of PeopleSoft Financials PeopleCode:</p>\n\n<pre><code>/* I don't know how you can ever get here so I'll have to fix it later */\n</code></pre>\n" }, { "answer_id": 779899, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><code># as you can see: I comment the code!</code></p>\n" }, { "answer_id": 779948, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>In the middle of a few thousand line JScript file after a completely arbitrary line...</p>\n\n<pre><code>// The world is a happy place.\n</code></pre>\n" }, { "answer_id": 779987, "author": "Paul", "author_id": 68968, "author_profile": "https://Stackoverflow.com/users/68968", "pm_score": 5, "selected": false, "text": "<pre><code>long time; /* just seems that way */\n</code></pre>\n" }, { "answer_id": 779993, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code> rescue\n # silently, we fail\n # many validations fade\n # like tear drops in rain\n end\n</code></pre>\n\n<p>This is just one of many...</p>\n" }, { "answer_id": 779999, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 3, "selected": false, "text": "<pre><code>\"\"\".........................:~+?7$$$ZZZZZZZ$$$7I+=:,............................\n........................~+7ZZZZZOZZOOZOZZOZOZOOZZZZZ7?~:........................\n......................,~7$ZZOOOOOZOZOZOZZOOZZOZOOOOOZ$$I,.......................\n...................,=I$OOZOZOZZOOOZZOZOOOOZOZZZOOZZZOZZOZI=:....................\n.................:?$ZZOOZZOZOZZOOOZZZOOZOZOZZZZZZZOZZOZOOOZ$I~..................\n................IZOOOZOOOZZZOZZZZOZZOZOOOOZOZZZOOZZZZOOZOZZZOZ7=................\n...............~ZZOZZOZOOZOOZOZOZZOZOZOZZZZZOZOZZOZOOZOZZOOOOZZ7................\n.............:IZOOZOZZZZOZOZZOZOOZOZOZOZZOZOOZOOOOZOZZZZZOZOZZOOI~..............\n...........,+$ZOOZZOZOZOZOZOZZOZOZOOZZOZZOZZOZOOOOZOZZOZZOOZOOOOO$?:............\n..........:IZZOOOZOZZZZOOZOOZOZOZZOZOZZZZOZOOZOZZOZOZOZOOOOOOOZZZOZ7~...........\n..........+$OOZZZOZZOOZOOZZZZOZZOZOZZOZOOOZOZOZZOZOZOZOOOOOZ$$77I77$+:..........\n........,?$OOZZZZZZZOZOOOZOZZOZZZOOZOZOOOOZOZZZOOZOOZOOO7?~:,.......,...........\n........+ZOOZZZZZOZOOZOOZZZZOZZOOOZZZOZOZOOZZOZOZZZOOO$?........................\n........$ZOZZZOZZZZOZOOZZZOZOZZOOOOOOOOOOOZOZOZZOZOO$?,.........................\n.......:ZOOZOZOZZOOZZOZOZOZOOOZOOOOOOOOOOOOOOOZOZOOZI:..........................\n.......+OOOZOOZOZOZOZZZOOZOOZOOO$I+=~:::~+I$OOOOOOZ?:........,:=,...............\n......:7ZOOZOZZOOOZOZOZOOZOOZ$I=............:?$OOZ7:.......:IZOOZ?,.............\n......=$OZOZOOZOOOOOZOZZOOZ7=,................:?O$+.......~7OOOOOZ+,............\n.....,?$OOOOOZZZZOOOOOOZOZ?,....................ZZ=.......=$OOZOOZ+,............\n.....:IZOZZ$777I7$ZOOOOOZ7~.....................$Z=.......~7OOOOO7=.............\n.....:+?~:,.......,~IZOO7~........~+II?=........?$?,.......:I$ZZ?:..............\n.....................+ZO=,......:IOOOOOZ:.......=7$~............................\n.....................:IO~.......=OOZOZOO=,......~7O7~...........................\n...........:~:.......:IO~.......+OOOOZOO=.......~78Z?,.................,:.......\n..........:IZ7~......+ZO~.......:7OOOOO$,.......+$OOZ7=,.............:?$=.......\n...........,,.....,=7ZOO+,.......,=II?=:........7OOOOOOZ=:,.....,:=I$ZOO=.......\n....................,:+$7=.....................~OOOZZZOOOZZ$$7$$ZOOOOOOZ=.......\n......................:?Z?,...................:?OZOOZOOZOOOOOOOOOOZOZOZO=.......\n............,::,.......,OO7:................,+$OOZOZOOZOZZOZOZZOOZOZOZOO=.......\n...........~$8OI........$OOZI~,.........,:=IZOOZOZOZOZOOOZOZOZOOOZZZOZOO=.......\n...........:??=:.......:OOOOOZZ7+=~~==+?$ZOOOOZOOOZOZOZOOZOZOZZOZZOZOZZO=.......\n............::,.......,+OOZOOOOO$7777$$ZOOOOOZOZZZZOZOZZZOOZOZZOOOZOOZOO=.......\n.....................=7OOZOOZOOZOOOOOOOOOZZZOZOZZOZOZOZOOOZOZOZZOZOOZOOO=.......\n................,:=I$OOOZZOOOZOOOOOZOZOZZZZZOOZZZOZOZZZOOZOOZOZOZOZOZOOZ=.......\n...........:~+?7ZOOOOOOZZZOZOOZOZOOZOZOZZOZZOZOZZZZOZOZZOZOZOZZOZOOZOOOZ=.......\n........$$ZOOOOOOOOZOZOZZZZOZOZOOOZZZOZZZOZOOZOZZZZZZZZOOOZOOZZZOZOOZOOZ=.......\n.......~OOZOOZZOOZZZZZZOOZOZOZOZZOOZOOZZZOZZOZOZZOZZZOZOOOOOZOZOZOOZOOOZ=.......\n.......~OOZOOZZOZZOZOZZOZZOZOOZOZOOZOZOZZOZOOZOZZOZOZOZOZOOZOZOOOZOOZOZO=.......\n.......~OOZZZOZOOOZOZOZZOZOZOZOZOOZOOZOOOOZOZOOZOOOZOOOZOZZOZOZOOZZOOOOZ=.......\n.......~OOZZOZOZZZOOZOOZOZOZOZZOZZZZOZZZZOZOZZOOOOZ$ZZZZZZOZZZOZZOZOZZZO=.......\n.......~OOZZOO$??$OOZOOZZOOZOZOZ+~IZOOOZOZOOZZOOZI==IZOZZOZOOZOZZOZI~=7O=.......\n.......~OOZO$I:..~IZZZOZOZOZOZ$+...=7ZOOZOOZZOZZ=,..,=$ZZOZZZZZOZI~...,?=.......\n.......~OOOZI:....:IZOOOZZOOO$+:....~7ZOZOZOZOZ$,....,=$OOZOOOZOI~.....:~.......\n.......~OZI~........~IZZZOZ$?:........=IOOZZZ$+,.......,$ZOOOZZ7................\n.......=7~............~IOZI:............7ZO$+:..........,=7ZZ7=,................\n.......,,...............=~...............~=:..............,~=...................\n GlassGiant.com\"\"\" \nprint \"Hello World!\"\n</code></pre>\n" }, { "answer_id": 780060, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>//Maybe you should make anyone knows your code's purpose. \n</code></pre>\n" }, { "answer_id": 780103, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>My favorite is from the late, great Paul DiLascia:</p>\n\n<p><code>// Author: If this code works, it was written by Paul DiLascia. If not then I don't know who wrote it.</code></p>\n" }, { "answer_id": 780234, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>/**\n * Happy Javadoc haiku:\n *\n * Without Javadoc\n * Builds break in Maven site stage\n * This fixes the build.\n */\n</code></pre>\n" }, { "answer_id": 780267, "author": "Brad Tutterow", "author_id": 308, "author_profile": "https://Stackoverflow.com/users/308", "pm_score": 4, "selected": false, "text": "<p>Using semi-colons in VB.NET</p>\n\n<pre><code>TextBox2.Visible = True';\nFor Each row In data.Tables(0).Rows\n If row(\"Customers.Id\").ToString &lt;&gt; customerId Then\n customerId = row(\"Customers.ID\").ToString';\n name = \"Customer Name: \" &amp; row(\"Name\").ToString &amp; CrLf';\n address = \"Address: \" &amp; row(\"Address\").ToString &amp; CrLf &amp; CrLf';\n TextBox2.Text += name &amp; address ';s\n End If';\nNext';\n</code></pre>\n" }, { "answer_id": 780286, "author": "Niran", "author_id": 169495, "author_profile": "https://Stackoverflow.com/users/169495", "pm_score": 4, "selected": false, "text": "<pre><code>//todo: never to be implemented\n</code></pre>\n" }, { "answer_id": 780312, "author": "David", "author_id": 89682, "author_profile": "https://Stackoverflow.com/users/89682", "pm_score": 2, "selected": false, "text": "<p>Our team, just tonight, released a new version of a CSS file that removed the comments from a file which was structured like this:</p>\n\n<pre><code>@charset \"UTF-8\";\n/* Who knew comments here could COMPLETELY ruin our page in Safari? */\nbody {\n /* Really important stuff here */\n /* Of course, comment or not, this will all get ignored by Safari because \n its the first rule after the comments which break everything.\n see http://www.w3.org/International/questions/qa-css-charset for the exact details!\n */\n}\n</code></pre>\n\n<p>The funny thing is on the web you'll find people's solutions are to just enter in a bogus element as the first rule below the charset statement to get ignored and proceed as normal...</p>\n\n<p>Food for thought: Where does one put the comment not to comment?</p>\n\n<p>Sidenote: I know this shouldn't be needed due to headers, meta rules etc. Unfortunately we need it as a catch all :(</p>\n" }, { "answer_id": 780361, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "<pre><code> #Christmas tree initializer \n toConnect = [] \n toRead = [ ] \n toWrite = [ ] \n primes = [ ] \n responses = {} \n remaining = {} \n</code></pre>\n" }, { "answer_id": 780566, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 4, "selected": false, "text": "<pre><code>// some sport psychology\nif (!focused)\n Focus();\n</code></pre>\n" }, { "answer_id": 780804, "author": "Iain", "author_id": 5993, "author_profile": "https://Stackoverflow.com/users/5993", "pm_score": 5, "selected": false, "text": "<p>Stating the obvious?</p>\n\n<pre><code>/** Logger */\nprivate Logger logger = Logger.getLogger();\n</code></pre>\n" }, { "answer_id": 781187, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>// now that's compact!\nlist-&gt;insert(list-&gt;end(),**pitch)-&gt;IdxOfSample=(pitch-&gt;pos-Offset)*SamplingRate;\n</code></pre>\n" }, { "answer_id": 781356, "author": "rawpower", "author_id": 25735, "author_profile": "https://Stackoverflow.com/users/25735", "pm_score": 5, "selected": false, "text": "<p>In a GIGANTIC 800 line 'switch' statement, somewhere in the middle:</p>\n\n<pre><code>// Joe is sorry\n</code></pre>\n\n<p>A few hundred lines later...</p>\n\n<pre><code>// Harry is sorry too\n</code></pre>\n" }, { "answer_id": 781433, "author": "Florjon", "author_id": 86653, "author_profile": "https://Stackoverflow.com/users/86653", "pm_score": 1, "selected": false, "text": "<pre><code>[vrk:Cloud ID=\"cTags\" runat=\"server\" DataTextField=\"Tag\" DataWeightField=\"Total\"\n Width=\"100%\" DataHrefField=\"Tag\" DataHrefFormatString=\"~/tags.aspx?tag={0}\"]\n[/vrk:Cloud]\n\n[!--if anybody would like to change the control's color contact with FLORJON--]\n</code></pre>\n" }, { "answer_id": 781860, "author": "Jason Orendorff", "author_id": 94977, "author_profile": "https://Stackoverflow.com/users/94977", "pm_score": 2, "selected": false, "text": "<p>From Python/ceval.c:</p>\n\n<pre><code>/* This is gonna seem *real weird*, but if you put some other code between\n PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust\n the test in the if statements in Misc/gdbinit (pystack and pystackv). */\n</code></pre>\n" }, { "answer_id": 782168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>'Mind boggling, gibberish version of a SQL statement, but it work's, so dont touch it\n</code></pre>\n" }, { "answer_id": 782202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>//BELOW IS THE REAL CODE...JABRONI\n //\n // Yeah, but can you play the outtro to Bark At The Moon?\n //\n\n //|--------------------------------------------------|------------------------------------------------|\n //|--------------------------------------------------|------------------------------------------------|\n //|--17^16-16-16-17^16-17^16-16-16-17^16-17^16----16-|-19^16----16-19^16-19^16---16-19^16-19^16----17-|\n //|--------------------------------------------19----|-------17----------------17---------------17----|\n //|--------------------------------------------------|----------------------------------------------\n</code></pre>\n" }, { "answer_id": 782502, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 5, "selected": false, "text": "<p>This comment was in a unit containing interfaces which were used to bind communication between the main application and various 3rd party drivers.</p>\n\n<pre><code>//**************************************\n// Dear code maintainer:\n//\n// This source contains COM interfaces, not to be confused with interfaces \n// of any other sort, please do not just willy-nilly add additional methods \n// to these interfaces as they are truely immutable, unlike the interfaces \n// that other software vendors like Microsoft maintain. IF you need to add \n// new functionality, then go thru the trouble of creating a NEW interface \n// and implement this functionality on only the objects you need. \n//\n// While the money is good for fixing all of the problems caused by not \n// following the rules, I would rather work on things which actually have\n// an impact on the future of the product rather than curse and yell \n// obsenities at the screen because someone didn't bother to understand the\n// true meaning of IMMUTABLE. \n//**************************************\n</code></pre>\n" }, { "answer_id": 782521, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p><code>/* This is a replica of a horrible hack - many moons ago, the legacy PortfolioServer was modified to return cash trades in an \"optionTrade\" block, because the client side developer was too lazy to get their XPaths right. Their laziness echoes through the ages, and means we need a similar hack here...*/</code></p>\n</blockquote>\n" }, { "answer_id": 782524, "author": "DJ.", "author_id": 83214, "author_profile": "https://Stackoverflow.com/users/83214", "pm_score": 6, "selected": false, "text": "<pre><code>//uncomment the following line if the program manager changes her mind again this week\n</code></pre>\n" }, { "answer_id": 782529, "author": "Steel Plume", "author_id": 85178, "author_profile": "https://Stackoverflow.com/users/85178", "pm_score": 2, "selected": false, "text": "<pre><code>public static final void attachListener(Object listener) {\n\n/* ======================= */\n\n// This does nothing, continue searching\n\n/* ======================= */\n\n...\n</code></pre>\n\n<p>painful with listeners!</p>\n" }, { "answer_id": 782806, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Back in the early eighties, I came across this in assembler (quoting from dim memory): </p>\n\n<pre><code>I don't understand how the following bit works, but it worked in the program I stole it from.\n</code></pre>\n" }, { "answer_id": 783107, "author": "Paul Redman", "author_id": 95136, "author_profile": "https://Stackoverflow.com/users/95136", "pm_score": 3, "selected": false, "text": "<p>Control + A, Rewrite</p>\n\n<p>This was a comment added to source control on a previous project as the check in comment.</p>\n" }, { "answer_id": 783174, "author": "Christopher Klein", "author_id": 17632, "author_profile": "https://Stackoverflow.com/users/17632", "pm_score": 1, "selected": false, "text": "<p>I really almost like the oh_my_gawd tag better than the comment...</p>\n\n<pre>\n /*\n * IOC3 is fucked fucked beyond believe ... Don't even give the\n * generic PCI code a chance to look at it for real ...\n */\n if (cf == (PCI_VENDOR_ID_SGI | (PCI_DEVICE_ID_SGI_IOC3 b_type0_cfg_dev[slot].f[fn].c[where ^ (4 - size)];\n\n if (size == 1)\n res = get_dbe(*value, (u8 *) addr);\n else if (size == 2)\n res = get_dbe(*value, (u16 *) addr);\n else\n res = get_dbe(*value, (u32 *) addr);\n\n return res ? PCIBIOS_DEVICE_NOT_FOUND : PCIBIOS_SUCCESSFUL;\n\noh_my_gawd:\n\n /*\n * IOC3 is fucked fucked beyond believe ... Don't even give the\n * generic PCI code a chance to look at the wrong register.\n */\n if ((where >= 0x14 && where = 0x48)) {\n *value = 0;\n return PCIBIOS_SUCCESSFUL;\n }\n</pre>\n" }, { "answer_id": 783220, "author": "savannah", "author_id": 94317, "author_profile": "https://Stackoverflow.com/users/94317", "pm_score": 3, "selected": false, "text": "<pre><code>//Time log says you've been here for 15 hours GO HOME, your code is hobo\n</code></pre>\n" }, { "answer_id": 783289, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>/* Only break the connection if it actually exists. It is important to\n * check the timeslot saved in the SOURCE of the disconnect message. */\n</code></pre>\n\n<p>I wrote this comment, and now I can't remember WHY it's important...</p>\n" }, { "answer_id": 783368, "author": "Jim Evans", "author_id": 87627, "author_profile": "https://Stackoverflow.com/users/87627", "pm_score": 2, "selected": false, "text": "<pre><code>'I hate nested regions and will delete them along with any code found in them.\n</code></pre>\n" }, { "answer_id": 783793, "author": "stdave", "author_id": 71091, "author_profile": "https://Stackoverflow.com/users/71091", "pm_score": 3, "selected": false, "text": "<p>This was for a custom DHCP server that we used in a university's dorms to put computers into 'clean' or 'dirty' IP address pools depending on whether or not they'd registered/installed patches and Antivirus:</p>\n\n<pre><code>public boolean getDirty (String MAC) // not as fun as it sounds\n</code></pre>\n" }, { "answer_id": 783935, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>Tweet tweet = (Tweet) tweets.get(i); // Poetic.\n</code></pre>\n" }, { "answer_id": 784001, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The below code was seen in a mock tutorial for Python.</p>\n\n<pre><code># This is my rifle.\ndef rifle(type='hunting'):\n print('This is my (%s) rifle.' % type)\n\n# This is my gun.\ndef gun(type='hand'):\n print('This is my (%s) gun.' % type)\n\n# This is for fighting.\ndef fighting(type='illegal'):\n print('This is for (%s) fighting.' % type)\n\n# This is for fun.\ndef fun(type='gaming'):\n print('This is for (%s) fun.' % type)</code></pre>\n\n<p>The author must have been a fan of Family Guy. ^_^</p>\n" }, { "answer_id": 784055, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>// TODO: what the hell is this all about?\n</code></pre>\n\n<p>And then some commented out code.</p>\n\n<p>This was found in our code in work earlier today. I'm not sure if I should laugh or cry...</p>\n" }, { "answer_id": 784725, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>We had a group project to create a Connect 4 AI using Min-Max trees. In our move-scoring function, we had it calculate a score for the board, and above that block of code there was this comment:</p>\n\n<pre><code>// This is kind of almost useless\n</code></pre>\n\n<p>But it gets better. Our instructor gave us some sample code from a crude AI he had made, and he left a great comment:</p>\n\n<pre><code>// We also add/subtract some points based on what's going on, on the bottom\n// row. (I think this is retarded, but apparently when I coded this up \n// back in 1999 I didn't.)\n</code></pre>\n" }, { "answer_id": 784955, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 2, "selected": false, "text": "<p>I just finished a logging framework (that uses Trace, why nothing like this exists I don't know). I made a convenience base class that inherits from TraceListener. It overrides all of the TraceListener methods and routes them into one method - so that is a lot of doc commenting:</p>\n\n<pre><code>// TODO: Need some codemonkey to doc comment this class.\n</code></pre>\n" }, { "answer_id": 785220, "author": "bretik", "author_id": 42074, "author_profile": "https://Stackoverflow.com/users/42074", "pm_score": 3, "selected": false, "text": "<p>Recompiling FreeTextBox3 for the first time in our application because we need IE8 support... And look what I've found:</p>\n\n<pre><code>// IE7 update. this is still bad code, but IE8 is probably a long way off :)\n</code></pre>\n" }, { "answer_id": 785272, "author": "Tim Post", "author_id": 50049, "author_profile": "https://Stackoverflow.com/users/50049", "pm_score": 4, "selected": false, "text": "<p>Well, here's one I <a href=\"http://echoreply.us/hg/nexgent.hg/index.cgi/rev/4b0b3e693f3b\" rel=\"nofollow noreferrer\">just committed</a>:</p>\n\n<pre><code>/* Every time I re-visit this function, I feel like\n * I need to take a shower.\n *\n * Don't get too used to this function, its days are\n * numbered.\n */\n</code></pre>\n\n<p>Someone could start something like greatcodecomments.com and make some cash. That person, however, is not me.</p>\n" }, { "answer_id": 785328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>// need a coffee to fix this.\n</code></pre>\n" }, { "answer_id": 785345, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 3, "selected": false, "text": "<p>In a bunch of poorly cut &amp; pasted source code for a content management web app:</p>\n\n<pre><code>// load image 1 - JPEG 240x320\nimg = f1.getImage();\nif (check(img))\n{\n load(img, Constants.JPEG_240x320);\n}\n\n// load image 2 - JPEG 128x128\nimg = f2.getImage();\nif (check(img))\n{\n load(img, Constants.JPEG_128x128);\n}\n\n...\n\n// load image 13 - GIF 256x256\nimg = f13.getImage();\nif (check(img))\n{\n load(img, Constants.GIF256x256);\n}\n\n// loaded all of the f**king images\n</code></pre>\n\n<p>note: roughly translated from italian :-)</p>\n" }, { "answer_id": 786255, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<pre><code>//I'm sorry, but our princess is in another castle.\n</code></pre>\n" }, { "answer_id": 786495, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>//too much log will kill you\n</code></pre>\n\n<p>This comment I wrote it myself, when lowering the priority of some logs which otherwise would write hundreds of MB of crap and seriously crippled an application performance. </p>\n" }, { "answer_id": 786818, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Found this in makefile</p>\n\n<pre><code># ===== Never edit below this line. Ever. Or I'll kick your ass. ====\n</code></pre>\n" }, { "answer_id": 787238, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<pre><code>//\n//3.4 JeK My manager promised me a lap dance if I can fix this release\n//3.5 JeK Still waiting for that dance from my manager\n//3.6 JeK My manager got changed, the new manager is hairy, dont want the dance anymore\n//3.7 Jek Got that dance, yuck!\n//\n</code></pre>\n" }, { "answer_id": 787243, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>BEGIN.\n// Here might be dragons\n.\n.\n IF...\n // Beware of the Jabberwocky\n .//user the force, luke\n .\n .\n ENDIF.\n.\nEND.\n</code></pre>\n" }, { "answer_id": 787301, "author": "splicer", "author_id": 86436, "author_profile": "https://Stackoverflow.com/users/86436", "pm_score": 6, "selected": false, "text": "<p>From a battery monitor module in an embedded system:</p>\n\n<pre><code>// batmon.c drives the rastamobile\n</code></pre>\n" }, { "answer_id": 788086, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Technically not a comment, but from coding on something at 2 am or so:</p>\n\n<pre><code>consent = False\n</code></pre>\n\n<p>... that variable is never used again EVER and appears in the beginning of a listen loop for a socket.</p>\n" }, { "answer_id": 788223, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 2, "selected": false, "text": "<pre><code>// The following array may contain either TexturedObjects or ColoredObjects.\n// I know, it sucks.\n</code></pre>\n" }, { "answer_id": 788577, "author": "MaoTseTongue", "author_id": 87375, "author_profile": "https://Stackoverflow.com/users/87375", "pm_score": 4, "selected": false, "text": "<pre><code>// Singleton object. Leave $me alone.\nprivate static $me;\n</code></pre>\n" }, { "answer_id": 788609, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>my favorite was something like this</p>\n\n<pre>\n # commented out\n ...\n ### end of the formerly uncommented #2001-02-22 John Doe\n</pre>\n" }, { "answer_id": 789811, "author": "Neil Kodner", "author_id": 92287, "author_profile": "https://Stackoverflow.com/users/92287", "pm_score": 8, "selected": false, "text": "<pre><code>// no comments for you\n// it was hard to write\n// so it should be hard to read\n</code></pre>\n" }, { "answer_id": 792783, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>// woot, global var. I havent done this for a long time.\n</code></pre>\n" }, { "answer_id": 792901, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>// *** AAAAAHAHAHAH!! What is this??\n</code></pre>\n" }, { "answer_id": 792982, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre>\n<code>\n$you = live(\"free\") or die(\"hard\");\n</code>\n</pre>\n" }, { "answer_id": 794252, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code># dont question, i just felt like throwing some globals in\n# this is actually quite pointless as youll soon see\n</code></pre>\n\n<p>later in the code</p>\n\n<pre><code>#draw the circles (complicated)...dont question\n</code></pre>\n\n<p>even later...</p>\n\n<pre><code># complicated process of drawing the circles in a\n# somewhat symmetrical, 3-d pattern\n# dont question again\n</code></pre>\n\n<p>and even later...</p>\n\n<pre><code># will determine if user clicks on die\n# i determined these values...dont worry about them\n</code></pre>\n" }, { "answer_id": 794891, "author": "corymathews", "author_id": 1925, "author_profile": "https://Stackoverflow.com/users/1925", "pm_score": 1, "selected": false, "text": "<pre><code>TextBox1.Text = TextBox1.Text; //Point less yes, who writes this crap?\n</code></pre>\n" }, { "answer_id": 796400, "author": "Lyudmil", "author_id": 13121, "author_profile": "https://Stackoverflow.com/users/13121", "pm_score": 7, "selected": false, "text": "<pre><code>public boolean isDirty() {\n //Why do you always go out and\n return dirty;\n}\n</code></pre>\n" }, { "answer_id": 796746, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>When coding MAPPER Apps we had <em>some</em> standards and one of these was that there was a list of standard variables in use throughout the suite. One of these - 'V43' was always used to hold a Surname. So imagine my annoyance when the <em>only comment</em> in a big cryptic chunk of MAPPER code I'd been asked to fix was: </p>\n\n<pre><code>Here V43 contains the Surname\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15985/" ]
What is the best comment in source code you have ever encountered?
I am particularly guilty of this, embedding non-constructive comments, code poetry and little jokes into most of my projects (although I usually have enough sense to remove anything directly offensive before releasing the code). Here's one I'm particulary fond of, placed far, far down a poorly-designed 'God Object': ``` /** * For the brave souls who get this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. */ ``` **I'M SORRY!!!!** I just couldn't help myself.....! And another, which I'll admit I haven't actually released into the wild, even though I am *very* tempted to do so in one of my less intuitive classes: ``` // // Dear maintainer: // // Once you are done trying to 'optimize' this routine, // and have realized what a terrible mistake that was, // please increment the following counter as a warning // to the next guy: // // total_hours_wasted_here = 42 // ```
184,641
<p>I have a mysql table with albums. Each album can be a top level album, or a child album of another album. Each album has a foldername which is the name of the folder its pictures are in. Each album also has a field called parent which is the id of the parent album. So, if I have a path to an image like this:</p> <pre><code>root/album1/album2/image1.jpg </code></pre> <p>then the album table in the database will look like this:</p> <pre><code>id parent foldername 1 NULL root 2 1 album1 3 2 album2 </code></pre> <p>The question is then, how do I get the path printed earlier from this table with only mysql?</p>
[ { "answer_id": 185255, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 0, "selected": false, "text": "<p>Totally untested and typed off the top of my head...</p>\n\n<pre><code>DECLARE @FOLDER VARCHAR(200)\nDECLARE @TOPID AS INT\nDECLARE @MYID As int\n\nCREATE TABLE #tmp\n(\n [id] INT,\n [path] VARCHAR(50)\n)\n\nDECLARE tempCursor CURSOR FOR SELECT id FROM albums ORDER BY id\nOPEN tempCursor\n\nFETCH NEXT FROM tempCursor INTO @TOPID\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SET @FOLDER = ''\n SET @MYID = @TOPID\n\n WHILE @MYID is not null\n BEGIN\n SELECT @MYFOLDER = foldername FROM albums WHERE id = @MYID\n SET @FOLDER = @MYFOLDER + '/' + @FOLDER\n SELECT @MYID = parent FROM albums WHERE id = @MYID\n END\n\n INSERT INTO #tmp\n SELECT @TOPID, @FOLDER\n\n FETCH NEXT FROM tempCursor INTO @TOPID\nEND\nCLOSE tempCursor\nDEALLOCATE tempCursor\n\nSELECT * FROM #tmp\nDROP TABLE #tmp\n</code></pre>\n\n<p>That should at least give you an idea how to get your path names. You never specified where your file names were stored.</p>\n\n<p>BTW, this is gonna be slow. I hate using cursors...</p>\n" }, { "answer_id": 185317, "author": "sebthebert", "author_id": 24820, "author_profile": "https://Stackoverflow.com/users/24820", "pm_score": 3, "selected": false, "text": "<p>I'm not sure storing a tree in Database is a good idea...</p>\n\n<p>To keep your problem simple maybe just store the full path of an album in a column of your table...</p>\n\n<pre><code>id parent path foldername\n1 NULL / root\n2 1 /root/ album1\n3 2 /root/album1/ album2\n</code></pre>\n" }, { "answer_id": 1350778, "author": "richardtallent", "author_id": 16306, "author_profile": "https://Stackoverflow.com/users/16306", "pm_score": 0, "selected": false, "text": "<p>DB2, SQL Server, PostgreSQL, and Oracle all support Common Table Expressions (CTE), which can be used to accomplish this. Oracle also has the \"CONNECT BY\" keyword.</p>\n\n<p>I know that doesn't solve your problem, but maybe it will help someone else looking for a solution on something other than MySQL.</p>\n\n<p>In your case, for performance sake, I recommend storing the full path in a column--the management of the denormalized data on insert/update will likely pay itself back many times in performance on reads.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
I have a mysql table with albums. Each album can be a top level album, or a child album of another album. Each album has a foldername which is the name of the folder its pictures are in. Each album also has a field called parent which is the id of the parent album. So, if I have a path to an image like this: ``` root/album1/album2/image1.jpg ``` then the album table in the database will look like this: ``` id parent foldername 1 NULL root 2 1 album1 3 2 album2 ``` The question is then, how do I get the path printed earlier from this table with only mysql?
I'm not sure storing a tree in Database is a good idea... To keep your problem simple maybe just store the full path of an album in a column of your table... ``` id parent path foldername 1 NULL / root 2 1 /root/ album1 3 2 /root/album1/ album2 ```
184,643
<p>What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?</p> <pre><code>lst = ['one', 2, 3] lst1 = list(lst) lst2 = lst[:] import copy lst3 = copy.copy(lst) </code></pre>
[ { "answer_id": 184660, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 8, "selected": true, "text": "<p>If you want a shallow copy (elements aren't copied) use:</p>\n\n<pre><code>lst2=lst1[:]\n</code></pre>\n\n<p>If you want to make a deep copy then use the copy module:</p>\n\n<pre><code>import copy\nlst2=copy.deepcopy(lst1)\n</code></pre>\n" }, { "answer_id": 184679, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 5, "selected": false, "text": "<p>I often use:</p>\n\n<pre><code>lst2 = lst1 * 1\n</code></pre>\n\n<p>If lst1 it contains other containers (like other lists) you should use deepcopy from the copy lib as shown by Mark.</p>\n\n<hr>\n\n<p>UPDATE: Explaining deepcopy</p>\n\n<pre><code>&gt;&gt;&gt; a = range(5)\n&gt;&gt;&gt; b = a*1\n&gt;&gt;&gt; a,b\n([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])\n&gt;&gt;&gt; a[2] = 55 \n&gt;&gt;&gt; a,b\n([0, 1, 55, 3, 4], [0, 1, 2, 3, 4])\n</code></pre>\n\n<p>As you may see only a changed...\nI'll try now with a list of lists</p>\n\n<pre><code>&gt;&gt;&gt; \n&gt;&gt;&gt; a = [range(i,i+3) for i in range(3)]\n&gt;&gt;&gt; a\n[[0, 1, 2], [1, 2, 3], [2, 3, 4]]\n&gt;&gt;&gt; b = a*1\n&gt;&gt;&gt; a,b\n([[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[0, 1, 2], [1, 2, 3], [2, 3, 4]])\n</code></pre>\n\n<p>Not so readable, let me print it with a for:</p>\n\n<pre><code>&gt;&gt;&gt; for i in (a,b): print i \n[[0, 1, 2], [1, 2, 3], [2, 3, 4]]\n[[0, 1, 2], [1, 2, 3], [2, 3, 4]]\n&gt;&gt;&gt; a[1].append('appended')\n&gt;&gt;&gt; for i in (a,b): print i\n\n[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]\n[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]\n</code></pre>\n\n<p>You see that? It appended to the b[1] too, so b[1] and a[1] are the very same object.\nNow try it with deepcopy</p>\n\n<pre><code>&gt;&gt;&gt; from copy import deepcopy\n&gt;&gt;&gt; b = deepcopy(a)\n&gt;&gt;&gt; a[0].append('again...')\n&gt;&gt;&gt; for i in (a,b): print i\n\n[[0, 1, 2, 'again...'], [1, 2, 3, 'appended'], [2, 3, 4]]\n[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]\n</code></pre>\n" }, { "answer_id": 184712, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<p>You can also do this:</p>\n\n<pre><code>import copy\nlist2 = copy.copy(list1)\n</code></pre>\n\n<p>This should do the same thing as Mark Roddy's shallow copy.</p>\n" }, { "answer_id": 184751, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 4, "selected": false, "text": "<p>You can also do:</p>\n\n<pre><code>a = [1, 2, 3]\nb = list(a)\n</code></pre>\n" }, { "answer_id": 185194, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 3, "selected": false, "text": "<p>I like to do:</p>\n\n<pre><code>lst2 = list(lst1)\n</code></pre>\n\n<p>The advantage over lst1[:] is that the same idiom works for dicts:</p>\n\n<pre><code>dct2 = dict(dct1)\n</code></pre>\n" }, { "answer_id": 8917632, "author": "DNS", "author_id": 51025, "author_profile": "https://Stackoverflow.com/users/51025", "pm_score": 2, "selected": false, "text": "<p>In terms of performance, there is some overhead to calling <code>list()</code> versus slicing. So for short lists, <code>lst2 = lst1[:]</code> is about twice as fast as <code>lst2 = list(lst1)</code>.</p>\n\n<p>In most cases, this is probably outweighed by the fact that <code>list()</code> is more readable, but in tight loops this can be a valuable optimization.</p>\n" }, { "answer_id": 14821420, "author": "shakefu", "author_id": 1418232, "author_profile": "https://Stackoverflow.com/users/1418232", "pm_score": 2, "selected": false, "text": "<p>Short lists, [:] is the best:</p>\n\n<pre><code>In [1]: l = range(10)\n\nIn [2]: %timeit list(l)\n1000000 loops, best of 3: 477 ns per loop\n\nIn [3]: %timeit l[:]\n1000000 loops, best of 3: 236 ns per loop\n\nIn [6]: %timeit copy(l)\n1000000 loops, best of 3: 1.43 us per loop\n</code></pre>\n\n<p>For larger lists, they're all about the same:</p>\n\n<pre><code>In [7]: l = range(50000)\n\nIn [8]: %timeit list(l)\n1000 loops, best of 3: 261 us per loop\n\nIn [9]: %timeit l[:]\n1000 loops, best of 3: 261 us per loop\n\nIn [10]: %timeit copy(l)\n1000 loops, best of 3: 248 us per loop\n</code></pre>\n\n<p>For very large lists (I tried 50MM), they're still about the same.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4915/" ]
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way? ``` lst = ['one', 2, 3] lst1 = list(lst) lst2 = lst[:] import copy lst3 = copy.copy(lst) ```
If you want a shallow copy (elements aren't copied) use: ``` lst2=lst1[:] ``` If you want to make a deep copy then use the copy module: ``` import copy lst2=copy.deepcopy(lst1) ```
184,662
<p>In our product we have a big utilities file that we require (with <code>do</code>) at the beginning of a lot of our files. Is there a reason <em>not</em> to turn this into a module? For example, instead of doing this:</p> <pre><code>do '../dbi_utilities.pl'; our ($db,$user,$pw,$attr); my $Data = DBI-&gt;connect($db,$user,$pw,$attr) or die "Could not connect to database: $DBI::errstr"; </code></pre> <p>Couldn't I just do this?:</p> <pre><code>use AppUtil; my $Data = AppUtil-&gt;connect(); </code></pre>
[ { "answer_id": 184687, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>Making a module out of it will make it a lot more robust. Right now a lot of things informally depend on each other, but those dependencies aren't immediately obvious.</p>\n\n<p>Also, it would enable you to import only part of the utilities.</p>\n" }, { "answer_id": 184689, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 3, "selected": false, "text": "<p>With do(), you're loading and compiling the utilities.pl file each time, which may cause problems if you do() it more than once. Also, <code>use</code> is done at compile which will allow your program to fail sooner, or even be tested with <code>perl -wc</code>.</p>\n\n<p>Lastly, keeping it in a package allows you to protect it's namespace, which can be helpful as your project grows.</p>\n\n<p>I would advise strongly to turn your utilites.pl into a proper Perl package that is loaded with <code>use</code>.</p>\n" }, { "answer_id": 184717, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "<p>You get all of the cool module stuff, encapsulation, module specific functions, and so on.</p>\n\n<p>Notice though, by using <code>use</code> with your syntax. creating an object for the AppUtil namespace, and calling the connect subroutine. for your utilities.</p>\n\n<p>Also you must have 1; at the end of your file.</p>\n\n<hr>\n\n<p>Sticking with the other method means you don't have to change any code, you don't have to add 1 at the end. </p>\n\n<p>All \"do\", \"use\", and \"require\" import, but scope code that is within them (except named subroutines cause they can't be hidden).</p>\n" }, { "answer_id": 184785, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 4, "selected": true, "text": "<p>The only reason not to do this is time.</p>\n\n<p>That is, it'll take time to clean up your interface, as well as all calling apps to use the new interface.</p>\n\n<p>What it'll cost you in time now will be more than made up when you start using proper tests (\"make test\" or \"./Build test\" or just \"prove ...\") and be able to check that your changes won't break anything before checking it in. So, by all means, convert. Just be aware that it's not a free gain.</p>\n" }, { "answer_id": 185059, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>By making your code into a module with proper refactoring, you make it easy to test. I talk about this in my <a href=\"http://www.ddj.com/184416165\" rel=\"nofollow noreferrer\">\"Scripts as Modules\"</a> article for <i>The Perl Journal</i> as well as <a href=\"http://www.perlmonks.org/index.pl?node_id=396759\" rel=\"nofollow noreferrer\">\"How a Script Becomes a Module\"</a> on Perlmonks.</p>\n\n<p>Good luck, </p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
In our product we have a big utilities file that we require (with `do`) at the beginning of a lot of our files. Is there a reason *not* to turn this into a module? For example, instead of doing this: ``` do '../dbi_utilities.pl'; our ($db,$user,$pw,$attr); my $Data = DBI->connect($db,$user,$pw,$attr) or die "Could not connect to database: $DBI::errstr"; ``` Couldn't I just do this?: ``` use AppUtil; my $Data = AppUtil->connect(); ```
The only reason not to do this is time. That is, it'll take time to clean up your interface, as well as all calling apps to use the new interface. What it'll cost you in time now will be more than made up when you start using proper tests ("make test" or "./Build test" or just "prove ...") and be able to check that your changes won't break anything before checking it in. So, by all means, convert. Just be aware that it's not a free gain.
184,678
<p>I'm using SimpleDateFormat with the pattern <code>EEE MM/dd hh:mma</code>, passing in the date String <code>Thu 10/9 08:15PM</code> and it's throwing an Unparseable date exception. Why? I've used various patterns with <code>SimpleDateFormat</code> before so I'm fairly familiar with its usage. Maybe I'm missing something obvious from staring at it too long.</p> <p>The other possibility is funky (technical term) whitespace. The context is a screen-scraping app, where I'm using HtmlCleaner to tidy up the messy html. While I've found HtmlCleaner to be pretty good overall, I've noticed strange issues with characters that look like whitespace but aren't recognized as such with a StringTokenizer, for example. I've mostly worked around it and haven't dug into the character encoding or anything like that but am starting to wonder.</p>
[ { "answer_id": 184694, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Try this instead for your pattern:</p>\n\n<pre><code>EEE MM/d hh:mma\n</code></pre>\n\n<p>The difference is the single <code>d</code> instead of double <code>dd</code>, since your date is for 10/9 instead of 10/09.</p>\n" }, { "answer_id": 184827, "author": "Eric Tuttleman", "author_id": 25677, "author_profile": "https://Stackoverflow.com/users/25677", "pm_score": 3, "selected": true, "text": "<p>To test if it's the date format, write a test class to prove it out. For these types of things, I like to use bsh (beanshell). Here was my test:</p>\n\n<pre><code>sdf = new java.text.SimpleDateFormat(\"EEE MM/dd hh:mma\");\nSystem.out.println(sdf.format(sdf.parse(\"Thu 10/9 08:15PM\")));\n</code></pre>\n\n<p>Which outputted: Fri 10/09 08:15PM</p>\n\n<p>So, at least with my jdk / jre version (1.6), the format strings seem to work just fine. i think the next step is to make sure the string you're dealing with is exactly what you think it is. Can you add logging to your code, and dump out the input string to a log file? Then you could look at it in a nice text editor, run it through your test class, or look at it in a hex editor to make sure that it's just normal text.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 188195, "author": "user26270", "author_id": 26270, "author_profile": "https://Stackoverflow.com/users/26270", "pm_score": 2, "selected": false, "text": "<p>First question here on StackOverFlow so I'm not sure what the proper way to mark this resolved is. Most of the answers are in the comments of Eric's answer.</p>\n\n<p>The root cause was a 'space' character in the date string that was not recognized as such. It was a hex char of 'A0', which is a non-breaking space. I ended up converting the date string to a char array, checking the characters with Character.isSpaceChar(), and replacing those that returned true with a \" \" char.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26270/" ]
I'm using SimpleDateFormat with the pattern `EEE MM/dd hh:mma`, passing in the date String `Thu 10/9 08:15PM` and it's throwing an Unparseable date exception. Why? I've used various patterns with `SimpleDateFormat` before so I'm fairly familiar with its usage. Maybe I'm missing something obvious from staring at it too long. The other possibility is funky (technical term) whitespace. The context is a screen-scraping app, where I'm using HtmlCleaner to tidy up the messy html. While I've found HtmlCleaner to be pretty good overall, I've noticed strange issues with characters that look like whitespace but aren't recognized as such with a StringTokenizer, for example. I've mostly worked around it and haven't dug into the character encoding or anything like that but am starting to wonder.
To test if it's the date format, write a test class to prove it out. For these types of things, I like to use bsh (beanshell). Here was my test: ``` sdf = new java.text.SimpleDateFormat("EEE MM/dd hh:mma"); System.out.println(sdf.format(sdf.parse("Thu 10/9 08:15PM"))); ``` Which outputted: Fri 10/09 08:15PM So, at least with my jdk / jre version (1.6), the format strings seem to work just fine. i think the next step is to make sure the string you're dealing with is exactly what you think it is. Can you add logging to your code, and dump out the input string to a log file? Then you could look at it in a nice text editor, run it through your test class, or look at it in a hex editor to make sure that it's just normal text. Good luck!
184,681
<p>Which of these pieces of code is faster?</p> <pre><code>if (obj is ClassA) {} if (obj.GetType() == typeof(ClassA)) {} </code></pre> <p>Edit: I'm aware that they don't do the same thing.</p>
[ { "answer_id": 184697, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 8, "selected": true, "text": "<p><a href=\"https://learn.microsoft.com/en-us/archive/blogs/vancem/drilling-into-net-runtime-microbenchmarks-typeof-optimizations\" rel=\"nofollow noreferrer\">This should answer that question, and then some.</a></p>\n\n<p>The second line, <code>if (obj.GetType() == typeof(ClassA)) {}</code>, is faster, for those that don't want to read the article.</p>\n\n<p><em>(Be aware that they don't do the same thing)</em></p>\n" }, { "answer_id": 184711, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": false, "text": "<p>They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.</p>\n\n<p>For those who want to know the reason, but don't want to read the article referenced in <a href=\"https://stackoverflow.com/questions/184681/is-vs-typeof#184697\"><a href=\"https://stackoverflow.com/questions/184681/is-vs-typeof#184697\">is vs typeof</a></a>.</p>\n" }, { "answer_id": 184718, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 8, "selected": false, "text": "<p>Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.</p>\n\n<p><code>is</code> tells you if the object implements <code>ClassA</code> anywhere in its type heirarchy. <code>GetType()</code> tells you about the most-derived type.</p>\n\n<p>Not the same thing.</p>\n" }, { "answer_id": 14836403, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 4, "selected": false, "text": "<p>I did some benchmarking where they do the same - sealed types.</p>\n\n<pre><code>var c1 = \"\";\nvar c2 = typeof(string);\nobject oc1 = c1;\nobject oc2 = c2;\n\nvar s1 = 0;\nvar s2 = '.';\nobject os1 = s1;\nobject os2 = s2;\n\nbool b = false;\n\nStopwatch sw = Stopwatch.StartNew();\nfor (int i = 0; i &lt; 10000000; i++)\n{\n b = c1.GetType() == typeof(string); // ~60ms\n b = c1 is string; // ~60ms\n\n b = c2.GetType() == typeof(string); // ~60ms\n b = c2 is string; // ~50ms\n\n b = oc1.GetType() == typeof(string); // ~60ms\n b = oc1 is string; // ~68ms\n\n b = oc2.GetType() == typeof(string); // ~60ms\n b = oc2 is string; // ~64ms\n\n\n b = s1.GetType() == typeof(int); // ~130ms\n b = s1 is int; // ~50ms\n\n b = s2.GetType() == typeof(int); // ~140ms\n b = s2 is int; // ~50ms\n\n b = os1.GetType() == typeof(int); // ~60ms\n b = os1 is int; // ~74ms\n\n b = os2.GetType() == typeof(int); // ~60ms\n b = os2 is int; // ~68ms\n\n\n b = GetType1&lt;string, string&gt;(c1); // ~178ms\n b = GetType2&lt;string, string&gt;(c1); // ~94ms\n b = Is&lt;string, string&gt;(c1); // ~70ms\n\n b = GetType1&lt;string, Type&gt;(c2); // ~178ms\n b = GetType2&lt;string, Type&gt;(c2); // ~96ms\n b = Is&lt;string, Type&gt;(c2); // ~65ms\n\n b = GetType1&lt;string, object&gt;(oc1); // ~190ms\n b = Is&lt;string, object&gt;(oc1); // ~69ms\n\n b = GetType1&lt;string, object&gt;(oc2); // ~180ms\n b = Is&lt;string, object&gt;(oc2); // ~64ms\n\n\n b = GetType1&lt;int, int&gt;(s1); // ~230ms\n b = GetType2&lt;int, int&gt;(s1); // ~75ms\n b = Is&lt;int, int&gt;(s1); // ~136ms\n\n b = GetType1&lt;int, char&gt;(s2); // ~238ms\n b = GetType2&lt;int, char&gt;(s2); // ~69ms\n b = Is&lt;int, char&gt;(s2); // ~142ms\n\n b = GetType1&lt;int, object&gt;(os1); // ~178ms\n b = Is&lt;int, object&gt;(os1); // ~69ms\n\n b = GetType1&lt;int, object&gt;(os2); // ~178ms\n b = Is&lt;int, object&gt;(os2); // ~69ms\n}\n\nsw.Stop();\nMessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());\n</code></pre>\n\n<p>The generic functions to test for generic types:</p>\n\n<pre><code>static bool GetType1&lt;S, T&gt;(T t)\n{\n return t.GetType() == typeof(S);\n}\nstatic bool GetType2&lt;S, T&gt;(T t)\n{\n return typeof(T) == typeof(S);\n}\nstatic bool Is&lt;S, T&gt;(T t)\n{\n return t is S;\n}\n</code></pre>\n\n<p>I tried for custom types as well and the results were consistent: </p>\n\n<pre><code>var c1 = new Class1();\nvar c2 = new Class2();\nobject oc1 = c1;\nobject oc2 = c2;\n\nvar s1 = new Struct1();\nvar s2 = new Struct2();\nobject os1 = s1;\nobject os2 = s2;\n\nbool b = false;\n\nStopwatch sw = Stopwatch.StartNew();\nfor (int i = 0; i &lt; 10000000; i++)\n{\n b = c1.GetType() == typeof(Class1); // ~60ms\n b = c1 is Class1; // ~60ms\n\n b = c2.GetType() == typeof(Class1); // ~60ms\n b = c2 is Class1; // ~55ms\n\n b = oc1.GetType() == typeof(Class1); // ~60ms\n b = oc1 is Class1; // ~68ms\n\n b = oc2.GetType() == typeof(Class1); // ~60ms\n b = oc2 is Class1; // ~68ms\n\n\n b = s1.GetType() == typeof(Struct1); // ~150ms\n b = s1 is Struct1; // ~50ms\n\n b = s2.GetType() == typeof(Struct1); // ~150ms\n b = s2 is Struct1; // ~50ms\n\n b = os1.GetType() == typeof(Struct1); // ~60ms\n b = os1 is Struct1; // ~64ms\n\n b = os2.GetType() == typeof(Struct1); // ~60ms\n b = os2 is Struct1; // ~64ms\n\n\n b = GetType1&lt;Class1, Class1&gt;(c1); // ~178ms\n b = GetType2&lt;Class1, Class1&gt;(c1); // ~98ms\n b = Is&lt;Class1, Class1&gt;(c1); // ~78ms\n\n b = GetType1&lt;Class1, Class2&gt;(c2); // ~178ms\n b = GetType2&lt;Class1, Class2&gt;(c2); // ~96ms\n b = Is&lt;Class1, Class2&gt;(c2); // ~69ms\n\n b = GetType1&lt;Class1, object&gt;(oc1); // ~178ms\n b = Is&lt;Class1, object&gt;(oc1); // ~69ms\n\n b = GetType1&lt;Class1, object&gt;(oc2); // ~178ms\n b = Is&lt;Class1, object&gt;(oc2); // ~69ms\n\n\n b = GetType1&lt;Struct1, Struct1&gt;(s1); // ~272ms\n b = GetType2&lt;Struct1, Struct1&gt;(s1); // ~140ms\n b = Is&lt;Struct1, Struct1&gt;(s1); // ~163ms\n\n b = GetType1&lt;Struct1, Struct2&gt;(s2); // ~272ms\n b = GetType2&lt;Struct1, Struct2&gt;(s2); // ~140ms\n b = Is&lt;Struct1, Struct2&gt;(s2); // ~163ms\n\n b = GetType1&lt;Struct1, object&gt;(os1); // ~178ms\n b = Is&lt;Struct1, object&gt;(os1); // ~64ms\n\n b = GetType1&lt;Struct1, object&gt;(os2); // ~178ms\n b = Is&lt;Struct1, object&gt;(os2); // ~64ms\n}\n\nsw.Stop();\nMessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());\n</code></pre>\n\n<p>And the types:</p>\n\n<pre><code>sealed class Class1 { }\nsealed class Class2 { }\nstruct Struct1 { }\nstruct Struct2 { }\n</code></pre>\n\n<p>Inference:</p>\n\n<ol>\n<li><p><strong>Calling <code>GetType</code> on <code>struct</code>s is slower.</strong> <code>GetType</code> is defined on <code>object</code> class which can't be overridden in sub types and thus <code>struct</code>s need to be boxed to be called <code>GetType</code>. </p></li>\n<li><p><strong>On an object instance, <code>GetType</code> is faster, but very marginally.</strong></p></li>\n<li><p><strong>On generic type, if <code>T</code> is <code>class</code>, then <code>is</code> is much faster. If <code>T</code> is <code>struct</code>, then <code>is</code> is much faster than <code>GetType</code> but <code>typeof(T)</code> is much faster than both.</strong> In cases of <code>T</code> being <code>class</code>, <code>typeof(T)</code> is not reliable since its different from actual underlying type <code>t.GetType</code>.</p></li>\n</ol>\n\n<p>In short, if you have an <code>object</code> instance, use <code>GetType</code>. If you have a generic <code>class</code> type, use <code>is</code>. If you have a generic <code>struct</code> type, use <code>typeof(T)</code>. If you are unsure if generic type is reference type or value type, use <code>is</code>. If you want to be consistent with one style always (for sealed types), use <code>is</code>..</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
Which of these pieces of code is faster? ``` if (obj is ClassA) {} if (obj.GetType() == typeof(ClassA)) {} ``` Edit: I'm aware that they don't do the same thing.
[This should answer that question, and then some.](https://learn.microsoft.com/en-us/archive/blogs/vancem/drilling-into-net-runtime-microbenchmarks-typeof-optimizations) The second line, `if (obj.GetType() == typeof(ClassA)) {}`, is faster, for those that don't want to read the article. *(Be aware that they don't do the same thing)*
184,683
<p>Is there a way in C# to play audio (for example, MP3) direcly from a <a href="http://msdn.microsoft.com/en-us/library/system.io.stream%28v=vs.110%29.aspx" rel="noreferrer">System.IO.Stream</a> that for instance was returend from a WebRequest without saving the data temporarily to the disk?</p> <hr> <h3>Solution with <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a></h3> <p>With the help of <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a> 1.3 it is possible to:</p> <ol> <li>Load an MP3 file from a URL into a MemoryStream</li> <li>Convert MP3 data into wave data after it was completely loaded</li> <li>Playback the wave data using <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a>'s WaveOut class</li> </ol> <p>It would have been nice to be able to even play a half loaded MP3 file, but this seems to be impossible due to the <a href="https://github.com/naudio/NAudio" rel="noreferrer">NAudio</a> library design.</p> <p>And this is the function that will do the work:</p> <pre><code> public static void PlayMp3FromUrl(string url) { using (Stream ms = new MemoryStream()) { using (Stream stream = WebRequest.Create(url) .GetResponse().GetResponseStream()) { byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) &gt; 0) { ms.Write(buffer, 0, read); } } ms.Position = 0; using (WaveStream blockAlignedStream = new BlockAlignReductionStream( WaveFormatConversionStream.CreatePcmStream( new Mp3FileReader(ms)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing ) { System.Threading.Thread.Sleep(100); } } } } } </code></pre>
[ { "answer_id": 184796, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/w5bfdtza.aspx\" rel=\"noreferrer\">SoundPlayer</a> class can do this. It looks like all you have to do is set its <em>Stream</em> property to the stream, then call <code>Play</code>.</p>\n\n<p><em>edit</em><br/>\nI don't think it can play MP3 files though; it seems limited to .wav. I'm not certain if there's anything in the framework that can play an MP3 file directly. Everything I find about that involves either using a WMP control or interacting with DirectX.</p>\n" }, { "answer_id": 185041, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 7, "selected": true, "text": "<p><strong>Edit: Answer updated to reflect changes in recent versions of NAudio</strong></p>\n\n<p>It's possible using the <a href=\"https://github.com/naudio/NAudio\" rel=\"noreferrer\">NAudio</a> open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the <code>MP3Frame</code> and <code>AcmMp3FrameDecompressor</code> classes in NAudio to decompress streamed MP3 on the fly.</p>\n\n<p>I have posted an article on my blog explaining <a href=\"http://mark-dot-net.blogspot.com/2011/05/how-to-play-back-streaming-mp3-using.html\" rel=\"noreferrer\">how to play back an MP3 stream using NAudio</a>. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a <code>BufferedWaveProvider</code>. Another thread then plays back using the <code>BufferedWaveProvider</code> as an input.</p>\n" }, { "answer_id": 217064, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 1, "selected": false, "text": "<p>NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.</p>\n\n<p>Using the waveOutWrite() function allows you to \"read ahead\" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.</p>\n" }, { "answer_id": 225244, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.un4seen.com/bass.html\" rel=\"nofollow noreferrer\">Bass</a> can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..</p>\n" }, { "answer_id": 285194, "author": "Ramiro Berrelleza", "author_id": 548, "author_profile": "https://Stackoverflow.com/users/548", "pm_score": 1, "selected": false, "text": "<p>I haven't tried it from a WebRequest, but both the <a href=\"http://en.wikipedia.org/wiki/Windows_Media_Player\" rel=\"nofollow noreferrer\">Windows Media Player</a> <a href=\"http://en.wikipedia.org/wiki/ActiveX\" rel=\"nofollow noreferrer\">ActiveX</a> and the MediaElement (from <a href=\"http://en.wikipedia.org/wiki/Windows_Presentation_Foundation\" rel=\"nofollow noreferrer\">WPF</a>) components are capable of playing and buffering MP3 streams.</p>\n\n<p>I use it to play data coming from a <a href=\"https://en.wikipedia.org/wiki/SHOUTcast\" rel=\"nofollow noreferrer\">SHOUTcast</a> stream and it worked great. However, I'm not sure if it will work in the scenario you propose.</p>\n" }, { "answer_id": 1692522, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 0, "selected": false, "text": "<p>I've always used FMOD for things like this because it's free for non-commercial use and works well.</p>\n\n<p>That said, I'd gladly switch to something that's smaller (FMOD is ~300k) and open-source. Super bonus points if it's fully managed so that I can compile / merge it with my .exe and not have to take extra care to get portability to other platforms...</p>\n\n<p>(FMOD does portability too but you'd obviously need different binaries for different platforms)</p>\n" }, { "answer_id": 3560402, "author": "Daniel Mošmondor", "author_id": 166251, "author_profile": "https://Stackoverflow.com/users/166251", "pm_score": 1, "selected": false, "text": "<p>I wrapped the MP3 decoder library and made it available for <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow noreferrer\">.NET</a> developers as <a href=\"http://sourceforge.net/projects/mpg123net/\" rel=\"nofollow noreferrer\">mpg123.net</a>.</p>\n\n<p>Included are the samples to convert MP3 files to <a href=\"https://en.wikipedia.org/wiki/Pulse-code_modulation\" rel=\"nofollow noreferrer\">PCM</a>, and read <a href=\"https://en.wikipedia.org/wiki/ID3\" rel=\"nofollow noreferrer\">ID3</a> tags.</p>\n" }, { "answer_id": 5081173, "author": "ReVolly", "author_id": 492016, "author_profile": "https://Stackoverflow.com/users/492016", "pm_score": 2, "selected": false, "text": "<p>I slightly modified the topic starter source, so it can now play a not-fully-loaded file. Here it is (note, that it is just a sample and is a point to start from; you need to do some exception and error handling here):</p>\n\n<pre><code>private Stream ms = new MemoryStream();\npublic void PlayMp3FromUrl(string url)\n{\n new Thread(delegate(object o)\n {\n var response = WebRequest.Create(url).GetResponse();\n using (var stream = response.GetResponseStream())\n {\n byte[] buffer = new byte[65536]; // 64KB chunks\n int read;\n while ((read = stream.Read(buffer, 0, buffer.Length)) &gt; 0)\n {\n var pos = ms.Position;\n ms.Position = ms.Length;\n ms.Write(buffer, 0, read);\n ms.Position = pos;\n }\n }\n }).Start();\n\n // Pre-buffering some data to allow NAudio to start playing\n while (ms.Length &lt; 65536*10)\n Thread.Sleep(1000);\n\n ms.Position = 0;\n using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms))))\n {\n using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))\n {\n waveOut.Init(blockAlignedStream);\n waveOut.Play();\n while (waveOut.PlaybackState == PlaybackState.Playing)\n {\n System.Threading.Thread.Sleep(100);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 9245124, "author": "M.Babcock", "author_id": 635634, "author_profile": "https://Stackoverflow.com/users/635634", "pm_score": 2, "selected": false, "text": "<p>I've tweaked the source posted in the question to allow usage with Google's TTS API in order to answer the question <a href=\"https://stackoverflow.com/questions/9243560/how-can-i-use-google-text-to-speech-api-in-windows-form/9243705#9243705\">here</a>:</p>\n\n<pre><code>bool waiting = false;\nAutoResetEvent stop = new AutoResetEvent(false);\npublic void PlayMp3FromUrl(string url, int timeout)\n{\n using (Stream ms = new MemoryStream())\n {\n using (Stream stream = WebRequest.Create(url)\n .GetResponse().GetResponseStream())\n {\n byte[] buffer = new byte[32768];\n int read;\n while ((read = stream.Read(buffer, 0, buffer.Length)) &gt; 0)\n {\n ms.Write(buffer, 0, read);\n }\n }\n ms.Position = 0;\n using (WaveStream blockAlignedStream =\n new BlockAlignReductionStream(\n WaveFormatConversionStream.CreatePcmStream(\n new Mp3FileReader(ms))))\n {\n using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))\n {\n waveOut.Init(blockAlignedStream);\n waveOut.PlaybackStopped += (sender, e) =&gt;\n {\n waveOut.Stop();\n };\n waveOut.Play();\n waiting = true;\n stop.WaitOne(timeout);\n waiting = false;\n }\n }\n }\n}\n</code></pre>\n\n<p>Invoke with:</p>\n\n<pre><code>var playThread = new Thread(timeout =&gt; PlayMp3FromUrl(\"http://translate.google.com/translate_tts?q=\" + HttpUtility.UrlEncode(relatedLabel.Text), (int)timeout));\nplayThread.IsBackground = true;\nplayThread.Start(10000);\n</code></pre>\n\n<p>Terminate with:</p>\n\n<pre><code>if (waiting)\n stop.Set();\n</code></pre>\n\n<p>Notice that I'm using the <code>ParameterizedThreadDelegate</code> in the code above, and the thread is started with <code>playThread.Start(10000);</code>. The 10000 represents a maximum of 10 seconds of audio to be played so it will need to be tweaked if your stream takes longer than that to play. This is necessary because the current version of NAudio (v1.5.4.0) seems to have a problem determining when the stream is done playing. It may be fixed in a later version or perhaps there is a workaround that I didn't take the time to find.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25782/" ]
Is there a way in C# to play audio (for example, MP3) direcly from a [System.IO.Stream](http://msdn.microsoft.com/en-us/library/system.io.stream%28v=vs.110%29.aspx) that for instance was returend from a WebRequest without saving the data temporarily to the disk? --- ### Solution with [NAudio](https://github.com/naudio/NAudio) With the help of [NAudio](https://github.com/naudio/NAudio) 1.3 it is possible to: 1. Load an MP3 file from a URL into a MemoryStream 2. Convert MP3 data into wave data after it was completely loaded 3. Playback the wave data using [NAudio](https://github.com/naudio/NAudio)'s WaveOut class It would have been nice to be able to even play a half loaded MP3 file, but this seems to be impossible due to the [NAudio](https://github.com/naudio/NAudio) library design. And this is the function that will do the work: ``` public static void PlayMp3FromUrl(string url) { using (Stream ms = new MemoryStream()) { using (Stream stream = WebRequest.Create(url) .GetResponse().GetResponseStream()) { byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } } ms.Position = 0; using (WaveStream blockAlignedStream = new BlockAlignReductionStream( WaveFormatConversionStream.CreatePcmStream( new Mp3FileReader(ms)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing ) { System.Threading.Thread.Sleep(100); } } } } } ```
**Edit: Answer updated to reflect changes in recent versions of NAudio** It's possible using the [NAudio](https://github.com/naudio/NAudio) open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the `MP3Frame` and `AcmMp3FrameDecompressor` classes in NAudio to decompress streamed MP3 on the fly. I have posted an article on my blog explaining [how to play back an MP3 stream using NAudio](http://mark-dot-net.blogspot.com/2011/05/how-to-play-back-streaming-mp3-using.html). Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a `BufferedWaveProvider`. Another thread then plays back using the `BufferedWaveProvider` as an input.
184,703
<p>I have a form that is sending in sizes of things, and I need to see what the strings are equal to so that I can set the price accordingly. When i try to do this, it says that they are not equal, and i get no prices. This is the code i'm using:</p> <pre><code>if ($_POST['sizes'] == "Small ($30)"){$total = "30";} if ($_POST['sizes'] == "Medium ($40)"){$total = "40";} if ($_POST['sizes'] == "Large ($50)"){$total = "50";} else {$total = $_POST['price'];} </code></pre> <p>What am i doing wrong here? I can echo $_POST['sizes'] and it gives me exactly one of those things.</p>
[ { "answer_id": 184737, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>Try using single quotes</p>\n\n<pre><code>if ($_POST['sizes'] == 'Small ($30)'){$total = \"30\";}\nelseif ($_POST['sizes'] == 'Medium ($40)'){$total = \"40\";}\nelseif ($_POST['sizes'] == 'Large ($50)'){$total = \"50\";}\nelse {$total = $_POST['price'];}\n</code></pre>\n\n<p>Double quoted strings use variable interpolation, so the $ symbol becomes significant! See <a href=\"http://us2.php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">this manual page</a> for the differences in how you can declare string literals in PHP.</p>\n\n<p>(Edited to correct the logic error - as others noted, a switch would be much clearer here)</p>\n" }, { "answer_id": 184752, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 4, "selected": true, "text": "<p>What <a href=\"https://stackoverflow.com/questions/184703/compare-strings-given-in-post-with-php/184737#184737\">Paul Dixon said</a> is correct. Might I also recommend using a switch statement instead of that clunky chunk of if statements (which actually has a logic bug in it, I might add - <code>$total</code> will always equal <code>$_POST['price']</code> when not <code>'Large ($50)'</code>)</p>\n\n<pre><code>&lt;?php\n\nswitch ( $_POST['sizes'] )\n{\n case 'Small ($30)' :\n $total = 30;\n break;\n case 'Medium ($40)' :\n $total = 40;\n break;\n case 'Large ($50)' :\n $total = 50;\n break;\n default:\n $total = $_POST['price'];\n break;\n}\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 184765, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 2, "selected": false, "text": "<p>That's a good candidate for a switch/case statement, with your 'else' being a default.</p>\n\n<p>Also, without using elseif's on Medium and Large, if your $_POST['sizes'] is not Large, then your $total will always be $_POST['price']. This could be throwing you off as well.</p>\n" }, { "answer_id": 184856, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "<p>So you know, the problem with your if/else's is that the last else is always happening. A switch is still better, but here is what your code should be:</p>\n\n<pre><code>if ($_POST['sizes'] == \"Small ($30)\") { $total = \"30\";\n} else if ($_POST['sizes'] == \"Medium ($40)\") { $total = \"40\";\n} else if ($_POST['sizes'] == \"Large ($50)\") { $total = \"50\";\n} else { $total = $_POST['price']; }\n</code></pre>\n\n<p>To everyone that says the problem is the $30, $40, etc, it's not. Variables can't start with a number so PHP will ignore the $40, etc.</p>\n" }, { "answer_id": 509520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Is $total a string? </p>\n\n<p>$total = \"30\"; is the syntax for a string. $total = 30; would be correct for Numeric. </p>\n" }, { "answer_id": 509523, "author": "Chris KL", "author_id": 58110, "author_profile": "https://Stackoverflow.com/users/58110", "pm_score": 0, "selected": false, "text": "<p>Isn't there a security hole here? What if someone just submits whatever price they want for the default clause?</p>\n" }, { "answer_id": 509546, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 1, "selected": false, "text": "<p>Or, even better than the clunky switch, you can take advantage of this simple logic and practise 'data-driven programming':</p>\n\n<pre><code>$vals = array(\n 'Small ($30)' =&gt; 30,\n 'Medium ($40)' =&gt; 40,\n 'Large ($50)' =&gt; 50\n);\n\n$total = array_key_exists($_POST['sizes'], $vals)\n ? $vals[$_POST['sizes']]\n : $_POST['price'];\n</code></pre>\n" }, { "answer_id": 509554, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": 0, "selected": false, "text": "<pre><code>// remove any non-decimal characters from the front, then extract your value,\n// then remove any trailing characters and cast to an integer\n$total = (integer)preg_replace(\"/^\\D*(\\d+)\\D.*/\", \"$1\", $_POST['sizes']);\nif (!$total) $total = $_POST['price'];\n</code></pre>\n" }, { "answer_id": 509572, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 1, "selected": false, "text": "<p>Apart from the actual cause of this error, it could have been avoided if you had used other values than the labels, e.g.:</p>\n\n<pre><code>&lt;select name=\"sizes\"&gt;\n &lt;option value=\"small\"&gt;Small ($30)&lt;/option&gt;\n &lt;option value=\"meduim\"&gt;Medium ($40)&lt;/option&gt;\n &lt;option value=\"large\"&gt;Large ($50)&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50/" ]
I have a form that is sending in sizes of things, and I need to see what the strings are equal to so that I can set the price accordingly. When i try to do this, it says that they are not equal, and i get no prices. This is the code i'm using: ``` if ($_POST['sizes'] == "Small ($30)"){$total = "30";} if ($_POST['sizes'] == "Medium ($40)"){$total = "40";} if ($_POST['sizes'] == "Large ($50)"){$total = "50";} else {$total = $_POST['price'];} ``` What am i doing wrong here? I can echo $\_POST['sizes'] and it gives me exactly one of those things.
What [Paul Dixon said](https://stackoverflow.com/questions/184703/compare-strings-given-in-post-with-php/184737#184737) is correct. Might I also recommend using a switch statement instead of that clunky chunk of if statements (which actually has a logic bug in it, I might add - `$total` will always equal `$_POST['price']` when not `'Large ($50)'`) ``` <?php switch ( $_POST['sizes'] ) { case 'Small ($30)' : $total = 30; break; case 'Medium ($40)' : $total = 40; break; case 'Large ($50)' : $total = 50; break; default: $total = $_POST['price']; break; } ?> ```
184,704
<p>In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.</p> <p>Is there a more elegant way of doing this? Perhaps an API call that will reveal this?</p> <p>Here's some rough code of what I'm talking about:</p> <pre><code>Throwable t = null; try { stream.write(buffer); } catch(IOException e) { t = e; //Need to save this exception for finally throw e; } finally { try { stream.close(); //may throw exception } catch(IOException e) { //Is there something better than saving the exception from the exception block? if(t!=null) { //propagate the read exception as the "cause"--not great, but you see what I mean. throw new IOException("Could not close in finally block: " + e.getMessage(),t); } else { throw e; //just pass it up } }//end close } </code></pre> <p>Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.</p> <p>Maybe something like <code>Thread.getPendingException()</code> or something similar? For that matter, is there an elegant solution in other languages?</p> <p>This question actually spawned from comments in <a href="https://stackoverflow.com/questions/183499/is-there-a-preference-for-nested-trycatch-blocks#183572">another question</a> that raised an interesting question. </p>
[ { "answer_id": 184715, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You could always set a boolean flag in your catch(es). I don't know of any \"slick\" way to do it, but then I'm more of a .Net guy.</p>\n" }, { "answer_id": 184731, "author": "Jeremy Ross", "author_id": 2517, "author_profile": "https://Stackoverflow.com/users/2517", "pm_score": 5, "selected": true, "text": "<p>Your idea about setting a variable outside the scope of the try/catch/finally is correct.</p>\n\n<p>There cannot be more than one exception propagating at once.</p>\n" }, { "answer_id": 190631, "author": "gedevan", "author_id": 20225, "author_profile": "https://Stackoverflow.com/users/20225", "pm_score": 2, "selected": false, "text": "<p>Use logging...</p>\n\n<pre><code>try { \n stream.write(buffer); \n} catch(IOException ex) {\n if (LOG.isErrorEnabled()) { // You can use log level whatever you want\n LOG.error(\"Something wrong: \" + ex.getMessage(), ex);\n }\n throw ex;\n} finally { \n if (stream != null) {\n try {\n stream.close();\n } catch (IOException ex) {\n if (LOG.isWarnEnabled()) {\n LOG.warn(\"Could not close in finally block\", ex);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1354697, "author": "Triynko", "author_id": 88409, "author_profile": "https://Stackoverflow.com/users/88409", "pm_score": 3, "selected": false, "text": "<p>Instead of using a Boolean flag, I would store a reference to the Exception object.\nThat way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).</p>\n\n<p><strong>I think this is a missing C# language feature that should be added.</strong> The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be <strong>an easy task for the compiler</strong>, <strong>saving us the work</strong> of <strong>manually</strong> creating a local Exception variable and <strong>remembering</strong> to manually set its value before re-throwing an error, as well as preventing us from <strong>making the mistake</strong> of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).</p>\n\n<pre><code>finally (Exception main_exception)\n{\n try\n {\n //cleanup that may throw an error (absolutely unpredictably)\n }\n catch (Exception err)\n {\n //Instead of throwing another error,\n //just add data to main exception mentioning that an error occurred in the finally block!\n main_exception.Data.Add( \"finally_error\", err );\n //main exception propagates from finally block normally, with additional data\n }\n}\n</code></pre>\n\n<p>As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of <strong>overwriting the main exception by throwing a new error (bad)</strong> or just <strong>ignoring the error (also bad)</strong>, it could add the error as additional data to the original error.</p>\n" }, { "answer_id": 4502657, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "<p>In vb.net, it's possible to use a \"Catch...When\" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:</p>\n\n<ol>\n<li>If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.\n<li>Although a rethrow won't clear the stack trace the way \"Throw Ex\" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.\n</ol>\n\n<p>Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a \"Try\" and the Action in a \"Finally\".<p></p>\n\n<p>One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17871/" ]
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block. Is there a more elegant way of doing this? Perhaps an API call that will reveal this? Here's some rough code of what I'm talking about: ``` Throwable t = null; try { stream.write(buffer); } catch(IOException e) { t = e; //Need to save this exception for finally throw e; } finally { try { stream.close(); //may throw exception } catch(IOException e) { //Is there something better than saving the exception from the exception block? if(t!=null) { //propagate the read exception as the "cause"--not great, but you see what I mean. throw new IOException("Could not close in finally block: " + e.getMessage(),t); } else { throw e; //just pass it up } }//end close } ``` Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant. Maybe something like `Thread.getPendingException()` or something similar? For that matter, is there an elegant solution in other languages? This question actually spawned from comments in [another question](https://stackoverflow.com/questions/183499/is-there-a-preference-for-nested-trycatch-blocks#183572) that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct. There cannot be more than one exception propagating at once.
184,721
<p>I have a windows c# application and I want to display a pdf file, located on a webserver, in an acrobat com object added to my form. </p> <pre><code>pdf.loadfile(@"http://somewhere.com/nowwhere.pdf") </code></pre> <p>As my pdf is large, the application seems to hang till the entire file is loaded. </p> <p>I want to read the large file without the user being under the perception that the application is hung.</p>
[ { "answer_id": 184741, "author": "wax eagle", "author_id": 1001650, "author_profile": "https://Stackoverflow.com/users/1001650", "pm_score": 1, "selected": false, "text": "<p>Three suggestions. </p>\n\n<p>the first would be to break it and load a page at a time like some online books do. This is a bit annoying but would save you the loading time. I think ItextSharp has some functionality to do this.</p>\n\n<p>Second try compression. again itextsharp has tools that allow for this</p>\n\n<p>My third suggestion would be to check out <a href=\"https://stackoverflow.com/questions/182112/funny-loading-statements-to-keep-users-amused\">This thread</a>. choose a few nerdy loading phrases and use an animated gif to distract your client from the long loading time. Obviously this is a last resort, but could useful.</p>\n" }, { "answer_id": 184744, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 1, "selected": false, "text": "<p>Use a Worker Thread. (BackgroundWorker for example)<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">MSDN Link to BackgroundWorker</a></p>\n" }, { "answer_id": 184749, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 2, "selected": false, "text": "<p>I would do the following:</p>\n\n<ol>\n<li>Create another thread to import the pdf.</li>\n<li>Display some kind of a progress bar to the user. perhaps with a cancel button.</li>\n</ol>\n" }, { "answer_id": 184818, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>Obviously, if you can use a background thread to do the loading - you'd be all set:</p>\n\n<pre><code>Pdf pdf;\n\nvoid ShowPdf() {\n if (this.InvokeRequired) {\n this.Invoke(() =&gt; this.ShowPdf());\n }\n // give pdf a window...\n}\n\nvoid LoadPdf() {\n System.Threading.ThreadPool.QueueUserWorkItem(() =&gt; {\n pdf.LoadFile(\"http://example.com/somelarge.pdf\");\n this.ShowPdf();\n });\n}\n</code></pre>\n\n<p>The issue that <em>may</em> come up there (I've never worked with Acrobat's COM PDF viewer) is that the PDF object expects to be on the UI thread. In that case, you'll end up with issues.</p>\n" }, { "answer_id": 184918, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 1, "selected": false, "text": "<p>If PDF.LoadFile has to run from the UI thread, you can download the file in a BackgroundWorker with HttpWebRequest, save it locally, then call pdf.loadfile() in an Invoke'd (UI thread) function.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a windows c# application and I want to display a pdf file, located on a webserver, in an acrobat com object added to my form. ``` pdf.loadfile(@"http://somewhere.com/nowwhere.pdf") ``` As my pdf is large, the application seems to hang till the entire file is loaded. I want to read the large file without the user being under the perception that the application is hung.
I would do the following: 1. Create another thread to import the pdf. 2. Display some kind of a progress bar to the user. perhaps with a cancel button.
184,729
<p>After reading Martin Fowler's <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="nofollow noreferrer">Mocks Aren't Stubs</a>, I've discovered I've been practicing TDD in the "mockist" fashion.</p> <p>But I'm wondering if even in mockist TDD if one can take mocking too far.</p> <p>Here's an <strong>updated</strong> example in Python-style pseudo-code:</p> <pre><code>def sync_path(self): if self.confirm_or_create_connection(): self.sync(self.dirpath) </code></pre> <p>The confirm_or_create_connection() method creates a connection to a server.</p> <p>I tested a method similar to this in two tests, both of which mock confirm_or_create_connection() and sync() (even though they're both methods in the same class). In one test the mock confirm_or_create_connection() returns True and the test confirms that sync() was called, and in the other the mock confirm_or_create_connection() returns False and the test confirms that sync() was not called.</p> <p>Is this reasonable? Or should I mock the objects that confirm_or_create_connection() and sync() call? (I have other tests of both of these methods that already do this.)</p> <p>Please don't answer the question by explaining that I should be practicing "classical" TDD instead. That's an answer to another question: <a href="https://stackoverflow.com/questions/184666/should-i-practice-mockist-or-classical-tdd">Should I practice mockist or classical TDD?</a></p>
[ { "answer_id": 184806, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 1, "selected": false, "text": "<p><strong>edited for the new example</strong><br>\nTo me it looks like you're stubbing confirm_or_create_connection, you're only interested in defining the return call and you're mocking sync, here you're interested in testing if it's really called. (I'll have to check if my definition of stubbing or mocking is the same as the fowler article you referenced. It's been some time since i've read it and I've been using rhinomocks in c# that might have it's own defenition of these terms :-) )</p>\n\n<p>I think for what you're testing mocking and stubbing those calls is the right way to go. You don't want to test to fail if one of those functions has an error, there are other tests for that. You just want to test the operation of sync_path.</p>\n\n<p>I agree with Avdi that this is kind of smelly. The tests are ok but your class might be doing too much.</p>\n" }, { "answer_id": 184928, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 3, "selected": false, "text": "<p>Personally I think that mocking on self is almost always a code smell. It's testing the implementation rather than the behavior.</p>\n" }, { "answer_id": 294650, "author": "Jeffrey Fredrick", "author_id": 35894, "author_profile": "https://Stackoverflow.com/users/35894", "pm_score": 0, "selected": false, "text": "<p>Can you take mocking too far? I don't know about too far but it can be done badly such that you are actually testing the mocks instead of the code, or worse so that you have brittle tests.</p>\n\n<p>But as long as you're writing good tests — tests that confirm your expected behavior, tests that are helping you write the code — then mock on!</p>\n" }, { "answer_id": 870271, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 2, "selected": false, "text": "<p>Edited for updated sample:</p>\n\n<p>I see now. You have problems testing this class because it has design flaws. This class violates the single responsibility principle. It is doing two things. First, it's managing a connection to a database. It's also syncing.</p>\n\n<p>You need a separate class to manage your database connection. This class will be a dependency of the class under test. The database connecting class can be faked when you unit test the class under test.</p>\n\n<p>Formerly:</p>\n\n<blockquote>\n <p>As a fellow interaction tester,\n consider refactoring if you have a\n need to do this. That class is\n probably doing too much.</p>\n \n <p>Let me put it to you this way: calling\n a private method does not make an\n interaction.</p>\n \n <p>This is one of the main points of TDD.\n When it hurts your design can be\n improved.</p>\n</blockquote>\n" }, { "answer_id": 893894, "author": "Steve Freeman", "author_id": 75123, "author_profile": "https://Stackoverflow.com/users/75123", "pm_score": 1, "selected": false, "text": "<p>Guessing wildly, it looks like the connection activity might belong in another object which should be delegated to, in which case you can mock <em>that</em>. I usually recommend against mocking one part of an object to test another part. It suggests that there are two concepts bolted together.</p>\n" }, { "answer_id": 901882, "author": "Nat", "author_id": 99389, "author_profile": "https://Stackoverflow.com/users/99389", "pm_score": 4, "selected": true, "text": "<p>The technique is called \"mock objects\", not \"mock methods\" for a reason. It encourages designs that divide the system into easily composed, collaborating objects and away from procedural code. The aim is to raise the level of abstraction so that you mostly program by composing objects and rarely write low-level control flow statements.</p>\n" }, { "answer_id": 2298447, "author": "Frank Schwieterman", "author_id": 32203, "author_profile": "https://Stackoverflow.com/users/32203", "pm_score": 0, "selected": false, "text": "<p>Here's a good read on it: \"Principle: Don't modify the SUT\" at <a href=\"http://xunitpatterns.com/Principles%20of%20Test%20Automation.html#Don\" rel=\"nofollow noreferrer\">http://xunitpatterns.com/Principles%20of%20Test%20Automation.html#Don</a></p>\n\n<p>Modifying the class you're testing by mocking or stubbing portions of its implementation is a code smell. The refactoring to get away from it is to move the part you're mocking/stubbing to another class. That said its not always a terrible thing. Its a code smell but its not always inappropriate. For languages like C# or Java where you have good refactoring tools its easy to fix this code smell and I normally would (in C#, assuming Java is similar). I do a lot of development in Lua and Javascript though, where things are a little different. Creating and managing lots of classes in those languages are more difficult, so I am more tolerant of modifying the SUT in tests. Its always something I can fix later once the initial test coverage is there. It does require extra care.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
After reading Martin Fowler's [Mocks Aren't Stubs](http://martinfowler.com/articles/mocksArentStubs.html), I've discovered I've been practicing TDD in the "mockist" fashion. But I'm wondering if even in mockist TDD if one can take mocking too far. Here's an **updated** example in Python-style pseudo-code: ``` def sync_path(self): if self.confirm_or_create_connection(): self.sync(self.dirpath) ``` The confirm\_or\_create\_connection() method creates a connection to a server. I tested a method similar to this in two tests, both of which mock confirm\_or\_create\_connection() and sync() (even though they're both methods in the same class). In one test the mock confirm\_or\_create\_connection() returns True and the test confirms that sync() was called, and in the other the mock confirm\_or\_create\_connection() returns False and the test confirms that sync() was not called. Is this reasonable? Or should I mock the objects that confirm\_or\_create\_connection() and sync() call? (I have other tests of both of these methods that already do this.) Please don't answer the question by explaining that I should be practicing "classical" TDD instead. That's an answer to another question: [Should I practice mockist or classical TDD?](https://stackoverflow.com/questions/184666/should-i-practice-mockist-or-classical-tdd)
The technique is called "mock objects", not "mock methods" for a reason. It encourages designs that divide the system into easily composed, collaborating objects and away from procedural code. The aim is to raise the level of abstraction so that you mostly program by composing objects and rarely write low-level control flow statements.
184,766
<p>I believe the simplest way to request data from a server in XML format is to have a PHP/JSP/ASP.net page which actually generates XML based on HTTP GET params, and to somehow call/load this page from Flex.</p> <p>How exactly can this be achieved using the Flex library classes?</p>
[ { "answer_id": 184787, "author": "MidnightGun", "author_id": 13220, "author_profile": "https://Stackoverflow.com/users/13220", "pm_score": 1, "selected": false, "text": "<p>Never mind, found it: <a href=\"http://livedocs.adobe.com/flex/3/langref/flash/net/URLLoader.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/langref/flash/net/URLLoader.html</a></p>\n" }, { "answer_id": 185061, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 1, "selected": false, "text": "<p>I know you've already found it, but here is some sample code:</p>\n\n<pre><code>public var dataRequest:URLRequest;\npublic var dataLoader:URLLoader;\npublic var allowCache:Boolean;\n\ndataLoader = new URLLoader();\ndataLoader.addEventListener(Event.COMPLETE, onComplete);\ndataLoader.addEventListener(ProgressEvent.PROGRESS, onProgress);\ndataLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);\ndataLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);\ndataLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);\n\ndataRequest = new URLRequest();\ndataRequest.url = \"xmlfilelocation.xml\" + ((this.allowCache) ? \"\" : \"?cachekiller=\" + new Date().valueOf());\n\ndataLoader.load(dataRequest);\n\npublic function onComplete(event:Event):void{\n trace(\"onComplete\");\n}\npublic function onProgress(event:ProgressEvent):void{\n trace(\"onProgress\");\n}\npublic function onIOError(event:IOErrorEvent):void{\n trace(\"onIOError\");\n}\npublic function onSecurityError(event:SecurityErrorEvent):void{\n trace(\"onSecurityError\");\n}\npublic function onHTTPStatus(event:HTTPStatusEvent):void{\n trace(\"onHTTPStatus\");\n}\n</code></pre>\n\n<p>I like to add the \"allowCache\" because Flash/Flex is terrible about caching stuff like this when you don't want it to.</p>\n" }, { "answer_id": 186087, "author": "Laura", "author_id": 5103, "author_profile": "https://Stackoverflow.com/users/5103", "pm_score": 2, "selected": false, "text": "<p>I'd like to add that you can also use <a href=\"http://livedocs.adobe.com/flex/201/langref/mx/rpc/http/mxml/HTTPService.html\" rel=\"nofollow noreferrer\">mx:HTTPService</a>. If you specify the returnFormat attribute, you would get an XML document as opposed to simple text: </p>\n\n<pre><code>&lt;mx:HTTPService resultFormat=\"e4x\" ..../&gt; or &lt;mx:HTTPService resultFormat=\"xml\" .../&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
I believe the simplest way to request data from a server in XML format is to have a PHP/JSP/ASP.net page which actually generates XML based on HTTP GET params, and to somehow call/load this page from Flex. How exactly can this be achieved using the Flex library classes?
I'd like to add that you can also use [mx:HTTPService](http://livedocs.adobe.com/flex/201/langref/mx/rpc/http/mxml/HTTPService.html). If you specify the returnFormat attribute, you would get an XML document as opposed to simple text: ``` <mx:HTTPService resultFormat="e4x" ..../> or <mx:HTTPService resultFormat="xml" .../> ```
184,782
<p>I'm a doing some blackbox testing of a ASP.Net website and I need to test different session timeout scenarios. </p> <p>I'm not sure they fully encapsulated session timeouts. Other then leaving a page open for 20 minutes is there an easier way to force a session timeout?</p>
[ { "answer_id": 184784, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 1, "selected": false, "text": "<p>Recycle the app pool on the server.</p>\n" }, { "answer_id": 184786, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>Add a page to the site and call Session.Abandon()</p>\n" }, { "answer_id": 184791, "author": "Petey", "author_id": 2059, "author_profile": "https://Stackoverflow.com/users/2059", "pm_score": 2, "selected": false, "text": "<p>If you are storing your session information in a cookie, you could try deleting your cookies.</p>\n" }, { "answer_id": 184792, "author": "nportelli", "author_id": 7024, "author_profile": "https://Stackoverflow.com/users/7024", "pm_score": 2, "selected": false, "text": "<p>Make a shorter timeout.</p>\n" }, { "answer_id": 184793, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>Bounce the AppPool and session will be lost.</p>\n\n<p>if you don't have direct IIS access, you can open and save Web.Config to do the same thing (Don't use notepad, it screws up the encoding).</p>\n" }, { "answer_id": 184810, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 2, "selected": false, "text": "<p>You can change the timeout in your webconfig</p>\n\n<pre><code> &lt;authentication mode=\"Forms\"&gt;\n &lt;forms timeout=\"10\" protection=\"All\" slidingExpiration=\"true\" loginUrl=\"~/login.aspx\" cookieless=\"UseCookies\"/&gt;\n &lt;/authentication&gt;\n</code></pre>\n" }, { "answer_id": 375277, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 7, "selected": true, "text": "<p><strong>Decrease the timeout</strong></p>\n\n<p>The easiest and most non-intrusive way to test this is probably to just decrease the timeout to a fairly small number, such as 3 or 5 minutes. This way you can pause for a few minutes to simulate a longer pause without worrying about application restarts or special reset code having any affect on your test results.</p>\n\n<p>You can modify the session state timeout in a few locations - globally (in the web.config located in the config folder for the applicable .NET framework version), or just for your application.</p>\n\n<p>To modify the timeout just for your application, you can add the following to your application's web.config:</p>\n\n<pre><code> &lt;system.web&gt;\n &lt;sessionState timeout=\"60\" /&gt; \n ...\n</code></pre>\n\n<p>Alternatively, you can also modify this same setting for your application through an IIS configuration dialog (I believe you still need to have a web.config defined for your application though, otherwise Edit Configuration will be disabled).</p>\n\n<p>To access this, right-click on your web application in IIS, and navigate to Properties | ASP.NET tab | Edit Configuration | State Management tab | Session timeout (minutes).</p>\n\n<p>Note that you can also manipulate this setting through code - if this is already being done, than the setting in the web.config file will effectively be ignored and you will need to use another technique.</p>\n\n<p><strong>Call Session.Abandon()</strong></p>\n\n<p>A slightly more intrusive technique than setting a low timeout would be to call Session.Abandon(). Be sure to call this from a page separate from your application though, as the session isn't actually ended until all script commands on the current page are processed.</p>\n\n<p>My understanding is that this would be a fairly clean way to test session timeouts without actually waiting for them.</p>\n\n<p><strong>Force an application restart</strong></p>\n\n<p>In a default configuration of session state, you can simulate a session timeout by blowing away the sessions entirely by causing the application to restart. This can be done several ways, a few of which are listed below:</p>\n\n<ul>\n<li>Recycle the app pool through\n\n<ul>\n<li>the IIS MMC snap-in</li>\n<li>the command-line (iisapp /a AppPoolID /r)</li>\n<li>modifying web.config, global.asax, or a dll in the bin directory</li>\n</ul></li>\n<li>Restart IIS through\n\n<ul>\n<li>the IIS MMC snap-in</li>\n<li>services.msc and restarting the IIS Admin service</li>\n<li>the command-line (iisreset)</li>\n</ul></li>\n</ul>\n\n<p>When I mention \"default configuration\", I mean a web application that is configured to use \"InProc\" session state mode. There are others modes that can actually maintain session state even if the web application is restarted (StateServer, SQLServer, Custom).</p>\n\n<p><strong>Tamper with the state tracking mechanism</strong></p>\n\n<p>Assuming your web application isn't configured with a \"cookie-less\" mode (by default, cookies will be used), you could remove the cookie containing the session ID from the client browser.</p>\n\n<p>However, my understanding is that this isn't really simulating a time-out, as the server will still be aware of the session, it just won't see anyone using it. The request without a session ID will simply be treated as an unseen request in need of a new session, which may or may not be what you want to test.</p>\n" }, { "answer_id": 6186860, "author": "Zeeshan Umar", "author_id": 367305, "author_profile": "https://Stackoverflow.com/users/367305", "pm_score": 0, "selected": false, "text": "<p>You have two options:-</p>\n\n<p>1- Decrease the session timeout in web.config.\n2- Restart IIS or Application pool.</p>\n" }, { "answer_id": 18575319, "author": "SkylimitRavindra", "author_id": 2740143, "author_profile": "https://Stackoverflow.com/users/2740143", "pm_score": 3, "selected": false, "text": "<p>The easiest way would be to open the page in two different tab and logout at other tab would automatically expire session in first tab.\nMost of the browsers share session across the tab. So i find it very easy without modifying anything in web.config.\nThis way you could test even if a particular feature is not handling redirect to login when session expires.</p>\n" }, { "answer_id": 30414900, "author": "Mehdi Maujood", "author_id": 819592, "author_profile": "https://Stackoverflow.com/users/819592", "pm_score": 0, "selected": false, "text": "<p>I usually use the ASP .NET session state server. Apart from other benefits during development, I can simply restart the ASP .NET state service to abandon the session. If you're using the state server, simply run services.msc and restart the \"ASP .NET State Service\".</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
I'm a doing some blackbox testing of a ASP.Net website and I need to test different session timeout scenarios. I'm not sure they fully encapsulated session timeouts. Other then leaving a page open for 20 minutes is there an easier way to force a session timeout?
**Decrease the timeout** The easiest and most non-intrusive way to test this is probably to just decrease the timeout to a fairly small number, such as 3 or 5 minutes. This way you can pause for a few minutes to simulate a longer pause without worrying about application restarts or special reset code having any affect on your test results. You can modify the session state timeout in a few locations - globally (in the web.config located in the config folder for the applicable .NET framework version), or just for your application. To modify the timeout just for your application, you can add the following to your application's web.config: ``` <system.web> <sessionState timeout="60" /> ... ``` Alternatively, you can also modify this same setting for your application through an IIS configuration dialog (I believe you still need to have a web.config defined for your application though, otherwise Edit Configuration will be disabled). To access this, right-click on your web application in IIS, and navigate to Properties | ASP.NET tab | Edit Configuration | State Management tab | Session timeout (minutes). Note that you can also manipulate this setting through code - if this is already being done, than the setting in the web.config file will effectively be ignored and you will need to use another technique. **Call Session.Abandon()** A slightly more intrusive technique than setting a low timeout would be to call Session.Abandon(). Be sure to call this from a page separate from your application though, as the session isn't actually ended until all script commands on the current page are processed. My understanding is that this would be a fairly clean way to test session timeouts without actually waiting for them. **Force an application restart** In a default configuration of session state, you can simulate a session timeout by blowing away the sessions entirely by causing the application to restart. This can be done several ways, a few of which are listed below: * Recycle the app pool through + the IIS MMC snap-in + the command-line (iisapp /a AppPoolID /r) + modifying web.config, global.asax, or a dll in the bin directory * Restart IIS through + the IIS MMC snap-in + services.msc and restarting the IIS Admin service + the command-line (iisreset) When I mention "default configuration", I mean a web application that is configured to use "InProc" session state mode. There are others modes that can actually maintain session state even if the web application is restarted (StateServer, SQLServer, Custom). **Tamper with the state tracking mechanism** Assuming your web application isn't configured with a "cookie-less" mode (by default, cookies will be used), you could remove the cookie containing the session ID from the client browser. However, my understanding is that this isn't really simulating a time-out, as the server will still be aware of the session, it just won't see anyone using it. The request without a session ID will simply be treated as an unseen request in need of a new session, which may or may not be what you want to test.
184,813
<p>I have a (Wordpress powered) website, and Google is indexing some of the sub-directories. How can I stop Apache from showing users the directory listing? I know I can edit .htaccess to password-protect a directory, but I would prefer a 403 / custom redirect if possible.</p>
[ { "answer_id": 184820, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 2, "selected": false, "text": "<p>Look at your robots.txt rules, and make sure apache is not serving-up directory listings.</p>\n\n<p>see <a href=\"http://httpd.apache.org/docs/2.0/howto/htaccess.html\" rel=\"nofollow noreferrer\">http://httpd.apache.org/docs/2.0/howto/htaccess.html</a> &amp;&amp; <a href=\"http://www.webmasterworld.com/forum92/5272.htm\" rel=\"nofollow noreferrer\">http://www.webmasterworld.com/forum92/5272.htm</a></p>\n" }, { "answer_id": 184821, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 5, "selected": true, "text": "<p>You need this entry in your <code>.htaccess</code> file:</p>\n\n<pre>Options -Indexes</pre>\n" }, { "answer_id": 184831, "author": "Flory", "author_id": 5551, "author_profile": "https://Stackoverflow.com/users/5551", "pm_score": -1, "selected": false, "text": "<p>Don't know much about Apache but you should do a 404 instead of a 403 if you can because a 403 tells someone that they may have found something interesting.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4812/" ]
I have a (Wordpress powered) website, and Google is indexing some of the sub-directories. How can I stop Apache from showing users the directory listing? I know I can edit .htaccess to password-protect a directory, but I would prefer a 403 / custom redirect if possible.
You need this entry in your `.htaccess` file: ``` Options -Indexes ```
184,853
<p>I swear there used to be a way in X to start capturing all terminal traffic to a file on your host. It may have been a HummingBird extension, but I thought it was standard. Now, I can't find the trick. Am I hallucinating (happens when you get old), or is it possible?<br><br>I'm not talking about 'tee'. I want to be able to send a xterm control-sequence to stdout, giving a file name, and have everthing shown in the window from that time onward saved to the file (until the bookend cancel is issued).</p>
[ { "answer_id": 184867, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 0, "selected": false, "text": "<p>I am a little bit confused by the way you asked your question. First you mention Xterm then X and then terminal, are you simply looking for the \"tee\" (<code>man tee</code>) command? </p>\n" }, { "answer_id": 184905, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 1, "selected": false, "text": "<p>Question is rather vague.</p>\n\n<p>Try looking at:</p>\n\n<ol>\n<li>\"ttyrec/ttyplay\" for recording a text-mode \"movie\" of your terminal session</li>\n<li>\"screen\" for recording a log out stdout of your entire session</li>\n<li>\"tee\" for recording a stdout/stderr of a single command</li>\n</ol>\n" }, { "answer_id": 759017, "author": "andrewdotn", "author_id": 14558, "author_profile": "https://Stackoverflow.com/users/14558", "pm_score": 3, "selected": true, "text": "<p>This feature is called logging and exists in the source code but is disabled by default for security reasons. Do you really want everyone with the ability to write control sequences to your terminal (<em>e.g.</em>, the author of any file you might one day <code>cat</code>) to be able to write arbitrary data to arbitrarily-named files under your account?</p>\n\n<p>For example, an attacker could easily use this functionality to modify your <code>~/.ssh/authorized_keys</code> to grant the attacker access, and change your <code>~/.profile</code> to ping the attacker with your IP address.</p>\n\n<p>That said, if you compile xterm with <code>--enable-logging</code> AND you <code>#define ALLOWLOGFILECHANGES</code>, then according to the <a href=\"http://www.x.org/docs/xterm/ctlseqs.pdf\" rel=\"nofollow noreferrer\">Xterm Control Sequences</a> manual, you will gain access to the following control sequences:</p>\n\n<pre><code>^[[?46h Start logging\n^[[?46l Stop logging\n^[]46;filename\\007 Change log file to `filename`\n</code></pre>\n\n<p>The log file name will by default be called <code>Xterm.log.hostname.yyyy.mm.dd.hh.mm.ss.XXXXXX</code>.</p>\n\n<p>There is also an option to enable logging through a pipe, which is also very dangerous if you allow changing the logger via control sequences. That would also allow anyone to execute their code on your system.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14028/" ]
I swear there used to be a way in X to start capturing all terminal traffic to a file on your host. It may have been a HummingBird extension, but I thought it was standard. Now, I can't find the trick. Am I hallucinating (happens when you get old), or is it possible? I'm not talking about 'tee'. I want to be able to send a xterm control-sequence to stdout, giving a file name, and have everthing shown in the window from that time onward saved to the file (until the bookend cancel is issued).
This feature is called logging and exists in the source code but is disabled by default for security reasons. Do you really want everyone with the ability to write control sequences to your terminal (*e.g.*, the author of any file you might one day `cat`) to be able to write arbitrary data to arbitrarily-named files under your account? For example, an attacker could easily use this functionality to modify your `~/.ssh/authorized_keys` to grant the attacker access, and change your `~/.profile` to ping the attacker with your IP address. That said, if you compile xterm with `--enable-logging` AND you `#define ALLOWLOGFILECHANGES`, then according to the [Xterm Control Sequences](http://www.x.org/docs/xterm/ctlseqs.pdf) manual, you will gain access to the following control sequences: ``` ^[[?46h Start logging ^[[?46l Stop logging ^[]46;filename\007 Change log file to `filename` ``` The log file name will by default be called `Xterm.log.hostname.yyyy.mm.dd.hh.mm.ss.XXXXXX`. There is also an option to enable logging through a pipe, which is also very dangerous if you allow changing the logger via control sequences. That would also allow anyone to execute their code on your system.
184,858
<p>I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this:</p> <pre><code>&lt;a href="#" onclick="foo()"&gt;Click&lt;/a&gt; </code></pre> <p>But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't good for what I'm doing. </p>
[ { "answer_id": 184876, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;a href=\"javascript: foo()\" &gt;Click&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 184877, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 3, "selected": false, "text": "<p>Just make sure to return <code>false</code> from your onclick handler. E.g. <code>foo()</code> should be defined as:</p>\n\n<pre><code>function foo() {\n // ... do stuff\n return false;\n}\n</code></pre>\n\n<p>Someone pointed out in the comments that you may need to change your HTML slightly for that to work:</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"return foo()\"&gt;Click&lt;/a&gt;\n</code></pre>\n\n<p>Or just put it in the HTML:</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"foo(); return false;\"&gt;Click&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 184882, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>return false after calling foo()</p>\n" }, { "answer_id": 184884, "author": "Rob Drimmie", "author_id": 24213, "author_profile": "https://Stackoverflow.com/users/24213", "pm_score": -1, "selected": false, "text": "<p>If you include</p>\n\n<pre><code>return false;\n</code></pre>\n\n<p>from the onclick event, then the page won't load at all. For example:</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"foo();return false;\"&gt;Click&lt;/a&gt;\n</code></pre>\n\n<p>Or in the function itself:</p>\n\n<pre><code>function foo() {\n // other stuff\n return false;\n}\n</code></pre>\n" }, { "answer_id": 184891, "author": "Matt Brunell", "author_id": 24970, "author_profile": "https://Stackoverflow.com/users/24970", "pm_score": -1, "selected": false, "text": "<p>Set the href attribute to execute the javascript. Like this:</p>\n\n<p><code>\n &lt;a href=\"javascript:foo()\"&gt;Click&lt;/a&gt;\n</code></p>\n\n<p>That way all of your a:hover CSS styles work as expected.</p>\n" }, { "answer_id": 184902, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The problem with <code>href=\"#\"</code> is that it will throw the browser to the top of the page. You can do:</p>\n\n<pre><code>&lt;a href=\"javascript:foo()\"&gt;clicky&lt;/a&gt;\n</code></pre>\n\n<p>Though more people are recommending against doing that (separation of layers). A better way, using <a href=\"http://www.prototypejs.org/api/event\" rel=\"nofollow noreferrer\">Prototype</a> (just as easy in JQuery, et al):</p>\n\n<pre><code>&lt;a id=\"foo\" href=\"#\"&gt;clicky&lt;/a&gt;\n\n$('foo').observe('click', function(evt) { \n foo();\n evt.stop(); // keeps it from navigating to the href url\n}); \n</code></pre>\n" }, { "answer_id": 184908, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 2, "selected": false, "text": "<p>First, there are two ways to setup the href - you can either do as you have stated above with the href referencing a '#', or you may set the href to reference \"javascript:;\"</p>\n\n<p>Secondly, I always recommend keeping the JavaScript in an external file and then managing the event handler there. Assuming you'd like to set this up whenever the page loads, you could do something like this:</p>\n\n<pre><code>window.onload = {\n var myLink = document.getElementById('myLinkID');\n myLink.onclick = function(evt) {\n var evt = (evt) ? evt : ((event) ? event : null); // for cross-browser issues\n evt.preventDefault();\n evt.stopPropagation();\n foo();\n }\n}\n</code></pre>\n" }, { "answer_id": 184916, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 5, "selected": true, "text": "<p>Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. Example... Let's say you have the following search link:</p>\n\n<pre><code>&lt;a href=\"search.php\" id=\"searchLink\"&gt;Search&lt;/a&gt;\n</code></pre>\n\n<p>You can always do the following:</p>\n\n<pre><code>var link = document.getElementById('searchLink');\n\nlink.onclick = function() {\n try {\n // Do Stuff Here \n } finally {\n return false;\n }\n};\n</code></pre>\n\n<p>That way, people with javascript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality.</p>\n\n<p><strong>Edit:</strong> As <a href=\"https://stackoverflow.com/users/9021/nickf\">nickf</a> pointed out in comment #2, a try and catch will prevent the link to follow if there is an error in your handler.</p>\n" }, { "answer_id": 185009, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<p>A lot of confusion is around the use of a-tags because they cross-browser support the :hover pseudo-css-selector ...</p>\n\n<p>Therefore it's often obvious to use an a-tag, as it would render differently according to different stages of mouse-hover ...</p>\n\n<p>Some would claim that the functionality built into the :hover pseudo-tag shouldn't be available at all, as the W3C intention is to separate content, visual presentation and functionality in the three parts of dynamic html; html, css and javascript.</p>\n\n<p>But for now we're stuck with it, and for the time being it is functional to use a-tags in a lot of ways, as they accomplish tasks in a simple way, and it is right-forward cross-browser !-)</p>\n\n<p>But that means that you sometimes have to disable the default behavior of those link-tags, and that means that you have to make the onclick-event return false, when it doesn't make sense to change the contents of the current document ...</p>\n\n<p>However very good examples of using the dismissing of default behavior can be made, an example could be to provide a popup with certain properties even if the user has disabled the use of javascript:</p>\n\n<pre><code>&lt;a href=\"http://en.wikipedia.org/wiki/Css\" target=\"_blank\" onclick=\"window.open(this.href,'_blank','width=600,height=450,status=no');return false;\"&gt;Show wikipedia css&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 185020, "author": "Tivac", "author_id": 7847, "author_profile": "https://Stackoverflow.com/users/7847", "pm_score": -1, "selected": false, "text": "<p>Beware just using </p>\n\n<p><code>&lt;a href=\"#\"&gt;Click&lt;/a&gt;</code></p>\n\n<p>as it can cause an obnoxious <a href=\"http://webbugtrack.blogspot.com/2007/09/bug-223-magical-http-get-requests-in.html\" rel=\"nofollow noreferrer\">IE6 problem</a>. </p>\n\n<p>I always recommend using an anchor that points to nothing. I like to use this</p>\n\n<p><code>&lt;a href=\"#MAGIC\"&gt;Click&lt;/a&gt;</code></p>\n\n<p>because it makes me laugh.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4915/" ]
I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this: ``` <a href="#" onclick="foo()">Click</a> ``` But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't good for what I'm doing.
Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. Example... Let's say you have the following search link: ``` <a href="search.php" id="searchLink">Search</a> ``` You can always do the following: ``` var link = document.getElementById('searchLink'); link.onclick = function() { try { // Do Stuff Here } finally { return false; } }; ``` That way, people with javascript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality. **Edit:** As [nickf](https://stackoverflow.com/users/9021/nickf) pointed out in comment #2, a try and catch will prevent the link to follow if there is an error in your handler.
184,863
<p>To save some typing and clarify my code, is there a standard version of the following method?</p> <pre><code>public static boolean bothNullOrEqual(Object x, Object y) { return ( x == null ? y == null : x.equals(y) ); } </code></pre>
[ { "answer_id": 184942, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 5, "selected": false, "text": "<p>if by some chance you are have access to the Jakarta Commons library there is <a href=\"http://commons.apache.org/lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#equals(java.lang.Object,%20java.lang.Object)\" rel=\"noreferrer\">ObjectUtils.equals()</a> and lots of other useful functions.</p>\n\n<p>EDIT: misread the question initially</p>\n" }, { "answer_id": 9363676, "author": "Kdeveloper", "author_id": 306276, "author_profile": "https://Stackoverflow.com/users/306276", "pm_score": 9, "selected": true, "text": "<p>With Java 7 you can now directly do a null safe equals:</p>\n<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html\" rel=\"noreferrer\">Objects.equals(x, y)</a></p>\n<p>(The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7)</p>\n" }, { "answer_id": 32725394, "author": "Sam Berry", "author_id": 1756430, "author_profile": "https://Stackoverflow.com/users/1756430", "pm_score": 3, "selected": false, "text": "<p>If you are using &lt;1.7 but have Guava available: <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Objects.html#equal(java.lang.Object,%20java.lang.Object)\" rel=\"noreferrer\"><code>Objects.equal(x, y)</code></a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
To save some typing and clarify my code, is there a standard version of the following method? ``` public static boolean bothNullOrEqual(Object x, Object y) { return ( x == null ? y == null : x.equals(y) ); } ```
With Java 7 you can now directly do a null safe equals: [Objects.equals(x, y)](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html) (The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7)
184,864
<p>Has anyone had good experiences of talking direct to RPG programs running on a V5R4 iSeries machine from Java? If so, what are the recommendations of the community, and what pitfalls should I try to avoid?</p> <p>From the various pieces of literature and spike solutions I have attempted it looks as though we can use ProgramCallBeans (either through PCML or xPCML), talking to the DataQueues (for asynchronous comms), or even JNI.</p> <p>I'm looking for something that's robust, performant, quick to develop, easy to maintain, and easy to test (aren't we all!?!).</p>
[ { "answer_id": 185164, "author": "KC Baltz", "author_id": 9910, "author_profile": "https://Stackoverflow.com/users/9910", "pm_score": 1, "selected": false, "text": "<p>We just use JDBC and stored procedures. The stored procedure calls the RPG instead of running SQL. I'm not an RPG programmer, but it seems like a very simple interface. DataQueues are OK, but they aren't as robust as something like JMS (no guaranteed delivery). </p>\n" }, { "answer_id": 187233, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 1, "selected": false, "text": "<p>It is quite simple to call java methods directly from RPG. I am not sure exactly what you are trying to do, I have made calls directly to java methods several times.</p>\n\n<p>For an example of how this is done. Take a look at <a href=\"http://mowyourlawn.com/html/RPGMail.php\" rel=\"nofollow noreferrer\">RPGMail</a>. You can look at the source and see how Aaron used RPG to connect to JavaMail.</p>\n" }, { "answer_id": 192140, "author": "carson", "author_id": 25343, "author_profile": "https://Stackoverflow.com/users/25343", "pm_score": 2, "selected": false, "text": "<p>You should look at <a href=\"http://jt400.sourceforge.net/\" rel=\"nofollow noreferrer\">JTOpen</a>. It is fairly easy to use that to do what you want to do. Here is an example someone has put together: <a href=\"http://codenewbie.com/forum/java/1921-program-call-as400-using-jtopen.html\" rel=\"nofollow noreferrer\">program call to as400 using jtopen</a></p>\n" }, { "answer_id": 222558, "author": "Tracy Probst", "author_id": 22770, "author_profile": "https://Stackoverflow.com/users/22770", "pm_score": 4, "selected": false, "text": "<p>I suggest using IBM's Java Toolbox for Java. Put the JT400.jar into your classpath (or JT400Ntv.jar if the Java is running on the iSeries). I've used both the ProgramCall class and the CommandCall classes.</p>\n\n<p>The com.ibm.as400.access.CommandCall class is easy to use. It has a simple constructor that you pass a com.ibm.as400.access.AS400 class to. Then just use the run method like this:</p>\n\n<pre><code>CommandCall command = new CommandCall(as400);\ncommand.run(\"CPYF FROMFILE(BLAH) TOFILE(BLAHBLAH) CRTFILE(*YES)\");\n</code></pre>\n\n<p>Of course, you wouldn't use that particular CL command, but you get the idea. When using the CommandCall class, it's always a good idea to process any messages that came from the command. In the one program I use this for, I display the messages to the user in a textbox on their screen like this:</p>\n\n<pre><code>AS400Message[] messageList = command.getMessageList();\nfor (int i=0;i &lt; messageList.length;i++) {\nString sMessageText = messageList[i].getText();\n sMessage+=sMessageText + \"\\n\";\n}\n</code></pre>\n\n<p>The com.ibm.as400.access.ProgramCall class takes more work, but it allows you to access the returned parameters. I use this one more often because I'm usually calling existing RPG worker programs that return values. For this, define a com.ibm.as400.access.ProgramParameter array. When you pass parameters to a program from Java, remember to convert them to AS/400-friendly values using a class like com.ibm.as400.access.AS400Text. The details of the ProgramCall command are better researched using IBM's documentation: <a href=\"http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=/rzahh/page1.htm\" rel=\"noreferrer\">http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=/rzahh/page1.htm</a></p>\n" }, { "answer_id": 263103, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I've had some success with PCML documents. I decided to use PCML since encoding the commandcall into a string when passing parameters to an RPG program can get really ugly.</p>\n\n<p>PCML allows you to somewhat transparently pass java data types to an rpg program as a parameter. The drawback is that the xml in the PCML doc becomes a static interface and must be updated if the program is ever updated. With the right build tools, it might be pretty straightforward to automate the update of the pcml xml, but right now I'm doing this manually.</p>\n\n<p>I've used this approach when the rpg program needs to be called from java, and the logic flow is controlled by the java program.</p>\n\n<p>In a case where the logic flow was controlled by an rpg program, I've used dataqueues for both synchronous and asynchronous calls to java. This required writing a significant amount of code to standardize on how to read and write to dataqueues in a coordinated manner from different programming languages</p>\n" }, { "answer_id": 1678598, "author": "Brian", "author_id": 203190, "author_profile": "https://Stackoverflow.com/users/203190", "pm_score": 0, "selected": false, "text": "<p>Hmm, I'm new here and would vote KC Baltz answer up, but cannot yet. Stored procedures are the way to go. I've used JT open to call programs natively and found issues with the number of parms that could be passed, issues with data types, etc. Once you have an SQL procedure wrapper around your program you'll find the Java support for SQL to be far superior than the java support for native 400 calls.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26283/" ]
Has anyone had good experiences of talking direct to RPG programs running on a V5R4 iSeries machine from Java? If so, what are the recommendations of the community, and what pitfalls should I try to avoid? From the various pieces of literature and spike solutions I have attempted it looks as though we can use ProgramCallBeans (either through PCML or xPCML), talking to the DataQueues (for asynchronous comms), or even JNI. I'm looking for something that's robust, performant, quick to develop, easy to maintain, and easy to test (aren't we all!?!).
I suggest using IBM's Java Toolbox for Java. Put the JT400.jar into your classpath (or JT400Ntv.jar if the Java is running on the iSeries). I've used both the ProgramCall class and the CommandCall classes. The com.ibm.as400.access.CommandCall class is easy to use. It has a simple constructor that you pass a com.ibm.as400.access.AS400 class to. Then just use the run method like this: ``` CommandCall command = new CommandCall(as400); command.run("CPYF FROMFILE(BLAH) TOFILE(BLAHBLAH) CRTFILE(*YES)"); ``` Of course, you wouldn't use that particular CL command, but you get the idea. When using the CommandCall class, it's always a good idea to process any messages that came from the command. In the one program I use this for, I display the messages to the user in a textbox on their screen like this: ``` AS400Message[] messageList = command.getMessageList(); for (int i=0;i < messageList.length;i++) { String sMessageText = messageList[i].getText(); sMessage+=sMessageText + "\n"; } ``` The com.ibm.as400.access.ProgramCall class takes more work, but it allows you to access the returned parameters. I use this one more often because I'm usually calling existing RPG worker programs that return values. For this, define a com.ibm.as400.access.ProgramParameter array. When you pass parameters to a program from Java, remember to convert them to AS/400-friendly values using a class like com.ibm.as400.access.AS400Text. The details of the ProgramCall command are better researched using IBM's documentation: <http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=/rzahh/page1.htm>
184,878
<h2>Intro:</h2> <p>I successfully implemented a WCF Service hosted in a Windows Service a few days ago. The community here at StackOverflow helped me with <a href="https://stackoverflow.com/questions/167852/wsdl-url-for-a-wcf-service-basichttpbinding-hosted-inside-a-windows-service">the WSDL exposure here</a>. I thank you once again. However recently I found out that there is another potential client for this service this time located on the same machine as the service and this lead me to think I should add another endpoint with the namedPipesBinding.</p> <p>Named pipes seem to be the best solution for intra-machine communication as far as I am concerned. <strong>Please</strong> correct me if this is wrong.</p> <h2>Problem:</h2> <p>I need to expose another endpoint for the same service/contract but this time using a netNamedPipeBinding. However I really don't understand how do I can then add a service reference from a client. Foolishly after adding </p> <pre><code>&lt;endpoint address="net.pipe://localhost/OfficeService" binding="netNamedPipeBinding" contract="netBridge.Development.OfficeService.IWordService" bindingConfiguration="localBinding" /&gt; </code></pre> <p>I have tried to add a service reference in a Windows Forms Application located on the same machine typing the net.pipe://.... url. It didn't work. I must mention I have removed the mex (MetaData Exchange) endpoint earlier because I considered it not necessary.</p> <ol> <li>Is this mex endpoint necessary for named pipes endpoint binding discovery?</li> <li>How should I add a service reference in the client app to the named pipe endpoint?</li> </ol>
[ { "answer_id": 185005, "author": "James Bender", "author_id": 22848, "author_profile": "https://Stackoverflow.com/users/22848", "pm_score": 5, "selected": true, "text": "<p>Your endpoint looks fine, although I'm curious about what's in localBinding...</p>\n\n<p>Sounds like the easiest option is to just change the endpoint configuration on the named pipes client to match your service endpoint. The client shouldn't care as long as it's the only endpoint in the clients config file. Otherwise you'll have to add names to your endpoints and have the client pick a specific one when you new-up the proxy object.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 1017600, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>the mex endpoint is necessary during development as it provides an http location where the wsdl is built. the wsdl describes to the client how to communicate with the server through named pipes, or TCP/IP, or anything else. once the client app has built the proxy to the named pipes binding and set up the configuration, the mex endpoint is no longer necessary. hence, the mex endpoint can be removed prior to deployment through the environments if desired. </p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
Intro: ------ I successfully implemented a WCF Service hosted in a Windows Service a few days ago. The community here at StackOverflow helped me with [the WSDL exposure here](https://stackoverflow.com/questions/167852/wsdl-url-for-a-wcf-service-basichttpbinding-hosted-inside-a-windows-service). I thank you once again. However recently I found out that there is another potential client for this service this time located on the same machine as the service and this lead me to think I should add another endpoint with the namedPipesBinding. Named pipes seem to be the best solution for intra-machine communication as far as I am concerned. **Please** correct me if this is wrong. Problem: -------- I need to expose another endpoint for the same service/contract but this time using a netNamedPipeBinding. However I really don't understand how do I can then add a service reference from a client. Foolishly after adding ``` <endpoint address="net.pipe://localhost/OfficeService" binding="netNamedPipeBinding" contract="netBridge.Development.OfficeService.IWordService" bindingConfiguration="localBinding" /> ``` I have tried to add a service reference in a Windows Forms Application located on the same machine typing the net.pipe://.... url. It didn't work. I must mention I have removed the mex (MetaData Exchange) endpoint earlier because I considered it not necessary. 1. Is this mex endpoint necessary for named pipes endpoint binding discovery? 2. How should I add a service reference in the client app to the named pipe endpoint?
Your endpoint looks fine, although I'm curious about what's in localBinding... Sounds like the easiest option is to just change the endpoint configuration on the named pipes client to match your service endpoint. The client shouldn't care as long as it's the only endpoint in the clients config file. Otherwise you'll have to add names to your endpoints and have the client pick a specific one when you new-up the proxy object. Good luck!
184,927
<p>I have a webapp which resizes its window to exactly fit its contents:</p> <pre><code>window.resizeTo(200,300) </code></pre> <p>People do like having the page fit its window in this way. However with Firefox the next browser window the user opens comes up at the same size, which is ridiculously small.</p> <p>Is there a way to tell Firefox to resize the current window, but not change its notion of how large subsequent windows should be?</p>
[ { "answer_id": 184964, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>People do like having the page fit its window in this way.</p>\n</blockquote>\n\n<p><em>Which</em> people?! I'd be seriously annoyed if a web page did anything to the size of my browser window. Fortunately, FF also allows users to disable moving or resizing existing windows, a feature i've taken advantage of for several years. </p>\n\n<p>You should be able to open a <em>new</em> window at a specific size using <a href=\"http://developer.mozilla.org/en/DOM/window.open\" rel=\"nofollow noreferrer\"><code>window.open</code></a>, so you could use that... or better yet, just allow your document to resize / reflow to fit into whatever window size the user prefers.</p>\n" }, { "answer_id": 184990, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 3, "selected": true, "text": "<p>Two different questions at work here:</p>\n\n<p><strong>1. Specifying Window Dimensions-</strong></p>\n\n<p>Specifying window attributes using <strong>window.open</strong> will not affect the dimensions of other windows.<br>\nYou are getting the <strong>expected behavior</strong> from Firefox with regards to the resizeTo function.</p>\n\n<p><strong>2. The User Experience-</strong></p>\n\n<p>What users value first and foremost is <strong>maintaining control</strong> of their environment and your product. It's important to let them resize their browser windows. The browser is an application on their desktop machine, and most windowed operating systems give the user general control over the size and placement of windows. Controlling the size of the window is a step into their <strong>personal workspace</strong>.</p>\n\n<p>I'm in agreement with @Shog9, that you should reconsider your use of window.resizeTo.. It's probably not appropriate to <strong>force the window</strong> to any particular size, except perhaps in the case of a <strong>popup</strong>. Using <a href=\"http://search.atomz.com/search/?sp-q=liquid+layout&amp;x=0&amp;y=0&amp;sp-a=sp1002d27b&amp;sp-f=ISO-8859-1&amp;sp-p=All&amp;sp-k=All\" rel=\"nofollow noreferrer\"><strong>Liquid layouts</strong></a> may help you achieve an acceptable <strong>design for any reasonable window dimension</strong>.</p>\n" }, { "answer_id": 185122, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>Argh, I have a weather site doing that: trying to spawn a popup (which ends being a new tab) and resizing it (thus resizing the whole Firefox browser!).</p>\n\n<p>No need to say I hate it.</p>\n\n<p>Some popups are blocked, others manage to be displayed as popup, others go to a new tab. It depends on the method used to spawn them and the browser/extensions settings. Nearly impossible to control, even less in a cross-browser way.</p>\n\n<p>The modern way (still very annoying for ads!) is to do div overlays, a bit less intrusive. Of course, it might not suit every need.</p>\n" }, { "answer_id": 185415, "author": "user21582", "author_id": 21582, "author_profile": "https://Stackoverflow.com/users/21582", "pm_score": 1, "selected": false, "text": "<p>The only way to do it as one of the poster already mentioned is to set width and height when you open new popup by window.open - window.open('<a href=\"http://www.google.com\" rel=\"nofollow noreferrer\">http://www.google.com</a>', 'Test', 'width=800, height=800'); \nWindow.resizeTo never worked in Firefox for whatever reason, political ot technical. \nAnd apparently Firefox developers managed to broke window.open() in Firefox 3.01, refer to this blog post - \n<a href=\"http://tough-to-find.blogspot.com/2008/07/firefox-301-breaks-windowopen-width.html\" rel=\"nofollow noreferrer\">http://tough-to-find.blogspot.com/2008/07/firefox-301-breaks-windowopen-width.html</a> </p>\n" }, { "answer_id": 185436, "author": "user21582", "author_id": 21582, "author_profile": "https://Stackoverflow.com/users/21582", "pm_score": 2, "selected": false, "text": "<p>Just want to add that your best shot is to avoid using window.open and use instead some sort of LightWindow framework - much nicer, behaves the same on all browsers and not affected by browser options.\nYou can see a sample framework here <a href=\"http://www.stickmanlabs.com/lightwindow/\" rel=\"nofollow noreferrer\">http://www.stickmanlabs.com/lightwindow/</a> </p>\n" }, { "answer_id": 195142, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 2, "selected": false, "text": "<p>Strongly agree that in nearly every case, sites that resize the viewport totally suck. </p>\n\n<p>The size of the app window is for the user to decide, and not for web site owners to screw with. </p>\n\n<p>In very rare cases there may be a good argument for it, or a client might just insist on it cos \"they know better\", but it always sucks. </p>\n\n<p>It is a huge annoyance for most users, especially when you have 17 tabs open at 1600 px wide, and some print designer decreed that the next tab you open, should force all your other ones to 300 px wide. </p>\n\n<p>It is much more user friendly to use something like thick/light/grey/slim-box techniques. </p>\n\n<p>I just find alternative web sites, or run a greasemonkey script to avoid sites doing that. </p>\n\n<p>Just had to rant about that. Sorry.</p>\n" }, { "answer_id": 8425081, "author": "KSev", "author_id": 1042253, "author_profile": "https://Stackoverflow.com/users/1042253", "pm_score": 0, "selected": false, "text": "<p>Here's some related information that may help users reading this post.</p>\n\n<p>Firefox has been pressured to remove support for window.resizeTo, and it appears for a short while did. See\n<a href=\"http://kb.mozillazine.org/Resizing_oversize_window#JavaScript_no_longer_allowed_to_resize_windows\" rel=\"nofollow\">http://kb.mozillazine.org/Resizing_oversize_window#JavaScript_no_longer_allowed_to_resize_windows</a></p>\n\n<p>You can disable window resizing in Firefox:\n<a href=\"http://www.howtogeek.com/howto/internet/firefox/disable-web-site-window-resizing-in-firefox/\">http://www.howtogeek.com/howto/internet/firefox/disable-web-site-window-resizing-in-firefox/</a></p>\n\n<p>If you've enabled JavaScript window resizing and it's still not working, then you probably have Firebug installed. Disable Firebug and restart Firefox, and window.resizeTo will function again.\nSee here: <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=565541#c47\" rel=\"nofollow\">https://bugzilla.mozilla.org/show_bug.cgi?id=565541#c47</a></p>\n\n<p>As for whether window resizing should occur, I can't think of many cases, but I know of one so I'll share it. I code a help window that has an optional navigation pane. I have a button that allows users to show/hide the navigation pane. When they show it, I resize the window for them to allow space for the navigation pane. In this case it's user initiated, so it doesn't annoy users. However, disabling resizeTo would make that impossible and thus diminish the user experience (in this case). What it boils down to in most cases is that most tools can be used for good or bad. The more considerate people are, the less problem there is with cool tools.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
I have a webapp which resizes its window to exactly fit its contents: ``` window.resizeTo(200,300) ``` People do like having the page fit its window in this way. However with Firefox the next browser window the user opens comes up at the same size, which is ridiculously small. Is there a way to tell Firefox to resize the current window, but not change its notion of how large subsequent windows should be?
Two different questions at work here: **1. Specifying Window Dimensions-** Specifying window attributes using **window.open** will not affect the dimensions of other windows. You are getting the **expected behavior** from Firefox with regards to the resizeTo function. **2. The User Experience-** What users value first and foremost is **maintaining control** of their environment and your product. It's important to let them resize their browser windows. The browser is an application on their desktop machine, and most windowed operating systems give the user general control over the size and placement of windows. Controlling the size of the window is a step into their **personal workspace**. I'm in agreement with @Shog9, that you should reconsider your use of window.resizeTo.. It's probably not appropriate to **force the window** to any particular size, except perhaps in the case of a **popup**. Using [**Liquid layouts**](http://search.atomz.com/search/?sp-q=liquid+layout&x=0&y=0&sp-a=sp1002d27b&sp-f=ISO-8859-1&sp-p=All&sp-k=All) may help you achieve an acceptable **design for any reasonable window dimension**.
184,970
<p>I am using partial classes to split some functionality between 2 files, but I am getting an error. What am I doing wrong?</p> <p>A1.cs:</p> <pre><code>private partial class A { private string SomeProperty { get { return "SomeGeneratedString"; } } } </code></pre> <p>A2.cs:</p> <pre><code>private partial class A { void SomeFunction() { //trying to access this.SomeProperty produces the following compiler error, at least with C# 2.0 //error CS0117: 'A' does not contain a definition for 'SomeProperty' } } </code></pre>
[ { "answer_id": 184975, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 6, "selected": true, "text": "<p>Are the two partial classes in the same namespace? That could be an explanation.</p>\n" }, { "answer_id": 184979, "author": "Matt Brunell", "author_id": 24970, "author_profile": "https://Stackoverflow.com/users/24970", "pm_score": 3, "selected": false, "text": "<p>different namespace?</p>\n" }, { "answer_id": 184987, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<p>I think it's because you're declaring your class as \"private\". Try changing the modifier to \"internal\" so that the two \"halves\" of the class can \"see\" each other within the same assembly.</p>\n" }, { "answer_id": 184991, "author": "John Kraft", "author_id": 7495, "author_profile": "https://Stackoverflow.com/users/7495", "pm_score": 1, "selected": false, "text": "<p>The error I get is:</p>\n\n<blockquote>Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal</blockquote>\n\n<p>I'm guessing it's a namespace issue as previously stated.</p>\n" }, { "answer_id": 185055, "author": "Troy Howard", "author_id": 19258, "author_profile": "https://Stackoverflow.com/users/19258", "pm_score": 3, "selected": false, "text": "<p>At first, I was unable to reproduce your error. </p>\n\n<p>When these partial classes are defined alone, inside a namespace, the private keyword causes the build to fail with \"Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal\"... </p>\n\n<p>If I keep them private and nest them within another class, everything works fine.</p>\n\n<p>I can reproduce your error only when, in one file, I have part of the class nested inside another class, and in another file, I do NOT nest the class, and then remove the private keyword... like this:</p>\n\n<p>Class1.cs:</p>\n\n<pre><code>namespace stackoverflow.answers\n{\n public class Foo\n {\n private partial class Bar\n {\n private string SomeProperty { get { return \"SomeGeneratedString\"; } }\n }\n }\n}\n</code></pre>\n\n<p>Class2.cs:</p>\n\n<pre><code>namespace stackoverflow.answers\n{\n partial class Bar\n {\n void SomeFunction()\n {\n string bar = this.SomeProperty;\n }\n } \n}\n</code></pre>\n\n<p>I also get the error you described if the namespaces differ. </p>\n\n<p>Please post the entire code for the solution, because the provided code is invalid C# syntax, and can't be looked into without more context. </p>\n" }, { "answer_id": 3988991, "author": "sada", "author_id": 483201, "author_profile": "https://Stackoverflow.com/users/483201", "pm_score": 0, "selected": false, "text": "<p>I analyze your code. you declared partial class as nested class this is cause to show error. why bcz partial class will not declare as nested class the parial keyword is split into ultiple files so, every file nae is same when you declared in nested class it will not recognize.</p>\n" }, { "answer_id": 31831949, "author": "Andrey K.", "author_id": 2772330, "author_profile": "https://Stackoverflow.com/users/2772330", "pm_score": 2, "selected": false, "text": "<p><strong>Edit:</strong></p>\n\n<p>solution: build action -> Complile, nothing else</p>\n\n<p>I'll try to be more specific:</p>\n\n<p>I had a class shared among 3 partial classes in 3 different files. At one moment a function call (from one part, of a function declared in other part) started showing error \"does not exist in current context\". It took me long until some guy <a href=\"https://ru.stackoverflow.com/questions/439998/%D0%9D%D0%B5-%D0%B2%D0%B8%D0%B4%D0%BD%D0%B0-partial-%D1%81%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D0%BB%D1%8F%D1%8E%D1%89%D0%B0%D1%8F-%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B0-namespase-%D0%BE%D0%B4%D0%B8%D0%BD-%D0%B8-%D1%82%D0%BE%D1%82-%D0%B6%D0%B5\">helped</a> me to figure out that accidentally i set the build action of the file with one part to \"EmbeddedResourse\" instead of \"Compile\".</p>\n\n<p>To switch build action you should right click on file in solution explorer, then choose properties. Then change the build action.</p>\n\n<p>This question is old, and my answer is not exactly helpful in this very case. But it may be helpful in one other very rare case related to partial classes. Sorry if my English is not clear.</p>\n" }, { "answer_id": 45292702, "author": "Ram", "author_id": 193061, "author_profile": "https://Stackoverflow.com/users/193061", "pm_score": 5, "selected": false, "text": "<p>Same answer as @Andrey K but in simple terms</p>\n\n<p><strong>Set the build action of all your partial classes to 'Compile' using the 'Properties' windows of each of those files</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/eLv99.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eLv99.png\" alt=\"Properties window -&gt; Build action property\"></a></p>\n" }, { "answer_id": 51361703, "author": "Vic Seedoubleyew", "author_id": 2873507, "author_profile": "https://Stackoverflow.com/users/2873507", "pm_score": 0, "selected": false, "text": "<p>A corner case where additional help can save you time is if you are using a partial class to complement a Run-time Text Template's generated class.</p>\n\n<p>Chances are that the problem is indeed that your partial class' namespace is different from the namespace of the generated part of that class. To check that, simply look at the generated code.</p>\n\n<p>To fix that, you need to edit the <code>.csproj</code> file for your project, and in the section about that template, add the <code>&lt;ClassNamespace&gt;</code> tag:</p>\n\n<pre><code>&lt;Content Include=\"MyTemplate.tt\"&gt;\n &lt;Generator&gt;TextTemplatingFilePreprocessor&lt;/Generator&gt;\n &lt;ClassNamespace&gt;My.Namespace&lt;/ClassNamespace&gt;\n &lt;LastGenOutput&gt;MyTemplate.cs&lt;/LastGenOutput&gt;\n&lt;/Content&gt;\n</code></pre>\n" }, { "answer_id": 53917143, "author": "Anton Andreev", "author_id": 422894, "author_profile": "https://Stackoverflow.com/users/422894", "pm_score": 1, "selected": false, "text": "<p>All the files should be in the same folder.</p>\n" }, { "answer_id": 64157415, "author": "Eric Ouellet", "author_id": 452845, "author_profile": "https://Stackoverflow.com/users/452845", "pm_score": -1, "selected": false, "text": "<p>Just for reference (VS 2020)... Error CS0103 =&gt; All same but different folder.</p>\n<p>But classes should have same namespace AND ALSO BE in same folder !!!</p>\n<p>Although they could be defined in the same namespace, both files should be in the same folder. I know that the folder structure should reflect the namespace but for clarity between the generated code and my added code, I wanted to separate by folder, but it does not works.</p>\n" }, { "answer_id": 70267521, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 0, "selected": false, "text": "<p>Same namespace in textual context just a <strong>different case</strong> on the words; which actually puts them into different compiler namespaces.</p>\n<hr />\n<h2>Example</h2>\n<p>Note the case of <code>O</code> in <strong>overflow</strong>.</p>\n<h3>File 1:</h3>\n<pre><code>namespace StackOverflow {\npublic partial class MyVM\n</code></pre>\n<h3>File 2:</h3>\n<pre><code>namespace Stackoverflow {\npublic partial class MyVM\n</code></pre>\n<p>Turns out somewhere in the past ten years my default project name became different that my original project name, but only in case. Uggg.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
I am using partial classes to split some functionality between 2 files, but I am getting an error. What am I doing wrong? A1.cs: ``` private partial class A { private string SomeProperty { get { return "SomeGeneratedString"; } } } ``` A2.cs: ``` private partial class A { void SomeFunction() { //trying to access this.SomeProperty produces the following compiler error, at least with C# 2.0 //error CS0117: 'A' does not contain a definition for 'SomeProperty' } } ```
Are the two partial classes in the same namespace? That could be an explanation.
184,985
<p>I seem to be having an issue with iPhone SDK 2.1 in as far as being able to establish a relationship between a ViewController and a View window. In as far as a Cocoa Touch Class, I went forward and added a <code>UIViewController</code> subclass. I made sure that the target is part of the existing project. Right afterwards I added a User Interfaces -> View XIB. Within the <code>UIViewController</code> I have some straight forward code I literally copy/pasted from sample code elsewhere:</p> <p>EditViewController.h:</p> <pre><code>@interface EditorViewController : UIViewController &lt;UITextFieldDelegate&gt; { UITextField *field; } @property(nonatomic, retain) IBOutlet UITextField *field; @end </code></pre> <p>EditViewController.m</p> <pre><code>#import "EditorViewController.h" @implementation EditorViewController - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void)dealloc { [super dealloc]; } @end </code></pre> <p>As you can tell, it doesn't do much. Now when I click my new xib, and reference a class identity with <code>EditorViewController</code>, no auto complete happens, which to me implies that it has no such awareness of a <code>EditorViewClass</code>. When I attempt to control+click from the view to File's Owners, I get nada.</p> <p>What are some of the possible idiosyncrasies in this process that I'm overlooking that's not allowing me to outlet my view to a controller?</p> <p>How would I also ensure that my User Interface View XIB is associated with the project besides seeing the project name checked off as a Target?</p>
[ { "answer_id": 184975, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 6, "selected": true, "text": "<p>Are the two partial classes in the same namespace? That could be an explanation.</p>\n" }, { "answer_id": 184979, "author": "Matt Brunell", "author_id": 24970, "author_profile": "https://Stackoverflow.com/users/24970", "pm_score": 3, "selected": false, "text": "<p>different namespace?</p>\n" }, { "answer_id": 184987, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<p>I think it's because you're declaring your class as \"private\". Try changing the modifier to \"internal\" so that the two \"halves\" of the class can \"see\" each other within the same assembly.</p>\n" }, { "answer_id": 184991, "author": "John Kraft", "author_id": 7495, "author_profile": "https://Stackoverflow.com/users/7495", "pm_score": 1, "selected": false, "text": "<p>The error I get is:</p>\n\n<blockquote>Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal</blockquote>\n\n<p>I'm guessing it's a namespace issue as previously stated.</p>\n" }, { "answer_id": 185055, "author": "Troy Howard", "author_id": 19258, "author_profile": "https://Stackoverflow.com/users/19258", "pm_score": 3, "selected": false, "text": "<p>At first, I was unable to reproduce your error. </p>\n\n<p>When these partial classes are defined alone, inside a namespace, the private keyword causes the build to fail with \"Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal\"... </p>\n\n<p>If I keep them private and nest them within another class, everything works fine.</p>\n\n<p>I can reproduce your error only when, in one file, I have part of the class nested inside another class, and in another file, I do NOT nest the class, and then remove the private keyword... like this:</p>\n\n<p>Class1.cs:</p>\n\n<pre><code>namespace stackoverflow.answers\n{\n public class Foo\n {\n private partial class Bar\n {\n private string SomeProperty { get { return \"SomeGeneratedString\"; } }\n }\n }\n}\n</code></pre>\n\n<p>Class2.cs:</p>\n\n<pre><code>namespace stackoverflow.answers\n{\n partial class Bar\n {\n void SomeFunction()\n {\n string bar = this.SomeProperty;\n }\n } \n}\n</code></pre>\n\n<p>I also get the error you described if the namespaces differ. </p>\n\n<p>Please post the entire code for the solution, because the provided code is invalid C# syntax, and can't be looked into without more context. </p>\n" }, { "answer_id": 3988991, "author": "sada", "author_id": 483201, "author_profile": "https://Stackoverflow.com/users/483201", "pm_score": 0, "selected": false, "text": "<p>I analyze your code. you declared partial class as nested class this is cause to show error. why bcz partial class will not declare as nested class the parial keyword is split into ultiple files so, every file nae is same when you declared in nested class it will not recognize.</p>\n" }, { "answer_id": 31831949, "author": "Andrey K.", "author_id": 2772330, "author_profile": "https://Stackoverflow.com/users/2772330", "pm_score": 2, "selected": false, "text": "<p><strong>Edit:</strong></p>\n\n<p>solution: build action -> Complile, nothing else</p>\n\n<p>I'll try to be more specific:</p>\n\n<p>I had a class shared among 3 partial classes in 3 different files. At one moment a function call (from one part, of a function declared in other part) started showing error \"does not exist in current context\". It took me long until some guy <a href=\"https://ru.stackoverflow.com/questions/439998/%D0%9D%D0%B5-%D0%B2%D0%B8%D0%B4%D0%BD%D0%B0-partial-%D1%81%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D0%BB%D1%8F%D1%8E%D1%89%D0%B0%D1%8F-%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B0-namespase-%D0%BE%D0%B4%D0%B8%D0%BD-%D0%B8-%D1%82%D0%BE%D1%82-%D0%B6%D0%B5\">helped</a> me to figure out that accidentally i set the build action of the file with one part to \"EmbeddedResourse\" instead of \"Compile\".</p>\n\n<p>To switch build action you should right click on file in solution explorer, then choose properties. Then change the build action.</p>\n\n<p>This question is old, and my answer is not exactly helpful in this very case. But it may be helpful in one other very rare case related to partial classes. Sorry if my English is not clear.</p>\n" }, { "answer_id": 45292702, "author": "Ram", "author_id": 193061, "author_profile": "https://Stackoverflow.com/users/193061", "pm_score": 5, "selected": false, "text": "<p>Same answer as @Andrey K but in simple terms</p>\n\n<p><strong>Set the build action of all your partial classes to 'Compile' using the 'Properties' windows of each of those files</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/eLv99.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eLv99.png\" alt=\"Properties window -&gt; Build action property\"></a></p>\n" }, { "answer_id": 51361703, "author": "Vic Seedoubleyew", "author_id": 2873507, "author_profile": "https://Stackoverflow.com/users/2873507", "pm_score": 0, "selected": false, "text": "<p>A corner case where additional help can save you time is if you are using a partial class to complement a Run-time Text Template's generated class.</p>\n\n<p>Chances are that the problem is indeed that your partial class' namespace is different from the namespace of the generated part of that class. To check that, simply look at the generated code.</p>\n\n<p>To fix that, you need to edit the <code>.csproj</code> file for your project, and in the section about that template, add the <code>&lt;ClassNamespace&gt;</code> tag:</p>\n\n<pre><code>&lt;Content Include=\"MyTemplate.tt\"&gt;\n &lt;Generator&gt;TextTemplatingFilePreprocessor&lt;/Generator&gt;\n &lt;ClassNamespace&gt;My.Namespace&lt;/ClassNamespace&gt;\n &lt;LastGenOutput&gt;MyTemplate.cs&lt;/LastGenOutput&gt;\n&lt;/Content&gt;\n</code></pre>\n" }, { "answer_id": 53917143, "author": "Anton Andreev", "author_id": 422894, "author_profile": "https://Stackoverflow.com/users/422894", "pm_score": 1, "selected": false, "text": "<p>All the files should be in the same folder.</p>\n" }, { "answer_id": 64157415, "author": "Eric Ouellet", "author_id": 452845, "author_profile": "https://Stackoverflow.com/users/452845", "pm_score": -1, "selected": false, "text": "<p>Just for reference (VS 2020)... Error CS0103 =&gt; All same but different folder.</p>\n<p>But classes should have same namespace AND ALSO BE in same folder !!!</p>\n<p>Although they could be defined in the same namespace, both files should be in the same folder. I know that the folder structure should reflect the namespace but for clarity between the generated code and my added code, I wanted to separate by folder, but it does not works.</p>\n" }, { "answer_id": 70267521, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 0, "selected": false, "text": "<p>Same namespace in textual context just a <strong>different case</strong> on the words; which actually puts them into different compiler namespaces.</p>\n<hr />\n<h2>Example</h2>\n<p>Note the case of <code>O</code> in <strong>overflow</strong>.</p>\n<h3>File 1:</h3>\n<pre><code>namespace StackOverflow {\npublic partial class MyVM\n</code></pre>\n<h3>File 2:</h3>\n<pre><code>namespace Stackoverflow {\npublic partial class MyVM\n</code></pre>\n<p>Turns out somewhere in the past ten years my default project name became different that my original project name, but only in case. Uggg.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/184985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I seem to be having an issue with iPhone SDK 2.1 in as far as being able to establish a relationship between a ViewController and a View window. In as far as a Cocoa Touch Class, I went forward and added a `UIViewController` subclass. I made sure that the target is part of the existing project. Right afterwards I added a User Interfaces -> View XIB. Within the `UIViewController` I have some straight forward code I literally copy/pasted from sample code elsewhere: EditViewController.h: ``` @interface EditorViewController : UIViewController <UITextFieldDelegate> { UITextField *field; } @property(nonatomic, retain) IBOutlet UITextField *field; @end ``` EditViewController.m ``` #import "EditorViewController.h" @implementation EditorViewController - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void)dealloc { [super dealloc]; } @end ``` As you can tell, it doesn't do much. Now when I click my new xib, and reference a class identity with `EditorViewController`, no auto complete happens, which to me implies that it has no such awareness of a `EditorViewClass`. When I attempt to control+click from the view to File's Owners, I get nada. What are some of the possible idiosyncrasies in this process that I'm overlooking that's not allowing me to outlet my view to a controller? How would I also ensure that my User Interface View XIB is associated with the project besides seeing the project name checked off as a Target?
Are the two partial classes in the same namespace? That could be an explanation.
185,004
<p>I just noticed that java.beans.Introspector getBeanInfo does not pickup any superinterface's properties. Example:</p> <pre><code>public interface Person { String getName(); } public interface Employee extends Person { int getSalary(); } </code></pre> <p>Introspecting on Employee only yields salary even though name is inherited from Person.</p> <p>Why is this? I would rather not have to use reflection to get all the getters.</p>
[ { "answer_id": 185959, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 1, "selected": false, "text": "<p>Try using</p>\n\n<pre><code>public static BeanInfo getBeanInfo(Class&lt;?&gt; beanClass, Introspector.USE_ALL_BEANINFO);\n</code></pre>\n\n<p>and see if this yields the result you're looking for.</p>\n" }, { "answer_id": 196307, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 0, "selected": false, "text": "<p>In such a case, you should write a custom BeanInfo class.</p>\n" }, { "answer_id": 867423, "author": "Phil", "author_id": 33897, "author_profile": "https://Stackoverflow.com/users/33897", "pm_score": 3, "selected": true, "text": "<p>This issue is covered in Sun bug\n<a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4275879\" rel=\"nofollow noreferrer\">java.beans.Introspector doesn't work for interfaces</a></p>\n" }, { "answer_id": 5484079, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 2, "selected": false, "text": "<p>The Java VM does not support this out of the box as <a href=\"https://stackoverflow.com/questions/185004/java-beans-introspector-getbeaninfo-does-not-pickup-any-superinterfaces-properti/867423#867423\">Phil</a> wrote. I also needed this and implemented a <a href=\"http://kenai.com/projects/deut/sources/repo/content/trunk/src/diergo/util/BeanHelper.java\" rel=\"nofollow noreferrer\">helper class</a> as part of <a href=\"http://kenai.com/projects/deut\" rel=\"nofollow noreferrer\">Diergo Utils 1.5</a>.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
I just noticed that java.beans.Introspector getBeanInfo does not pickup any superinterface's properties. Example: ``` public interface Person { String getName(); } public interface Employee extends Person { int getSalary(); } ``` Introspecting on Employee only yields salary even though name is inherited from Person. Why is this? I would rather not have to use reflection to get all the getters.
This issue is covered in Sun bug [java.beans.Introspector doesn't work for interfaces](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4275879)
185,034
<p>Is there a way to test the type of an element in JavaScript? </p> <p>The answer may or may not require the prototype library, however the following setup does make use of the library.</p> <pre><code>function(event) { var element = event.element(); // if the element is an anchor ... // if the element is a td ... } </code></pre>
[ { "answer_id": 185039, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 6, "selected": false, "text": "<pre><code>if (element.nodeName == &quot;A&quot;) {\n ...\n} else if (element.nodeName == &quot;TD&quot;) {\n ...\n}\n</code></pre>\n" }, { "answer_id": 185046, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 8, "selected": true, "text": "<p>You can use <code>typeof(N)</code> to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.</p>\n\n<p>In that case, use the <code>elem.tagName</code> or <code>elem.nodeName</code> property.</p>\n\n<p>if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.</p>\n" }, { "answer_id": 185092, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 4, "selected": false, "text": "<p>Perhaps you'll have to check the nodetype too:</p>\n\n<pre><code>if(element.nodeType == 1){//element of type html-object/tag\n if(element.tagName==\"a\"){\n //this is an a-element\n }\n if(element.tagName==\"div\"){\n //this is a div-element\n }\n}\n</code></pre>\n\n<p>Edit: Corrected the nodeType-value</p>\n" }, { "answer_id": 185810, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 3, "selected": false, "text": "<p>roenving is correct BUT you need to change the test to:</p>\n\n<pre>\nif(element.nodeType == 1) {\n//code\n}\n</pre>\n\n<p>because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See <a href=\"http://www.w3schools.com/Dom/dom_nodetype.asp\" rel=\"noreferrer\">http://www.w3schools.com/Dom/dom_nodetype.asp</a></p>\n" }, { "answer_id": 34826843, "author": "nicolsondsouza", "author_id": 2176723, "author_profile": "https://Stackoverflow.com/users/2176723", "pm_score": 0, "selected": false, "text": "<h1>I have another way of testing the same.</h1>\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>Element.prototype.typeof = \"element\";\r\nvar element = document.body; // any dom element\r\nif (element &amp;&amp; element.typeof == \"element\"){\r\n return true; \r\n // this is a dom element\r\n}\r\nelse{\r\n return false; \r\n // this isn't a dom element\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 44747913, "author": "Herbertusz", "author_id": 1814837, "author_profile": "https://Stackoverflow.com/users/1814837", "pm_score": 2, "selected": false, "text": "<p>I usually get it from the toString() return value. It works in differently accessed DOM elements:</p>\n\n<pre><code>var a = document.querySelector('a');\n\nvar img = document.createElement('img');\n\ndocument.body.innerHTML += '&lt;div id=\"newthing\"&gt;&lt;/div&gt;';\nvar div = document.getElementById('newthing');\n\nObject.prototype.toString.call(a); // \"[object HTMLAnchorElement]\"\nObject.prototype.toString.call(img); // \"[object HTMLImageElement]\"\nObject.prototype.toString.call(div); // \"[object HTMLDivElement]\"\n</code></pre>\n\n<p>Then the relevant piece:</p>\n\n<pre><code>Object.prototype.toString.call(...).split(' ')[1].slice(0, -1);\n</code></pre>\n\n<p>It works in Chrome, FF, Opera, Edge, IE9+ (in older IE it return \"[object Object]\").</p>\n" }, { "answer_id": 50972410, "author": "Vignesh Raja", "author_id": 4593057, "author_profile": "https://Stackoverflow.com/users/4593057", "pm_score": 2, "selected": false, "text": "<p>Although the previous answers work perfectly, I will just add another way where the elements can also be classified using the interface they have implemented.</p>\n\n<p>Refer <a href=\"https://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/html2/HTMLElement.html\" rel=\"nofollow noreferrer\">W3 Org for available interfaces</a></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>console.log(document.querySelector(\"#anchorelem\") instanceof HTMLAnchorElement);\r\nconsole.log(document.querySelector(\"#divelem\") instanceof HTMLDivElement);\r\nconsole.log(document.querySelector(\"#buttonelem\") instanceof HTMLButtonElement);\r\nconsole.log(document.querySelector(\"#inputelem\") instanceof HTMLInputElement);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;a id=\"anchorelem\" href=\"\"&gt;Anchor element&lt;/a&gt;\r\n&lt;div id=\"divelem\"&gt;Div Element&lt;/div&gt;\r\n&lt;button id=\"buttonelem\"&gt;Button Element&lt;/button&gt;\r\n&lt;br&gt;&lt;input id=\"inputelem\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The interface check can be made in 2 ways as <code>elem instanceof HTMLAnchorElement</code> or <code>elem.constructor.name == \"HTMLAnchorElement\"</code>, both returns <code>true</code></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ]
Is there a way to test the type of an element in JavaScript? The answer may or may not require the prototype library, however the following setup does make use of the library. ``` function(event) { var element = event.element(); // if the element is an anchor ... // if the element is a td ... } ```
You can use `typeof(N)` to get the actual object type, but what you want to do is check the tag, not the type of the DOM element. In that case, use the `elem.tagName` or `elem.nodeName` property. if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.
185,042
<p><strong>Environment:</strong><br/> Windows Server 2003 R2 Enterprise 64bit, SP2<br/> .NET framework is supposedly installed (2.0 SP2, 3.0 SP2, 3.5 SP1)</p> <p>I say "supposedly" because they are listed as installed under Add/Remove programs. I'm not sure it's <em>properly</em> installed, because the "ASP.NET" tab isn't added to any of the sites in IIS.</p> <p>In the IIS Web Service Extensions section, I have both "ASP.NET v2.0.50727" (Allowed), and "ASP.NET v2.0.50727 (32-bit)" (Prohibited).</p> <p>The site in question has script-execute enabled.</p> <p><strong>Problem:</strong></p> <p>I created a super-simple ASP.NET/C# website: Default.aspx with a label id="Label1", and a code-behind with: <code>Label1.text = "Hello World";</code> and the error I'm getting is:</p> <blockquote> <p>%1 is not a valid Win32 application.</p> </blockquote>
[ { "answer_id": 185056, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 4, "selected": true, "text": "<p>Have you tried running:</p>\n\n<pre><code>aspnet_regiis -i\n</code></pre>\n\n<p>from the command line?</p>\n" }, { "answer_id": 185835, "author": "Jérôme Laban", "author_id": 26346, "author_profile": "https://Stackoverflow.com/users/26346", "pm_score": 1, "selected": false, "text": "<p>I had a similar error with IIS7 on Windows Server 2008 64 Bits.</p>\n\n<p>The fusion log is not of any help here, and it turned out that in my case there was a third party assembly that was referencing a 32 Bits only assembly or native dll. (Xceed to be precise)</p>\n\n<p>To find which assembly is being loaded by the 64 bits runtime :</p>\n\n<ul>\n<li>Attach the VS2008 debugger on <em>w3wp.exe</em> process that matches your application pool</li>\n<li>Intercept all exceptions (Menu Debug / Exceptions / check all \"<em>Common Language Runtime Exceptions</em>\"). </li>\n<li>Make sure your application is reloaded completely (by modifying the web.config, for instance).</li>\n<li>When the <em>System.BadImageFormatException</em> exception is raised, look for a assembly name in the stack trace viewer window.</li>\n</ul>\n\n<p>Remember that all assemblies placed in the bin directory are loaded, regardless of their actual implication in the application.</p>\n" }, { "answer_id": 1524531, "author": "Juuso Ohtonen", "author_id": 1097104, "author_profile": "https://Stackoverflow.com/users/1097104", "pm_score": 2, "selected": false, "text": "<p>I had \"%1 is not a valid Win32 application.\" error message because my PATH environment variable was messed up. Well, more specifically, the PATH itself had nothing wrong with it. Instead, I had accidentally created a file named \"C:\\Program\" that was used instead of \"C:\\Program Files\\\" for path lookup. \nThe accidental creation of \"C:\\Program\" was a result of calling Notepad++ on the command line for C:\\Program Files\\test.txt (without quotation marks), so Notepad++ thought I was trying to edit a file called \"C:\\Program\" and created the file for me.</p>\n" }, { "answer_id": 7479120, "author": "Razor", "author_id": 17211, "author_profile": "https://Stackoverflow.com/users/17211", "pm_score": 3, "selected": false, "text": "<p>Also check your application pool. In a 64-bit environment, you may need to set \"Enable 32-bit applications\" in Advanced Settings.</p>\n" }, { "answer_id": 14991957, "author": "Tom Kelly TAK", "author_id": 2093432, "author_profile": "https://Stackoverflow.com/users/2093432", "pm_score": 2, "selected": false, "text": "<p>I had \"%1 is not a valid Win32 application.\" error message because my PATH environment variable was messed up as well. It included this garbage from a python install:</p>\n\n<pre><code>%PYTHON_HOME%;\n%PYTHON_HOME%\\Scripts;\n</code></pre>\n" }, { "answer_id": 15911241, "author": "Pete Haas", "author_id": 43841, "author_profile": "https://Stackoverflow.com/users/43841", "pm_score": 1, "selected": false, "text": "<p>I had this problem. I deployed an .EXE to a Windows 2003 that doesn't support .NET 4.5. I rebuilt the program with .NET 4 and it worked.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
**Environment:** Windows Server 2003 R2 Enterprise 64bit, SP2 .NET framework is supposedly installed (2.0 SP2, 3.0 SP2, 3.5 SP1) I say "supposedly" because they are listed as installed under Add/Remove programs. I'm not sure it's *properly* installed, because the "ASP.NET" tab isn't added to any of the sites in IIS. In the IIS Web Service Extensions section, I have both "ASP.NET v2.0.50727" (Allowed), and "ASP.NET v2.0.50727 (32-bit)" (Prohibited). The site in question has script-execute enabled. **Problem:** I created a super-simple ASP.NET/C# website: Default.aspx with a label id="Label1", and a code-behind with: `Label1.text = "Hello World";` and the error I'm getting is: > > %1 is not a valid Win32 application. > > >
Have you tried running: ``` aspnet_regiis -i ``` from the command line?
185,072
<p>I took the plunge this afternoon and began studying LINQ, so far just mucking around with LINQ on collections. One of the first things I tried was to implement QSort.</p> <p>Now -- ignoring the fact that I <em>could</em> just use an ORDERBY and that this is a very silly qsort implementation -- what I came up with was this:</p> <pre><code>public class lqsort { public static List&lt;int&gt; QSLinq(List&lt;int&gt; _items) { if (_items.Count &lt;= 1) return _items; int _pivot = _items[0]; List&lt;int&gt; _less = (from _item in _items where _item &lt; _pivot select _item).ToList(); List&lt;int&gt; _same = (from _item in _items where _item == _pivot select _item).ToList(); List&lt;int&gt; _greater = (from _item in _items where _item &gt; _pivot select _item).ToList(); return (QSLinq(_less).Concat(_same.Concat(QSLinq(_greater)))).ToList(); } } </code></pre> <p>The only thing that really bugs me is all of the casting involved. Are there any LINQ tricks I might use? Or am I just using LINQ for things it wasn't intended for?</p>
[ { "answer_id": 185128, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": false, "text": "<p>How about this? (If I understand well you don't like the .ToList calls)</p>\n\n<pre><code>public static IEnumerable&lt;int&gt; QSLinq(IEnumerable&lt;int&gt; items)\n{\n if (items.Count() &lt;= 1)\n return items;\n\n int pivot = items.First();\n\n return QSLinq(items.Where(i =&gt; i &lt; pivot))\n .Concat(items.Where(i =&gt; i == pivot))\n .Concat(QSLinq(items.Where(i =&gt; i &gt; pivot)));\n}\n</code></pre>\n\n<p><em>Disclaimer based on <a href=\"https://stackoverflow.com/questions/185072/learning-linq-quicksort#185139\">Jon answer</a></em>: <strong>Do NOT use this algorithm in a real problem. It is very inefficient.</strong></p>\n" }, { "answer_id": 185139, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>All the casting involved? I don't see any casting. What I <em>do</em> see is calls to \"ToList\" which are hideously inefficient. Basically LINQ is designed to work over sequences, which intrinsically don't allow you to work in place (or in a duplicate space) in the way that quicksort tends to. Basically you've got an awful lot of data copying going on here :(</p>\n" }, { "answer_id": 185146, "author": "Alfred B. Thordarson", "author_id": 3379, "author_profile": "https://Stackoverflow.com/users/3379", "pm_score": 4, "selected": true, "text": "<p>Just change the type of the parameter to <code>IEnumerable</code> and use the <code>var</code> construct instead of your <code>List&lt;int&gt;</code> for your local variables.</p>\n\n<p>This will make your <code>QSLinq</code> method better because it will accept more types of parameters, for example <code>int[]</code>, as well as <code>List&lt;int&gt;</code>.</p>\n\n<p>See the new method:</p>\n\n<pre><code> public static IEnumerable&lt;int&gt; QSLinq(IEnumerable&lt;int&gt; _items)\n {\n if (_items.Count() &lt;= 1)\n return _items;\n\n var _pivot = _items.First();\n\n var _less = from _item in _items where _item &lt; _pivot select _item;\n var _same = from _item in _items where _item == _pivot select _item;\n var _greater = from _item in _items where _item &gt; _pivot select _item;\n\n return QSLinq(_less).Concat(QSLinq(_same)).Concat(QSLinq(_greater));\n }\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 185656, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>Fun Question! This doesn't outperform OrderBy, but it does limit the repeated enumerations some.</p>\n\n<pre><code> public static IEnumerable&lt;int&gt; QSort2(IEnumerable&lt;int&gt; source)\n {\n if (!source.Any())\n return source;\n int first = source.First();\n return source\n .GroupBy(i =&gt; i.CompareTo(first))\n .OrderBy(g =&gt; g.Key)\n .SelectMany(g =&gt; g.Key == 0 ? g : QSort2(g));\n }\n</code></pre>\n\n<p>I inadvertently generated a stackoverflow during development, as I QSorted when the Key == 0.</p>\n\n<hr>\n\n<p>Just for fun I tested these solutions. I commited the cardinal performance testing sin (testing in debug mode), but I don't think that affects the big O effect we'll see. Here is the input (reversed input is <em>worst case</em> for quicksort)</p>\n\n<pre><code>IEnumerable&lt;int&gt; source = Enumerable.Range(0, 1000).Reverse().ToList();\n</code></pre>\n\n<ul>\n<li>The triple concat-where solution took 71000 milliseconds.</li>\n<li>My solution took 330 milliseconds</li>\n<li>OrderBy.ToArray took 15 milliseconds (the timer's resolution, so actual time is probably less)</li>\n</ul>\n" }, { "answer_id": 185769, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>Here's another solution using Aggregate. I call it: <em>Group and Go Fish</em>. This one takes 170 ms by my 1000 reversed elements test.</p>\n\n<pre><code> public static IEnumerable&lt;int&gt; QSort3(IEnumerable&lt;int&gt; source)\n {\n if (!source.Any())\n return source;\n int first = source.First();\n\n QSort3Helper myHelper = \n source.GroupBy(i =&gt; i.CompareTo(first))\n .Aggregate(new QSort3Helper(), (a, g) =&gt;\n {\n if (g.Key == 0)\n a.Same = g;\n else if (g.Key == -1)\n a.Less = g;\n else if (g.Key == 1)\n a.More = g;\n return a;\n });\n IEnumerable&lt;int&gt; myResult = Enumerable.Empty&lt;int&gt;();\n if (myHelper.Less != null)\n myResult = myResult.Concat(QSort3(myHelper.Less));\n if (myHelper.Same != null)\n myResult = myResult.Concat(myHelper.Same);\n if (myHelper.More != null)\n myResult = myResult.Concat(QSort3(myHelper.More));\n\n return myResult;\n }\n\n public class QSort3Helper\n {\n public IEnumerable&lt;int&gt; Less;\n public IEnumerable&lt;int&gt; Same;\n public IEnumerable&lt;int&gt; More;\n }\n</code></pre>\n\n<p>Why is this faster than my solution using OrderBy? I guess it's a little more resistent to the worst case.</p>\n" }, { "answer_id": 48954500, "author": "fartwhif", "author_id": 6620171, "author_profile": "https://Stackoverflow.com/users/6620171", "pm_score": 0, "selected": false, "text": "<p>The chosen answer is broken because it includes QSLinq(_same) instead of just _same in the returned collection and results in a StackOverflowException. I'll be using the fixed version as the control. If the solution can use copying then the speed can be drastically increased. Usage of threads instead of parallel actually decreases performance slightly for copying variants. Usage of threads for non-copying variants increases performance slightly. Parallel and non-copying performance difference from the control is negligent.</p>\n\n<p><a href=\"https://i.stack.imgur.com/JpsFE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JpsFE.png\" alt=\"all variants\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/pTtVa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pTtVa.png\" alt=\"copying variants\"></a></p>\n\n<p>fastest copying:</p>\n\n<pre><code>private static List&lt;int&gt; quickie7(List&lt;int&gt; ites)\n{\n if (ites.Count &lt;= 1)\n return ites;\n var piv = ites[0];\n List&lt;int&gt; les = new List&lt;int&gt;();\n List&lt;int&gt; sam = new List&lt;int&gt;();\n List&lt;int&gt; mor = new List&lt;int&gt;();\n Enumerable.Range(0, 3).AsParallel().ForAll(i =&gt;\n {\n switch (i)\n {\n case 0: les = (from _item in ites where _item &lt; piv select _item).ToList(); break;\n case 1: sam = (from _item in ites where _item == piv select _item).ToList(); break;\n case 2: mor = (from _item in ites where _item &gt; piv select _item).ToList(); break;\n }\n });\n var _les = new List&lt;int&gt;();\n var _mor = new List&lt;int&gt;();\n Enumerable.Range(0, 2).AsParallel().ForAll(i =&gt;\n {\n switch (i)\n {\n case 0: _les = quickie7(les); break;\n case 1: _mor = quickie7(mor); break;\n }\n });\n List&lt;int&gt; allofem = new List&lt;int&gt;();\n allofem.AddRange(_les);\n allofem.AddRange(sam);\n allofem.AddRange(_mor);\n return allofem;\n}\n</code></pre>\n\n<p>fastest non copying:</p>\n\n<pre><code>public static IEnumerable&lt;int&gt; QSLinq3(IEnumerable&lt;int&gt; _items)\n{\n if (_items.Count() &lt;= 1)\n return _items;\n var _pivot = _items.First();\n IEnumerable&lt;int&gt; _less = null;\n IEnumerable&lt;int&gt; _same = null;\n IEnumerable&lt;int&gt; _greater = null;\n ConcurrentBag&lt;ManualResetEvent&gt; finishes = new ConcurrentBag&lt;ManualResetEvent&gt;();\n Enumerable.Range(0, 3).AsParallel().ForAll(i =&gt;\n {\n var fin = new ManualResetEvent(false);\n finishes.Add(fin);\n (new Thread(new ThreadStart(() =&gt;\n {\n if (i == 0)\n _less = from _item in _items where _item &lt; _pivot select _item;\n else if (i == 1)\n _same = from _item in _items where _item == _pivot select _item;\n else if (i == 2)\n _greater = from _item in _items where _item &gt; _pivot select _item;\n fin.Set();\n }))).Start();\n });\n finishes.ToList().ForEach(k =&gt; k.WaitOne());\n return QSLinq(_less).Concat(_same).Concat(QSLinq(_greater));\n}\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
I took the plunge this afternoon and began studying LINQ, so far just mucking around with LINQ on collections. One of the first things I tried was to implement QSort. Now -- ignoring the fact that I *could* just use an ORDERBY and that this is a very silly qsort implementation -- what I came up with was this: ``` public class lqsort { public static List<int> QSLinq(List<int> _items) { if (_items.Count <= 1) return _items; int _pivot = _items[0]; List<int> _less = (from _item in _items where _item < _pivot select _item).ToList(); List<int> _same = (from _item in _items where _item == _pivot select _item).ToList(); List<int> _greater = (from _item in _items where _item > _pivot select _item).ToList(); return (QSLinq(_less).Concat(_same.Concat(QSLinq(_greater)))).ToList(); } } ``` The only thing that really bugs me is all of the casting involved. Are there any LINQ tricks I might use? Or am I just using LINQ for things it wasn't intended for?
Just change the type of the parameter to `IEnumerable` and use the `var` construct instead of your `List<int>` for your local variables. This will make your `QSLinq` method better because it will accept more types of parameters, for example `int[]`, as well as `List<int>`. See the new method: ``` public static IEnumerable<int> QSLinq(IEnumerable<int> _items) { if (_items.Count() <= 1) return _items; var _pivot = _items.First(); var _less = from _item in _items where _item < _pivot select _item; var _same = from _item in _items where _item == _pivot select _item; var _greater = from _item in _items where _item > _pivot select _item; return QSLinq(_less).Concat(QSLinq(_same)).Concat(QSLinq(_greater)); } ``` Hope this helps.
185,073
<p>I'm trying to call into a C++ library from Perl on an AIX 5.1 machine. I've created a very simple test project to try to exercise this.</p> <p>My C++ shared library (<code>test.cpp</code>):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;iostream&gt; void myfunc() { printf("in myfunc()\n"); std::cout &lt;&lt; "in myfunc() also" &lt;&lt; std::endl; } </code></pre> <p>My SWIG interface file (<code>test.i</code>):</p> <pre><code>%module test %{ void myfunc(); %} void myfunc(); </code></pre> <p>I then build the shared object like so:</p> <pre><code>swig -c++ -perl test.i g++ -c test_wrap.cxx -I/usr/opt/perl5/lib/5.6.0/aix/CORE -o test_wrap.o g++ -c test.cpp -o test.o ld -G -bI:/usr/opt/perl5/lib/5.6.0/aix/CORE/perl.exp -bnoentry -bexpall -lc_r test.o test_wrap.o -o test.so </code></pre> <p>At this point, I have a <code>test.so</code> shared object that should be loadable in perl (via the SWIG generated <code>test.pm</code>). I have a very simple perl script to try to load the shared object and call the one function that I am exporting (<code>test.pl</code>):</p> <pre><code>#!/usr/bin/perl use test; test::myfunc(); </code></pre> <p>When I run <code>test.pl</code>, I get the following output:</p> <blockquote> <p>in myfunc()<br> Illegal instruction (core dumped)</p> </blockquote> <p>If I comment-out the <code>std::cout</code> usage in <code>myfunc</code>, it works without problem. It appears as though using anything in the C++ STL causes a core dump (I tried just declaring a <code>std::vector</code> and <code>std::stringstream</code>, both result in the core dump). I can create a standalone C++ executable that uses the STL without any issues, it's only when called in my shared object when loaded from perl that I get into trouble.</p> <p>I've also tried using xlc rather than gcc, but I get the same result. I'm thinking there is some funky linker flag that I need to pass in to ensure that all of the linkage occurs correctly? Any ideas are welcome...</p> <p>Edit: If I link using <code>gcc</code>/<code>xlc</code> instead of invoking the linker directly (<code>ld</code>), I immediately get a segmentation fault. It looks like it crashes when perl is trying to simply load the shared library. Calling <code>ld</code> as I have above is the closest that I've got it to working, but I think I may be missing some libraries or special AIX linker flags for the C++ libraries.</p> <p>Edit2: Ok, I've got it working. AIX is very fragile when it comes to linking. I ultimately came up with the following link command that seems to be working correctly:</p> <pre><code>ld -G -bI:/usr/opt/perl5/lib/5.6.0/aix/CORE/perl.exp -bnoentry -bexpall -lC -lc -ldl test.o test_wrap.o -o test.so </code></pre> <p>The libraries that I linked against are the most relevant. It turns out that the order in which the libraries are mentioned is very important also (ugh). Also note that this is being built against Perl 5.6.0 that ships with AIX 5.1. I've tried building this same simple application against Perl 5.8.8 and it doesn't work. However, I'm pretty sure the much more sane method of linking (using straight <code>gcc</code>/<code>xlc</code> instead of having to call <code>ld</code> directly) seems to work better. So this issue appears to be a bug in the Perl distribution or the linker or something.</p> <p>Hopefully this will help some poor soul cursed with having to work with AIX...</p>
[ { "answer_id": 185118, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 2, "selected": false, "text": "<p>Wouldn't you just add your libstdc++ to your ld command? e.g., <code>-lstdc++</code>?</p>\n\n<p>What I did on Linux, after replicating your problem was:</p>\n\n<pre><code>gcc -g -lstdc++ -shared test*.o -o test.so\n</code></pre>\n\n<p>Then the problem went away.</p>\n\n<p>(Trying to get the exact right list of libraries for ld was too much work, so I just told gcc to do it for me.)</p>\n" }, { "answer_id": 185408, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 0, "selected": false, "text": "<p>I know nothing about SWIG, but you might also want to check that it's expecting a function using cdecl (rather than pascal, fastcall, or some other calling convention). Using the wrong one between tools can lead to \"bad things happening\" (usually stack corruption, as far as I can tell).</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26302/" ]
I'm trying to call into a C++ library from Perl on an AIX 5.1 machine. I've created a very simple test project to try to exercise this. My C++ shared library (`test.cpp`): ``` #include <stdio.h> #include <iostream> void myfunc() { printf("in myfunc()\n"); std::cout << "in myfunc() also" << std::endl; } ``` My SWIG interface file (`test.i`): ``` %module test %{ void myfunc(); %} void myfunc(); ``` I then build the shared object like so: ``` swig -c++ -perl test.i g++ -c test_wrap.cxx -I/usr/opt/perl5/lib/5.6.0/aix/CORE -o test_wrap.o g++ -c test.cpp -o test.o ld -G -bI:/usr/opt/perl5/lib/5.6.0/aix/CORE/perl.exp -bnoentry -bexpall -lc_r test.o test_wrap.o -o test.so ``` At this point, I have a `test.so` shared object that should be loadable in perl (via the SWIG generated `test.pm`). I have a very simple perl script to try to load the shared object and call the one function that I am exporting (`test.pl`): ``` #!/usr/bin/perl use test; test::myfunc(); ``` When I run `test.pl`, I get the following output: > > in myfunc() > > Illegal instruction (core dumped) > > > If I comment-out the `std::cout` usage in `myfunc`, it works without problem. It appears as though using anything in the C++ STL causes a core dump (I tried just declaring a `std::vector` and `std::stringstream`, both result in the core dump). I can create a standalone C++ executable that uses the STL without any issues, it's only when called in my shared object when loaded from perl that I get into trouble. I've also tried using xlc rather than gcc, but I get the same result. I'm thinking there is some funky linker flag that I need to pass in to ensure that all of the linkage occurs correctly? Any ideas are welcome... Edit: If I link using `gcc`/`xlc` instead of invoking the linker directly (`ld`), I immediately get a segmentation fault. It looks like it crashes when perl is trying to simply load the shared library. Calling `ld` as I have above is the closest that I've got it to working, but I think I may be missing some libraries or special AIX linker flags for the C++ libraries. Edit2: Ok, I've got it working. AIX is very fragile when it comes to linking. I ultimately came up with the following link command that seems to be working correctly: ``` ld -G -bI:/usr/opt/perl5/lib/5.6.0/aix/CORE/perl.exp -bnoentry -bexpall -lC -lc -ldl test.o test_wrap.o -o test.so ``` The libraries that I linked against are the most relevant. It turns out that the order in which the libraries are mentioned is very important also (ugh). Also note that this is being built against Perl 5.6.0 that ships with AIX 5.1. I've tried building this same simple application against Perl 5.8.8 and it doesn't work. However, I'm pretty sure the much more sane method of linking (using straight `gcc`/`xlc` instead of having to call `ld` directly) seems to work better. So this issue appears to be a bug in the Perl distribution or the linker or something. Hopefully this will help some poor soul cursed with having to work with AIX...
Wouldn't you just add your libstdc++ to your ld command? e.g., `-lstdc++`? What I did on Linux, after replicating your problem was: ``` gcc -g -lstdc++ -shared test*.o -o test.so ``` Then the problem went away. (Trying to get the exact right list of libraries for ld was too much work, so I just told gcc to do it for me.)
185,091
<p>I got a very similar error to the one below:</p> <p><a href="https://stackoverflow.com/questions/97800/how-can-i-fix-this-delphi-7-compile-error-duplicate-resources">How can I fix this delphi 7 compile error - &quot;Duplicate resource(s)&quot;</a></p> <p>However, the error I got is this:</p> <pre><code> [Error] WARNING. Duplicate resource(s): [Error] Type 10 (RCDATA), ID TFMMAINTQUOTE: [Error] File P:\[PATH SNIPPED]\Manufacturing.RES resource kept; file FMaintQuote.DFM resource discarded. </code></pre> <p>Manufacturing.res is the default resource file (application is called Manufacturing.exe), and FMainQuote is one of the forms. .dfm files are plain text files, so I'm not sure what resources is being duplicated, how to find it and fix it?</p> <p>If I tried to compile the project again, it works OK, but the exe's icon is different to the one I've set in Project Options using the "Load Icon" button. The icon on the app is some sort of bell image that I don't recognize.</p>
[ { "answer_id": 185100, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 3, "selected": true, "text": "<p>Try renaming Manufacturing,res to Manufacturing.bak or something. Delphi should recreate the res file.</p>\n\n<p>You would of course need to recreate any references, strings etc in the res file in the new one, but worth trying anyway...</p>\n" }, { "answer_id": 185450, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 3, "selected": false, "text": "<p>try looking for having an extra {$R *.res} or {$R *.dfm},you may have copied it from somewhere.</p>\n" }, { "answer_id": 185644, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 3, "selected": false, "text": "<p>Delphi converts all of your DFM files into resources, and names them the name of the class. You can verify this by using a resource editor and opening any of your form based Delphi applications. </p>\n\n<p>search all of your units for instances of the TFMMAINTQUOTE form. Its most likely in two units, one of which is NOT linked to your project, but is being pulled in via the uses clause referencing the wrong unit (wrong as in it is saved with a different name but has the SAME form name, if it was part of your project then the compiler would complain when you added the unit in the first place).</p>\n\n<p>The simple solution to this problem is to find the TFMMAINTQUOTE form IN your project and rename the form to something else, but then the old TFMMAINTQUOTE will still be pulled in.</p>\n\n<p>I suggest using a good directory grep tool such as the one in <a href=\"http://www.gexperts.org\" rel=\"nofollow noreferrer\">GExperts</a> to do your searching. It will save you alot of time and can be set to search your entire hard drive if so desired. The advantage of GExperts is that its free and integrates directly into the Delphi IDE.</p>\n" }, { "answer_id": 844181, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>the extra <code>{$R *.res}</code> is in the *.dpr file like this:</p>\n\n<pre><code>program Test;\n\nuses\n Forms,\n Unit1 in 'Unit1.pas' {Form1},\n Sample in 'Sample.pas',\n Proc in 'Proc.pas';\n\n{$R *.res} //&lt;----delete this if you put them in the Unt1.pas. ok.\n\nbegin\n Application.Initialize;\n Application.CreateForm(TForm1, Form1);\n Application.Run;\nend.\n</code></pre>\n" }, { "answer_id": 1021264, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you rename a from and this form is referenced in the Uses part of other Units then you get the above error.</p>\n\n<p>Solution is a mixture of the above.</p>\n\n<p>(1) Change the resources file ending to .bak (so it will be re-created later).\n(2) Search through all the units and change the reference to old unit/form name to the new one.\n(3) re-compile and will now be ok. </p>\n" }, { "answer_id": 2937663, "author": "erte", "author_id": 353866, "author_profile": "https://Stackoverflow.com/users/353866", "pm_score": 1, "selected": false, "text": "<p>I got the same error. I think that the contributing factors were:</p>\n\n<ol>\n<li>no *.res-file</li>\n<li>common units with another project</li>\n<li>the project with the error had a form with the same name as a form in that another project</li>\n</ol>\n\n<p>Solution: rename the form (in the project with the error message)</p>\n" }, { "answer_id": 3725698, "author": "Server Overflow", "author_id": 46207, "author_profile": "https://Stackoverflow.com/users/46207", "pm_score": 0, "selected": false, "text": "<p>Edit the RES file and delete from it the duplicate resource. This way you will be able to keep your original icon.</p>\n" }, { "answer_id": 5051631, "author": "Pekka Puhakka", "author_id": 624467, "author_profile": "https://Stackoverflow.com/users/624467", "pm_score": 1, "selected": false, "text": "<p>This kind of \"WARNING. Duplicate resource(s): File resource kept resource discarded\" appeared me to Delphi 7 lately, when I was trying to re-install DBISAM database component to the palette.</p>\n\n<pre><code>File D:\\DELPHI\\DBISAM\\db324d6d.res resource kept; file \n D:\\DELPHI\\DBISAM\\db324d6d.res resource discarded.\nType 14 (ICON GROUP), ID MAINICON:\n</code></pre>\n\n<p>As you can see above, when <em>exactly this</em> RES related Delphi error situation appears <strong>there are two identical notices to the same resource</strong>, in here to \"D:\\DELPHI\\DBISAM\\db324d6d.res\" file.</p>\n\n<p>I first thought there are resources from two vendor packages conflicting, so I ripped and ripped down the other installed components. After 4 hours or so unfruitful struggling, I finally found that there had appeared another Resource reference to DBISAM DPK package file:</p>\n\n<pre><code>package db324d6d;\n{$R *.res}\n{$R 'db324d6d.res'}\n...\n</code></pre>\n\n<p>Now I remembered that DBIsam had about week ago or so complaint something about \"missing .RES resource file\". I routinely checked, and made sure the line existed in DPK file and RES file was on disk. \nAt that point I probably have somehow added that second line to the DPK file, yet got the Package built, and I was able to work with it the whole week. </p>\n\n<p>Now that extra line hit back, and hit it hard . I just love there 4 hour Saturday struggles. </p>\n\n<p>Shortly, how to fix it: Remove the latter of those resource lines. The error appears while they both will point to same resource. </p>\n\n<p>So, only this should be left:</p>\n\n<pre><code>package db324d6d;\n{$R *.res}\n...\n</code></pre>\n\n<p>Phew, I hope this will help someone else.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26305/" ]
I got a very similar error to the one below: [How can I fix this delphi 7 compile error - "Duplicate resource(s)"](https://stackoverflow.com/questions/97800/how-can-i-fix-this-delphi-7-compile-error-duplicate-resources) However, the error I got is this: ``` [Error] WARNING. Duplicate resource(s): [Error] Type 10 (RCDATA), ID TFMMAINTQUOTE: [Error] File P:\[PATH SNIPPED]\Manufacturing.RES resource kept; file FMaintQuote.DFM resource discarded. ``` Manufacturing.res is the default resource file (application is called Manufacturing.exe), and FMainQuote is one of the forms. .dfm files are plain text files, so I'm not sure what resources is being duplicated, how to find it and fix it? If I tried to compile the project again, it works OK, but the exe's icon is different to the one I've set in Project Options using the "Load Icon" button. The icon on the app is some sort of bell image that I don't recognize.
Try renaming Manufacturing,res to Manufacturing.bak or something. Delphi should recreate the res file. You would of course need to recreate any references, strings etc in the res file in the new one, but worth trying anyway...
185,101
<p>I have an XSL stylesheet with content in an <code>xsl:text</code> node like this:</p> <pre><code>&lt;xsl:text&gt; foo bar baz &lt;/xsl:text&gt; </code></pre> <p>The stylesheet itself is a text file with "unix-style" newline line terminators. I invoke this stylesheet on Windows as well as unix-like platforms. It would be nice to have the output conform to the conventions of the platform on which it is invoked.</p> <p>When I run this stylesheet on Windows, the output has carriage return/newline pairs for everything <em>except</em> the contents of the <code>xsl:text</code> node.</p> <p><strong>Can I instruct the XSLT processor to translate the newline characters in the content of the <code>xsl:text</code> node into platform specific end-of-lines?</strong></p> <p>More context: I'm invoking the stylesheet from the <a href="http://ant.apache.org/manual/Tasks/style.html" rel="noreferrer">Apache Ant 1.7.1 XSLT task</a> like this:</p> <pre><code>&lt;xslt in="in.xml" out="out.xml" style="stylesheet.xsl"/&gt; </code></pre> <p>The stylesheet header currently looks like this:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" exclude-result-prefixes="xalan"&gt; &lt;!-- contents elided --&gt; &lt;/xsl:stylesheet&gt; </code></pre>
[ { "answer_id": 185231, "author": "Jen A", "author_id": 12979, "author_profile": "https://Stackoverflow.com/users/12979", "pm_score": 1, "selected": false, "text": "<p>Im not sure how to do the correct newlines automatically (it may depend on the xslt processor you are using), but you may be able to force the newlines in the contents of your text node. \\r\\n is <code>&amp;#xD; &amp;#xA;</code>, \\n is <code>&amp;#xA;</code>, e.g. you'd use:</p>\n\n<p><code>&lt;xsl:text&gt;foo&amp;#xD;&amp;#xa;bar&amp;#xD;&amp;#xa;&lt;/xsl:text&gt;</code> to get the output you're looking for.</p>\n" }, { "answer_id": 187729, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 3, "selected": false, "text": "<p>You could define a parameter for the stylesheet like so:</p>\n\n<pre><code>&lt;xsl:param name=\"br\"&gt;\n &lt;xsl:text&gt;&amp;#10;&lt;/xsl:text&gt;\n&lt;/xsl:param&gt;\n</code></pre>\n\n<p>and pass in the appropriate end of line character(s) by using a nested param element in your Ant script. The default in this example would be a Unix-style newline, of course. I think to output the value, you'd have to use:</p>\n\n<pre><code>&lt;xsl:copy-of select=\"$br\"/&gt;\n</code></pre>\n\n<p>It's verbose, but it works.</p>\n" }, { "answer_id": 191983, "author": "Mads Hansen", "author_id": 14419, "author_profile": "https://Stackoverflow.com/users/14419", "pm_score": 2, "selected": false, "text": "<p>If you are calling the transform from Ant, then <a href=\"http://ant.apache.org/manual/Tasks/condition.html\" rel=\"nofollow noreferrer\">you can test for the OS using a conditional task with a test for the OS family</a>:</p>\n\n<pre><code> &lt;condition property=\"linebreak\" value=\"&amp;#xD;&amp;#xa;\"&gt;\n &lt;os family=\"windows\"/&gt;\n &lt;/condition&gt;\n &lt;condition property=\"linebreak\" value=\"&amp;#xa;\"&gt;\n &lt;os family=\"unix\"/&gt;\n &lt;/condition&gt;\n</code></pre>\n\n<p>Then pass that parameter to the XSLT to signal which newline character(s) you want to use.</p>\n\n<pre><code> &lt;xslt in=\"data.xml\" out=\"${out.dir}/out.xml\"&gt;\n &lt;param name=\"linebreak\" expression=\"${linebreak}\" /&gt;\n &lt;/xslt&gt;\n</code></pre>\n" }, { "answer_id": 5824987, "author": "granadaCoder", "author_id": 214977, "author_profile": "https://Stackoverflow.com/users/214977", "pm_score": 0, "selected": false, "text": "<p>Well, I got mine to work (using Saxon) with a combination of 2 ideas above:</p>\n\n<pre><code>&lt;xsl:param name=\"br\"&gt;\n &lt;xsl:text&gt;&amp;#xD;&amp;#xa;&lt;/xsl:text&gt;\n&lt;/xsl:param&gt;\n</code></pre>\n\n<p>and then using line(s) like these where needed.</p>\n\n<pre><code>&lt;xsl:value-of select=\"$br\" /&gt;\n</code></pre>\n\n<p>Here is my full (but slimline) xsl</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n &lt;!--&lt;xsl:strip-space elements=\"*\" /&gt;--&gt;\n &lt;xsl:output method=\"text\" /&gt;\n &lt;!-- &lt;xsl:preserve-space elements=\"*\"/&gt;--&gt;\n&lt;xsl:param name=\"br\"&gt;\n &lt;xsl:text&gt;&amp;#xD;&amp;#xa;&lt;/xsl:text&gt;\n&lt;/xsl:param&gt;\n\n\n &lt;!-- --&gt;\n &lt;xsl:template match=\"/\"&gt;\n\n\n &lt;xsl:for-each select=\"//root/Item\"&gt;\n\n &lt;xsl:value-of select=\"@Name\" /&gt; &lt;!-- Your xpath will vary of course! --&gt;\n &lt;xsl:value-of select=\"$br\" /&gt;\n\n &lt;/xsl:for-each&gt;\n\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p></p>\n\n<p>Again, I am using Saxon\n%ProgramFiles%\\SaxonHE\\bin\\Transform.exe\non a windows 7 x64 machine.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13940/" ]
I have an XSL stylesheet with content in an `xsl:text` node like this: ``` <xsl:text> foo bar baz </xsl:text> ``` The stylesheet itself is a text file with "unix-style" newline line terminators. I invoke this stylesheet on Windows as well as unix-like platforms. It would be nice to have the output conform to the conventions of the platform on which it is invoked. When I run this stylesheet on Windows, the output has carriage return/newline pairs for everything *except* the contents of the `xsl:text` node. **Can I instruct the XSLT processor to translate the newline characters in the content of the `xsl:text` node into platform specific end-of-lines?** More context: I'm invoking the stylesheet from the [Apache Ant 1.7.1 XSLT task](http://ant.apache.org/manual/Tasks/style.html) like this: ``` <xslt in="in.xml" out="out.xml" style="stylesheet.xsl"/> ``` The stylesheet header currently looks like this: ``` <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" exclude-result-prefixes="xalan"> <!-- contents elided --> </xsl:stylesheet> ```
You could define a parameter for the stylesheet like so: ``` <xsl:param name="br"> <xsl:text>&#10;</xsl:text> </xsl:param> ``` and pass in the appropriate end of line character(s) by using a nested param element in your Ant script. The default in this example would be a Unix-style newline, of course. I think to output the value, you'd have to use: ``` <xsl:copy-of select="$br"/> ``` It's verbose, but it works.
185,110
<p>Can you please let me know the SQL to split date ranges when they overlap?</p> <p>Data (sample data with a date range and possibly other columns):</p> <pre><code> Col1 FromDate ToDate 1. 1 1/1/2008 31/12/2010 2. 1 1/1/2009 31/12/2012 3. 1 1/1/2009 31/12/2014 </code></pre> <p>Output:</p> <pre><code> Col1 From Date ToDate 1. 1 1/1/2008 31/12/2008 (from row 1 above) 2. 1 1/1/2009 31/12/2010 (from rows 1,2 and 3 above) 3. 1 1/1/2011 31/12/2012 (from rows 2 and 3 above) 4. 1 1/1/2013 31/12/2014 (from row 3 above) </code></pre>
[ { "answer_id": 185305, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "<p>This should do the trick (MySQL dialect, but easily adaptable)</p>\n\n<p>Initial setup</p>\n\n<pre><code>SQL query: SELECT * FROM `test` LIMIT 0, 30 ;\nRows: 3\nstart end\n2008-01-01 2010-12-31\n2009-01-01 2012-12-31\n2009-01-01 2014-12-31\n</code></pre>\n\n<p>Query</p>\n\n<pre><code>SELECT \n `start` , min( `end` )\nFROM (\n SELECT t1.start, t2.end\n FROM test t1, test t2\n WHERE t1.start &lt; t2.end\n UNION\n SELECT t1.end + INTERVAL 1 DAY , t2.end\n FROM test t1, test t2\n WHERE t1.end + INTERVAL 1 DAY &lt; t2.end\n UNION\n SELECT t1.start, t2.start - INTERVAL 1 DAY\n FROM test t1, test t2\n WHERE t1.start &lt; t2.start - INTERVAL 1 DAY\n) allRanges\nGROUP BY `start`\n</code></pre>\n\n<p>Result</p>\n\n<pre><code>start min( `end` )\n2008-01-01 2008-12-31\n2009-01-01 2010-12-31\n2011-01-01 2012-12-31\n2013-01-01 2014-12-31\n</code></pre>\n" }, { "answer_id": 185871, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 2, "selected": false, "text": "<p>Skliwz's answer adapted for SQL Server:</p>\n\n<pre><code>DECLARE @DateTest TABLE \n(\n FromDate datetime,\n ToDate datetime \n)\n\ninsert into @DateTest (FromDate, ToDate)\n(\nselect cast('1/1/2008' as datetime), cast('12/31/2010' as datetime)\nunion\nselect cast('1/1/2009' as datetime), cast('12/31/2012' as datetime)\nunion\nselect cast('1/1/2009' as datetime), cast('12/31/2014' as datetime)\n)\n\nSELECT \n FromDate , min(ToDate)\nFROM (\n SELECT t1.FromDate, t2.ToDate\n FROM \n @DateTest t1, \n @DateTest t2\n WHERE t1.FromDate &lt; t2.ToDate\n\n UNION\n\n SELECT dateadd(DAY, 1, t1.ToDate), t2.ToDate\n FROM \n @DateTest t1, \n @DateTest t2\n WHERE dateadd(DAY, 1, t1.ToDate) &lt; t2.ToDate\n) allRanges\ngroup by FromDate\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26309/" ]
Can you please let me know the SQL to split date ranges when they overlap? Data (sample data with a date range and possibly other columns): ``` Col1 FromDate ToDate 1. 1 1/1/2008 31/12/2010 2. 1 1/1/2009 31/12/2012 3. 1 1/1/2009 31/12/2014 ``` Output: ``` Col1 From Date ToDate 1. 1 1/1/2008 31/12/2008 (from row 1 above) 2. 1 1/1/2009 31/12/2010 (from rows 1,2 and 3 above) 3. 1 1/1/2011 31/12/2012 (from rows 2 and 3 above) 4. 1 1/1/2013 31/12/2014 (from row 3 above) ```
This should do the trick (MySQL dialect, but easily adaptable) Initial setup ``` SQL query: SELECT * FROM `test` LIMIT 0, 30 ; Rows: 3 start end 2008-01-01 2010-12-31 2009-01-01 2012-12-31 2009-01-01 2014-12-31 ``` Query ``` SELECT `start` , min( `end` ) FROM ( SELECT t1.start, t2.end FROM test t1, test t2 WHERE t1.start < t2.end UNION SELECT t1.end + INTERVAL 1 DAY , t2.end FROM test t1, test t2 WHERE t1.end + INTERVAL 1 DAY < t2.end UNION SELECT t1.start, t2.start - INTERVAL 1 DAY FROM test t1, test t2 WHERE t1.start < t2.start - INTERVAL 1 DAY ) allRanges GROUP BY `start` ``` Result ``` start min( `end` ) 2008-01-01 2008-12-31 2009-01-01 2010-12-31 2011-01-01 2012-12-31 2013-01-01 2014-12-31 ```
185,112
<p>I have a bit of html like so:</p> <pre><code>&lt;a href="#somthing" id="a1"&gt;&lt;img src="something" /&gt;&lt;/a&gt; &lt;a href="#somthing" id="a2"&gt;&lt;img src="something" /&gt;&lt;/a&gt; </code></pre> <p>I need to strip off the links so I'm just left with a couple of image tags. What would be the most efficient way to do this with jQuery?</p>
[ { "answer_id": 185140, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "<pre><code>$(\"a &gt; img\").parent() // match all &lt;a&gt;&lt;img&gt;&lt;/a&gt;, select &lt;a&gt; parents\n .each( function() // for each link\n { \n $(this).replaceWith( // replace the &lt;a&gt;\n $(this).children().remove() ); // with its detached children.\n });\n</code></pre>\n" }, { "answer_id": 185148, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 2, "selected": false, "text": "<p>This should do it:</p>\n\n<pre><code>$('a[id^=a]').each(function() { $(this).replaceWith($(this).html()); });\n</code></pre>\n" }, { "answer_id": 185160, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 1, "selected": false, "text": "<p>In plain javascript it would be something like:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nwindow.onload = function(){\n var l = document.getElementsByTagName(\"a\");\n for(i=0, im=l.length; im&gt;i; i++){\n if(l[i].firstChild.tagName == \"img\"){\n l[i].parentNode.replaceChild(l[i].firstChild,l[i]);\n }\n }\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6007/" ]
I have a bit of html like so: ``` <a href="#somthing" id="a1"><img src="something" /></a> <a href="#somthing" id="a2"><img src="something" /></a> ``` I need to strip off the links so I'm just left with a couple of image tags. What would be the most efficient way to do this with jQuery?
``` $("a > img").parent() // match all <a><img></a>, select <a> parents .each( function() // for each link { $(this).replaceWith( // replace the <a> $(this).children().remove() ); // with its detached children. }); ```
185,114
<p>I have a module in the parent directory of my script and I would like to 'use' it.</p> <p>If I do</p> <pre><code>use '../Foo.pm'; </code></pre> <p>I get syntax errors.</p> <p>I tried to do:</p> <pre><code>push @INC, '..'; use EPMS; </code></pre> <p>and .. apparently doesn't show up in @INC</p> <p>I'm going crazy! What's wrong here?</p>
[ { "answer_id": 185120, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>You have to have the <code>push</code> processed before the <code>use</code> is -- and <code>use</code> is processed early. So, you'll need a <code>BEGIN { push @INC, \"..\"; }</code> to have a chance, I believe.</p>\n" }, { "answer_id": 185121, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 8, "selected": true, "text": "<p><code>use</code> takes place at compile-time, so this would work:</p>\n\n<pre><code>BEGIN {push @INC, '..'}\nuse EPMS;\n</code></pre>\n\n<p>But the better solution is to <code>use lib</code>, which is a nicer way of writing the above:</p>\n\n<pre><code>use lib '..';\nuse EPMS;\n</code></pre>\n\n<p>In case you are running from a different directory, though, the use of <code>FindBin</code> is recommended:</p>\n\n<pre><code>use FindBin; # locate this script\nuse lib \"$FindBin::RealBin/..\"; # use the parent directory\nuse EPMS;\n</code></pre>\n" }, { "answer_id": 185131, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "<p>'use lib' is the answer, as @ephemient mentioned earlier. One other option is to use require/import instead of use. It means the module wouldn't be loaded at compile time, but instead in runtime.</p>\n\n<p>That will allow you to modify @INC as you tried there, or you could pass require a path to the file instead of the module name. From 'perldoc -f require':</p>\n\n<blockquote>\n <p>If EXPR is a bareword, the require assumes a \".pm\" extension and\n replaces \"::\" with \"/\" in the filename for you, to make it easy to\n load standard modules. This form of loading of modules does not risk\n altering your namespace.</p>\n</blockquote>\n" }, { "answer_id": 185153, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 5, "selected": false, "text": "<p>There are several ways you can modify <code>@INC</code>.</p>\n\n<ul>\n<li><p>set <code>PERL5LIB</code>, as documented in <a href=\"http://perldoc.perl.org/perlrun.html\" rel=\"nofollow noreferrer\">perlrun</a></p></li>\n<li><p>use the <code>-I</code> switch on the command line, also documented in <a href=\"http://perldoc.perl.org/perlrun.html\" rel=\"nofollow noreferrer\">perlrun</a>. You can also apply this automatically with PERL5OPT, but just use PERL5LIB if you are going to do that.</p></li>\n<li><p><code>use lib</code> inside your program, although this is fragile since another person on a different machine might have it in a different directory.</p></li>\n<li><p>Manually modify <code>@INC</code>, making sure you do that at compile time if you want to pull in a module with use. That's too much work though.</p></li>\n<li><p><code>require</code> the filename directly. While this is possible, it doesn't allow that filename to load files in the same directory. This would definitely raise eyebrows in a code review. </p></li>\n</ul>\n" }, { "answer_id": 185154, "author": "Berserk", "author_id": 26313, "author_profile": "https://Stackoverflow.com/users/26313", "pm_score": 4, "selected": false, "text": "<p>Personally I prefer to keep my modules (those that I write for myself or for systems I can control) in a certain directory, and also to place them in a subdirectory. As in:</p>\n\n<pre><code>/www/modules/MyMods/Foo.pm\n/www/modules/MyMods/Bar.pm\n</code></pre>\n\n<p>And then where I use them:</p>\n\n<pre><code>use lib qw(/www/modules);\nuse MyMods::Foo;\nuse MyMods::Bar;\n</code></pre>\n\n<p>As an aside.. when it comes to pushing, I prefer the fat-arrow comma:</p>\n\n<pre><code>push @array =&gt; $pushee;\n</code></pre>\n\n<p>But that's just a matter of preference.</p>\n" }, { "answer_id": 383845, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>As reported by \"perldoc -f use\":</p>\n\n<blockquote>\n <p>It is exactly equivalent to<br>\n <code>BEGIN { require Module; import Module LIST; }</code><br>\n except that Module must be a bareword.</p>\n</blockquote>\n\n<p>Putting that another way, \"use\" is equivalent to:</p>\n\n<ul>\n<li>running at compile time, </li>\n<li>converting the package name to a file name, </li>\n<li><code>require</code>-ing that file name, and </li>\n<li><code>import</code>-ing that package.</li>\n</ul>\n\n<p>So, instead of calling use, you can call require and import inside a BEGIN block:</p>\n\n<pre><code>BEGIN {\n require '../EPMS.pm';\n EPMS-&gt;import();\n}\n</code></pre>\n\n<p>And of course, if your module don't actually do any symbol exporting or other initialization when you call import, you can leave that line out:</p>\n\n<pre><code>BEGIN {\n require '../EPMS.pm';\n}\n</code></pre>\n" }, { "answer_id": 65531545, "author": "Billious", "author_id": 2937973, "author_profile": "https://Stackoverflow.com/users/2937973", "pm_score": 0, "selected": false, "text": "<p>Some IDEs don't work correctly with 'use lib', the favored answer. I found 'use lib::relative' works with my IDE, JetBrains' WebStorm.</p>\n<p>see <a href=\"https://metacpan.org/pod/lib::relative\" rel=\"nofollow noreferrer\">POD for lib::relative</a></p>\n" }, { "answer_id": 70816975, "author": "Richard", "author_id": 4294886, "author_profile": "https://Stackoverflow.com/users/4294886", "pm_score": 0, "selected": false, "text": "<p>The reason it's not working is because what you're adding to <code>@INC</code> is relative to the current working directory in the command line rather than the script's directory.</p>\n<p>For example, if you're currently in:</p>\n<pre><code>a/b/\n</code></pre>\n<p>And the script you're running has this URL:</p>\n<pre><code>a/b/modules/tests/test1.pl\n</code></pre>\n<hr />\n<pre><code>BEGIN {\n unshift(@INC, &quot;..&quot;); \n}\n</code></pre>\n<p>The above will mean that <code>..</code> results in directory <code>a/</code> rather than <code>a/b/modules</code>.</p>\n<p>Either you must change <code>..</code> to <code>./modules</code> in your code or do a <code>cd modules/tests</code> in the command line before running the script again.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
I have a module in the parent directory of my script and I would like to 'use' it. If I do ``` use '../Foo.pm'; ``` I get syntax errors. I tried to do: ``` push @INC, '..'; use EPMS; ``` and .. apparently doesn't show up in @INC I'm going crazy! What's wrong here?
`use` takes place at compile-time, so this would work: ``` BEGIN {push @INC, '..'} use EPMS; ``` But the better solution is to `use lib`, which is a nicer way of writing the above: ``` use lib '..'; use EPMS; ``` In case you are running from a different directory, though, the use of `FindBin` is recommended: ``` use FindBin; # locate this script use lib "$FindBin::RealBin/.."; # use the parent directory use EPMS; ```
185,124
<p>Say if I have a dropdown in a form and I have another nested class inside of this class . Now what's the best way to access this dropdown from the nested class? </p>
[ { "answer_id": 185144, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 7, "selected": false, "text": "<p>Unlike Java, a nested class isn't a special \"inner class\" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : <a href=\"https://devblogs.microsoft.com/oldnewthing/?p=30273\" rel=\"noreferrer\">C# nested classes are like C++ nested classes, not Java inner classes</a>.</p>\n\n<p>Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference. </p>\n\n<pre><code>// C#\nclass OuterClass \n{\n string s;\n // ...\n class InnerClass \n {\n OuterClass o_;\n public InnerClass(OuterClass o) { o_ = o; }\n public string GetOuterString() { return o_.s; }\n }\n void SomeFunction() {\n InnerClass i = new InnerClass(this);\n i.GetOuterString();\n }\n\n}\n</code></pre>\n\n<p>Note that the InnerClass can access the \"<code>s</code>\" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the \"<code>string s;</code>\" is <code>private</code> because no other access permission was specified. </p>\n" }, { "answer_id": 185150, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>Nested types aren't like inner classes in Java - there's no inherent instance of the containing type. (They're more like static nested classes in Java.) They're effectively separate classes, with two distinctions:</p>\n\n<ul>\n<li>If the containing type is generic, the nested type is effectively parameterised by the containing type, e.g. <code>Outer&lt;int&gt;.Nested</code> isn't the same as <code>Outer&lt;string&gt;.Nested</code>.</li>\n<li>Nested types have access to private members in the containing type.</li>\n</ul>\n" }, { "answer_id": 185152, "author": "Jason Kresowaty", "author_id": 14280, "author_profile": "https://Stackoverflow.com/users/14280", "pm_score": 4, "selected": false, "text": "<p>Unlike Java, in C# there is no implicit reference to an instance of the enclosing class.</p>\n\n<p>You need to pass such a reference to the nested class. A typical way to do this is through the nested class's constructor.</p>\n\n<pre><code>public partial class Form1 : Form\n{\n private Nested m_Nested;\n\n public Form1()\n {\n InitializeComponent();\n\n m_Nested = new Nested(this);\n m_Nested.Test();\n }\n\n private class Nested\n {\n private Form1 m_Parent;\n\n protected Form1 Parent\n {\n get\n {\n return m_Parent;\n }\n }\n\n public Nested(Form1 parent)\n {\n m_Parent = parent;\n }\n\n public void Test()\n {\n this.Parent.textBox1.Text = \"Testing access to parent Form's control\";\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 185159, "author": "mannu", "author_id": 15858, "author_profile": "https://Stackoverflow.com/users/15858", "pm_score": 1, "selected": false, "text": "<p>You could pass the enclosing class as a parameter to the nested class constructor, like this:</p>\n\n<pre><code>private NestedClass _nestedClass;\npublic ParentClass() \n{\n _nestedClass = new NestedClass(this);\n}\n</code></pre>\n\n<p>Nested classes are generally not recommended and should be private and/or internal. They are, in my opinion, useful sometimes though.</p>\n" }, { "answer_id": 185171, "author": "questzen", "author_id": 25210, "author_profile": "https://Stackoverflow.com/users/25210", "pm_score": 1, "selected": false, "text": "<p>Correct me if I am wrong, you are trying to process the outer control from inner class hence you ran into this. A better way of doing this would be to handle affairs in a event driven fashion. Use an Observer pattern, Register a listener on the outer control (your nested/inner class will be the listener). Makes life simpler. I am afraid that this is not the answer you were expecting!</p>\n" }, { "answer_id": 25000602, "author": "kmote", "author_id": 93394, "author_profile": "https://Stackoverflow.com/users/93394", "pm_score": 2, "selected": false, "text": "<p>One other method, which is useful under certain circumstances, is to derive the nested class off of the outer class. Like so:</p>\n\n<pre><code>class Outer()\n{\n protected int outerVar;\n class Nested() : Outer\n {\n //can access outerVar here, without the need for a \n // reference variable (or the associated dot notation).\n }\n}\n</code></pre>\n\n<p>I have used this technique especially in the context of <a href=\"http://haacked.com/archive/2012/01/02/structuring-unit-tests.aspx/\" rel=\"nofollow noreferrer\">Structured Unit Tests</a>. (This may not apply to the OP's particular question, but it can be helpful with nested classes in general, as in the case of this \"duplicate\" question: \" <a href=\"https://stackoverflow.com/questions/2957900/can-i-access-outer-class-objects-in-inner-class\">Can i access outer class objects in inner class</a> \")</p>\n" }, { "answer_id": 29672792, "author": "Levite", "author_id": 1680919, "author_profile": "https://Stackoverflow.com/users/1680919", "pm_score": 4, "selected": false, "text": "<h1>Static Members</h1>\n<p>Since no one has mentioned it so far: <em>Depending on your situation</em>, if the member variable can also be <strong>static</strong>, you could simply access it in following way.</p>\n<pre><code>class OuterClass\n{\n private static int memberVar;\n\n class NestedClass \n {\n void SomeFunction() { OuterClass.memberVar = 42; }\n }\n}\n</code></pre>\n<p><em>Sidenote:</em> I marked <code>memberVar</code> purposefully (and redundantly) as <code>private</code> to illustrate the given ability of the nested class to access private members of it's outer class.</p>\n<h3>Caution / Please consider</h3>\n<p>In <em>some situations</em> this might be the easiest way/workaround to get access, but ...</p>\n<ul>\n<li><p>Static also means, that the variable will be shared across all instance objects, with all the downsides/consequences there are (thread-safety, etc.)</p>\n</li>\n<li><p>Static also means, that this will obviously not work if you have more than one instance of the parent's class and the variable should hold an individual value for each instance</p>\n</li>\n</ul>\n<p>So in most cases you might wanna go with a different approach ...</p>\n<h1>Passing a Reference</h1>\n<p>As most people have suggested (and because it is also the most correct answer), here an example of passing a reference to the outer class' instance.</p>\n<pre><code>class OuterClass\n{\n private int memberVar;\n private NestedClass n;\n\n OuterClass() { n = new NestedClass(this); }\n\n\n class NestedClass\n {\n private OuterClass parent;\n\n NestedClass(OuterClass p) { parent = p; }\n SomeFunction() { parent.memberVar = 42; }\n }\n}\n</code></pre>\n" }, { "answer_id": 39633539, "author": "Hamid Jolany", "author_id": 555078, "author_profile": "https://Stackoverflow.com/users/555078", "pm_score": 0, "selected": false, "text": "<p>send the master class as an constructor parameter to the nested (inner) class.</p>\n" }, { "answer_id": 67768135, "author": "afshar003", "author_id": 5613695, "author_profile": "https://Stackoverflow.com/users/5613695", "pm_score": -1, "selected": false, "text": "<p>there is a good answer above but I like to write sth.</p>\n<p>c# nested class is by default private</p>\n<p>private to containing class <strong>if your want to use it must be public</strong></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Say if I have a dropdown in a form and I have another nested class inside of this class . Now what's the best way to access this dropdown from the nested class?
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : [C# nested classes are like C++ nested classes, not Java inner classes](https://devblogs.microsoft.com/oldnewthing/?p=30273). Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference. ``` // C# class OuterClass { string s; // ... class InnerClass { OuterClass o_; public InnerClass(OuterClass o) { o_ = o; } public string GetOuterString() { return o_.s; } } void SomeFunction() { InnerClass i = new InnerClass(this); i.GetOuterString(); } } ``` Note that the InnerClass can access the "`s`" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "`string s;`" is `private` because no other access permission was specified.
185,141
<p>I have a simple panel that is used as a drawing surface. The goal here is to draw a 4 pixel wide outline around a child ListView under certain circumstances. I would like to make the outline pulsate when something can be dragged into it. </p> <p>I am just drawing a simple rectangle around the ListView and updating the opacity of the rectangle inside of a timer tick event. When the opacity is changed, the border is re-drawn. I am double-buffering the painting at this point. I am also only allowing a redraw every 15 ticks or so (the timer interval is 20 ms). After all of this, the drawing process still flickers a bit. This is not acceptable, so I need some guidance on how I could avoid this.</p> <p>I don't see a way around painting the control quite often. There needs to be a smooth transition from opaque to solid and back again. When I lower the tick interval enough (down to about 300 -500 ms), the flashing stops, but the refresh rate is too slow.</p> <p>I am open to any and all ideas. Perhaps the way I am approaching this is just plain wrong, or perhaps one of you have already created a glow effect and know what to do. Thanks for any help in advance.</p>
[ { "answer_id": 185168, "author": "rice", "author_id": 23933, "author_profile": "https://Stackoverflow.com/users/23933", "pm_score": 1, "selected": false, "text": "<p>I don't have a strong answer, but since you have none, I'll post anyway:</p>\n\n<p>First, I have never used the System.Drawing.ImageAnimator class, but could that be a better approach for you?</p>\n\n<p>Second, if that fails, have you tried <em>not</em> using double-buffering? It's a long shot, but maybe your double-buffering code is actually making it worse.</p>\n" }, { "answer_id": 185178, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 0, "selected": false, "text": "<p>Long shot, but have you tried</p>\n\n<pre><code>SetStyle(ControlStyles.OptimizedDoubleBuffer, true);\n</code></pre>\n\n<p>On the Panel Control?</p>\n" }, { "answer_id": 185179, "author": "mannu", "author_id": 15858, "author_profile": "https://Stackoverflow.com/users/15858", "pm_score": 2, "selected": false, "text": "<p>Set DoubleBuffered = true on the form.</p>\n" }, { "answer_id": 185299, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 0, "selected": false, "text": "<p>You also may want to look at doing the drawing on a bitmap and then just displaying the bitmap if it has changed. Just my 2c.</p>\n" }, { "answer_id": 185303, "author": "Mark Allen", "author_id": 5948, "author_profile": "https://Stackoverflow.com/users/5948", "pm_score": 1, "selected": false, "text": "<p>I'm sorry in advance that this likely won't help but: WPF has animations and could at least in theory do this smoothly.</p>\n" }, { "answer_id": 185475, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 3, "selected": true, "text": "<p>I stumbled on a solution for this if anyone is interested. It turns out that the flashing is caused by the painting of the background. I used SetStyle to tell the control that I will be handling all of the painting. </p>\n\n<pre><code>SetStyle(ControlStyles.SupportsTransparentBackColor |\n ControlStyles.Opaque |\n ControlStyles.UserPaint |\n ControlStyles.AllPaintingInWmPaint, true);\n</code></pre>\n\n<p>I then first paint a transparent color over the region, and then I paint my border. I bit of a hack, but it works like a charm.</p>\n\n<p>EDIT: And remember to double buffer the image as well.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053/" ]
I have a simple panel that is used as a drawing surface. The goal here is to draw a 4 pixel wide outline around a child ListView under certain circumstances. I would like to make the outline pulsate when something can be dragged into it. I am just drawing a simple rectangle around the ListView and updating the opacity of the rectangle inside of a timer tick event. When the opacity is changed, the border is re-drawn. I am double-buffering the painting at this point. I am also only allowing a redraw every 15 ticks or so (the timer interval is 20 ms). After all of this, the drawing process still flickers a bit. This is not acceptable, so I need some guidance on how I could avoid this. I don't see a way around painting the control quite often. There needs to be a smooth transition from opaque to solid and back again. When I lower the tick interval enough (down to about 300 -500 ms), the flashing stops, but the refresh rate is too slow. I am open to any and all ideas. Perhaps the way I am approaching this is just plain wrong, or perhaps one of you have already created a glow effect and know what to do. Thanks for any help in advance.
I stumbled on a solution for this if anyone is interested. It turns out that the flashing is caused by the painting of the background. I used SetStyle to tell the control that I will be handling all of the painting. ``` SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.Opaque | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); ``` I then first paint a transparent color over the region, and then I paint my border. I bit of a hack, but it works like a charm. EDIT: And remember to double buffer the image as well.
185,149
<p>Please take a look at the html listed below and let me know why IE6 freezes when trying to load the remote script (located at '<a href="http://code.katzenbach.com/Default.aspx" rel="nofollow noreferrer">http://code.katzenbach.com/Default.aspx</a>'). The script returns JSONP and executes the 'callbackFunction' listed in the header. When it runs correctly, you'll see a pop-up alert showing numbers 1-500. This works fine in FF3 and IE7. I can't understand why it fails in Internet Explorer 6 -the processor gets pegged and everything hangs.</p> <p>Run it yourself and let me know if you experience the same problem. I've been staring at this problem all day. Thanks for your help.</p> <p>Andrew</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function callbackFunction(Result) { alert(Result) ; } &lt;/script&gt; &lt;script type="text/javascript" src="http://code.katzenbach.com/Default.aspx?callback=callbackFunction&amp;test=true&amp;c=500"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; Here &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 185188, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>The return is of the external script is:</p>\n\n<pre><code>callbackFunction([\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\",\"30\",\"31\",\"32\",\"33\",\"34\",\"35\",\"36\",\"37\",\"38\",\"39\",\"40\",\"41\",\"42\",\"43\",\"44\",\"45\",\"46\",\"47\",\"48\",\"49\",\"50\",\"51\",\"52\",\"53\",\"54\",\"55\",\"56\",\"57\",\"58\",\"59\",\"60\",\"61\",\"62\",\"63\",\"64\",\"65\",\"66\",\"67\",\"68\",\"69\",\"70\",\"71\",\"72\",\"73\",\"74\",\"75\",\"76\",\"77\",\"78\",\"79\",\"80\",\"81\",\"82\",\"83\",\"84\",\"85\",\"86\",\"87\",\"88\",\"89\",\"90\",\"91\",\"92\",\"93\",\"94\",\"95\",\"96\",\"97\",\"98\",\"99\",\"100\",\"101\",\"102\",\"103\",\"104\",\"105\",\"106\",\"107\",\"108\",\"109\",\"110\",\"111\",\"112\",\"113\",\"114\",\"115\",\"116\",\"117\",\"118\",\"119\",\"120\",\"121\",\"122\",\"123\",\"124\",\"125\",\"126\",\"127\",\"128\",\"129\",\"130\",\"131\",\"132\",\"133\",\"134\",\"135\",\"136\",\"137\",\"138\",\"139\",\"140\",\"141\",\"142\",\"143\",\"144\",\"145\",\"146\",\"147\",\"148\",\"149\",\"150\",\"151\",\"152\",\"153\",\"154\",\"155\",\"156\",\"157\",\"158\",\"159\",\"160\",\"161\",\"162\",\"163\",\"164\",\"165\",\"166\",\"167\",\"168\",\"169\",\"170\",\"171\",\"172\",\"173\",\"174\",\"175\",\"176\",\"177\",\"178\",\"179\",\"180\",\"181\",\"182\",\"183\",\"184\",\"185\",\"186\",\"187\",\"188\",\"189\",\"190\",\"191\",\"192\",\"193\",\"194\",\"195\",\"196\",\"197\",\"198\",\"199\",\"200\",\"201\",\"202\",\"203\",\"204\",\"205\",\"206\",\"207\",\"208\",\"209\",\"210\",\"211\",\"212\",\"213\",\"214\",\"215\",\"216\",\"217\",\"218\",\"219\",\"220\",\"221\",\"222\",\"223\",\"224\",\"225\",\"226\",\"227\",\"228\",\"229\",\"230\",\"231\",\"232\",\"233\",\"234\",\"235\",\"236\",\"237\",\"238\",\"239\",\"240\",\"241\",\"242\",\"243\",\"244\",\"245\",\"246\",\"247\",\"248\",\"249\",\"250\",\"251\",\"252\",\"253\",\"254\",\"255\",\"256\",\"257\",\"258\",\"259\",\"260\",\"261\",\"262\",\"263\",\"264\",\"265\",\"266\",\"267\",\"268\",\"269\",\"270\",\"271\",\"272\",\"273\",\"274\",\"275\",\"276\",\"277\",\"278\",\"279\",\"280\",\"281\",\"282\",\"283\",\"284\",\"285\",\"286\",\"287\",\"288\",\"289\",\"290\",\"291\",\"292\",\"293\",\"294\",\"295\",\"296\",\"297\",\"298\",\"299\",\"300\",\"301\",\"302\",\"303\",\"304\",\"305\",\"306\",\"307\",\"308\",\"309\",\"310\",\"311\",\"312\",\"313\",\"314\",\"315\",\"316\",\"317\",\"318\",\"319\",\"320\",\"321\",\"322\",\"323\",\"324\",\"325\",\"326\",\"327\",\"328\",\"329\",\"330\",\"331\",\"332\",\"333\",\"334\",\"335\",\"336\",\"337\",\"338\",\"339\",\"340\",\"341\",\"342\",\"343\",\"344\",\"345\",\"346\",\"347\",\"348\",\"349\",\"350\",\"351\",\"352\",\"353\",\"354\",\"355\",\"356\",\"357\",\"358\",\"359\",\"360\",\"361\",\"362\",\"363\",\"364\",\"365\",\"366\",\"367\",\"368\",\"369\",\"370\",\"371\",\"372\",\"373\",\"374\",\"375\",\"376\",\"377\",\"378\",\"379\",\"380\",\"381\",\"382\",\"383\",\"384\",\"385\",\"386\",\"387\",\"388\",\"389\",\"390\",\"391\",\"392\",\"393\",\"394\",\"395\",\"396\",\"397\",\"398\",\"399\",\"400\",\"401\",\"402\",\"403\",\"404\",\"405\",\"406\",\"407\",\"408\",\"409\",\"410\",\"411\",\"412\",\"413\",\"414\",\"415\",\"416\",\"417\",\"418\",\"419\",\"420\",\"421\",\"422\",\"423\",\"424\",\"425\",\"426\",\"427\",\"428\",\"429\",\"430\",\"431\",\"432\",\"433\",\"434\",\"435\",\"436\",\"437\",\"438\",\"439\",\"440\",\"441\",\"442\",\"443\",\"444\",\"445\",\"446\",\"447\",\"448\",\"449\",\"450\",\"451\",\"452\",\"453\",\"454\",\"455\",\"456\",\"457\",\"458\",\"459\",\"460\",\"461\",\"462\",\"463\",\"464\",\"465\",\"466\",\"467\",\"468\",\"469\",\"470\",\"471\",\"472\",\"473\",\"474\",\"475\",\"476\",\"477\",\"478\",\"479\",\"480\",\"481\",\"482\",\"483\",\"484\",\"485\",\"486\",\"487\",\"488\",\"489\",\"490\",\"491\",\"492\",\"493\",\"494\",\"495\",\"496\",\"497\",\"498\",\"499\"])\n</code></pre>\n\n<p>Why do you want to alert this?<br />\n<strong>What problem are you trying to solve?</strong> </p>\n" }, { "answer_id": 185189, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": true, "text": "<p>If you go directly to the script (<a href=\"http://code.katzenbach.com/Default.aspx?callback=callbackFunction&amp;test=true&amp;c=500\" rel=\"nofollow noreferrer\">http://code.katzenbach.com/Default.aspx?callback=callbackFunction&amp;test=true&amp;c=500</a>), you'll see the file (unknown mime type) is not being processed. This is likely due to a problem with your server setup. It doesn't seem to know how to process .aspx and in instead trying to stream out the file.</p>\n" }, { "answer_id": 193233, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "<p>I took a look with Fiddler and IE6 and was unable to see anything out of the ordinary (besides the fact that it freezes the browser).</p>\n\n<p>The request to <code>http://code.katzenbach.com/Default.aspx?callback=callbackFunction&amp;test=true&amp;c=500</code> does get made and returns 2909 bytes.</p>\n\n<p>I'd suggest three things:</p>\n\n<ol>\n<li>Remove one of the semi-colons from your Content-Type: <code>application/json;; charset=utf-8</code> or maybe remove both semi-colons and <code>charset=utf-8</code> entirely (just to test)</li>\n<li>Send a newline character after you're done sending the final <code>)</code> of <code>callbackFunction</code></li>\n<li>Change it to <code>Content-Type: text/javascript</code> because you really are returning Javascript to the browser, and the other content type might be confusing IE6 (although it is very unlikely).</li>\n</ol>\n\n<p>I'm thinking 1. is most likely. There may be a parsing bug in IE6 that causes it to go into an endless loop when it encounters two semi-colons. Because otherwise there simply isn't any reason why what you are doing should not work.</p>\n\n<p>It also might be worthwhile to try a different MIME type as a test.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21832/" ]
Please take a look at the html listed below and let me know why IE6 freezes when trying to load the remote script (located at '<http://code.katzenbach.com/Default.aspx>'). The script returns JSONP and executes the 'callbackFunction' listed in the header. When it runs correctly, you'll see a pop-up alert showing numbers 1-500. This works fine in FF3 and IE7. I can't understand why it fails in Internet Explorer 6 -the processor gets pegged and everything hangs. Run it yourself and let me know if you experience the same problem. I've been staring at this problem all day. Thanks for your help. Andrew ``` <html> <head> <script type="text/javascript"> function callbackFunction(Result) { alert(Result) ; } </script> <script type="text/javascript" src="http://code.katzenbach.com/Default.aspx?callback=callbackFunction&test=true&c=500"></script> </head> <body> Here </body> </html> ```
If you go directly to the script (<http://code.katzenbach.com/Default.aspx?callback=callbackFunction&test=true&c=500>), you'll see the file (unknown mime type) is not being processed. This is likely due to a problem with your server setup. It doesn't seem to know how to process .aspx and in instead trying to stream out the file.
185,187
<p>I have created a common library at work, and it is installed in the GAC on our test server. I've recently updated it and I want all of our applications to be using the update. I created a publisher policy assembly and installed it in the GAC along with the update, but when a web app loads Leggett.Common, 1.0.0.0, it isn't redirected to Leggett.Common, 1.1.0.0.</p> <p>I have the common assembly (there are actually five, but lets keep it simple) on a network drive, I created the publisher policy xml file there next to it and then used al.exe to create the publisher policy assembly in the same folder. After that I put the updated assembly in the GAC and then put the publisher policy assembly in the GAC.</p> <p>The common assembly is 'Leggett.Common.dll', the publisher policy file is '1.1.Leggett.Common.policy', and the publisher policy assembly is 'policy.1.1.Leggett.Common.dll'. </p> <p>The XML for the publisher policy file looks like the following:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;runtime&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="Leggett.Common" publicKeyToken="32cd8f1a53a4c744" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0" newVersion="1.1.0.0"/&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; &lt;/configuration&gt; </code></pre> <p>What am I doing wrong?</p> <p><strong>Clarification</strong><br /> I'm testing this on my local dev machine since developers don't have access to the test server.</p>
[ { "answer_id": 185202, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>Absolutely not. Utility modules over time turn into large collections of cruddy code.</p>\n" }, { "answer_id": 185213, "author": "mannu", "author_id": 15858, "author_profile": "https://Stackoverflow.com/users/15858", "pm_score": 0, "selected": false, "text": "<p>I usually only put things like configuration and constants in a singleton or static class, because it will never change and might as well be \"global\".</p>\n" }, { "answer_id": 185811, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": "<p>You're talking about code that would be shared library stuff. Static methods do have a place in shared libs. Check out System.Linq.Enumerable</p>\n\n<p>I'd follow these guidelines:</p>\n\n<ul>\n<li>These aren't static methods by default. They should only be static methods because they are naturally stateless (behavior only depend on parameters). If they aren't naturally stateless, then you should be making a proper class to manage that state.</li>\n<li>Cover these with Unit Tests. If you don't Unit Test anything else, Unit Test these. This should be very very easy to do. If this isn't easy, this isn't right.</li>\n</ul>\n\n<p>If dependency injection is something you like, you can still have it. Code that relies on a static method could instead be calling a Func(T, U) or an Action that references that static method.</p>\n" }, { "answer_id": 185852, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I've heard some talk that in an 'enterprise level' application it is often considered best practice to avoid large libraries of these static classes and methods. I imagine that it could get quite hard to maintain.</p>\n</blockquote>\n\n<p>IMHO you should apply things like generics to cut down on the size of your utility methods/libraries, and if you only use a utility method in one place, then it doesn't belong in a shared library, but at the end of the day you're still likely to have quite a lot.</p>\n\n<p>At any rate, this perplexes me. If you didn't put them in a shared library where would you put them? Copy/paste into each project or something daft like that?</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3226/" ]
I have created a common library at work, and it is installed in the GAC on our test server. I've recently updated it and I want all of our applications to be using the update. I created a publisher policy assembly and installed it in the GAC along with the update, but when a web app loads Leggett.Common, 1.0.0.0, it isn't redirected to Leggett.Common, 1.1.0.0. I have the common assembly (there are actually five, but lets keep it simple) on a network drive, I created the publisher policy xml file there next to it and then used al.exe to create the publisher policy assembly in the same folder. After that I put the updated assembly in the GAC and then put the publisher policy assembly in the GAC. The common assembly is 'Leggett.Common.dll', the publisher policy file is '1.1.Leggett.Common.policy', and the publisher policy assembly is 'policy.1.1.Leggett.Common.dll'. The XML for the publisher policy file looks like the following: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Leggett.Common" publicKeyToken="32cd8f1a53a4c744" culture="neutral" /> <bindingRedirect oldVersion="1.0.0.0" newVersion="1.1.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> ``` What am I doing wrong? **Clarification** I'm testing this on my local dev machine since developers don't have access to the test server.
You're talking about code that would be shared library stuff. Static methods do have a place in shared libs. Check out System.Linq.Enumerable I'd follow these guidelines: * These aren't static methods by default. They should only be static methods because they are naturally stateless (behavior only depend on parameters). If they aren't naturally stateless, then you should be making a proper class to manage that state. * Cover these with Unit Tests. If you don't Unit Test anything else, Unit Test these. This should be very very easy to do. If this isn't easy, this isn't right. If dependency injection is something you like, you can still have it. Code that relies on a static method could instead be calling a Func(T, U) or an Action that references that static method.
185,203
<p>I'm mostly familiar with Java, C and C++ in which there are ways to control that only one thread is accessing a resource at any given time. Now I'm in search for something similar but in PHP 5.x.</p> <p>To formulate my problem with one example:</p> <p>I have an ASCII-file which only stores a number, the value of a page load counter. At application deployment the file will simply hold a 0. For each access the value will be incremented by one. The goal is to keep track of page loads.</p> <p>The problem comes when many users are concurrently accessing the page containing the counter. When thread A has read the current value, let's say it is 11, another thread which we call B reads the value, still 11. Then the first thread A increments the read value and writes 12 in the file and closes it. Then the second thread B, increments the read value, which was 11, gets 12 and writes that into the file. The value 12 is stored in the file, when it really should have been 13.</p> <p>In another programming language I would have solved this using a mutex. I understand there are mutexes, shared memory and other funcionality as part of modules. But I would like a solution which works on "most servers" out there. Platform independent. Installed on most cheap web hosts. Is there a good solution to this problem? And if there isn't, which way would you take if using a <strong>database is not an option</strong>?</p>
[ { "answer_id": 185218, "author": "terson", "author_id": 22974, "author_profile": "https://Stackoverflow.com/users/22974", "pm_score": 4, "selected": true, "text": "<p>You could try php's variant of flock (<a href=\"http://www.php.net/flock\" rel=\"noreferrer\">http://www.php.net/flock</a>)</p>\n\n<p>I would envision something similar to (this assumes that the file /tmp/counter.txt already exists and has a counter in the file):</p>\n\n<pre><code>&lt;?php\n\n$fp = fopen(\"/tmp/counter.txt\", \"r+\");\n\necho \"Attempt to lock\\n\";\nif (flock($fp, LOCK_EX)) {\n echo \"Locked\\n\";\n // Read current value of the counter and increment\n $cntr = fread($fp, 80);\n $cntr = intval($cntr) + 1;\n\n // Pause to prove that race condition doesn't exist\n sleep(5);\n\n // Write new value to the file\n ftruncate($fp, 0);\n fseek($fp, 0, SEEK_SET);\n fwrite($fp, $cntr);\n flock($fp, LOCK_UN); // release the lock\n fclose($fp);\n}\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 185237, "author": "Magsol", "author_id": 13604, "author_profile": "https://Stackoverflow.com/users/13604", "pm_score": 2, "selected": false, "text": "<p>PHP's flock() function is the route to go. However, you have to make sure that <em>all</em> accesses to the file are protected by a call to flock() first. PHP won't check if the file is locked unless you explicitly make the call to do so.</p>\n\n<p>The concept is virtually identical as with mutexes (protecting shared resources, et al), but it's important enough to bear special emphasis.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm mostly familiar with Java, C and C++ in which there are ways to control that only one thread is accessing a resource at any given time. Now I'm in search for something similar but in PHP 5.x. To formulate my problem with one example: I have an ASCII-file which only stores a number, the value of a page load counter. At application deployment the file will simply hold a 0. For each access the value will be incremented by one. The goal is to keep track of page loads. The problem comes when many users are concurrently accessing the page containing the counter. When thread A has read the current value, let's say it is 11, another thread which we call B reads the value, still 11. Then the first thread A increments the read value and writes 12 in the file and closes it. Then the second thread B, increments the read value, which was 11, gets 12 and writes that into the file. The value 12 is stored in the file, when it really should have been 13. In another programming language I would have solved this using a mutex. I understand there are mutexes, shared memory and other funcionality as part of modules. But I would like a solution which works on "most servers" out there. Platform independent. Installed on most cheap web hosts. Is there a good solution to this problem? And if there isn't, which way would you take if using a **database is not an option**?
You could try php's variant of flock (<http://www.php.net/flock>) I would envision something similar to (this assumes that the file /tmp/counter.txt already exists and has a counter in the file): ``` <?php $fp = fopen("/tmp/counter.txt", "r+"); echo "Attempt to lock\n"; if (flock($fp, LOCK_EX)) { echo "Locked\n"; // Read current value of the counter and increment $cntr = fread($fp, 80); $cntr = intval($cntr) + 1; // Pause to prove that race condition doesn't exist sleep(5); // Write new value to the file ftruncate($fp, 0); fseek($fp, 0, SEEK_SET); fwrite($fp, $cntr); flock($fp, LOCK_UN); // release the lock fclose($fp); } ?> ```
185,208
<p>How can I get Environnment variables and if something is missing, set the value?</p>
[ { "answer_id": 185214, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 9, "selected": true, "text": "<p>Use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.environment\" rel=\"noreferrer\">System.Environment</a> class.</p>\n\n<p>The methods</p>\n\n<pre><code>var value = System.Environment.GetEnvironmentVariable(variable [, Target])\n</code></pre>\n\n<p>and </p>\n\n<pre><code>System.Environment.SetEnvironmentVariable(variable, value [, Target])\n</code></pre>\n\n<p>will do the job for you. </p>\n\n<p>The optional parameter <code>Target</code> is an enum of type <code>EnvironmentVariableTarget</code> and it can be one of: <code>Machine</code>, <code>Process</code>, or <code>User</code>. If you omit it, the default target is the <strong>current process.</strong></p>\n" }, { "answer_id": 2763116, "author": "SpeedyNinja", "author_id": 331416, "author_profile": "https://Stackoverflow.com/users/331416", "pm_score": 4, "selected": false, "text": "<p>This will work for an environment variable that is machine setting. For Users, just change to User instead. </p>\n\n<pre><code>String EnvironmentPath = System.Environment\n .GetEnvironmentVariable(\"Variable_Name\", EnvironmentVariableTarget.Machine);\n</code></pre>\n" }, { "answer_id": 9845159, "author": "Nathan Bedford", "author_id": 434, "author_profile": "https://Stackoverflow.com/users/434", "pm_score": 5, "selected": false, "text": "<p>I ran into this while working on a .NET console app to read the PATH environment variable, and found that using System.Environment.GetEnvironmentVariable will expand the environment variables automatically.</p>\n\n<p>I didn't want that to happen...that means folders in the path such as '%SystemRoot%\\system32' were being re-written as 'C:\\Windows\\system32'. To get the un-expanded path, I had to use this:</p>\n\n<pre><code>string keyName = @\"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\\";\nstring existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue(\"PATH\", \"\", RegistryValueOptions.DoNotExpandEnvironmentNames);\n</code></pre>\n\n<p>Worked like a charm for me.</p>\n" }, { "answer_id": 11760142, "author": "Karthik Chintala", "author_id": 1551730, "author_profile": "https://Stackoverflow.com/users/1551730", "pm_score": 3, "selected": false, "text": "<pre><code>Environment.SetEnvironmentVariable(\"Variable name\", value, EnvironmentVariableTarget.User);\n</code></pre>\n" }, { "answer_id": 17033912, "author": "Tom Stickel", "author_id": 756246, "author_profile": "https://Stackoverflow.com/users/756246", "pm_score": 5, "selected": false, "text": "<p><strong><em>Get and Set</em></strong></p>\n\n<p><strong>Get</strong></p>\n\n<pre><code>string getEnv = Environment.GetEnvironmentVariable(\"envVar\");\n</code></pre>\n\n<p><strong>Set</strong></p>\n\n<pre><code>string setEnv = Environment.SetEnvironmentVariable(\"envvar\", varEnv);\n</code></pre>\n" }, { "answer_id": 39141893, "author": "Ajit", "author_id": 1986966, "author_profile": "https://Stackoverflow.com/users/1986966", "pm_score": 0, "selected": false, "text": "<p>I could be able to update the environment variable by using the following</p>\n\n<pre><code>string EnvPath = System.Environment.GetEnvironmentVariable(\"PATH\", EnvironmentVariableTarget.Machine) ?? string.Empty;\nif (!string.IsNullOrEmpty(EnvPath) &amp;&amp; !EnvPath .EndsWith(\";\"))\n EnvPath = EnvPath + ';';\nEnvPath = EnvPath + @\"C:\\Test\";\nEnvironment.SetEnvironmentVariable(\"PATH\", EnvPath , EnvironmentVariableTarget.Machine);\n</code></pre>\n" }, { "answer_id": 65661184, "author": "Vijendran Selvarajah", "author_id": 7605370, "author_profile": "https://Stackoverflow.com/users/7605370", "pm_score": 1, "selected": false, "text": "<p>If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through <a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.environmentvariablesextensions.addenvironmentvariables?view=dotnet-plat-ext-5.0\" rel=\"nofollow noreferrer\">EnvironmentVariablesExtensions</a>.</p>\n<pre><code>var builder = new ConfigurationBuilder()\n .AddJsonFile(&quot;appSettings.json&quot;)\n .AddEnvironmentVariables(prefix: &quot;ABC_&quot;)\n\nvar config = builder.Build();\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/fz2Lr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fz2Lr.png\" alt=\"enter image description here\" /></a></p>\n<p>According to this example, Url for the environment is read from the appsettings.json. but when the <code>AddEnvironmentVariables(prefix: &quot;ABC_&quot;)</code> line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.</p>\n" }, { "answer_id": 66724014, "author": "D. Kermott", "author_id": 1620607, "author_profile": "https://Stackoverflow.com/users/1620607", "pm_score": 0, "selected": false, "text": "<p>In Visual Studio 2019 -- Right Click on your project, select Properties &gt; Settings, Add a new variable by giving it a name (like ConnectionString), type, and value. Then in your code read it so:</p>\n<pre><code>var sConnectionStr = Properties.Settings.Default.ConnectionString;\n</code></pre>\n<p>These variables will be stored in a config file (web.config or app.config) depending upon your type of project. Here's an example of what it would look like:</p>\n<pre><code> &lt;applicationSettings&gt;\n &lt;Testing.Properties.Settings&gt;\n &lt;setting name=&quot;ConnectionString&quot; serializeAs=&quot;String&quot;&gt;\n &lt;value&gt;data source=blah-blah;etc-etc&lt;/value&gt;\n &lt;/setting&gt;\n &lt;/Testing.Properties.Settings&gt;\n &lt;/applicationSettings&gt;\n</code></pre>\n" }, { "answer_id": 68708239, "author": "OfirD", "author_id": 3002584, "author_profile": "https://Stackoverflow.com/users/3002584", "pm_score": 0, "selected": false, "text": "<p>Environment variables can also be placed in an application's <code>app.config</code> or <code>web.config</code> file, by their name bounded with percentages (<code>%</code>), and then expanded in code.</p>\n<ul>\n<li>Note that when a value of an environment variable is changed (or a new one is set), Visual Studio should be closed and reopened.</li>\n</ul>\n<p>For example, in <code>app.config</code>:</p>\n<pre><code>&lt;connectionStrings&gt;\n &lt;add name=&quot;myConnectionString&quot; connectionString=&quot;%DEV_SQL_SERVER_CONNECTION_STRING%&quot; providerName=&quot;System.Data.SqlClient&quot; /&gt;\n&lt;/connectionStrings&gt;\n</code></pre>\n<p>And then in the code:</p>\n<pre><code>string connectionStringEnv = ConfigurationManager.AppSettings[&quot;myConnectionString&quot;];\nstring connectionString = System.Environment.ExpandEnvironmentVariables(connectionStringEnv); \n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14441/" ]
How can I get Environnment variables and if something is missing, set the value?
Use the [System.Environment](https://learn.microsoft.com/en-us/dotnet/api/system.environment) class. The methods ``` var value = System.Environment.GetEnvironmentVariable(variable [, Target]) ``` and ``` System.Environment.SetEnvironmentVariable(variable, value [, Target]) ``` will do the job for you. The optional parameter `Target` is an enum of type `EnvironmentVariableTarget` and it can be one of: `Machine`, `Process`, or `User`. If you omit it, the default target is the **current process.**
185,235
<p>I've previously used <a href="https://jqueryui.com/tabs/" rel="nofollow noreferrer"><code>jquery-ui tabs</code></a> extension to load page fragments via <code>ajax</code>, and to conceal or reveal hidden <code>div</code>s within a page. Both of these methods are well documented, and I've had no problems there.</p> <p>Now, however, I want to do something different with tabs. When the user selects a tab, it should reload the page entirely - the reason for this is that the contents of each tabbed section are somewhat expensive to render, so I don't want to just send them all at once and use the normal method of toggling 'display:none' to reveal them.</p> <p>My plan is to intercept the tabs' <code>select</code> event, and have that function reload the page with by manipulating document.location.</p> <p>How, in the <code>select</code> handler, can I get the newly selected tab index and the html LI object it corresponds to?</p> <pre><code>$('#edit_tabs').tabs( { selected: 2, // which tab to start on when page loads select: function(e, ui) { var t = $(e.target); // alert("data is " + t.data('load.tabs')); // undef // alert("data is " + ui.data('load.tabs')); // undef // This gives a numeric index... alert( "selected is " + t.data('selected.tabs') ) // ... but it's the index of the PREVIOUSLY selected tab, not the // one the user is now choosing. return true; // eventual goal is: // ... document.location= extract-url-from(something); return false; } }); </code></pre> <p>Is there an attribute of the event or ui object that I can read that will give the index, id, or object of the newly selected tab or the anchor tag within it? </p> <p>Or is there a better way altogether to use tabs to reload the entire page?</p>
[ { "answer_id": 185257, "author": "imjoevasquez", "author_id": 24630, "author_profile": "https://Stackoverflow.com/users/24630", "pm_score": 6, "selected": true, "text": "<p>I would take a look at the <a href=\"http://docs.jquery.com/UI/Tabs#Events\" rel=\"noreferrer\">events</a> for Tabs. The following is taken from the jQuery docs:</p>\n\n<pre><code> $('.ui-tabs-nav').bind('tabsselect', function(event, ui) {\n ui.options // options used to intialize this widget\n ui.tab // anchor element of the selected (clicked) tab\n ui.panel // element, that contains the contents of the selected (clicked) tab\n ui.index // zero-based index of the selected (clicked) tab\n });\n</code></pre>\n\n<p>Looks like ui.tab is the way to go.</p>\n" }, { "answer_id": 185354, "author": "Matt Hucke", "author_id": 2554901, "author_profile": "https://Stackoverflow.com/users/2554901", "pm_score": 0, "selected": false, "text": "<p>thanks, jobscry - the 'ui.tab' you pointed out gave me the clicked anchor tag, from which I can extract its class, id, href, etc... I choose to use the id to encode my url. My final tabs() call looks like this:</p>\n\n<pre><code>$(document).ready(function() {\n $('#edit_tabs').tabs( {\n selected: [% page.selected_tab ? page.selected_tab : 0 %],\n select: function(e, ui) {\n // ui.tab is an 'a' object\n // it has an id of \"link_foo_bar\"\n // transform it into http://....something&amp;cmd=foo-bar\n var url = idToTabURL(ui.tab.id);\n\n document.location = url;\n return false;\n }\n }).show();\n});\n</code></pre>\n" }, { "answer_id": 186665, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>in my implementation it works like:</p>\n\n<pre><code>$(document).ready(function() {\n $('#edit_tabs').tabs( {\n selected: [% page.selected_tab ? page.selected_tab : 0 %],\n select: function(e, ui) {\n // ui.tab is an 'a' object\n var url = ui.tab.href;\n\n document.location = url;\n return false;\n }\n }).show();\n});\n</code></pre>\n" }, { "answer_id": 992336, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Or another option I have used for my website is this. Its a basic UL/Div Tab Navigation System. The key to firing the correct tab upon clicking a link to another page with a hash mark attached, is by simply filtering through your UL for the #example that matches whats being passed through the browser. Its like so.</p>\n\n<p>Here is the example HTML :</p>\n\n<pre><code> &lt;div id=\"tabNav\"&gt;\n\n &lt;ul class=\"tabs\"&gt;\n &lt;li&gt;&lt;a href=\"#message\"&gt;Send a message&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#shareFile\"&gt;Share a file&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#arrange\"&gt;Arrange a meetup&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n\n&lt;div id=\"tabCont\"&gt;\n\n &lt;div id=\"message\"&gt;\n &lt;p&gt;Lorem ipsum dolor sit amet.&lt;/p&gt;\n &lt;/div&gt;\n &lt;div id=\"shareFile\"&gt;\n &lt;p&gt;Sed do eiusmod tempor incididunt.&lt;/p&gt;\n &lt;/div&gt;\n &lt;div id=\"arrange\"&gt;\n &lt;p&gt;Ut enim ad minim veniam&lt;/p&gt;\n &lt;/div&gt;\n\n&lt;/div&gt;\n</code></pre>\n\n<p>And the Jquery to make it happen :</p>\n\n<pre><code>$(document).ready(function() {\n$(function () {\n var tabs = [];\n var tabContainers = [];\n\n $('ul.tabs a').each(function () {\n // note that this only compares the pathname, not the entire url\n // which actually may be required for a more terse solution.\n if (this.pathname == window.location.pathname) {\n tabs.push(this);\n tabContainers.push($(this.hash).get(0));\n }\n });\n\n $(tabs).click(function () {\n // hide all tabs\n $(tabContainers).hide().filter(this.hash).show();\n\n\n // set up the selected class\n $(tabs).removeClass('active');\n $(this).addClass('active');\n\n return false;\n\n});\n\n\n\n\n $(tabs).filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();\n\n });\n\n});\n</code></pre>\n\n<p>That should take care of it for you. I knwo this isn't the cleanest code, but it'll get ya there.</p>\n" }, { "answer_id": 3564091, "author": "user376026", "author_id": 376026, "author_profile": "https://Stackoverflow.com/users/376026", "pm_score": 3, "selected": false, "text": "<pre><code>select: function(e, ui){var index=ui.index;}\n</code></pre>\n\n<p>works well for me. see: <a href=\"http://api.jqueryui.com/tabs/#events\" rel=\"nofollow noreferrer\">http://api.jqueryui.com/tabs/#events</a></p>\n" }, { "answer_id": 7367203, "author": "Ekta", "author_id": 792959, "author_profile": "https://Stackoverflow.com/users/792959", "pm_score": 0, "selected": false, "text": "<p>I did find out two ways to to accomplish this requirement, as it's tough for me to put code here, you can have a look at it on <a href=\"http://ektaraval.blogspot.com/2011/09/calling-javascript-when-jquery-ui-tab.html\" rel=\"nofollow\">http://ektaraval.blogspot.com/2011/09/calling-javascript-when-jquery-ui-tab.html</a></p>\n\n<p>Hope that helps someone..</p>\n" }, { "answer_id": 12813783, "author": "Yasser Shaikh", "author_id": 1182982, "author_profile": "https://Stackoverflow.com/users/1182982", "pm_score": 0, "selected": false, "text": "<p>A quick look into the documentation gives us the solution: </p>\n\n<pre><code>$('#edit_tabs').tabs({ selected: 2 }); \n</code></pre>\n\n<p>The above statement will activate the third tab.</p>\n" }, { "answer_id": 14560636, "author": "aorlando", "author_id": 1396276, "author_profile": "https://Stackoverflow.com/users/1396276", "pm_score": 3, "selected": false, "text": "<p>in jQuery UI - v1.9.2</p>\n\n<pre><code>ui.newTab.index()\n</code></pre>\n\n<p>to get a base 0 index of active tab</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2554901/" ]
I've previously used [`jquery-ui tabs`](https://jqueryui.com/tabs/) extension to load page fragments via `ajax`, and to conceal or reveal hidden `div`s within a page. Both of these methods are well documented, and I've had no problems there. Now, however, I want to do something different with tabs. When the user selects a tab, it should reload the page entirely - the reason for this is that the contents of each tabbed section are somewhat expensive to render, so I don't want to just send them all at once and use the normal method of toggling 'display:none' to reveal them. My plan is to intercept the tabs' `select` event, and have that function reload the page with by manipulating document.location. How, in the `select` handler, can I get the newly selected tab index and the html LI object it corresponds to? ``` $('#edit_tabs').tabs( { selected: 2, // which tab to start on when page loads select: function(e, ui) { var t = $(e.target); // alert("data is " + t.data('load.tabs')); // undef // alert("data is " + ui.data('load.tabs')); // undef // This gives a numeric index... alert( "selected is " + t.data('selected.tabs') ) // ... but it's the index of the PREVIOUSLY selected tab, not the // one the user is now choosing. return true; // eventual goal is: // ... document.location= extract-url-from(something); return false; } }); ``` Is there an attribute of the event or ui object that I can read that will give the index, id, or object of the newly selected tab or the anchor tag within it? Or is there a better way altogether to use tabs to reload the entire page?
I would take a look at the [events](http://docs.jquery.com/UI/Tabs#Events) for Tabs. The following is taken from the jQuery docs: ``` $('.ui-tabs-nav').bind('tabsselect', function(event, ui) { ui.options // options used to intialize this widget ui.tab // anchor element of the selected (clicked) tab ui.panel // element, that contains the contents of the selected (clicked) tab ui.index // zero-based index of the selected (clicked) tab }); ``` Looks like ui.tab is the way to go.
185,240
<p>I have an import-from-excel script as part of a CMS that previously ran without issue.</p> <p>My shared-hosting provider has recently upgraded their infrastructure, including PHP from 5.1 to 5.2.6, and the script now returns "Uninitialized string offset: -XXX in /path/scriptname.php on line 27" (XXX being a decreasing number from 512 and /path/scriptname.php of course being the full path to script in question). </p> <p>It returns this error for every line of the excel file. Line 27 is just a return from within a function that is the first point at which the imported data is being processed:</p> <pre><code>function GetInt4d($data, $pos) { return ord($data[$pos]) | (ord($data[$pos+1]) &lt;&lt; 8) | (ord($data[$pos+2]) &lt;&lt; 16) | (ord($data[$pos+3]) &lt;&lt; 24); } </code></pre> <p>It finally implodes with a "Fatal error: Allowed memory size of 47185920 bytes exhausted (tried to allocate 71 bytes) in /path/scriptname.php on line 133".</p> <p>There's nothing useful in Apache error logs. I am stumped. Anyone have any ideas of at least where to look? Even knowing if it's likely to be something within my script or something to do with upgrade would be useful. I had another issue with a different site on same provider that (after upgrade) couldn't write sessions to tmp directory (since resolved), but am pretty sure it's not that (?).</p> <p>EDIT: As it turned out that the answer was to do with the version of the parser being incompatible in some way with PHP 5.2.6, I thought it might be of use to someone that the parser in question is <a href="http://sourceforge.net/project/showfiles.php?group_id=99160&amp;package_id=106368" rel="nofollow noreferrer">Spreadsheet Excel Reader</a> .</p>
[ { "answer_id": 189625, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Uninitialized string offset:</p>\n</blockquote>\n\n<p>... means that <code>$data</code> is not an array.</p>\n" }, { "answer_id": 189774, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 1, "selected": false, "text": "<p>Thanks for the input, the situation has 'resolved itself' via me finding a more recent version of the parsing library I was using. My guess is the issue was something to do with the difference between php versions, though I'm unsure exactly what. Fixed but frustrating.</p>\n\n<p>EDIT: I'm going to accept Till's answer purely in the interests of closing the question. Thx again for input.</p>\n" }, { "answer_id": 507491, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Solved here:\n<a href=\"http://www.phpbuilder.com/board/archive/index.php/t-10328608.html\" rel=\"nofollow noreferrer\">http://www.phpbuilder.com/board/archive/index.php/t-10328608.html</a></p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14979/" ]
I have an import-from-excel script as part of a CMS that previously ran without issue. My shared-hosting provider has recently upgraded their infrastructure, including PHP from 5.1 to 5.2.6, and the script now returns "Uninitialized string offset: -XXX in /path/scriptname.php on line 27" (XXX being a decreasing number from 512 and /path/scriptname.php of course being the full path to script in question). It returns this error for every line of the excel file. Line 27 is just a return from within a function that is the first point at which the imported data is being processed: ``` function GetInt4d($data, $pos) { return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24); } ``` It finally implodes with a "Fatal error: Allowed memory size of 47185920 bytes exhausted (tried to allocate 71 bytes) in /path/scriptname.php on line 133". There's nothing useful in Apache error logs. I am stumped. Anyone have any ideas of at least where to look? Even knowing if it's likely to be something within my script or something to do with upgrade would be useful. I had another issue with a different site on same provider that (after upgrade) couldn't write sessions to tmp directory (since resolved), but am pretty sure it's not that (?). EDIT: As it turned out that the answer was to do with the version of the parser being incompatible in some way with PHP 5.2.6, I thought it might be of use to someone that the parser in question is [Spreadsheet Excel Reader](http://sourceforge.net/project/showfiles.php?group_id=99160&package_id=106368) .
> > Uninitialized string offset: > > > ... means that `$data` is not an array.
185,252
<p>I have a Flex application where load time is extremely important (consumer site). i want to be able to get something up on screen and then allow additional modules to be loaded as necessary.</p> <p>The issue I'm facing is that the sum total of all the modules is much larger than if i were to include all the components in a single .swf file.</p> <p>Its pretty obvious why. For instance the classes needed for web service access seem to take about 100kb. If I dont use those classes in my main.swf then they'll be included in EVERY module that uses them. So if I have 5 modules thats an extra 500kB wasted.</p> <p>In theory I want 3 levels</p> <p>main.swf - minimum possible layout / style / font / framework type stuff common.swf - additional classes needed by module 1 + module 2 (such as web services) module1.swf - module 1 in site module2.swf - module 2 in site</p> <p>I dont know if this is even possible.</p> <p>I'm wondering if I can load swz/swf files for portions of the framework instead of the entire framework.</p> <p>I really need to get my main app size down to 200Kb. It grows to 450kb when I add web services and basic datagrid functionality.</p> <p>Any lessons learned would be appreciated.</p>
[ { "answer_id": 188095, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 0, "selected": false, "text": "<p>You could look into the <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=modular_5.html#171081\" rel=\"nofollow noreferrer\">ModuleLoader</a> class, maybe you can load up your core stuff in the first 200kbs then load the rest when and if it's needed.</p>\n\n<p>Also it's worth bearing in mind that any SWC's you use are embedded at compile time whereas any SWF's are loaded at runtime.</p>\n" }, { "answer_id": 194615, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 1, "selected": false, "text": "<p>Flex is a bit of a pig when it comes to file size. There really is only one way to get your app sizes down and that is to use an external swz for the framework. There is an Adobe Devnet article on <a href=\"http://www.adobe.com/devnet/flex/articles/flash_player_cache_02.html\" rel=\"nofollow noreferrer\">Improving Flex application performance using the Flash Player cache</a> which I recommend you read.</p>\n\n<p>On a project I worked on we had problems with our preloading module sucking in classes that we didn't want. What we had to do was create interfaces to the classes that resided in the other modules and reference them that way. When the module is loaded we simply assigned a reference to the IApplicationModule in order to call our initialization code.</p>\n\n<p>Also look into putting your classes into a seperate SWF file and then use ApplicationDomain to get access to the classes </p>\n\n<p>(this code taken from <a href=\"http://flashdevelop.org/community/viewtopic.php?t=3387\" rel=\"nofollow noreferrer\">this forum post</a> which explains how to access classes loaded from modules in Flex)</p>\n\n<pre><code>\nprivate function loadContent(path:String):void \n{\n var contentLoader:Loader = new Loader();\n contentLoader.contentLoaderInfo.addEventListener(\n Event.COMPLETE,\n loadContent_onComplete);\n contentLoader.load(new URLRequest(path));\n}\n\n\nprivate function loadContent_onComplete (event:Event):void\n{ \n var content:DisplayObject = event.target.content;\n\n if(content is IFlexModuleFactory) \n {\n var content_onReady:Function = function (event:Event):void \n { \n var factory:IFlexModuleFactory = content as IFlexModuleFactory;\n var info:Object = factory.info();\n var instanceClass:Class = info.currentDomain.getDefinition(\n info.mainClassName) as Class;\n\n addChild (new instanceClass ());\n }\n\n content.addEventListener (\"ready\", content_onReady);\n\n } \n else\n {\n addChild (content); \n }\n}\n</code></pre>\n" }, { "answer_id": 399161, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>There is an option on the command-line compiler to exclude class definitions that are already compiled into another swf. It works like this:</p>\n\n<ol>\n<li>Compile the Main Application (which contains a loader) and opt to generate a report.</li>\n<li>Compile the Module and opt to exclude classes in the above report.</li>\n</ol>\n" }, { "answer_id": 675967, "author": "evanmcd", "author_id": 78199, "author_profile": "https://Stackoverflow.com/users/78199", "pm_score": 2, "selected": false, "text": "<p>I know this was awhile ago, but I figured I'd post another response in case anyone is still looking for an answer on this.</p>\n\n<p>I've been looking into optimizing Flex apps and, after some checking into it, have decided to use Modules. Primarily 'cause they have such good options for optimization.</p>\n\n<p>The two mxmlc commands you need are:</p>\n\n<pre><code>mxmlc -link-report=MyAppReport.xml MyApp.mxml\n</code></pre>\n\n<p>and</p>\n\n<pre><code>mxmlc -load-externs=MyAppReport.xml MyModule.mxml\n</code></pre>\n\n<p>My external swf (using the Flex Framework) is now only 21k. It's doing much (yet), but even as it does more and more, it will continue to use resources from the main app code.</p>\n\n<p>Here's the batch file I created to speed up the process (you have to have put mxmlc in your Environment Path variable for it to work like this. Control Panel -> System -> Advanced -> Environment Variables, Edit the Path System Variable, adding the path to your mxmlc (requires a reboot)):</p>\n\n<pre><code>cd C:\\Projects\\MyProject\\Develop\\Modules\nmxmlc -link-report=MyAppReport.xml C:\\Projects\\MyProject\\Develop\\Source\\Main.mxml\nmxmlc -load-externs=MyAppReport.xml MyModule.mxml\nmove /Y MyModule.swf ..\\Runtime\\Modules\n</code></pre>\n\n<p>More info here:\n<a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=modular_4.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/html/help.html?content=modular_4.html</a></p>\n\n<p>Hope that helps!</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
I have a Flex application where load time is extremely important (consumer site). i want to be able to get something up on screen and then allow additional modules to be loaded as necessary. The issue I'm facing is that the sum total of all the modules is much larger than if i were to include all the components in a single .swf file. Its pretty obvious why. For instance the classes needed for web service access seem to take about 100kb. If I dont use those classes in my main.swf then they'll be included in EVERY module that uses them. So if I have 5 modules thats an extra 500kB wasted. In theory I want 3 levels main.swf - minimum possible layout / style / font / framework type stuff common.swf - additional classes needed by module 1 + module 2 (such as web services) module1.swf - module 1 in site module2.swf - module 2 in site I dont know if this is even possible. I'm wondering if I can load swz/swf files for portions of the framework instead of the entire framework. I really need to get my main app size down to 200Kb. It grows to 450kb when I add web services and basic datagrid functionality. Any lessons learned would be appreciated.
I know this was awhile ago, but I figured I'd post another response in case anyone is still looking for an answer on this. I've been looking into optimizing Flex apps and, after some checking into it, have decided to use Modules. Primarily 'cause they have such good options for optimization. The two mxmlc commands you need are: ``` mxmlc -link-report=MyAppReport.xml MyApp.mxml ``` and ``` mxmlc -load-externs=MyAppReport.xml MyModule.mxml ``` My external swf (using the Flex Framework) is now only 21k. It's doing much (yet), but even as it does more and more, it will continue to use resources from the main app code. Here's the batch file I created to speed up the process (you have to have put mxmlc in your Environment Path variable for it to work like this. Control Panel -> System -> Advanced -> Environment Variables, Edit the Path System Variable, adding the path to your mxmlc (requires a reboot)): ``` cd C:\Projects\MyProject\Develop\Modules mxmlc -link-report=MyAppReport.xml C:\Projects\MyProject\Develop\Source\Main.mxml mxmlc -load-externs=MyAppReport.xml MyModule.mxml move /Y MyModule.swf ..\Runtime\Modules ``` More info here: <http://livedocs.adobe.com/flex/3/html/help.html?content=modular_4.html> Hope that helps!
185,291
<p>This is kinda a general question, open for opinions. I've been trying to come up with a good way to design for localization of string resources for a Windows MFC application and related utilities. My wishlist is:</p> <ul> <li>Must preserve string literals in code (as opposed to replacing with macro #define resource ID's), so that the messages are still readable inline</li> <li>Must allow localized string resources (duh)</li> <li>Must not impose additional run-time environment restrictions (eg: dependency on .NET, etc.)</li> <li>Should have minimal obtrusion into existing code (the less modification the better)</li> <li>Should be debuggable</li> <li>Should generate resource files which are editable by common tools (ie: common format)</li> <li>Should not use copy/paste comment blocks to preserve literal strings in code, or anything else which creates the potential for de-synchronization</li> <li>Would be nice to allow static (compile-time) checking that every "notated" string is in the resource file(s)</li> <li>Would be nice to allow cross-language resource string pooling (for components in various languages, eg: native C++ and .NET)</li> </ul> <p>I have a way which fulfills all my wishlist to some extent except for static checking, but I have had to develop a bit of custom code to achieve it (and it has limitations). I'm wondering if anyone has solved this problem in a particularly good way.</p> <p>Edit: The solution I currently have looks like this:</p> <pre><code>ShowMessage( RESTRING( _T("Some string") ) ); ShowMessage( RESTRING( _T("Some string with variable %1"), sNonTranslatedStringVariable ) ); </code></pre> <p>I then have a custom utility to parse out the strings from within the 'RESTRING' blocks and put them into a .resx file for localization, and a separate C# COM object to load them from localized resource files with fallback. If the C# object is not available (or cannot load), I fallback to the string in the code. The macro expands to a template class which calls the COM object and does the formatting, etc.</p> <p>Anyway, I thought it would be useful to add what I have now for reference.</p>
[ { "answer_id": 185318, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 0, "selected": false, "text": "<p>On one project I had localized into 10+ languages, I put everything that was to be localized into a single resource-only dll. At install time, the user selected which dll got installed with their application.</p>\n\n<p>I only had to deliver the English dll to the localization team. They returned a localized dll to me for each language which I included in the build.</p>\n\n<p>I know it's not perfect, but it worked.</p>\n" }, { "answer_id": 185329, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 1, "selected": false, "text": "<p>I don't know much about how this is normally done on Windows, but the way localized strings are handled in Apple's <a href=\"http://developer.apple.com/documentation/MacOSX/Conceptual/BPInternational/Articles/StringsFiles.html\" rel=\"nofollow noreferrer\">Cocoa framework</a> works pretty well. They have a very basic text-format file that you can send to a translator, and some preprocessor macros to retrieve the values from the files.</p>\n\n<p>In your code, you'll see the strings in your native language, rather than as opaque IDs.</p>\n" }, { "answer_id": 185356, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>We use the English string as the ID.</p>\n\n<p>If it fails the look up from the international resource object (loaded from the I18N dll installed) then we default to the ID string.</p>\n\n<p>Code looks like:</p>\n\n<pre><code>doAction(I18N.get(\"Press OK to continue\"));\n</code></pre>\n\n<p>As part of the build processes we have a perl script that parses all source for string constants. It builds a temp file of all strings in the application and then compares these against the resource strings in each local to see if they exists. Any missing strings generates an e-mail to the appropriate translation team.</p>\n\n<p>We can have multiple dll for each local. The name of the dll is based on RFC 3066<br>\nlanguage[_territory][.codeset][@modifier]</p>\n\n<p>We try and extract the locale from the machine and be as specific as possible when loading the I18N dll but fallback to less specific local variations if the more specific version is not present.</p>\n\n<p>Example:</p>\n\n<p>In the UK: If the local was <b>en_GB.UTF-8</b><br>\n(I use the term dll loosely not in the specific windows sense).</p>\n\n<p>First look for the <b>I18N.en_GB.UTF-8</b> dll. If this dll does not exist fall back to <b>I18N.en_GB</b>. If this dll does not exist fall back to <b>I18N.en</b> If this dll does not exist fall beck to <b>I18N.default</b></p>\n\n<p>The only exception to this rule is:\nSimplified Chinese (zh_CN) where the fallback is US English (en_US). If the machine does not support simplified Chinese then it is unlikely to support full Chinese.</p>\n" }, { "answer_id": 185700, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 1, "selected": false, "text": "<p>Since it is open for opinions, here is how I do it.</p>\n\n<p>My localized text file is a simple tab delimited text file that can be loaded in Excel and edited.\nThe first column is for the define and each column to the right is a subsequent language, for example:</p>\n\n<pre><code>ID ENGLISH FRENCH GERMAN\nSTRING_YES YES OUI YA\nSTRING_NO NO NON NEIN\n</code></pre>\n\n<p>Then in my makefile is a cusom build step that generates a strings.h file and a strings.dat. In my case it builds an enum list for the string ids and then a binary file with offsets for the text. Since in my app the user can change the language at any time i have them all in memory but you could easily have your pre-processer generate a different output file for each language if necessary.</p>\n\n<p>The thing that I like about this design is that if any strings are missing then I would get a compile error whereas if strings were looked up at runtime then you might not know about a missing string in a seldom used part of the code until later.</p>\n" }, { "answer_id": 188642, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 0, "selected": false, "text": "<p>You want an advanced utility that I've always wanted to write but never had the time to.\nIf you don't find such a tool, you may want to fallback on my CMsg() and CFMsg() wrapper classes that allow to very easily pull strings from the resource table. (CFMsg even provide a FormatMessage one-liner wrapper.\nAnd yes, in the absence of that tool you're looking for, keeping a copy of the string in comment is a good solution. Regarding desynchronisation of the comment, remember that string literals are very rarely changed.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/string/stringtable.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/string/stringtable.aspx</a></p>\n\n<p>BTW, native Win32 programs and .NET programs have a totally different resource storage management. You'll have a hard time finding a common solution for both.</p>\n" }, { "answer_id": 191799, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "<p>Your solution is quite similar to the Unix/Linux \"<code>gettext</code>\" solution. In fact, you would not need to write the extraction routines.</p>\n\n<p>I'm not sure why you want the _RESTRING macro to handle multiple arguments. My code (using wxWidgets' support for gettext) looks like this: <code>MyString.Format(_(\"Some string with variable %ls\"), _(\"variable\"));</code>. That is to say, String::Format(...) gets two individually translated arguments. In hindsight, Boost::Format would have been better, but it too would allow <code>boost::format(_(\"Some string with variable %1\")) % _(\"variable\");</code></p>\n\n<p>(We use the <code>_()</code> macro for brevity)</p>\n" }, { "answer_id": 232321, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>The simple way is to only use string IDs in your code - no literal strings.\nYou can then produce different versions of the.rc file for each language and either create resource only DLLs or simply different language builds.</p>\n\n<p>There are a couple of shareware utilstohelp localising the rc file which handle resizing dialog elements for languages with longer words and warnign about missing translations.</p>\n\n<p>A more complicated problem is word order, if you have several numbers in a printf which must be in a different order for different language's grammar. \nThere are some extended printf classes on codeproject that let you specify things like printf(\"word %1s and %2s\",var1,var2) so you can switch %1s and %2s if necessary.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26240/" ]
This is kinda a general question, open for opinions. I've been trying to come up with a good way to design for localization of string resources for a Windows MFC application and related utilities. My wishlist is: * Must preserve string literals in code (as opposed to replacing with macro #define resource ID's), so that the messages are still readable inline * Must allow localized string resources (duh) * Must not impose additional run-time environment restrictions (eg: dependency on .NET, etc.) * Should have minimal obtrusion into existing code (the less modification the better) * Should be debuggable * Should generate resource files which are editable by common tools (ie: common format) * Should not use copy/paste comment blocks to preserve literal strings in code, or anything else which creates the potential for de-synchronization * Would be nice to allow static (compile-time) checking that every "notated" string is in the resource file(s) * Would be nice to allow cross-language resource string pooling (for components in various languages, eg: native C++ and .NET) I have a way which fulfills all my wishlist to some extent except for static checking, but I have had to develop a bit of custom code to achieve it (and it has limitations). I'm wondering if anyone has solved this problem in a particularly good way. Edit: The solution I currently have looks like this: ``` ShowMessage( RESTRING( _T("Some string") ) ); ShowMessage( RESTRING( _T("Some string with variable %1"), sNonTranslatedStringVariable ) ); ``` I then have a custom utility to parse out the strings from within the 'RESTRING' blocks and put them into a .resx file for localization, and a separate C# COM object to load them from localized resource files with fallback. If the C# object is not available (or cannot load), I fallback to the string in the code. The macro expands to a template class which calls the COM object and does the formatting, etc. Anyway, I thought it would be useful to add what I have now for reference.
We use the English string as the ID. If it fails the look up from the international resource object (loaded from the I18N dll installed) then we default to the ID string. Code looks like: ``` doAction(I18N.get("Press OK to continue")); ``` As part of the build processes we have a perl script that parses all source for string constants. It builds a temp file of all strings in the application and then compares these against the resource strings in each local to see if they exists. Any missing strings generates an e-mail to the appropriate translation team. We can have multiple dll for each local. The name of the dll is based on RFC 3066 language[\_territory][.codeset][@modifier] We try and extract the locale from the machine and be as specific as possible when loading the I18N dll but fallback to less specific local variations if the more specific version is not present. Example: In the UK: If the local was **en\_GB.UTF-8** (I use the term dll loosely not in the specific windows sense). First look for the **I18N.en\_GB.UTF-8** dll. If this dll does not exist fall back to **I18N.en\_GB**. If this dll does not exist fall back to **I18N.en** If this dll does not exist fall beck to **I18N.default** The only exception to this rule is: Simplified Chinese (zh\_CN) where the fallback is US English (en\_US). If the machine does not support simplified Chinese then it is unlikely to support full Chinese.
185,314
<p>I have a C# app which uses a System.Diagnostics.Process to run another exe. I ran into some example code where the process is started in a try block and closed in a finally block. I also saw example code where the process is not closed.</p> <p>What happens when the process is not closed? </p> <p>Are the resources used by the process reclaimed when the console app that created the process is closed? </p> <p>Is it bad to open lots of processes and not close any of them in a console app that's open for long periods of time?</p> <p>Cheers!</p>
[ { "answer_id": 185325, "author": "mannu", "author_id": 15858, "author_profile": "https://Stackoverflow.com/users/15858", "pm_score": 1, "selected": false, "text": "<p>They will continue to run as if you started them yourself.</p>\n" }, { "answer_id": 185336, "author": "Declan Shanaghy", "author_id": 21297, "author_profile": "https://Stackoverflow.com/users/21297", "pm_score": 1, "selected": false, "text": "<p>A process is a standalone entity.\nProgramatically creating a process is much the same as launching a process from your desktop.</p>\n\n<p>The handle to a process you create is only returned for convenience. For example to access its input and output streams or (as you saw) to kill it.</p>\n\n<p>The resources are not reclaimed when the parent process is killed.</p>\n\n<p>The only time it is bad to open lots of processes is if you open so many that the CPU and RAM cannot handle it!</p>\n" }, { "answer_id": 185342, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 5, "selected": true, "text": "<p>When the other process <em>exits</em>, all of <em>its</em> resources are freed up, but you will still be holding onto a process handle (which is a pointer to a block of information about the process) unless you call <code>Close()</code> on your <code>Process</code> reference. I doubt there would be much of an issue, but <strong>you may as well</strong>.<code>Process</code> implements <code>IDisposable</code> so you can use C#'s <code>using(...)</code> statement, which will automatically call <code>Dispose</code> (and therefore <code>Close()</code>) for you :</p>\n\n<pre><code>using (Process p = Process.Start(...))\n{\n ...\n}\n</code></pre>\n\n<p>As a rule of thumb: if something implements <code>IDisposable</code>, You really <em>should</em> call <code>Dispose</code>/<code>Close</code> or use <code>using(...)</code> on it.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I have a C# app which uses a System.Diagnostics.Process to run another exe. I ran into some example code where the process is started in a try block and closed in a finally block. I also saw example code where the process is not closed. What happens when the process is not closed? Are the resources used by the process reclaimed when the console app that created the process is closed? Is it bad to open lots of processes and not close any of them in a console app that's open for long periods of time? Cheers!
When the other process *exits*, all of *its* resources are freed up, but you will still be holding onto a process handle (which is a pointer to a block of information about the process) unless you call `Close()` on your `Process` reference. I doubt there would be much of an issue, but **you may as well**.`Process` implements `IDisposable` so you can use C#'s `using(...)` statement, which will automatically call `Dispose` (and therefore `Close()`) for you : ``` using (Process p = Process.Start(...)) { ... } ``` As a rule of thumb: if something implements `IDisposable`, You really *should* call `Dispose`/`Close` or use `using(...)` on it.
185,327
<p>I knew stackoverflow would help me for other than know what is the "favorite programming cartoon" :P </p> <p>This was the accepted answer by: <a href="https://stackoverflow.com/questions/185327/oracle-joins-left-outer-right-etc-s#185439">Bill Karwin</a></p> <p>Thanks to all for the help ( I would like to double vote you all ) </p> <p>My query ended up like this ( this is the real one ) </p> <pre><code>SELECT accepted.folio, COALESCE( inprog.activityin, accepted.activityin ) as activityin, inprog.participantin, accepted.completiondate FROM performance accepted LEFT OUTER JOIN performance inprog ON( accepted.folio = inprog.folio AND inprog.ACTIVITYIN IN ( 4, 435 ) -- both are ids for inprogress AND inprog.PARTICIPANTIN != 1 ) -- Ignore the "bot" participant LEFT OUTER JOIN performance closed ON( accepted.folio = closed.folio AND closed.ACTIVITYIN IN ( 10,436, 4, 430 ) ) -- all these are closed or cancelled WHERE accepted.ACTIVITYIN IN ( 3, 429 ) --- both are id for new AND accepted.folio IS NOT NULL AND closed.folio IS NULL; </code></pre> <p>Now I just have to join with the other tables for a human readable report.</p> <p><hr> <strong>ORIGINAL POST</strong></p> <p>Hello. </p> <p>I'm struggling for about 6 hrs. now with a DB query ( my long time nemesis ) </p> <p>I have a data table with some fields like:</p> <pre><code>table performance( identifier varchar, activity number, participant number, closedate date, ) </code></pre> <p>It is used to keep track of the history of ticket</p> <p><strong>Identifier</strong>: is a customer id like ( NAF0000001 ) </p> <p><strong>activity</strong>: is a fk of where the ticket is ( new, in_progress, rejected, closed, etc )</p> <p><strong>participant</strong>: is a fk of who is attending at that point the ticket</p> <p><strong>closedate</strong>: is the date when that activity finished.</p> <p><strong>EDIT:</strong> I should have said "completiondate" rather than closedate. This is the date when the activity was completed, not necessary when the ticket was closed.</p> <p>For instance a typical history may be like this:</p> <pre> identifier|activity|participant|closedate ------------------------------------------- NA00000001| 1| 1|2008/10/08 15:00| ------------------------------------------- NA00000001| 2| 2|2008/10/08 15:20| ------------------------------------------- NA00000001| 3| 2|2008/10/08 15:40| ------------------------------------------- NA00000001| 4| 4|2008/10/08 17:05| ------------------------------------------- </pre> <p>And participant 1=jonh, 2=scott, 3=mike, 4=rob</p> <p>and activties 1=new, 2=inprogress, 3=waitingforapproval, 4=closed</p> <p>etc. And tens of other irrelevant info.</p> <p>Well my problem is the following.</p> <p>I have managed to create a query where I can know when a ticket was opened and closed</p> <p>it is like this:</p> <pre><code> select a.identifier, a.participant, a.closedate as start, b.closedate as finish from performance a, performance b where a.activity = 1 -- new and b.activity = 4 -- closed and a.identifier = b.identifier </code></pre> <p>But I can't know what tickets are <strong>not</strong> closed and who is attending them.</p> <p>So far I have something like this:</p> <pre><code> select a.identifier, a.participant, a.closedate as start from performance a where a.activity = 1 -- new and a.identifier not in ( select identifier from performance where activity = 4 ) --closed </code></pre> <p>That is give me all the ones who have an start ( new = 1 ) but are not closed ( closed = 4 ) </p> <p>But the big problem here is that it prints the participant who opened the ticket, but I need the participant who is attending it. So I add the "inprogress" activity to the query.</p> <pre><code> select a.identifier, a.participant, a.closedate as start from performance a, performance b where a.activity = 1 -- new and a.identifier not in ( select identifier from performance where activity = 4 ) --closed and b.identifier = a.identifier and b.activity = 2 -- inprogress.. </code></pre> <p>But not all the rows that are in "new" are "inprogress" and with that query I drop all of them.</p> <p>What I need is to show all the "inprogress" participant and if the ticket is not "inprogress", it will show as empty.</p> <p>Somthing like</p> <pre> identifier|activity|participant|closedate ------------------------------------------- NA00000002| 1| |2008/10/08 15:00| ------------------------------------------- NA00000003| 1| |2008/10/08 15:20| ------------------------------------------- NA00000004| 1| |2008/10/08 15:40| ------------------------------------------- NA00000005| 2| 4|2008/10/08 15:40| ------------------------------------------- NA00000006| 2| 4|2008/10/08 15:40| </pre> <p>In this case</p> <p>NA002, NA003 and NA004 are in "new", so no participant is shown</p> <p>While</p> <p>NA005 and NA006 are being "inprgress (act = 2 )" and they are being attended by rob ( participant 4 ) </p> <p>So I remember there was this thing called left outer join or something like that but I never ever understand it. What I would like to know is how can I fetch the identifiers that are "inprogress" and "new" and that are not closed.</p> <p>Probably taking a little rest would help me to clear my mind. If anyone knows how to do it I'll appreciate it.</p> <p>By the way I've tried:</p> <pre><code> select a.identifier, a.participant, a.closedate as start from performance a left outer join performance b on b.identifier = a.identifier where a.activity = 1 -- new and a.identifier not in ( select identifier from performance where activity = 4 ) --closed and b.activity = 2 -- inprogress.. </code></pre> <p>But gives me the same result as the previous ( drop the only in "new" records )</p>
[ { "answer_id": 185375, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 2, "selected": false, "text": "<p>Typically the better way to write those is with EXISTS. The first one would be:</p>\n\n<pre><code>select * from performance p1\nwhere not exists \n ( select * from performance p2 \n where p2.identifier = p1.identifier and p2.activity = 4 )\n</code></pre>\n\n<p>This way lets you do a keyed lookup on performance.identifier, rather than potentially having to build a massive list of identifiers in <code>(select identifier from performance where activity=4)</code>.</p>\n" }, { "answer_id": 185398, "author": "Andrew not the Saint", "author_id": 23670, "author_profile": "https://Stackoverflow.com/users/23670", "pm_score": 0, "selected": false, "text": "<p>Firstly, you may have a design issue if you can have a customer with multiple tickets open at the same time. You should ideally have a ticket_id, and then you can perform Andy's query by using ticket_id instead of identifier.</p>\n" }, { "answer_id": 185425, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 2, "selected": false, "text": "<p>I think this should do it. </p>\n\n<p>The first part gets all records that are new, not closed and not in progress. The second part gets all in progress records. We then join them together, we can also sort by identifier by wrapping a 'SELECT * FROM' around this query.</p>\n\n<pre><code>select \n a.identifier,\n a.participant,\n a.closedate as start\nfrom \n performance a\nwhere\n a.activity = 1\n and not exists ( select identifier \n from performance b \n where b.activity = 4 \n and b.identifier = a.identifier) \n and not exists ( select identifier \n from performance c \n where c.activity = 2 \n and c.identifier = a.identifier) \nUNION ALL\nselect \n a.identifier,\n a.participant,\n a.closedate as start\nfrom \n performance a\nwhere\n a.activity = 2\n and not exists ( select identifier \n from performance b \n where b.activity = 4 \n and b.identifier = a.identifier); \n</code></pre>\n" }, { "answer_id": 185428, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 0, "selected": false, "text": "<p>What tickets are not closed:</p>\n\n<pre><code>select identifier as closed_identifier \n from performance where identifier not exists\n (select identifier from performance where activity=4)\n</code></pre>\n\n<p>Tickets that are being attended:</p>\n\n<pre><code>select identifier as inprogress_identifier, participant performance \n from performance where activity=2\n</code></pre>\n\n<p>Unclosed tickets, with the participant of that are being attended:</p>\n\n<pre><code>select * from \n (select identifier as notclosed_identifier \n from performance where identifier not exists\n (select identifier from performance where activity=4)) closed \nleft join \n (select identifier as inprogress_identifier, participant performance \n from performance where activity=2) attended \non notclosed_identifier=inprogress_identifier\n</code></pre>\n" }, { "answer_id": 185439, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>Try something like this (I haven't tested it):</p>\n\n<pre><code>SELECT p_new.identifier, COALESCE(p_inprog.activity, p_new.activity) AS activity,\n p_inprog.participant, COALESCE(p_inprog.closedate, p_new.closedate) AS closedate\nFROM performance p_new\n LEFT OUTER JOIN performance p_inprog \n ON (p_new.identifier = p_inprog.identifier AND p_inprog.activity = 2)\n LEFT OUTER JOIN performance p_closed \n ON (p_new.identifier = p_closed.identifier AND p_closed.activity = 4)\nWHERE p_new.activity = 1\n AND p_closed.identifier IS NULL;\n</code></pre>\n\n<p>I think people believe outer joins are harder than they really are. For example:</p>\n\n<pre><code>A LEFT OUTER JOIN B ON (...condition...)\n</code></pre>\n\n<p>This returns all rows from A, whether or not there are any matching rows in B. If no rows in B match, treat all columns B.* as NULL in the result set for that row of A. The join condition can be an expression that the row in B must satisfy, or else it isn't included in the join. So, more rows in A will be solo.</p>\n" }, { "answer_id": 185567, "author": "Metro", "author_id": 18978, "author_profile": "https://Stackoverflow.com/users/18978", "pm_score": 1, "selected": false, "text": "<p>I would suggest that what you want is the earliest record (presumably, but not necessarily the one with activity=1) and the most recent record (regardless of activity number). If the activity of the most recent record is 4 then the ticket is closed. otherwise, the participant is the current holder of the ticket. There is a potential bug introduced by just matching on activity = 4 if the ticket can be re-opened.</p>\n\n<p>Actually, based upon your example, you may not even need the earliest record. How about the following:</p>\n\n<pre><code>SELECT\n identifier,\n activity,\n participant,\n closedate\n FROM\n performance a\n WHERE\n (a.identifier, a.closedate) in\n (select b.identifier, max(b.closedate)\n from performance b\n group by b.identifier\n )\n;\n</code></pre>\n" }, { "answer_id": 185888, "author": "Salamander2007", "author_id": 10629, "author_profile": "https://Stackoverflow.com/users/10629", "pm_score": 0, "selected": false, "text": "<p>May be you can use this kind of query as a starting point.</p>\n\n<pre><code>select x.identifier, \n max(x.p_1) as new_participant, max(x.c_1) as new_date,\n max(x.p_2) as inprogress_participant, max(x.c_2) as inprogress_date,\n max(x.p_3) as approval_participant, max(x.c_3) as approval_date,\n max(x.p_4) as closing_participant, max(x.c_4) as closing_date\n from (\n select a.identifier, \n decode (activity, 1, participant, null) as p_1, decode (activity, 1, closedate, null) as c_1,\n decode (activity, 2, participant, null) as p_2, decode (activity, 2, closedate, null) as c_2,\n decode (activity, 3, participant, null) as p_3, decode (activity, 3, closedate, null) as c_3,\n decode (activity, 4, participant, null) as p_4, decode (activity, 4, closedate, null) as c_4\n from performance a\n ) x\n group by x.identifier\n</code></pre>\n\n<p>The idea is to serialize your table from row into field, and create a view based on it.\nYou can create report based on this view.</p>\n\n<p>Regards,</p>\n" }, { "answer_id": 186305, "author": "Thorsten", "author_id": 25320, "author_profile": "https://Stackoverflow.com/users/25320", "pm_score": 0, "selected": false, "text": "<p>Just a quick idea that others might build on (untested, but I hope the idea comes across):</p>\n\n<p>First, select all not yet closed activities (as posted by others):</p>\n\n<pre><code>select id\nfrom performance p1 where identifier not exists\n (select * from performance p2 where activity=4 and p1.id=p2.id)\n</code></pre>\n\n<p>Then, you can add the person attending the activity by adding a subquery in the select clause:</p>\n\n<pre><code>select id,\n (select participant \n from performance p3 \n where p3.activity=3 and p1.id=p2.id)\nfrom performance p1 where identifier not exists\n (select * from performance p2 where activity=4 and p1.id=p2.id)\n</code></pre>\n\n<p>If there is no activity 3 record for this id, the subquery returns null which is exactly what we need.</p>\n\n<p>Hope this helps - please expand if necessary.</p>\n" }, { "answer_id": 187316, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 1, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>SELECT * FROM (\n SELECT identifier,\n MAX(activity) activity,\n MAX(participant) KEEP (DENSE_RANK LAST ORDER BY activity)\n FROM performance\n GROUP BY identifier\n)\nWHERE activity in (1,2)\n</code></pre>\n\n<p>The inner query gives the latest activity for each ticket and its corresponding participant. The outer query filters this down to the ones where the activity is either \"new\" or \"in progress\".</p>\n\n<p>I love the DENSE_RANK functions.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
I knew stackoverflow would help me for other than know what is the "favorite programming cartoon" :P This was the accepted answer by: [Bill Karwin](https://stackoverflow.com/questions/185327/oracle-joins-left-outer-right-etc-s#185439) Thanks to all for the help ( I would like to double vote you all ) My query ended up like this ( this is the real one ) ``` SELECT accepted.folio, COALESCE( inprog.activityin, accepted.activityin ) as activityin, inprog.participantin, accepted.completiondate FROM performance accepted LEFT OUTER JOIN performance inprog ON( accepted.folio = inprog.folio AND inprog.ACTIVITYIN IN ( 4, 435 ) -- both are ids for inprogress AND inprog.PARTICIPANTIN != 1 ) -- Ignore the "bot" participant LEFT OUTER JOIN performance closed ON( accepted.folio = closed.folio AND closed.ACTIVITYIN IN ( 10,436, 4, 430 ) ) -- all these are closed or cancelled WHERE accepted.ACTIVITYIN IN ( 3, 429 ) --- both are id for new AND accepted.folio IS NOT NULL AND closed.folio IS NULL; ``` Now I just have to join with the other tables for a human readable report. --- **ORIGINAL POST** Hello. I'm struggling for about 6 hrs. now with a DB query ( my long time nemesis ) I have a data table with some fields like: ``` table performance( identifier varchar, activity number, participant number, closedate date, ) ``` It is used to keep track of the history of ticket **Identifier**: is a customer id like ( NAF0000001 ) **activity**: is a fk of where the ticket is ( new, in\_progress, rejected, closed, etc ) **participant**: is a fk of who is attending at that point the ticket **closedate**: is the date when that activity finished. **EDIT:** I should have said "completiondate" rather than closedate. This is the date when the activity was completed, not necessary when the ticket was closed. For instance a typical history may be like this: ``` identifier|activity|participant|closedate ------------------------------------------- NA00000001| 1| 1|2008/10/08 15:00| ------------------------------------------- NA00000001| 2| 2|2008/10/08 15:20| ------------------------------------------- NA00000001| 3| 2|2008/10/08 15:40| ------------------------------------------- NA00000001| 4| 4|2008/10/08 17:05| ------------------------------------------- ``` And participant 1=jonh, 2=scott, 3=mike, 4=rob and activties 1=new, 2=inprogress, 3=waitingforapproval, 4=closed etc. And tens of other irrelevant info. Well my problem is the following. I have managed to create a query where I can know when a ticket was opened and closed it is like this: ``` select a.identifier, a.participant, a.closedate as start, b.closedate as finish from performance a, performance b where a.activity = 1 -- new and b.activity = 4 -- closed and a.identifier = b.identifier ``` But I can't know what tickets are **not** closed and who is attending them. So far I have something like this: ``` select a.identifier, a.participant, a.closedate as start from performance a where a.activity = 1 -- new and a.identifier not in ( select identifier from performance where activity = 4 ) --closed ``` That is give me all the ones who have an start ( new = 1 ) but are not closed ( closed = 4 ) But the big problem here is that it prints the participant who opened the ticket, but I need the participant who is attending it. So I add the "inprogress" activity to the query. ``` select a.identifier, a.participant, a.closedate as start from performance a, performance b where a.activity = 1 -- new and a.identifier not in ( select identifier from performance where activity = 4 ) --closed and b.identifier = a.identifier and b.activity = 2 -- inprogress.. ``` But not all the rows that are in "new" are "inprogress" and with that query I drop all of them. What I need is to show all the "inprogress" participant and if the ticket is not "inprogress", it will show as empty. Somthing like ``` identifier|activity|participant|closedate ------------------------------------------- NA00000002| 1| |2008/10/08 15:00| ------------------------------------------- NA00000003| 1| |2008/10/08 15:20| ------------------------------------------- NA00000004| 1| |2008/10/08 15:40| ------------------------------------------- NA00000005| 2| 4|2008/10/08 15:40| ------------------------------------------- NA00000006| 2| 4|2008/10/08 15:40| ``` In this case NA002, NA003 and NA004 are in "new", so no participant is shown While NA005 and NA006 are being "inprgress (act = 2 )" and they are being attended by rob ( participant 4 ) So I remember there was this thing called left outer join or something like that but I never ever understand it. What I would like to know is how can I fetch the identifiers that are "inprogress" and "new" and that are not closed. Probably taking a little rest would help me to clear my mind. If anyone knows how to do it I'll appreciate it. By the way I've tried: ``` select a.identifier, a.participant, a.closedate as start from performance a left outer join performance b on b.identifier = a.identifier where a.activity = 1 -- new and a.identifier not in ( select identifier from performance where activity = 4 ) --closed and b.activity = 2 -- inprogress.. ``` But gives me the same result as the previous ( drop the only in "new" records )
Try something like this (I haven't tested it): ``` SELECT p_new.identifier, COALESCE(p_inprog.activity, p_new.activity) AS activity, p_inprog.participant, COALESCE(p_inprog.closedate, p_new.closedate) AS closedate FROM performance p_new LEFT OUTER JOIN performance p_inprog ON (p_new.identifier = p_inprog.identifier AND p_inprog.activity = 2) LEFT OUTER JOIN performance p_closed ON (p_new.identifier = p_closed.identifier AND p_closed.activity = 4) WHERE p_new.activity = 1 AND p_closed.identifier IS NULL; ``` I think people believe outer joins are harder than they really are. For example: ``` A LEFT OUTER JOIN B ON (...condition...) ``` This returns all rows from A, whether or not there are any matching rows in B. If no rows in B match, treat all columns B.\* as NULL in the result set for that row of A. The join condition can be an expression that the row in B must satisfy, or else it isn't included in the join. So, more rows in A will be solo.
185,349
<p>In XAML I can declare a DataTemplate so that the template is used whenever a specific type is displayed. For example, this DataTemplate will use a TextBlock to display the name of a customer:</p> <pre><code>&lt;DataTemplate DataType="{x:Type my:Customer}"&gt; &lt;TextBlock Text="{Binding Name}" /&gt; &lt;/DataTemplate&gt; </code></pre> <p>I'm wondering if it's possible to define a DataTemplate that will be used any time an IList&lt;Customer&gt; is displayed. So if a ContentControl's Content is, say, an ObservableCollection&lt;Customer&gt; it would use that template.</p> <p>Is it possible to declare a generic type like IList in XAML using the {x:Type} Markup Extension?</p>
[ { "answer_id": 185589, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 6, "selected": true, "text": "<p>Not out of the box, no; but there are enterprising developers out there who have done so.</p>\n<p>Mike Hillberg at Microsoft played with it in <a href=\"https://learn.microsoft.com/en-us/archive/blogs/mikehillberg/limited-generics-support-in-xaml\" rel=\"nofollow noreferrer\">this post</a>, for example. Google has others of course.</p>\n" }, { "answer_id": 186694, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 5, "selected": false, "text": "<p>Not directly in XAML, however you could reference a <code>DataTemplateSelector</code> from XAML to choose the correct template.</p>\n\n<pre><code>public class CustomerTemplateSelector : DataTemplateSelector\n{\n public override DataTemplate SelectTemplate(object item,\n DependencyObject container)\n {\n DataTemplate template = null;\n if (item != null)\n {\n FrameworkElement element = container as FrameworkElement;\n if (element != null)\n {\n string templateName = item is ObservableCollection&lt;MyCustomer&gt; ?\n \"MyCustomerTemplate\" : \"YourCustomerTemplate\";\n\n template = element.FindResource(templateName) as DataTemplate;\n } \n }\n return template;\n }\n}\n\npublic class MyCustomer\n{\n public string CustomerName { get; set; }\n}\n\npublic class YourCustomer\n{\n public string CustomerName { get; set; }\n}\n</code></pre>\n\n<p>The resource dictionary:</p>\n\n<pre><code>&lt;ResourceDictionary \n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:WpfApplication1\"\n &gt;\n &lt;DataTemplate x:Key=\"MyCustomerTemplate\"&gt;\n &lt;Grid&gt;\n &lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;RowDefinition Height=\"150\"/&gt;\n &lt;/Grid.RowDefinitions&gt;\n &lt;TextBlock Text=\"My Customer Template\"/&gt;\n &lt;ListBox ItemsSource=\"{Binding}\"\n DisplayMemberPath=\"CustomerName\"\n Grid.Row=\"1\"/&gt;\n &lt;/Grid&gt;\n &lt;/DataTemplate&gt;\n\n &lt;DataTemplate x:Key=\"YourCustomerTemplate\"&gt;\n &lt;Grid&gt;\n &lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;RowDefinition Height=\"150\"/&gt;\n &lt;/Grid.RowDefinitions&gt;\n &lt;TextBlock Text=\"Your Customer Template\"/&gt;\n &lt;ListBox ItemsSource=\"{Binding}\"\n DisplayMemberPath=\"CustomerName\"\n Grid.Row=\"1\"/&gt;\n &lt;/Grid&gt;\n &lt;/DataTemplate&gt;\n&lt;/ResourceDictionary&gt;\n</code></pre>\n\n<p>The window XAML:</p>\n\n<pre><code>&lt;Window \n x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Window1\" \n Height=\"300\" \n Width=\"300\"\n xmlns:local=\"clr-namespace:WpfApplication1\"\n &gt;\n &lt;Grid&gt;\n &lt;Grid.Resources&gt;\n &lt;local:CustomerTemplateSelector x:Key=\"templateSelector\"/&gt;\n &lt;/Grid.Resources&gt;\n &lt;ContentControl \n Content=\"{Binding}\" \n ContentTemplateSelector=\"{StaticResource templateSelector}\" \n /&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>The window code behind:</p>\n\n<pre><code>public partial class Window1\n{\n public Window1()\n {\n InitializeComponent();\n ObservableCollection&lt;MyCustomer&gt; myCustomers\n = new ObservableCollection&lt;MyCustomer&gt;()\n {\n new MyCustomer(){CustomerName=\"Paul\"},\n new MyCustomer(){CustomerName=\"John\"},\n new MyCustomer(){CustomerName=\"Mary\"}\n };\n\n ObservableCollection&lt;YourCustomer&gt; yourCustomers\n = new ObservableCollection&lt;YourCustomer&gt;()\n {\n new YourCustomer(){CustomerName=\"Peter\"},\n new YourCustomer(){CustomerName=\"Chris\"},\n new YourCustomer(){CustomerName=\"Jan\"}\n };\n //DataContext = myCustomers;\n DataContext = yourCustomers;\n }\n}\n</code></pre>\n" }, { "answer_id": 260549, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 3, "selected": false, "text": "<p>aelij (the project coordinator for the <a href=\"http://www.codeplex.com/wpfcontrib\" rel=\"noreferrer\">WPF Contrib</a> project) has another <a href=\"http://arbel.net/blog/archive/2008/10/27/activator-2-xaml-and-generics-day.aspx\" rel=\"noreferrer\">way</a> to do it.</p>\n\n<p>What's even cooler (even though it is sometime off in the future) ... is that XAML 2009 (XAML 2006 is the current version) is going to support this natively. Check out this <a href=\"http://channel9.msdn.com/pdc2008/TL36/\" rel=\"noreferrer\">PDC 2008 session</a> for info on it and more.</p>\n" }, { "answer_id": 4047863, "author": "Claudiu Mihaila", "author_id": 167350, "author_profile": "https://Stackoverflow.com/users/167350", "pm_score": 4, "selected": false, "text": "<p>You also can wrap your generic class in a derived class that specifies the T</p>\n\n<pre><code>public class StringList : List&lt;String&gt;{}\n</code></pre>\n\n<p>and use StringList from XAML.</p>\n" }, { "answer_id": 40545499, "author": "Mike de Klerk", "author_id": 1567665, "author_profile": "https://Stackoverflow.com/users/1567665", "pm_score": 0, "selected": false, "text": "<p>Quite defeats the purpose of a generic, but you could define a class that derives from the generic like so, with the sole purpose of being able to use that type in XAML.</p>\n\n<pre><code>public class MyType : List&lt;int&gt; { }\n</code></pre>\n\n<p>And use it in xaml e.g. like</p>\n\n<pre><code>&lt;DataTemplate DataType={x:Type myNamespace:MyType}&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
In XAML I can declare a DataTemplate so that the template is used whenever a specific type is displayed. For example, this DataTemplate will use a TextBlock to display the name of a customer: ``` <DataTemplate DataType="{x:Type my:Customer}"> <TextBlock Text="{Binding Name}" /> </DataTemplate> ``` I'm wondering if it's possible to define a DataTemplate that will be used any time an IList<Customer> is displayed. So if a ContentControl's Content is, say, an ObservableCollection<Customer> it would use that template. Is it possible to declare a generic type like IList in XAML using the {x:Type} Markup Extension?
Not out of the box, no; but there are enterprising developers out there who have done so. Mike Hillberg at Microsoft played with it in [this post](https://learn.microsoft.com/en-us/archive/blogs/mikehillberg/limited-generics-support-in-xaml), for example. Google has others of course.
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
[ { "answer_id": 185387, "author": "moo", "author_id": 23107, "author_profile": "https://Stackoverflow.com/users/23107", "pm_score": 0, "selected": false, "text": "<p>This probably doesn't fully comply with file-naming standards, but here it goes:</p>\n\n<pre><code>/^Run[\\w]*?\\.py$/\n</code></pre>\n" }, { "answer_id": 185388, "author": "Rob Howard", "author_id": 3528, "author_profile": "https://Stackoverflow.com/users/3528", "pm_score": 3, "selected": false, "text": "<pre><code>/^Run.*\\.py$/\n</code></pre>\n\n<p>Or, in python specifically:</p>\n\n<pre><code>import re\nre.match(r\"^Run.*\\.py$\", stringtocheck)\n</code></pre>\n\n<p>This will match \"Runfoobar.py\", but not \"runfoobar.PY\". To make it case insensitive, instead use:</p>\n\n<pre><code>re.match(r\"^Run.*\\.py$\", stringtocheck, re.I)\n</code></pre>\n" }, { "answer_id": 185393, "author": "imjoevasquez", "author_id": 24630, "author_profile": "https://Stackoverflow.com/users/24630", "pm_score": 0, "selected": false, "text": "<p>mabye:</p>\n\n<pre><code>^Run.*\\.py$\n</code></pre>\n\n<p>just a quick try</p>\n" }, { "answer_id": 185397, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 7, "selected": true, "text": "<p>For a regular expression, you would use:</p>\n\n<pre><code>re.match(r'Run.*\\.py$')\n</code></pre>\n\n<p>A quick explanation:</p>\n\n<ul>\n<li>. means match any character.</li>\n<li>* means match any repetition of the previous character (hence .* means any sequence of chars)</li>\n<li>\\ is an escape to escape the explicit dot</li>\n<li>$ indicates \"end of the string\", so we don't match \"Run_foo.py.txt\"</li>\n</ul>\n\n<p>However, for this task, you're probably better off using simple string methods. ie.</p>\n\n<pre><code>filename.startswith(\"Run\") and filename.endswith(\".py\")\n</code></pre>\n\n<p>Note: if you want case insensitivity (ie. matching \"run.PY\" as well as \"Run.py\", use the re.I option to the regular expression, or convert to a specific case (eg filename.lower()) before using string methods.</p>\n" }, { "answer_id": 185426, "author": "Rob Howard", "author_id": 3528, "author_profile": "https://Stackoverflow.com/users/3528", "pm_score": 4, "selected": false, "text": "<p>Warning:</p>\n\n<ul>\n<li>jobscry's answer (\"^Run.?.py$\") is incorrect (will not match \"Run123.py\", for example).</li>\n<li>orlandu63's answer (\"/^Run[\\w]*?.py$/\") will not match \"RunFoo.Bar.py\".</li>\n</ul>\n\n<p>(I don't have enough reputation to comment, sorry.)</p>\n" }, { "answer_id": 185583, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 2, "selected": false, "text": "<p>If you write a slightly more complex regular expression, you can get an extra feature: extract the bit between \"Run\" and \".py\":</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; regex = '^Run(?P&lt;name&gt;.*)\\.py$'\n&gt;&gt;&gt; m = re.match(regex, 'RunFoo.py')\n&gt;&gt;&gt; m.group('name')\n'Foo'\n</code></pre>\n\n<p>(the extra bit is the parentheses and everything between them, except for '.*' which is as in Rob Howard's answer)</p>\n" }, { "answer_id": 185593, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "<p>I don't really understand why you're after a regular expression to solve this 'problem'. You're just after a way to find all .py files that start with 'Run'. So this is a simple solution that will work, without resorting to compiling an running a regular expression:</p>\n\n<pre><code>import os\nfor filename in os.listdir(dirname):\n root, ext = os.path.splitext(filename)\n if root.startswith('Run') and ext == '.py':\n print filename\n</code></pre>\n" }, { "answer_id": 186927, "author": "Simon Peverett", "author_id": 6063, "author_profile": "https://Stackoverflow.com/users/6063", "pm_score": 3, "selected": false, "text": "<p>You don't need a regular expression, you can use glob, which takes wildcards e.g. Run*.py</p>\n\n<p>For example, to get those files in your current directory...</p>\n\n<pre><code>import os, glob\nfiles = glob.glob( \"\".join([ os.getcwd(), \"\\\\Run*.py\"]) )\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'? The regular expression should match any of the following: ``` RunFoo.py RunBar.py Run42.py ``` It should not match: ``` myRunFoo.py RunBar.py1 Run42.txt ``` The SQL equivalent of what I am looking for is `... LIKE 'Run%.py' ...`.
For a regular expression, you would use: ``` re.match(r'Run.*\.py$') ``` A quick explanation: * . means match any character. * \* means match any repetition of the previous character (hence .\* means any sequence of chars) * \ is an escape to escape the explicit dot * $ indicates "end of the string", so we don't match "Run\_foo.py.txt" However, for this task, you're probably better off using simple string methods. ie. ``` filename.startswith("Run") and filename.endswith(".py") ``` Note: if you want case insensitivity (ie. matching "run.PY" as well as "Run.py", use the re.I option to the regular expression, or convert to a specific case (eg filename.lower()) before using string methods.
185,381
<p>I have some System.Diagnotics.Processes to run. I'd like to call the close method on them automatically. Apparently the "using" keyword does this for me.</p> <p>Is this the way to use the using keyword?</p> <pre><code>foreach(string command in S) // command is something like "c:\a.exe" { try { using(p = Process.Start(command)) { // I literally put nothing in here. } } catch (Exception e) { // notify of process failure } } </code></pre> <p>I'd like to start multiple processes to run concurrently.</p>
[ { "answer_id": 185419, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 0, "selected": false, "text": "<pre><code>try\n{\n foreach(string command in S) // command is something like \"c:\\a.exe\"\n {\n using(p = Process.Start(command))\n {\n // I literally put nothing in here.\n }\n\n } \n}\ncatch (Exception e)\n{\n // notify of process failure\n}\n</code></pre>\n\n<p>The reason it works is because when the exception happens, the variable p falls out of scope and thus it's Dispose method is called that closes the process is how that would go. Additionally, I would think you'd want to spin a thread off for each command rather than wait for an executable to finish before going on to the next one.</p>\n" }, { "answer_id": 185449, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": true, "text": "<pre><code>using(p = Process.Start(command))\n</code></pre>\n\n<p>This will compile, as the <code>Process</code> class implements <code>IDisposable</code>, however you actually want to call the <code>Close</code> method.<br>\nLogic would have it that the <code>Dispose</code> method would call <code>Close</code> for you, and by digging into the CLR using reflector, we can see that it does in fact do this for us. So far so good.</p>\n\n<p>Again using reflector, I looked at what the <code>Close</code> method does - it releases the underlying native win32 process handle, and clears some member variables. This (releasing external resources) is <em>exactly</em> what the IDisposable pattern is supposed to do.</p>\n\n<p><strong>However</strong> I'm not sure if this is what you want to achieve here.</p>\n\n<p>Releasing the underlying handles simply says to windows 'I am no longer interested in tracking this other process'. At no point does it actually cause the other process to quit, or cause your process to wait.</p>\n\n<p>If you want to force them quit, you'll need to use the <code>p.Kill()</code> method on the processes - however be advised it is never a good idea to kill processes as they can't clean up after themselves, and may leave behind corrupt files, and so on.</p>\n\n<p>If you want to wait for them to quit on their own, you could use <code>p.WaitForExit()</code> - however this will only work if you're waiting for one process at a time. If you want to wait for them all concurrently, it gets tricky.</p>\n\n<p>Normally you'd use <code>WaitHandle.WaitAll</code> for this, but as there's no way to get a <code>WaitHandle</code> object out of a <code>System.Diagnostics.Process</code>, you can't do this (seriously, wtf were microsoft thinking?).</p>\n\n<p>You could spin up a thread for each process, and call `WaitForExit in those threads, but this is also the wrong way to do it.</p>\n\n<p>You instead have to use p/invoke to access the native win32 <code>WaitForMultipleObjects</code> function.</p>\n\n<p>Here's a sample (which I've tested, and actually works)</p>\n\n<pre><code>[System.Runtime.InteropServices.DllImport( \"kernel32.dll\" )]\nstatic extern uint WaitForMultipleObjects( uint nCount, IntPtr[] lpHandles, bool bWaitAll, uint dwMilliseconds );\n\nstatic void Main( string[] args )\n{\n var procs = new Process[] {\n Process.Start( @\"C:\\Program Files\\ruby\\bin\\ruby.exe\", \"-e 'sleep 2'\" ),\n Process.Start( @\"C:\\Program Files\\ruby\\bin\\ruby.exe\", \"-e 'sleep 3'\" ),\n Process.Start( @\"C:\\Program Files\\ruby\\bin\\ruby.exe\", \"-e 'sleep 4'\" ) };\n // all started asynchronously in the background\n\n var handles = procs.Select( p =&gt; p.Handle ).ToArray();\n WaitForMultipleObjects( (uint)handles.Length, handles, true, uint.MaxValue ); // uint.maxvalue waits forever\n\n}\n</code></pre>\n" }, { "answer_id": 185636, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 2, "selected": false, "text": "<p>For reference:\nThe <em>using</em> keyword for <em>IDisposable</em> objects:</p>\n\n<pre><code>using(Writer writer = new Writer())\n{\n writer.Write(\"Hello\");\n}\n</code></pre>\n\n<p>is just compiler syntax. What it compiles down to is:</p>\n\n<pre><code>Writer writer = null;\ntry\n{\n writer = new Writer();\n writer.Write(\"Hello\");\n}\nfinally\n{\n if( writer != null)\n {\n ((IDisposable)writer).Dispose();\n }\n}\n</code></pre>\n\n<p><code>using</code> is a bit better since the compiler prevents you from reassigning the writer reference inside the using block.</p>\n\n<p>The framework guidelines Section 9.3.1 p. 256 state:</p>\n\n<blockquote>\n <p><strong>CONSIDER</strong> providing method Close(), in addition to the Dispose(), if close is standard terminology in the area.</p>\n</blockquote>\n\n<hr>\n\n<p>In your code example, the outer try-catch is unnecessary (see above). </p>\n\n<p>Using probably isn't doing what you want to here since Dispose() gets called as soon as <code>p</code> goes out of scope. This doesn't shut down the process (tested). </p>\n\n<p>Processes are independent, so unless you call <code>p.WaitForExit()</code> they spin off and do their own thing completely independent of your program. </p>\n\n<p>Counter-intuitively, for a Process, Close() only releases resources but leaves the program running. CloseMainWindow() can work for some processes, and Kill() will work to kill any process. Both CloseMainWindow() and Kill() can throw exceptions, so be careful if you're using them in a finally block.</p>\n\n<p>To finish, here's some code that waits for processes to finish but doesn't kill off the processes when an exception occurs. I'm not saying it's better than Orion Edwards, just different.</p>\n\n<pre><code>List&lt;System.Diagnostics.Process&gt; processList = new List&lt;System.Diagnostics.Process&gt;();\n\ntry\n{\n foreach (string command in Commands)\n {\n processList.Add(System.Diagnostics.Process.Start(command));\n }\n\n // loop until all spawned processes Exit normally.\n while (processList.Any())\n {\n System.Threading.Thread.Sleep(1000); // wait and see.\n List&lt;System.Diagnostics.Process&gt; finished = (from o in processList\n where o.HasExited\n select o).ToList();\n\n processList = processList.Except(finished).ToList();\n foreach (var p in finished)\n {\n // could inspect exit code and exit time.\n // note many properties are unavailable after process exits\n p.Close();\n }\n }\n}\ncatch (Exception ex)\n{\n // log the exception\n throw;\n}\nfinally\n{\n foreach (var p in processList)\n {\n if (p != null)\n {\n //if (!p.HasExited)\n // processes will still be running\n // but CloseMainWindow() or Kill() can throw exceptions\n p.Dispose();\n }\n\n }\n}\n</code></pre>\n\n<p>I didn't bother Kill()'ing off the processes because the code starts get even uglier. Read the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx\" rel=\"nofollow noreferrer\">msdn</a> documentation for more information.</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I have some System.Diagnotics.Processes to run. I'd like to call the close method on them automatically. Apparently the "using" keyword does this for me. Is this the way to use the using keyword? ``` foreach(string command in S) // command is something like "c:\a.exe" { try { using(p = Process.Start(command)) { // I literally put nothing in here. } } catch (Exception e) { // notify of process failure } } ``` I'd like to start multiple processes to run concurrently.
``` using(p = Process.Start(command)) ``` This will compile, as the `Process` class implements `IDisposable`, however you actually want to call the `Close` method. Logic would have it that the `Dispose` method would call `Close` for you, and by digging into the CLR using reflector, we can see that it does in fact do this for us. So far so good. Again using reflector, I looked at what the `Close` method does - it releases the underlying native win32 process handle, and clears some member variables. This (releasing external resources) is *exactly* what the IDisposable pattern is supposed to do. **However** I'm not sure if this is what you want to achieve here. Releasing the underlying handles simply says to windows 'I am no longer interested in tracking this other process'. At no point does it actually cause the other process to quit, or cause your process to wait. If you want to force them quit, you'll need to use the `p.Kill()` method on the processes - however be advised it is never a good idea to kill processes as they can't clean up after themselves, and may leave behind corrupt files, and so on. If you want to wait for them to quit on their own, you could use `p.WaitForExit()` - however this will only work if you're waiting for one process at a time. If you want to wait for them all concurrently, it gets tricky. Normally you'd use `WaitHandle.WaitAll` for this, but as there's no way to get a `WaitHandle` object out of a `System.Diagnostics.Process`, you can't do this (seriously, wtf were microsoft thinking?). You could spin up a thread for each process, and call `WaitForExit in those threads, but this is also the wrong way to do it. You instead have to use p/invoke to access the native win32 `WaitForMultipleObjects` function. Here's a sample (which I've tested, and actually works) ``` [System.Runtime.InteropServices.DllImport( "kernel32.dll" )] static extern uint WaitForMultipleObjects( uint nCount, IntPtr[] lpHandles, bool bWaitAll, uint dwMilliseconds ); static void Main( string[] args ) { var procs = new Process[] { Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 2'" ), Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 3'" ), Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 4'" ) }; // all started asynchronously in the background var handles = procs.Select( p => p.Handle ).ToArray(); WaitForMultipleObjects( (uint)handles.Length, handles, true, uint.MaxValue ); // uint.maxvalue waits forever } ```
185,384
<p>While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:</p> <pre><code>static private List&lt;int&gt; a = new List&lt;int&gt;() { 0 }; static private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] }; </code></pre> <p>Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this?</p> <p><strong>Edit:</strong> (re: Panos) In a file lexical order seems to be king? what about across files?</p> <p>In looking I tried a cyclical dependency like this:</p> <pre><code>static private List&lt;int&gt; a = new List&lt;int&gt;() { b[0] }; static private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] }; </code></pre> <p>and the program didn't run the same (the test suit failed across the board and I didn't look further).</p>
[ { "answer_id": 185409, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 5, "selected": true, "text": "<p>It seems to depend on the sequence of lines. This code works:</p>\n\n<pre><code>static private List&lt;int&gt; a = new List&lt;int&gt;() { 1 };\nstatic private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] };\n</code></pre>\n\n<p>while this code does not work (it throws a <code>NullReferenceException</code>)</p>\n\n<pre><code>static private List&lt;int&gt; a = new List&lt;int&gt;() { b[0] };\nstatic private List&lt;int&gt; b = new List&lt;int&gt;() { 1 };\n</code></pre>\n\n<p>So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain...</p>\n\n<hr>\n\n<p>EDIT - What's happening \"across files\"? If we declare these two classes:</p>\n\n<pre><code>public class A {\n public static List&lt;int&gt; a = new List&lt;int&gt;() { B.b[0] };\n}\npublic class B {\n public static List&lt;int&gt; b = new List&lt;int&gt;() { A.a[0] };\n}\n</code></pre>\n\n<p>and try to access them with this code:</p>\n\n<pre><code>try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }\ntry { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }\ntry { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }\n</code></pre>\n\n<p>we are getting this output:</p>\n\n<pre><code>The type initializer for 'A' threw an exception.\nObject reference not set to an instance of an object.\nThe type initializer for 'A' threw an exception.\n</code></pre>\n\n<p>So the initialization of <code>B</code> causes an exception in static constructor <code>A</code> and lefts field <code>a</code> with the default value (null). Since <code>a</code> is <code>null</code>, <code>b</code> can not also be initialized properly.</p>\n\n<p>If we do not have cyclical dependencies, everything works fine.</p>\n\n<hr>\n\n<p>EDIT: Just in case you didn't read the comments, <a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon Skeet</a> provides a very interesting reading: <a href=\"http://csharpindepth.com/Articles/General/Beforefieldinit.aspx\" rel=\"nofollow noreferrer\">The differences between static constructors and type initializers</a>.</p>\n" }, { "answer_id": 185418, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "<p>Yes, you were lucky. C# appears to execute the code in the order it appears in the class.</p>\n\n<pre><code>static private List&lt;int&gt; a = new List&lt;int&gt;() { 0 };\nstatic private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] };\n</code></pre>\n\n<p>Will work but ... </p>\n\n<pre><code>static private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] };\nstatic private List&lt;int&gt; a = new List&lt;int&gt;() { 0 };\n</code></pre>\n\n<p>Will fail.</p>\n\n<p>I would recommend putting all your dependencies in one place, the static constructor is the place for this.</p>\n\n<pre><code>static MyClass()\n{\n a = new List&lt;int&gt;() { 0 };\n b = new List&lt;int&gt;() { a[0] };\n}\n</code></pre>\n" }, { "answer_id": 185421, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 2, "selected": false, "text": "<p>Personally I would get rid of the static initializers since it isn't clear and add a static constructor to initialize these variables. </p>\n\n<pre><code>static private List&lt;int&gt; a;\nstatic private List&lt;int&gt; b;\n\nstatic SomeClass()\n{\n a = new List&lt;int&gt;() { 0 };\n b = new List&lt;int&gt;() { a[0] };\n}\n</code></pre>\n\n<p>Then you don't have to guess what is going on and you're being clear in your intentions.</p>\n" }, { "answer_id": 185422, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 5, "selected": false, "text": "<p>See <a href=\"http://msdn.microsoft.com/en-us/library/aa645757(VS.71).aspx\" rel=\"noreferrer\">section 10.4 of the C# spec</a> for the rules here: </p>\n\n<blockquote>\n <p>when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order. It is possible for static fields with variable initializers to be observed in their default value state. However, this is strongly discouraged as a matter of style.</p>\n</blockquote>\n\n<p>So in other words, in your example 'b' is initialized to its default state (null) and so the reference to it in the initializer of 'a' is legal but would result in a NullReferenceException.</p>\n\n<p>These rules are different to Java's (see <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/classes.html#287406\" rel=\"noreferrer\">section 8.3.2.3 of the JLS</a> for Java's rules about forward references, which are more restrictive).</p>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this: ``` static private List<int> a = new List<int>() { 0 }; static private List<int> b = new List<int>() { a[0] }; ``` Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this? **Edit:** (re: Panos) In a file lexical order seems to be king? what about across files? In looking I tried a cyclical dependency like this: ``` static private List<int> a = new List<int>() { b[0] }; static private List<int> b = new List<int>() { a[0] }; ``` and the program didn't run the same (the test suit failed across the board and I didn't look further).
It seems to depend on the sequence of lines. This code works: ``` static private List<int> a = new List<int>() { 1 }; static private List<int> b = new List<int>() { a[0] }; ``` while this code does not work (it throws a `NullReferenceException`) ``` static private List<int> a = new List<int>() { b[0] }; static private List<int> b = new List<int>() { 1 }; ``` So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain... --- EDIT - What's happening "across files"? If we declare these two classes: ``` public class A { public static List<int> a = new List<int>() { B.b[0] }; } public class B { public static List<int> b = new List<int>() { A.a[0] }; } ``` and try to access them with this code: ``` try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); } try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); } try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); } ``` we are getting this output: ``` The type initializer for 'A' threw an exception. Object reference not set to an instance of an object. The type initializer for 'A' threw an exception. ``` So the initialization of `B` causes an exception in static constructor `A` and lefts field `a` with the default value (null). Since `a` is `null`, `b` can not also be initialized properly. If we do not have cyclical dependencies, everything works fine. --- EDIT: Just in case you didn't read the comments, [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) provides a very interesting reading: [The differences between static constructors and type initializers](http://csharpindepth.com/Articles/General/Beforefieldinit.aspx).
185,423
<p>I'm working on an application that is implemented as an HTA. I have a series of links that I would like to have open in the system's default web browser. Using <code>&lt;a href="url" target="_blank"&gt;</code> opens the link in IE regardless of the default browser.</p> <p>Is there a way to use the default browser? Using JavaScript is an option.</p>
[ { "answer_id": 185528, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": -1, "selected": false, "text": "<p>Nope, sadly I believe this is a browser specific implementation that will open new links with target=\"_blank\" within the same browser.</p>\n\n<p>If you wanted to open it in the default browser, then you would need to interact with the OS, which JavaScript cannot do.</p>\n" }, { "answer_id": 185581, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": true, "text": "<p>Create a shell and attempt to run a URL.</p>\n\n<p>This works for me (save as whatever.hta and execute it) on my system. Clicking on the button opens Google in Firefox:</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;title&gt;HTA Test&lt;/title&gt;\n &lt;hta:application applicationname=\"HTA Test\" scroll=\"yes\" singleinstance=\"yes\"&gt;\n &lt;script type=\"text/javascript\"&gt;\n function openURL()\n {\n var shell = new ActiveXObject(\"WScript.Shell\");\n shell.run(\"http://www.google.com\");\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;input type=\"button\" onclick=\"openURL()\" value=\"Open Google\"&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
2008/10/08
[ "https://Stackoverflow.com/questions/185423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441/" ]
I'm working on an application that is implemented as an HTA. I have a series of links that I would like to have open in the system's default web browser. Using `<a href="url" target="_blank">` opens the link in IE regardless of the default browser. Is there a way to use the default browser? Using JavaScript is an option.
Create a shell and attempt to run a URL. This works for me (save as whatever.hta and execute it) on my system. Clicking on the button opens Google in Firefox: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>HTA Test</title> <hta:application applicationname="HTA Test" scroll="yes" singleinstance="yes"> <script type="text/javascript"> function openURL() { var shell = new ActiveXObject("WScript.Shell"); shell.run("http://www.google.com"); } </script> </head> <body> <input type="button" onclick="openURL()" value="Open Google"> </body> </html> ```
185,429
<p>I know how to use JSON to create objects, but there doesn't seem to be away to use JSON to create an object that is of a specific object type.</p> <p>Here's an example of an Object and creating an instance of it:</p> <pre><code>Person = function() { }; Person.prototype = { FirstName: null, GetFirstName: function() { return this.FirstName; } }; //Create an instance of the Person Object var me = new Person(); me.FirstName = "Chris"; alert(me.GetFirstName()); //alert the FirstName property </code></pre> <p>Now, I would like to use JSON to create a new Person object so that the GetFirstName function works on it.</p> <p>Here's something like that I'm looking to do (but this code doesn't work):</p> <pre><code>var you = new Person() { FirstName: "Mike" }; // OR var you = new Person{ FirstName: "Mike" }; </code></pre> <p>Is there anyway to use JSON to create an object that is of a specific type?</p> <p>UPDATE: My sample with the Person object is just to simplify the question. In fact, I am unable to modify the constructors of the actual objects that I need to create instances of. The objects are part of a third-party library.</p> <p>UPDATE: Using some of the suggestions below, I was able to figure out a way to create an object that inherits from the original, and accept JSON in it's constructor. This is neat!</p> <pre><code>personWrapper = function(obj){ for(var o in obj){ this[o] = obj[o]; } }; personWrapper.prototype = new Person(); var you = new personWrapper({FirstName: "Chris"}); alert(you.GetFirstName()); alert(you instanceof Person); // returns True - we are successfully inheriting from Person! </code></pre>
[ { "answer_id": 185438, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "<p>I don't imagine so. I'd create a function on the Person class to initialise from a JSON object if I were you.</p>\n\n<pre><code>function Person() {\n this.loadFromJSON = function(json) {\n this.FirstName = json.FirstName;\n };\n}\n</code></pre>\n\n<p>If you didn't know what class the JSON object was representing beforehand, perhaps add an extra variable into your JSON.</p>\n\n<pre><code>{ _className : \"Person\", FirstName : \"Mike\" }\n</code></pre>\n\n<p>And then have a 'builder' function which interprets it.</p>\n\n<pre><code>function buildFromJSON(json) {\n var myObj = new json[\"_className\"]();\n myObj.loadFromJSON(json);\n return myObj;\n}\n</code></pre>\n\n<hr>\n\n<p>Update: since you say the class is part of a third-party library which you can't change, you could either extend the class with prototyping, or write a function which just populates the class externally.</p>\n\n<p>eg:</p>\n\n<pre><code>Person.prototype.loadFromJSON = function(json) {\n // as above...\n};\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function populateObject(obj, json) {\n for (var i in json) {\n // you might want to put in a check here to test\n // that obj actually has an attribute named i\n obj[i] = json[i];\n }\n}\n</code></pre>\n" }, { "answer_id": 185443, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 2, "selected": false, "text": "<p>You could allow new Person() to accept an object to populate attributes with as a parameter.</p>\n\n<pre><code>var you = new Person({ firstName: 'Mike' });\n</code></pre>\n" }, { "answer_id": 185892, "author": "harley.333", "author_id": 26259, "author_profile": "https://Stackoverflow.com/users/26259", "pm_score": 2, "selected": false, "text": "<p>You can derive an object from theirs. Your constructor can accept the object you want, but call their constructor in an unaffected fashion:</p>\n\n<pre><code>function yourWrapper(obj) {\n theirObject.call(this);\n for (var s in obj) {\n this[s] = obj[s];\n }\n}\nyourWrapper.prototype = new theirObject();\n</code></pre>\n\n<p>Or something like that :)</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
I know how to use JSON to create objects, but there doesn't seem to be away to use JSON to create an object that is of a specific object type. Here's an example of an Object and creating an instance of it: ``` Person = function() { }; Person.prototype = { FirstName: null, GetFirstName: function() { return this.FirstName; } }; //Create an instance of the Person Object var me = new Person(); me.FirstName = "Chris"; alert(me.GetFirstName()); //alert the FirstName property ``` Now, I would like to use JSON to create a new Person object so that the GetFirstName function works on it. Here's something like that I'm looking to do (but this code doesn't work): ``` var you = new Person() { FirstName: "Mike" }; // OR var you = new Person{ FirstName: "Mike" }; ``` Is there anyway to use JSON to create an object that is of a specific type? UPDATE: My sample with the Person object is just to simplify the question. In fact, I am unable to modify the constructors of the actual objects that I need to create instances of. The objects are part of a third-party library. UPDATE: Using some of the suggestions below, I was able to figure out a way to create an object that inherits from the original, and accept JSON in it's constructor. This is neat! ``` personWrapper = function(obj){ for(var o in obj){ this[o] = obj[o]; } }; personWrapper.prototype = new Person(); var you = new personWrapper({FirstName: "Chris"}); alert(you.GetFirstName()); alert(you instanceof Person); // returns True - we are successfully inheriting from Person! ```
I don't imagine so. I'd create a function on the Person class to initialise from a JSON object if I were you. ``` function Person() { this.loadFromJSON = function(json) { this.FirstName = json.FirstName; }; } ``` If you didn't know what class the JSON object was representing beforehand, perhaps add an extra variable into your JSON. ``` { _className : "Person", FirstName : "Mike" } ``` And then have a 'builder' function which interprets it. ``` function buildFromJSON(json) { var myObj = new json["_className"](); myObj.loadFromJSON(json); return myObj; } ``` --- Update: since you say the class is part of a third-party library which you can't change, you could either extend the class with prototyping, or write a function which just populates the class externally. eg: ``` Person.prototype.loadFromJSON = function(json) { // as above... }; ``` or ``` function populateObject(obj, json) { for (var i in json) { // you might want to put in a check here to test // that obj actually has an attribute named i obj[i] = json[i]; } } ```
185,448
<p>Imagine in the Global.asax.cs file I had an instance class as a private field. Let's say like this:</p> <pre><code>private MyClass _myClass = new MyClass(); </code></pre> <p>And I had a static method on Global called GetMyClass() that gets the current HttpApplication and returns that instance.</p> <pre><code>public static MyClass GetMyClass() { return ((Global)HttpContext.Current.ApplicationInstance)._myClass; } </code></pre> <p>So I could get the instance on the current requests httpapplication by calling Global.GetMyClass().</p> <p>Keep in mind that there is more than one (Global) HttpApplication. There is an HttpApplication for each request and they are pooled/shared, so in the truest sense it is not a real <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">singleton</a>. But it does follow the pattern to a degree.</p> <p>So as the question asked, would you consider this at the very least the singleton pattern?</p> <p>Would you say it should not be used? Would you discourage its use? Would you say it's a <strong><em>possibly</em></strong> bad practice like a true singleton.</p> <p>Could you see any problems that may arise from this type of usage scenario?</p> <p>Or would you say it's not a true singleton, so it's OK, and not bad practice. Would you recommend this as a semi-quasi singleton where an instance per request is required? If not what other pattern/suggestion would you use/give?</p> <p>Have you ever used anything such as this?</p> <p>I have used this on past projects, but I am unsure if it's a practice I should stay away from. I have never had any issues in the past though.</p> <p>Please give me your thoughts and opinions on this.</p> <p>I am not asking what a singleton is. And I consider a singleton bad practice when used improperly which is in many many many cases. That is me. However, that is not what I am trying to discuss. I am trying to discuss THIS scenario I gave.</p>
[ { "answer_id": 185456, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 2, "selected": false, "text": "<p>I'm not a .NET person so I'll refrain from commenting on this, except for this part:</p>\n\n<blockquote>\n <p>Would you say its bad practice like a true singleton. </p>\n</blockquote>\n\n<p>True singletons aren't 'bad practice'. They're HORRIBLY OVERUSED but that's not the same thing. I read something recently (can't remember where, alas) where someone pointed out the -- 'want or need' vs. 'can'.</p>\n\n<p>\"We only want one of these\", or \"we'll only need one\": not a singleton.</p>\n\n<p>\"We CAN only have one of these\": singleton</p>\n\n<p>That is, if the very idea of having two of that object will break something in horrible and subtle ways, yes, use a singleton. This is true a lot more rarely than people think, hence the proliferation of singletons.</p>\n" }, { "answer_id": 185457, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>A Singleton is an object, of which, there CAN BE only one. </p>\n\n<p>Objects of which there just happens to be one right now are not singleton.</p>\n" }, { "answer_id": 185460, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 3, "selected": true, "text": "<p>Whether or not this fits the cookie-cutter pattern of a Singleton, it still suffers from the same problems as Singleton:</p>\n\n<ul>\n<li>It is a static, concrete reference and cannot be substituted for separate behavior or stubbed/mocked during a test</li>\n<li>You cannot subclass this and preserve this behavior, so it's quite easy to circumvent the singleton nature of this example</li>\n</ul>\n" }, { "answer_id": 185465, "author": "tsimon", "author_id": 1685, "author_profile": "https://Stackoverflow.com/users/1685", "pm_score": 0, "selected": false, "text": "<p>I would say that it is definitely NOT a singleton. Design patterns are most useful as definitions of common coding practices. When you talk about singletons, you are talking about an object where there is only one instance.</p>\n\n<p>As you yourself have noted, there are multiple HttpApplications, so your code does not follow the design of a Singleton and does not have the same side-effects.</p>\n\n<p>For example, one might use a singleton to update currency exchange rates. If this person unknowingly used your example, they would fire up seven instances to do the job that 'only one object' was meant to do.</p>\n" }, { "answer_id": 185547, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>Forget singleton for a moment.</p>\n\n<p>You have static methods that return application state. You better watch out.</p>\n\n<p>If two threads access this shared state... boom. If you live on the webserver, your code will eventually be run in a multi-threaded context.</p>\n" }, { "answer_id": 185670, "author": "Kevin Dostalek", "author_id": 22732, "author_profile": "https://Stackoverflow.com/users/22732", "pm_score": 2, "selected": false, "text": "<p>Since you're talking about a web application, you need to be very careful with assuming anything with static classes or this type of pseudo-singleton because as David B said, they are only shared across that thread. Where you will get in trouble is if IIS is configured to use more than one worker process (configured with the ill-named \"Web-Garden\" mode, but also the # worker processes can be set in machine.config). Assuming the box has more than one processor, whoever is trying to tweak it's performance is bound to turn this on.</p>\n\n<p>A better pattern for this sort of thing is to use the HttpCache object. It is already thread-safe by nature, but what still catches most people is you object also needs to be thread-safe (since you're only going to probably create the instance and then read/write to a lot of its properties over time). Here's some skeleton code to give you an idea of what I'm talking about:</p>\n\n<pre><code>public SomeClassType SomeProperty\n{\n get\n {\n if (HttpContext.Current.Cache[\"SomeKey\"] == null)\n {\n HttpContext.Current.Cache.Add(\"SomeKey\", new SomeClass(), null,\n System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1),\n CacheItemPriority.NotRemovable, null);\n }\n return (SomeClassType) HttpContext.Current.Cache[\"SomeKey\"];\n }\n}\n</code></pre>\n\n<p>Now if you think you might need a web farm (multi-server) scale path, then the above won't work as the application cache isn't shared across machines.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14642/" ]
Imagine in the Global.asax.cs file I had an instance class as a private field. Let's say like this: ``` private MyClass _myClass = new MyClass(); ``` And I had a static method on Global called GetMyClass() that gets the current HttpApplication and returns that instance. ``` public static MyClass GetMyClass() { return ((Global)HttpContext.Current.ApplicationInstance)._myClass; } ``` So I could get the instance on the current requests httpapplication by calling Global.GetMyClass(). Keep in mind that there is more than one (Global) HttpApplication. There is an HttpApplication for each request and they are pooled/shared, so in the truest sense it is not a real [singleton](http://en.wikipedia.org/wiki/Singleton_pattern). But it does follow the pattern to a degree. So as the question asked, would you consider this at the very least the singleton pattern? Would you say it should not be used? Would you discourage its use? Would you say it's a ***possibly*** bad practice like a true singleton. Could you see any problems that may arise from this type of usage scenario? Or would you say it's not a true singleton, so it's OK, and not bad practice. Would you recommend this as a semi-quasi singleton where an instance per request is required? If not what other pattern/suggestion would you use/give? Have you ever used anything such as this? I have used this on past projects, but I am unsure if it's a practice I should stay away from. I have never had any issues in the past though. Please give me your thoughts and opinions on this. I am not asking what a singleton is. And I consider a singleton bad practice when used improperly which is in many many many cases. That is me. However, that is not what I am trying to discuss. I am trying to discuss THIS scenario I gave.
Whether or not this fits the cookie-cutter pattern of a Singleton, it still suffers from the same problems as Singleton: * It is a static, concrete reference and cannot be substituted for separate behavior or stubbed/mocked during a test * You cannot subclass this and preserve this behavior, so it's quite easy to circumvent the singleton nature of this example
185,451
<p>What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?</p>
[ { "answer_id": 169969, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 8, "selected": false, "text": "<p>Use <a href=\"http://linux.die.net/man/1/flock\" rel=\"noreferrer\"><code>flock(1)</code></a> to make an exclusive scoped lock a on file descriptor. This way you can even synchronize different parts of the script.</p>\n\n<pre><code>#!/bin/bash\n\n(\n # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds\n flock -x -w 10 200 || exit 1\n\n # Do stuff\n\n) 200&gt;/var/lock/.myscript.exclusivelock\n</code></pre>\n\n<p>This ensures that code between <code>(</code> and <code>)</code> is run only by one process at a time and that the process doesn’t wait too long for a lock.</p>\n\n<p>Caveat: this particular command is a part of <a href=\"http://en.wikipedia.org/wiki/Util-linux\" rel=\"noreferrer\"><code>util-linux</code></a>. If you run an operating system other than Linux, it may or may not be available.</p>\n" }, { "answer_id": 170014, "author": "I GIVE CRAP ANSWERS", "author_id": 25083, "author_profile": "https://Stackoverflow.com/users/25083", "pm_score": 0, "selected": false, "text": "<p>The flock path is the way to go. Think about what happens when the script suddenly dies. In the flock-case you just loose the flock, but that is not a problem. Also, note that an evil trick is to take a flock on the script itself .. but that of course lets you run full-steam-ahead into permission problems.</p>\n" }, { "answer_id": 185459, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 3, "selected": false, "text": "<p>Create a lock file in a known location and check for existence on script start? Putting the PID in the file might be helpful if someone's attempting to track down an errant instance that's preventing execution of the script.</p>\n" }, { "answer_id": 185466, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 0, "selected": false, "text": "<p>Quick and dirty?</p>\n\n<pre><code>#!/bin/sh\n\nif [ -f sometempfile ]\n echo \"Already running... will now terminate.\"\n exit\nelse\n touch sometempfile\nfi\n\n..do what you want here..\n\nrm sometempfile\n</code></pre>\n" }, { "answer_id": 185467, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 1, "selected": false, "text": "<p>PID and lockfiles are definitely the most reliable. When you attempt to run the program, it can check for the lockfile which and if it exists, it can use <code>ps</code> to see if the process is still running. If it's not, the script can start, updating the PID in the lockfile to its own.</p>\n" }, { "answer_id": 185473, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 8, "selected": true, "text": "<p>Here's an implementation that uses a <em>lockfile</em> and echoes a PID into it. This serves as a protection if the process is killed before removing the <em>pidfile</em>:</p>\n\n<pre><code>LOCKFILE=/tmp/lock.txt\nif [ -e ${LOCKFILE} ] &amp;&amp; kill -0 `cat ${LOCKFILE}`; then\n echo \"already running\"\n exit\nfi\n\n# make sure the lockfile is removed when we exit and then claim it\ntrap \"rm -f ${LOCKFILE}; exit\" INT TERM EXIT\necho $$ &gt; ${LOCKFILE}\n\n# do stuff\nsleep 1000\n\nrm -f ${LOCKFILE}\n</code></pre>\n\n<p>The trick here is the <code>kill -0</code> which doesn't deliver any signal but just checks if a process with the given PID exists. Also the call to <code>trap</code> will ensure that the <em>lockfile</em> is removed even when your process is killed (except <code>kill -9</code>).</p>\n" }, { "answer_id": 185478, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 5, "selected": false, "text": "<p>There's a wrapper around the flock(2) system call called, unimaginatively, flock(1). This makes it relatively easy to reliably obtain exclusive locks without worrying about cleanup etc. There are examples on <a href=\"http://linux.die.net/man/1/flock\" rel=\"noreferrer\">the man page</a> as to how to use it in a shell script.</p>\n" }, { "answer_id": 187304, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "<p>Some unixes have <strong><code>lockfile</code></strong> which is very similar to the already mentioned <strong><code>flock</code></strong>.</p>\n\n<p>From the manpage:</p>\n\n<blockquote>\n <p>lockfile can be used to create one\n or more semaphore files. If lock-\n file can't create all the specified\n files (in the specified order), it\n waits sleeptime (defaults to 8)\n seconds and retries the last file that\n didn't succeed. You can specify the\n number of retries to do until\n failure is returned. If the number\n of retries is -1 (default, i.e.,\n -r-1) lockfile will retry forever.</p>\n</blockquote>\n" }, { "answer_id": 327991, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>To make locking reliable you need an atomic operation. Many of the above proposals\nare not atomic. The proposed lockfile(1) utility looks promising as the man-page\nmentioned, that its \"NFS-resistant\". If your OS does not support lockfile(1) and\nyour solution has to work on NFS, you have not many options....</p>\n\n<p>NFSv2 has two atomic operations:</p>\n\n<ul>\n<li>symlink</li>\n<li>rename</li>\n</ul>\n\n<p>With NFSv3 the create call is also atomic.</p>\n\n<p>Directory operations are NOT atomic under NFSv2 and NFSv3 (please refer to the book 'NFS Illustrated' by Brent Callaghan, ISBN 0-201-32570-5; Brent is a NFS-veteran at Sun).</p>\n\n<p>Knowing this, you can implement spin-locks for files and directories (in shell, not PHP):</p>\n\n<p>lock current dir:</p>\n\n<pre><code>while ! ln -s . lock; do :; done\n</code></pre>\n\n<p>lock a file:</p>\n\n<pre><code>while ! ln -s ${f} ${f}.lock; do :; done\n</code></pre>\n\n<p>unlock current dir (assumption, the running process really acquired the lock):</p>\n\n<pre><code>mv lock deleteme &amp;&amp; rm deleteme\n</code></pre>\n\n<p>unlock a file (assumption, the running process really acquired the lock):</p>\n\n<pre><code>mv ${f}.lock ${f}.deleteme &amp;&amp; rm ${f}.deleteme\n</code></pre>\n\n<p>Remove is also not atomic, therefore first the rename (which is atomic) and then the remove.</p>\n\n<p>For the symlink and rename calls, both filenames have to reside on the same filesystem. My proposal: use only simple filenames (no paths) and put file and lock into the same directory.</p>\n" }, { "answer_id": 731634, "author": "lhunath", "author_id": 58803, "author_profile": "https://Stackoverflow.com/users/58803", "pm_score": 7, "selected": false, "text": "<p>Naive approaches that test the existence of &quot;lock files&quot; are flawed.</p>\n<p>Why? Because they don't check whether the file exists and create it in a single atomic action. Because of this; there is a race condition that <strong>WILL</strong> make your attempts at mutual exclusion break.</p>\n<p>Instead, you can use <code>mkdir</code>. <code>mkdir</code> creates a directory if it doesn't exist yet, and if it does, it sets an exit code. More importantly, it does all this in a single atomic action making it perfect for this scenario.</p>\n<pre><code>if ! mkdir /tmp/myscript.lock 2&gt;/dev/null; then\n echo &quot;Myscript is already running.&quot; &gt;&amp;2\n exit 1\nfi\n</code></pre>\n<p>For all details, see the excellent BashFAQ: <a href=\"http://mywiki.wooledge.org/BashFAQ/045\" rel=\"noreferrer\">http://mywiki.wooledge.org/BashFAQ/045</a></p>\n<p>If you want to take care of stale locks, <a href=\"http://linux.die.net/man/1/fuser\" rel=\"noreferrer\">fuser(1)</a> comes in handy. The only downside here is that the operation takes about a second, so it isn't instant.</p>\n<p>Here's a function I wrote once that solves the problem using fuser:</p>\n<pre><code># mutex file\n#\n# Open a mutual exclusion lock on the file, unless another process already owns one.\n#\n# If the file is already locked by another process, the operation fails.\n# This function defines a lock on a file as having a file descriptor open to the file.\n# This function uses FD 9 to open a lock on the file. To release the lock, close FD 9:\n# exec 9&gt;&amp;-\n#\nmutex() {\n local file=$1 pid pids \n\n exec 9&gt;&gt;&quot;$file&quot;\n { pids=$(fuser -f &quot;$file&quot;); } 2&gt;&amp;- 9&gt;&amp;- \n for pid in $pids; do\n [[ $pid = $$ ]] &amp;&amp; continue\n\n exec 9&gt;&amp;- \n return 1 # Locked by a pid.\n done \n}\n</code></pre>\n<p>You can use it in a script like so:</p>\n<pre><code>mutex /var/run/myscript.lock || { echo &quot;Already running.&quot; &gt;&amp;2; exit 1; }\n</code></pre>\n<p>If you don't care about portability (these solutions should work on pretty much any UNIX box), Linux' <a href=\"http://linux.die.net/man/1/fuser\" rel=\"noreferrer\">fuser(1)</a> offers some additional options and there is also <a href=\"http://linux.die.net/man/1/flock\" rel=\"noreferrer\">flock(1)</a>.</p>\n" }, { "answer_id": 901221, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 2, "selected": false, "text": "<p>When targeting a Debian machine I find the <code>lockfile-progs</code> package to be a good solution. <code>procmail</code> also comes with a <code>lockfile</code> tool. However sometimes I am stuck with neither of these.</p>\n\n<p>Here's my solution which uses <code>mkdir</code> for atomic-ness and a PID file to detect stale locks. This code is currently in production on a Cygwin setup and works well.</p>\n\n<p>To use it simply call <code>exclusive_lock_require</code> when you need get exclusive access to something. An optional lock name parameter lets you share locks between different scripts. There's also two lower level functions (<code>exclusive_lock_try</code> and <code>exclusive_lock_retry</code>) should you need something more complex.</p>\n\n<pre><code>function exclusive_lock_try() # [lockname]\n{\n\n local LOCK_NAME=\"${1:-`basename $0`}\"\n\n LOCK_DIR=\"/tmp/.${LOCK_NAME}.lock\"\n local LOCK_PID_FILE=\"${LOCK_DIR}/${LOCK_NAME}.pid\"\n\n if [ -e \"$LOCK_DIR\" ]\n then\n local LOCK_PID=\"`cat \"$LOCK_PID_FILE\" 2&gt; /dev/null`\"\n if [ ! -z \"$LOCK_PID\" ] &amp;&amp; kill -0 \"$LOCK_PID\" 2&gt; /dev/null\n then\n # locked by non-dead process\n echo \"\\\"$LOCK_NAME\\\" lock currently held by PID $LOCK_PID\"\n return 1\n else\n # orphaned lock, take it over\n ( echo $$ &gt; \"$LOCK_PID_FILE\" ) 2&gt; /dev/null &amp;&amp; local LOCK_PID=\"$$\"\n fi\n fi\n if [ \"`trap -p EXIT`\" != \"\" ]\n then\n # already have an EXIT trap\n echo \"Cannot get lock, already have an EXIT trap\"\n return 1\n fi\n if [ \"$LOCK_PID\" != \"$$\" ] &amp;&amp;\n ! ( umask 077 &amp;&amp; mkdir \"$LOCK_DIR\" &amp;&amp; umask 177 &amp;&amp; echo $$ &gt; \"$LOCK_PID_FILE\" ) 2&gt; /dev/null\n then\n local LOCK_PID=\"`cat \"$LOCK_PID_FILE\" 2&gt; /dev/null`\"\n # unable to acquire lock, new process got in first\n echo \"\\\"$LOCK_NAME\\\" lock currently held by PID $LOCK_PID\"\n return 1\n fi\n trap \"/bin/rm -rf \\\"$LOCK_DIR\\\"; exit;\" EXIT\n\n return 0 # got lock\n\n}\n\nfunction exclusive_lock_retry() # [lockname] [retries] [delay]\n{\n\n local LOCK_NAME=\"$1\"\n local MAX_TRIES=\"${2:-5}\"\n local DELAY=\"${3:-2}\"\n\n local TRIES=0\n local LOCK_RETVAL\n\n while [ \"$TRIES\" -lt \"$MAX_TRIES\" ]\n do\n\n if [ \"$TRIES\" -gt 0 ]\n then\n sleep \"$DELAY\"\n fi\n local TRIES=$(( $TRIES + 1 ))\n\n if [ \"$TRIES\" -lt \"$MAX_TRIES\" ]\n then\n exclusive_lock_try \"$LOCK_NAME\" &gt; /dev/null\n else\n exclusive_lock_try \"$LOCK_NAME\"\n fi\n LOCK_RETVAL=\"${PIPESTATUS[0]}\"\n\n if [ \"$LOCK_RETVAL\" -eq 0 ]\n then\n return 0\n fi\n\n done\n\n return \"$LOCK_RETVAL\"\n\n}\n\nfunction exclusive_lock_require() # [lockname] [retries] [delay]\n{\n if ! exclusive_lock_retry \"$@\"\n then\n exit 1\n fi\n}\n</code></pre>\n" }, { "answer_id": 1560651, "author": "Gunstick", "author_id": 15653, "author_profile": "https://Stackoverflow.com/users/15653", "pm_score": 5, "selected": false, "text": "<p>You need an atomic operation, like flock, else this will eventually fail.</p>\n\n<p>But what to do if flock is not available. Well there is mkdir. That's an atomic operation too. Only one process will result in a successful mkdir, all others will fail.</p>\n\n<p>So the code is:</p>\n\n<pre><code>if mkdir /var/lock/.myscript.exclusivelock\nthen\n # do stuff\n :\n rmdir /var/lock/.myscript.exclusivelock\nfi\n</code></pre>\n\n<p>You need to take care of stale locks else aftr a crash your script will never run again.</p>\n" }, { "answer_id": 4689326, "author": "thecowster", "author_id": 575389, "author_profile": "https://Stackoverflow.com/users/575389", "pm_score": 1, "selected": false, "text": "<p>I find that bmdhack's solution is the most practical, at least for my use case. Using flock and lockfile rely on removing the lockfile using rm when the script terminates, which can't always be guaranteed (e.g., kill -9).</p>\n\n<p>I would change one minor thing about bmdhack's solution: It makes a point of removing the lock file, without stating that this is unnecessary for the safe working of this semaphore. His use of kill -0 ensures that an old lockfile for a dead process will simply be ignored/over-written.</p>\n\n<p>My simplified solution is therefore to simply add the following to the top of your singleton:</p>\n\n<pre><code>## Test the lock\nLOCKFILE=/tmp/singleton.lock \nif [ -e ${LOCKFILE} ] &amp;&amp; kill -0 `cat ${LOCKFILE}`; then\n echo \"Script already running. bye!\"\n exit \nfi\n\n## Set the lock \necho $$ &gt; ${LOCKFILE}\n</code></pre>\n\n<p>Of course, this script still has the flaw that processes that are likely to start at the same time have a race hazard, as the lock test and set operations are not a single atomic action. But the proposed solution for this by lhunath to use mkdir has the flaw that a killed script may leave behind the directory, thus preventing other instances from running.</p>\n" }, { "answer_id": 5112787, "author": "Mikel", "author_id": 102182, "author_profile": "https://Stackoverflow.com/users/102182", "pm_score": 5, "selected": false, "text": "<p>Another option is to use shell's <code>noclobber</code> option by running <code>set -C</code>. Then <code>&gt;</code> will fail if the file already exists.</p>\n\n<p>In brief:</p>\n\n<pre><code>set -C\nlockfile=\"/tmp/locktest.lock\"\nif echo \"$$\" &gt; \"$lockfile\"; then\n echo \"Successfully acquired lock\"\n # do work\n rm \"$lockfile\" # XXX or via trap - see below\nelse\n echo \"Cannot acquire lock - already locked by $(cat \"$lockfile\")\"\nfi\n</code></pre>\n\n<p>This causes the shell to call:</p>\n\n<pre><code>open(pathname, O_CREAT|O_EXCL)\n</code></pre>\n\n<p>which atomically creates the file or fails if the file already exists.</p>\n\n<hr>\n\n<p>According to a comment on <a href=\"http://mywiki.wooledge.org/BashFAQ/045\" rel=\"noreferrer\">BashFAQ 045</a>, this may fail in <code>ksh88</code>, but it works in all my shells:</p>\n\n<pre><code>$ strace -e trace=creat,open -f /bin/bash /home/mikel/bin/testopen 2&gt;&amp;1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_LARGEFILE, 0666) = 3\n\n$ strace -e trace=creat,open -f /bin/zsh /home/mikel/bin/testopen 2&gt;&amp;1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_NOCTTY|O_LARGEFILE, 0666) = 3\n\n$ strace -e trace=creat,open -f /bin/pdksh /home/mikel/bin/testopen 2&gt;&amp;1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_TRUNC|O_LARGEFILE, 0666) = 3\n\n$ strace -e trace=creat,open -f /bin/dash /home/mikel/bin/testopen 2&gt;&amp;1 | grep -F testopen.lock\nopen(\"/tmp/testopen.lock\", O_WRONLY|O_CREAT|O_EXCL|O_LARGEFILE, 0666) = 3\n</code></pre>\n\n<p>Interesting that <code>pdksh</code> adds the <code>O_TRUNC</code> flag, but obviously it's redundant:<br>\neither you're creating an empty file, or you're not doing anything.</p>\n\n<hr>\n\n<p>How you do the <code>rm</code> depends on how you want unclean exits to be handled.</p>\n\n<p><strong>Delete on clean exit</strong></p>\n\n<p>New runs fail until the issue that caused the unclean exit to be resolved and the lockfile is manually removed.</p>\n\n<pre><code># acquire lock\n# do work (code here may call exit, etc.)\nrm \"$lockfile\"\n</code></pre>\n\n<p><strong>Delete on any exit</strong></p>\n\n<p>New runs succeed provided the script is not already running.</p>\n\n<pre><code>trap 'rm \"$lockfile\"' EXIT\n</code></pre>\n" }, { "answer_id": 7935037, "author": "Mark Stinson", "author_id": 407989, "author_profile": "https://Stackoverflow.com/users/407989", "pm_score": 4, "selected": false, "text": "<p>For shell scripts, I tend to go with the <code>mkdir</code> over <code>flock</code> as it makes the locks more portable.</p>\n\n<p>Either way, using <code>set -e</code> isn't enough. That only exits the script if any command fails. Your locks will still be left behind.</p>\n\n<p>For proper lock cleanup, you really should set your traps to something like this psuedo code (lifted, simplified and untested but from actively used scripts) :</p>\n\n<pre><code>#=======================================================================\n# Predefined Global Variables\n#=======================================================================\n\nTMPDIR=/tmp/myapp\n[[ ! -d $TMP_DIR ]] \\\n &amp;&amp; mkdir -p $TMP_DIR \\\n &amp;&amp; chmod 700 $TMPDIR\n\nLOCK_DIR=$TMP_DIR/lock\n\n#=======================================================================\n# Functions\n#=======================================================================\n\nfunction mklock {\n __lockdir=\"$LOCK_DIR/$(date +%s.%N).$$\" # Private Global. Use Epoch.Nano.PID\n\n # If it can create $LOCK_DIR then no other instance is running\n if $(mkdir $LOCK_DIR)\n then\n mkdir $__lockdir # create this instance's specific lock in queue\n LOCK_EXISTS=true # Global\n else\n echo \"FATAL: Lock already exists. Another copy is running or manually lock clean up required.\"\n exit 1001 # Or work out some sleep_while_execution_lock elsewhere\n fi\n}\n\nfunction rmlock {\n [[ ! -d $__lockdir ]] \\\n &amp;&amp; echo \"WARNING: Lock is missing. $__lockdir does not exist\" \\\n || rmdir $__lockdir\n}\n\n#-----------------------------------------------------------------------\n# Private Signal Traps Functions {{{2\n#\n# DANGER: SIGKILL cannot be trapped. So, try not to `kill -9 PID` or \n# there will be *NO CLEAN UP*. You'll have to manually remove \n# any locks in place.\n#-----------------------------------------------------------------------\nfunction __sig_exit {\n\n # Place your clean up logic here \n\n # Remove the LOCK\n [[ -n $LOCK_EXISTS ]] &amp;&amp; rmlock\n}\n\nfunction __sig_int {\n echo \"WARNING: SIGINT caught\" \n exit 1002\n}\n\nfunction __sig_quit {\n echo \"SIGQUIT caught\"\n exit 1003\n}\n\nfunction __sig_term {\n echo \"WARNING: SIGTERM caught\" \n exit 1015\n}\n\n#=======================================================================\n# Main\n#=======================================================================\n\n# Set TRAPs\ntrap __sig_exit EXIT # SIGEXIT\ntrap __sig_int INT # SIGINT\ntrap __sig_quit QUIT # SIGQUIT\ntrap __sig_term TERM # SIGTERM\n\nmklock\n\n# CODE\n\nexit # No need for cleanup code here being in the __sig_exit trap function\n</code></pre>\n\n<p>Here's what will happen. All traps will produce an exit so the function <code>__sig_exit</code> will always happen (barring a SIGKILL) which cleans up your locks.</p>\n\n<p>Note: my exit values are not low values. Why? Various batch processing systems make or have expectations of the numbers 0 through 31. Setting them to something else, I can have my scripts and batch streams react accordingly to the previous batch job or script.</p>\n" }, { "answer_id": 10437121, "author": "presto8", "author_id": 307413, "author_profile": "https://Stackoverflow.com/users/307413", "pm_score": 2, "selected": false, "text": "<p>If flock's limitations, which have already been described elsewhere on this thread, aren't an issue for you, then this should work:</p>\n\n<pre><code>#!/bin/bash\n\n{\n # exit if we are unable to obtain a lock; this would happen if \n # the script is already running elsewhere\n # note: -x (exclusive) is the default\n flock -n 100 || exit\n\n # put commands to run here\n sleep 100\n} 100&gt;/tmp/myjob.lock \n</code></pre>\n" }, { "answer_id": 12892370, "author": "NickSoft", "author_id": 676439, "author_profile": "https://Stackoverflow.com/users/676439", "pm_score": 2, "selected": false, "text": "<p>Actually although the answer of bmdhacks is almost good, there is a slight chance the second script to run after first checked the lockfile and before it wrote it. So they both will write the lock file and they will both be running. Here is how to make it work for sure:</p>\n\n<pre><code>lockfile=/var/lock/myscript.lock\n\nif ( set -o noclobber; echo \"$$\" &gt; \"$lockfile\") 2&gt; /dev/null ; then\n trap 'rm -f \"$lockfile\"; exit $?' INT TERM EXIT\nelse\n # or you can decide to skip the \"else\" part if you want\n echo \"Another instance is already running!\"\nfi\n</code></pre>\n\n<p>The <code>noclobber</code> option will make sure that redirect command will fail if file already exists. So the redirect command is actually atomic - you write and check the file with one command. You don't need to remove the lockfile at the end of file - it'll be removed by the trap. I hope this helps to people that will read it later.</p>\n\n<p>P.S. I didn't see that Mikel already answered the question correctly, although he didn't include the trap command to reduce the chance the lock file will be left over after stopping the script with Ctrl-C for example. So this is the complete solution</p>\n" }, { "answer_id": 15921192, "author": "Znik", "author_id": 2261349, "author_profile": "https://Stackoverflow.com/users/2261349", "pm_score": 3, "selected": false, "text": "<p>This example is explained in the man flock, but it needs some impovements, because we should manage bugs and exit codes:</p>\n\n<pre><code> #!/bin/bash\n #set -e this is useful only for very stupid scripts because script fails when anything command exits with status more than 0 !! without possibility for capture exit codes. not all commands exits &gt;0 are failed.\n\n( #start subprocess\n # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds\n flock -x -w 10 200\n if [ \"$?\" != \"0\" ]; then echo Cannot lock!; exit 1; fi\n echo $$&gt;&gt;/var/lock/.myscript.exclusivelock #for backward lockdir compatibility, notice this command is executed AFTER command bottom ) 200&gt;/var/lock/.myscript.exclusivelock.\n # Do stuff\n # you can properly manage exit codes with multiple command and process algorithm.\n # I suggest throw this all to external procedure than can properly handle exit X commands\n\n) 200&gt;/var/lock/.myscript.exclusivelock #exit subprocess\n\nFLOCKEXIT=$? #save exitcode status\n #do some finish commands\n\nexit $FLOCKEXIT #return properly exitcode, may be usefull inside external scripts\n</code></pre>\n\n<p>You can use another method, list processes that I used in the past. But this is more complicated that method above. You should list processes by ps, filter by its name, additional filter grep -v grep for remove parasite nad finally count it by grep -c . and compare with number. Its complicated and uncertain</p>\n" }, { "answer_id": 18670656, "author": "Majal", "author_id": 2756066, "author_profile": "https://Stackoverflow.com/users/2756066", "pm_score": 4, "selected": false, "text": "<p><i><strong>Really</strong></i> quick and <i>really</i> dirty? This one-liner on the top of your script will work:</p>\n\n<pre><code>[[ $(pgrep -c \"`basename \\\"$0\\\"`\") -gt 1 ]] &amp;&amp; exit\n</code></pre>\n\n<p>Of course, just make sure that your script name is unique. :)</p>\n" }, { "answer_id": 20862433, "author": "rouble", "author_id": 215120, "author_profile": "https://Stackoverflow.com/users/215120", "pm_score": 2, "selected": false, "text": "<p>I use a simple approach that handles stale lock files.</p>\n\n<p>Note that some of the above solutions that store the pid, ignore the fact that the pid can wrap around. So - just checking if there is a valid process with the stored pid is not enough, especially for long running scripts.</p>\n\n<p>I use noclobber to make sure only one script can open and write to the lock file at one time. Further, I store enough information to uniquely identify a process in the lockfile. I define the set of data to uniquely identify a process to be pid,ppid,lstart. </p>\n\n<p>When a new script starts up, if it fails to create the lock file, it then verifies that the process that created the lock file is still around. If not, we assume the original process died an ungraceful death, and left a stale lock file. The new script then takes ownership of the lock file, and all is well the world, again.</p>\n\n<p>Should work with multiple shells across multiple platforms. Fast, portable and simple.</p>\n\n<pre><code>#!/usr/bin/env sh\n# Author: rouble\n\nLOCKFILE=/var/tmp/lockfile #customize this line\n\ntrap release INT TERM EXIT\n\n# Creates a lockfile. Sets global variable $ACQUIRED to true on success.\n# \n# Returns 0 if it is successfully able to create lockfile.\nacquire () {\n set -C #Shell noclobber option. If file exists, &gt; will fail.\n UUID=`ps -eo pid,ppid,lstart $$ | tail -1`\n if (echo \"$UUID\" &gt; \"$LOCKFILE\") 2&gt;/dev/null; then\n ACQUIRED=\"TRUE\"\n return 0\n else\n if [ -e $LOCKFILE ]; then \n # We may be dealing with a stale lock file.\n # Bring out the magnifying glass. \n CURRENT_UUID_FROM_LOCKFILE=`cat $LOCKFILE`\n CURRENT_PID_FROM_LOCKFILE=`cat $LOCKFILE | cut -f 1 -d \" \"`\n CURRENT_UUID_FROM_PS=`ps -eo pid,ppid,lstart $CURRENT_PID_FROM_LOCKFILE | tail -1`\n if [ \"$CURRENT_UUID_FROM_LOCKFILE\" == \"$CURRENT_UUID_FROM_PS\" ]; then \n echo \"Script already running with following identification: $CURRENT_UUID_FROM_LOCKFILE\" &gt;&amp;2\n return 1\n else\n # The process that created this lock file died an ungraceful death. \n # Take ownership of the lock file.\n echo \"The process $CURRENT_UUID_FROM_LOCKFILE is no longer around. Taking ownership of $LOCKFILE\"\n release \"FORCE\"\n if (echo \"$UUID\" &gt; \"$LOCKFILE\") 2&gt;/dev/null; then\n ACQUIRED=\"TRUE\"\n return 0\n else\n echo \"Cannot write to $LOCKFILE. Error.\" &gt;&amp;2\n return 1\n fi\n fi\n else\n echo \"Do you have write permissons to $LOCKFILE ?\" &gt;&amp;2\n return 1\n fi\n fi\n}\n\n# Removes the lock file only if this script created it ($ACQUIRED is set), \n# OR, if we are removing a stale lock file (first parameter is \"FORCE\") \nrelease () {\n #Destroy lock file. Take no prisoners.\n if [ \"$ACQUIRED\" ] || [ \"$1\" == \"FORCE\" ]; then\n rm -f $LOCKFILE\n fi\n}\n\n# Test code\n# int main( int argc, const char* argv[] )\necho \"Acquring lock.\"\nacquire\nif [ $? -eq 0 ]; then \n echo \"Acquired lock.\"\n read -p \"Press [Enter] key to release lock...\"\n release\n echo \"Released lock.\"\nelse\n echo \"Unable to acquire lock.\"\nfi\n</code></pre>\n" }, { "answer_id": 22427524, "author": "tiian", "author_id": 3423812, "author_profile": "https://Stackoverflow.com/users/3423812", "pm_score": 0, "selected": false, "text": "<p>Take a look to FLOM (Free LOck Manager) <a href=\"http://sourceforge.net/projects/flom/\" rel=\"nofollow\">http://sourceforge.net/projects/flom/</a>: you can synchronize commands and/or scripts using abstract resources that does not need lock files in a filesystem. You can synchronize commands running in different systems without a NAS (Network Attached Storage) like an NFS (Network File System) server.</p>\n\n<p>Using the simplest use case, serializing \"command1\" and \"command2\" may be as easy as executing:</p>\n\n<pre><code>flom -- command1\n</code></pre>\n\n<p>and</p>\n\n<pre><code>flom -- command2\n</code></pre>\n\n<p>from two different shell scripts.</p>\n" }, { "answer_id": 23625689, "author": "Stefan Rogin", "author_id": 1342199, "author_profile": "https://Stackoverflow.com/users/1342199", "pm_score": 0, "selected": false, "text": "<p>Here is a more elegant, fail-safe, quick <s>&amp; dirty</s> method, combining the answers provided above.</p>\n\n<h1>Usage</h1>\n\n<ol>\n<li>include <strong>sh_lock_functions.sh</strong></li>\n<li>init using <strong>sh_lock_init</strong></li>\n<li>lock using <strong>sh_acquire_lock</strong></li>\n<li>check lock using <strong>sh_check_lock</strong></li>\n<li>unlock using <strong>sh_remove_lock</strong></li>\n</ol>\n\n<h1>Script File</h1>\n\n<p><strong>sh_lock_functions.sh</strong></p>\n\n<pre><code>#!/bin/bash\n\nfunction sh_lock_init {\n sh_lock_scriptName=$(basename $0)\n sh_lock_dir=\"/tmp/${sh_lock_scriptName}.lock\" #lock directory\n sh_lock_file=\"${sh_lock_dir}/lockPid.txt\" #lock file\n}\n\nfunction sh_acquire_lock {\n if mkdir $sh_lock_dir 2&gt;/dev/null; then #check for lock\n echo \"$sh_lock_scriptName lock acquired successfully.\"&gt;&amp;2\n touch $sh_lock_file\n echo $$ &gt; $sh_lock_file # set current pid in lockFile\n return 0\n else\n touch $sh_lock_file\n read sh_lock_lastPID &lt; $sh_lock_file\n if [ ! -z \"$sh_lock_lastPID\" -a -d /proc/$sh_lock_lastPID ]; then # if lastPID is not null and a process with that pid exists\n echo \"$sh_lock_scriptName is already running.\"&gt;&amp;2\n return 1\n else\n echo \"$sh_lock_scriptName stopped during execution, reacquiring lock.\"&gt;&amp;2\n echo $$ &gt; $sh_lock_file # set current pid in lockFile\n return 2\n fi\n fi\n return 0\n}\n\nfunction sh_check_lock {\n [[ ! -f $sh_lock_file ]] &amp;&amp; echo \"$sh_lock_scriptName lock file removed.\"&gt;&amp;2 &amp;&amp; return 1\n read sh_lock_lastPID &lt; $sh_lock_file\n [[ $sh_lock_lastPID -ne $$ ]] &amp;&amp; echo \"$sh_lock_scriptName lock file pid has changed.\"&gt;&amp;2 &amp;&amp; return 2\n echo \"$sh_lock_scriptName lock still in place.\"&gt;&amp;2\n return 0\n}\n\nfunction sh_remove_lock {\n rm -r $sh_lock_dir\n}\n</code></pre>\n\n<h1>Usage example</h1>\n\n<p><strong>sh_lock_usage_example.sh</strong></p>\n\n<pre><code>#!/bin/bash\n. /path/to/sh_lock_functions.sh # load sh lock functions\n\nsh_lock_init || exit $?\n\nsh_acquire_lock\nlockStatus=$?\n[[ $lockStatus -eq 1 ]] &amp;&amp; exit $lockStatus\n[[ $lockStatus -eq 2 ]] &amp;&amp; echo \"lock is set, do some resume from crash procedures\";\n\n#monitoring example\ncnt=0\nwhile sh_check_lock # loop while lock is in place\ndo\n echo \"$sh_scriptName running (pid $$)\"\n sleep 1\n let cnt++\n [[ $cnt -gt 5 ]] &amp;&amp; break\ndone\n\n#remove lock when process finished\nsh_remove_lock || exit $?\n\nexit 0\n</code></pre>\n\n<h1>Features</h1>\n\n<ul>\n<li>Uses a combination of file, directory and process id to lock to make sure that the process is not already running</li>\n<li>You can detect if the script stopped before lock removal (eg. process kill, shutdown, error etc.)</li>\n<li>You can check the lock file, and use it to trigger a process shutdown when the lock is missing</li>\n<li>Verbose, outputs error messages for easier debug</li>\n</ul>\n" }, { "answer_id": 25133391, "author": "user3132194", "author_id": 3132194, "author_profile": "https://Stackoverflow.com/users/3132194", "pm_score": 3, "selected": false, "text": "<p>Add this line at the beginning of your script</p>\n\n<pre><code>[ \"${FLOCKER}\" != \"$0\" ] &amp;&amp; exec env FLOCKER=\"$0\" flock -en \"$0\" \"$0\" \"$@\" || :\n</code></pre>\n\n<p>It's a boilerplate code from man flock.</p>\n\n<p>If you want more logging, use this one</p>\n\n<pre><code>[ \"${FLOCKER}\" != \"$0\" ] &amp;&amp; { echo \"Trying to start build from queue... \"; exec bash -c \"FLOCKER='$0' flock -E $E_LOCKED -en '$0' '$0' '$@' || if [ \\\"\\$?\\\" -eq $E_LOCKED ]; then echo 'Locked.'; fi\"; } || echo \"Lock is free. Completing.\"\n</code></pre>\n\n<p>This sets and checks locks using <code>flock</code> utility.\nThis code detects if it was run first time by checking FLOCKER variable, if it is not set to script name, then it tries to start script again recursively using flock and with FLOCKER variable initialized, if FLOCKER is set correctly, then flock on previous iteration succeeded and it is OK to proceed. If lock is busy, it fails with configurable exit code.</p>\n\n<p>It seems to not work on Debian 7, but seems to work back again with experimental util-linux 2.25 package. It writes \"flock: ... Text file busy\". It could be overridden by disabling write permission on your script.</p>\n" }, { "answer_id": 25243837, "author": "bk138", "author_id": 361413, "author_profile": "https://Stackoverflow.com/users/361413", "pm_score": 3, "selected": false, "text": "<p>Here's an approach that combines atomic directory locking with a check for stale lock via PID and restart if stale. Also, this does not rely on any bashisms.</p>\n\n<pre><code>#!/bin/dash\n\nSCRIPTNAME=$(basename $0)\nLOCKDIR=\"/var/lock/${SCRIPTNAME}\"\nPIDFILE=\"${LOCKDIR}/pid\"\n\nif ! mkdir $LOCKDIR 2>/dev/null\nthen\n # lock failed, but check for stale one by checking if the PID is really existing\n PID=$(cat $PIDFILE)\n if ! kill -0 $PID 2>/dev/null\n then\n echo \"Removing stale lock of nonexistent PID ${PID}\" >&2\n rm -rf $LOCKDIR\n echo \"Restarting myself (${SCRIPTNAME})\" >&2\n exec \"$0\" \"$@\"\n fi\n echo \"$SCRIPTNAME is already running, bailing out\" >&2\n exit 1\nelse\n # lock successfully acquired, save PID\n echo $$ > $PIDFILE\nfi\n\ntrap \"rm -rf ${LOCKDIR}\" QUIT INT TERM EXIT\n\n\necho hello\n\nsleep 30s\n\necho bye\n</code></pre>\n" }, { "answer_id": 25288106, "author": "Sadhun", "author_id": 3455684, "author_profile": "https://Stackoverflow.com/users/3455684", "pm_score": -1, "selected": false, "text": "<p>Try something like the below,</p>\n\n<pre><code>ab=`ps -ef | grep -v grep | grep -wc processname`\n</code></pre>\n\n<p>Then match the variable with 1 using an if loop.</p>\n" }, { "answer_id": 29123275, "author": "Tim Bunce", "author_id": 77193, "author_profile": "https://Stackoverflow.com/users/77193", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://github.com/timbunce/semaphoric\" rel=\"nofollow noreferrer\">semaphoric</a> utility uses <code>flock</code> (as discussed above, e.g. by presto8) to implement a <a href=\"https://stackoverflow.com/questions/10898022/differnce-between-counting-and-binary-semaphores\">counting semaphore</a>. It enables any specific number of concurrent processes you want. We use it to limit the level of concurrency of various queue worker processes.</p>\n\n<p>It's like <a href=\"http://www.gnu.org/software/parallel/sem.html\" rel=\"nofollow noreferrer\">sem</a> but <em>much</em> lighter-weight. (Full disclosure: I wrote it after finding the sem was way too heavy for our needs and there wasn't a simple counting semaphore utility available.)</p>\n" }, { "answer_id": 31691826, "author": "Jabir Ahmed", "author_id": 1058505, "author_profile": "https://Stackoverflow.com/users/1058505", "pm_score": 0, "selected": false, "text": "<p>why dont we use something like </p>\n\n<pre><code>pgrep -f $cmd || $cmd\n</code></pre>\n" }, { "answer_id": 33999807, "author": "Rudolf Lörcks", "author_id": 5621457, "author_profile": "https://Stackoverflow.com/users/5621457", "pm_score": 0, "selected": false, "text": "<pre><code>if [ 1 -ne $(/bin/fuser \"$0\" 2&gt;/dev/null | wc -w) ]; then\n exit 1\nfi\n</code></pre>\n" }, { "answer_id": 35772112, "author": "Gianluca Casati", "author_id": 1217468, "author_profile": "https://Stackoverflow.com/users/1217468", "pm_score": 0, "selected": false, "text": "<p>I have a simple solution based on the file name</p>\n\n<pre><code>#!/bin/bash\n\nMY_FILENAME=`basename \"$BASH_SOURCE\"`\n\nMY_PROCESS_COUNT=$(ps a -o pid,cmd | grep $MY_FILENAME | grep -v grep | grep -v $$ | wc -\nl)\n\nif [ $MY_PROCESS_COUNT -ne 0 ]; then\n echo found another process\n exit 0\nif\n\n# Follows the code to get the job done.\n</code></pre>\n" }, { "answer_id": 37303133, "author": "Mark Setchell", "author_id": 2836621, "author_profile": "https://Stackoverflow.com/users/2836621", "pm_score": 5, "selected": false, "text": "<p>You can use <code>GNU Parallel</code> for this as it works as a mutex when called as <code>sem</code>. So, in concrete terms, you can use:</p>\n\n<pre><code>sem --id SCRIPTSINGLETON yourScript\n</code></pre>\n\n<p>If you want a timeout too, use:</p>\n\n<pre><code>sem --id SCRIPTSINGLETON --semaphoretimeout -10 yourScript\n</code></pre>\n\n<p>Timeout of &lt;0 means exit without running script if semaphore is not released within the timeout, timeout of >0 mean run the script anyway.</p>\n\n<p>Note that you should give it a name (with <code>--id</code>) else it defaults to the controlling terminal.</p>\n\n<p><code>GNU Parallel</code> is a very simple install on most Linux/OSX/Unix platforms - it is just a Perl script.</p>\n" }, { "answer_id": 38717423, "author": "biocyberman", "author_id": 588867, "author_profile": "https://Stackoverflow.com/users/588867", "pm_score": 0, "selected": false, "text": "<p>Late to the party, using the idea from @Majal, this is my script to start only one instance of emacsclient GUI. With it, I can set shortcutkey to open or jump back to the same emacsclient. I have another script to call emacsclient in terminals when I need it. The use of emacsclient here is just to show a working example, one can choose something else. This approach is quick and good enough for my tiny scripts. Tell me where it is dirty :)</p>\n\n<pre><code>#!/bin/bash\n\n# if [ $(pgrep -c $(basename $0)) -lt 2 ]; then # this works but requires script name to be unique\nif [ $(pidof -x \"$0\"|wc -w ) -lt 3 ]; then\n echo -e \"Starting $(basename $0)\"\n emacsclient --alternate-editor=\"\" -c \"$@\"\nelse\n echo -e \"$0 is running already\"\nfi\n</code></pre>\n" }, { "answer_id": 39649227, "author": "rubo77", "author_id": 1069083, "author_profile": "https://Stackoverflow.com/users/1069083", "pm_score": -1, "selected": false, "text": "<p>This will work, if your script name is unique:</p>\n\n<pre><code>#!/bin/bash\nif [ $(pgrep -c $(basename $0)) -gt 1 ]; then \n echo $(basename $0) is already running\n exit 0\nfi\n</code></pre>\n\n<p>If the scriptname is not unique, this works on most linux distributions:</p>\n\n<pre><code>#!/bin/bash\nexec 9&gt;/tmp/my_lock_file\nif ! flock -n 9 ; then\n echo \"another instance of this script is already running\";\n exit 1\nfi\n</code></pre>\n\n<p><em>source:</em> <a href=\"http://mywiki.wooledge.org/BashFAQ/045\" rel=\"nofollow\">http://mywiki.wooledge.org/BashFAQ/045</a></p>\n" }, { "answer_id": 40145228, "author": "one-liner", "author_id": 3130850, "author_profile": "https://Stackoverflow.com/users/3130850", "pm_score": 2, "selected": false, "text": "<p>I wanted to do away with lockfiles, lockdirs, special locking programs and even <code>pidof</code> since it isn't found on all Linux installations. Also wanted to have the simplest code possible (or at least as few lines as possible). Simplest <code>if</code> statement, in one line:</p>\n\n<pre><code>if [[ $(ps axf | awk -v pid=$$ '$1!=pid &amp;&amp; $6~/'$(basename $0)'/{print $1}') ]]; then echo \"Already running\"; exit; fi\n</code></pre>\n" }, { "answer_id": 44296058, "author": "David M. Syzdek", "author_id": 903194, "author_profile": "https://Stackoverflow.com/users/903194", "pm_score": 3, "selected": false, "text": "<p>The existing answers posted either rely on the CLI utility <code>flock</code> or do not properly secure the lock file. The flock utility is not available on all non-Linux systems (i.e. FreeBSD), and does not work properly on NFS.</p>\n\n<p>In my early days of system administration and system development, I was told that a safe and relatively portable method of creating a lock file was to create a temp file using <code>mkemp(3)</code> or <code>mkemp(1)</code>, write identifying information to the temp file (i.e. PID), then hard link the temp file to the lock file. If the link was successful, then you have successfully obtained the lock.</p>\n\n<p>When using locks in shell scripts, I typically place an <code>obtain_lock()</code> function in a shared profile and then source it from the scripts. Below is an example of my lock function:</p>\n\n<pre><code>obtain_lock()\n{\n LOCK=\"${1}\"\n LOCKDIR=\"$(dirname \"${LOCK}\")\"\n LOCKFILE=\"$(basename \"${LOCK}\")\"\n\n # create temp lock file\n TMPLOCK=$(mktemp -p \"${LOCKDIR}\" \"${LOCKFILE}XXXXXX\" 2&gt; /dev/null)\n if test \"x${TMPLOCK}\" == \"x\";then\n echo \"unable to create temporary file with mktemp\" 1&gt;&amp;2\n return 1\n fi\n echo \"$$\" &gt; \"${TMPLOCK}\"\n\n # attempt to obtain lock file\n ln \"${TMPLOCK}\" \"${LOCK}\" 2&gt; /dev/null\n if test $? -ne 0;then\n rm -f \"${TMPLOCK}\"\n echo \"unable to obtain lockfile\" 1&gt;&amp;2\n if test -f \"${LOCK}\";then\n echo \"current lock information held by: $(cat \"${LOCK}\")\" 1&gt;&amp;2\n fi\n return 2\n fi\n rm -f \"${TMPLOCK}\"\n\n return 0;\n};\n</code></pre>\n\n<p>The following is an example of how to use the lock function:</p>\n\n<pre><code>#!/bin/sh\n\n. /path/to/locking/profile.sh\nPROG_LOCKFILE=\"/tmp/myprog.lock\"\n\nclean_up()\n{\n rm -f \"${PROG_LOCKFILE}\"\n}\n\nobtain_lock \"${PROG_LOCKFILE}\"\nif test $? -ne 0;then\n exit 1\nfi\ntrap clean_up SIGHUP SIGINT SIGTERM\n\n# bulk of script\n\nclean_up\nexit 0\n# end of script\n</code></pre>\n\n<p>Remember to call <code>clean_up</code> at any exit points in your script.</p>\n\n<p>I've used the above in both Linux and FreeBSD environments.</p>\n" }, { "answer_id": 47578176, "author": "sivann", "author_id": 848547, "author_profile": "https://Stackoverflow.com/users/848547", "pm_score": 2, "selected": false, "text": "<p>An example with flock(1) but without subshell. flock()ed file /tmp/foo is never removed, but that doesn't matter as it gets flock() and un-flock()ed.</p>\n\n<pre><code>#!/bin/bash\n\nexec 9&lt;&gt; /tmp/foo\nflock -n 9\nRET=$?\nif [[ $RET -ne 0 ]] ; then\n echo \"lock failed, exiting\"\n exit\nfi\n\n#Now we are inside the \"critical section\"\necho \"inside lock\"\nsleep 5\nexec 9&gt;&amp;- #close fd 9, and release lock\n\n#The part below is outside the critical section (the lock)\necho \"lock released\"\nsleep 5\n</code></pre>\n" }, { "answer_id": 49338826, "author": "WinEunuuchs2Unix", "author_id": 6929343, "author_profile": "https://Stackoverflow.com/users/6929343", "pm_score": 2, "selected": false, "text": "<p>This one line answer comes from someone related <a href=\"https://askubuntu.com/questions/988032/how-can-i-cause-a-script-to-log-in-a-separate-file-the-number-of-times-it-has-be/1015648#1015648\">Ask Ubuntu Q&amp;A</a>:</p>\n\n<pre><code>[ \"${FLOCKER}\" != \"$0\" ] &amp;&amp; exec env FLOCKER=\"$0\" flock -en \"$0\" \"$0\" \"$@\" || :\n# This is useful boilerplate code for shell scripts. Put it at the top of\n# the shell script you want to lock and it'll automatically lock itself on\n# the first run. If the env var $FLOCKER is not set to the shell script\n# that is being run, then execute flock and grab an exclusive non-blocking\n# lock (using the script itself as the lock file) before re-execing itself\n# with the right arguments. It also sets the FLOCKER env var to the right\n# value so it doesn't run again.\n</code></pre>\n" }, { "answer_id": 49920240, "author": "Filidor Wiese", "author_id": 3964328, "author_profile": "https://Stackoverflow.com/users/3964328", "pm_score": 1, "selected": false, "text": "<p>Answered a million times already, but another way, without the need for external dependencies:</p>\n\n<pre><code>LOCK_FILE=\"/var/lock/$(basename \"$0\").pid\"\ntrap \"rm -f ${LOCK_FILE}; exit\" INT TERM EXIT\nif [[ -f $LOCK_FILE &amp;&amp; -d /proc/`cat $LOCK_FILE` ]]; then\n // Process already exists\n exit 1\nfi\necho $$ &gt; $LOCK_FILE\n</code></pre>\n\n<p>Each time it writes the current PID ($$) into the lockfile and on script startup checks if a process is running with the latest PID.</p>\n" }, { "answer_id": 50373642, "author": "untore", "author_id": 2229761, "author_profile": "https://Stackoverflow.com/users/2229761", "pm_score": 0, "selected": false, "text": "<p>This I have not found mentioned anywhere, it uses read, I don't exactly know if read is actually atomic but it has served me well so far..., it is juicy because it is only bash builtins, this is an in process implementation, you start the locker coprocess and use its i/o to manage locks, the same can be done interprocess by just swapping the target i/o from the locker file descriptors to a on filesystem file descriptor (<code>exec 3&lt;&gt;/file &amp;&amp; exec 4&lt;/file</code>)</p>\n\n\n\n<pre><code>## gives locks\nlocker() {\n locked=false\n while read l; do\n case \"$l\" in\n lock)\n if $locked; then\n echo false\n else\n locked=true\n echo true\n fi\n ;;\n unlock)\n if $locked; then\n locked=false\n echo true\n else\n echo false\n fi\n ;;\n *)\n echo false\n ;;\n esac\n done\n}\n## locks\nlock() {\n local response\n echo lock &gt;&amp;${locker[1]}\n read -ru ${locker[0]} response\n $response &amp;&amp; return 0 || return 1\n}\n\n## unlocks\nunlock() {\n local response\n echo unlock &gt;&amp;${locker[1]}\n read -ru ${locker[0]} response\n $response &amp;&amp; return 0 || return 1\n}\n</code></pre>\n" }, { "answer_id": 54321529, "author": "Sudhir Kumar", "author_id": 10954104, "author_profile": "https://Stackoverflow.com/users/10954104", "pm_score": 1, "selected": false, "text": "<p>Using the process's lock is much stronger and takes care of the ungraceful exits also.\nlock_file is kept open as long as the process is running. It will be closed (by shell) once the process exists (even if it gets killed). \nI found this to be very efficient:</p>\n\n<pre><code>lock_file=/tmp/`basename $0`.lock\n\nif fuser $lock_file &gt; /dev/null 2&gt;&amp;1; then\n echo \"WARNING: Other instance of $(basename $0) running.\"\n exit 1\nfi\nexec 3&gt; $lock_file \n</code></pre>\n" }, { "answer_id": 59494571, "author": "Z KC", "author_id": 11167486, "author_profile": "https://Stackoverflow.com/users/11167486", "pm_score": 1, "selected": false, "text": "<p>I use oneliner @ the very beginning of script:</p>\n\n<pre><code>#!/bin/bash\n\nif [[ $(pgrep -afc \"$(basename \"$0\")\") -gt \"1\" ]]; then echo \"Another instance of \"$0\" has already been started!\" &amp;&amp; exit; fi\n.\nthe_beginning_of_actual_script\n</code></pre>\n\n<p>It is good to see the presence of process in the memory (no matter what the status of process is); but it does the job for me.</p>\n" }, { "answer_id": 70285077, "author": "AnyDev", "author_id": 2742342, "author_profile": "https://Stackoverflow.com/users/2742342", "pm_score": 0, "selected": false, "text": "<p>I have following problems with the existing answers:</p>\n<ul>\n<li>Some answers try to clean up lock files and then having to deal with stale lock files caused by e.g. sudden crash/reboot.\nIMO that is unnecessarily complicated.\nLet lock files stay.</li>\n<li>Some answers use script file itself <code>$0</code> or <code>$BASH_SOURCE</code> for locking often referring to examples from <code>man flock</code>.\nThis fails when script is replaced due to update or edit causing next run to open and obtain lock on the new script file even though another instance holding a lock on the removed file is still running.</li>\n<li>Few answers use a fixed file descriptor.\nThis is not ideal.\nI do not want to rely on how this will behave e.g. opening lock file fails but gets mishandled and attempts to lock on unrelated file descriptor inherited from parent process.\nAnother fail case is injecting locking wrapper for a 3rd party binary that does not handle locking itself but fixed file descriptors can interfere with file descriptor passing to child processes.</li>\n<li>I reject answers using process lookup for already running script name.\nThere are several reasons for it, such as but not limited to reliability/atomicity, parsing output, and having script that does several related functions some of which do not require locking.</li>\n</ul>\n<p>This answer does:</p>\n<ul>\n<li>rely on <code>flock</code> because it gets kernel to provide locking ... provided lock file is created atomically and not replaced.</li>\n<li>assume and rely on lock file being stored on the local filesystem as opposed to NFS.</li>\n<li>change lock file presence to NOT mean anything about a running instance.\nIts role is purely to prevent two concurrent instances creating file with same name and replacing another's copy.\nLock file does not get deleted, it gets left behind and can survive across reboots.\nThe locking is indicated via <code>flock</code> not via lock file presence.</li>\n<li>assume bash shell, as tagged by the question.</li>\n</ul>\n<p>It's not a oneliner, but without comments nor error messages it's small enough:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\nLOCKFILE=/var/lock/TODO\n\nset -o noclobber\nexec {lockfd}&lt;&gt; &quot;${LOCKFILE}&quot; || exit 1\nset +o noclobber # depends on what you need\nflock --exclusive --nonblock ${lockfd} || exit 1\n</code></pre>\n<p>But I prefer comments and error messages:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\n# TODO Set a lock file name\nLOCKFILE=/var/lock/myprogram.lock\n\n# Set noclobber option to ensure lock file is not REPLACED.\nset -o noclobber\n\n# Open lock file for R+W on a new file descriptor\n# and assign the new file descriptor to &quot;lockfd&quot; variable.\n# This does NOT obtain a lock but ensures the file exists and opens it.\nexec {lockfd}&lt;&gt; &quot;${LOCKFILE}&quot; || {\n echo &quot;pid=$$ failed to open LOCKFILE='${LOCKFILE}'&quot; 1&gt;&amp;2\n exit 1\n}\n\n# TODO!!!! undo/set the desired noclobber value for the remainder of the script\nset +o noclobber\n\n# Lock on the allocated file descriptor or fail\n# Adjust flock options e.g. --noblock as needed\nflock --exclusive --nonblock ${lockfd} || {\n echo &quot;pid=$$ failed to obtain lock fd='${lockfd}' LOCKFILE='${LOCKFILE}'&quot; 1&gt;&amp;2\n exit 1\n}\n\n# DO work here\necho &quot;pid=$$ obtained exclusive lock fd='${lockfd}' LOCKFILE='${LOCKFILE}'&quot;\n\n# Can unlock after critical section and do more work after unlocking\n#flock -u ${lockfd};\n# if unlocking then might as well close lockfd too\n#exec {lockfd}&lt;&amp;-\n</code></pre>\n" }, { "answer_id": 72634429, "author": "Keyless", "author_id": 19345335, "author_profile": "https://Stackoverflow.com/users/19345335", "pm_score": 1, "selected": false, "text": "<p>If you do not want to or cannot use <code>flock</code> (e.g. you are not using a shared file system), consider using an external service like <a href=\"https://lockable.dev\" rel=\"nofollow noreferrer\">lockable</a>.</p>\n<p>It exposes advisory lock primitives, much like <code>flock</code> would. In particular, you can acquire a lock via:</p>\n<pre><code>https://lockable.dev/api/acquire/my-lock-name\n</code></pre>\n<p>and release it via</p>\n<pre><code>https://lockable.dev/api/release/my-lock-name\n</code></pre>\n<p>By wrapping script execution with lock acquisition and release, you can make sure only a single instance of the process is running at any given time.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?
Here's an implementation that uses a *lockfile* and echoes a PID into it. This serves as a protection if the process is killed before removing the *pidfile*: ``` LOCKFILE=/tmp/lock.txt if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then echo "already running" exit fi # make sure the lockfile is removed when we exit and then claim it trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT echo $$ > ${LOCKFILE} # do stuff sleep 1000 rm -f ${LOCKFILE} ``` The trick here is the `kill -0` which doesn't deliver any signal but just checks if a process with the given PID exists. Also the call to `trap` will ensure that the *lockfile* is removed even when your process is killed (except `kill -9`).
185,461
<p>I would like MATLAB to tell me if I have an input file (.m file) that contains some variables with their numbers (i.e., <code>a = 5</code>, <code>b = 6</code>, <code>c = 7</code>) so that I can then use that .m file in another program (main .m file) that uses these variables to calculate <code>S = a + b + c</code>. How can I then read the input file from the main file? Assume the input file is called INP and the main MAIN.</p>
[ { "answer_id": 185469, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 2, "selected": false, "text": "<p>If your \"input\" file is an m-file, just use the name of the file in your \"main\" m-file. For example you might have a file called input.m that looks like this:</p>\n\n<pre><code>% File: inputs.m\na = 5;\nb = 6;\nc = 7;\n</code></pre>\n\n<p>Then, you can use it in the file main.m like this:</p>\n\n<pre><code>% File: main.m\ninputs;\nS = a + b + c;\n</code></pre>\n" }, { "answer_id": 185660, "author": "KennyMorton", "author_id": 4135, "author_profile": "https://Stackoverflow.com/users/4135", "pm_score": 3, "selected": false, "text": "<p>This is typically not good practice in MATLAB. The file containing the input variables would, in your example, be a script. As would your main file. MATLAB does not error when running one script from another, as suggested by ScottieT812, but under certain circumstances strange errors can arise. (Run time compiling has difficulty, variable name collisions across scripts)</p>\n\n<p>A better option is to turn the inputs script into a function which returns the variables of interest</p>\n\n<pre><code>function [a,b c] = inputs\na = 5;\nb = 6;\nc = 7;\n</code></pre>\n\n<p>Then this function can be called in the main.m script.</p>\n\n<pre><code>% main.m\n[a,b,c] = inputs;\ns = a+b+c;\n</code></pre>\n" }, { "answer_id": 189482, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 0, "selected": false, "text": "<p>I ran into the exact problem <a href=\"https://stackoverflow.com/questions/185461/reading-input-m-file-in-a-main-m-file#185660\">KennyMorton</a> mentioned when trying to create runtime compiled versions of MATLAB software for my work. The software uses m-files extensively for passing arguments between functions. Additionally, we create these m-files dynamically which the deployed version of MATLAB does not play nice with. Our workaround was:</p>\n\n<ul>\n<li>save the parameters to a file without the .m extension </li>\n<li>read and eval the contents of the file</li>\n</ul>\n\n<p>So, to follow the OPs example, in a function we would create a text file, INP, containing our parameters. We create this file in the directory returned by the <strong>ctfroot</strong> function. Then, in MAIN, we would use the following to retrieve these parameters:</p>\n\n<pre><code>eval(char(textread(fullfile(ctfroot, INP), '%s', 'whitespace', '');\n</code></pre>\n" }, { "answer_id": 193394, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 2, "selected": false, "text": "<p>It sounds like you want to have some global configuration information that's used by scripts. Often, it's much better to create functions and pass values as arguments, but sometimes it makes sense to do things the way you suggest. One way to accomplish this is to save the information in a file. See \"load\" and \"save\" in the Matlab documentation.</p>\n" }, { "answer_id": 309162, "author": "Todd", "author_id": 30841, "author_profile": "https://Stackoverflow.com/users/30841", "pm_score": 0, "selected": false, "text": "<p>If the data script is just a script, you can call it from a function or another script directly. Not extra commands required. For example:</p>\n\n<pre><code>%mydata.m\na = 1;\nb = 2;\n\n\n%mymain.m\nmydata\nwhos\nmymain\n</code></pre>\n\n<p><code>&gt;&gt;</code>mymain<br>\n Name Size Bytes Class Attributes</p>\n\n<p>a 1x1 8 double<br>\n b 1x1 8 double </p>\n\n<p>This also works for functions in addition to scripts</p>\n\n<p>%foo.m<br>\nfunction foo\nmydata<br>\nwhos<br>\n<code>&gt;&gt;</code>foo </p>\n\n<p>Name Size Bytes Class Attributes</p>\n\n<p>a 1x1 8 double<br>\n b 1x1 8 double </p>\n\n<p>Generally, it is preferable to use a MAT or other data file for this sort of thing. </p>\n" }, { "answer_id": 356821, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 2, "selected": false, "text": "<p>For this sort of stuff (parameters that are easily adjusted later) I almost always use structures:</p>\n\n<pre><code>function S = zark\n S.wheels = 24;\n S.mpg = 13.2;\n S.name = 'magic bus';\n S.transfer_fcn = @(x) x+7;\n S.K = [1 2; -2 1];\n</code></pre>\n\n<p>Then you can return lots of data without having to do stuff like [a,b,c,d,e,f]=some_function;</p>\n\n<p>One nice thing about structures is you can address them dynamically:</p>\n\n<pre><code>&gt;&gt; f = 'wheels';\n&gt;&gt; S.(f)\n\nans =\n\n 24\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like MATLAB to tell me if I have an input file (.m file) that contains some variables with their numbers (i.e., `a = 5`, `b = 6`, `c = 7`) so that I can then use that .m file in another program (main .m file) that uses these variables to calculate `S = a + b + c`. How can I then read the input file from the main file? Assume the input file is called INP and the main MAIN.
This is typically not good practice in MATLAB. The file containing the input variables would, in your example, be a script. As would your main file. MATLAB does not error when running one script from another, as suggested by ScottieT812, but under certain circumstances strange errors can arise. (Run time compiling has difficulty, variable name collisions across scripts) A better option is to turn the inputs script into a function which returns the variables of interest ``` function [a,b c] = inputs a = 5; b = 6; c = 7; ``` Then this function can be called in the main.m script. ``` % main.m [a,b,c] = inputs; s = a+b+c; ```
185,474
<p>I have a connection string being passed to a function, and I need to create a DbConnection based object (i.e. SQLConnection, OracleConnection, OLEDbConnection etc) based on this string.</p> <p>Is there any inbuilt functionality to do this, or any 3rd party libraries to assist. We are not necessarily building this connection string, so we cannot rely on a format the string is written in to determine its type, and I would <em>prefer</em> not to have to code up all combinations and permutations of possible connection strings</p>
[ { "answer_id": 185481, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 1, "selected": false, "text": "<p>You should be able to parse out the Provider section and pass it into DbProviderFactories.GetFactory which will return a OdbcFactory, OleDbFactory or SqlClientFactory and let you then perform CreateConnection etc.</p>\n\n<p>I'm not sure how this would work with Oracle unless they provide an OracleDbFactory.</p>\n" }, { "answer_id": 185482, "author": "Eric Tuttleman", "author_id": 25677, "author_profile": "https://Stackoverflow.com/users/25677", "pm_score": 4, "selected": false, "text": "<p>if you're using framework 2.0 or above, and you can get them to pass in a second string with the driver class, you can use the dbProviderFactory class to load the driver for you.</p>\n\n<pre><code>DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(myDriverClass);\nDbConnection dbConnection = dbProviderFactory.CreateConnection();\ndbConnection.ConnectionString = myConnectionString;\n</code></pre>\n\n<p>Here's an MSDN link to the Factory class:\n<a href=\"http://msdn.microsoft.com/en-us/library/wda6c36e.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/wda6c36e.aspx</a></p>\n" }, { "answer_id": 185488, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 1, "selected": false, "text": "<p>Most connection strings (at least in .NET 2.0) also have a providerName property that goes with them. So a SQL connection string will have a provider Name like:</p>\n\n<pre><code>providerName=\"System.Data.SqlClient\"\n</code></pre>\n\n<p>So your method would need to accept both the connection string and the provider name and then you could use the DbProviderFactory <a href=\"https://stackoverflow.com/questions/185474/c-retrieving-correct-dbconnection-object-by-connection-string#185481\">as mentioned by damieng</a>.</p>\n" }, { "answer_id": 185571, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "<pre><code>DbConnection GetConnection(string connStr)\n{\n string providerName = null;\n var csb = new DbConnectionStringBuilder { ConnectionString = connStr };\n \n if (csb.ContainsKey(&quot;provider&quot;)) \n {\n providerName = csb[&quot;provider&quot;].ToString();\n } \n else\n {\n var css = ConfigurationManager\n .ConnectionStrings\n .Cast&lt;ConnectionStringSettings&gt;()\n .FirstOrDefault(x =&gt; x.ConnectionString == connStr);\n if (css != null) providerName = css.ProviderName;\n }\n \n if (providerName != null) \n {\n var providerExists = DbProviderFactories\n .GetFactoryClasses()\n .Rows.Cast&lt;DataRow&gt;()\n .Any(r =&gt; r[2].Equals(providerName));\n if (providerExists) \n {\n var factory = DbProviderFactories.GetFactory(providerName);\n var dbConnection = factory.CreateConnection();\n \n dbConnection.ConnectionString = connStr;\n return dbConnection;\n }\n }\n \n return null;\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
I have a connection string being passed to a function, and I need to create a DbConnection based object (i.e. SQLConnection, OracleConnection, OLEDbConnection etc) based on this string. Is there any inbuilt functionality to do this, or any 3rd party libraries to assist. We are not necessarily building this connection string, so we cannot rely on a format the string is written in to determine its type, and I would *prefer* not to have to code up all combinations and permutations of possible connection strings
``` DbConnection GetConnection(string connStr) { string providerName = null; var csb = new DbConnectionStringBuilder { ConnectionString = connStr }; if (csb.ContainsKey("provider")) { providerName = csb["provider"].ToString(); } else { var css = ConfigurationManager .ConnectionStrings .Cast<ConnectionStringSettings>() .FirstOrDefault(x => x.ConnectionString == connStr); if (css != null) providerName = css.ProviderName; } if (providerName != null) { var providerExists = DbProviderFactories .GetFactoryClasses() .Rows.Cast<DataRow>() .Any(r => r[2].Equals(providerName)); if (providerExists) { var factory = DbProviderFactories.GetFactory(providerName); var dbConnection = factory.CreateConnection(); dbConnection.ConnectionString = connStr; return dbConnection; } } return null; } ```
185,483
<p>How do I prevent my users from accessing directly pages meant for ajax calls only?</p> <p>Passing a key during ajax call seems like a solution, whereas access without the key will not be processed. But it is also easy to fabricate the key, no? Curse of View Source...</p> <p>p/s: Using Apache as webserver.</p> <p>EDIT: To answer why, I have jQuery ui-tabs in my index.php, and inside those tabs are forms with scripts, which won't work if they're accessed directly. Why a user would want to do that, I don't know, I just figure I'd be more user friendly by preventing direct access to forms without validation scripts.</p>
[ { "answer_id": 185508, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": false, "text": "<p>There is no way of guaranteeing that they're accessing it through AJAX. Both direct access and AJAX access come from the client, so it can easily be faked.</p>\n\n<p>Why do you want to do this anyways?</p>\n\n<p>If it's because the PHP code isn't very secure, make the PHP code more secure. (For example, if your AJAX passes the user id to the PHP file, write code in the PHP file to make sure that is the correct user id.)</p>\n" }, { "answer_id": 185511, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 3, "selected": false, "text": "<p>It sounds like you might be going about things the wrong way. An AJAX call is just like a standard page request, only by convention the response is not intended for display to the user.</p>\n\n<p>It is, however, still a client request, and so you must be happy for the client to be able to see the response. Obfuscating access using a \"key\" in this way only serves to complicate things.</p>\n\n<p>I'd actually say the \"curse\" of view source is a small weapon in the fight against security through obscurity.</p>\n\n<p>So what's your reason for wanting to do this?</p>\n" }, { "answer_id": 185515, "author": "Cristian Vat", "author_id": 20109, "author_profile": "https://Stackoverflow.com/users/20109", "pm_score": 2, "selected": false, "text": "<p>If the browser will call your page, either by normal request or ajax, then someone can call it manually. There really isn't a well defined difference between normal and ajax requests as far as the server-client communication goes. </p>\n\n<p>Common case is to pass a header to the server that says \"this request was done by ajax\". If you're using Prototype, it automatically sets the http header \"X-Requested-With\" to \"XMLHttpRequest\" and also some other headers including the prototype version. (See more at <a href=\"http://www.prototypejs.org/api/ajax/options\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/ajax/options</a> at \"requestHeaders\" )</p>\n\n<p>Add: In case you're using another AJAX library you can probably add your own header. This is useful for knowing what type of request it was on the server side, and for avoiding simple cases when an ajax page would be requested in the browser. It does not protect your request from everyone because you can't.</p>\n" }, { "answer_id": 185517, "author": "Eric Tuttleman", "author_id": 25677, "author_profile": "https://Stackoverflow.com/users/25677", "pm_score": 0, "selected": false, "text": "<p>Not sure about this, but possibly check for a referrer header? i think if someone manually typed in your url, it wouldn't have a referrer header, while AJAX calls do (at least in the quickly test I just did on my system).</p>\n\n<p>It's a bad way of checking though. Referrer can be blank for a lot of reasons. Are you trying to stop people from using your web service as a public service or something?</p>\n\n<p>After reading your edit comments, if the forms will be loaded via ajax calls, than you could check window.location to see if the url is your ajax form's url. if it is, go to the right page via document.location</p>\n" }, { "answer_id": 185562, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 6, "selected": true, "text": "<p>As others have said, Ajax request can be emulated be creating the proper headers.\nIf you want to have a basic check to see if the request is an Ajax request you can use:</p>\n\n<pre><code> if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {\n //Request identified as ajax request\n }\n</code></pre>\n\n<p>However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.</p>\n" }, { "answer_id": 1280607, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This definitely isn't useful for securing something.. but I think this could be of use if you wanted to have say a php page that generated a whole page if the page was not requested by ajax but only generate the part that you needed returned when ajax was used.. This would allow you to make your site non ajax friendly so if say they click on a link and it's supposed to load a box of comments but they don't have ajax it still sends them to the page that is then generated as a whole page displaying the comments.</p>\n" }, { "answer_id": 1474549, "author": "Kzqai", "author_id": 69993, "author_profile": "https://Stackoverflow.com/users/69993", "pm_score": 1, "selected": false, "text": "<p>COOKIES are not secure... try the $_SESSION. That's pretty much one of the few things that you can actually rely on cross-page that can't be spoofed. Because, of course, it essentially never leaves your control.</p>\n" }, { "answer_id": 2521988, "author": "Antony Carthy", "author_id": 106118, "author_profile": "https://Stackoverflow.com/users/106118", "pm_score": 0, "selected": false, "text": "<p>Pass your direct requests through index.php and your ajax requests through ajax.php and then dont let the user browse to any other source file directly - make sure that index.php and ajax.php have the appropriate logic to include the code they need.</p>\n" }, { "answer_id": 5032338, "author": "foxybagga", "author_id": 95350, "author_profile": "https://Stackoverflow.com/users/95350", "pm_score": 1, "selected": false, "text": "<p>thanks, albeit I use</p>\n\n<pre><code>define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');\n\nif(IS_AJAX) {\n //Request identified as ajax request\n}\n</code></pre>\n\n<p>cheers!</p>\n" }, { "answer_id": 21524330, "author": "Jeroenv3", "author_id": 1573574, "author_profile": "https://Stackoverflow.com/users/1573574", "pm_score": 0, "selected": false, "text": "<p>In the javascript file that calls the script: </p>\n\n<pre><code>var url = \"http://website.com/ajax.php?say=hello+world\";\nxmlHttp.open(\"GET\", url, true);\nxmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n</code></pre>\n\n<p>then in the php file ajax.php:</p>\n\n<pre><code>if($_SERVER['HTTP_X_REQUESTED_WITH'] != \"XMLHttpRequest\") {\n header(\"Location: http://website.com\");\n die();\n}\n</code></pre>\n\n<p>Geeks can still call the ajax.php script by forging the header but the rest of my script requires sessions so execution ends when no valid session is detected. I needed this to work in order to redirect people with expired hybridauth sessions to the main site in order to login again because they ended up being redirected to the ajax script.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
How do I prevent my users from accessing directly pages meant for ajax calls only? Passing a key during ajax call seems like a solution, whereas access without the key will not be processed. But it is also easy to fabricate the key, no? Curse of View Source... p/s: Using Apache as webserver. EDIT: To answer why, I have jQuery ui-tabs in my index.php, and inside those tabs are forms with scripts, which won't work if they're accessed directly. Why a user would want to do that, I don't know, I just figure I'd be more user friendly by preventing direct access to forms without validation scripts.
As others have said, Ajax request can be emulated be creating the proper headers. If you want to have a basic check to see if the request is an Ajax request you can use: ``` if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { //Request identified as ajax request } ``` However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.
185,487
<p>Assuming I have three tables : TableA (key, value) TableB (key, value) TableC (key, value)</p> <p>and I want to return a value for all keys. If the key exists in TableC return that value else if the key exists in B return that value else return the value from table A</p> <p>The best I have come up with so far is</p> <pre><code>SELECT key,Value FROM TableA WHERE key NOT IN (SELECT key FROM TableB) AND key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableB WHERE key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableC </code></pre> <p>But this seems pretty brute force. Anyone know a better way?</p> <p>Edit: Here is a more concrete example. Consider TableA as a standard work schedule where the key is a date and the value is the assigned shift. Table B is a statutory holiday calendar that overrides the standard work week. Table C is an exception schedule that is used to override the other two schedules when someone is asked to come in and work either an extra shift or a different shift.</p>
[ { "answer_id": 185506, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 0, "selected": false, "text": "<p>If you have a number of tables that you want data from, then you are going to have to select from them, there is no other way around it.</p>\n\n<p>From your SQL, it seems that you could get restuls from tableC that contains keys in tableA and tableB, as you are UNION-ing the restuls of a simple select on tableC (of which there is no where clause). Where you after an exclusive set of keys that do NOT exist in any of the other tables? If so, then you will need to do what you did for the where clause for tableA in the selects for tableB and tableC. </p>\n\n<p>I hope that makes sense...</p>\n" }, { "answer_id": 185509, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 0, "selected": false, "text": "<p>Your query looks fine.</p>\n\n<p>Alternatively, you can use the query below and filter on the client side. It will be less stressful for the database server.</p>\n\n<pre><code>SELECT key, value, 2 AS priority\nFROM TableA\nUNION\nSELECT key, value, 1 AS priority\nFROM TableB\nUNION\nSELECT key, value, 0 AS priority\nFROM TableC\nORDER BY key, priority\n</code></pre>\n" }, { "answer_id": 185527, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Here's how I would do it in SQL Server. This solution should generate less logical IO than the original. If the tables were sufficiently huge, I would swap over to #temp tables to enable parallelism.</p>\n\n<pre><code>DECLARE @MyTable TABLE\n(\n Key int PRIMARY KEY,\n Value int\n)\n\n --Grab from TableC\nINSERT INTO @MyTable(Key, Value)\nSELECT Key, Value\nFROM TableC\n\n --Grab from TableB\nINSERT INTO @MyTable(Key, Value)\nSELECT Key, Value\nFROM TableB\nWHERE Key not in (SELECT Key FROM @MyTable)\n\n --Grab from TableA \nINSERT INTO @MyTable(Key, Value)\nSELECT Key, Value\nFROM TableA\nWHERE Key not in (SELECT Key FROM @MyTable)\n --Pop the result\nSELECT Key, Value\nFROM @MyTable\n</code></pre>\n\n<p>This technique mirrors how I would handle 3 lists in C#... by creating a dictionary.</p>\n" }, { "answer_id": 185556, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 1, "selected": false, "text": "<p>Here is an alternate SQL statement:-</p>\n\n<pre><code>SELECT\n ALL_KEYS.KEY,\n NVL( TABLEC.VALUE, NVL( TABLEB.VALUE, TABLEA.VALUE)) AS VALUE\nFROM\n (SELECT KEY AS KEY FROM TABLEA\n UNION\n SELECT KEY FROM TABLEB\n UNION\n SELECT KEY FROM TABLEC) ALL_KEYS,\n TABLEA,\n TABLEB,\n TABLEC\nWHERE\n ALL_KEYS.KEY = TABLEA.KEY(+) AND\n ALL_KEYS.KEY = TABLEB.KEY(+) AND\n ALL_KEYS.KEY = TABLEC.KEY(+);\n</code></pre>\n\n<p>NB. The NVL() is an Oracle function. If the first parameter is NULL, the second parameter is returned otherwise the first parameter is returned. You didn't say which database you were using but no doubt there are equivalents in everything.</p>\n" }, { "answer_id": 185783, "author": "JeremyDWill", "author_id": 12603, "author_profile": "https://Stackoverflow.com/users/12603", "pm_score": 3, "selected": true, "text": "<p>OK, using your concrete example as a basis, I came up with a solution different from the others posted (although I think I like your solution better). This was tested on MS SQL Server 2005 - changes may be needed for your SQL dialect.</p>\n\n<p>First, some DDL to set the stage:</p>\n\n<pre><code>CREATE TABLE [dbo].[StandardSchedule](\n [scheduledate] [datetime] NOT NULL,\n [shift] [varchar](25) NOT NULL,\n CONSTRAINT [PK_StandardSchedule] PRIMARY KEY CLUSTERED \n( [scheduledate] ASC ));\n\nCREATE TABLE [dbo].[HolidaySchedule](\n [holidaydate] [datetime] NOT NULL,\n [shift] [varchar](25) NOT NULL,\n CONSTRAINT [PK_HolidaySchedule] PRIMARY KEY CLUSTERED \n( [holidaydate] ASC ));\n\nCREATE TABLE [dbo].[ExceptionSchedule](\n [exceptiondate] [datetime] NOT NULL,\n [shift] [varchar](25) NOT NULL,\n CONSTRAINT [PK_ExceptionDate] PRIMARY KEY CLUSTERED \n( [exceptiondate] ASC ));\n\nINSERT INTO ExceptionSchedule VALUES ('2008.01.06', 'ExceptionShift1');\nINSERT INTO ExceptionSchedule VALUES ('2008.01.08', 'ExceptionShift2');\nINSERT INTO ExceptionSchedule VALUES ('2008.01.10', 'ExceptionShift3');\nINSERT INTO HolidaySchedule VALUES ('2008.01.01', 'HolidayShift1');\nINSERT INTO HolidaySchedule VALUES ('2008.01.06', 'HolidayShift2');\nINSERT INTO HolidaySchedule VALUES ('2008.01.09', 'HolidayShift3');\nINSERT INTO StandardSchedule VALUES ('2008.01.01', 'RegularShift1');\nINSERT INTO StandardSchedule VALUES ('2008.01.02', 'RegularShift2');\nINSERT INTO StandardSchedule VALUES ('2008.01.03', 'RegularShift3');\nINSERT INTO StandardSchedule VALUES ('2008.01.04', 'RegularShift4');\nINSERT INTO StandardSchedule VALUES ('2008.01.05', 'RegularShift5');\nINSERT INTO StandardSchedule VALUES ('2008.01.07', 'RegularShift6');\nINSERT INTO StandardSchedule VALUES ('2008.01.09', 'RegularShift7');\nINSERT INTO StandardSchedule VALUES ('2008.01.10', 'RegularShift8');\n</code></pre>\n\n<p>Using these tables/rows as a basis, this SELECT statement retrieves the desired data:</p>\n\n<pre><code>SELECT DISTINCT\n COALESCE(e2.exceptiondate, e.exceptiondate, holidaydate, scheduledate) AS ShiftDate,\n COALESCE(e2.shift, e.shift, h.shift, s.shift) AS Shift\nFROM standardschedule s\nFULL OUTER JOIN holidayschedule h ON s.scheduledate = h.holidaydate\nFULL OUTER JOIN exceptionschedule e ON h.holidaydate = e.exceptiondate\nFULL OUTER JOIN exceptionschedule e2 ON s.scheduledate = e2.exceptiondate\nORDER BY shiftdate\n</code></pre>\n" }, { "answer_id": 186820, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT isnull( c.key, isnull( b.key, a.key) ) , \n isnull( c.value, isnull( b.value, a.value ) ) \nFROM TableA a \nLEFT JOIN TableB b \nON a.key = b.key\nLEFT JOIN TableC c \nON b.key = c.key\n</code></pre>\n" }, { "answer_id": 186828, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 0, "selected": false, "text": "<p>Create a master table of all keys, then left join this master table to the three tables and investigate the <code>COALESCE</code> command. </p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6819/" ]
Assuming I have three tables : TableA (key, value) TableB (key, value) TableC (key, value) and I want to return a value for all keys. If the key exists in TableC return that value else if the key exists in B return that value else return the value from table A The best I have come up with so far is ``` SELECT key,Value FROM TableA WHERE key NOT IN (SELECT key FROM TableB) AND key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableB WHERE key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableC ``` But this seems pretty brute force. Anyone know a better way? Edit: Here is a more concrete example. Consider TableA as a standard work schedule where the key is a date and the value is the assigned shift. Table B is a statutory holiday calendar that overrides the standard work week. Table C is an exception schedule that is used to override the other two schedules when someone is asked to come in and work either an extra shift or a different shift.
OK, using your concrete example as a basis, I came up with a solution different from the others posted (although I think I like your solution better). This was tested on MS SQL Server 2005 - changes may be needed for your SQL dialect. First, some DDL to set the stage: ``` CREATE TABLE [dbo].[StandardSchedule]( [scheduledate] [datetime] NOT NULL, [shift] [varchar](25) NOT NULL, CONSTRAINT [PK_StandardSchedule] PRIMARY KEY CLUSTERED ( [scheduledate] ASC )); CREATE TABLE [dbo].[HolidaySchedule]( [holidaydate] [datetime] NOT NULL, [shift] [varchar](25) NOT NULL, CONSTRAINT [PK_HolidaySchedule] PRIMARY KEY CLUSTERED ( [holidaydate] ASC )); CREATE TABLE [dbo].[ExceptionSchedule]( [exceptiondate] [datetime] NOT NULL, [shift] [varchar](25) NOT NULL, CONSTRAINT [PK_ExceptionDate] PRIMARY KEY CLUSTERED ( [exceptiondate] ASC )); INSERT INTO ExceptionSchedule VALUES ('2008.01.06', 'ExceptionShift1'); INSERT INTO ExceptionSchedule VALUES ('2008.01.08', 'ExceptionShift2'); INSERT INTO ExceptionSchedule VALUES ('2008.01.10', 'ExceptionShift3'); INSERT INTO HolidaySchedule VALUES ('2008.01.01', 'HolidayShift1'); INSERT INTO HolidaySchedule VALUES ('2008.01.06', 'HolidayShift2'); INSERT INTO HolidaySchedule VALUES ('2008.01.09', 'HolidayShift3'); INSERT INTO StandardSchedule VALUES ('2008.01.01', 'RegularShift1'); INSERT INTO StandardSchedule VALUES ('2008.01.02', 'RegularShift2'); INSERT INTO StandardSchedule VALUES ('2008.01.03', 'RegularShift3'); INSERT INTO StandardSchedule VALUES ('2008.01.04', 'RegularShift4'); INSERT INTO StandardSchedule VALUES ('2008.01.05', 'RegularShift5'); INSERT INTO StandardSchedule VALUES ('2008.01.07', 'RegularShift6'); INSERT INTO StandardSchedule VALUES ('2008.01.09', 'RegularShift7'); INSERT INTO StandardSchedule VALUES ('2008.01.10', 'RegularShift8'); ``` Using these tables/rows as a basis, this SELECT statement retrieves the desired data: ``` SELECT DISTINCT COALESCE(e2.exceptiondate, e.exceptiondate, holidaydate, scheduledate) AS ShiftDate, COALESCE(e2.shift, e.shift, h.shift, s.shift) AS Shift FROM standardschedule s FULL OUTER JOIN holidayschedule h ON s.scheduledate = h.holidaydate FULL OUTER JOIN exceptionschedule e ON h.holidaydate = e.exceptiondate FULL OUTER JOIN exceptionschedule e2 ON s.scheduledate = e2.exceptiondate ORDER BY shiftdate ```
185,510
<p>Is it possible to do something like this?</p> <pre><code>var pattern = /some regex segment/ + /* comment here */ /another segment/; </code></pre> <p>Or do I have to use new <code>RegExp()</code> syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.</p>
[ { "answer_id": 185529, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 9, "selected": true, "text": "<p>Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object:</p>\n\n<pre><code>var segment_part = \"some bit of the regexp\";\nvar pattern = new RegExp(\"some regex segment\" + /*comment here */\n segment_part + /* that was defined just now */\n \"another segment\");\n</code></pre>\n\n<p>If you have two regular expression literals, you can in fact concatenate them using this technique:</p>\n\n<pre><code>var regex1 = /foo/g;\nvar regex2 = /bar/y;\nvar flags = (regex1.flags + regex2.flags).split(\"\").sort().join(\"\").replace(/(.)(?=.*\\1)/g, \"\");\nvar regex3 = new RegExp(expression_one.source + expression_two.source, flags);\n// regex3 is now /foobar/gy\n</code></pre>\n\n<p>It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions.</p>\n" }, { "answer_id": 185540, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 1, "selected": false, "text": "<p>No, the literal way is not supported. You'll have to use RegExp.</p>\n" }, { "answer_id": 752169, "author": "Praesagus", "author_id": 58013, "author_profile": "https://Stackoverflow.com/users/58013", "pm_score": -1, "selected": false, "text": "<p>I prefer to use <code>eval('your expression')</code> because it does not add the <code>/</code>on each end<code>/</code> that <code>='new RegExp'</code> does.</p>\n" }, { "answer_id": 2065588, "author": "Alex", "author_id": 250873, "author_profile": "https://Stackoverflow.com/users/250873", "pm_score": 5, "selected": false, "text": "<p>I don't quite agree with the \"eval\" option.</p>\n\n<pre><code>var xxx = /abcd/;\nvar yyy = /efgh/;\nvar zzz = new RegExp(eval(xxx)+eval(yyy));\n</code></pre>\n\n<p>will give \"//abcd//efgh//\" which is not the intended result.</p>\n\n<p>Using source like</p>\n\n<pre><code>var zzz = new RegExp(xxx.source+yyy.source);\n</code></pre>\n\n<p>will give \"/abcdefgh/\" and that is correct.</p>\n\n<p>Logicaly there is no need to EVALUATE, you know your EXPRESSION. You just need its SOURCE or how it is written not necessarely its value. As for the flags, you just need to use the optional argument of RegExp.</p>\n\n<p>In my situation, I do run in the issue of ^ and $ being used in several expression I am trying to concatenate together! Those expressions are grammar filters used accross the program. Now I wan't to use some of them together to handle the case of PREPOSITIONS.\nI may have to \"slice\" the sources to remove the starting and ending ^( and/or )$ :)\nCheers, Alex.</p>\n" }, { "answer_id": 11641612, "author": "Jonathan Wright", "author_id": 1550268, "author_profile": "https://Stackoverflow.com/users/1550268", "pm_score": 2, "selected": false, "text": "<p>It would be preferable to use the literal syntax as often as possible. It's shorter, more legible, and you do not need escape quotes or double-escape backlashes. From \"Javascript Patterns\", Stoyan Stefanov 2010. </p>\n\n<p>But using New may be the only way to concatenate.</p>\n\n<p>I would avoid eval. Its not safe. </p>\n" }, { "answer_id": 22543432, "author": "Japheth Salva", "author_id": 3157637, "author_profile": "https://Stackoverflow.com/users/3157637", "pm_score": 5, "selected": false, "text": "<p>Just randomly concatenating regular expressions <b>objects</b> can have some adverse side effects. Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source\" rel=\"noreferrer\">RegExp.source</a> instead:</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 r1 = /abc/g;\r\nvar r2 = /def/;\r\nvar r3 = new RegExp(r1.source + r2.source, \r\n (r1.global ? 'g' : '') \r\n + (r1.ignoreCase ? 'i' : '') + \r\n (r1.multiline ? 'm' : ''));\r\nconsole.log(r3);\r\nvar m = 'test that abcdef and abcdef has a match?'.match(r3);\r\nconsole.log(m);\r\n// m should contain 2 matches</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This will also give you the ability to retain the regular expression flags from a previous RegExp using the standard RegExp flags.</p>\n\n<p><a href=\"http://jsfiddle.net/LZf7H/514/\" rel=\"noreferrer\">jsFiddle</a></p>\n" }, { "answer_id": 23230231, "author": "ph7", "author_id": 2955894, "author_profile": "https://Stackoverflow.com/users/2955894", "pm_score": 2, "selected": false, "text": "<p>Use the constructor with 2 params and avoid the problem with trailing '/':</p>\n\n<pre><code>var re_final = new RegExp(\"\\\\\" + \".\", \"g\"); // constructor can have 2 params!\nconsole.log(\"...finally\".replace(re_final, \"!\") + \"\\n\" + re_final + \n \" works as expected...\"); // !!!finally works as expected\n\n // meanwhile\n\nre_final = new RegExp(\"\\\\\" + \".\" + \"g\"); // appends final '/'\nconsole.log(\"... finally\".replace(re_final, \"!\")); // ...finally\nconsole.log(re_final, \"does not work!\"); // does not work\n</code></pre>\n" }, { "answer_id": 27191354, "author": "Mikaël Mayer", "author_id": 1287856, "author_profile": "https://Stackoverflow.com/users/1287856", "pm_score": 3, "selected": false, "text": "<p><strong>Problem</strong> If the regexp contains back-matching groups like \\1.</p>\n\n<pre><code>var r = /(a|b)\\1/ // Matches aa, bb but nothing else.\nvar p = /(c|d)\\1/ // Matches cc, dd but nothing else.\n</code></pre>\n\n<p>Then just contatenating the sources will not work. Indeed, the combination of the two is:</p>\n\n<pre><code>var rp = /(a|b)\\1(c|d)\\1/\nrp.test(\"aadd\") // Returns false\n</code></pre>\n\n<p><strong>The solution:</strong>\n First we count the number of matching groups in the first regex, Then for each back-matching token in the second, we increment it by the number of matching groups.</p>\n\n<pre><code>function concatenate(r1, r2) {\n var count = function(r, str) {\n return str.match(r).length;\n }\n var numberGroups = /([^\\\\]|^)(?=\\((?!\\?:))/g; // Home-made regexp to count groups.\n var offset = count(numberGroups, r1.source); \n var escapedMatch = /[\\\\](?:(\\d+)|.)/g; // Home-made regexp for escaped literals, greedy on numbers.\n var r2newSource = r2.source.replace(escapedMatch, function(match, number) { return number?\"\\\\\"+(number-0+offset):match; });\n return new RegExp(r1.source+r2newSource,\n (r1.global ? 'g' : '') \n + (r1.ignoreCase ? 'i' : '')\n + (r1.multiline ? 'm' : ''));\n}\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>var rp = concatenate(r, p) // returns /(a|b)\\1(c|d)\\2/\nrp.test(\"aadd\") // Returns true\n</code></pre>\n" }, { "answer_id": 41870726, "author": "antoni", "author_id": 2012407, "author_profile": "https://Stackoverflow.com/users/2012407", "pm_score": 3, "selected": false, "text": "<p>Providing that:</p>\n\n<ul>\n<li>you know what you do in your regexp;</li>\n<li>you have many regex pieces to form a pattern and they will use same flag;</li>\n<li>you find it more readable to separate your small pattern chunks into an array;</li>\n<li>you also want to be able to comment each part for next dev or yourself later;</li>\n<li>you prefer to visually simplify your regex like <code>/this/g</code> rather than <code>new RegExp('this', 'g')</code>;</li>\n<li>it's ok for you to assemble the regex in an extra step rather than having it in one piece from the start;</li>\n</ul>\n\n<p>Then you may like to write this way:</p>\n\n<pre><code>var regexParts =\n [\n /\\b(\\d+|null)\\b/,// Some comments.\n /\\b(true|false)\\b/,\n /\\b(new|getElementsBy(?:Tag|Class|)Name|arguments|getElementById|if|else|do|null|return|case|default|function|typeof|undefined|instanceof|this|document|window|while|for|switch|in|break|continue|length|var|(?:clear|set)(?:Timeout|Interval))(?=\\W)/,\n /(\\$|jQuery)/,\n /many more patterns/\n ],\n regexString = regexParts.map(function(x){return x.source}).join('|'),\n regexPattern = new RegExp(regexString, 'g');\n</code></pre>\n\n<p>you can then do something like:</p>\n\n<pre><code>string.replace(regexPattern, function()\n{\n var m = arguments,\n Class = '';\n\n switch(true)\n {\n // Numbers and 'null'.\n case (Boolean)(m[1]):\n m = m[1];\n Class = 'number';\n break;\n\n // True or False.\n case (Boolean)(m[2]):\n m = m[2];\n Class = 'bool';\n break;\n\n // True or False.\n case (Boolean)(m[3]):\n m = m[3];\n Class = 'keyword';\n break;\n\n // $ or 'jQuery'.\n case (Boolean)(m[4]):\n m = m[4];\n Class = 'dollar';\n break;\n\n // More cases...\n }\n\n return '&lt;span class=\"' + Class + '\"&gt;' + m + '&lt;/span&gt;';\n})\n</code></pre>\n\n<p>In my particular case (a code-mirror-like editor), it is much easier to perform one big regex, rather than a lot of replaces like following as each time I replace with a html tag to wrap an expression, the next pattern will be harder to target without affecting the html tag itself (and without the good <em>lookbehind</em> that is unfortunately not supported in javascript):</p>\n\n<pre><code>.replace(/(\\b\\d+|null\\b)/g, '&lt;span class=\"number\"&gt;$1&lt;/span&gt;')\n.replace(/(\\btrue|false\\b)/g, '&lt;span class=\"bool\"&gt;$1&lt;/span&gt;')\n.replace(/\\b(new|getElementsBy(?:Tag|Class|)Name|arguments|getElementById|if|else|do|null|return|case|default|function|typeof|undefined|instanceof|this|document|window|while|for|switch|in|break|continue|var|(?:clear|set)(?:Timeout|Interval))(?=\\W)/g, '&lt;span class=\"keyword\"&gt;$1&lt;/span&gt;')\n.replace(/\\$/g, '&lt;span class=\"dollar\"&gt;$&lt;/span&gt;')\n.replace(/([\\[\\](){}.:;,+\\-?=])/g, '&lt;span class=\"ponctuation\"&gt;$1&lt;/span&gt;')\n</code></pre>\n" }, { "answer_id": 43010821, "author": "Neil Strain", "author_id": 4840721, "author_profile": "https://Stackoverflow.com/users/4840721", "pm_score": 2, "selected": false, "text": "<p>You could do something like:</p>\n\n<pre><code>function concatRegex(...segments) {\n return new RegExp(segments.join(''));\n}\n</code></pre>\n\n<p>The segments would be strings (rather than regex literals) passed in as separate arguments.</p>\n" }, { "answer_id": 57980801, "author": "Jeff Lowery", "author_id": 591529, "author_profile": "https://Stackoverflow.com/users/591529", "pm_score": 2, "selected": false, "text": "<p>You can concat regex source from both the literal and RegExp class:</p>\n\n<pre><code>var xxx = new RegExp(/abcd/);\nvar zzz = new RegExp(xxx.source + /efgh/.source);\n</code></pre>\n" }, { "answer_id": 58732513, "author": "Daniel Aragão", "author_id": 6287060, "author_profile": "https://Stackoverflow.com/users/6287060", "pm_score": 1, "selected": false, "text": "<p>the easier way to me would be concatenate the sources, ex.:</p>\n\n<pre><code>a = /\\d+/\nb = /\\w+/\nc = new RegExp(a.source + b.source)\n</code></pre>\n\n<p>the c value will result in:</p>\n\n<blockquote>\n <p>/\\d+\\w+/</p>\n</blockquote>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17964/" ]
Is it possible to do something like this? ``` var pattern = /some regex segment/ + /* comment here */ /another segment/; ``` Or do I have to use new `RegExp()` syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.
Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object: ``` var segment_part = "some bit of the regexp"; var pattern = new RegExp("some regex segment" + /*comment here */ segment_part + /* that was defined just now */ "another segment"); ``` If you have two regular expression literals, you can in fact concatenate them using this technique: ``` var regex1 = /foo/g; var regex2 = /bar/y; var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, ""); var regex3 = new RegExp(expression_one.source + expression_two.source, flags); // regex3 is now /foobar/gy ``` It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions.
185,520
<p>I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.</p>
[ { "answer_id": 185548, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 8, "selected": true, "text": "<p>A little hacky but should work:</p>\n\n<pre><code>SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime)))\n</code></pre>\n" }, { "answer_id": 185574, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 3, "selected": false, "text": "<p>In some locales like Hebrew, there are <a href=\"http://en.wikipedia.org/wiki/Hebrew_calendar#Leap_months\" rel=\"noreferrer\">leap months</a> dependant upon the year so to avoid errors in such locales you might consider the following solution:</p>\n\n<pre><code>SELECT DATENAME(month, STR(YEAR(GETDATE()), 4) + REPLACE(STR(@month, 2), ' ', '0') + '01') \n</code></pre>\n" }, { "answer_id": 188390, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 8, "selected": false, "text": "<p>I think this is the best way to get the <strong>month name</strong> when you have the <strong>month number</strong></p>\n\n<pre><code>Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>Select DateName( month , DateAdd( month , @MonthNumber , -1 ) )\n</code></pre>\n" }, { "answer_id": 626025, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You can use the inbuilt <code>CONVERT</code> function</p>\n\n<pre><code>select CONVERT(varchar(3), Date, 100) as Month from MyTable.\n</code></pre>\n\n<p>This will display first 3 characters of month (JAN,FEB etc..)</p>\n" }, { "answer_id": 3138377, "author": "Dharamvir", "author_id": 378697, "author_profile": "https://Stackoverflow.com/users/378697", "pm_score": 7, "selected": false, "text": "<pre><code>SELECT DATENAME(month, GETDATE()) AS 'Month Name'\n</code></pre>\n" }, { "answer_id": 4129448, "author": "Nori", "author_id": 255497, "author_profile": "https://Stackoverflow.com/users/255497", "pm_score": 2, "selected": false, "text": "<p>You can use the convert functin as below</p>\n\n<pre><code>CONVERT(VARCHAR(3), DATENAME(MM, GETDATE()), 100)\n</code></pre>\n" }, { "answer_id": 6712227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>in addition to original </p>\n\n<p><code>SELECT DATENAME(m, str(2) + '/1/2011')</code> </p>\n\n<p>you can do this </p>\n\n<p><code>SELECT DATENAME(m, str([column_name]) + '/1/2011')</code> </p>\n\n<p>this way you get names for all rows in a table. where [column_name] represents a integer column containing numeric value 1 through 12</p>\n\n<p>2 represents any integer, by contact string i created a date where i can extract the month. '/1/2011' can be any date </p>\n\n<p>if you want to do this with variable</p>\n\n<pre><code>DECLARE @integer int;\n\nSET @integer = 6;\n\nSELECT DATENAME(m, str(@integer) + '/1/2011')\n</code></pre>\n" }, { "answer_id": 6963137, "author": "Roadrunner327", "author_id": 345314, "author_profile": "https://Stackoverflow.com/users/345314", "pm_score": 1, "selected": false, "text": "<p>This one worked for me: </p>\n\n<pre><code>@MetricMonthNumber (some number)\n\nSELECT \n(DateName( month , DateAdd( month , @MetricMonthNumber - 1 , '1900-01-01' ) )) AS MetricMonthName\nFROM TableName\n</code></pre>\n\n<p>From a post above from @leoinfo and @Valentino Vranken. Just did a quick select and it works. </p>\n" }, { "answer_id": 7583543, "author": "Cedricve", "author_id": 969111, "author_profile": "https://Stackoverflow.com/users/969111", "pm_score": -1, "selected": false, "text": "<p>Use this statement</p>\n\n<pre><code>SELECT TO_CHAR(current_date,'dd MONTH yyyy') FROM dual\n</code></pre>\n\n<p>this will convert the month number to month full string</p>\n" }, { "answer_id": 8218454, "author": "Darryl Martin", "author_id": 1058597, "author_profile": "https://Stackoverflow.com/users/1058597", "pm_score": 6, "selected": false, "text": "<pre><code>SUBSTRING('JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ', (@intMonth * 4) - 3, 3)\n</code></pre>\n" }, { "answer_id": 11417240, "author": "shailesh", "author_id": 1515362, "author_profile": "https://Stackoverflow.com/users/1515362", "pm_score": -1, "selected": false, "text": "<pre><code>to_char(to_date(V_MONTH_NUM,'MM'),'MONTH')\n</code></pre>\n\n<p>where <code>V_MONTH_NUM</code> is the month number</p>\n\n<pre><code>SELECT to_char(to_date(V_MONTH_NUM,'MM'),'MONTH') from dual;\n</code></pre>\n" }, { "answer_id": 11574461, "author": "Wafa Abbas", "author_id": 1458809, "author_profile": "https://Stackoverflow.com/users/1458809", "pm_score": 1, "selected": false, "text": "<pre><code>Declare @MonthNumber int\nSET @MonthNumber=DatePart(Month,GETDATE())\nSelect DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )\n</code></pre>\n\n<p>Explaination:</p>\n\n<ol>\n<li>First Decalre Variable <code>MonthNumber</code></li>\n<li>Get Current Month for <code>DatePart</code> which Return Month Number</li>\n<li>Third Query Return Month Name</li>\n</ol>\n" }, { "answer_id": 12724184, "author": "Benazir", "author_id": 1719560, "author_profile": "https://Stackoverflow.com/users/1719560", "pm_score": 2, "selected": false, "text": "<p>i think this is enough to get month name when u have date.</p>\n\n<pre><code>SELECT DATENAME(month ,GETDATE())\n</code></pre>\n" }, { "answer_id": 15088927, "author": "unitario", "author_id": 308645, "author_profile": "https://Stackoverflow.com/users/308645", "pm_score": 3, "selected": false, "text": "<p>The following works for me:</p>\n\n<pre><code>CAST(GETDATE() AS CHAR(3))\n</code></pre>\n" }, { "answer_id": 16463285, "author": "gvila", "author_id": 2366489, "author_profile": "https://Stackoverflow.com/users/2366489", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))\n</code></pre>\n" }, { "answer_id": 18205547, "author": "Asif", "author_id": 1386158, "author_profile": "https://Stackoverflow.com/users/1386158", "pm_score": 5, "selected": false, "text": "<p><strong>Use the Best way</strong> </p>\n\n<pre><code>Select DateName( month , DateAdd( month , @MonthNumber , -1 ))\n</code></pre>\n" }, { "answer_id": 20579907, "author": "Piyush", "author_id": 3101531, "author_profile": "https://Stackoverflow.com/users/3101531", "pm_score": 2, "selected": false, "text": "<pre><code>select monthname(curdate());\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>select monthname('2013-12-12');\n</code></pre>\n" }, { "answer_id": 20583939, "author": "Kashif Aslam", "author_id": 3102280, "author_profile": "https://Stackoverflow.com/users/3102280", "pm_score": 2, "selected": false, "text": "<p>Working for me</p>\n\n<pre><code>SELECT MONTHNAME(&lt;fieldname&gt;) AS \"Month Name\" FROM &lt;tablename&gt; WHERE &lt;condition&gt;\n</code></pre>\n" }, { "answer_id": 24585186, "author": "Shyam Sa", "author_id": 3807478, "author_profile": "https://Stackoverflow.com/users/3807478", "pm_score": 2, "selected": false, "text": "<p>Sure this will work</p>\n\n<pre><code>select datename(M,GETDATE())\n</code></pre>\n" }, { "answer_id": 28671252, "author": "Ashish Singh", "author_id": 2017212, "author_profile": "https://Stackoverflow.com/users/2017212", "pm_score": 3, "selected": false, "text": "<p><strong>Use this statement to convert Month numeric value to Month name.</strong></p>\n\n<pre><code>SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE()))\n</code></pre>\n" }, { "answer_id": 30635960, "author": "user4972370", "author_id": 4972370, "author_profile": "https://Stackoverflow.com/users/4972370", "pm_score": 0, "selected": false, "text": "<p>Use this statement for getting month name:</p>\n\n<pre><code>DECLARE @date datetime\nSET @date='2015/1/4 00:00:00'\n\nSELECT CAST(DATENAME(month,@date ) AS CHAR(3))AS 'Month Name'\n</code></pre>\n\n<p>This will give you short month name. Like this: Jan, Feb, Mar, etc.</p>\n" }, { "answer_id": 31031373, "author": "lancepants28", "author_id": 2414620, "author_profile": "https://Stackoverflow.com/users/2414620", "pm_score": 0, "selected": false, "text": "<p>Here is my solution using some information from others to solve a problem.</p>\n\n<pre><code>datename(month,dateadd(month,datepart(month,Help_HelpMain.Ticket_Closed_Date),-1)) as monthname\n</code></pre>\n" }, { "answer_id": 32854250, "author": "Geoffrey Fuller", "author_id": 5390636, "author_profile": "https://Stackoverflow.com/users/5390636", "pm_score": 2, "selected": false, "text": "<p>Just subtract the current month from today's date, then add back your month number. Then use the datename function to give the full name all in 1 line.</p>\n\n<pre><code>print datename(month,dateadd(month,-month(getdate()) + 9,getdate()))\n</code></pre>\n" }, { "answer_id": 36925160, "author": "Isaiah", "author_id": 5947614, "author_profile": "https://Stackoverflow.com/users/5947614", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT DateName(M, DateAdd(M, @MONTHNUMBER, -1))\n</code></pre>\n" }, { "answer_id": 41193009, "author": "Charlie Brown", "author_id": 7308559, "author_profile": "https://Stackoverflow.com/users/7308559", "pm_score": 0, "selected": false, "text": "<p>There is no system defined function in SQL server. But you can create your own user-defined function- a scalar function. You would find scalar functions in the Object Explorer for your database: Programmability->Functions->Scalar-valued Functions. Below, I use a table variable to bring it all together.</p>\n\n<pre><code>--Create the user-defined function\nCREATE FUNCTION getmonth (@num int)\nRETURNS varchar(9) --since 'September' is the longest string, length 9\nAS\nBEGIN\n\nDECLARE @intMonth Table (num int PRIMARY KEY IDENTITY(1,1), month varchar(9))\n\nINSERT INTO @intMonth VALUES ('January'), ('February'), ('March'), ('April'), ('May')\n , ('June'), ('July'), ('August') ,('September'), ('October')\n , ('November'), ('December')\n\nRETURN (SELECT I.month\n FROM @intMonth I\n WHERE I.num = @num)\nEND\nGO\n\n--Use the function for various months\nSELECT dbo.getmonth(4) AS [Month]\nSELECT dbo.getmonth(5) AS [Month]\nSELECT dbo.getmonth(6) AS [Month]\n</code></pre>\n" }, { "answer_id": 41875950, "author": "Saeed ur Rehman", "author_id": 4856329, "author_profile": "https://Stackoverflow.com/users/4856329", "pm_score": 4, "selected": false, "text": "<p>It is very simple.</p>\n\n<pre><code>select DATENAME(month, getdate())\n</code></pre>\n\n<p>output : January</p>\n" }, { "answer_id": 42626048, "author": "M2012", "author_id": 1522823, "author_profile": "https://Stackoverflow.com/users/1522823", "pm_score": 2, "selected": false, "text": "<p>To convert month number to month name, try the below</p>\n\n<pre><code>declare @month smallint = 1\nselect DateName(mm,DATEADD(mm,@month - 1,0))\n</code></pre>\n" }, { "answer_id": 46357846, "author": "Janaka Pushpakumara", "author_id": 4465118, "author_profile": "https://Stackoverflow.com/users/4465118", "pm_score": 1, "selected": false, "text": "<p>you can get the date like this. \neg:- <strong>Users</strong> table</p>\n\n<pre><code>id name created_at\n1 abc 2017-09-16\n2 xyz 2017-06-10\n</code></pre>\n\n<p>you can get the monthname like this</p>\n\n<pre><code>select year(created_at), monthname(created_at) from users;\n</code></pre>\n\n<p>output</p>\n\n<pre><code>+-----------+-------------------------------+\n| year(created_at) | monthname(created_at) |\n+-----------+-------------------------------+\n| 2017 | september |\n| 2017 | june |\n</code></pre>\n" }, { "answer_id": 49454712, "author": "Paul", "author_id": 2109512, "author_profile": "https://Stackoverflow.com/users/2109512", "pm_score": 4, "selected": false, "text": "<p>Starting with SQL Server 2012, you can use <strong><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql\" rel=\"noreferrer\">FORMAT</a></strong> and <strong><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/datefromparts-transact-sql\" rel=\"noreferrer\">DATEFROMPARTS</a></strong> to solve this problem. (If you want month names from other cultures, change: <code>en-US</code>)</p>\n\n<pre><code>select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')\n</code></pre>\n\n<p>If you want a three-letter month:</p>\n\n<pre><code>select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMM', 'en-US')\n</code></pre>\n\n<p>If you really want to, you can create a function for this:</p>\n\n<pre><code>CREATE FUNCTION fn_month_num_to_name\n(\n @month_num tinyint\n)\nRETURNS varchar(20)\nAS\nBEGIN\n RETURN FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')\nEND\n</code></pre>\n" }, { "answer_id": 53341050, "author": "Seth Winters", "author_id": 4149921, "author_profile": "https://Stackoverflow.com/users/4149921", "pm_score": 0, "selected": false, "text": "<p>You can create a function like this to generate the Month and do\nSELECT dbo.fn_GetMonthFromDate(date_column) as Month FROM table_name\n<pre><code>\n/****** Object: UserDefinedFunction [dbo].[fn_GetMonthFromDate] Script Date: 11/16/2018 10:26:33 AM ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE FUNCTION [dbo].[fn_GetMonthFromDate] \n(@date datetime)\nRETURNS varchar(50)\nAS\nBEGIN\n DECLARE @monthPart int</p>\n\nSET @monthPart = MONTH(@date)\n\nIF @monthPart = 1\n BEGIN\n RETURN 'January'\n END\nELSE IF @monthPart = 2\n BEGIN\n RETURN 'February'\n END\nELSE IF @monthPart = 3\n BEGIN\n RETURN 'March'\n END\nELSE IF @monthPart = 4\n BEGIN\n RETURN 'April'\n END\nELSE IF @monthPart = 5\n BEGIN\n RETURN 'May'\n END\nELSE IF @monthPart = 6\n BEGIN\n RETURN 'June'\n END\nELSE IF @monthPart = 7\n BEGIN\n RETURN 'July'\n END\nELSE IF @monthPart = 8\n BEGIN\n RETURN 'August'\n END\nELSE IF @monthPart = 9\n BEGIN\n RETURN 'September'\n END\nELSE IF @monthPart = 10\n BEGIN\n RETURN 'October'\n END\nELSE IF @monthPart = 11\n BEGIN\n RETURN 'November'\n END\nELSE IF @monthPart = 12\n BEGIN\n RETURN 'December'\n END\nRETURN NULL END\n</code></pre>\n" }, { "answer_id": 56238864, "author": "Armand Mamitiana Rakotoarisoa", "author_id": 10403715, "author_profile": "https://Stackoverflow.com/users/10403715", "pm_score": -1, "selected": false, "text": "<p>The easiest way is by calling the function <code>MONTHNAME(your_date)</code>. <strong>your_date</strong> can be a static value or the value from one of your table fields.</p>\n" }, { "answer_id": 60226167, "author": "Atanu Samanta", "author_id": 9779410, "author_profile": "https://Stackoverflow.com/users/9779410", "pm_score": -1, "selected": false, "text": "<p>Try this: <code>SELECT MONTHNAME(concat('1970-',[Month int val],'-01'))</code></p>\n<p>For example- <code>SELECT MONTHNAME(concat('1970-',4,'-01'))</code></p>\n<p>The answer is - April</p>\n" }, { "answer_id": 70213009, "author": "CodeByAk", "author_id": 8195540, "author_profile": "https://Stackoverflow.com/users/8195540", "pm_score": -1, "selected": false, "text": "<p>If anyone is trying to get the same kind of thing in MySQL. please check below query.</p>\n<pre><code> SELECT MONTH(STR_TO_DATE('November', '%M'))\n</code></pre>\n<p>By this I got required result.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.
A little hacky but should work: ``` SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime))) ```
185,521
<p>I run into similar codes like this all the time in aspx pages:</p> <pre><code>&lt;asp:CheckBox Runat="server" ID="myid" Checked='&lt;%# DataBinder.Eval(Container.DataItem, "column").Equals(1) %&gt;'&gt; </code></pre> <p>I was wondering what other objects I have access to inside of that &lt;%# %> tag. How come DataBinder.Eval() and Container.DataItem are not visible anywhere inside .CS code?</p>
[ { "answer_id": 185570, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 1, "selected": false, "text": "<p>I believe you have access to anything within scope of the page class, though the results of the expression are converted to a string, so you can't embed conditional expressions the way you can with \"&lt;%\" expression holes.</p>\n\n<p><a href=\"http://www.odetocode.com/Articles/278.aspx\" rel=\"nofollow noreferrer\">Here</a> is a nice blog post which dives under the covers of the generated ASPX class.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 185604, "author": "Brendan Kowitz", "author_id": 25767, "author_profile": "https://Stackoverflow.com/users/25767", "pm_score": 1, "selected": false, "text": "<p>&lt;%# is specific to inline ASPX databinding like the link ckramer posted suggests.</p>\n\n<blockquote>\n <p>How come DataBinder.Eval() and Container.DataItem are not visible anywhere inside .CS code?</p>\n</blockquote>\n\n<p>To access the binding item in codebehind you would need to set up an <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datagrid.itemdatabound.aspx\" rel=\"nofollow noreferrer\" title=\"ItemDataBound\">ItemDataBound</a> event.</p>\n" }, { "answer_id": 185612, "author": "Fung", "author_id": 8280, "author_profile": "https://Stackoverflow.com/users/8280", "pm_score": 4, "selected": true, "text": "<p>Within &lt;%# %> tags you have access to </p>\n\n<ol>\n<li>Anything that is visible in your code-behind class (including protected methods and properties).</li>\n<li>Anything declared on the aspx page using &lt;@import @>.</li>\n<li>Anything passed in as the event arguments when the ItemDataBound event is fired (e.g. RepeaterItemEventArgs, DataListItemEventArgs, etc).</li>\n</ol>\n\n<p><em>Container</em> is actually a wrapper for RepeaterItemEventArgs.Item, DataListItemEventArgs.Item, etc. So you can actually access it in code behind within your ItemDataBound events as <em>e.Item</em> (e normally being the event arguments parameter name).</p>\n\n<p><em>DataBinder</em> is also accessible in code behind by using <em>System.Web.UI.DataBinder</em>.</p>\n\n<p>On a side note, casting the Container.DataItem is preferred over using Eval. Eval uses reflection so there's an overhead there. In VB.NET it would be something like</p>\n\n<pre><code>&lt;%#DirectCast(Container.DataItem, DataRow)(\"some_column\")%&gt;\n</code></pre>\n\n<p>Or C#</p>\n\n<pre><code>&lt;%#((DataRow)Container.DataItem)[\"some_column\"].ToString()%&gt;\n</code></pre>\n" }, { "answer_id": 185642, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 1, "selected": false, "text": "<p>ASP.NET generates a subclass of <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.aspx\" rel=\"nofollow noreferrer\">TemplateControl</a> for each occurence of a template. Databinding statements are expressions used in a method inside that class. Thus, you can call any public/protected instance method on TemplateControl. See <a href=\"https://web.archive.org/web/20210510015225/https://aspnet.4guysfromrolla.com/articles/092706-1.aspx\" rel=\"nofollow noreferrer\">any example</a> that uses XPath, as those will use the XPath and XPathSelect methods; Eval, XPath and XPathSelect are all instance methods on TemplateControl.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.databinder.aspx\" rel=\"nofollow noreferrer\">DataBinder</a> is actually a separate class, and Eval is a public static method on it; it's in System.Web.UI. DataBinder.Eval and plain Eval are not directly related though they do very similar things visibly.</p>\n\n<p>I believe that \"Container\" is actually a local variable or parameter where databinding statements are compiled. I can't remember its type at the moment.</p>\n" }, { "answer_id": 1287615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Great example </p>\n\n<pre><code>&lt;%#((System.Data.DataRow)Container.DataItem)[\"ColumnName\"].ToString()%&gt;\n</code></pre>\n" }, { "answer_id": 1287673, "author": "Robert Koritnik", "author_id": 75642, "author_profile": "https://Stackoverflow.com/users/75642", "pm_score": 1, "selected": false, "text": "<p>using <code>&lt;%# %&gt;</code> actually means that code inside this block will execute when <code>page.DataBind()</code> method is being executed. Thus you can access anything at that point accessible as protected/public to that particular page/control.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ]
I run into similar codes like this all the time in aspx pages: ``` <asp:CheckBox Runat="server" ID="myid" Checked='<%# DataBinder.Eval(Container.DataItem, "column").Equals(1) %>'> ``` I was wondering what other objects I have access to inside of that <%# %> tag. How come DataBinder.Eval() and Container.DataItem are not visible anywhere inside .CS code?
Within <%# %> tags you have access to 1. Anything that is visible in your code-behind class (including protected methods and properties). 2. Anything declared on the aspx page using <@import @>. 3. Anything passed in as the event arguments when the ItemDataBound event is fired (e.g. RepeaterItemEventArgs, DataListItemEventArgs, etc). *Container* is actually a wrapper for RepeaterItemEventArgs.Item, DataListItemEventArgs.Item, etc. So you can actually access it in code behind within your ItemDataBound events as *e.Item* (e normally being the event arguments parameter name). *DataBinder* is also accessible in code behind by using *System.Web.UI.DataBinder*. On a side note, casting the Container.DataItem is preferred over using Eval. Eval uses reflection so there's an overhead there. In VB.NET it would be something like ``` <%#DirectCast(Container.DataItem, DataRow)("some_column")%> ``` Or C# ``` <%#((DataRow)Container.DataItem)["some_column"].ToString()%> ```
185,522
<p>When working with CSS inside of XML such as</p> <pre><code>&lt;span class="IwuvAS3"&gt;&lt;/span&gt; </code></pre> <p>when parsed in flash, if I don't use CDATA like the following:</p> <pre><code>&lt;![CDATA[&lt;span class="IwuvAS3"&gt;&lt;/span&gt;]]&gt; </code></pre> <p>then the parsed data drops down a line for every "&lt;" character it sees.</p> <p>When parsing the data into a single-line text field, nothing was shown because it was actually down a line. Soon as I wrap it inside of <code>CDATA</code> it works great. I have played with <code>prettyIndent</code>, and as I understand <code>ignoreWhite</code> is true by default.</p> <p>Is there a way to parse the data without the use of <code>CDATA</code> and keep the implied line breaks out?</p> <p><strong>EDIT 1 (10/10/08)</strong>: Thank you, but I am actually looking for a Function or Method. Escaping each is much more cumbersome than using CDATA. The only reason I don't want to use CDATA is that I was taught to stay clear of it. If ActionScript has a method associated to E4X XML handling that will remove the requirement to wrap my XML in CDATA, I would love to know about it.</p> <p><strong>EDIT 1 (10/15/08)</strong>: Thanks Philippe! I never would have thought that HTML formatting in Flash is treated as whitespace. The answer was</p> <pre><code>textField.condenseWhite = true; </code></pre> <p>&lt;3AS3</p>
[ { "answer_id": 185537, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>You could escape the \"&lt;\" characters (and &amp;, \", >, ', among others) as entities instead.</p>\n" }, { "answer_id": 196182, "author": "Philippe", "author_id": 27219, "author_profile": "https://Stackoverflow.com/users/27219", "pm_score": 3, "selected": true, "text": "<p>Set the TextField's <strong>condenseWhite</strong> property to true - so only &lt; br/> tags will generate linebreaks.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20628/" ]
When working with CSS inside of XML such as ``` <span class="IwuvAS3"></span> ``` when parsed in flash, if I don't use CDATA like the following: ``` <![CDATA[<span class="IwuvAS3"></span>]]> ``` then the parsed data drops down a line for every "<" character it sees. When parsing the data into a single-line text field, nothing was shown because it was actually down a line. Soon as I wrap it inside of `CDATA` it works great. I have played with `prettyIndent`, and as I understand `ignoreWhite` is true by default. Is there a way to parse the data without the use of `CDATA` and keep the implied line breaks out? **EDIT 1 (10/10/08)**: Thank you, but I am actually looking for a Function or Method. Escaping each is much more cumbersome than using CDATA. The only reason I don't want to use CDATA is that I was taught to stay clear of it. If ActionScript has a method associated to E4X XML handling that will remove the requirement to wrap my XML in CDATA, I would love to know about it. **EDIT 1 (10/15/08)**: Thanks Philippe! I never would have thought that HTML formatting in Flash is treated as whitespace. The answer was ``` textField.condenseWhite = true; ``` <3AS3
Set the TextField's **condenseWhite** property to true - so only < br/> tags will generate linebreaks.
185,524
<p>I'm trying to build the example described at <a href="http://support.microsoft.com/kb/178749/EN-US/" rel="nofollow noreferrer">http://support.microsoft.com/kb/178749/EN-US/</a> in order to build an application that programatically accesses Excel using Automation. I have Visual C++ 2005/Visual Studio 2005. Some of the instructions don't exactly match up (classwizard, mostly), but the general idea seems to be the same.</p> <p>Problems: I don't end up with an excel.h file after using the "new class" to create my wrapper classes. So I can' t #include that file as it specifies in step 13. I do get a excel.tlh and an excel.tli in my windebug directory, but that doesn't seem to work. I tried all orders for </p> <pre><code>#include "stdafx.h" #include "debug/excel.tli" #include "debug/excel.tlh" </code></pre> <p>... including leaving one of those files out of the compile, but I still end up with a ton of compile errors.</p> <p>Here's the top 5 compile errors with the above #includes:</p> <pre><code>1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(16) : error C3861: 'get_Parent': identifier not found </code></pre> <p>Here's the top 5 errors with these includes:</p> <pre><code>#include "stdafx.h" #include "debug/excel.tlh" 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(550) : error C3121: cannot change GUID for class 'IFilter' 1&gt; c:\program files\microsoft sdks\windows\v6.0\include\comdef.h(483) : see declaration of 'IFilter' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2786: 'BOOL (__stdcall *)(HDC,int,int,int,int)' : invalid operand for __uuidof 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2923: '_com_IIID' : 'Rectangle' is not a valid template type argument for parameter '_Interface' 1&gt; c:\program files\microsoft sdks\windows\v6.0\include\wingdi.h(3667) : see declaration of 'Rectangle' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C3203: '_com_IIID' : unspecialized class template can't be used as a template argument for template parameter '_IIID', expected a real type </code></pre> <p>Here's the top 5 errors with these includes:</p> <pre><code>#include "stdafx.h" #include "debug/excel.tli" 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 186009, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 1, "selected": false, "text": "<p>I'm not familiar with the ClassWizard wrapper generator, but it looks like it may have #imported the Excel COM type library without a namespace, and you're getting conflicts with the SDK header files. Check the <code>.tlh</code> file and ensure there's a namespace around the definitions. If not, I'd look at importing it the more manual (but safer) way using #import.</p>\n\n<p>Check out using #import directly; it will generate the <code>.tlh</code> and <code>.tli</code> files in the build directory, which you can then use directory with <code>CComPtr&lt;&gt;</code> and the like. I've found that to be much more straightforward than using CW wrapper classes. That's my advice anyway.</p>\n" }, { "answer_id": 186029, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 0, "selected": false, "text": "<p>I don't know if this helps but generally you <code>#import</code> the type library but you do NOT <code>#include</code> the .tli and .tlh files (the <code>#import</code> implicitly does this).</p>\n\n<p>Also, remember there are two ways of calling a COM server in MFC.</p>\n\n<ol>\n<li><p>Use <code>#import</code> which basically creates smart ATL pointers to create COM objects and call methods.</p></li>\n<li><p>Use the class wizard to create an <code>IDispatch</code> style class wrapper to create COM object and call the methods.</p></li>\n</ol>\n" }, { "answer_id": 193332, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 0, "selected": false, "text": "<p>At Nick's request, I'm posting the build error output and following that the <code>vbe6ext.tlh</code> file, up to the error:</p>\n\n<pre><code>********************* Build output:\n\n1&gt;------ Build started: Project: testole, Configuration: Debug Win32 ------\n1&gt;Compiling...\n1&gt;testoleDlg.cpp\n1&gt;c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\debug\\vbe6ext.tlh(463) : error C2061: syntax error : identifier '__missing_type__'\n1&gt;c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(164) : error C2065: '_Application' : undeclared identifier\n1&gt;c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(164) : error C2146: syntax error : missing ';' before identifier 'app'\n1&gt;c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(164) : error C2065: 'app' : undeclared identifier\n1&gt;c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(166) : error C2228: left of '.CreateDispatch' must have class/struct/union\n1&gt; type is ''unknown-type''\n1&gt;c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\testoledlg.cpp(172) : error C2228: left of '.SetVisible' must have class/struct/union\n1&gt; type is ''unknown-type''\n1&gt;Build log was saved at \"file://c:\\Users\\sniles\\Documents\\Visual Studio 2005\\Source10\\testole\\testole\\Debug\\BuildLog.htm\"\n1&gt;testole - 6 error(s), 0 warning(s)\n========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========\n\n******************* vbe6ext.tlh\n// Created by Microsoft (R) C/C++ Compiler Version 14.00.50727.42 (e112bc16).\n//\n// c:\\users\\sniles\\documents\\visual studio 2005\\source10\\testole\\testole\\debug\\vbe6ext.tlh\n//\n// C++ source equivalent of Win32 type library C:\\Program Files\\Common Files\\Microsoft Shared\\VBA\\VBA6\\VBE6EXT.OLB\n// compiler-generated file created 10/10/08 at 14:03:16 - DO NOT EDIT!\n\n#pragma once\n#pragma pack(push, 8)\n\n#include &lt;comdef.h&gt;\n\nnamespace VBIDE {\n\n//\n// Forward references and typedefs\n//\n\nstruct __declspec(uuid(\"0002e157-0000-0000-c000-000000000046\"))\n/* LIBID */ __VBIDE;\nstruct __declspec(uuid(\"0002e158-0000-0000-c000-000000000046\"))\n/* dual interface */ Application;\nenum vbextFileTypes;\nstruct __declspec(uuid(\"0002e166-0000-0000-c000-000000000046\"))\n/* dual interface */ testVBE;\nenum vbext_WindowType;\nenum vbext_WindowState;\nstruct __declspec(uuid(\"0002e16b-0000-0000-c000-000000000046\"))\n/* dual interface */ Window;\nstruct __declspec(uuid(\"0002e16a-0000-0000-c000-000000000046\"))\n/* dual interface */ _Windows_old;\nstruct __declspec(uuid(\"f57b7ed0-d8ab-11d1-85df-00c04f98f42c\"))\n/* dual interface */ _Windows;\nstruct /* coclass */ Windows;\nstruct __declspec(uuid(\"0002e16c-0000-0000-c000-000000000046\"))\n/* dual interface */ _LinkedWindows;\nstruct /* coclass */ LinkedWindows;\nstruct __declspec(uuid(\"0002e167-0000-0000-c000-000000000046\"))\n/* dual interface */ Events;\nstruct __declspec(uuid(\"0002e113-0000-0000-c000-000000000046\"))\n/* interface */ _VBProjectsEvents;\nstruct __declspec(uuid(\"0002e103-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispVBProjectsEvents;\nstruct __declspec(uuid(\"0002e115-0000-0000-c000-000000000046\"))\n/* interface */ _VBComponentsEvents;\nstruct __declspec(uuid(\"0002e116-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispVBComponentsEvents;\nstruct __declspec(uuid(\"0002e11a-0000-0000-c000-000000000046\"))\n/* interface */ _ReferencesEvents;\nstruct __declspec(uuid(\"0002e118-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispReferencesEvents;\nstruct /* coclass */ ReferencesEvents;\nstruct __declspec(uuid(\"0002e130-0000-0000-c000-000000000046\"))\n/* interface */ _CommandBarControlEvents;\nstruct __declspec(uuid(\"0002e131-0000-0000-c000-000000000046\"))\n/* dispinterface */ _dispCommandBarControlEvents;\nstruct /* coclass */ CommandBarEvents;\nstruct __declspec(uuid(\"0002e159-0000-0000-c000-000000000046\"))\n/* dual interface */ _ProjectTemplate;\nstruct /* coclass */ ProjectTemplate;\nenum vbext_ProjectType;\nenum vbext_ProjectProtection;\nenum vbext_VBAMode;\nstruct __declspec(uuid(\"0002e160-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBProject_Old;\nstruct __declspec(uuid(\"eee00915-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBProject;\nstruct /* coclass */ VBProject;\nstruct __declspec(uuid(\"0002e165-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBProjects_Old;\nstruct __declspec(uuid(\"eee00919-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBProjects;\nstruct /* coclass */ VBProjects;\nstruct __declspec(uuid(\"be39f3d4-1b13-11d0-887f-00a0c90f2744\"))\n/* dual interface */ SelectedComponents;\nenum vbext_ComponentType;\nstruct __declspec(uuid(\"0002e161-0000-0000-c000-000000000046\"))\n/* dual interface */ _Components;\nstruct /* coclass */ Components;\nstruct __declspec(uuid(\"0002e162-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBComponents_Old;\nstruct __declspec(uuid(\"eee0091c-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBComponents;\nstruct /* coclass */ VBComponents;\nstruct __declspec(uuid(\"0002e163-0000-0000-c000-000000000046\"))\n/* dual interface */ _Component;\nstruct /* coclass */ Component;\nstruct __declspec(uuid(\"0002e164-0000-0000-c000-000000000046\"))\n/* dual interface */ _VBComponent_Old;\nstruct __declspec(uuid(\"eee00921-e393-11d1-bb03-00c04fb6c4a6\"))\n/* dual interface */ _VBComponent;\nstruct /* coclass */ VBComponent;\nstruct __declspec(uuid(\"0002e18c-0000-0000-c000-000000000046\"))\n/* dual interface */ Property;\nstruct __declspec(uuid(\"0002e188-0000-0000-c000-000000000046\"))\n/* dual interface */ _Properties;\nstruct /* coclass */ Properties;\nstruct __declspec(uuid(\"da936b62-ac8b-11d1-b6e5-00a0c90f2744\"))\n/* dual interface */ _AddIns;\nstruct /* coclass */ Addins;\nstruct __declspec(uuid(\"da936b64-ac8b-11d1-b6e5-00a0c90f2744\"))\n/* dual interface */ AddIn;\nenum vbext_ProcKind;\nstruct __declspec(uuid(\"0002e16e-0000-0000-c000-000000000046\"))\n/* dual interface */ _CodeModule;\nstruct /* coclass */ CodeModule;\nstruct __declspec(uuid(\"0002e172-0000-0000-c000-000000000046\"))\n/* dual interface */ _CodePanes;\nstruct /* coclass */ CodePanes;\nenum vbext_CodePaneview;\nstruct __declspec(uuid(\"0002e176-0000-0000-c000-000000000046\"))\n/* dual interface */ _CodePane;\nstruct /* coclass */ CodePane;\nstruct __declspec(uuid(\"0002e17a-0000-0000-c000-000000000046\"))\n/* dual interface */ _References;\nenum vbext_RefKind;\nstruct __declspec(uuid(\"0002e17e-0000-0000-c000-000000000046\"))\n/* dual interface */ ignorethis;\nstruct __declspec(uuid(\"cdde3804-2064-11cf-867f-00aa005ff34a\"))\n/* dispinterface */ _dispReferences_Events;\nstruct /* coclass */ References;\n\n//\n// Smart pointer typedef declarations\n//\n\n_COM_SMARTPTR_TYPEDEF(Application, __uuidof(Application));\n_COM_SMARTPTR_TYPEDEF(_VBProjectsEvents, __uuidof(_VBProjectsEvents));\n_COM_SMARTPTR_TYPEDEF(_dispVBProjectsEvents, __uuidof(_dispVBProjectsEvents));\n_COM_SMARTPTR_TYPEDEF(_VBComponentsEvents, __uuidof(_VBComponentsEvents));\n_COM_SMARTPTR_TYPEDEF(_dispVBComponentsEvents, __uuidof(_dispVBComponentsEvents));\n_COM_SMARTPTR_TYPEDEF(_ReferencesEvents, __uuidof(_ReferencesEvents));\n_COM_SMARTPTR_TYPEDEF(_dispReferencesEvents, __uuidof(_dispReferencesEvents));\n_COM_SMARTPTR_TYPEDEF(_CommandBarControlEvents, __uuidof(_CommandBarControlEvents));\n_COM_SMARTPTR_TYPEDEF(_dispCommandBarControlEvents, __uuidof(_dispCommandBarControlEvents));\n_COM_SMARTPTR_TYPEDEF(_ProjectTemplate, __uuidof(_ProjectTemplate));\n_COM_SMARTPTR_TYPEDEF(Events, __uuidof(Events));\n_COM_SMARTPTR_TYPEDEF(_Component, __uuidof(_Component));\n_COM_SMARTPTR_TYPEDEF(SelectedComponents, __uuidof(SelectedComponents));\n_COM_SMARTPTR_TYPEDEF(_dispReferences_Events, __uuidof(_dispReferences_Events));\n_COM_SMARTPTR_TYPEDEF(testVBE, __uuidof(testVBE));\n_COM_SMARTPTR_TYPEDEF(Window, __uuidof(Window));\n_COM_SMARTPTR_TYPEDEF(_Windows_old, __uuidof(_Windows_old));\n_COM_SMARTPTR_TYPEDEF(_LinkedWindows, __uuidof(_LinkedWindows));\n_COM_SMARTPTR_TYPEDEF(_VBProject_Old, __uuidof(_VBProject_Old));\n_COM_SMARTPTR_TYPEDEF(_VBProject, __uuidof(_VBProject));\n_COM_SMARTPTR_TYPEDEF(_VBProjects_Old, __uuidof(_VBProjects_Old));\n_COM_SMARTPTR_TYPEDEF(_VBProjects, __uuidof(_VBProjects));\n_COM_SMARTPTR_TYPEDEF(_Components, __uuidof(_Components));\n_COM_SMARTPTR_TYPEDEF(_VBComponents_Old, __uuidof(_VBComponents_Old));\n_COM_SMARTPTR_TYPEDEF(_VBComponents, __uuidof(_VBComponents));\n_COM_SMARTPTR_TYPEDEF(_VBComponent_Old, __uuidof(_VBComponent_Old));\n_COM_SMARTPTR_TYPEDEF(_VBComponent, __uuidof(_VBComponent));\n_COM_SMARTPTR_TYPEDEF(Property, __uuidof(Property));\n_COM_SMARTPTR_TYPEDEF(_Properties, __uuidof(_Properties));\n_COM_SMARTPTR_TYPEDEF(AddIn, __uuidof(AddIn));\n_COM_SMARTPTR_TYPEDEF(_Windows, __uuidof(_Windows));\n_COM_SMARTPTR_TYPEDEF(_AddIns, __uuidof(_AddIns));\n_COM_SMARTPTR_TYPEDEF(_CodeModule, __uuidof(_CodeModule));\n_COM_SMARTPTR_TYPEDEF(_CodePanes, __uuidof(_CodePanes));\n_COM_SMARTPTR_TYPEDEF(_CodePane, __uuidof(_CodePane));\n_COM_SMARTPTR_TYPEDEF(ignorethis, __uuidof(ignorethis));\n_COM_SMARTPTR_TYPEDEF(_References, __uuidof(_References));\n\n//\n// Type library items\n//\n\nstruct __declspec(uuid(\"0002e158-0000-0000-c000-000000000046\"))\nApplication : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_Version (\n /*[out,retval]*/ BSTR * lpbstrReturn ) = 0;\n};\n\nenum __declspec(uuid(\"06a03650-2369-11ce-bfdc-08002b2b8cda\"))\nvbextFileTypes\n{\n vbextFileTypeForm = 0,\n vbextFileTypeModule = 1,\n vbextFileTypeClass = 2,\n vbextFileTypeProject = 3,\n vbextFileTypeExe = 4,\n vbextFileTypeFrx = 5,\n vbextFileTypeRes = 6,\n vbextFileTypeUserControl = 7,\n vbextFileTypePropertyPage = 8,\n vbextFileTypeDocObject = 9,\n vbextFileTypeBinary = 10,\n vbextFileTypeGroupProject = 11,\n vbextFileTypeDesigners = 12\n};\n\nenum __declspec(uuid(\"be39f3db-1b13-11d0-887f-00a0c90f2744\"))\nvbext_WindowType\n{\n vbext_wt_CodeWindow = 0,\n vbext_wt_Designer = 1,\n vbext_wt_Browser = 2,\n vbext_wt_Watch = 3,\n vbext_wt_Locals = 4,\n vbext_wt_Immediate = 5,\n vbext_wt_ProjectWindow = 6,\n vbext_wt_PropertyWindow = 7,\n vbext_wt_Find = 8,\n vbext_wt_FindReplace = 9,\n vbext_wt_Toolbox = 10,\n vbext_wt_LinkedWindowFrame = 11,\n vbext_wt_MainWindow = 12,\n vbext_wt_ToolWindow = 15\n};\n\nenum __declspec(uuid(\"be39f3dc-1b13-11d0-887f-00a0c90f2744\"))\nvbext_WindowState\n{\n vbext_ws_Normal = 0,\n vbext_ws_Minimize = 1,\n vbext_ws_Maximize = 2\n};\n\nstruct __declspec(uuid(\"0002e185-0000-0000-c000-000000000046\"))\nWindows;\n // [ default ] interface _Windows\n\nstruct __declspec(uuid(\"0002e187-0000-0000-c000-000000000046\"))\nLinkedWindows;\n // [ default ] interface _LinkedWindows\n\nstruct __declspec(uuid(\"0002e113-0000-0000-c000-000000000046\"))\n_VBProjectsEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e103-0000-0000-c000-000000000046\"))\n_dispVBProjectsEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e115-0000-0000-c000-000000000046\"))\n_VBComponentsEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e116-0000-0000-c000-000000000046\"))\n_dispVBComponentsEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e11a-0000-0000-c000-000000000046\"))\n_ReferencesEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e118-0000-0000-c000-000000000046\"))\n_dispReferencesEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e119-0000-0000-c000-000000000046\"))\nReferencesEvents;\n // [ default ] interface _ReferencesEvents\n // [ default, source ] dispinterface _dispReferencesEvents\n\nstruct __declspec(uuid(\"0002e130-0000-0000-c000-000000000046\"))\n_CommandBarControlEvents : IUnknown\n{};\n\nstruct __declspec(uuid(\"0002e131-0000-0000-c000-000000000046\"))\n_dispCommandBarControlEvents : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e132-0000-0000-c000-000000000046\"))\nCommandBarEvents;\n // [ default ] interface _CommandBarControlEvents\n // [ default, source ] dispinterface _dispCommandBarControlEvents\n\nstruct __declspec(uuid(\"0002e159-0000-0000-c000-000000000046\"))\n_ProjectTemplate : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_Application (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n virtual HRESULT __stdcall get_Parent (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n};\n\nstruct __declspec(uuid(\"32cdf9e0-1602-11ce-bfdc-08002b2b8cda\"))\nProjectTemplate;\n // [ default ] interface _ProjectTemplate\n\nenum __declspec(uuid(\"ffcf3247-debf-11d1-baff-00c04fb6c4a6\"))\nvbext_ProjectType\n{\n vbext_pt_HostProject = 100,\n vbext_pt_StandAlone = 101\n};\n\nenum __declspec(uuid(\"0002e129-0000-0000-c000-000000000046\"))\nvbext_ProjectProtection\n{\n vbext_pp_none = 0,\n vbext_pp_locked = 1\n};\n\nenum __declspec(uuid(\"be39f3d2-1b13-11d0-887f-00a0c90f2744\"))\nvbext_VBAMode\n{\n vbext_vm_Run = 0,\n vbext_vm_Break = 1,\n vbext_vm_Design = 2\n};\n\nstruct __declspec(uuid(\"0002e169-0000-0000-c000-000000000046\"))\nVBProject;\n // [ default ] interface _VBProject\n\nstruct __declspec(uuid(\"0002e167-0000-0000-c000-000000000046\"))\nEvents : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_ReferencesEvents (\n /*[in]*/ struct _VBProject * VBProject,\n /*[out,retval]*/ struct _ReferencesEvents * * prceNew ) = 0;\n virtual HRESULT __stdcall get_CommandBarEvents (\n /*[in]*/ IDispatch * CommandBarControl,\n /*[out,retval]*/ struct _CommandBarControlEvents * * prceNew ) = 0;\n};\n\nstruct __declspec(uuid(\"0002e101-0000-0000-c000-000000000046\"))\nVBProjects;\n // [ default ] interface _VBProjects\n\nenum __declspec(uuid(\"be39f3d5-1b13-11d0-887f-00a0c90f2744\"))\nvbext_ComponentType\n{\n vbext_ct_StdModule = 1,\n vbext_ct_ClassModule = 2,\n vbext_ct_MSForm = 3,\n vbext_ct_ActiveXDesigner = 11,\n vbext_ct_Document = 100\n};\n\nstruct __declspec(uuid(\"be39f3d6-1b13-11d0-887f-00a0c90f2744\"))\nComponents;\n // [ default ] interface _Components\n\nstruct __declspec(uuid(\"be39f3d7-1b13-11d0-887f-00a0c90f2744\"))\nVBComponents;\n // [ default ] interface _VBComponents\n\nstruct __declspec(uuid(\"0002e163-0000-0000-c000-000000000046\"))\n_Component : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_Application (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n virtual HRESULT __stdcall get_Parent (\n /*[out,retval]*/ struct _Components * * lppcReturn ) = 0;\n virtual HRESULT __stdcall get_IsDirty (\n /*[out,retval]*/ VARIANT_BOOL * lpfReturn ) = 0;\n virtual HRESULT __stdcall put_IsDirty (\n /*[in]*/ VARIANT_BOOL lpfReturn ) = 0;\n virtual HRESULT __stdcall get_Name (\n /*[out,retval]*/ BSTR * pbstrReturn ) = 0;\n virtual HRESULT __stdcall put_Name (\n /*[in]*/ BSTR pbstrReturn ) = 0;\n};\n\nstruct __declspec(uuid(\"be39f3d8-1b13-11d0-887f-00a0c90f2744\"))\nComponent;\n // [ default ] interface _Component\n\nstruct __declspec(uuid(\"be39f3d4-1b13-11d0-887f-00a0c90f2744\"))\nSelectedComponents : IDispatch\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall Item (\n /*[in]*/ int index,\n /*[out,retval]*/ struct _Component * * lppcReturn ) = 0;\n virtual HRESULT __stdcall get_Application (\n /*[out,retval]*/ struct Application * * lppaReturn ) = 0;\n virtual HRESULT __stdcall get_Parent (\n /*[out,retval]*/ struct _VBProject * * lppptReturn ) = 0;\n virtual HRESULT __stdcall get_Count (\n /*[out,retval]*/ long * lplReturn ) = 0;\n virtual HRESULT __stdcall _NewEnum (\n /*[out,retval]*/ IUnknown * * lppiuReturn ) = 0;\n};\n\nstruct __declspec(uuid(\"be39f3da-1b13-11d0-887f-00a0c90f2744\"))\nVBComponent;\n // [ default ] interface _VBComponent\n\nstruct __declspec(uuid(\"0002e18b-0000-0000-c000-000000000046\"))\nProperties;\n // [ default ] interface _Properties\n\nstruct __declspec(uuid(\"da936b63-ac8b-11d1-b6e5-00a0c90f2744\"))\nAddins;\n // [ default ] interface _AddIns\n\nenum vbext_ProcKind\n{\n vbext_pk_Proc = 0,\n vbext_pk_Let = 1,\n vbext_pk_Set = 2,\n vbext_pk_Get = 3\n};\n\nstruct __declspec(uuid(\"0002e170-0000-0000-c000-000000000046\"))\nCodeModule;\n // [ default ] interface _CodeModule\n\nstruct __declspec(uuid(\"0002e174-0000-0000-c000-000000000046\"))\nCodePanes;\n // [ default ] interface _CodePanes\n\nenum vbext_CodePaneview\n{\n vbext_cv_ProcedureView = 0,\n vbext_cv_FullModuleView = 1\n};\n\nstruct __declspec(uuid(\"0002e178-0000-0000-c000-000000000046\"))\nCodePane;\n // [ default ] interface _CodePane\n\nenum vbext_RefKind\n{\n vbext_rk_TypeLib = 0,\n vbext_rk_Project = 1\n};\n\nstruct __declspec(uuid(\"cdde3804-2064-11cf-867f-00aa005ff34a\"))\n_dispReferences_Events : IDispatch\n{};\n\nstruct __declspec(uuid(\"0002e17c-0000-0000-c000-000000000046\"))\nReferences;\n // [ default ] interface _References\n // [ default, source ] dispinterface _dispReferences_Events\n\nstruct __declspec(uuid(\"0002e166-0000-0000-c000-000000000046\"))\ntestVBE : Application\n{\n //\n // Raw methods provided by interface\n //\n\n virtual HRESULT __stdcall get_VBProjects (\n /*[out,retval]*/ struct _VBProjects * * lppptReturn ) = 0;\n virtual HRESULT __stdcall get_CommandBars (\n /*[out,retval]*/ __missing_type__ * * ppcbs ) = 0;\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965047/" ]
I'm trying to build the example described at <http://support.microsoft.com/kb/178749/EN-US/> in order to build an application that programatically accesses Excel using Automation. I have Visual C++ 2005/Visual Studio 2005. Some of the instructions don't exactly match up (classwizard, mostly), but the general idea seems to be the same. Problems: I don't end up with an excel.h file after using the "new class" to create my wrapper classes. So I can' t #include that file as it specifies in step 13. I do get a excel.tlh and an excel.tli in my windebug directory, but that doesn't seem to work. I tried all orders for ``` #include "stdafx.h" #include "debug/excel.tli" #include "debug/excel.tlh" ``` ... including leaving one of those files out of the compile, but I still end up with a ton of compile errors. Here's the top 5 compile errors with the above #includes: ``` 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(16) : error C3861: 'get_Parent': identifier not found ``` Here's the top 5 errors with these includes: ``` #include "stdafx.h" #include "debug/excel.tlh" 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(550) : error C3121: cannot change GUID for class 'IFilter' 1> c:\program files\microsoft sdks\windows\v6.0\include\comdef.h(483) : see declaration of 'IFilter' 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2786: 'BOOL (__stdcall *)(HDC,int,int,int,int)' : invalid operand for __uuidof 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2923: '_com_IIID' : 'Rectangle' is not a valid template type argument for parameter '_Interface' 1> c:\program files\microsoft sdks\windows\v6.0\include\wingdi.h(3667) : see declaration of 'Rectangle' 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C3203: '_com_IIID' : unspecialized class template can't be used as a template argument for template parameter '_IIID', expected a real type ``` Here's the top 5 errors with these includes: ``` #include "stdafx.h" #include "debug/excel.tli" 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int ``` Thanks in advance.
I'm not familiar with the ClassWizard wrapper generator, but it looks like it may have #imported the Excel COM type library without a namespace, and you're getting conflicts with the SDK header files. Check the `.tlh` file and ensure there's a namespace around the definitions. If not, I'd look at importing it the more manual (but safer) way using #import. Check out using #import directly; it will generate the `.tlh` and `.tli` files in the build directory, which you can then use directory with `CComPtr<>` and the like. I've found that to be much more straightforward than using CW wrapper classes. That's my advice anyway.
185,536
<p>By default it seems that objects are drawn front to back. I am drawing a 2-D UI object and would like to create it back to front. For example I could create a white square first then create a slightly smaller black square on top of it thus creating a black pane with a white border. <a href="http://gpwiki.org/index.php/OpenGL:Tutorials:Tutorial_Framework:Ortho_and_Alpha" rel="noreferrer">This post</a> had some discussion on it and described this order as the "Painter's Algorithm" but ultimately the example they gave simply rendered the objects in reverse order to get the desired effect. I figure back to front (first objects go in back, subsequent objects get draw on top) rendering can be achieved via some transformation (gOrtho?) ?</p> <p>I will also mention that I am not interested in a solution using a wrapper library such as GLUT. </p> <p>I have also found that the default behavior on the Mac using the Cocoa NSOpenGLView appears to draw back to front, where as in windows I cannot get this behavior. The setup code in windows I am using is this:</p> <pre><code>glViewport (0, 0, wd, ht); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho (0.0f, wd, ht, 0.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); </code></pre>
[ { "answer_id": 185551, "author": "MrValdez", "author_id": 1599, "author_profile": "https://Stackoverflow.com/users/1599", "pm_score": 2, "selected": false, "text": "<p>Drawing order is hard. There is no easy solution. The painter's alogorithm (sort objects by their distance in relation to your camera's view) is the most straightforward, but as you have discovered, it doesn't solve all cases.</p>\n\n<p>I would suggest a combination of the painter's algroithm and layers. You build layers for specific elements on your program. So you got a background layer, objects layers, special effect layers, and GUI layer.</p>\n\n<p>Use the painter's algorithm on each layer's items. In some special layers (like your GUI layer), don't sort with the painter's algorithm, but by your call order. You call that white square first so it gets drawn first.</p>\n" }, { "answer_id": 185560, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>Draw items that you want to be in back slightly behind the items that you want to be in the front. That is, actually change the z value (assuming z is perpendicular to the screen plane). You don't have to change it a lot to get the items to draw in front of eachother. And if you only change the z value slightly, you shouldn't notice much of an offset from their desired position. You could even go really fancy, and calculate the correct x,y position based on the changed z position, so that the item appears where it is supposed to be.</p>\n" }, { "answer_id": 185618, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 3, "selected": false, "text": "<p>For your specific question, no there is no standardized way to specify depth ordering in OpenGL. Some implementations may do front to back depth ordering by default because it's usually faster, but that is not guaranteed (as you discovered).</p>\n\n<p>But I don't really see how it will help you in your scenario. If you draw a black square in front of a white square the black square should be drawn in front of the white square regardless of what order they're drawn in, as long as you have depth buffering enabled. If they're actually coplanar, then neither one is really in front of the other and any depth sorting algorithm would be unpredictable.</p>\n\n<p>The tutorial that you posted a link to only talked about it because depth sorting IS relevant when you're using transparency. But it doesn't sound to me like that's what you're after.</p>\n\n<p>But if you really have to do it that way, then you have to do it yourself. First send your white square to the rendering pipeline, force the render, and then send your black square. If you do it that way, and disable depth buffering, then the squares can be coplanar and you will still be guaranteed that the black square is drawn over the white square.</p>\n" }, { "answer_id": 189915, "author": "AlanKley", "author_id": 8761, "author_profile": "https://Stackoverflow.com/users/8761", "pm_score": 6, "selected": true, "text": "<p>The following call will turn off depth testing causing objects to be drawn in the order created. This will in effect cause objects to draw back to front.</p>\n\n<pre><code>glDepthFunc(GL_NEVER); // Ignore depth values (Z) to cause drawing bottom to top\n</code></pre>\n\n<p>Be sure you do not call this:</p>\n\n<pre><code>glEnable (GL_DEPTH_TEST); // Enables Depth Testing\n</code></pre>\n" }, { "answer_id": 189939, "author": "davidavr", "author_id": 8247, "author_profile": "https://Stackoverflow.com/users/8247", "pm_score": 0, "selected": false, "text": "<p>As AlanKley pointed out, the way to do this is to disable the depth buffer. The painter's algorithm is really a 2D scan-conversion technique used to render polygons in the correct order when you don't have something like a z-buffer. But you wouldn't apply it to 3D polygons. You'd typically transform and project them (handling intersections with other polygons) and then sort the resulting list of 2D projected polygons by their projected z-coordinate, then draw them in reverse z-order.</p>\n\n<p>I've always thought of the painter's algorithm as an alternate technique for hidden surface removal when you can't (or don't want to) use a z-buffer.</p>\n" }, { "answer_id": 189944, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 1, "selected": false, "text": "<p>Your stuff will be drawn in the exact order you call the glBegin/glEnd functions in. You can get depth-buffering using the z-buffer, and if your 2d objects have different z values, you can get the effect you want that way. The only way you are seeing the behavior you describe on the Mac is if the program is drawing stuff in back-to-front order manually or using the z-buffer to accomplish this. OpenGL otherwise does not have any functionality automatically as you describe.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761/" ]
By default it seems that objects are drawn front to back. I am drawing a 2-D UI object and would like to create it back to front. For example I could create a white square first then create a slightly smaller black square on top of it thus creating a black pane with a white border. [This post](http://gpwiki.org/index.php/OpenGL:Tutorials:Tutorial_Framework:Ortho_and_Alpha) had some discussion on it and described this order as the "Painter's Algorithm" but ultimately the example they gave simply rendered the objects in reverse order to get the desired effect. I figure back to front (first objects go in back, subsequent objects get draw on top) rendering can be achieved via some transformation (gOrtho?) ? I will also mention that I am not interested in a solution using a wrapper library such as GLUT. I have also found that the default behavior on the Mac using the Cocoa NSOpenGLView appears to draw back to front, where as in windows I cannot get this behavior. The setup code in windows I am using is this: ``` glViewport (0, 0, wd, ht); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho (0.0f, wd, ht, 0.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); ```
The following call will turn off depth testing causing objects to be drawn in the order created. This will in effect cause objects to draw back to front. ``` glDepthFunc(GL_NEVER); // Ignore depth values (Z) to cause drawing bottom to top ``` Be sure you do not call this: ``` glEnable (GL_DEPTH_TEST); // Enables Depth Testing ```
185,559
<p>I would like to remove the domain/computer information from a login id in C#. So, I would like to make either "Domain\me" or "Domain\me" just "me". I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact.</p> <p>Worse case scenario:</p> <pre><code>int startIndex = 0; int indexOfSlashesSingle = ResourceLoginName.IndexOf("\"); int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\"); if (indexOfSlashesSingle != -1) startIndex = indexOfSlashesSingle; else startIndex = indexOfSlashesDouble; string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1); </code></pre>
[ { "answer_id": 185572, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<p>I always do it this way:</p>\n\n<pre><code> string[] domainuser;\n string Auth_User = Request.ServerVariables[\"AUTH_USER\"].ToString().ToLower(); \n domainuser = Auth_User.Split('\\\\');\n</code></pre>\n\n<p>Now you can look at domainuser.Length to see how many parts are there and domainuser[0] for the domain and domainuser[1] for the username.</p>\n" }, { "answer_id": 185577, "author": "Matt Dawdy", "author_id": 232, "author_profile": "https://Stackoverflow.com/users/232", "pm_score": 2, "selected": false, "text": "<pre><code> string theString = \"domain\\\\me\";\n theString = theString.Split(new char[] { '\\\\' })[theString.Split(new char[] { '\\\\' }).Length - 1];\n</code></pre>\n" }, { "answer_id": 185716, "author": "user26350", "author_id": 26350, "author_profile": "https://Stackoverflow.com/users/26350", "pm_score": 6, "selected": true, "text": "<p>when all you have is a hammer, everything looks like a nail.....</p>\n\n<p>use a razor blade ----</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\npublic class MyClass\n{\n public static void Main()\n {\n string domainUser = Regex.Replace(\"domain\\\\user\",\".*\\\\\\\\(.*)\", \"$1\",RegexOptions.None);\n Console.WriteLine(domainUser); \n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 185767, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 5, "selected": false, "text": "<p>You could abuse the Path class, thusly:</p>\n\n<pre><code>string shortName = System.IO.Path.GetFileNameWithoutExtension(ResourceLoginName);\n</code></pre>\n" }, { "answer_id": 5859009, "author": "Drew Graham", "author_id": 734690, "author_profile": "https://Stackoverflow.com/users/734690", "pm_score": 3, "selected": false, "text": "<p>How's about:</p>\n\n<pre><code>string shortName = ResourceLoginName.Split('\\\\')[1]\n</code></pre>\n" }, { "answer_id": 25168681, "author": "anyhotcountry", "author_id": 3464789, "author_profile": "https://Stackoverflow.com/users/3464789", "pm_score": 2, "selected": false, "text": "<p>This works for both valid domain logins:</p>\n\n<pre><code>var regex = @\"^(.*\\\\)?([^\\@]*)(@.*)?$\";\nvar user = Regex.Replace(\"domain\\\\user\", regex, \"$2\", RegexOptions.None);\nuser = Regex.Replace(\"[email protected]\", regex, \"$2\", RegexOptions.None);\n</code></pre>\n" }, { "answer_id": 27909736, "author": "Derek Smalls", "author_id": 583426, "author_profile": "https://Stackoverflow.com/users/583426", "pm_score": 3, "selected": false, "text": "<p>This will work for both but with named groups.</p>\n\n<pre><code>^(?&lt;domain&gt;.*)\\\\(?&lt;username&gt;.*)|(?&lt;username&gt;[^\\@]*)@(?&lt;domain&gt;.*)?$\n</code></pre>\n" }, { "answer_id": 31973361, "author": "Earl", "author_id": 1253140, "author_profile": "https://Stackoverflow.com/users/1253140", "pm_score": 2, "selected": false, "text": "<p>Piggy backing on Derek Smalls Answer...</p>\n\n<pre><code>Regex.Replace(User.Identity.Name,@\"^(?&lt;domain&gt;.*)\\\\(?&lt;username&gt;.*)|(?&lt;username&gt;[^\\@]*)@(?&lt;domain&gt;.*)?$\", \"${username}\", RegexOptions.None)\n</code></pre>\n\n<p>worked for me.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18449/" ]
I would like to remove the domain/computer information from a login id in C#. So, I would like to make either "Domain\me" or "Domain\me" just "me". I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact. Worse case scenario: ``` int startIndex = 0; int indexOfSlashesSingle = ResourceLoginName.IndexOf("\"); int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\"); if (indexOfSlashesSingle != -1) startIndex = indexOfSlashesSingle; else startIndex = indexOfSlashesDouble; string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1); ```
when all you have is a hammer, everything looks like a nail..... use a razor blade ---- ``` using System; using System.Text.RegularExpressions; public class MyClass { public static void Main() { string domainUser = Regex.Replace("domain\\user",".*\\\\(.*)", "$1",RegexOptions.None); Console.WriteLine(domainUser); } } ```
185,569
<p>This is an age-old question where given a table with attributes 'type', 'variety' and 'price', that you fetch the record with the minimum price for each type there is.</p> <p>In SQL, we can do <a href="http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/" rel="noreferrer">this</a> by:</p> <pre><code>select f.type, f.variety, f.price from ( select type, min(price) as minprice from table group by type ) as x inner join table as f on f.type = x.type and f.price = x.minprice;` </code></pre> <p>We could perhaps imitate this by:</p> <pre><code>minprices = Table.minimum(:price, :group =&gt; type) result = [] minprices.each_pair do |t, p| result &lt;&lt; Table.find(:first, :conditions =&gt; ["type = ? and price = ?", t, p]) end </code></pre> <p>Is there a better implementation than this?</p>
[ { "answer_id": 185647, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 4, "selected": false, "text": "<pre><code>Table.minimum(:price, :group =&gt; :type)\n</code></pre>\n\n<p>See <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum\" rel=\"nofollow noreferrer\">http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum</a> for more.</p>\n" }, { "answer_id": 186219, "author": "François Beausoleil", "author_id": 7355, "author_profile": "https://Stackoverflow.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>You can use #<a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001302\" rel=\"nofollow noreferrer\"><code>find_by_sql</code></a>, but this implies returning a model object, which might not be what you want.</p>\n\n<p>If you want to go bare to the metal, you can also use #<a href=\"http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#M001063\" rel=\"nofollow noreferrer\"><code>select_values</code></a>:</p>\n\n<pre><code>data = ActiveRecord::Base.connection.select_values(\"\n SELECT f.type, f.variety, f.price\n FROM (SELECT type, MIN(price) AS minprice FROM table GROUP BY type ) AS x\n INNER JOIN table AS f ON f.type = x.type AND f.price = x.minprice\")\nputs data.inspect\n[[\"type\", \"variety\", 0.00]]\n</code></pre>\n\n<p>ActiveRecord is just a tool. You use it when it's convenient. When SQL does a better job, you use that.</p>\n" }, { "answer_id": 14881865, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 1, "selected": false, "text": "<p>I've been fighting with this for a while and for the moment it seems that you are pretty much stuck with generating SQL.</p>\n\n<p>However, I have a couple refinements to offer.</p>\n\n<p>Instead of <code>find_by_sql</code>, as @François suggested, I've used ActiveRecord's <code>to_sql</code> and <code>joins</code> to \"guide\" my SQL a little bit:</p>\n\n<pre><code>subquery_sql = Table.select([\"MIN(price) as price\", :type]).group(:type).to_sql\njoins_sql = \"INNER JOIN (#{subquery_sql}) as S\n ON table.type = S.type\n AND table.price = S.price\"\n\nTable.joins(joins_sql).where(&lt;other conditions&gt;).order(&lt;your order&gt;)\n</code></pre>\n\n<p>As you can see, I'm still using raw SQL, but at least it's only on the part where AR gives no support (AFAIK ActiveRecord simply can't manage <code>INNER JOIN ... ON ...</code>) and not on the whole thing.</p>\n\n<p>Using <code>joins</code> instead of find_by_sql makes the query chainable - you can add extra conditions, or sort the table, or put everything in a scope.</p>\n" }, { "answer_id": 24135836, "author": "danielmbarlow", "author_id": 2564759, "author_profile": "https://Stackoverflow.com/users/2564759", "pm_score": -1, "selected": false, "text": "<p>To update Avdi's answer above:</p>\n\n<blockquote>\n <p>Table.minimum(:price, :group => :type)</p>\n</blockquote>\n\n<p>Here is the updated URL:</p>\n\n<p><a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum\" rel=\"nofollow\">http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum</a></p>\n" }, { "answer_id": 61487434, "author": "Pat Newell", "author_id": 1081553, "author_profile": "https://Stackoverflow.com/users/1081553", "pm_score": 0, "selected": false, "text": "<p>While this question is pretty stale, I was asking the same question today.\nHere's a gist of a solution to compose the SQL needed to accomplish the goal with minimal (2) queries.</p>\n\n<p>Please lmk if there are better ways these days!</p>\n\n<p>Using <code>Security</code> and <code>Price</code> models, where Securities have many (historical) Prices, and you are after the Securities' most recent price:</p>\n\n<pre><code>module MostRecentBy\n def self.included(klass)\n klass.scope :most_recent_by, -&gt;(group_by_col, max_by_col) {\n from(\n &lt;&lt;~SQL\n (\n SELECT #{table_name}.*\n FROM #{table_name} JOIN (\n SELECT #{group_by_col}, MAX(#{max_by_col}) AS #{max_by_col}\n FROM #{table_name}\n GROUP BY #{group_by_col}\n ) latest\n ON #{table_name}.date = latest.#{max_by_col}\n AND #{table_name}.#{group_by_col} = latest.#{group_by_col}\n ) #{table_name}\n SQL\n )\n }\n end\nend\n\nclass Price &lt; ActiveRecord::Base\n include MostRecentBy\n\n belongs_to :security\n\n scope :most_recent_by_security, -&gt; { most_recent_by(:security_id, :date) }\nend\n\nclass Security &lt; ActiveRecord::Base\n has_many :prices\n has_one :latest_price, \n -&gt; { Price.most_recent_by_security },\n class_name: 'Price'\nend\n</code></pre>\n\n<p>now you can call the following in your controller code:</p>\n\n<pre><code>def index\n @resources = Security.all.includes(:latest_price)\n\n render json: @resources.as_json(include: :latest_price)\nend\n</code></pre>\n\n<p>which results in two queries:</p>\n\n<pre><code> Security Load (4.4ms) SELECT \"securities\".* FROM \"securities\"\n Price Load (140.3ms) SELECT \"prices\".* FROM (\n SELECT prices.*\n FROM prices JOIN (\n SELECT security_id, MAX(date) AS date\n FROM prices\n GROUP BY security_id\n ) latest\n ON prices.date = latest.date\n AND prices.security_id = latest.security_id\n ) prices\n WHERE \"prices\".\"price_type\" = $1 AND \"prices\".\"security_id\" IN (...)\n</code></pre>\n\n<p>for reference: <a href=\"https://gist.github.com/pmn4/eb58b036cc78fb41a36c56bcd6189d68\" rel=\"nofollow noreferrer\">https://gist.github.com/pmn4/eb58b036cc78fb41a36c56bcd6189d68</a></p>\n" }, { "answer_id": 66361028, "author": "Youngjoon Choi", "author_id": 10555769, "author_profile": "https://Stackoverflow.com/users/10555769", "pm_score": 2, "selected": false, "text": "<p>This worked for me.</p>\n<pre><code>Table.group(:type).minimum(:price)\n</code></pre>\n<p>And it returns an object like this.</p>\n<pre><code>{\n &quot;type1&quot;=&gt;500.0,\n &quot;type2&quot;=&gt;200.0\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/185569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is an age-old question where given a table with attributes 'type', 'variety' and 'price', that you fetch the record with the minimum price for each type there is. In SQL, we can do [this](http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/) by: ``` select f.type, f.variety, f.price from ( select type, min(price) as minprice from table group by type ) as x inner join table as f on f.type = x.type and f.price = x.minprice;` ``` We could perhaps imitate this by: ``` minprices = Table.minimum(:price, :group => type) result = [] minprices.each_pair do |t, p| result << Table.find(:first, :conditions => ["type = ? and price = ?", t, p]) end ``` Is there a better implementation than this?
``` Table.minimum(:price, :group => :type) ``` See <http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum> for more.