qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
296,978
<p>I've got a small piece of code that is parsing an index value to determine a cell input into Excel. It's got me thinking...</p> <p>What's the difference between </p> <pre><code>xlsSheet.Write("C" + rowIndex.ToString(), null, title); </code></pre> <p>and</p> <pre><code>xlsSheet.Write(string.Format("C{0}", rowIndex), null, title); </code></pre> <p>Is one "better" than the other? And why?</p>
[ { "answer_id": 296985, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "xlsSheet.Write(\"C\" + rowIndex, null, title);\n xlsSheet.Write($\"C{rowIndex}\", null, title);\n" }, { "answer_id": 296999, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "string.Format()" }, { "answer_id": 297021, "author": "Martin Hollingsworth", "author_id": 29491, "author_profile": "https://Stackoverflow.com/users/29491", "pm_score": 3, "selected": false, "text": "xlsSheet.Write(\"C\" + rowIndex.ToString(), null, title);\n" }, { "answer_id": 297031, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 3, "selected": false, "text": "string.Format string.Format .ToString() string.Concat(string, object) string.Format Console.WriteLine(\n \"Dear {0} {1},\\n\\n\" +\n\n \"Our records indicate that your {2}, \\\"{3}\\\", is due for {4} {5} shots.\\n\" +\n \"Please call our office at 1-900-382-5633 to make an appointment.\\n\\n\" +\n\n \"Thank you,\\n\" +\n \"Eastern Veterinary\",\n\n /*0*/client.Title,\n /*1*/client.LastName,\n /*2*/client.Pet.Animal,\n /*3*/client.Pet.Name,\n /*4*/client.Pet.Gender == Gender.Male ? \"his\" : \"her\",\n /*5*/client.Pet.Schedule[0]\n);\n string.Format string.Format Console.WriteLine(\n $\"Dear {client.Title} {client.LastName},\\n\\n\" +\n\n $\"Our records indicate that your {client.Pet.Animal}, \\\"{client.Pet.Name}\\\", \" +\n $\"is due for {(client.Pet.Gender == Gender.Male ? \"his\" : \"her\")} \" +\n $\"{client.Pet.Schedule[0]} shots.\\n\" +\n \"Please call our office at 1-900-382-5633 to make an appointment.\\n\\n\" +\n\n \"Thank you,\\n\" +\n \"Eastern Veterinary\"\n);\n string.Format const string s =\n \"This compiles successfully, \" +\n \"and you can see that it will \" +\n \"all be one string (named `s`) \" +\n \"at run time\";\n" }, { "answer_id": 297273, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 2, "selected": false, "text": "\"C\" + rowIndex.ToString();\n String.Format(\"C(0)\",rowIndex);\n \"a\" + rowIndex.ToString() + \"b\" + colIndex.ToString() + \"c\" + zIndex.ToString();\n" }, { "answer_id": 299541, "author": "Dan C.", "author_id": 26391, "author_profile": "https://Stackoverflow.com/users/26391", "pm_score": 7, "selected": false, "text": "String.Format s1 + null + s2 public static string Test(string s1, int i2, int i3, int i4, \n string s5, string s6, float f7, float f8)\n{\n return s1 + \" \" + i2 + i3 + i4 + \" ddd \" + s5 + s6 + f7 + f8;\n}\n public static string Test(string s1, int i2, int i3, int i4,\n string s5, string s6, float f7, float f8)\n{\n return string.Concat(new object[] { s1, \" \", i2, i3, i4, \n \" ddd \", s5, s6, f7, f8 });\n}\n String.Concat String.Format String.Format StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8)); ToString() ToString() ToString() String.Format()" }, { "answer_id": 21260753, "author": "deankarn", "author_id": 3158232, "author_profile": "https://Stackoverflow.com/users/3158232", "pm_score": 1, "selected": false, "text": "\"The user is not authorized for location \" + location \"The User is not authorized for location {0}\" location + \" does not allow this User Access\" \"{0} does not allow this User Access\"" }, { "answer_id": 29986688, "author": "Kitemark76", "author_id": 244035, "author_profile": "https://Stackoverflow.com/users/244035", "pm_score": 1, "selected": false, "text": "string concat = \"\";\n System.Diagnostics.Stopwatch sw1 = new System.Diagnostics.Stopwatch ();\n sw1.Start();\n for (int i = 0; i < 10000000; i++)\n {\n concat = string.Format(\"{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}\",\"1\", \"2\" , \"3\" , \"4\" , \"5\" , \"6\" , \"7\" , \"8\" , \"9\" , \"10\" , i);\n }\n sw1.Stop();\n Response.Write(\"format: \" + sw1.ElapsedMilliseconds.ToString());\n System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();\n sw2.Start();\n for (int i = 0; i < 10000000; i++)\n {\n concat = \"1\" + \"2\" + \"3\" + \"4\" + \"5\" + \"6\" + \"7\" + \"8\" + \"9\" + \"10\" + i;\n }\n sw2.Stop();\n" }, { "answer_id": 69348833, "author": "Nisar", "author_id": 2545270, "author_profile": "https://Stackoverflow.com/users/2545270", "pm_score": 1, "selected": false, "text": "void Main()\n{\n var start = CurrentTimeMillis();\n for (var i = 0; i < 1000000; i++)\n {\n var s = \"Hi \" + i.ToString() + \"; Hi to you \" + (i * 2).ToString();\n }\n var end = CurrentTimeMillis();\n Console.WriteLine(\"Concatenation = \" + ((end - start)).ToString() + \" millisecond\");\n start = CurrentTimeMillis();\n for (var i = 0; i < 1000000; i++)\n {\n var s = String.Format(\"Hi {0}; Hi to you {1}\", i, +i * 2);\n }\n end = CurrentTimeMillis();\n Console.WriteLine(\"Format = \" + ((end - start)).ToString() + \" millisecond\");\n start = CurrentTimeMillis();\n for (var i = 0; i < 1000000; i++)\n {\n var s = String.Concat(\"Hi \", i.ToString(), \"; Hi to you \", (i * 2).ToString());\n }\n end = CurrentTimeMillis();\n Console.WriteLine(\"Strng.concat = \" + ((end - start)).ToString() + \" millisecond\");\n\n start = CurrentTimeMillis();\n for (int i = 0; i < 1000000; i++)\n {\n StringBuilder bldString = new StringBuilder(\"Hi \");\n bldString.Append(i).Append(\"; Hi to you \").Append(i * 2);\n }\n end = CurrentTimeMillis();\n Console.WriteLine(\"String Builder = \" + ((end - start)) + \" millisecond\");\n}\n\nprivate static readonly DateTime Jan1st1970 = new DateTime\n (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n\npublic static long CurrentTimeMillis()\n{\n return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;\n}\n Concatenation = 69 millisecond\nFormat = 142 millisecond\nStrng.concat = 62 millisecond\nString Builder = 91 millisecond\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33226/" ]
296,981
<p>Could someone show me a regular expression that would look through this document and select the href value of every href that has <code>RELATION_ID</code> on the end of it? Then if it does, I have to get the Id that is before the question mark (example <code>href="dctm://ISDOFSDdev/</code>37004e1f800021f3<code>?DMS_OBJECT_SPEC=RELATION_ID</code>")</p> <p>Thanks!</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;?dctm xml_app="elearningContent"?&gt; &lt;!DOCTYPE OnlineContent PUBLIC "-//ISDOFSD//DTD Online Content//EN" "file:C:/dmExport/New%20Folder%20(2)/ISDOFSDdev/elearningContent/OnlineContent.dtd"&gt; &lt;OnlineContent outputclass="Graphic Down" id="OnlineContent_955627C91D8743B98DCB8BD9BE379DE8"&gt; &lt;title&gt;Text and Popup&lt;/title&gt; &lt;OnlineContentBody&gt; &lt;lcInstruction id="lcInstruction_770F26218C064A84BFA1813562173970"&gt; &lt;p&gt;This is an example of a plain text screen with an attached popup.&lt;/p&gt; &lt;p&gt; Popups are used to display additional content in a popup window. A &lt;xref scope="local" type="topic" format="dita" href="dctm://ISDOFSDdev/37004e1f800021f3?DMS_OBJECT_SPEC=RELATION_ID"&gt;link is provided&lt;/xref&gt; in the main text of the screen, which may clicked on to open a popup. A screen may contain &lt;xref scope="local" type="topic" format="dita" href="dctm://ISDOFSDdev/37004e1f800021f4?DMS_OBJECT_SPEC=RELATION_ID"&gt;more than one popup&lt;/xref&gt;. &lt;/p&gt; &lt;/lcInstruction&gt; &lt;/OnlineContentBody&gt; &lt;OnlinePopup id="OnlinePopup_AFE53E2CACBF4D8196E6360D4DDB6B70"&gt; &lt;title&gt;A Popup&lt;/title&gt; &lt;OnlinePopupBody&gt; &lt;p&gt;This is an example of popup content.&lt;/p&gt; &lt;p&gt;A popup may contain one or more paragraphs of text. They may also contain lists, like this:&lt;/p&gt; &lt;ul id="ul_7812991BBBDD4995B7499A9557C4EA9C"&gt; &lt;li id="li_E83BDB28EC494B98BFF3DD5924AF855E"&gt;An item in a list&lt;/li&gt; &lt;li id="li_270F2A3A85BA4E6EBF98CB4023344475"&gt;Another item in a list&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;A numbered list is demonstrated in the second popup.&lt;/p&gt; &lt;/OnlinePopupBody&gt; &lt;/OnlinePopup&gt; &lt;OnlinePopup id="OnlinePopup_5AE081BFB97043CE99F39A9E4A063332"&gt; &lt;title&gt;Another Popup&lt;/title&gt; &lt;OnlinePopupBody&gt; &lt;p&gt;This is the second popup on this screen, containing a numbered list.&lt;/p&gt; &lt;ol id="ol_EF18C080E7CC40B7998DEB75772367A6"&gt; &lt;li id="li_91B42F1B886B4CF887C001577C14B3F0"&gt;An item in a list&lt;/li&gt; &lt;li id="li_95C4F32E093843FAB985A3F6981A7D07"&gt;Another item in a list&lt;/li&gt; &lt;/ol&gt; &lt;/OnlinePopupBody&gt; &lt;/OnlinePopup&gt; &lt;/OnlineContent&gt; </code></pre>
[ { "answer_id": 296997, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "href=\".*/([^\"?/]*)?[^\"]*RELATION_ID[^\"]*\" ([^\"?/]*) Matcher.group(int) Matcher.find(int)" }, { "answer_id": 297088, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 1, "selected": false, "text": "expr = re.compile('href=.*?/(.*?)\\?.*?=RELATION_ID', re.MULTILINE)\n\nfor x in expr.finditer(test_string): # iterate through all matches\n s = x.group(1) # get the one and only group of the match\n ss = s.split(\"/\") # split off the ISDOFSDdev\n s = ss[len(ss) - 1] # grab the last element\n print s # print it\n 37004e1f800021f3\n37004e1f800021f4\n" }, { "answer_id": 297099, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "[a-fA-F0-9]+(?=\\?DMS_OBJECT_SPEC=RELATION_ID)\n" }, { "answer_id": 297171, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n >\n <xsl:output method=\"text\" indent=\"no\"/>\n <xsl:template match=\"*[@href]\">\n <xsl:if test=\"contains(@href, 'RELATION_ID')\">\n <xsl:value-of select=\"@href\"/>\n <xsl:text>&#xa;</xsl:text>\n </xsl:if>\n <xsl:apply-templates select=\"*\"/>\n </xsl:template>\n <xsl:template match=\"*\">\n <xsl:apply-templates select=\"*\"/>\n </xsl:template>\n</xsl:stylesheet>\n C:\\Documents and Settings\\fer\\Escritorio>msxsl.exe -xw example.xml example-xslt.xsl > out.txt\n <?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:fn=\"http://www.w3.org/2005/xpath-functions\" >\n <xsl:output method=\"text\" indent=\"no\"/>\n <xsl:template match=\"*[@href]\">\n <xsl:if test=\"fn:contains(@href, 'RELATION_ID')\">\n <xsl:value-of select=\"fn:replace(@href,'.*/([^/]*)\\?.*', '$1')\"/>\n <xsl:text>&#xa;</xsl:text>\n </xsl:if>\n <xsl:apply-templates select=\"*\"/>\n </xsl:template>\n <xsl:template match=\"*\">\n <xsl:apply-templates select=\"*\"/>\n </xsl:template>\n</xsl:stylesheet>\n C:\\Documents and Settings\\fer\\Escritorio>AltovaXML -xslt2 example-xslt.xsl -in example.xml\n" }, { "answer_id": 297384, "author": "Jason", "author_id": 38398, "author_profile": "https://Stackoverflow.com/users/38398", "pm_score": 0, "selected": false, "text": "href=\"[^=]*=RELATION_ID\" dctm:[^?]* href=\" [^=]* =RELATION___ID dctm [^?]*" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
297,018
<p>I have stored a txt file as string in a database column. Now on one of my aspx page I have a link...I want to open a txt file when the user clicks on this link. How can i read a file from database. I know how to do this using streamreader for a file stored on the disk.</p> <p>Thanks</p>
[ { "answer_id": 297044, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public void Page_Load(object sender, EventArgs e)\n var text = (from x in dataContext.MyTextTable where x.Id == someId select x.FileText).FirstOrDefault();\n\n this.textBox.Text = text;\n}\n public void Page_Load(object sender, EventArgs e)\n{\n var text = Repository.GetTextFile(this.FileTextBox.Text).ToCharArray();\n\n Response.Clear();\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\" & this.FileTextBox.Text);\n Response.AddHeader(\"Content-Length\", text.Length.ToString());\n Response.ContentType = \"application/octet-stream\";\n Response.Write(text, 0, text.length);\n Response.End();\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34219/" ]
297,029
<p>How to get file name and revision number as a list starting from a designated folder?</p>
[ { "answer_id": 298196, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 0, "selected": false, "text": "cvs status ===================================================================\nFile: test.pas Status: Up-to-date\n\n Working revision: 1.4\n Repository revision: 1.4 /cvsroot/MyModule/test.pas,v\n Expansion option: kv\n Commit Identifier: 86c473d9b385950\n Sticky Tag: (none)\n Sticky Date: (none)\n Sticky Options: (none)\n Merge From: (none)\n" }, { "answer_id": 306674, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 2, "selected": false, "text": "cvs status > cvs status | grep Repository\\ revision\\:\nRepository revision: 1.16 /cvsroot/module/.cvsignore,v\nRepository revision: 1.1.1.1 /cvsroot/module/build.sh,v\nRepository revision: 1.251 /cvsroot/module/build.xml,v\nRepository revision: 1.36 /cvsroot/module/manifest.xml,v\n... and on, and on...\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,034
<p>In <a href="https://stackoverflow.com/questions/204467/is-there-a-perl-function-to-turn-a-string-into-a-regexp-to-use-that-string-as-p">another Stack&nbsp;Overflow question</a> <a href="https://stackoverflow.com/users/4727/leon-timmermans">Leon Timmermans</a> asserted:</p> <blockquote> <p>I would advice you not to use prototypes. They have their uses, but not for most cases and definitely not in this one.</p> </blockquote> <p>Why might this be true (or otherwise)? I almost always supply prototypes for my Perl functions, and I've never before seen anyone else say anything bad about using them.</p>
[ { "answer_id": 297095, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 6, "selected": false, "text": "&function(...) $ my @array = qw(a b c);\n\nfoo(@array);\nfoo(@array[0..1]);\nfoo($array[0], $array[1], $array[2]);\n\nsub foo ($;$$) { print \"@_\\n\" }\n\nfoo(@array);\nfoo(@array[0..1]);\nfoo($array[0], $array[1], $array[2]);\n a b c\na b\na b c\n3\nb\na b c\n main::foo() called too early to check prototype" }, { "answer_id": 297265, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 8, "selected": true, "text": "sub mypush(\\@@) { ... }\n mypush @array, 1, 2, 3;\n \\" }, { "answer_id": 299467, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": false, "text": "$ & * \\@ \\$ \\% \\*" }, { "answer_id": 36825170, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "sub some_sub ($$) { ... }\n use v5.20;\nuse feature qw(signatures);\nno warnings qw(experimental::signatures);\n\nanimals( 'Buster', 'Nikki', 'Godzilla' );\n\nsub animals ($cat, $dog, $lizard = 'Default reptile') { \n say \"The cat is $cat\";\n say \"The dog is $dog\";\n say \"The lizard is $lizard\";\n }\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6782/" ]
297,035
<p>I am currently faced with a difficult sorting problem. I have a collection of events that need to be sorted against each other (a <a href="http://en.wikipedia.org/wiki/Comparison_sort" rel="nofollow noreferrer">comparison sort</a>) and against their relative position in the list.</p> <p>In the simplest terms I have list of events that each have a priority (integer), a duration (seconds), and an earliest occurrence time that the event can appear in the list. I need to sort the events based on priority, but no event can appear in the list before its earliest occurrence time. Here's an example to (hopefully) make it clearer:</p> <pre><code>// Psuedo C# code class Event { int priority; double duration; double earliestTime ; } void Example() { Event a = new Event { priority = 1, duration = 4.0, earliestTime = 0.0 }; Event b = new Event { priority = 2, duration = 5.0, earliestTime = 6.0 }; Event c = new Event { priority = 3, duration = 3.0, earliestTime = 0.0 }; Event d = new Event { priority = 4, duration = 2.0, earliestTime = 0.0 }; // assume list starts at 0.0 seconds List&lt;Event&gt; results = Sort( new List&lt;Event&gt; { a, b, c, d } ); assert( results[ 0 ] == a ); // 4.0 seconds elapsed assert( results[ 1 ] == c ); // 7.0 seconds elapsed assert( results[ 2 ] == b ); // 12.0 seconds elapsed assert( results[ 3 ] == d ); // 14.0 seconds elapsed } </code></pre> <p>Item "b" has to come last because it isn't allowed to start until 6.0 seconds into the list, so it is deferred and "c" gets to go before "b" even though its priority is lower. (Hopefully the above explains my problem, if not let me know and I'll edit it.)</p> <p>My current idea is to use an <a href="http://en.wikipedia.org/wiki/Insertion_sort" rel="nofollow noreferrer">insertion sort</a> to manage the sorting process. Unlike many of the other common sorting algorithms, insertion sort decides the order of the list one at a time and in order. So for each index I should be able to find the next lowest priority event whose earliest occurrence time will be satisfied.</p> <p>I'm hoping to find resources about sorting algorithms and data structures to help me design a good solution for this "sort" of problem. My real problem is actually more complex than this: hierarchical sorting, variable buffers between events, multiple non-constant time constraints, so the more information or ideas the better. Speed and space are not really a concern. Accuracy in sorting and maintainability of the code are a concern.</p> <p><strong>Edit:</strong> Clarifications (based on comments)</p> <ul> <li>Events consume their entire duration (that is there is no overlap of events allowed)</li> <li>Events <strong>must</strong> occur at or after their earliestTime, they cannot occur before their earliestTime.</li> <li>Events can occur later than their earliestTime if lower priority events exist</li> <li>Events cannot be interrupted</li> <li>There is a maximum duration the sum of all events that can fit in a list. This is not shown above. (In reality the duration of all events will be far greater than the time list's maximum duration.)</li> <li>There cannot be any gaps. (There are no holes to try and back fill.)</li> </ul> <p><strong>Edit:</strong> Answer</p> <p>While David Nehme gave the answer I selected, I wanted to point out that his answer is an insertion sorts at heart, and several other people provided insertions sort type answers. This confirms for me that a specialized insertion sort is probably the way to go. Thanks to all of you for your answers.</p>
[ { "answer_id": 297073, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "event a (priority = 1, start = 5)\nevent b (priority = 2, start = 0)\n a b b a" }, { "answer_id": 297079, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 5, "selected": true, "text": "1|ri;pmtn|Σ wiCi \n unreleased_jobs = jobs // sorted list of jobs, by release date\nreleased_jobs = {} // priority queue of jobs, by priority\nscheduled_jobs = {} // simple list\nwhile (!unreleased_jobs.empty() || !released_jobs.empty()) {\n\n while (unreleased_jobs.top().earliestTime <= t) {\n released_jobs.push(unreleased_jobs.pop())\n }\n if (!released_jobs.empty()) {\n next_job = released_jobs.pop();\n scheduled_jobs.push_back(next_job)\n t = t + next_job.duration\n } else {\n // we have a gap\n t = unreleased_jobs.top().earliestTime\n }\n}\n" }, { "answer_id": 297096, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 0, "selected": false, "text": "class Event : IComparable<Event>, IComparable{\n int priority;\n double duration;\n double earliestTime;\n\n public int CompareTo(Event other){\n if(other == null)\n return 1; /* define: non-null > null */\n\n int cmp = earliestTime.CompareTo(other.earliestTime);\n if(cmp != 0)\n return cmp;\n\n /* earliestTimes were equal, so move on to next comparison */\n return priority.CompareTo(other.priority);\n }\n\n int IComparable.CompareTo(object other){ /* for compatibility with non-generic collections */\n if(other == null)\n return 1; /* define: non-null > null */\n\n Event e_other = other as Event;\n if(e_other == null) /* must have been some other type */\n throw new ArgumentException(\"Must be an Event\", \"other\");\n\n return CompareTo(e_other); /* forward to strongly-typed implementation */\n }\n}\n CompareTo public int CompareTo(Event other){\n if(other == null)\n return 1; /* define: non-null > null */\n\n int cmp = priority.CompareTo(other.priority);\n\n if(cmp == 0)\n /*\n * calculate and compare the time each event will be late\n * if the other one were to start first. This time may be\n * negative if starting one will not make the other one late\n */\n return (earliestTime + duration - other.earliestTime).CompareTo(\n other.earliestTime + other.duration - earliestTime);\n\n /*\n * they're different priorities. if the lower-priority event\n * (presume that greater priority index means lower priority,\n * e.g. priority 4 is \"lower\" priority than priority 1), would\n * would make the higher-priority event late, then order the\n * higher-priority one first. Otherwise, just order them by\n * earliestTime.\n */\n if(cmp < 0){/* this one is higher priority */\n if(earliestTime <= other.earliestTime)\n /* this one must start first */\n return -1;\n\n if(other.earliestTime + other.duration <= earliestTime)\n /* the lower-priority event would not make this one late */\n return 1;\n\n return -1;\n }\n\n /* this one is lower priority */\n if(other.earliestTime <= earliestTime)\n /* the other one must start first */\n return 1;\n\n if(earliestTime + duration <= other.earliestTime)\n /* this event will not make the higher-priority one late */\n return -1;\n\n return 1;\n}\n" }, { "answer_id": 297150, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 0, "selected": false, "text": "Event a = new Event { priority = 1, duration = 1.0, earliestTime = 4.0 };\nEvent b = new Event { priority = 2, duration = 1.0, earliestTime = 4.0 };\nEvent c = new Event { priority = 3, duration = 1.0, earliestTime = 4.0 };\nEvent d = new Event { priority = 4, duration = 1.0, earliestTime = 4.0 };\n" }, { "answer_id": 297228, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 0, "selected": false, "text": "Event a = new Event { priority = 1, duration = 4.0, earliestTime = 1.0 };\nEvent b = new Event { priority = 2, duration = 5.0, earliestTime = 0.0 };\n b a" }, { "answer_id": 297370, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python\nMIN_PRIORITY = 100\n\nclass Event(object):\n def __init__(self, name, priority, duration, earliestTime):\n self.name = name\n self.priority = priority\n self.duration = duration\n self.earliestTime = earliestTime\n def __str__(self):\n return \"%-10s: P %3d D %3.1f T %3.1f\" % (self.name, self.priority, self.duration, self.earliestTime)\n\ndef sortEvents(_events):\n def comparePriority(event1, event2):\n if event1.priority < event2.priority: return -1\n if event1.priority > event2.priority: return 1\n return 0\n\n # Get a copy of the events and sort by priority\n events = [e for e in _events]\n events.sort(cmp=comparePriority)\n\n # Select one event at a time, checking for compatibility with elapsed time\n elapsedTime = 0.0\n sortedEvents = []\n while events:\n minGap = events[0].earliestTime - elapsedTime\n for e in events:\n currentGap = e.earliestTime - elapsedTime\n if currentGap < minGap:\n minGap = currentGap\n if currentGap <= 0.0:\n sortedEvents.append(e)\n elapsedTime += e.duration\n events.remove(e)\n break\n\n # If none of the events fits, add a suitable gap\n if minGap > 0:\n sortedEvents.append( Event(\"gap\", MIN_PRIORITY, minGap, elapsedTime) )\n elapsedTime += minGap\n return sortedEvents\n\nif __name__ == \"__main__\":\n #e1 = Event(\"event1\", 1, 1.0, 4.0)\n #e2 = Event(\"event2\", 2, 1.0, 6.0)\n #e3 = Event(\"event3\", 3, 1.0, 8.0)\n #e4 = Event(\"event4\", 4, 1.0, 10.0)\n\n e1 = Event(\"event1\", 1, 4.0, 0.0)\n e2 = Event(\"event2\", 2, 5.0, 6.0)\n e3 = Event(\"event3\", 3, 3.0, 0.0)\n e4 = Event(\"event4\", 4, 2.0, 0.0)\n\n events = [e1, e2, e3, e4]\n\n print \"Before:\"\n for event in events: print event\n sortedEvents = sortEvents(events)\n print \"\\nAfter:\"\n for event in sortedEvents: print event\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11889/" ]
297,048
<p>What is the best method to determine if a user has viewed a piece of data, ie like an update to a comment. The two solutions I have thought about are these....</p> <ol> <li><p>Use a separate table that has a row for each user and the data id that is being viewed and inserting into when the item was last viewed.</p></li> <li><p>Use the same table and add a row for every user when the item is changed and delete that row when the user actually views the data.</p></li> </ol> <p>Both methods solve the problem but in solution 2 the maximum rows for the table would at worst equal that of solution 1, no one viewed anything, and at best has 0 rows, everything has been viewed. I know in solution 2 you have no way to determine when it was viewed.</p> <p>Thoughts? </p> <p>Edit: I was using an update to a comment as an example. In the actual application, new users wouldn't be expected to view or read old data. It would mean nothing to them for they just joined. </p>
[ { "answer_id": 297083, "author": "Kyle West", "author_id": 34133, "author_profile": "https://Stackoverflow.com/users/34133", "pm_score": 2, "selected": false, "text": "select count(*) from DataAlerts where dataid = 1 and userid = 1\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342514/" ]
297,063
<p>I'm still trying to get my head around using Java's generics. I have no problems at all with using typed collections, but much of the rest of it just seems to escape me.</p> <p>Right now I'm trying to use the JUnit "PrivateAccessor", which requires a Class[] argument with a list of all the argument types for the private method being called. In Java 1.4, I'd define that as</p> <pre><code>Class[] args = new Class[] { Collection.class, ArrayList.class }; </code></pre> <p>but the actual code is defined to now take the arguments</p> <pre><code>myMethod(Collection&lt;MyClass1&gt; first, ArrayList&lt;MyClass2&gt; second) </code></pre> <p>I tried to change the definition of args to be</p> <pre><code>Class&lt;? extends Object&gt;[] args = new Class&lt;? extends Object&gt;[] { Collection&lt;MyClass1&gt;.class, ArrayList&lt;MyClass2&gt;.class }; </code></pre> <p>But Eclipse puts a red marker on the closing >s, and says it's expecting "void" at that point. Can I do this using generics, or shouldn't I bother?</p>
[ { "answer_id": 297138, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "Class<?>[] paramTypes = new Class[]{ Collection.class, ArrayList.class };\n" }, { "answer_id": 297170, "author": "bdumitriu", "author_id": 35415, "author_profile": "https://Stackoverflow.com/users/35415", "pm_score": 4, "selected": true, "text": "Class<?>[] args = new Class[]\n Class<? extends Object>[] args = new Class<? extends Object>[]\n { Collection.class, ArrayList.class };\n { Collection<MyClass1>.class, ArrayList<MyClass2>.class };\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ]
297,064
<p>This one has me beat;</p> <p>I have a WPF window with two (important for this case) controls, both from the WPF toolkit available at CodePlex; A DatePicker and a DataGrid.</p> <p>The DataContext of this window is set to a CLR object that has all the information it needs. This CLR object has a large list of data, and a method called GetDataForDate( DateTime date ) which decides which date we will see data for.</p> <p>How can I create a ObjectDataProvider (which I assume will be the correct solution) that the datagrid can bind to, which provides access to the data returned by GetDataForDate() called with the selected date of the DatePicker as the parameter?</p> <p>In other words, I want the user to use the datepicker to choose a date, and the grid should automatically update whenever the date is changed to reflect the correct data.</p> <p>What kind of black magic do I have to do to achieve something like this - which I would guess should be a relatively common databinding scenario?</p> <p>Thanks in advance!</p>
[ { "answer_id": 297186, "author": "Sacha Bruttin", "author_id": 20761, "author_profile": "https://Stackoverflow.com/users/20761", "pm_score": 1, "selected": false, "text": " <ObjectDataProvider ObjectType=\"{x:Type theObjectType}\" \n MethodName=\"GetDataForDate\"\n x:Key=\"odp\">\n <ObjectDataProvider.MethodParameters>\n <System:DateTime>2008-01-01</System:DateTime> \n </ObjectDataProvider.MethodParameters>\n </ObjectDataProvider>\n <dg:DatePicker x:Name=\"datePicker\" >\n <dg:DatePicker.SelectedDate>\n <Binding Source=\"{StaticResource odp}\"\n Path=\"MethodParameters[0]\" \n BindsDirectlyToSource=\"True\" \n Mode=\"OneWayToSource\"/>\n </dg:DatePicker.SelectedDate>\n</dg:DatePicker>\n <dg:DataGrid x:Name=\"dtgGrid\"\n ItemsSource=\"{Binding Source={StaticResource odp}}\"\n AutoGenerateColumns=\"False\"/>\n" }, { "answer_id": 315899, "author": "Sacha Bruttin", "author_id": 20761, "author_profile": "https://Stackoverflow.com/users/20761", "pm_score": 4, "selected": true, "text": "<Window x:Class=\"DataGridSort.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:dg=\"clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit\"\n xmlns:System=\"clr-namespace:System;assembly=mscorlib\"\n Title=\"Window1\" Height=\"413\" Width=\"727\"\n x:Name=\"_this\">\n <Window.Resources>\n <ObjectDataProvider ObjectInstance=\"_this.DataContext\"\n MethodName=\"GetFromDate\"\n x:Key=\"odp\">\n <ObjectDataProvider.MethodParameters>\n <System:DateTime>2008-01-01</System:DateTime> \n </ObjectDataProvider.MethodParameters>\n </ObjectDataProvider>\n </Window.Resources>\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"*\"/>\n </Grid.RowDefinitions>\n\n <dg:DatePicker Grid.Row=\"0\" x:Name=\"dtpSource\" >\n <dg:DatePicker.SelectedDate>\n <Binding Source=\"{StaticResource odp}\"\n Path=\"MethodParameters[0]\" \n BindsDirectlyToSource=\"True\" \n Mode=\"OneWayToSource\"/>\n </dg:DatePicker.SelectedDate>\n </dg:DatePicker>\n\n <dg:DataGrid x:Name=\"dtgGrid\"\n ItemsSource=\"{Binding Source={StaticResource odp}}\"\n AutoGenerateColumns=\"True\"\n Grid.Row=\"1\"/>\n </Grid>\n</Window>\n public partial class Window1 : Window\n{\n public Window1()\n {\n InitializeComponent();\n\n LoadData();\n }\n\n protected void LoadData()\n {\n DataContext = new Data();\n ObjectDataProvider odp = this.Resources[\"odp\"] as ObjectDataProvider;\n\n odp.ObjectInstance = DataContext;\n }\n}\n public class DataItem\n{\n public string Name { get; set; }\n public int BirthYear { get; set; }\n}\n\npublic class Data\n{\n private readonly List<DataItem> data;\n\n public Data()\n {\n data = new List<DataItem>();\n data.Add(new DataItem { Name = \"John\", BirthYear = 2007 });\n data.Add(new DataItem { Name = \"Mike\", BirthYear = 2007 });\n data.Add(new DataItem { Name = \"Aaron\", BirthYear = 2006 });\n data.Add(new DataItem { Name = \"Bill\", BirthYear = 2006 });\n data.Add(new DataItem { Name = \"Steven\", BirthYear = 2005 });\n data.Add(new DataItem { Name = \"George\", BirthYear = 2004 });\n data.Add(new DataItem { Name = \"Britany\", BirthYear = 2004 });\n }\n\n public List<DataItem> GetFromDate(DateTime dt)\n {\n return this.data.Where(d => d.BirthYear == dt.Year).ToList();\n }\n}\n" }, { "answer_id": 364525, "author": "a_hardin", "author_id": 1497, "author_profile": "https://Stackoverflow.com/users/1497", "pm_score": 0, "selected": false, "text": "public class MyDataObject : INotifyPropertyChanged\n{\n private DateTime _SelectedDate;\n public DateTime SelectedDate\n {\n get\n {\n return _SelectedDate;\n }\n set\n {\n _SelectedDate = value;\n NotifyPropertyChanged(\"SelectedDate\");\n GetDataForDate();\n }\n }\n\n private ObservableCollection<YourDataType> _Data;\n public ObservableCollection<YourDataType> Data\n {\n get\n {\n return _Data;\n }\n set\n {\n _Data = value;\n NotifyPropertyChanged(\"Data\");\n }\n }\n\n public void GetDataForDate()\n {\n // Your code here to fill the Data object with your data\n }\n\n\n #region INotifyPropertyChanged Members\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n private void NotifyPropertyChanged(string propertyName)\n {\n if (this.PropertyChanged != null)\n this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n\n #endregion\n}\n <ObjectDataProvider x:Key=\"MyDataSource\" ObjectType=\"{x:Type local:MyDataObject}\" />\n <DockPanel>\n <toolkit:DatePicker SelectedDate=\"{Binding Path=SelectedDate, Mode=Default, Source={StaticResource MyDataSource}}\"/>\n <toolkit:DataGrid ItemsSource=\"{Binding Path=Data, Mode=Default, Source={StaticResource MyDataSource}}\"/>\n</DockPanel>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2122/" ]
297,068
<p>Normally, the method of passing workflow parameters to the workflow happens in the call to RunWorkflow. However, with the WorkflowServiceHost, there is no such method call involved. You simply call the Open() method on the instance. Any ideas?</p> <p>Of course, the implication is that I add more parameters to the service contract, but these parameters are not relevant for the consumers of the service. They are more like configuration values. </p>
[ { "answer_id": 297186, "author": "Sacha Bruttin", "author_id": 20761, "author_profile": "https://Stackoverflow.com/users/20761", "pm_score": 1, "selected": false, "text": " <ObjectDataProvider ObjectType=\"{x:Type theObjectType}\" \n MethodName=\"GetDataForDate\"\n x:Key=\"odp\">\n <ObjectDataProvider.MethodParameters>\n <System:DateTime>2008-01-01</System:DateTime> \n </ObjectDataProvider.MethodParameters>\n </ObjectDataProvider>\n <dg:DatePicker x:Name=\"datePicker\" >\n <dg:DatePicker.SelectedDate>\n <Binding Source=\"{StaticResource odp}\"\n Path=\"MethodParameters[0]\" \n BindsDirectlyToSource=\"True\" \n Mode=\"OneWayToSource\"/>\n </dg:DatePicker.SelectedDate>\n</dg:DatePicker>\n <dg:DataGrid x:Name=\"dtgGrid\"\n ItemsSource=\"{Binding Source={StaticResource odp}}\"\n AutoGenerateColumns=\"False\"/>\n" }, { "answer_id": 315899, "author": "Sacha Bruttin", "author_id": 20761, "author_profile": "https://Stackoverflow.com/users/20761", "pm_score": 4, "selected": true, "text": "<Window x:Class=\"DataGridSort.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:dg=\"clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit\"\n xmlns:System=\"clr-namespace:System;assembly=mscorlib\"\n Title=\"Window1\" Height=\"413\" Width=\"727\"\n x:Name=\"_this\">\n <Window.Resources>\n <ObjectDataProvider ObjectInstance=\"_this.DataContext\"\n MethodName=\"GetFromDate\"\n x:Key=\"odp\">\n <ObjectDataProvider.MethodParameters>\n <System:DateTime>2008-01-01</System:DateTime> \n </ObjectDataProvider.MethodParameters>\n </ObjectDataProvider>\n </Window.Resources>\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"*\"/>\n </Grid.RowDefinitions>\n\n <dg:DatePicker Grid.Row=\"0\" x:Name=\"dtpSource\" >\n <dg:DatePicker.SelectedDate>\n <Binding Source=\"{StaticResource odp}\"\n Path=\"MethodParameters[0]\" \n BindsDirectlyToSource=\"True\" \n Mode=\"OneWayToSource\"/>\n </dg:DatePicker.SelectedDate>\n </dg:DatePicker>\n\n <dg:DataGrid x:Name=\"dtgGrid\"\n ItemsSource=\"{Binding Source={StaticResource odp}}\"\n AutoGenerateColumns=\"True\"\n Grid.Row=\"1\"/>\n </Grid>\n</Window>\n public partial class Window1 : Window\n{\n public Window1()\n {\n InitializeComponent();\n\n LoadData();\n }\n\n protected void LoadData()\n {\n DataContext = new Data();\n ObjectDataProvider odp = this.Resources[\"odp\"] as ObjectDataProvider;\n\n odp.ObjectInstance = DataContext;\n }\n}\n public class DataItem\n{\n public string Name { get; set; }\n public int BirthYear { get; set; }\n}\n\npublic class Data\n{\n private readonly List<DataItem> data;\n\n public Data()\n {\n data = new List<DataItem>();\n data.Add(new DataItem { Name = \"John\", BirthYear = 2007 });\n data.Add(new DataItem { Name = \"Mike\", BirthYear = 2007 });\n data.Add(new DataItem { Name = \"Aaron\", BirthYear = 2006 });\n data.Add(new DataItem { Name = \"Bill\", BirthYear = 2006 });\n data.Add(new DataItem { Name = \"Steven\", BirthYear = 2005 });\n data.Add(new DataItem { Name = \"George\", BirthYear = 2004 });\n data.Add(new DataItem { Name = \"Britany\", BirthYear = 2004 });\n }\n\n public List<DataItem> GetFromDate(DateTime dt)\n {\n return this.data.Where(d => d.BirthYear == dt.Year).ToList();\n }\n}\n" }, { "answer_id": 364525, "author": "a_hardin", "author_id": 1497, "author_profile": "https://Stackoverflow.com/users/1497", "pm_score": 0, "selected": false, "text": "public class MyDataObject : INotifyPropertyChanged\n{\n private DateTime _SelectedDate;\n public DateTime SelectedDate\n {\n get\n {\n return _SelectedDate;\n }\n set\n {\n _SelectedDate = value;\n NotifyPropertyChanged(\"SelectedDate\");\n GetDataForDate();\n }\n }\n\n private ObservableCollection<YourDataType> _Data;\n public ObservableCollection<YourDataType> Data\n {\n get\n {\n return _Data;\n }\n set\n {\n _Data = value;\n NotifyPropertyChanged(\"Data\");\n }\n }\n\n public void GetDataForDate()\n {\n // Your code here to fill the Data object with your data\n }\n\n\n #region INotifyPropertyChanged Members\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n private void NotifyPropertyChanged(string propertyName)\n {\n if (this.PropertyChanged != null)\n this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n\n #endregion\n}\n <ObjectDataProvider x:Key=\"MyDataSource\" ObjectType=\"{x:Type local:MyDataObject}\" />\n <DockPanel>\n <toolkit:DatePicker SelectedDate=\"{Binding Path=SelectedDate, Mode=Default, Source={StaticResource MyDataSource}}\"/>\n <toolkit:DataGrid ItemsSource=\"{Binding Path=Data, Mode=Default, Source={StaticResource MyDataSource}}\"/>\n</DockPanel>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5573/" ]
297,070
<p>I'm looking for Java code that can be used to generate sound at runtime - NOT playback of existing sound files.</p> <p>For example, what's the best code for generating a sawtooth waveform at 440 Hz for a duration of 2 milliseconds? <b>Source code appreciated!</b></p> <p>I remember my Commodore 128 had a simple Sound command that took as parameters voice, frequency, waveform, and duration to define a sound. That worked great in a lot of simple cases (quick and dirty games, experiments with sound, etc).</p> <p>I am looking specifically for sound-effect like sounds, not music or MIDI (which the <a href="http://www.jfugue.org" rel="noreferrer">JFugue</a> library covers quite well).</p>
[ { "answer_id": 376209, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 4, "selected": true, "text": "// in hz, number of samples in one second\nsampleRate = 44100\n\n// this is the time BETWEEN Samples\nsamplePeriod = 1.0 / sampleRate\n\n// 2ms\nduration = 0.002;\ndurationInSamples = Math.ceil(duration * sampleRate);\n\ntime = 0;\nfor(int i = 0; i < durationInSamples; i++)\n{\n // sample a sine wave at 440 hertz at each time tick\n // substitute a function that generates a sawtooth as a function of time / freq\n // rawOutput[i] = function_of_time(other_relevant_info, time);\n rawOutput[i] = Math.sin(2 * Math.PI * 440 * time);\n time += samplePeriod;\n}\n\n// now you can playback the rawOutput\n// streaming this may be trickier\n" }, { "answer_id": 11974521, "author": "cvezga", "author_id": 1601314, "author_profile": "https://Stackoverflow.com/users/1601314", "pm_score": 3, "selected": false, "text": "package notegenerator;\n\nimport java.io.IOException;\n\n/**\n * Tone generator and player.\n * \n * @author Cesar Vezga vcesar@yahoo.com\n */\npublic class Main {\n\npublic static void main(String[] args) throws IOException {\n\n Player player = new Player();\n\n player.play(BeachRock.getTack1(),BeachRock.getTack2());\n\n}\n\n }\n package notegenerator;\n\n public class BeachRock {\n\n// GUITAR\nstatic String gs1 = \"T332 A4-E4 F#5-C6 E5-A5 T166 G5 A5 F#5 A5 F5 A5 E5-A5 E3 G3 G#3 \";\nstatic String gs2 = \"A3 A3 A3 G3 E3 E3 G3 G#3 \";\nstatic String gs3 = \"A3 A3 A3 G3 E3 A3 C4 C#4 \";\nstatic String gs4 = gs2 + gs2 + gs2 + gs3;\nstatic String gs5 = \"D4 D4 D4 C4 A3 A3 C4 D#4 \";\nstatic String gs6 = \"D4 D4 D4 C4 A3 E3 G3 G#3 \";\nstatic String gs7 = gs4 + gs5 + gs6 + gs2 + \"A3 A3 A3 G3 E3 B3 D3 D#3 \";\nstatic String gs8 = \"E4 E4 E4 D4 B3 B3 E4 B3 \" + gs6 + gs2;\nstatic String gs9 = \"x E3-B3 E3-B3 E3-B3 E3-B3 E3 G3 G#3 \";\nstatic String gs10 = gs7 + gs8 + gs9;\nstatic String gs11 = \"A3-D4 X*7 X*16 X*5 E3 G3 G#3 \";\nstatic String guitar = gs1 + gs10 + gs11 + gs10 + gs11 + \"A3 A3 A3\";\n\n// DRUMS\nstatic String ds1 = \"D2 X D3 D3 X*2 D3 X \";\nstatic String ds2 = \"D2 X D3 D3 X D3 D3 D3 \";\nstatic String ds3 = \"D2 D3 D3 D3 D3 T83 D3 D3 T166 D3 \";\nstatic String ds4 = ds1 + ds1 + ds1 + ds2;\nstatic String ds5 = ds1 + ds1 + ds1 + ds3;\nstatic String ds6 = \"D2*2 D3 D3 X*2 D3*2 \";\nstatic String ds7 = \"D2*2 D3 D3 X D3 D3 D3 \";\nstatic String ds8 = ds6 + ds6 + ds6 + ds7;\n\nstatic String drums = \"V25 T166 X*16 \" + ds4 + ds4 + ds5 + ds8 + ds4 + ds4\n + ds5 + ds8;\n\npublic static String getTack1(){\n return guitar;\n}\n\npublic static String getTack2(){\n return drums;\n}\n\n\n}\n package notegenerator;\n\nimport java.util.HashMap;\n\n/**\n * \n * Physics of Music - Notes\n * \n * Frequencies for equal-tempered scale\n * This table created using A4 = 440 Hz\n * Speed of sound = 345 m/s = 1130 ft/s = 770 miles/hr\n * \n * (\"Middle C\" is C4 )\n * \n * http://www.phy.mtu.edu/~suits/notefreqs.html\n * \n * @author Cesar Vezga <vcesar@yahoo.com>\n *\n */\n public class Notes {\n\n\nprivate static final Object[] notes = {\n\"C0\",16.35,\n\"C#0/Db0\",17.32,\n\"D0\",18.35,\n\"D#0/Eb0\",19.45,\n\"E0\",20.6,\n\"F0\",21.83,\n\"F#0/Gb0\",23.12,\n\"G0\",24.5,\n\"G#0/Ab0\",25.96,\n\"A0\",27.5,\n\"A#0/Bb0\",29.14,\n\"B0\",30.87,\n\"C1\",32.7,\n\"C#1/Db1\",34.65,\n\"D1\",36.71,\n\"D#1/Eb1\",38.89,\n\"E1\",41.2,\n\"F1\",43.65,\n\"F#1/Gb1\",46.25,\n\"G1\",49.00,\n\"G#1/Ab1\",51.91,\n\"A1\",55.00,\n\"A#1/Bb1\",58.27,\n\"B1\",61.74,\n\"C2\",65.41,\n\"C#2/Db2\",69.3,\n\"D2\",73.42,\n\"D#2/Eb2\",77.78,\n\"E2\",82.41,\n\"F2\",87.31,\n\"F#2/Gb2\",92.5,\n\"G2\",98.00,\n\"G#2/Ab2\",103.83,\n\"A2\",110.00,\n\"A#2/Bb2\",116.54,\n\"B2\",123.47,\n\"C3\",130.81,\n\"C#3/Db3\",138.59,\n\"D3\",146.83,\n\"D#3/Eb3\",155.56,\n\"E3\",164.81,\n\"F3\",174.61,\n\"F#3/Gb3\",185.00,\n\"G3\",196.00,\n\"G#3/Ab3\",207.65,\n\"A3\",220.00,\n\"A#3/Bb3\",233.08,\n\"B3\",246.94,\n\"C4\",261.63, // Middle C\n\"C#4/Db4\",277.18,\n\"D4\",293.66,\n\"D#4/Eb4\",311.13,\n\"E4\",329.63,\n\"F4\",349.23,\n\"F#4/Gb4\",369.99,\n\"G4\",392.00,\n\"G#4/Ab4\",415.3,\n\"A4\",440.00,\n\"A#4/Bb4\",466.16,\n\"B4\",493.88,\n\"C5\",523.25,\n\"C#5/Db5\",554.37,\n\"D5\",587.33,\n\"D#5/Eb5\",622.25,\n\"E5\",659.26,\n\"F5\",698.46,\n\"F#5/Gb5\",739.99,\n\"G5\",783.99,\n\"G#5/Ab5\",830.61,\n\"A5\",880.00,\n\"A#5/Bb5\",932.33,\n\"B5\",987.77,\n\"C6\",1046.5,\n\"C#6/Db6\",1108.73,\n\"D6\",1174.66,\n\"D#6/Eb6\",1244.51,\n\"E6\",1318.51,\n\"F6\",1396.91,\n\"F#6/Gb6\",1479.98,\n\"G6\",1567.98,\n\"G#6/Ab6\",1661.22,\n\"A6\",1760.00,\n\"A#6/Bb6\",1864.66,\n\"B6\",1975.53,\n\"C7\",2093.00,\n\"C#7/Db7\",2217.46,\n\"D7\",2349.32,\n\"D#7/Eb7\",2489.02,\n\"E7\",2637.02,\n\"F7\",2793.83,\n\"F#7/Gb7\",2959.96,\n\"G7\",3135.96,\n\"G#7/Ab7\",3322.44,\n\"A7\",3520.00,\n\"A#7/Bb7\",3729.31,\n\"B7\",3951.07,\n\"C8\",4186.01,\n\"C#8/Db8\",4434.92,\n\"D8\",4698.64,\n\"D#8/Eb8\",4978.03\n\n};\n\nprivate HashMap<String,Double> noteMap;\n\npublic Notes(){\n noteMap = new HashMap<String,Double>();\n for(int i=0; i<notes.length; i=i+2){\n String name = (String)notes[i];\n double freq = (Double)notes[i+1];\n String[] keys = name.split(\"/\");\n for(String key : keys){\n noteMap.put(key, freq);\n System.out.println(key);\n }\n }\n}\n\n\npublic byte[] getCordData(String keys, double duration){\n int N = (int) (8000 * duration/1000);\n byte[] a = new byte[N+1];\n String[] key = keys.split(\" \");\n int count=0;\n for(String k : key){\n double freq = getFrequency(k);\n byte[] tone = tone(freq,duration);\n if(count==0){\n a = tone;\n }else{\n a = addWaves(a,tone);\n }\n count++;\n }\n\n return a;\n}\n\n\npublic byte[] addWaves(byte[] a, byte[] b){\n int len = Math.max(a.length, b.length);\n byte[] c = new byte[len];\n for(int i=0; i<c.length; i++){\n byte aa = ( i < a.length ? a[i] : 0);\n byte bb = ( i < b.length ? b[i] : 0);\n\n c[i] = (byte) (( aa + bb ) / 2);\n }\n return c;\n}\n\n\npublic double getFrequency(String key){\n Double f = noteMap.get(key);\n if(f==null){\n System.out.println(\"Key not found. \"+key);\n f = 0D;\n }\n return f;\n}\n\npublic byte[] tone(String key, double duration) {\n double freq = getFrequency(key);\n\n return tone(freq,duration); \n } \n\n public byte[] tone(double hz, double duration) {\n int N = (int) (8000 * duration/1000);\n byte[] a = new byte[N+1];\n for (int i = 0; i <= N; i++) {\n a[i] = (byte) ( Math.sin(2 * Math.PI * i * hz / 8000) * 127 );\n }\n return a; \n } \n\n\n}\n package notegenerator;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.DataLine;\nimport javax.sound.sampled.LineUnavailableException;\nimport javax.sound.sampled.SourceDataLine;\n\npublic class Player {\n\nprivate SourceDataLine line = null;\n\nprivate Notes notes = new Notes();\n\nprivate long time = 250;\n\nprivate double volumen = 1;\n\npublic void play(String keys) {\n\n byte[] data = parse(keys);\n\n start();\n\n line.write(data, 0, data.length);\n\n stop();\n\n}\n\npublic void play(String... track) {\n\n byte[] data2 = parseAll(track);\n\n if (data2 != null) {\n start();\n\n line.write(data2, 0, data2.length);\n\n stop();\n }\n\n}\n\nprivate byte[] parseAll(String... track) {\n\n byte[] data2 = null;\n\n for (String t : track) {\n byte[] data1 = parse(t);\n if (data2 == null) {\n data2 = data1;\n } else {\n data2 = notes.addWaves(data1, data2);\n }\n }\n\n return data2;\n\n}\n\nprivate byte[] parse(String song) {\n time = 250;\n\n volumen = 1;\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n String[] key = song.split(\" \");\n\n byte[] data = null;\n\n for (String k : key) {\n int mult = 1;\n\n if (k.indexOf(\"*\") > -1) {\n String keyAux = k.split(\"\\\\*\")[0];\n mult = Integer.parseInt(k.split(\"\\\\*\")[1]);\n k = keyAux;\n } else if (k.startsWith(\"T\")) {\n time = Long.parseLong(k.substring(1));\n continue;\n } else if (k.startsWith(\"V\")) {\n volumen = Double.parseDouble(k.substring(1)) / 100;\n\n if(volumen>1) volumen = 1;\n if(volumen<0) volumen = 0;\n\n continue;\n }\n\n if (k.indexOf(\"-\") > -1) {\n k = k.replaceAll(\"-\", \" \").trim();\n data = notes.getCordData(k, time * mult);\n } else {\n data = notes.tone(k, time * mult);\n }\n\n volumen(data);\n\n try {\n baos.write(data);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n }\n\n return baos.toByteArray();\n\n}\n\n\n\nprivate void volumen(byte[] data) {\n for(int i=0; i<data.length; i++){\n data[i] = (byte) (data[i] * volumen);\n }\n\n}\n\nprivate void stop() {\n line.drain();\n line.stop();\n\n}\n\nprivate void start() {\n\n AudioFormat format = new AudioFormat(8000.0F, 8, 1, true, false);\n\n SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class,\n format); // format\n // is\n // an\n // AudioFormat\n // object\n if (!AudioSystem.isLineSupported(info)) {\n System.out.println(\"Format not supported\");\n System.exit(1);\n }\n\n // Obtain and open the line.\n try {\n line = (SourceDataLine) AudioSystem.getLine(info);\n line.open(format);\n } catch (LineUnavailableException ex) {\n ex.printStackTrace();\n }\n\n // Assume that the TargetDataLine, line, has already\n // been obtained and opened.\n int numBytesRead;\n\n line.start();\n\n}\n\npublic void save(String track, String fname) throws IOException {\n byte[] data = parse(track);\n\n FileOutputStream fos = new FileOutputStream(fname);\n\n fos.write(data);\n fos.flush();\n fos.close();\n\n}\n\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197/" ]
297,081
<p>I am trying to RegisterClientScriptBlock in a method that is only called via an AJAX call. It doesn't appear to actually register the script on the page and I'm guessing this is because it's not actually reloading the entire page. Is there any way to register javascript on a page from within an ajax method call?</p> <pre><code> protected void MyMethod(object sender, EventArgs e) { // This method only called via AJAX call Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "resize", "alert('here');", true); } </code></pre>
[ { "answer_id": 297291, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 5, "selected": true, "text": "ScriptManager.RegisterClientScriptBlock(Page, typeof(MyPage), \n \"MyScript\", \"GoStuff()\", true)\n" }, { "answer_id": 6284233, "author": "Mark Brito", "author_id": 760119, "author_profile": "https://Stackoverflow.com/users/760119", "pm_score": 2, "selected": false, "text": "UpdatePanel ScriptManager.RegisterClientScriptBlock(UpdatePanelMain, typeof(UpdatePanel),\n UpdatePanelMain.ClientID,\n \"document.getElementById('imgLoading').style.display = 'none';\" +\n \"document.getElementById('divMultiView').style.display = 'inline';\",\n true);\n" }, { "answer_id": 19796500, "author": "FastTrack", "author_id": 1077670, "author_profile": "https://Stackoverflow.com/users/1077670", "pm_score": 0, "selected": false, "text": "WebMsgBox.Show(\"Your message here\");\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24908/" ]
297,084
<p>We're running into performance issues with our implementation of Team Foundation Build Server and I'm running out of ideas on how to speed things up. We've already added a few PropertyGroup elements to increase the performance on several steps (SkipClean, SkipLabel, SkipInitializeWorkspace), but I think we need to undergo a major restructuring to fix things. Here's our setup:</p> <ul> <li>We've got about 40 web applications that are each very different, but run off a bunch of shared assemblies</li> <li>Each of these web applications has their own solution;</li> <li>There are around 10 to 25 shared assemblies referenced by each of these web applications;</li> <li>There exists a build definition containing all the solutions which is fired on each check-in to the trunk;</li> </ul> <p>And here's the basic problems we're encountering</p> <ul> <li>During the build, it will build each shared assembly as many times as it is referenced, rather than building once and using for each app</li> <li>File copy time is reeeeally slow for the drop directory. It has to be over network share and won't take a local path.</li> <li>Every so many builds, one or more of the output files gets "locked" and causes the build to break even if compilation is fine.</li> <li>And another thing - I've also tried separate build definitions, but doing so will also force another workspace to be gotten on Get Latest version. I'd much rather have it be that the build server contains one version of the trunk to build off of.</li> </ul> <p>Over the last several months we've given in to lethargy and ignored this problem, but now the build time is over an hour to an hour and a half.</p> <p>I'm toying around with the idea of learning and switching to Cruise Control for the greater control I'd have. Anyone disagree with that?</p> <p>Any help is most appreciated. Thanks!</p>
[ { "answer_id": 352650, "author": "Chad Gilbert", "author_id": 34409, "author_profile": "https://Stackoverflow.com/users/34409", "pm_score": 2, "selected": false, "text": "<Target Name=\"CoreDropBuild\"\n Condition=\" '$(SkipDropBuild)'!='true' and '$(IsDesktopBuild)'!='true' \"\n DependsOnTargets=\"$(CoreDropBuildDependsOn)\" >\n <Exec Command=\"move $(BinariesRoot)\\Release d:\\BuildOutput\\$(BuildNumber)\\Release\"/> \n</Target>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34409/" ]
297,111
<p>Can anyone point me to an example of how to use ServletUnit to test JSP's? Do I need I need to call registerServlet()? If so, what class name do I pass?</p>
[ { "answer_id": 1798413, "author": "user142435", "author_id": 142435, "author_profile": "https://Stackoverflow.com/users/142435", "pm_score": 3, "selected": true, "text": "<dependency>\n <groupId>tomcat</groupId>\n <artifactId>jasper</artifactId>\n <version>3.3.2</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>tomcat</groupId>\n <artifactId>jasper-compiler</artifactId>\n <version>5.5.23</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>tomcat</groupId>\n <artifactId>tomcat-util</artifactId>\n <version>5.5.23</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>tomcat</groupId>\n <artifactId>core_util</artifactId>\n <version>3.3.2</version>\n <scope>test</scope>\n</dependency>\n" }, { "answer_id": 23565544, "author": "kszosze", "author_id": 3596537, "author_profile": "https://Stackoverflow.com/users/3596537", "pm_score": 0, "selected": false, "text": " <!-- Testing JSP -->\n<dependency>\n <groupId>net.sourceforge.openutils</groupId>\n <artifactId>openutils-testing4web</artifactId>\n <version>1.2.1</version>\n <scope>test</scope>\n <exclusions>\n <exclusion>\n <artifactId>slf4j-log4j12</artifactId>\n <groupId>org.slf4j</groupId>\n </exclusion>\n <exclusion>\n <artifactId>spring-core</artifactId>\n <groupId>org.springframework</groupId>\n </exclusion>\n <exclusion>\n <artifactId>spring-context</artifactId>\n <groupId>org.springframework</groupId>\n </exclusion>\n <exclusion>\n <artifactId>slf4j-api</artifactId>\n <groupId>org.slf4j</groupId>\n </exclusion>\n <exclusion>\n <artifactId>jcl-over-slf4j</artifactId>\n <groupId>org.slf4j</groupId>\n </exclusion>\n <exclusion>\n <artifactId>jsp-api</artifactId>\n <groupId>javax.servlet</groupId>\n </exclusion>\n <exclusion>\n <artifactId>jasper-runtime</artifactId>\n <groupId>tomcat</groupId>\n </exclusion>\n <exclusion>\n <artifactId>jasper-compiler</artifactId>\n <groupId>tomcat</groupId>\n </exclusion>\n <exclusion>\n <artifactId>jasper-compiler-jdt</artifactId>\n <groupId>tomcat</groupId>\n </exclusion>\n </exclusions>\n</dependency>\n<dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>catalina</artifactId>\n <version>${tomcat.version}</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>servlet-api</artifactId>\n <version>${tomcat.version}</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>jasper</artifactId>\n <version>${tomcat.version}</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>jasper-el</artifactId>\n <version>${tomcat.version}</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>jsp-api</artifactId>\n <version>${tomcat.version}</version>\n <scope>provided</scope>\n</dependency>\n<dependency>\n <groupId>javax.servlet</groupId>\n <artifactId>javax.servlet-api</artifactId>\n <version>${javax.servlet.version}</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>jasper-jdt</artifactId>\n <version>6.0.29</version>\n <scope>test</scope>\n</dependency>\n<!-- log configuration -->\n import it.openutils.testing.junit.AbstractDbUnitJunitSpringContextTests;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.runner.RunWith;\nimport org.springframework.core.io.Resource;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.TestExecutionListeners;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\nimport org.springframework.test.context.support.DependencyInjectionTestExecutionListener;\nimport org.springframework.test.context.support.DirtiesContextTestExecutionListener;\nimport org.springframework.test.context.transaction.TransactionalTestExecutionListener;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport com.meterware.servletunit.ServletRunner;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@ContextConfiguration(locations = { \"/integration/application-database-test.xml\", \"/integration/mvc-dispatcher-servlet-test.xml\" })\n@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class })\npublic abstract class ControllerIntegrationCommonTest extends AbstractDbUnitJunitSpringContextTests\n{\n\n /**\n * The Web CLient for JSP rendeting Test\n */\n\n\n protected ServletRunner servletRunner;\n\n /**\n * @throws java.lang.Exception\n */\n @Before\n public void setUp() throws Exception\n {\n Resource web = this.applicationContext.getResource(\"/WEB-INF/web.xml\");\n if (servletRunner == null)\n {\n servletRunner = new ServletRunner(web.getFile(),null);\n }\n }\n\n @After\n public void setDown() throws Exception\n {\n servletRunner.shutDown();\n }\n\n}\n PostMethodWebRequest webRequest = new PostMethodWebRequest(\"http://myserver/setup/checkXML\",true);\n webRequest.setParameter(\"param1\", \"11112\");\n File file = new File(\"src/test/resources/datasets/myxml.xml\");\n webRequest.selectFile(\"fileData\",file,\"multipart/form-data\");\n\n WebResponse webResponse = servletRunner.getResponse(webRequest);\n\n assertNotNull(webResponse);\n assertTrue(webResponse.getURL().getPath().contains(\"checkXML\"));\n assertNotNull(webResponse.getElementsByTagName(\"resultCheck\"));\n log.debug(\" ----------------- \");\n log.debug(webResponse.getText());\n log.debug(\" ----------------- \");\n webResponse.getFormWithID(\"resultsForm\").getSubmitButtons()[0].click();\n GetMethodWebRequest webRequest = new GetMethodWebRequest(\"http://myserver/setup/addarea\");\n webRequest.setParameter(\"param\", \"11\");\n\n WebResponse webResponse = servletRunner.getResponse(webRequest);\n\n assertNotNull(webResponse);\n assertTrue(webResponse.getURL().getPath().contains(\"addsomething\"));\n assertNotNull(webResponse.getElementsByTagName(\"listofsomething\"));\n assertNotNull(webResponse.getElementsByTagName(\"someelement\"));\n log.debug(\" ----------------- \");\n log.debug(webResponse.getText());\n log.debug(\" ----------------- \");\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38226/" ]
297,116
<p>I have a collection of domain objects that I need to convert into another type for use by the .NET framework. What is the best practice for doing such a transformation?</p> <p>Specifically, I have a type called ContentEntry and I need to convert it into a SyndicationItem for use in putting into a SyndicationFeed. The conversion itself is straight forward but I'm looking for a good pattern. Do I create a method on ContentEntry called CreateSyndicationItem() or perhaps a separate converter object? Perhaps an extension method?</p> <p>This will be somewhat subjective, but I'd appreciate some ideas.</p> <blockquote> <p>Edit Note: I'd like to note that I don't control SyndicationItem. It is built into the .NET Framework. Also, I'd really like to convert several ContentEntry objects into SyndicationItems at one time.</p> </blockquote>
[ { "answer_id": 297133, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 0, "selected": false, "text": "SyndicationItem item = (SyndicationItem)entry" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2656/" ]
297,119
<p>I've struggled for the last couple of months to come up with some clean code to report progress to a user. Everything always seems to boil down to:</p> <pre><code>ReportProgress("Starting Task 1"); doTask1(); ReportProgress("Task 1 is done"); ReportProgress("Starting Task 2"); doTask2(); ReportProgress("Task 2 is done"); //etc... where report progress does some form of output to the user. </code></pre> <p>The good coder in me screams "There's got to be a cleaner way!" But I'm stumped. Any thoughts?</p> <p>EDIT :: I'm looking more for information on architectural information as opposed to implementation specific. The code given is <b>very</b> oversimplified.</p>
[ { "answer_id": 297156, "author": "Ryan Thames", "author_id": 1459442, "author_profile": "https://Stackoverflow.com/users/1459442", "pm_score": 0, "selected": false, "text": "doTask1();\ndoTask2();\n" }, { "answer_id": 297185, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": true, "text": "EventQueue tasks = new EventQueue();\ntasks.Add(new TaskEvent(this.doTask1,\"Foo-ing the bar\"));\ntasks.Add(new TaskEvent(this.doTask2,\"Bar-ing the foo\"));\ntasks.Add(new TaskEvent(this.doTask3,\"Glitching and whinging\"));\n...\ntasks.Execute(this.ProgressEventHandler);\n" }, { "answer_id": 297208, "author": "Adam Jaskiewicz", "author_id": 35322, "author_profile": "https://Stackoverflow.com/users/35322", "pm_score": 1, "selected": false, "text": "do() do() {\n ReportProgress(\"Starting \" + this.getName());\n doTask();\n ReportProgress(\"Finished \" + this.getName());\n}\n class Task1 extends Task {\n getName(){return \"Task 1\";}\n doTask() {\n //do stuff here\n }\n}\n do()" }, { "answer_id": 297286, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 0, "selected": false, "text": "with progress_report(\"Task 1\"):\n do_task_1()\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33226/" ]
297,121
<p>I have a section on my ASP.net web.config for the Enterprise library logging block. Is it possible to separate the logging configuration into another configuration file? How do I do that?</p>
[ { "answer_id": 297156, "author": "Ryan Thames", "author_id": 1459442, "author_profile": "https://Stackoverflow.com/users/1459442", "pm_score": 0, "selected": false, "text": "doTask1();\ndoTask2();\n" }, { "answer_id": 297185, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": true, "text": "EventQueue tasks = new EventQueue();\ntasks.Add(new TaskEvent(this.doTask1,\"Foo-ing the bar\"));\ntasks.Add(new TaskEvent(this.doTask2,\"Bar-ing the foo\"));\ntasks.Add(new TaskEvent(this.doTask3,\"Glitching and whinging\"));\n...\ntasks.Execute(this.ProgressEventHandler);\n" }, { "answer_id": 297208, "author": "Adam Jaskiewicz", "author_id": 35322, "author_profile": "https://Stackoverflow.com/users/35322", "pm_score": 1, "selected": false, "text": "do() do() {\n ReportProgress(\"Starting \" + this.getName());\n doTask();\n ReportProgress(\"Finished \" + this.getName());\n}\n class Task1 extends Task {\n getName(){return \"Task 1\";}\n doTask() {\n //do stuff here\n }\n}\n do()" }, { "answer_id": 297286, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 0, "selected": false, "text": "with progress_report(\"Task 1\"):\n do_task_1()\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
297,122
<p>What should I keep in mind when converting my projects from C to C++? Is there any reason to use C at all? The only thing in my mind now is to make sure it's friendly to DLLs so I can create a C interface if I need it.</p> <p>Note: I know C++ just fine. Templates, partial specialization, why multiple inheritance is bad (I've only seen one proper use for it), etc. I mostly want to know why I would use C over C++. DLLs and script language bindings is one reason. So I just need to keep in mind I should have a C interface for certain things. Is there anything else?</p>
[ { "answer_id": 297229, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 3, "selected": false, "text": "extern \"C\" {}" }, { "answer_id": 297317, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 4, "selected": false, "text": "extern \"C\"" }, { "answer_id": 3443119, "author": "Brock Woolf", "author_id": 40002, "author_profile": "https://Stackoverflow.com/users/40002", "pm_score": 3, "selected": false, "text": "C C++ 'OO'**\n malloc free new delete" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,134
<p>I have a folder "FolderA" which contains three sub-folders: foldera1 foldera2 and foldera3</p> <p>I need to write a batch file which resides inside "FolderA". It should delete all the folders under "FolderA" as a cleanup activity. I don't know the folder names. <code>rmdir</code> does not support wild cards.</p> <p>Could someone provide a solution for this small problem?</p>
[ { "answer_id": 297152, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "for /f %%a in ('dir /ad /b') do (rmdir /S /Q \"%%a\")\nfor /d %%a in (*) do (rmdir /S /Q \"%%a\")\n for /f %a in ('dir /ad /b') do (rmdir /S /Q \"%a\")\nfor /d %a in (*) do (rmdir /S /Q \"%a\")\n" }, { "answer_id": 297161, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 2, "selected": false, "text": "for /D %a in (*) do rd /S /Q %a\n for /D %%a in (*) do rd /S /Q %%a\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32670/" ]
297,136
<p>Is there a way to prompt the user for input during a NAnt build? I want to execute a command that takes a password, but I don't want to put the password into the build script.</p>
[ { "answer_id": 297203, "author": "sundar venugopal", "author_id": 32670, "author_profile": "https://Stackoverflow.com/users/32670", "pm_score": 2, "selected": false, "text": "<script language=\"C#\" prefix=\"test\" >\n <code>\n <![CDATA[\n [Function(\"get-password\")]\n public static string GetPassword( ) {\n Console.WriteLine(\"Please enter the password\");\n ConsoleColor oldForegroundColor = Console.ForegroundColor; \n Console.ForegroundColor = Console.BackgroundColor;\n string password = Console.ReadLine();\n Console.ForegroundColor = oldForegroundColor;\n return password;\n }\n ]]>\n </code>\n</script>\n\n<target name=\"test.password\">\n <echo message='${test::get-password()}'/>\n</target>\n\n-->\n" }, { "answer_id": 297281, "author": "Don Kirkby", "author_id": 4794, "author_profile": "https://Stackoverflow.com/users/4794", "pm_score": 4, "selected": true, "text": "<target name=\"input\">\n <script language=\"C#\" prefix=\"password\" >\n <code><![CDATA[\n [Function(\"ask\")]\n public string AskPassword(string prompt) {\n Project.Log(Level.Info, prompt);\n ConsoleColor oldColor = Console.ForegroundColor;\n Console.ForegroundColor = Console.BackgroundColor;\n try\n {\n return Console.ReadLine();\n }\n finally\n {\n Console.ForegroundColor = oldColor;\n }\n }\n ]]></code>\n </script>\n\n <echo message=\"Password is ${password::ask('What is the password?')}\"/>\n</target>\n" }, { "answer_id": 2544569, "author": "cc.", "author_id": 305017, "author_profile": "https://Stackoverflow.com/users/305017", "pm_score": 2, "selected": false, "text": " <code><![CDATA[\n [Function(\"ask\")]\n public string AskPassword(string prompt) {\n Project.Log(Level.Info, prompt);\n string password = \"\";\n\n // get the first character of the password\n ConsoleKeyInfo nextKey = Console.ReadKey(true);\n\n while (nextKey.Key != ConsoleKey.Enter)\n {\n if (nextKey.Key == ConsoleKey.Backspace)\n {\n if (password.Length > 0)\n {\n password = password.Substring(0, password.Length - 1);\n\n // erase the last * as well\n Console.Write(nextKey.KeyChar);\n Console.Write(\" \");\n Console.Write(nextKey.KeyChar);\n }\n }\n else\n {\n password += nextKey.KeyChar;\n Console.Write(\"*\");\n }\n\n nextKey = Console.ReadKey(true);\n }\n\n Console.WriteLine();\n\n return password;\n }\n ]]></code>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
297,205
<p>I have a field (say, foo) in a table in a SQL Server database that was originally defined as nullable, but new requirements indicate that this field must be non-null.</p> <p>What's the best way of updating this field to non-null via an update script without deleting the contents of the table? I tried generating a script from the Design view, but fails during execution because the current contents of the table had NULL values for foo. Worse yet, if I ignored this error, it proceeds to delete all the contents of the table!</p>
[ { "answer_id": 297248, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": true, "text": "NULL NULL NOT NULL -- Clean up the data which won't comply with the schema changes\nUPDATE t SET foo = 0 WHERE foo IS NULL\n\n-- Apply the NOT NULL\nALTER TABLE t ALTER COLUMN foo int NOT NULL\n\n-- Add a default for the future if that's what you want\nALTER TABLE t ADD CONSTRAINT t_foo_def DEFAULT 0 FOR foo\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5563/" ]
297,206
<p>I have a simple page that displays a user's email addresses in a table. I also have a textbox underneath the table and an "add" button. Currently, I am using a simple form post that is handled by a controller that will add the e-mail address to the database and reload the page. This works fine, but I'm looking to streamline the process by using jQuery and AJAX so that the page doesn't need to be refreshed.</p> <p>What's the best way to go about doing this? I imagine I'll have to set up an event listener for the button's click event, perform an AJAX call to a url like "Email/Add". Where I get lost is figuring out what type of information to return from that controller action and how that information can get parsed on the client side to update the table of e-mail addresses. Are there any good samples of this out there?</p>
[ { "answer_id": 297259, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "{\n result: 'SUCCESS',\n description: 'Email Added.'\n}\n //This function abstracts away the strangeness in dealing with the eval method and returning JSON objects\n//If there is a better way, let me know\nfunction ParseJSON(jsonText) {\n var ret = null;\n eval('ret = '+jsonText);\n return ret;\n}\n\nvar ret = ParseJSON(response.value);;\n\nif(ret.result == 'SUCCESS') {\n //Add a new TR to your table here\n} else {\n //Display the error message here\n // alert(ret.description);\n}\n" }, { "answer_id": 298488, "author": "Morph", "author_id": 31489, "author_profile": "https://Stackoverflow.com/users/31489", "pm_score": 1, "selected": false, "text": " $(\"#ajaxLoading\").show();\n\n $.ajax({\n type: \"POST\",\n url: \"/Hoofdgroepen/Add\",\n data: \"nummer=\" + nummer + \"&omschr=\" + omschr,\n dataType: \"html\",\n success: function(result) {\n //alert(result); \n $(\"tr:last\").after(result);\n $(\"#ajaxLoading\").hide();\n $(\"#hfdgrpForm\").resetForm();\n }\n });\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
297,213
<p>Given a columns' index, how can you get an Excel column name?</p> <p>The problem is trickier than it sounds because it's <strong>not just base-26</strong>. The columns don't wrap over like normal digits would. Even the <a href="http://support.microsoft.com/kb/833402" rel="nofollow noreferrer">Microsoft Support Example</a> doesn't scale beyond ZZZ.</p> <p><sub><em>Disclaimer: This is some code I had done a while back, and it came across my desktop again today. I thought it was worthy of posting here as a pre-answered question.</em></sub></p>
[ { "answer_id": 297214, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": true, "text": "Function ColumnName(ByVal index As Integer) As String\n Static chars() As Char = {\"A\"c, \"B\"c, \"C\"c, \"D\"c, \"E\"c, \"F\"c, \"G\"c, \"H\"c, \"I\"c, \"J\"c, \"K\"c, \"L\"c, \"M\"c, \"N\"c, \"O\"c, \"P\"c, \"Q\"c, \"R\"c, \"S\"c, \"T\"c, \"U\"c, \"V\"c, \"W\"c, \"X\"c, \"Y\"c, \"Z\"c}\n\n index -= 1 ' adjust so it matches 0-indexed array rather than 1-indexed column\n\n Dim quotient As Integer = index \\ 26 ' normal / operator rounds. \\ does integer division, which truncates\n If quotient > 0 Then\n ColumnName = ColumnName(quotient) & chars(index Mod 26)\n Else\n ColumnName = chars(index Mod 26)\n End If\nEnd Function\n string ColumnName(int index)\n{\n index -= 1; //adjust so it matches 0-indexed array rather than 1-indexed column\n\n int quotient = index / 26;\n if (quotient > 0)\n return ColumnName(quotient) + chars[index % 26].ToString();\n else\n return chars[index % 26].ToString();\n}\nprivate char[] chars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};\n" }, { "answer_id": 297440, "author": "Ken Paul", "author_id": 26671, "author_profile": "https://Stackoverflow.com/users/26671", "pm_score": 3, "selected": false, "text": "Function colname(colindex)\n x = Cells(1, colindex).Address(False, False) ' get the range name (e.g. AB1)\n colname = Mid(x, 1, Len(x) - 1) ' return all but last character\nEnd Function\n" }, { "answer_id": 1046772, "author": "Joey", "author_id": 25962, "author_profile": "https://Stackoverflow.com/users/25962", "pm_score": 4, "selected": false, "text": " Public Shared Function GetExcelColumn(ByVal index As Integer) As String\n\n Dim quotient As Integer = index \\ 26 ' Truncate \n If quotient > 0 Then\n Return GetExcelColumn(quotient - 1) & Chr((index Mod 26) + 64).ToString\n\n Else\n Return Chr(index + 64).ToString\n\n End If\n\n End Function\n" }, { "answer_id": 1047554, "author": "John Machin", "author_id": 84270, "author_profile": "https://Stackoverflow.com/users/84270", "pm_score": 2, "selected": false, "text": "# Python 2.x, no recursive function calls\n\ndef colname_from_colx(colx):\n assert colx >= 0\n colname = ''\n r = colx\n while 1:\n r, d = divmod(r, 26)\n colname = chr(d + ord('A')) + colname\n if not r:\n return colname\n r -= 1\n" }, { "answer_id": 3110421, "author": "Mathe Szabolcs", "author_id": 375309, "author_profile": "https://Stackoverflow.com/users/375309", "pm_score": 3, "selected": false, "text": "public static String translateColumnIndexToName(int index) {\n //assert (index >= 0);\n\n int quotient = (index)/ 26;\n\n if (quotient > 0) {\n return translateColumnIndexToName(quotient-1) + (char) ((index % 26) + 65);\n } else {\n return \"\" + (char) ((index % 26) + 65);\n }\n\n\n }\n for (int i = 0; i < 100; i++) {\n System.out.println(i + \": \" + translateColumnIndexToName(i));\n}\n 0: A\n1: B\n2: C\n3: D\n4: E\n5: F\n6: G\n7: H\n8: I\n9: J\n10: K\n11: L\n12: M\n13: N\n14: O\n15: P\n16: Q\n17: R\n18: S\n19: T\n20: U\n21: V\n22: W\n23: X\n24: Y\n25: Z\n26: AA\n27: AB\n28: AC\n public static int translateComunNameToIndex0(String columnName) {\n if (columnName == null) {\n return -1;\n }\n columnName = columnName.toUpperCase().trim();\n\n int colNo = -1;\n\n switch (columnName.length()) {\n case 1:\n colNo = (int) columnName.charAt(0) - 64;\n break;\n case 2:\n colNo = ((int) columnName.charAt(0) - 64) * 26 + ((int) columnName.charAt(1) - 64);\n break;\n default:\n //illegal argument exception\n throw new IllegalArgumentException(columnName);\n }\n\n return colNo;\n }\n" }, { "answer_id": 4076021, "author": "eka808", "author_id": 287824, "author_profile": "https://Stackoverflow.com/users/287824", "pm_score": 1, "selected": false, "text": "/**\n * Get excel column name\n * @param index : a column index we want to get the value in excel column format\n * @return (string) : excel column format\n */\nfunction getexcelcolumnname($index) {\n //Get the quotient : if the index superior to base 26 max ?\n $quotient = $index / 26;\n if ($quotient >= 1) {\n //If yes, get top level column + the current column code\n return getexcelcolumnname($quotient-1). chr(($index % 26)+65);\n } else {\n //If no just return the current column code\n return chr(65 + $index);\n }\n}\n" }, { "answer_id": 7496996, "author": "Mark Lane", "author_id": 956500, "author_profile": "https://Stackoverflow.com/users/956500", "pm_score": 0, "selected": false, "text": "Public Function TranslateColumnIndexToName(index As Integer) As String\n'\nDim remainder As Integer\nDim remainder2 As Integer\nDim quotient As Integer\nDim quotient2 As Integer\n'\nquotient2 = ((index) / (26 * 26)) - 2\nremainder2 = (index Mod (26 * 26)) - 1\nquotient = ((remainder2) / 26) - 2\nremainder = (index Mod 26) - 1\n'\nIf quotient2 > 0 Then\n TranslateColumnIndexToName = ChrW(quotient2 + 65) & ChrW(quotient + 65) & ChrW(remainder + 65)\nElseIf quotient > 0 Then\n TranslateColumnIndexToName = ChrW(quotient + 65) & ChrW(remainder + 65)\nElse\n TranslateColumnIndexToName = ChrW(remainder + 65)\nEnd If \n" }, { "answer_id": 13021532, "author": "dana", "author_id": 315689, "author_profile": "https://Stackoverflow.com/users/315689", "pm_score": 2, "selected": false, "text": "public static String GetExcelColumnName(int columnIndex)\n{\n if (columnIndex < 0)\n {\n throw new ArgumentOutOfRangeException(\"columnIndex: \" + columnIndex);\n }\n Stack<char> stack = new Stack<char>();\n while (columnIndex >= 0)\n {\n stack.Push((char)('A' + (columnIndex % 26)));\n columnIndex = (columnIndex / 26) - 1;\n }\n return new String(stack.ToArray());\n}\n 0: A\n1: B\n2: C\n...\n24: Y\n25: Z\n26: AA\n27: AB\n...\n50: AY\n51: AZ\n52: BA\n53: BB\n...\n700: ZY\n701: ZZ\n702: AAA\n703: AAB\n" }, { "answer_id": 13289755, "author": "howardlo", "author_id": 1020898, "author_profile": "https://Stackoverflow.com/users/1020898", "pm_score": 0, "selected": false, "text": "// test\nvoid Main()\n{\n\n for( var i = 0; i< 1000; i++ )\n { var byte_array = code( i );\n Console.WriteLine(\"{0} | {1} | {2}\", i, byte_array, offset(byte_array));\n }\n}\n\n// Converts an offset to AAA code\npublic string code( int offset )\n{\n List<byte> byte_array = new List<byte>();\n while( offset >= 0 )\n {\n byte_array.Add( Convert.ToByte(65 + offset % 26) );\n offset = offset / 26 - 1;\n }\n return ASCIIEncoding.ASCII.GetString( byte_array.ToArray().Reverse().ToArray());\n}\n\n// Converts AAA code to an offset\npublic int offset( string code)\n{\n var offset = 0;\n var byte_array = Encoding.ASCII.GetBytes( code ).Reverse().ToArray();\n for( var i = 0; i < byte_array.Length; i++ )\n {\n offset += (byte_array[i] - 65 + 1) * Convert.ToInt32(Math.Pow(26.0, Convert.ToDouble(i)));\n }\n return offset - 1;\n}\n" }, { "answer_id": 14150491, "author": "TimS", "author_id": 395416, "author_profile": "https://Stackoverflow.com/users/395416", "pm_score": 0, "selected": false, "text": "/// <summary>\n/// Gets the name of a column given the index, as it would appear in Excel.\n/// </summary>\n/// <param name=\"columnIndex\">The zero-based column index number.</param>\n/// <returns>The name of the column.</returns>\n/// <example>Column 0 = A, 26 = AA.</example>\npublic static string GetColumnName(int columnIndex)\n{\n if (columnIndex < 0) throw new ArgumentOutOfRangeException(\"columnIndex\", \"Column index cannot be negative.\");\n\n var dividend = columnIndex + 1;\n var columnName = string.Empty;\n\n while (dividend > 0)\n {\n var modulo = (dividend - 1) % 26;\n columnName = Convert.ToChar(65 + modulo) + columnName;\n dividend = (dividend - modulo) / 26;\n }\n\n return columnName;\n}\n\n/// <summary>\n/// Gets the zero-based column index given a column name.\n/// </summary>\n/// <param name=\"columnName\">The column name.</param>\n/// <returns>The index of the column.</returns>\npublic static int GetColumnIndex(string columnName)\n{\n var index = 0;\n var total = 0;\n for (var i = columnName.Length - 1; i >= 0; i--)\n total += (columnName.ToUpperInvariant()[i] - 64) * (int)Math.Pow(26, index++);\n\n return total - 1;\n}\n" }, { "answer_id": 14687154, "author": "Iwan B.", "author_id": 731228, "author_profile": "https://Stackoverflow.com/users/731228", "pm_score": 0, "selected": false, "text": "class Fixnum\n def col_name\n quot = self/26\n (quot>0 ? (quot-1).col_name : \"\") + (self%26+65).chr\n end\nend\n\nputs 0.col_name # => \"A\"\nputs 51.col_name # => \"AZ\"\n" }, { "answer_id": 17131498, "author": "Anonymous Coward", "author_id": 2490375, "author_profile": "https://Stackoverflow.com/users/2490375", "pm_score": 0, "selected": false, "text": "function colName(x)\n{\n x = (parseInt(\"ooooooop0\", 26) + x).toString(26);\n return x.slice(x.indexOf('p') + 1).replace(/./g, function(c)\n {\n c = c.charCodeAt(0);\n return String.fromCharCode(c < 64 ? c + 17 : c - 22);\n });\n}\n .toString(26) 0 A\n1 B\n9 J\n10 K\n24 Y\n25 Z\n26 AA\n27 AB\n700 ZY\n701 ZZ\n702 AAA\n703 AAB\n18276 ZZY\n18277 ZZZ\n18278 AAAA\n18279 AAAB\n475252 ZZZY\n475253 ZZZZ\n475254 AAAAA\n475255 AAAAB\n12356628 ZZZZY\n12356629 ZZZZZ\n12356630 AAAAAA\n12356631 AAAAAB\n321272404 ZZZZZY\n321272405 ZZZZZZ\n321272406 AAAAAAA\n321272407 AAAAAAB\n8353082580 ZZZZZZY\n8353082581 ZZZZZZZ\n8353082582 AAAAAAAA\n8353082583 AAAAAAAB\n" }, { "answer_id": 19155823, "author": "Ally", "author_id": 837649, "author_profile": "https://Stackoverflow.com/users/837649", "pm_score": 1, "selected": false, "text": "/**\n * Calculate the column letter abbreviation from a 0 based index\n * @param {Number} value\n * @returns {string}\n */\ngetColumnFromIndex = function (value) {\n var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');\n value++;\n var remainder, result = \"\";\n do {\n remainder = value % 26;\n result = base[(remainder || 26) - 1] + result;\n value = Math.floor(value / 26);\n } while (value > 0);\n return result;\n};\n" }, { "answer_id": 19576446, "author": "Micah Stubbs", "author_id": 1732222, "author_profile": "https://Stackoverflow.com/users/1732222", "pm_score": 2, "selected": false, "text": "def GetExcelColumn(index):\n\n quotient = int(index / 26)\n\n if quotient > 0:\n return GetExcelColumn(quotient) + str(chr((index % 26) + 64))\n\n else:\n return str(chr(index + 64))\n" }, { "answer_id": 49412889, "author": "Ali Alzahrani", "author_id": 1484193, "author_profile": "https://Stackoverflow.com/users/1484193", "pm_score": 0, "selected": false, "text": "@IBAction func printlaction(_ sender: Any) {\n let textN : Int = Int (number_textfield.text!)!\n reslut.text = String (printEXCL_Letter(index: textN))\n}\n\n\nfunc printEXCL_Letter(index : Int) -> String {\n\n let letters = [\"a\", \"b\", \"c\",\"d\", \"e\", \"f\",\"g\", \"h\", \"i\",\"j\", \"k\", \"l\",\"m\", \"n\", \"o\",\"p\", \"q\", \"r\",\"s\", \"t\", \"u\",\"v\",\"w\" ,\"x\", \"y\",\"z\"]\n\n var index = index;\n index -= 1\n let index_div = index / 26\n\n if (index_div > 0){\n return printEXCL_Letter(index: index_div) + letters[index % 26];\n }\n else {\n return letters[index % 26]\n }\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
297,217
<p>I got a web application, the problem is that the text in the label will not update on the first click, I need to click the button twice, I debugged to code, and I found out that the label does not recive the data until after the second click,</p> <p>Here is my code:</p> <pre><code>System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(); System.Data.SqlClient.SqlConnection connection; string CommandText; string game; string modtype; bool filter; protected void Page_Load(object sender, EventArgs e) { labDownloadList.Text = null; //Session variables: if (Session["Game"] != null) { game = Convert.ToString(Session["Game"]); } if (Session["ModType"] != null) { modtype = Convert.ToString(Session["ModType"]); } if (Session["FilterBool"] != null) { filter = Convert.ToBoolean(Session["FilterBool"]); } string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\stian\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True"; connection = new System.Data.SqlClient.SqlConnection(ConnectionString); System.Data.SqlClient.SqlDataReader reader; command = connection.CreateCommand(); connection.Open(); CommandText = "SELECT * FROM Command"; if (filter) { CommandText = "SELECT * FROM Command WHERE Game='" + game + "' AND Type='" + modtype + "'"; } command.CommandText = CommandText; reader = command.ExecuteReader(); labDownloadList.Text = ""; while (reader.Read()) { string game = reader.GetString(1); string author = reader.GetString(2); string downloadlink = reader.GetString(3); string size = reader.GetString(4); string description = reader.GetString(5); string version = reader.GetString(6); string screenshotlink = reader.GetString(7); Int64 AmountDownloaded = reader.GetInt64(8); labDownloadList.Text += "Game: " + game + "&lt;br&gt;"; labDownloadList.Text += "Author: " + author + "&lt;br&gt;"; labDownloadList.Text += "Size: " + size + "&lt;br&gt;"; labDownloadList.Text += "Description: " + description + "&lt;br&gt;"; labDownloadList.Text += "Version: " + version + "&lt;br&gt;"; labDownloadList.Text += "&lt;img src='" + screenshotlink + " /&gt;&lt;br&gt;"; labDownloadList.Text += "Downloaded: " + AmountDownloaded + " times&lt;br&gt;&lt;hr&gt;"; labDownloadList.Text += "&lt;a href='" + downloadlink + "'&gt;Download&lt;/a&gt;&lt;br&gt;"; } } protected void Page_UnLoad(object sender, EventArgs e) { Session["Game"] = game; Session["ModType"] = modtype; Session["FilterBool"] = filter; connection.Close(); } protected void btnFilter_Click(object sender, EventArgs e) { game = lstGames.SelectedValue; modtype = lstTypeMod.SelectedValue; filter = true; } </code></pre>
[ { "answer_id": 297230, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "if (!Page.IsPostBack)\n{\n ...\n}\n" }, { "answer_id": 297362, "author": "JackCorn", "author_id": 14919, "author_profile": "https://Stackoverflow.com/users/14919", "pm_score": 5, "selected": true, "text": "\nprotected void Page_Load(object sender, EventArgs e)\n{ \n if (!Page.IsPostBack)\n { \n LoadData()\n }\n}\n\nprivate void LoadData()\n{\n labDownloadList.Text = null;\n //Session variables: \n if (Session[\"Game\"] != null)\n ...\n}\n\nprotected void btnFilter_Click(object sender, EventArgs e)\n{ \n game = lstGames.SelectedValue;\n modtype = lstTypeMod.SelectedValue;\n filter = true;\n LoadData();\n}\n" }, { "answer_id": 11181169, "author": "Woodsie", "author_id": 1478652, "author_profile": "https://Stackoverflow.com/users/1478652", "pm_score": 0, "selected": false, "text": "Button_Click TextChanged TextBox Button_click" }, { "answer_id": 41104533, "author": "Minh", "author_id": 5661928, "author_profile": "https://Stackoverflow.com/users/5661928", "pm_score": 0, "selected": false, "text": "function pageLoad(sender, args) {\n $(document).ready(function () {\n //your stuff\n });\n $(\":button\").each(function() {\n $(this).click();\n //this is a trick; click one when page load,\n });\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,220
<p>Using VBA in MS Office, how do I add text to the Windows clipboard so that it will paste into Word as a table?</p>
[ { "answer_id": 297288, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "Paste Special" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
297,236
<p>I am developing a site that makes extensive use of JavaScript (jQuery). I regularly get the IE 'Stop running this script?' error dialog when I try to close the browser. </p> <p>I'm guessing the problem occurs because the site is a single page that uses AJAX, so there are no postbacks to reset IE's count of commands executed.</p> <p>Client-side registry hacking is not an option.</p> <p>Does anyone know a way to get around this error?</p> <p>UPDATE: The page has a number (~10) interval timers that poll continually on 30 or 60 second intervals.</p>
[ { "answer_id": 297266, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 2, "selected": false, "text": "window.onunload = null;\n" }, { "answer_id": 2251407, "author": "Narsi", "author_id": 271792, "author_profile": "https://Stackoverflow.com/users/271792", "pm_score": 2, "selected": false, "text": "setTimeout" }, { "answer_id": 7427482, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 0, "selected": false, "text": "$(\"*\")" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2785/" ]
297,238
<p>How do you repopulate a form in ASP.NET MVC that contains a DropDownList?</p>
[ { "answer_id": 316240, "author": "BigJoe714", "author_id": 37786, "author_profile": "https://Stackoverflow.com/users/37786", "pm_score": 3, "selected": false, "text": "private Dictionary<string, string> getListItems()\n{\n Dictionary<string, string> d = new Dictionary<string, string>();\n d.Add(\"Apple\", \"APPL\");\n d.Add(\"Orange\", \"ORNG\");\n d.Add(\"Banana\", \"BNA\");\n return d;\n}\n\npublic ActionResult Index()\n{\n Dictionary<string, string> listItems = getListItems();\n SelectList selectList = new SelectList(listItems, \"Value\", \"Key\");\n ViewData[\"FruitDropDown\"] = selectList;\n\n return View();\n}\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Index(FormCollection form)\n{\n\n string selectedItem = form[\"FruitDropDown\"];\n\n Dictionary<string, string> listItems = getListItems();\n SelectList selectList = new SelectList(listItems, \"Value\", \"Key\", selectedItem);\n ViewData[\"FruitDropDown\"] = selectList;\n\n ViewData[\"Message\"] = \"You selected ID:\" + selectedItem;\n\n return View();\n\n}\n <div><strong><%= ViewData[\"Message\"] %></strong></div>\n\n<% using (Html.BeginForm()) { %>\n<%= Html.DropDownList(\"FruitDropDown\",\"(select a fruit)\") %>\n<input type=\"submit\" value=\"Submit\" />\n<% } %>\n" }, { "answer_id": 1289408, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public SelectList( IEnumerable items, string dataValueField, string dataTextField, object selectedValue );\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,239
<p>I am testing against the following test document:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;hi there&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;img class="foo" src="bar.png"/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If I parse the document using lxml.html, I can get the IMG with an xpath just fine:</p> <pre><code>&gt;&gt;&gt; root = lxml.html.fromstring(doc) &gt;&gt;&gt; root.xpath("//img") [&lt;Element img at 1879e30&gt;] </code></pre> <p>However, if I parse the document as XML and try to get the IMG tag, I get an empty result:</p> <pre><code>&gt;&gt;&gt; tree = etree.parse(StringIO(doc)) &gt;&gt;&gt; tree.getroot().xpath("//img") [] </code></pre> <p>I can navigate to the element directly:</p> <pre><code>&gt;&gt;&gt; tree.getroot().getchildren()[1].getchildren()[0] &lt;Element {http://www.w3.org/1999/xhtml}img at f56810&gt; </code></pre> <p>But of course that doesn't help me process arbitrary documents. I would also expect to be able to query etree to get an xpath expression that will directly identify this element, which, technically I can do:</p> <pre><code>&gt;&gt;&gt; tree.getpath(tree.getroot().getchildren()[1].getchildren()[0]) '/*/*[2]/*' &gt;&gt;&gt; tree.getroot().xpath('/*/*[2]/*') [&lt;Element {http://www.w3.org/1999/xhtml}img at fa1750&gt;] </code></pre> <p>But that xpath is, again, obviously not useful for parsing arbitrary documents.</p> <p>Obviously I am missing some key issue here, but I don't know what it is. My best guess is that it has something to do with namespaces but the only namespace defined is the default and I don't know what else I might need to consider in regards to namespaces.</p> <p>So, what am I missing?</p>
[ { "answer_id": 297243, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 6, "selected": true, "text": ">>> tree.getroot().xpath(\n... \"//xhtml:img\", \n... namespaces={'xhtml':'http://www.w3.org/1999/xhtml'}\n... )\n[<Element {http://www.w3.org/1999/xhtml}img at 11a29e0>]\n" }, { "answer_id": 5978436, "author": "Sharmila", "author_id": 46920, "author_profile": "https://Stackoverflow.com/users/46920", "pm_score": 2, "selected": false, "text": "from lxml import objectify\nroot = objectify.parse(url) #also available: fromstring\n root.html\nbody = root.html.body\nfor img in body.img: #Assuming all images are within the body tag\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2168/" ]
297,245
<p>Does anyone know of some good tutorials that explain how to use the JQuery Slider.</p> <p>I've found a few, but none of them really present what I need in clear terms. What I really need to figure out how to do is make the slider go from 1.0 - 5.0 (including all tenths) and when it changes set a hidden control based on that value.</p> <p>Thanks.</p>
[ { "answer_id": 297338, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "$('#mySlider').slider({\n min : 1,\n max : 5,\n stepping: .1, // or, steps: 40\n change : function (e, ui) {\n $('#myHiddenInput').val(ui.value);\n }\n})\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
297,251
<p>I have a vertical menu in my system which is basically made of HTML <code>ul</code>/<code>li</code> with CSS styling (see image below). However I don't want the <code>li</code> items which are wider than the menu to wrap, I would prefer them to overflow with a horizontal scroll bar at the bottom of the menu. How can I do this in CSS?</p>
[ { "answer_id": 297255, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "white-space:nowrap li {\n white-space:nowrap;\n}\n" }, { "answer_id": 297272, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 7, "selected": true, "text": "ul {\n overflow: auto; // allow li's to overflow w/ scroll bar\n // at the bottom of the menu\n}\n\nli {\n white-space: nowrap; // stop the wrapping in the first place\n}\n" }, { "answer_id": 297275, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 2, "selected": false, "text": "ul{\n width:250px;\n overflow:auto;\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
297,269
<p>Is there a tool which tells you (or gives you a hint) why a particular select statement dose not return any rows given the current data in your database. </p> <p>eg if you had the following 4 table join</p> <pre><code>select * from a, b, c, d where a.b_id = b.id and b.c_id = c.id and c.d_id = d.id </code></pre> <p>If there were rows which satisfied the conditions a.b_id = b.id also rows which satisfied b.c_id = c.id but no rows which satisfied the condition c.d_id = d.id it would highlight c.d_id = d.id as the problem.</p> <p>Ie it would brake up the where clause and find out which of the sub conditions returned true and highlight those which do not return true.</p> <p>It would not work well for complex querys but many select statements are simple joins over lots of tables.</p> <p>This would be useful when creating test data to exercise a peace of application code or debugging a problem with a live system.</p> <p>Graphical explain tools (that show the plan of the actual exiection path) come close but they show too much info and do not highlight the missing link in the select stament.</p> <p>I am using postgres, sqllight and mysql but would be interested in how tools for other databases/platforms work. </p> <p>Im also interested in any manula techniques.</p> <p>Does anybody else have this problem?</p> <p>Would anybody be interested if I wrote such a tool?</p>
[ { "answer_id": 297289, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": false, "text": "SELECT *\nFROM a -- First run just to here, are there records?\nINNER JOIN b\n ON a.b_id = b.id -- Then run just to here, is it OK?\nINNER JOIN c\n ON b.c_id = c.id -- Then run just to here, is it OK?\nINNER JOIN d\n ON c.d_id = d.id -- Then run just to here, is it OK?\n" }, { "answer_id": 297634, "author": "Ian Varley", "author_id": 37539, "author_profile": "https://Stackoverflow.com/users/37539", "pm_score": 2, "selected": false, "text": "part count\n-------------- -------------\nTRUNK 100\nAND clause 1 90\nAND clause 2 85\n... ...\nAND clause n 20\n" }, { "answer_id": 298437, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 1, "selected": false, "text": "SELECT a.id, b.id, c.id, d.id\nFROM a \nLEFT JOIN b\n ON a.b_id = b.id\nLEFT JOIN c\n ON b.c_id = c.id\nLEFT JOIN d\n ON c.d_id = d.id\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38383/" ]
297,277
<p>I am trying to do some prime factorisation with my VBA excel and I am hitting the limit of the <code>long</code> data type - </p> <blockquote> <p>Runtime Error 6 Overflow </p> </blockquote> <p>Is there any way to get around this and still stay within VBA? I am aware that the obvious one would be to use another more appropriate programming language.</p> <hr> <p><a href="https://stackoverflow.com/a/297480/1146308">Lance's solution</a> works in so far that I am able to get the big numbers into the variables now. However, when I try to apply the <code>MOD</code> function - bignumber <code>MOD 2</code>, for example - it still fails with error message </p> <blockquote> <p>Runtime Error 6 Overflow</p> </blockquote>
[ { "answer_id": 297480, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 2, "selected": true, "text": "r = A - Int(A / B) * B\n" }, { "answer_id": 297593, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 2, "selected": false, "text": "VERSION 1.0 CLASS\nBEGIN\n MultiUse = -1 'True\n Persistable = 0 'NotPersistable\n DataBindingBehavior = 0 'vbNone\n DataSourceBehavior = 0 'vbNone\n MTSTransactionMode = 0 'NotAnMTSObject\nEND\nAttribute VB_Name = \"Decimals\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = True\nAttribute VB_PredeclaredId = False\nAttribute VB_Exposed = True\nAttribute VB_Ext_KEY = \"SavedWithClassBuilder6\" ,\"Yes\"\nAttribute VB_Ext_KEY = \"Top_Level\" ,\"Yes\"\nOption Explicit\n\n'local variable(s) to hold property value(s)\nPrivate mvarDec As Variant 'local copy\n\nPublic Property Let Dec(ByVal vData As Variant)\n'used when assigning a value to the property, on the left side of an assignment.\n'Syntax: X.Dec = 5\n mvarDec = CDec(vData)\nEnd Property\n\nPublic Property Get Dec() As Variant\nAttribute Dec.VB_UserMemId = 0\n'used when retrieving value of a property, on the right side of an assignment.\n'Syntax: Debug.Print X.Dec\n Dec = CDec(mvarDec)\nEnd Property\n Dim dec1 As New Std.Decimals\nDim dec2 As New Std.Decimals\nDim dec3 As New Std.Decimals\nDim modulus As New Std.Decimals\n\nSub main()\n dec1 = \"1000.000000001\"\n dec2 = \"1000.00000000000001\"\n dec3 = dec1 + dec2\n Debug.Print dec1\n Debug.Print dec2\n Debug.Print dec3\n Debug.Print dec3 * dec3\n Debug.Print dec3 / 10\n Debug.Print dec3 / 100\n Debug.Print Sqr(dec3)\n modulus = dec1 - Int(dec1 / dec2) * dec2\n Debug.Print modulus\nEnd Sub\n 1000.000000001 \n 1000.00000000000001 \n 2000.00000000100001 \n 4000000.000004000040000001 \n 200.000000000100001 \n 20.0000000000100001 \n 44.721359550007 \n 0.00000000099999 \n 1000.000000001 \n 1000.00000000000001 \n 2000.00000000100001 \n 4000000.000004000040000001 \n 200.000000000100001 \n 20.0000000000100001 \n 44.721359550007 \n 0.00000000099999 \n" }, { "answer_id": 298066, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 2, "selected": false, "text": "Function BigMultiply(ByVal s1 As String, ByVal s2 As String) As String\n\nDim x As Long\nx = 7\n\nDim n1 As Long, n2 As Long, n As Long\nn1 = Int(Len(s1) / x + 0.999999)\nn2 = Int(Len(s2) / x + 0.999999)\nn = n1 + n2\n\nDim i As Long, j As Long\nReDim za1(n1) As Double\ni = Len(s1) Mod x\nIf i = 0 Then i = x\nza1(1) = Left(s1, i)\ni = i + 1\nFor j = 2 To n1\n za1(j) = Mid(s1, i, x)\n i = i + x\nNext j\n\nReDim za2(n2) As Double\ni = Len(s2) Mod x\nIf i = 0 Then i = x\nza2(1) = Left(s2, i)\ni = i + 1\nFor j = 2 To n2\n za2(j) = Mid(s2, i, x)\n i = i + x\nNext j\n\nReDim z(n) As Double\nDim u1 As Long, u2 As Long\nDim e As String\ne = String(x, \"0\")\n\nFor u1 = 1 To n1\n i = u1\n For u2 = 1 To n2\n i = i + 1\n z(i) = z(i) + za1(u1) * za2(u2)\n Next u2\nNext u1\n\nDim s As String, y As Double, w As Double, m As Long\nm = n * x\ns = String(m, \"0\")\ny = 10 ^ x\nFor i = n To 1 Step -1\n w = Int(z(i) / y)\n Mid(s, i * x - x + 1, x) = Format(z(i) - w * y, e)\n z(i - 1) = z(i - 1) + w\nNext i\n'truncate leading zeros\nFor i = 1 To m\n If Mid$(s, i, 1) <> \"0\" Then Exit For\nNext i\nIf i > m Then\n BigMultiply = \"\"\nElse\n BigMultiply = Mid$(s, i)\nEnd If\n\nEnd Function\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22972/" ]
297,280
<p>I have a databases table with ~50K rows in it, each row represents a job that need to be done. I have a program that extracts a job from the DB, does the job and puts the result back in the db. (this system is running right now)</p> <p>Now I want to allow more than one processing task to do jobs but be sure that no task is done twice (as a performance concern not that this will cause other problems). Because the access is by way of a stored procedure, my current though is to replace said stored procedure with something that looks something like this</p> <pre><code>update tbl set owner = connection_id() where available and owner is null limit 1; select stuff from tbl where owner = connection_id(); </code></pre> <p>BTW; worker's tasks might drop there connection between getting a job and submitting the results. Also, I don't expect the DB to even come close to being the bottle neck unless I mess that part up (~5 jobs per minute)</p> <p>Are there any issues with this? Is there a better way to do this?</p> <p>Note: the <a href="http://tripatlas.com/Database_as_an_IPC" rel="noreferrer">"Database as an IPC anti-pattern"</a> is only slightly apropos here because </p> <ol> <li>I'm not doing IPC (there is no process generating the rows, they all already exist right now) and </li> <li>the primary gripe described for that anti-pattern is that it results in unneeded load on the DB as processes wait for messages (in my case, if there are no messages, everything can shutdown as everything is done)</li> </ol>
[ { "answer_id": 297354, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 5, "selected": true, "text": "MsgId identity -- NOT NULL\nMsgTypeCode varchar(20) -- NOT NULL \nSourceCode varchar(20) -- process inserting the message -- NULLable \nState char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL \nCreateTime datetime -- default GETDATE() -- NOT NULL \nMsg varchar(255) -- NULLable \n CREATE PROCEDURE GetMessage @MsgType VARCHAR(8) ) \nAS \nDECLARE @MsgId INT \n\nBEGIN TRAN \n\nSELECT TOP 1 @MsgId = MsgId \nFROM MsgQueue \nWHERE MessageType = @pMessageType AND State = 'N' \nORDER BY CreateTime\n\n\nIF @MsgId IS NOT NULL \nBEGIN \n\nUPDATE MsgQueue \nSET State = 'A' \nWHERE MsgId = @MsgId \n\nSELECT MsgId, Msg \nFROM MsgQueue \nWHERE MsgId = @MsgId \nEND \nELSE \nBEGIN \nSELECT MsgId = NULL, Msg = NULL \nEND \n\nCOMMIT TRAN\n" }, { "answer_id": 55702399, "author": "Vlad Mihalcea", "author_id": 1025118, "author_profile": "https://Stackoverflow.com/users/1025118", "pm_score": 5, "selected": false, "text": "SKIP LOCKED SKIP LOCKED FOR SHARE FOR UPDATE post status Enum PENDING APPROVED SPAM post post SKIP LOCKED SKIP LOCKED [Alice]:\nSELECT\n p.id AS id1_0_,1\n p.body AS body2_0_,\n p.status AS status3_0_,\n p.title AS title4_0_\nFROM\n post p\nWHERE\n p.status = 0\nORDER BY\n p.id\nLIMIT 2\nFOR UPDATE OF p SKIP LOCKED\n \n[Bob]: \nSELECT\n p.id AS id1_0_,\n p.body AS body2_0_,\n p.status AS status3_0_,\n p.title AS title4_0_\nFROM\n post p\nWHERE\n p.status = 0\nORDER BY\n p.id\nLIMIT 2\nFOR UPDATE OF p SKIP LOCKED\n SKIP LOCKED" }, { "answer_id": 64534396, "author": "Connor McDonald", "author_id": 7367293, "author_profile": "https://Stackoverflow.com/users/7367293", "pm_score": 0, "selected": false, "text": "SELECT * FROM t order by x limit 2 FOR UPDATE OF t SKIP LOCKED\n SQL> create table t as\n 2 select rownum x\n 3 from dual\n 4 connect by level <= 100;\n\nTable created.\n\nSQL> declare\n 2 rc sys_refcursor;\n 3 begin\n 4 open rc for select * from t order by x for update skip locked fetch first 2 rows only;\n 5 end;\n 6 /\n open rc for select * from t order by x for update skip locked fetch first 2 rows only;\n *\nERROR at line 4:\nORA-06550: line 4, column 65:\nPL/SQL: ORA-00933: SQL command not properly ended\nORA-06550: line 4, column 15:\nPL/SQL: SQL Statement ignored\n\nSQL> declare\n 2 rc sys_refcursor;\n 3 begin\n 4 open rc for select * from t order by x fetch first 2 rows only for update skip locked ;\n 5 end;\n 6 /\ndeclare\n*\nERROR at line 1:\nORA-02014: cannot select FOR UPDATE from view with DISTINCT, GROUP BY, etc.\nORA-06512: at line 4\n SQL> declare\n 2 rc sys_refcursor;\n 3 begin\n 4 open rc for select * from ( select * from t order by x ) where rownum <= 10 for update skip locked;\n 5 end;\n 6 /\ndeclare\n*\nERROR at line 1:\nORA-02014: cannot select FOR UPDATE from view with DISTINCT, GROUP BY, etc.\nORA-06512: at line 4\n SQL> declare\n 2 rc sys_refcursor;\n 3 res1 sys.odcinumberlist := sys.odcinumberlist();\n 4 begin\n 5 open rc for select * from t order by x for update skip locked;\n 6 fetch rc bulk collect into res1 limit 10;\n 7 end;\n 8 /\n\nPL/SQL procedure successfully completed.\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
297,294
<p>My build environment is configured to compile, run and create coverage file at the command line (using Ned Batchelder coverage.py tool). </p> <p>I'm using Eclipse with PyDev as my editor, but for practical reasons, it's not possible/convenient for me to convert my whole build environment to Eclipse (and thus generate the coverage data directly from the IDE, as it's designed to do)</p> <p>PyDev seems to be using the same coverage tool (or something very similar to it) to generate its coverage information, so I'm guessing there should be some way of integrating my external coverage files into Eclipse/PyDev.</p> <p>Any idea on how to do this?</p>
[ { "answer_id": 297354, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 5, "selected": true, "text": "MsgId identity -- NOT NULL\nMsgTypeCode varchar(20) -- NOT NULL \nSourceCode varchar(20) -- process inserting the message -- NULLable \nState char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL \nCreateTime datetime -- default GETDATE() -- NOT NULL \nMsg varchar(255) -- NULLable \n CREATE PROCEDURE GetMessage @MsgType VARCHAR(8) ) \nAS \nDECLARE @MsgId INT \n\nBEGIN TRAN \n\nSELECT TOP 1 @MsgId = MsgId \nFROM MsgQueue \nWHERE MessageType = @pMessageType AND State = 'N' \nORDER BY CreateTime\n\n\nIF @MsgId IS NOT NULL \nBEGIN \n\nUPDATE MsgQueue \nSET State = 'A' \nWHERE MsgId = @MsgId \n\nSELECT MsgId, Msg \nFROM MsgQueue \nWHERE MsgId = @MsgId \nEND \nELSE \nBEGIN \nSELECT MsgId = NULL, Msg = NULL \nEND \n\nCOMMIT TRAN\n" }, { "answer_id": 55702399, "author": "Vlad Mihalcea", "author_id": 1025118, "author_profile": "https://Stackoverflow.com/users/1025118", "pm_score": 5, "selected": false, "text": "SKIP LOCKED SKIP LOCKED FOR SHARE FOR UPDATE post status Enum PENDING APPROVED SPAM post post SKIP LOCKED SKIP LOCKED [Alice]:\nSELECT\n p.id AS id1_0_,1\n p.body AS body2_0_,\n p.status AS status3_0_,\n p.title AS title4_0_\nFROM\n post p\nWHERE\n p.status = 0\nORDER BY\n p.id\nLIMIT 2\nFOR UPDATE OF p SKIP LOCKED\n \n[Bob]: \nSELECT\n p.id AS id1_0_,\n p.body AS body2_0_,\n p.status AS status3_0_,\n p.title AS title4_0_\nFROM\n post p\nWHERE\n p.status = 0\nORDER BY\n p.id\nLIMIT 2\nFOR UPDATE OF p SKIP LOCKED\n SKIP LOCKED" }, { "answer_id": 64534396, "author": "Connor McDonald", "author_id": 7367293, "author_profile": "https://Stackoverflow.com/users/7367293", "pm_score": 0, "selected": false, "text": "SELECT * FROM t order by x limit 2 FOR UPDATE OF t SKIP LOCKED\n SQL> create table t as\n 2 select rownum x\n 3 from dual\n 4 connect by level <= 100;\n\nTable created.\n\nSQL> declare\n 2 rc sys_refcursor;\n 3 begin\n 4 open rc for select * from t order by x for update skip locked fetch first 2 rows only;\n 5 end;\n 6 /\n open rc for select * from t order by x for update skip locked fetch first 2 rows only;\n *\nERROR at line 4:\nORA-06550: line 4, column 65:\nPL/SQL: ORA-00933: SQL command not properly ended\nORA-06550: line 4, column 15:\nPL/SQL: SQL Statement ignored\n\nSQL> declare\n 2 rc sys_refcursor;\n 3 begin\n 4 open rc for select * from t order by x fetch first 2 rows only for update skip locked ;\n 5 end;\n 6 /\ndeclare\n*\nERROR at line 1:\nORA-02014: cannot select FOR UPDATE from view with DISTINCT, GROUP BY, etc.\nORA-06512: at line 4\n SQL> declare\n 2 rc sys_refcursor;\n 3 begin\n 4 open rc for select * from ( select * from t order by x ) where rownum <= 10 for update skip locked;\n 5 end;\n 6 /\ndeclare\n*\nERROR at line 1:\nORA-02014: cannot select FOR UPDATE from view with DISTINCT, GROUP BY, etc.\nORA-06512: at line 4\n SQL> declare\n 2 rc sys_refcursor;\n 3 res1 sys.odcinumberlist := sys.odcinumberlist();\n 4 begin\n 5 open rc for select * from t order by x for update skip locked;\n 6 fetch rc bulk collect into res1 limit 10;\n 7 end;\n 8 /\n\nPL/SQL procedure successfully completed.\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8027/" ]
297,297
<p>I've got a button that I'm adding as a subview of a table view's tableHeaderView. The button appears fine, and tap-and-holding on it works intermittently - for the most part, though, it's unresponsive. I've tried adding it as a subview of the table itself; the effect is about the same. I thought the problem might be with the scroll view's touch interception, but disabling scrolling on the table has no effect either. </p> <p>Am I doing something wrong? Has anyone else encountered this?</p> <p>edit - to clarify, I'm talking about the main table header, not a section header, in a grouped-style table; think basically modeled after the "Contact" screen.</p>
[ { "answer_id": 7897148, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "- (void)viewDidLoad\n{\n [super viewDidLoad];\n\n MYCustomWidget *headerView = [[[NSBundle mainBundle] \n loadNibNamed:@\"MYCustomWidgetView\" owner:self options:nil] \n objectAtIndex:0];\n\n [headerView setAutoresizingMask:UIViewAutoresizingNone];\n\n self.tableView.tableHeaderView = headerView;\n}\n" }, { "answer_id": 19590461, "author": "Alexey Ryabinin", "author_id": 2549907, "author_profile": "https://Stackoverflow.com/users/2549907", "pm_score": 1, "selected": false, "text": "#import <UIKit/UIKit.h> \n@interface CustomHeaderCell : UIView\n\n@end \n\n//-----\n\n@import \"CustomHeaderCell.h\"\n\n@implementation CustomHeaderCell\n\n\n-(void)setFrame:(CGRect)frame {\n frame.size.height = 43; // !!! constant height\n [super setFrame:frame];\n}\n\n@end\n" }, { "answer_id": 32865819, "author": "Davyd Geyl", "author_id": 899656, "author_profile": "https://Stackoverflow.com/users/899656", "pm_score": 2, "selected": false, "text": "- (void)viewDidLayoutSubviews {\n CGRect frame = self.tableView.tableHeaderView.frame;\n frame.size.height = 116.0;\n self.tableView.tableHeaderView.frame = frame;\n}\n" }, { "answer_id": 33177911, "author": "mskw", "author_id": 1454775, "author_profile": "https://Stackoverflow.com/users/1454775", "pm_score": -1, "selected": false, "text": "-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{\n" }, { "answer_id": 43447574, "author": "Ravi Sharma", "author_id": 996796, "author_profile": "https://Stackoverflow.com/users/996796", "pm_score": 1, "selected": false, "text": "UIButtons UITableView's setAutoresizingMask .None self.tablevwMain.tableHeaderView?.frame = CGRect(x: 0, y: 0, width: width_view, height: your_height)\n UIButton's UITableView's" }, { "answer_id": 72120209, "author": "Samuel Folledo", "author_id": 7277928, "author_profile": "https://Stackoverflow.com/users/7277928", "pm_score": 0, "selected": false, "text": "addSubview(stackView) //Does not work\ncontentView.addSubview(stackView) //Works\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30618/" ]
297,298
<p>When you hit F5, the browser windows pops up, how do you set which browser the debugger users in Visual Studio 2008?</p> <p><strong>Update 1</strong><br> I have looked for the 'Browse with' option and not found it.<br> <a href="https://stackoverflow.com/questions/79954/visual-studio-opens-default-browser-instead-of-ie">Visual Studio opens the default browser instead of Internet Explorer</a> </p> <p><strong>Update 2</strong><br> If you are already debugging you dont have the 'Browse with' option. </p> <ul> <li><em>Stop debugging and then its there!</em></li> </ul> <p><strong>Update 3</strong><br> The accepted answer below is also relevant to changing the default browser to debug with in Visual Studio 2010.</p>
[ { "answer_id": 618007, "author": "Matthew Lock", "author_id": 74585, "author_profile": "https://Stackoverflow.com/users/74585", "pm_score": 3, "selected": false, "text": "Project Properties -> Web -> Start Action" }, { "answer_id": 3180941, "author": "PHOTON", "author_id": 383846, "author_profile": "https://Stackoverflow.com/users/383846", "pm_score": 2, "selected": false, "text": "* Right click the webform \n* Select Browse With... \n* Choose your browser \n* Click Set as Default \n* Delete the webform\n" }, { "answer_id": 16914248, "author": "Jitender Kumar", "author_id": 1107618, "author_profile": "https://Stackoverflow.com/users/1107618", "pm_score": 0, "selected": false, "text": "In VS 2010 just make the browser as your default broswer in which you want to run your application and there is no need to set anything in visual studio. " }, { "answer_id": 28633733, "author": "Ken", "author_id": 1671746, "author_profile": "https://Stackoverflow.com/users/1671746", "pm_score": 0, "selected": false, "text": "Browse With.. Run as administrator" }, { "answer_id": 50513017, "author": "Andy Braham", "author_id": 1601882, "author_profile": "https://Stackoverflow.com/users/1601882", "pm_score": 0, "selected": false, "text": "Web Browser Browse with..." } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6268/" ]
297,299
<p>I have my enumHelper class that contains these:</p> <pre><code>public static IList&lt;T&gt; GetValues() { IList&lt;T&gt; list = new List&lt;T&gt;(); foreach (object value in Enum.GetValues(typeof(T))) { list.Add((T)value); } return list; } </code></pre> <p>and</p> <pre><code>public static string Description(Enum value) { Attribute DescAttribute = LMIGHelper.GetAttribute(value, typeof(DescriptionAttribute)); if (DescAttribute == null) return value.ToString(); else return ((DescriptionAttribute)DescAttribute).Description; } </code></pre> <p>my enum is something like:</p> <pre><code>public enum OutputType { File, [Description("Data Table")] DataTable } </code></pre> <p>So far so good. All the previous work fine. Now I want to add a new helper to return BindingList>, so I can link any enum to any combo using </p> <pre><code>BindingList&lt;KeyValuePair&lt;OutputType, string&gt;&gt; list = Enum&lt;OutputType&gt;.GetBindableList(); cbo.datasource=list; cbo.DisplayMember="Value"; cbo.ValueMember="Key"; </code></pre> <p>For that I added:</p> <pre><code>public static BindingList&lt;KeyValuePair&lt;T, string&gt;&gt; GetBindingList() { BindingList&lt;KeyValuePair&lt;T, string&gt;&gt; list = new BindingList&lt;KeyValuePair&lt;T, string&gt;&gt;(); foreach (T value in Enum&lt;T&gt;.GetValues()) { string Desc = Enum&lt;T&gt;.Description(value); list.Add(new KeyValuePair&lt;T, string&gt;(value, Desc)); } return list; } </code></pre> <p>But "Enum.Description(value)" is not even compiling: Argument '1': cannot convert from 'T' to 'System.Enum'</p> <p>How can I do that? Is that even possible?</p> <p>Thank you.</p>
[ { "answer_id": 297333, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": -1, "selected": false, "text": "public static BindingList<KeyValuePair<T extends _interface_, String>> getBindingList()\n T foo = ...?\nfoo.Description(...);\n" }, { "answer_id": 297409, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 2, "selected": false, "text": "public static string Description(Enum value)\n{\n ...\n}\n public static string Description(T value)\n{\n ...\n}\n foreach(var field in typeof(T).GetFields())\n{\n T fieldValue;\n\n try\n {\n fieldValue = (T) field.GetRawConstantValue();\n }\n catch(InvalidOperationException)\n {\n // For some reason, one of the fields returned is {Int32 value__},\n // which throws an InvalidOperationException if you try and retrieve\n // its constant value.\n //\n // I am unsure how to check for this state before\n // attempting GetRawConstantValue().\n\n continue;\n }\n\n if(fieldValue == value)\n {\n var attribute = LMIGHelper.GetAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;\n\n return attribute == null ? value.ToString() : attribute.Description;\n }\n}\n FillComboFromEnum public static void FillComboFromEnum<T>(ComboBox Cbo, BindingList<KeyValuePair<T, string>> List) where T : struct\n" }, { "answer_id": 415641, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Provides a description for an enumerated type.\n/// </summary>\n[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, \n AllowMultiple = false)]\npublic sealed class EnumDescriptionAttribute : Attribute\n{\n private string description;\n\n /// <summary>\n /// Gets the description stored in this attribute.\n /// </summary>\n /// <value>The description stored in the attribute.</value>\n public string Description\n {\n get\n {\n return this.description;\n }\n }\n\n /// <summary>\n /// Initializes a new instance of the\n /// <see cref=\"EnumDescriptionAttribute\"/> class.\n /// </summary>\n /// <param name=\"description\">The description to store in this attribute.\n /// </param>\n public EnumDescriptionAttribute(string description)\n : base()\n {\n this.description = description;\n }\n} \n public enum SimpleEnum\n{\n [EnumDescription(\"Today\")]\n Today,\n\n [EnumDescription(\"Last 7 days\")]\n Last7,\n\n [EnumDescription(\"Last 14 days\")]\n Last14,\n\n [EnumDescription(\"Last 30 days\")]\n Last30,\n\n [EnumDescription(\"All\")]\n All\n} \n /// <summary>\n/// Provides a static utility object of methods and properties to interact\n/// with enumerated types.\n/// </summary>\npublic static class EnumHelper\n{\n /// <summary>\n /// Gets the <see cref=\"DescriptionAttribute\" /> of an <see cref=\"Enum\" /> \n /// type value.\n /// </summary>\n /// <param name=\"value\">The <see cref=\"Enum\" /> type value.</param>\n /// <returns>A string containing the text of the\n /// <see cref=\"DescriptionAttribute\"/>.</returns>\n public static string GetDescription(this Enum value)\n {\n if (value == null)\n {\n throw new ArgumentNullException(\"value\");\n }\n\n string description = value.ToString();\n FieldInfo fieldInfo = value.GetType().GetField(description);\n EnumDescriptionAttribute[] attributes =\n (EnumDescriptionAttribute[])\n fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);\n\n if (attributes != null && attributes.Length > 0)\n {\n description = attributes[0].Description;\n }\n return description;\n }\n\n /// <summary>\n /// Converts the <see cref=\"Enum\" /> type to an <see cref=\"IList\" /> \n /// compatible object.\n /// </summary>\n /// <param name=\"type\">The <see cref=\"Enum\"/> type.</param>\n /// <returns>An <see cref=\"IList\"/> containing the enumerated\n /// type value and description.</returns>\n public static IList ToList(this Type type)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n ArrayList list = new ArrayList();\n Array enumValues = Enum.GetValues(type);\n\n foreach (Enum value in enumValues)\n {\n list.Add(new KeyValuePair<Enum, string>(value, GetDescription(value)));\n }\n\n return list;\n }\n} \n combo.DataSource = typeof(SimpleEnum).ToList();\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,303
<p>Some days ago I realized that <a href="http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html" rel="noreferrer">PrintWriter</a> (as well as <a href="http://java.sun.com/javase/6/docs/api/java/io/PrintStream.html" rel="noreferrer">PrintStream</a>) <strong>never throw an IOException</strong> when writing, flushing or closing.</p> <p>Instead it sets an internal flag (<code>trouble=true</code>) when an error occurs.<br/> It's not possible to get the exact exception, but only <strong>if</strong> there was some exception (<a href="http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html#checkError()" rel="noreferrer">checkError()</a>).</p> <p>My question is: why would one want to have such behavior? Isn't that bad API design?</p>
[ { "answer_id": 297649, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "System.out System.err PrintStream PrintWriter PrintStream System.err" }, { "answer_id": 62482878, "author": "David L.", "author_id": 1182474, "author_profile": "https://Stackoverflow.com/users/1182474", "pm_score": 0, "selected": false, "text": "System.out System.err System.out System.err PrintWriter FileWriter OutputStreamWriter PrintWriter FileWriter FileWriter OutputStreamWriter" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ]
297,335
<p>I've got some code that will generically get all Controls in a form and put them in a list. Here's some of the code:</p> <pre><code> private List&lt;Control&gt; GetControlList(Form parentForm) { List&lt;Control&gt; controlList = new List&lt;Control&gt;(); AddControlsToList(parentForm.Controls, controlList); return controlList; } private void AddControlsToList(Control.ControlCollection rootControls, List&lt;Control&gt; controlList) { foreach (Control c in rootControls) { controlList.Add(c); if (c.HasChildren) AddControlsToList(c.Controls, controlList); // } } </code></pre> <p>So I'm only able to use c.HasChildren to check and see if there's any more child controls from this root control.</p> <p><strong>What about a menuStrip, toolStrip, and statusStrip? How do I get all of the controls that are in these controls generically? Ex: MenuStripItem</strong></p> <p>I know that I could try testing the c.GetType() == typeof(MenuStrip) but I was hoping to not have to do specific type tests.</p> <p>If I need to give more info, please ask.</p> <p>Thanks a bunch</p>
[ { "answer_id": 297378, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 4, "selected": true, "text": "Designer ComponentDesigner AssociatedComponents Timer DesignerAttribute ControlDesigner ComponentDesigner ComponentDesigner AssociatedComponents ToolStrip MenuStrip DesignerAttribute ToolStripDesigner /*\n * note that in C#, I can refer to the \"DesignerAttribute\" class within the [ brackets ]\n * by simply \"Designer\". The compiler adds the \"Attribute\" to the end for us (assuming\n * there's no attribute class named simply \"Designer\").\n */\n[Designer(\"System.Windows.Forms.Design.ToolStripDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"), ...(other attributes)]\npublic class ToolStrip : ScrollableControl, IArrangedElement, ...(other interfaces){\n ...\n}\n ToolStripDesigner Activator.CreateInstance ToolStripDesigner ComponentDesigner AssociatedComponents ArrayList ToolStrip /*\n * Some controls will require that we set their \"Site\" property before\n * we associate a IDesigner with them. This \"site\" is used by the\n * IDesigner to get services from the designer. Because we're not\n * implementing a real designer, we'll create a dummy site that\n * provides bare minimum services and which relies on the framework\n * for as much of its functionality as possible.\n */\nclass DummySite : ISite, IDisposable{\n DesignSurface designSurface;\n IComponent component;\n string name;\n\n public IComponent Component {get{return component;}}\n public IContainer Container {get{return designSurface.ComponentContainer;}}\n public bool DesignMode{get{return false;}}\n public string Name {get{return name;}set{name = value;}}\n\n public DummySite(IComponent component){\n this.component = component;\n designSurface = new DesignSurface();\n }\n ~DummySite(){Dispose(false);}\n\n protected virtual void Dispose(bool isDisposing){\n if(isDisposing)\n designSurface.Dispose();\n }\n\n public void Dispose(){\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n public object GetService(Type serviceType){return designSurface.GetService(serviceType);}\n}\n\nstatic void GetComponents(IComponent component, int level, Action<IComponent, int> action){\n action(component, level);\n\n bool visible, enabled;\n Control control = component as Control;\n if(control != null){\n /*\n * Attaching the IDesigner sets the Visible and Enabled properties to true.\n * This is useful when you're designing your form in Visual Studio, but at\n * runtime, we'd rather the controls maintain their state, so we'll save the\n * values of these properties and restore them after we detach the IDesigner.\n */\n visible = control.Visible;\n enabled = control.Enabled;\n\n foreach(Control child in control.Controls)\n GetComponents(child, level + 1, action);\n }else visible = enabled = false;\n\n /*\n * The TypeDescriptor class has a handy static method that gets\n * the DesignerAttribute of the type of the component we pass it\n * and creates an instance of the IDesigner class for us. This\n * saves us a lot of trouble.\n */\n ComponentDesigner des = TypeDescriptor.CreateDesigner(component, typeof(IDesigner)) as ComponentDesigner;\n if(des != null)\n try{\n DummySite site;\n if(component.Site == null)\n component.Site = site = new DummySite(component);\n else site = null;\n\n try{\n des.Initialize(component);\n foreach(IComponent child in des.AssociatedComponents)\n GetComponents(child, level + 1, action);\n }finally{\n if(site != null){\n component.Site = null;\n site.Dispose();\n }\n }\n }finally{des.Dispose();}\n\n if(control != null){\n control.Visible = visible;\n control.Enabled = enabled;\n }\n}\n\n\n/* We'll use this in the ListComponents call */\n[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\nstatic extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);\n\nconst int WM_SETREDRAW = 11;\n\nvoid ListComponents(){\n /*\n * Invisible controls and disabled controls will be temporarily shown and enabled\n * during the GetComponents call (see the comment within that call), so to keep\n * them from showing up and then disappearing again (or appearing to temporarily\n * change enabled state), we'll disable redrawing of our window and re-enable it\n * afterwards.\n */\n SendMessage(Handle, WM_SETREDRAW, 0, 0);\n GetComponents(this, 0,\n /* You'll want to do something more useful here */\n (component, level)=>System.Diagnostics.Debug.WriteLine(new string('\\t', level) + component));\n SendMessage(Handle, WM_SETREDRAW, 1, 0);\n}\n" }, { "answer_id": 297411, "author": "Joshua Tacoma", "author_id": 35514, "author_profile": "https://Stackoverflow.com/users/35514", "pm_score": 0, "selected": false, "text": "if (c is ToolStrip)\n foreach (ToolStripItem item in EnumerateTree(c, \"Items\"))\n if (item is ToolStripControlHost)\n AddControlsToList(\n new Control[] { ((ToolStripControlHost)item).Control },\n controlList);\n IEnumerable<Control>" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21828/" ]
297,345
<p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p> <p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p> <p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
[ { "answer_id": 297376, "author": "altunyurt", "author_id": 37491, "author_profile": "https://Stackoverflow.com/users/37491", "pm_score": 2, "selected": false, "text": "file = gzip.GzipFile('blah.gz', 'wb')\nsourcefile = open('source', 'rb')\nchunks = []\nfor line in sourcefile:\n chunks.append(line)\n if len(chunks) >= X: \n file.write(\"\".join(chunks))\n file.flush()\n chunks = []\n" }, { "answer_id": 297423, "author": "Oddthinking", "author_id": 8014, "author_profile": "https://Stackoverflow.com/users/8014", "pm_score": 0, "selected": false, "text": "class GzipFile([filename [,mode [,compresslevel [,fileobj]]]])\n" }, { "answer_id": 297711, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "def write(self, filename, arcname=None, compress_type=None):\n \"\"\"Put the bytes from filename into the archive under the name\n arcname.\"\"\"\n\n st = os.stat(filename)\n mtime = time.localtime(st.st_mtime)\n date_time = mtime[0:6]\n # Create ZipInfo instance to store file information\n if arcname is None:\n zinfo = ZipInfo(filename, date_time)\n else:\n zinfo = ZipInfo(arcname, date_time)\n zinfo.external_attr = st[0] << 16L # Unix attributes\n if compress_type is None:\n zinfo.compress_type = self.compression\n else:\n zinfo.compress_type = compress_type\n self._writecheck(zinfo)\n fp = open(filename, \"rb\")\n\n zinfo.flag_bits = 0x00\n zinfo.header_offset = self.fp.tell() # Start of header bytes\n # Must overwrite CRC and sizes with correct data later\n zinfo.CRC = CRC = 0\n zinfo.compress_size = compress_size = 0\n zinfo.file_size = file_size = 0\n self.fp.write(zinfo.FileHeader())\n zinfo.file_offset = self.fp.tell() # Start of file bytes\n if zinfo.compress_type == ZIP_DEFLATED:\n cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,\n zlib.DEFLATED, -15)\n else:\n cmpr = None\n while 1:\n buf = fp.read(1024 * 8)\n if not buf:\n break\n file_size = file_size + len(buf)\n CRC = binascii.crc32(buf, CRC)\n if cmpr:\n buf = cmpr.compress(buf)\n compress_size = compress_size + len(buf)\n self.fp.write(buf)\n fp.close()\n if cmpr:\n buf = cmpr.flush()\n compress_size = compress_size + len(buf)\n self.fp.write(buf)\n zinfo.compress_size = compress_size\n else:\n zinfo.compress_size = file_size\n zinfo.CRC = CRC\n zinfo.file_size = file_size\n # Seek backwards and write CRC and file sizes\n position = self.fp.tell() # Preserve current position in file\n self.fp.seek(zinfo.header_offset + 14, 0)\n self.fp.write(struct.pack(\"<lLL\", zinfo.CRC, zinfo.compress_size,\n zinfo.file_size))\n self.fp.seek(position, 0)\n self.filelist.append(zinfo)\n self.NameToInfo[zinfo.filename] = zinfo\n" }, { "answer_id": 299830, "author": "Chris B.", "author_id": 9161, "author_profile": "https://Stackoverflow.com/users/9161", "pm_score": 5, "selected": true, "text": "import zipfile, zlib, binascii, struct\nclass BufferedZipFile(zipfile.ZipFile):\n def writebuffered(self, zipinfo, buffer):\n zinfo = zipinfo\n\n zinfo.file_size = file_size = 0\n zinfo.flag_bits = 0x00\n zinfo.header_offset = self.fp.tell()\n\n self._writecheck(zinfo)\n self._didModify = True\n\n zinfo.CRC = CRC = 0\n zinfo.compress_size = compress_size = 0\n self.fp.write(zinfo.FileHeader())\n if zinfo.compress_type == zipfile.ZIP_DEFLATED:\n cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)\n else:\n cmpr = None\n\n while True:\n buf = buffer.read(1024 * 8)\n if not buf:\n break\n\n file_size = file_size + len(buf)\n CRC = binascii.crc32(buf, CRC) & 0xffffffff\n if cmpr:\n buf = cmpr.compress(buf)\n compress_size = compress_size + len(buf)\n\n self.fp.write(buf)\n\n if cmpr:\n buf = cmpr.flush()\n compress_size = compress_size + len(buf)\n self.fp.write(buf)\n zinfo.compress_size = compress_size\n else:\n zinfo.compress_size = file_size\n\n zinfo.CRC = CRC\n zinfo.file_size = file_size\n\n position = self.fp.tell()\n self.fp.seek(zinfo.header_offset + 14, 0)\n self.fp.write(struct.pack(\"<LLL\", zinfo.CRC, zinfo.compress_size, zinfo.file_size))\n self.fp.seek(position, 0)\n self.filelist.append(zinfo)\n self.NameToInfo[zinfo.filename] = zinfo\n" }, { "answer_id": 2734156, "author": "haridsv", "author_id": 95750, "author_profile": "https://Stackoverflow.com/users/95750", "pm_score": 3, "selected": false, "text": "import os\nimport threading\nfrom zipfile import *\nimport zlib, binascii, struct\n\nclass ZipEntryWriter(threading.Thread):\n def __init__(self, zf, zinfo, fileobj):\n self.zf = zf\n self.zinfo = zinfo\n self.fileobj = fileobj\n\n zinfo.file_size = 0\n zinfo.flag_bits = 0x00\n zinfo.header_offset = zf.fp.tell()\n\n zf._writecheck(zinfo)\n zf._didModify = True\n\n zinfo.CRC = 0\n zinfo.compress_size = compress_size = 0\n zf.fp.write(zinfo.FileHeader())\n\n super(ZipEntryWriter, self).__init__()\n\n def run(self):\n zinfo = self.zinfo\n zf = self.zf\n file_size = 0\n CRC = 0\n\n if zinfo.compress_type == ZIP_DEFLATED:\n cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)\n else:\n cmpr = None\n while True:\n buf = self.fileobj.read(1024 * 8)\n if not buf:\n self.fileobj.close()\n break\n\n file_size = file_size + len(buf)\n CRC = binascii.crc32(buf, CRC)\n if cmpr:\n buf = cmpr.compress(buf)\n compress_size = compress_size + len(buf)\n\n zf.fp.write(buf)\n\n if cmpr:\n buf = cmpr.flush()\n compress_size = compress_size + len(buf)\n zf.fp.write(buf)\n zinfo.compress_size = compress_size\n else:\n zinfo.compress_size = file_size\n\n zinfo.CRC = CRC\n zinfo.file_size = file_size\n\n position = zf.fp.tell()\n zf.fp.seek(zinfo.header_offset + 14, 0)\n zf.fp.write(struct.pack(\"<lLL\", zinfo.CRC, zinfo.compress_size, zinfo.file_size))\n zf.fp.seek(position, 0)\n zf.filelist.append(zinfo)\n zf.NameToInfo[zinfo.filename] = zinfo\n\nclass EnhZipFile(ZipFile, object):\n\n def _current_writer(self):\n return hasattr(self, 'cur_writer') and self.cur_writer or None\n\n def assert_no_current_writer(self):\n cur_writer = self._current_writer()\n if cur_writer and cur_writer.isAlive():\n raise ValueError('An entry is already started for name: %s' % cur_write.zinfo.filename)\n\n def write(self, filename, arcname=None, compress_type=None):\n self.assert_no_current_writer()\n super(EnhZipFile, self).write(filename, arcname, compress_type)\n\n def writestr(self, zinfo_or_arcname, bytes):\n self.assert_no_current_writer()\n super(EnhZipFile, self).writestr(zinfo_or_arcname, bytes)\n\n def close(self):\n self.finish_entry()\n super(EnhZipFile, self).close()\n\n def start_entry(self, zipinfo):\n \"\"\"\n Start writing a new entry with the specified ZipInfo and return a\n file like object. Any data written to the file like object is\n read by a background thread and written directly to the zip file.\n Make sure to close the returned file object, before closing the\n zipfile, or the close() would end up hanging indefinitely.\n\n Only one entry can be open at any time. If multiple entries need to\n be written, make sure to call finish_entry() before calling any of\n these methods:\n - start_entry\n - write\n - writestr\n It is not necessary to explicitly call finish_entry() before closing\n zipfile.\n\n Example:\n zf = EnhZipFile('tmp.zip', 'w')\n w = zf.start_entry(ZipInfo('t.txt'))\n w.write(\"some text\")\n w.close()\n zf.close()\n \"\"\"\n self.assert_no_current_writer()\n r, w = os.pipe()\n self.cur_writer = ZipEntryWriter(self, zipinfo, os.fdopen(r, 'r'))\n self.cur_writer.start()\n return os.fdopen(w, 'w')\n\n def finish_entry(self, timeout=None):\n \"\"\"\n Ensure that the ZipEntry that is currently being written is finished.\n Joins on any background thread to exit. It is safe to call this method\n multiple times.\n \"\"\"\n cur_writer = self._current_writer()\n if not cur_writer or not cur_writer.isAlive():\n return\n cur_writer.join(timeout)\n\nif __name__ == \"__main__\":\n zf = EnhZipFile('c:/tmp/t.zip', 'w')\n import time\n w = zf.start_entry(ZipInfo('t.txt', time.localtime()[:6]))\n w.write(\"Line1\\n\")\n w.write(\"Line2\\n\")\n w.close()\n zf.finish_entry()\n w = zf.start_entry(ZipInfo('p.txt', time.localtime()[:6]))\n w.write(\"Some text\\n\")\n w.close()\n zf.close()\n" }, { "answer_id": 43987831, "author": "jkitchen", "author_id": 639792, "author_profile": "https://Stackoverflow.com/users/639792", "pm_score": 1, "selected": false, "text": "import io\nimport zipfile\nimport zlib\nimport binascii\nimport struct\n\nclass ByteStreamer(io.BytesIO):\n '''\n Variant on BytesIO which lets you write and consume data while\n keeping track of the total filesize written. When data is consumed\n it is removed from memory, keeping the memory requirements low.\n '''\n def __init__(self):\n super(ByteStreamer, self).__init__()\n self._tellall = 0\n\n def tell(self):\n return self._tellall\n\n def write(self, b):\n orig_size = super(ByteStreamer, self).tell()\n super(ByteStreamer, self).write(b)\n new_size = super(ByteStreamer, self).tell()\n self._tellall += (new_size - orig_size)\n\n def consume(self):\n bytes = self.getvalue()\n self.seek(0)\n self.truncate(0)\n return bytes\n\nclass BufferedZipFileWriter(zipfile.ZipFile):\n '''\n ZipFile writer with true streaming (input and output).\n Created zip files are always ZIP64-style because it is the only safe way to stream\n potentially large zip files without knowing the full size ahead of time.\n\n Example usage:\n >>> def stream():\n >>> bzfw = BufferedZip64FileWriter()\n >>> for arc_path, buffer in inputs: # buffer is a file-like object which supports read(size)\n >>> for chunk in bzfw.streambuffer(arc_path, buffer):\n >>> yield chunk\n >>> yield bzfw.close()\n '''\n def __init__(self, compression=zipfile.ZIP_DEFLATED):\n self._buffer = ByteStreamer()\n super(BufferedZipFileWriter, self).__init__(self._buffer, mode='w', compression=compression, allowZip64=True)\n\n def streambuffer(self, zinfo_or_arcname, buffer, chunksize=2**16):\n if not isinstance(zinfo_or_arcname, zipfile.ZipInfo):\n zinfo = zipfile.ZipInfo(filename=zinfo_or_arcname,\n date_time=time.localtime(time.time())[:6])\n zinfo.compress_type = self.compression\n zinfo.external_attr = 0o600 << 16 # ?rw-------\n else:\n zinfo = zinfo_or_arcname\n\n zinfo.file_size = file_size = 0\n zinfo.flag_bits = 0x08 # Streaming mode: crc and size come after the data\n zinfo.header_offset = self.fp.tell()\n\n self._writecheck(zinfo)\n self._didModify = True\n\n zinfo.CRC = CRC = 0\n zinfo.compress_size = compress_size = 0\n self.fp.write(zinfo.FileHeader())\n if zinfo.compress_type == zipfile.ZIP_DEFLATED:\n cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)\n else:\n cmpr = None\n\n while True:\n buf = buffer.read(chunksize)\n if not buf:\n break\n\n file_size += len(buf)\n CRC = binascii.crc32(buf, CRC) & 0xffffffff\n if cmpr:\n buf = cmpr.compress(buf)\n compress_size += len(buf)\n\n self.fp.write(buf)\n compressed_bytes = self._buffer.consume()\n if compressed_bytes:\n yield compressed_bytes\n\n if cmpr:\n buf = cmpr.flush()\n compress_size += len(buf)\n self.fp.write(buf)\n zinfo.compress_size = compress_size\n compressed_bytes = self._buffer.consume()\n if compressed_bytes:\n yield compressed_bytes\n else:\n zinfo.compress_size = file_size\n\n zinfo.CRC = CRC\n zinfo.file_size = file_size\n\n # Write CRC and file sizes after the file data\n # Always write as zip64 -- only safe way to stream what might become a large zipfile\n fmt = '<LQQ'\n self.fp.write(struct.pack(fmt, zinfo.CRC, zinfo.compress_size, zinfo.file_size))\n\n self.fp.flush()\n self.filelist.append(zinfo)\n self.NameToInfo[zinfo.filename] = zinfo\n yield self._buffer.consume()\n\n # The close method needs to be patched to force writing a ZIP64 file\n # We'll hack ZIP_FILECOUNT_LIMIT to do the forcing\n def close(self):\n tmp = zipfile.ZIP_FILECOUNT_LIMIT\n zipfile.ZIP_FILECOUNT_LIMIT = 0\n super(BufferedZipFileWriter, self).close()\n zipfile.ZIP_FILECOUNT_LIMIT = tmp\n return self._buffer.consume()\n" }, { "answer_id": 55169752, "author": "don_vanchos", "author_id": 5717886, "author_profile": "https://Stackoverflow.com/users/5717886", "pm_score": 4, "selected": false, "text": "zipfile.ZipFile from zipfile import ZipFile, ZipInfo\n\ndef zipfile_generator(path, stream):\n with ZipFile(stream, mode='w') as zf:\n z_info = ZipInfo.from_file(path)\n with open(path, 'rb') as entry, zf.open(z_info, mode='w') as dest:\n for chunk in iter(lambda: entry.read(16384), b''):\n dest.write(chunk)\n # Yield chunk of the zip file stream in bytes.\n yield stream.get()\n # ZipFile was closed.\n yield stream.get()\n path pathlike stream from io import RawIOBase\n\nclass UnseekableStream(RawIOBase):\n def __init__(self):\n self._buffer = b''\n\n def writable(self):\n return True\n\n def write(self, b):\n if self.closed:\n raise ValueError('Stream was closed!')\n self._buffer += b\n return len(b)\n\n def get(self):\n chunk = self._buffer\n self._buffer = b''\n return chunk\n ZipInfo queue.Queue() UnseekableStream()" }, { "answer_id": 73155874, "author": "Aniket Das", "author_id": 18514243, "author_profile": "https://Stackoverflow.com/users/18514243", "pm_score": 0, "selected": false, "text": "file = gzip.GzipFile('blah.gz', 'wb')\nsourcefile = open('source', 'rb')\nchunks = []\nfor line in sourcefile:\n chunks.append(line)\n if len(chunks) >= X: \n file.write(\"\".join(chunks))\n file.flush()\n chunks = []\n" }, { "answer_id": 73493141, "author": "Michal Charemza", "author_id": 1319998, "author_profile": "https://Stackoverflow.com/users/1319998", "pm_score": 0, "selected": false, "text": "def file_data_1():\n yield b'Some bytes a'\n yield b'Some bytes b'\n\ndef file_data_2():\n yield b'Some bytes c'\n yield b'Some bytes d'\n from datetime import datetime\nfrom stream_zip import ZIP_64, stream_zip\n\ndef zip_member_files():\n modified_at = datetime.now()\n perms = 0o600\n yield 'my-file-1.txt', modified_at, perms, ZIP_64, file_data_1()\n yield 'my-file-2.txt', modified_at, perms, ZIP_64, file_data_2()\n\nzipped_chunks = stream_zip(zip_member_files()):\n with open('my.zip', 'wb') as f:\n for chunk in zipped_chunks:\n f.write(chunk)\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
297,349
<p>I am trying to use google search for my site:</p> <p><a href="http://www.houseofhawkins.com/search.php" rel="noreferrer">http://www.houseofhawkins.com/search.php</a></p> <p>It is not playing nice with some screen resolutions. Here is the code given from google:</p> <pre><code>&lt;div id="cse-search-results"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; var googleSearchIframeName = "cse-search-results"; var googleSearchFormName = "cse-search-box"; var googleSearchFrameWidth = 250; var googleSearchDomain = "www.google.com"; var googleSearchPath = "/cse"; &lt;/script&gt; &lt;script type="text/javascript" src="http://www.google.com/afsonline/show_afs_search.js"&gt;&lt;/script&gt; </code></pre> <p>I changed the "googleSearchFrameWidth" down to 250 thinking that should be setting the width in px, (it was 600 to start with). But with smaller screens (1024 * 768) it sticks out the side of my divs.</p> <p>Am I doing something stupid?</p>
[ { "answer_id": 1085229, "author": "Thomas Beck", "author_id": 131794, "author_profile": "https://Stackoverflow.com/users/131794", "pm_score": 3, "selected": false, "text": "style =\"width:500\" #cse-search-results iframe { }" }, { "answer_id": 1273628, "author": "dhorn", "author_id": 148632, "author_profile": "https://Stackoverflow.com/users/148632", "pm_score": 0, "selected": false, "text": "<style>\n#cse-search-results iframe {width: 200px; }\n</style>\n" }, { "answer_id": 2098900, "author": "Jacob Gube", "author_id": 140928, "author_profile": "https://Stackoverflow.com/users/140928", "pm_score": 3, "selected": true, "text": "googleSearchFrameWidth googleSearchFrame <script type=\"text/javascript\" src=\"http://www.google.com/afsonline/show_afs_search.js\"></script>\n <script> <script type=\"text/javascript\">\n document.getElementsByName('googleSearchFrame').item(0).width = 600;\n</script>\n 600px 250 getElementsByTagName('iFrame')" }, { "answer_id": 3092102, "author": "Xerri", "author_id": 204675, "author_profile": "https://Stackoverflow.com/users/204675", "pm_score": 2, "selected": false, "text": "<input type=\"hidden\" name=\"cof\" value=\"FORID:11;NB:1\" />\n #cse-search-results iframe {width: 100%;}\n" }, { "answer_id": 29440306, "author": "Ali Bektash", "author_id": 1792984, "author_profile": "https://Stackoverflow.com/users/1792984", "pm_score": 1, "selected": false, "text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js\"></script>\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"iframe[name='googleSearchFrame']\").css(\"width\",\"100%\");\n });\n</script>" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6486/" ]
297,371
<p>I want to stress test a web service method by calling it several thousand times in quick succession. The method has a single string parameter that I will vary on each call.</p> <p>I'm planning on writing a Powershell script to loop and call this method a number of times.</p> <p>Is there a better way to do this?</p>
[ { "answer_id": 53878777, "author": "davidp_1978", "author_id": 1988756, "author_profile": "https://Stackoverflow.com/users/1988756", "pm_score": 0, "selected": false, "text": "ForEach -Parallel ($item in $collection) { }\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
297,383
<p>I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from <code>as_p()</code>, <code>as_ul()</code>, etc does not reflect the updated Meta exclude.</p> <p>I assume then that the html is generated when the ModelForm is created not when the <code>as_*()</code> is called. Is there a way to force the update of the HTML? </p> <p>Is this even the best way to do it? I just assumed this <em>should</em> work.</p> <p>Thoughts?</p> <pre><code>from django.forms import ModelForm from testprogram.online_bookings.models import Passenger class PassengerInfoForm(ModelForm): def set_form_excludes(self, exclude_list): self.Meta.exclude = excludes_list class Meta: model = Passenger exclude = [] </code></pre>
[ { "answer_id": 297478, "author": "Daniel Naab", "author_id": 32638, "author_profile": "https://Stackoverflow.com/users/32638", "pm_score": 7, "selected": true, "text": "def get_form(exclude_list):\n class MyForm(ModelForm):\n class Meta:\n model = Passenger\n exclude = exclude_list\n return MyForm\n\nform_class = get_form(('field1', 'field2'))\nform = form_class()\n def PassengerForm(exclude_list, *args, **kwargs):\n class MyPassengerForm(ModelForm):\n class Meta:\n model = Passenger\n exclude = exclude_list\n\n def __init__(self):\n super(MyPassengerForm, self).__init__(*args, **kwargs)\n\n return MyPassengerForm()\n\nform = PassengerForm(('field1', 'field2'))\n" }, { "answer_id": 703888, "author": "user85461", "author_id": 85461, "author_profile": "https://Stackoverflow.com/users/85461", "pm_score": 4, "selected": false, "text": "class PassengerInfoForm(ModelForm):\n def __init__(self, *args, **kwargs):\n exclude_list=kwargs.pop('exclude_list', '')\n\n super(PassengerInfoForm, self).__init__(*args, **kwargs)\n\n for field in exclude_list:\n del self.fields[field]\n\n class Meta:\n model = Passenger\n\nform = PassengerInfoForm(exclude_list=['field1', 'field2'])\n" }, { "answer_id": 3840924, "author": "Hraban", "author_id": 464042, "author_profile": "https://Stackoverflow.com/users/464042", "pm_score": 2, "selected": false, "text": "from django.contrib.admin.widgets import AdminDateWidget\nfrom django.forms import ModelForm\nfrom django.db import models\n\ndef ModelFormFactory(some_model, *args, **kwargs):\n \"\"\"\n Create a ModelForm for some_model\n \"\"\"\n widdict = {}\n # set some widgets for special fields\n for field in some_model._meta.local_fields:\n if type(field) is models.DateField:\n widdict[field.name] = AdminDateWidget()\n\n class MyModelForm(ModelForm): # I use my personal BaseModelForm as parent\n class Meta:\n model = some_model\n widgets = widdict\n\n return MyModelForm(*args, **kwargs)\n" }, { "answer_id": 33685003, "author": "keisuke", "author_id": 2500650, "author_profile": "https://Stackoverflow.com/users/2500650", "pm_score": 2, "selected": false, "text": "modelform_factory from django.forms.models import modelform_factory\n\nfrom testprogram.online_bookings.models import Passenger\n\nexclude = ('field1', 'field2')\nCustomForm = modelform_factory(model=Passenger, exclude=exclude) # generates ModelForm dynamically\ncustom_form = CustomForm(data=request.POST, ...) # form instance\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ]
297,387
<p>I have a problem where I am attempting to update a set of attributes with a fixed value contained within a repeating section of an XML document using the <code>Microsoft.BizTalk.Streaming.ValueMutator</code>. </p> <p>For example the XML document which I am attempting to update contains the following input:</p> <pre><code>&lt;ns0:TestXML xmlns:ns0="http://Test.Schemas"&gt; &lt;ns0:NodeA&gt; &lt;ns0:NodeB&gt; &lt;ns0:alpha Id="1" Value="Apple" Type=""&gt;&lt;/ns0:alpha&gt; &lt;ns0:alpha Id="2" Value="Banana" Type=""&gt;&lt;/ns0:alpha&gt; &lt;ns0:alpha Id="3" Value="Car" Type=""&gt;&lt;/ns0:alpha&gt; &lt;ns0:alpha Id="4" Value="Duck" Type=""&gt;&lt;/ns0:alpha&gt; &lt;/ns0:NodeB&gt; &lt;/ns0:NodeA&gt; &lt;/ns0:TestXML&gt; </code></pre> <p>The code which I am attempting to use to update the XML document is:</p> <pre><code>XmlDocument xDocInput = new XmlDocument(); XmlDocument xDocOutput = new XmlDocument(); string inputFileName = @"C:\Input.xml"; string outputFileName = @"C:\Output.xml"; string newValue = "fruit"; string xpathToUpdate = "/*[namespace-uri()='http://Test.Schemas']/*[local-name()='NodeA']/*[local-name()='NodeB']/*[@Type]"; xDocInput.Load(inputFileName); using (MemoryStream memstream = new MemoryStream()) { xDocInput.Save(memstream); memstream.Position = 0; XPathCollection queries = new XPathCollection(); queries.Add(new XPathExpression(xpathToUpdate)); //ValueMutator xpathMatcher = new ValueMutator(this.XPathCallBack); //Get resulting stream into response xml xDocOutput.Load(new XPathMutatorStream(memstream, queries, delegate(int matchIdx, XPathExpression expr, string origValue, ref string finalValue) { finalValue = newValue; })); //System.Diagnostics.Trace.WriteLine("Trace: " + memstream.Length.ToString()); } xDocOutput.Save(outputFileName); </code></pre> <p>The resulting output of this code is the file "Output.xml". Contained within the output document "Output.xml" is the following output:</p> <pre><code>&lt;ns0:TestXML xmlns:ns0="http://Test.Schemas" &gt; &lt;ns0:NodeA&gt; &lt;ns0:NodeB&gt; &lt;ns0:alpha Id="1" Value="Apple" Type="" &gt;fruit&lt;/ns0:alpha&gt; &lt;ns0:alpha Id="2" Value="Banana" Type="" &gt;fruit&lt;/ns0:alpha&gt; &lt;ns0:alpha Id="3" Value="Child" Type="" &gt;fruit&lt;/ns0:alpha&gt; &lt;ns0:alpha Id="4" Value="Duck" Type="" &gt;fruit&lt;/ns0:alpha&gt; &lt;/ns0:NodeB&gt; &lt;/ns0:NodeA&gt; &lt;/ns0:TestXML&gt; </code></pre> <p>As you will notice the "alpha" element's text value is updated incorrectly. The desired result is to update all attributes named "Type" with the value "Fruit". What is going wrong and how is this problem solved?</p>
[ { "answer_id": 297453, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 0, "selected": false, "text": "//namespace-uri()='http://Test.Schemas']/*[local-name()='NodeA']/*[local-name()='NodeB']/*[@Type] /*[namespace-uri()='http://Test.Schemas']/*[local-name()='NodeA']/*[local-name()='NodeB']/@Type" }, { "answer_id": 297984, "author": "David Hall", "author_id": 2660, "author_profile": "https://Stackoverflow.com/users/2660", "pm_score": 3, "selected": true, "text": "string xpathToUpdate = \"/*[namespace-uri()='http://Test.Schemas']/*[local-name()='NodeA']/*[local-name()='NodeB']/*[local-name()='alpha']/@Type\";\n <ns0:TestXML xmlns:ns0=\"http://Test.Schemas\">\n <ns0:NodeA>\n <ns0:NodeB>\n <ns0:alpha Id=\"1\" Value=\"Apple\" Type=\"fruit\">\n </ns0:alpha>\n <ns0:alpha Id=\"2\" Value=\"Banana\" Type=\"fruit\">\n </ns0:alpha>\n <ns0:alpha Id=\"3\" Value=\"Car\" Type=\"fruit\">\n </ns0:alpha>\n <ns0:alpha Id=\"4\" Value=\"Duck\" Type=\"fruit\">\n </ns0:alpha>\n </ns0:NodeB>\n </ns0:NodeA>\n</ns0:TestXML>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3810/" ]
297,392
<p>I'm preferably looking for a SQL query to accomplish this, but other options might be useful too.</p>
[ { "answer_id": 297400, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 6, "selected": true, "text": "SELECT LAST_DDL_TIME, TIMESTAMP\nFROM USER_OBJECTS\nWHERE OBJECT_TYPE = 'PROCEDURE'\nAND OBJECT_NAME = 'MY_PROC';\n LAST_DDL_TIME TIMESTAMP" }, { "answer_id": 7991355, "author": "Keerthi", "author_id": 964362, "author_profile": "https://Stackoverflow.com/users/964362", "pm_score": 0, "selected": false, "text": "SELECT name, create_date, modify_date \nFROM sys.procedures order by modify_date desc\n" }, { "answer_id": 8131581, "author": "nayakam", "author_id": 136054, "author_profile": "https://Stackoverflow.com/users/136054", "pm_score": 0, "selected": false, "text": " SELECT * FROM ALL_OBJECTS WHERE OBJECT_NAME = 'OBJ_NAME' ;\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
297,398
<p>How can I validate date strings in Perl? I'd like to account for leap years and also time zones. Someone may enter dates in the following formats:</p> <pre> 11/17/2008 11/17/2008 3pm 11/17/2008 12:01am 11/17/2008 12:01am EST 11/17/2008 12:01am CST </pre>
[ { "answer_id": 298345, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 4, "selected": true, "text": "use DateTime::Format::DateManip; \n\nmy @dates = (\n '11/17/2008',\n '11/17/2008 3pm',\n '11/17/2008 12:01am',\n '11/17/2008 12:01am EST',\n '11/17/2008 12:01am CST',\n);\n\nfor my $date ( @dates ) {\n my $dt = DateTime::Format::DateManip->parse_datetime( $date );\n die \"Cannot parse date $date\" unless defined $dt;\n say $dt;\n}\n\n# no dies.. produced the following....\n# => 2008-11-17T00:00:00\n# => 2008-11-17T15:00:00\n# => 2008-11-17T00:01:00\n# => 2008-11-17T05:01:00\n# => 2008-11-17T06:01:00\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/297398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,417
<p>Can someone show me a regex to select <strong>#OnlinePopup_AFE53E2CACBF4D8196E6360D4DDB6B70</strong> its okay to assume <code>#OnlinePopup</code></p> <pre><code>~DCTM~dctm://aicpcudev/37004e1f8000219e?DMS_OBJECT_SPEC=RELATION_ID#OnlinePopup_AFE53E2CACBF4D8196E6360D4DDB6B70_11472026_1214836152225_6455280574472127786 </code></pre>
[ { "answer_id": 297428, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 3, "selected": true, "text": "#[^_]+_[^_]+\n #OnlinePopup_[A-F0-9]+\n" }, { "answer_id": 297430, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "/(#[^_]+_[^_]+)/\n" }, { "answer_id": 297442, "author": "Gavin Miller", "author_id": 33226, "author_profile": "https://Stackoverflow.com/users/33226", "pm_score": 0, "selected": false, "text": "(\\#OnlinePopup_.*?)_\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
297,420
<p>Does anyone have a list of email addresses that I can use to test my JS address validation script? I'm looking for as complete of a list as is reasonable to test the most common edge cases, if not all cases.</p>
[ { "answer_id": 297707, "author": "some", "author_id": 36866, "author_profile": "https://Stackoverflow.com/users/36866", "pm_score": 0, "selected": false, "text": "function isEmail(address) {\n var pos = address.lastIndexOf(\"@\");\n return pos > 0 && (address.lastIndexOf(\".\") > pos) && (address.length - pos > 4);\n}\n function isEmail(address) {\n var pos = address.lastIndexOf(\"@\");\n return pos > 0 && (address.lastIndexOf(\".\") > pos) && (address.length - pos > 4) ? \n {\n local:address.substr(0,pos < 0 ? 0 : pos),\n domain:address.substr(pos+1)\n }: false;\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38407/" ]
297,421
<p>Where can I set it? I need files to be encoded in UTF-8 by default... there is nothing in Tools -> Options or any other menu as far as I know :( </p> <p>P.S. I don't need to set default encoding for Project or so, I need it to be default for any files I create. Thanks for your help :)</p>
[ { "answer_id": 297436, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "Save As..." } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25413/" ]
297,426
<p>I'm writing a basic sprite engine for my own amusement and to get better aquainted with Java's 2d API. Currently I am making use of large numbers of separate .png files with transparent backgrounds to represent the various sprites and different frames of animation that I need. Most 'real world' game development projects seem to make use of 'sprite sheets' which contain multiple sprites or frames of animation within a single file. Also, rather than making use of native image transparency support, people often nominate an arbitrary colour that does not appear in the sprite pallette to be the transparent colour. How does one manage a file like this programatically?</p> <ul> <li>how do you know where one sprite starts and the next begins</li> <li>how do you deal with transparency</li> </ul> <p>There may be other factors that I've not thought of here, so I may add to the list above as I think of things or as people make suggestions (please do so in the comments).</p>
[ { "answer_id": 2760766, "author": "SAKIPOOH", "author_id": 331739, "author_profile": "https://Stackoverflow.com/users/331739", "pm_score": 0, "selected": false, "text": "currentframe=spritesheet.getSubimage(x, y, w, h); \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
297,431
<p>When I create a new instance of a ChannelFactory:</p> <pre><code>var factory = new ChannelFactory&lt;IMyService&gt;(); </code></pre> <p>and that I create a new channel, I have an exception saying that the address of the Endpoint is null. </p> <p>My configuration inside my web.config is as mentioned and everything is as it is supposed to be (especially the address of the endpoint).</p> <p>If I create a new MyServiceClientBase, it loads all the configuration from my channel factory:</p> <pre><code>var factoryWithClientBase = new MyServiceClientBase().ChannelFactory; Console.WriteLine(factoryWithClientBase.Endpoint.Address); //output the configuration inside the web.config var factoryWithChannelFactory = new ChannelFactory&lt;IMyService&gt;(); Console.WriteLine(factoryWithChannelFactory.Endpoint.Address); //output nothing (null) </code></pre> <p>Why?</p>
[ { "answer_id": 298110, "author": "AnAngel", "author_id": 38482, "author_profile": "https://Stackoverflow.com/users/38482", "pm_score": 3, "selected": false, "text": "<endpoint address=\"http://localhost:2000/MyService/\" binding=\"wsHttpBinding\"\n behaviorConfiguration=\"wsHttpBehaviour\" contract=\"IService\"\n name=\"MyWsHttpEndpoint\" />\n var factory = new ChannelFactory<IMyService>(\"MyWsHttpEndpoint\");\n" }, { "answer_id": 2486021, "author": "suparthawijaya", "author_id": 298299, "author_profile": "https://Stackoverflow.com/users/298299", "pm_score": 2, "selected": false, "text": "<endpoint address=\"http://localhost:2000/MyService/\" binding=\"wsHttpBinding\"\nbehaviorConfiguration=\"wsHttpBehaviour\" contract=\"TheCorrectNamespace.IService\"\nname=\"MyWsHttpEndpoint\" />\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
297,435
<p>If I have...</p> <pre><code>class Bunny &lt; ActiveRecord::Base has_many :carrots end </code></pre> <p>...how can I check in the View if <code>@bunny</code> has any carrots? I want to do something like this:</p> <pre><code>&lt;% if @bunny.carrots? %&gt; &lt;strong&gt;Yay! Carrots!&lt;/strong&gt; &lt;% for carrot in @bunny.carrots %&gt; You got a &lt;%=h carrot.color %&gt; carrot!&lt;br /&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>I know <code>@bunny.carrots?</code> doesn't work -- what would?</p>
[ { "answer_id": 297451, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 1, "selected": false, "text": " if @bunny.carrots.length>0\n unless @bunny.carrots.nil? || @bunny.carrots.length>0\n if @bunny.carrots.any?\n" }, { "answer_id": 297454, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 4, "selected": true, "text": "<% if @bunny.carrots.any? %>\n <strong>Yay! Carrots!</strong>\n <% for carrot in @bunny.carrots %>\n You got a <%=h carrot.color %> carrot!<br />\n <% end %>\n<% end %>\n" }, { "answer_id": 297463, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 2, "selected": false, "text": "unless @bunny.carrots.empty? \n" }, { "answer_id": 307314, "author": "Sarah Vessels", "author_id": 38743, "author_profile": "https://Stackoverflow.com/users/38743", "pm_score": 0, "selected": false, "text": "@bunny.carrots unless @bunny.carrots.empty?" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
297,438
<p>I'm using JPA (Hibernate's implementation) to annotate entity classes to persist to a relational database (MySQL or SQL Server). Is there an easy way to auto generate the database schema (table creation scripts) from the annotated classes?</p> <p>I'm still in the prototyping phase and anticipate frequent schema changes. I would like to be able to specify and change the data model from the annotated code. Grails is similar in that it generates the database from the domain classes.</p>
[ { "answer_id": 1068003, "author": "H2000", "author_id": 115887, "author_profile": "https://Stackoverflow.com/users/115887", "pm_score": 4, "selected": false, "text": "import java.util.Collection;\nimport java.util.Properties;\n\nimport org.hibernate.cfg.AnnotationConfiguration;\nimport org.hibernate.dialect.Dialect;\nimport org.hibernate.ejb.Ejb3Configuration;\n\n/**\n * SQL Creator for Tables according to JPA/Hibernate annotations.\n *\n * Use:\n *\n * {@link #createTablesScript()} To create the table creationg script\n *\n * {@link #dropTablesScript()} to create the table destruction script\n * \n */\npublic class SqlTableCreator {\n\n private final AnnotationConfiguration hibernateConfiguration;\n private final Properties dialectProps;\n\n public SqlTableCreator(final Collection<Class<?>> entities) {\n\n final Ejb3Configuration ejb3Configuration = new Ejb3Configuration();\n for (final Class<?> entity : entities) {\n ejb3Configuration.addAnnotatedClass(entity);\n }\n\n dialectProps = new Properties();\n dialectProps.put(\"hibernate.dialect\", \"org.hibernate.dialect.SQLServerDialect\");\n\n hibernateConfiguration = ejb3Configuration.getHibernateConfiguration();\n }\n\n /**\n * Create the SQL script to create all tables.\n * \n * @return A {@link String} representing the SQL script.\n */\n public String createTablesScript() {\n final StringBuilder script = new StringBuilder();\n\n final String[] creationScript = hibernateConfiguration.generateSchemaCreationScript(Dialect\n .getDialect(dialectProps));\n for (final String string : creationScript) {\n script.append(string).append(\";\\n\");\n }\n script.append(\"\\ngo\\n\\n\");\n\n return script.toString();\n }\n\n /**\n * Create the SQL script to drop all tables.\n * \n * @return A {@link String} representing the SQL script.\n */\n public String dropTablesScript() {\n final StringBuilder script = new StringBuilder();\n\n final String[] creationScript = hibernateConfiguration.generateDropSchemaScript(Dialect\n .getDialect(dialectProps));\n for (final String string : creationScript) {\n script.append(string).append(\";\\n\");\n }\n script.append(\"\\ngo\\n\\n\");\n\n return script.toString();\n }\n}\n" }, { "answer_id": 12970346, "author": "George Papatheodorou", "author_id": 1570793, "author_profile": "https://Stackoverflow.com/users/1570793", "pm_score": 2, "selected": false, "text": " <!-- CONTAINER-MANAGED JPA Entity manager factory (No need for persistence.xml)-->\n <bean id=\"emf\" class=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n <property name=\"dataSource\" ref=\"dataSource\"/>\n <property name=\"jpaVendorAdapter\" ref=\"jpaVendorAdapter\"/>\n <!-- Fine Grained JPA properties Create-Drop Records -->\n <property name=\"jpaProperties\">\n <props>\n <prop key=\"hibernate.hbm2ddl.auto\">create</prop>\n </props>\n </property> \n </bean> \n <!-- The JPA vendor -->\n <bean id=\"jpaVendorAdapter\" class=\"org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter\">\n <!-- <property name=\"database\" value=\"MySQL\"/> -->\n <property name=\"showSql\" value=\"true\"/>\n <!-- <property name=\"generateDdl\" value=\"true\"/> -->\n <property name=\"databasePlatform\" value=\"org.hibernate.dialect.MySQLDialect\"/> \n </bean> \n <bean id=\"transactionManager\" class=\"org.springframework.orm.jpa.JpaTransactionManager\">\n <property name=\"entityManagerFactory\" ref=\"emf\" />\n </bean>\n" }, { "answer_id": 18465392, "author": "sendon1982", "author_id": 2680640, "author_profile": "https://Stackoverflow.com/users/2680640", "pm_score": 2, "selected": false, "text": " <plugin>\n <!-- run command \"mvn hibernate3:hbm2ddl\" to generate DLL -->\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>hibernate3-maven-plugin</artifactId>\n <version>3.0</version>\n <configuration>\n <hibernatetool>\n <classpath>\n <path location=\"${project.build.directory}/classes\" />\n <path location=\"${project.basedir}/src/main/resources/META-INF/\" /> \n </classpath> \n\n <jpaconfiguration persistenceunit=\"galleryPersistenceUnit\" /> \n <hbm2ddl create=\"true\" export=\"false\" destdir=\"${project.basedir}/target\" drop=\"true\" outputfilename=\"mysql.sql\" format=\"true\" console=\"true\"/>\n </hibernatetool>\n </configuration>\n </plugin>\n" }, { "answer_id": 18524921, "author": "sendon1982", "author_id": 2680640, "author_profile": "https://Stackoverflow.com/users/2680640", "pm_score": 1, "selected": false, "text": "<property name=\"hibernate.hbm2ddl.auto\" value=\"update\"/>\n" }, { "answer_id": 27313680, "author": "Donatello", "author_id": 1034782, "author_profile": "https://Stackoverflow.com/users/1034782", "pm_score": 3, "selected": false, "text": "<property name=\"javax.persistence.schema-generation.scripts.action\" value=\"create\"/>\n<property name=\"javax.persistence.schema-generation.create-source\" value=\"metadata\"/>\n<property name=\"javax.persistence.schema-generation.scripts.create-target\" value=\"target/jpa/sql/create-schema.sql\"/>\n import java.io.IOException;\nimport java.util.Properties;\n\nimport javax.persistence.Persistence;\n\nimport org.hibernate.jpa.AvailableSettings;\n\npublic class JpaSchemaExport {\n\n public static void main(String[] args) throws IOException {\n execute(args[0], args[1]);\n System.exit(0);\n }\n\n public static void execute(String persistenceUnitName, String destination) {\n System.out.println(\"Generating DDL create script to : \" + destination);\n\n final Properties persistenceProperties = new Properties();\n\n // XXX force persistence properties : remove database target\n persistenceProperties.setProperty(org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, \"\");\n persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, \"none\");\n\n // XXX force persistence properties : define create script target from metadata to destination\n // persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_CREATE_SCHEMAS, \"true\");\n persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_SCRIPTS_ACTION, \"create\");\n persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_CREATE_SOURCE, \"metadata\");\n persistenceProperties.setProperty(AvailableSettings.SCHEMA_GEN_SCRIPTS_CREATE_TARGET, destination);\n\n Persistence.generateSchema(persistenceUnitName, persistenceProperties);\n }\n\n}\n <plugin>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.7</version>\n <executions>\n <execution>\n <id>generate-ddl-create</id>\n <phase>process-classes</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <target>\n <!-- ANT Task definition -->\n <java classname=\"com.orange.tools.jpa.JpaSchemaExport\"\n fork=\"true\" failonerror=\"true\">\n <arg value=\"${persistenceUnitName}\" />\n <arg value=\"target/jpa/sql/schema-create.sql\" />\n <!-- reference to the passed-in classpath reference -->\n <classpath refid=\"maven.compile.classpath\" />\n </java>\n </target>\n </configuration>\n\n </execution>\n </executions>\n </plugin>\n" }, { "answer_id": 33500471, "author": "Krystian", "author_id": 1397115, "author_profile": "https://Stackoverflow.com/users/1397115", "pm_score": 1, "selected": false, "text": "<property name=\"eclipselink.ddl-generation\" value=\"create-tables\"/>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.1\" xmlns=\"http://xmlns.jcp.org/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd\">\n <persistence-unit name=\"appDB\" transaction-type=\"JTA\">\n <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>\n <jta-data-source>LocalMySQL</jta-data-source>\n <class>entity.Us</class>\n <class>entity.Btl</class>\n <class>entity.Co</class>\n <properties>\n <property name=\"eclipselink.ddl-generation\" value=\"create-tables\"/>\n </properties>\n </persistence-unit>\n</persistence>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
297,460
<p>Is there any way to force Text-Mate to use a two-space tab instead of a full tab when editing HTML (Rails) documents?</p>
[ { "answer_id": 297466, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 5, "selected": true, "text": "Tabs: 4 2 Soft Tabs rhtml erb" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
297,465
<p>Is it possible to write a PL/SQL query to identify a complete list of a stored procedures dependencies? I'm only interested in identifying other stored procedures and I'd prefer not to limit the depth of nesting that it gets too either. For example, if A calls B, which calls C, which calls D, I'd want B, C and D reported as dependencies for A.</p>
[ { "answer_id": 297492, "author": "Eddie Awad", "author_id": 17273, "author_profile": "https://Stackoverflow.com/users/17273", "pm_score": 4, "selected": true, "text": " SELECT lvl\n , u.object_id\n , u.object_type\n , LPAD (' ', lvl) || object_name obj\n FROM ( SELECT LEVEL lvl, object_id\n FROM SYS.public_dependency s\n START WITH s.object_id =\n ( SELECT object_id\n FROM user_objects\n WHERE object_name = UPPER ('&OBJECT_NAME')\n AND object_type = UPPER ('&OBJECT_TYPE'))\n CONNECT BY s.object_id = PRIOR referenced_object_id\n GROUP BY LEVEL, object_id) tree\n , user_objects u\n WHERE tree.object_id = u.object_id\nORDER BY lvl\n/\n" }, { "answer_id": 397118, "author": "Dwayne King", "author_id": 49715, "author_profile": "https://Stackoverflow.com/users/49715", "pm_score": 2, "selected": false, "text": "...\nmysql := 'select count(*) from '||table_name_in;\nexecute immediate mysql;\n...\n" }, { "answer_id": 5649001, "author": "Kalpesh Nayak", "author_id": 706011, "author_profile": "https://Stackoverflow.com/users/706011", "pm_score": 2, "selected": false, "text": "select * from all_dependencies where owner = '&OWNER' and NAME='&OBJECT_NAME' \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
297,470
<p>I have a couple search forms, 1 with ~50 fields and the other with ~100. Typically, as the HTML spec says, I do searches using the GET method as no data is changed. I haven't run into this problem yet, but I'm wondering if I will run out of URL space soon?</p> <p>The limit of <a href="http://support.microsoft.com/kb/208427" rel="noreferrer">Internet Explorer</a> is 2083 characters. Other browsers, have a <a href="http://www.boutell.com/newfaq/misc/urllength.html" rel="noreferrer">much higher limit</a>. I'm running Apache, so the limit there is around 4000 characters, which IIS is 16384 characters.</p> <p>At 100 fields, say average field name length of 10 characters, that's already 5000 characters...amazing on the 100 field form, I haven't had any errors yet. (25% of the fields are multiple selects, so the field length is much longer.)</p> <p>So, I'm wondering what my options are. (Shortening the forms is not an option.) Here my ideas:</p> <ul> <li>Use POST. I don't like this as much because at the moment users can bookmark their searches and perform them again later--a really dang nice feature.</li> <li>Have JavaScript loop through the form to determine which fields are different than default, populate another form and submit that one. The user would of course bookmark the shortened version.</li> </ul> <p>Any other ideas?</p> <p>Also, does anyone know if the length is the encoded length or just plain text?</p> <p>I'm developing in PHP, but it probably doesn't make a difference.</p> <p><strong>Edit:</strong> I am unable to remove any fields; I am unable to shorten the form. This is what the client has asked for and they often do use a range of fields, in the different categories. I know that it's hard to think of a form that looks nice with this many fields, but the users don't have a problem understanding how it works.</p>
[ { "answer_id": 298089, "author": "Tom", "author_id": 26155, "author_profile": "https://Stackoverflow.com/users/26155", "pm_score": 1, "selected": false, "text": "GET <?php\nif (isset($_GET['token']))\n{\n $token = addslashes($_GET['token']);\n $qry = mysql_query(\"SELECT fields FROM searches WHERE token = '{$token}'\");\n if ($row = mysql_fetch_assoc($qry))\n {\n performSearch(unserialize($row['fields']));\n exit;\n }\n showError('Your saved search has been removed because it hasn\\'t been used in a while');\n exit;\n}\n$fields = addslashes(serialize($_POST));\n$token = sha1($_SERVER['REMOTE_ADDR'].rand());\nmysql_query(\"INSERT INTO searches (token, fields, save_time) Values ('{$token}', '{$fields}', NOW())\");\nheader('Location: ?token='.$token);\nexit;\n?>\n <?php\nmysql_query('DELETE FROM searches WHERE save_time < DATE_ADD(NOW(), INTERVAL -200 DAY)');\n?>\n" }, { "answer_id": 298585, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "hidden value select" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
297,471
<p>I get an error when I compile this code:</p> <pre><code>using System; public struct Vector2 { public event EventHandler trigger; public float X; public float Y; public Vector2 func() { Vector2 vector; vector.X = 1; vector.Y = 2; return vector; // error CS0165: Use of unassigned local variable 'vector' } } </code></pre> <p>hi!</p> <p>The compiler says: "Use of unassigned local variable 'vector'" and points to the return value. It looks to me that Vector2 become a reference type (without the event member it acts normally). What is happening?</p>
[ { "answer_id": 297481, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": true, "text": "Vector2 vector = new Vector2()\n" }, { "answer_id": 297509, "author": "Kennet Belenky", "author_id": 37788, "author_profile": "https://Stackoverflow.com/users/37788", "pm_score": 1, "selected": false, "text": "initobj initobj Vector2 Vector2 trigger" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38413/" ]
297,472
<p>I am trying to do a simple datagrid in Flex with a doubleclick event, but I cannot get <code>itemDoubleClick</code> to fire:</p> <pre><code>&lt;mx:DataGrid id="gridReportConversions" height="100%" width="100%" mouseEnabled="true" doubleClickEnabled="true" itemDoubleClick="refererRowDoubleClicked(event)"&gt; &lt;mx:columns&gt; &lt;mx:DataGridColumn width="75" dataField="qty" headerText="Qty" /&gt; &lt;mx:DataGridColumn dataField="referer" headerText="URL" /&gt; &lt;/mx:columns&gt; &lt;/mx:DataGrid&gt; </code></pre> <p>If I use the <code>itemClicked</code> event then the event is raised just fine. When I search for this problem I find many people saying 'you need to set <code>doubleClickEnabled=true</code>, but I've done that and it still doesn't work.</p> <p>This control is nested within quite a few levels of VBox and other containers. Surely I dont need to set <code>doubleClickEnabled</code> on each of those containers do I?</p> <p>Just to clarify how I tested this - I have an alert box in my <code>refererRowDoubleClicked</code> event handler and it never gets shown when I use <code>itemDoubleClick</code></p>
[ { "answer_id": 297481, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": true, "text": "Vector2 vector = new Vector2()\n" }, { "answer_id": 297509, "author": "Kennet Belenky", "author_id": 37788, "author_profile": "https://Stackoverflow.com/users/37788", "pm_score": 1, "selected": false, "text": "initobj initobj Vector2 Vector2 trigger" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
297,482
<p>I would like to be able to manipulate the DOM just before my page is sent to be printed. Internet Explorer has an event on the window object called "onbeforeprint" but this is proprietary and isn't supported by other browsers. Is it possible to do this via javascript (jQuery in particular, if possible)?</p> <p>Before you ask, I can't easily use a print media stylesheet to apply the changes as the elements I need to change have inline styles which can't be overridden with a global stylesheet. I need to override these inline styles for print purposes. It should be possible to modify the existing jQuery if needs be, however that would be a more time-consuming and risky change.</p> <p>Cheers, Zac</p>
[ { "answer_id": 297545, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 3, "selected": true, "text": "!important <div class=\"test\" style=\"color: blue;\">Some Text</div>\n .test {\n color: red !important;\n }\n" }, { "answer_id": 1868887, "author": "Olivier", "author_id": 218000, "author_profile": "https://Stackoverflow.com/users/218000", "pm_score": 2, "selected": false, "text": "function myPrint() {\n $(\"#myDiv\").css({\"border-color\":\"red\"});\n window.print();\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32935/" ]
297,498
<p>I am wondering if it is possible to use Code Access Security, and a custom permission class (and attribute), without having to register the assembly that the attribute is in, in the GAC.</p> <p>At the moment, I get a TypeLoadException when the method with my attribute is called, and I can't seem to get around it. Everything i've read seems to imply that you need to use the GAC in order to achieve this.</p> <p>Does anyone have any insight?</p> <p>I've tried to acheive the same end-goal with AOP using PostSharp or AspectDNG, but both of those add an addition dependency to my product, which is not ideal.</p>
[ { "answer_id": 297545, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 3, "selected": true, "text": "!important <div class=\"test\" style=\"color: blue;\">Some Text</div>\n .test {\n color: red !important;\n }\n" }, { "answer_id": 1868887, "author": "Olivier", "author_id": 218000, "author_profile": "https://Stackoverflow.com/users/218000", "pm_score": 2, "selected": false, "text": "function myPrint() {\n $(\"#myDiv\").css({\"border-color\":\"red\"});\n window.print();\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489/" ]
297,504
<p>Is there a way in MySQL to select rows which fall on a specific day, as in Mondays, using a date column?</p>
[ { "answer_id": 297513, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 4, "selected": true, "text": "SELECT * FROM foo WHERE DAYOFWEEK(bar) = 2\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3410/" ]
297,514
<p>I have the following makefile that I use to build a program (a kernel, actually) that I'm working on. Its from scratch and I'm learning about the process, so its not perfect, but I think its powerful enough at this point for my level of experience writing makefiles.</p> <pre><code>AS = nasm CC = gcc LD = ld TARGET = core BUILD = build SOURCES = source INCLUDE = include ASM = assembly VPATH = $(SOURCES) CFLAGS = -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions \ -nostdinc -fno-builtin -I $(INCLUDE) ASFLAGS = -f elf #CFILES = core.c consoleio.c system.c CFILES = $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) SFILES = assembly/start.asm SOBJS = $(SFILES:.asm=.o) COBJS = $(CFILES:.c=.o) OBJS = $(SOBJS) $(COBJS) build : $(TARGET).img $(TARGET).img : $(TARGET).elf c:/python26/python.exe concat.py stage1 stage2 pad.bin core.elf floppy.img $(TARGET).elf : $(OBJS) $(LD) -T link.ld -o $@ $^ $(SOBJS) : $(SFILES) $(AS) $(ASFLAGS) $&lt; -o $@ %.o: %.c @echo Compiling $&lt;... $(CC) $(CFLAGS) -c -o $@ $&lt; #Clean Script - Should clear out all .o files everywhere and all that. clean: -del *.img -del *.o -del assembly\*.o -del core.elf </code></pre> <p>My main issue with this makefile is that when I modify a header file that one or more C files include, the C files aren't rebuilt. I can fix this quite easily by having all of my header files be dependencies for all of my C files, but that would effectively cause a complete rebuild of the project any time I changed/added a header file, which would not be very graceful.</p> <p>What I want is for only the C files that <em>include</em> the header file I change to be rebuilt, and for the entire project to be linked again. I can do the linking by causing all header files to be dependencies of the target, but I cannot figure out how to make the C files be invalidated when their included header files are newer.</p> <p>I've heard that GCC has some commands to make this possible (so the makefile can somehow figure out which files need to be rebuilt) but I can't for the life of me find an actual implementation example to look at. Can someone post a solution that will enable this behavior in a makefile?</p> <p>EDIT: I should clarify, I'm familiar with the concept of putting the individual targets in and having each target.o require the header files. That requires me to be editing the makefile every time I include a header file somewhere, which is a bit of a pain. I'm looking for a solution that can derive the header file dependencies on its own, which I'm fairly certain I've seen in other projects.</p>
[ { "answer_id": 297523, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 3, "selected": false, "text": ".h %.o: %.c\n @echo Compiling $<...\n $(CC) $(CFLAGS) -c -o $@ $<\n\nfoo.c: bar.h\n# And so on...\n" }, { "answer_id": 297539, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "-M make depend" }, { "answer_id": 297543, "author": "Chris Dodd", "author_id": 29759, "author_profile": "https://Stackoverflow.com/users/29759", "pm_score": 2, "selected": false, "text": "$(OBJDIR)/%.d: %.c\n $(CC) -MM -MG $(CPPFLAGS) $< | sed -e 's,^\\([^:]*\\)\\.o[ ]*:,$(@D)/\\1.o $(@D)/\\1.d:,' >$@\n\nifneq ($(MAKECMDGOALS),clean)\ninclude $(SRCS:%.c=$(OBJDIR)/%.d)\nendif\n" }, { "answer_id": 2394668, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 4, "selected": false, "text": "sed depend: .depend\n\n.depend: $(SOURCES)\n rm -f ./.depend\n $(CC) $(CFLAGS) -MM $^>>./.depend;\n\ninclude .depend\n makedepend gcc -MM" }, { "answer_id": 2394677, "author": "jdizzle", "author_id": 70603, "author_profile": "https://Stackoverflow.com/users/70603", "pm_score": -1, "selected": false, "text": "mkdep #include" }, { "answer_id": 2501673, "author": "Martin Fido", "author_id": 62457, "author_profile": "https://Stackoverflow.com/users/62457", "pm_score": 4, "selected": false, "text": "DEPS := $(COBJS:.o=.d)\n\n-include $(DEPS)\n\n%.o: %.c\n $(CC) -c $(CFLAGS) -MM -MF $(patsubst %.o,%.d,$@) -o $@ $<\n obj/_file__c.o _file_.d _file_.o obj/_file_c.o" }, { "answer_id": 38154101, "author": "Tagar", "author_id": 470583, "author_profile": "https://Stackoverflow.com/users/470583", "pm_score": 1, "selected": false, "text": "CC = g++\nCFLAGS = -Wall -g -std=c++0x\nINCLUDES = -I./includes/\n\n# LFLAGS = -L../lib\n# LIBS = -lmylib -lm\n\n# List of all source files\nSRCS = main.cc cache.cc\n\n# Object files defined from source files\nOBJS = $(SRCS:.cc=.o)\n\n# # define the executable file \nMAIN = cache_test\n\n#List of non-file based targets:\n.PHONY: depend clean all\n\n## .DEFAULT_GOAL := all\n\n# List of dependencies defined from list of object files\nDEPS := $(OBJS:.o=.d)\n\nall: $(MAIN)\n\n-include $(DEPS)\n\n$(MAIN): $(OBJS)\n $(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS) $(LFLAGS) $(LIBS)\n\n#suffix replacement rule for building .o's from .cc's\n#build dependency files first, second line actually compiles into .o\n.cc.o:\n $(CC) $(CFLAGS) $(INCLUDES) -c -MM -MF $(patsubst %.o,%.d,$@) $<\n $(CC) $(CFLAGS) $(INCLUDES) -c -o $@ $<\n\nclean:\n $(RM) *.o *~ $(MAIN) *.d\n $(CC) $(CFLAGS) $(INCLUDES) -c -MM -MF $(patsubst %.o,%.d,$@) $<\n$(CC) $(CFLAGS) $(INCLUDES) -c -o $@ $<\n" }, { "answer_id": 39296543, "author": "Richard Elkins", "author_id": 6169583, "author_profile": "https://Stackoverflow.com/users/6169583", "pm_score": 2, "selected": false, "text": "DEPENDENCIES=mydefs.h yourdefs.h Makefile GameOfThrones.S07E01.mkv\n\n::: (your other Makefile statements like rules \n::: for constructing executables or libraries)\n\n# Compile any .c to the corresponding .o file:\n%.o: %.c $(DEPENDENCIES)\n $(CC) $(CFLAGS) -c -o $@ $<\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
297,517
<p>I have a user control that has several buttons.</p> <p>On <code>page_load</code>, I want to run a method unless a specific button was pressed.</p> <p>When I check the sender on <code>page_load</code> inside the user control, I just get the name of the user control and not the button itself.</p> <p>Is there a way that I can determine what button was pressed on <code>page_load</code>? Otherwise I will have to come up with some hacky method to solve the issue.</p>
[ { "answer_id": 297546, "author": "Chris Roberts", "author_id": 475, "author_profile": "https://Stackoverflow.com/users/475", "pm_score": 2, "selected": false, "text": "Request.Form (\"__EVENTTARGET\") ClientID ClientID" }, { "answer_id": 534635, "author": "Geri Langlois", "author_id": 4888, "author_profile": "https://Stackoverflow.com/users/4888", "pm_score": 0, "selected": false, "text": "protected bool isButtonClicked(string buttonName)\n {\n bool isClicked = false;\n foreach (string ctl in this.Request.Form)\n {\n if (ctl.EndsWith(buttonName))\n {\n isButtonClicked = true;\n break;\n }\n }\n return isClicked;\n } \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
297,526
<p>I do remember seeing someone ask something along these lines a while ago but I did a search and couldn't find anything. </p> <p>I'm trying to come up with the cleanest way to clear all the controls on a form back to their defaults (e.g., clear textboxes, uncheck checkboxes).</p> <p>How would you go about this?</p>
[ { "answer_id": 297529, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 5, "selected": true, "text": "public static class extenstions\n{\n private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { \n {typeof(TextBox), c => ((TextBox)c).Clear()},\n {typeof(CheckBox), c => ((CheckBox)c).Checked = false},\n {typeof(ListBox), c => ((ListBox)c).Items.Clear()},\n {typeof(RadioButton), c => ((RadioButton)c).Checked = false},\n {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},\n {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}\n };\n\n private static void FindAndInvoke(Type type, Control control) \n {\n if (controldefaults.ContainsKey(type)) {\n controldefaults[type].Invoke(control);\n }\n }\n\n public static void ClearControls(this Control.ControlCollection controls)\n {\n foreach (Control control in controls)\n {\n FindAndInvoke(control.GetType(), control);\n }\n }\n\n public static void ClearControls<T>(this Control.ControlCollection controls) where T : class \n {\n if (!controldefaults.ContainsKey(typeof(T))) return;\n\n foreach (Control control in controls)\n {\n if (control.GetType().Equals(typeof(T)))\n {\n FindAndInvoke(typeof(T), control);\n }\n } \n\n }\n\n}\n private void button1_Click(object sender, EventArgs e)\n {\n this.Controls.ClearControls();\n }\n this.Controls.ClearControls<TextBox>();\n" }, { "answer_id": 297534, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "foreach (Control ctrl in this)\n{\n if(ctrl is TextBox)\n (ctrl as TextBox).Clear();\n}\n" }, { "answer_id": 297698, "author": "Chuck Conway", "author_id": 17360, "author_profile": "https://Stackoverflow.com/users/17360", "pm_score": 0, "selected": false, "text": "//Clears the textboxes\nWebControlUtilities.ClearControls<TextBox>(myPanel.Controls);\n /// <summary>\n /// Clears Text from Controls...ie TextBox, Label, anything that implements ITextBox\n /// </summary>\n /// <typeparam name=\"T\">Collection Type, ie. ContentPlaceHolder..</typeparam>\n /// <typeparam name=\"C\">ie TextBox, Label, anything that implements ITextBox</typeparam>\n /// <param name=\"controls\"></param>\n public static void Clear<T, C>(ControlCollection controls)\n where C : ITextControl\n where T : Control\n {\n IEnumerable<T> placeHolders = controls.OfType<T>();\n List<T> holders = placeHolders.ToList();\n\n foreach (T holder in holders)\n {\n IEnumerable<C> enumBoxes = holder.Controls.OfType<C>();\n List<C> boxes = enumBoxes.ToList();\n\n foreach (C box in boxes)\n {\n box.Text = string.Empty;\n }\n }\n }\n\n /// <summary>\n /// Clears the text from control.\n /// </summary>\n /// <typeparam name=\"C\"></typeparam>\n /// <param name=\"controls\">The controls.</param>\n public static void ClearControls<C>(ControlCollection controls) where C : ITextControl\n {\n IEnumerable<C> enumBoxes = controls.OfType<C>();\n List<C> boxes = enumBoxes.ToList();\n\n foreach (C box in boxes)\n {\n box.Text = string.Empty;\n }\n }\n" }, { "answer_id": 297772, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 2, "selected": false, "text": "public void ClearControl(Control control)\n{\n TextBox tb = control as TextBox;\n if (tb != null)\n {\n tb.Text = String.Empty;\n }\n // repeat for combobox, listbox, checkbox and any other controls you want to clear\n if (control.HasChildren)\n {\n foreach(Control child in control.Controls)\n {\n ClearControl(child)\n }\n }\n}\n" }, { "answer_id": 297862, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 2, "selected": false, "text": "Public Module Extension\n Private Sub ClearTextBox(ByVal T As TextBox)\n T.Clear()\n End Sub\n\n Private Sub ClearCheckBox(ByVal T As CheckBox)\n T.Checked = False\n End Sub\n\n Private Sub ClearListBox(ByVal T As ListBox)\n T.Items.Clear()\n End Sub\n\n Private Sub ClearGroupbox(ByVal T As GroupBox)\n T.Controls.ClearControls()\n End Sub\n\n <Runtime.CompilerServices.Extension()> _\n Public Sub ClearControls(ByVal Controls As ControlCollection)\n For Each Control In Controls\n If ControlDefaults.ContainsKey(Control.GetType()) Then\n ControlDefaults(Control.GetType()).Invoke(Control)\n End If\n Next\n End Sub\n\n Private _ControlDefaults As Dictionary(Of Type, Action(Of Control))\n Private ReadOnly Property ControlDefaults() As Dictionary(Of Type, Action(Of Control))\n Get\n If (_ControlDefaults Is Nothing) Then\n _ControlDefaults = New Dictionary(Of Type, Action(Of Control))\n _ControlDefaults.Add(GetType(TextBox), AddressOf ClearTextBox)\n _ControlDefaults.Add(GetType(CheckBox), AddressOf ClearCheckBox)\n _ControlDefaults.Add(GetType(ListBox), AddressOf ClearListBox)\n _ControlDefaults.Add(GetType(GroupBox), AddressOf ClearGroupbox)\n End If\n Return _ControlDefaults\n End Get\n End Property\n\nEnd Module\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n Me.Controls.ClearControls()\n End Sub\n" }, { "answer_id": 13025794, "author": "Isuru", "author_id": 1077789, "author_profile": "https://Stackoverflow.com/users/1077789", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Windows.Forms;\n\nnamespace FormClearing\n{\n class Helper\n {\n public static void ClearFormControls(Form form)\n {\n foreach (Control control in form.Controls)\n {\n if (control is TextBox)\n {\n TextBox txtbox = (TextBox)control;\n txtbox.Text = string.Empty;\n }\n else if(control is CheckBox)\n {\n CheckBox chkbox = (CheckBox)control;\n chkbox.Checked = false;\n }\n else if (control is RadioButton)\n {\n RadioButton rdbtn = (RadioButton)control;\n rdbtn.Checked = false;\n }\n else if (control is DateTimePicker)\n {\n DateTimePicker dtp = (DateTimePicker)control;\n dtp.Value = DateTime.Now;\n }\n }\n }\n }\n}\n Helper.ClearFormControls(this);\n" }, { "answer_id": 71644170, "author": "soyer", "author_id": 14222464, "author_profile": "https://Stackoverflow.com/users/14222464", "pm_score": 0, "selected": false, "text": " public void Clear()\n{\n foreach (var item in this.Controls)\n {\n if (item is TextBox)\n {\n TextBox text = (TextBox)item;\n text.Clear();\n\n //text.Text = \"\";\n //text.Text=String.Empty;\n //text.Text = null;\n }\n else if (item is NumericUpDown)\n {\n NumericUpDown numeric = (NumericUpDown)item;\n numeric.Value = 0;\n }\n else if (item is DateTimePicker)\n {\n DateTimePicker dateTimePicker = (DateTimePicker)item;\n dateTimePicker.Value = DateTime.Now;\n }\n }\n //Focus the cursor where you want to \n txtBookName.Focus();\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
297,530
<p>I have a view that I would like the user to rotate around its center, by tapping and holding somewhere and just move their finger round and round.</p> <p>I have all the geometry worked out; What I do is store the initial touch angle relative to the center as offsetAngle, then my touchesMoved method looks like this:</p> <pre><code>- (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event { self.transform = CGAffineTransformMakeRotation(0); CGPoint location = [[touches anyObject] locationInView: self]; CGPoint actualCenter = [self convertPoint: self.center fromView: self.superview]; CGPoint relativeTouch = [MathHelper translatePoint:location relativeTo: actualCenter]; CGPoint zero = CGPointMake(0, 0); float angle = [MathHelper getAngleForPoint:zero andPoint:relativeTouch]; self.transform = CGAffineTransformMakeRotation(offsetAngle-angle); } </code></pre> <p>The ugly bit is the first line, where I have to restore the rotation in order to get the correct event positions in the view. If I don't that, then the locations jump all over the place as there's no continuity, since the view is rotating...</p> <p>Another issue is when you want to manipulate a view's frame (eg. moving it down), when the view has a transform applied:</p> <pre><code>- (IBAction)toggleSettingsView { BOOL state = [settingsSwitch isOn]; float height = optionsView.bounds.size.height; CGRect polygonFrame = polygonView.frame; [UIView beginAnimations:@"advancedAnimations" context:nil]; [UIView setAnimationDuration:0.3]; if (state) { optionsView.alpha = 1.0; polygonFrame.origin.y += height; } else { optionsView.alpha = 0.0; polygonFrame.origin.y -= height; } polygonView.frame = polygonFrame; [UIView commitAnimations]; } </code></pre> <p>This distorts the view heavily.</p> <p>I must mention that both the CGTransform and the CALayer transform have the same effect.</p> <p>This smells like I'm doing something wrong, but I don't know what I should be doing.</p>
[ { "answer_id": 299787, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 2, "selected": false, "text": "- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event\n{\n CGPoint location = [[touches anyObject] locationInView:self.superview];\n CGPoint relativeTouch = [MathHelper translatePoint:location relativeTo:self.center];\n CGPoint zero = CGPointMake(0, 0);\n float angle = [MathHelper getAngleForPoint:zero andPoint:relativeTouch];\n self.transform = CGAffineTransformMakeRotation(offsetAngle-angle);\n}" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32617/" ]
297,542
<p>I would like to be able to detect what country a visitor is from on my website, using PHP. </p> <p>Please note that I'm not trying to use this as a security measure or for anything important, just changing the spelling of some words <em>(Americans seems to believe that the word "enrolment" has 2 Ls.... crazy yanks)</em>, and perhaps to give a default option in a "Select your country" list.</p> <p>As such, using a Geolocation database is a tad over-the-top and I really don't want to muck about with installing new PHP libraries just for this, so <strong>what's the easiest/simplest way to find what country a visitor is from?</strong></p>
[ { "answer_id": 297549, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 3, "selected": false, "text": " Example: http://api.hostip.info/get_html.php?ip=12.215.42.19\n Return : Country: UNITED STATES (US)\n" }, { "answer_id": 297559, "author": "chroder", "author_id": 18802, "author_profile": "https://Stackoverflow.com/users/18802", "pm_score": 4, "selected": false, "text": "HTTP_ACCEPT_LANGUAGE $_SERVER" }, { "answer_id": 297723, "author": "Slipo", "author_id": 38432, "author_profile": "https://Stackoverflow.com/users/38432", "pm_score": 2, "selected": false, "text": "$_SERVER[\"HTTP_ACCEPT_LANGUAGE\"]" }, { "answer_id": 15990323, "author": "Tomasz Brzezina", "author_id": 354420, "author_profile": "https://Stackoverflow.com/users/354420", "pm_score": 0, "selected": false, "text": "$SystemLocales = explode(\"\\n\", shell_exec('locale -a'));\n$BrowserLocales = explode(\",\",str_replace(\"-\",\"_\",$_SERVER[\"HTTP_ACCEPT_LANGUAGE\"])); // brosers use en-US, Linux uses en_US\nfor($i=0;$i<count($BrowserLocales);$i++) { \n list($BrowserLocales[$i])=explode(\";\",$BrowserLocales[$i]); //trick for \"en;q=0.8\"\n for($j=0;$j<count($SystemLocales);$j++) {\n if ($BrowserLocales[$i]==substr($SystemLocales[$j],0,strlen($BrowserLocales[$i]))){\n setlocale(LC_ALL, $SystemLocales[$j]);\n break 2; // found and set, so no more check is needed\n }\n }\n}\n" }, { "answer_id": 22334417, "author": "Trevor Goodyear", "author_id": 2260114, "author_profile": "https://Stackoverflow.com/users/2260114", "pm_score": 5, "selected": false, "text": "$_SERVER['HTTP_ACCEPT_LANGUAGE'] $locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);\necho $locale; // returns \"en_US\"\n" }, { "answer_id": 42521367, "author": "Mircea Stanciu", "author_id": 1643711, "author_profile": "https://Stackoverflow.com/users/1643711", "pm_score": 2, "selected": false, "text": " $localePreferences = explode(\",\",$_SERVER['HTTP_ACCEPT_LANGUAGE']);\n if(is_array($localePreferences) && count($localePreferences) > 0) {\n $browserLocale = $localePreferences[0];\n $_SESSION['browser_locale'] = $browserLocale;\n }\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
297,555
<p>I have a multipart form that takes basic user information at the beginning with some jquery.validate error checking to see if the fields have been filled in and the email address is valid.</p> <p>Below that there is a series of check boxes (type_of_request) for new accounts, delete accounts, new software etc which show/hide those form elements as they are checked/unchecked.</p> <p>I would like to validate the required sections on the form ONLY if the corressponding type_of_request item has been checked.</p> <hr> <p>Update information</p> <hr> <p>That's a great solution but seems to make all of the children of the selected section required.</p> <p>A typical scenario will be both the email and other checkbox in the type_request has been selected:</p> <pre><code> &lt;div id="email" style="display: block;"&gt; // shown because other has been selected in the type request &lt;input id="email_new_account" class="sq-form-field" type="checkbox" value="0" name="q4836:q1"/&gt; // not required &lt;input id="email_new_account_name" class="sq-form-field" type="text" name="q4836:q2"/&gt; // if email_new_account checked then make required &lt;input id="email_new_account_access" class="sq-form-field" type="text" name="q4836:q2"/&gt; // if email_new_account checked then make required &lt;input id="email_new_account_manager" class="sq-form-field" type="text" name="q4836:q3"/&gt; // if email_new_account checked then make required &lt;input id="email_add_remove_access" class="sq-form-field" type="checkbox" value="0" name="q4837:q1"/&gt; // not required &lt;input id="email_add_remove_account_name" class="sq-form-field" type="text" name="q4837:q2"/&gt; // if email_add_remove_access checked then make required &lt;input id="email_add_access" class="sq-form-field" type="text" name="q4836:q2"/&gt; // if email_add_remove_access checked then make required &lt;input id="email_remove_access" class="sq-form-field" type="text" name="q4837:q3"/&gt; // if email_add_remove_access checked then make required &lt;/div&gt; &lt;div id="other" style="display: block;"&gt; // shown because other has been selected in the type request &lt;input id="other_describe_request" class="sq-form-field" type="text" name="q4838:q1"/&gt; // required because #other was checked in type request &lt;input id="other_request_justification" class="sq-form-field" type="text" name="q48387:q2"/&gt; // required because #other was checked in type request &lt;/div&gt; </code></pre> <hr> <p>Further Reading</p> <hr> <p>I have reviewed this even further and found that the following can be added to the class of the input items</p> <pre><code>class="{required:true, messages:{required:'Please enter your email address'}}" </code></pre> <p>or</p> <pre><code>class="{required:true, email:true, messages:{required:'Please enter your email address', email:'Please enter a valid email address'}}" </code></pre> <p>but when I add </p> <pre><code>class="{required:'input[@name=other]:checked'}" </code></pre> <p>which was described on the <a href="http://jquery.bassistance.de/api-browser/plugins.html#jQueryvalidatormethodsrequiredStringElementBooleanStringFunction" rel="nofollow noreferrer">http://jquery.bassistance.de</a> site, it doesn't work. Do I need to change the syntax to get this working?</p>
[ { "answer_id": 297597, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "$(document).ready( function() { $('form').validate(); } );\n\nfunction init_validation(divName)\n{\n $('div#' + divName).find('input').addClass( 'required' );\n $('div#inputs').children('div:not(#' + divName + ')')\n .find('input')\n .removeClass( 'required' );\n}\n <form>\n<div>\n <input type='radio'\n id='new_account_radio'\n name='interface_selector'\n value='new_account'\n selected=true\n onclick='init_validation(\"new_account\");' /> New Account\n\n <input type='radio'\n id='delete_account_radio'\n name='interface_selector'\n value='delete_account'\n onclick='init_validation(\"delete_account\");' /> Delete Account\n\n <input type='radio'\n id='new_software_radio'\n name='interface_selector'\n value='new_software'\n onclick='init_validation(\"new_software\");' /> New Software\n\n</div>\n\n<div id='inputs'>\n <div id='new_account'>\n <input type='text' id='new_account_name' class='required' />\n </div>\n\n <div id='delete_account'>\n <input type='text' id='delete_account_name' />\n </div>\n\n <div id='new_software'>\n <input type='text' id='new_software_name' />\n </div>\n</div>\n</form>\n" }, { "answer_id": 319290, "author": "justinavery", "author_id": 38419, "author_profile": "https://Stackoverflow.com/users/38419", "pm_score": 2, "selected": true, "text": "<fieldset id=\"request-type\">\n<legend>Type of Request</legend>\n<ul>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_0\" value=\"0\" class=\"sq-form-field\" /><label for=\"q4838_q1_0\">New account</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_1\" value=\"1\" class=\"sq-form-field\" /><label for=\"q4838_q1_1\">Delete account</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_2\" value=\"2\" class=\"sq-form-field\" /><label for=\"q4838_q1_2\">Change access/account transfer</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_3\" value=\"3\" class=\"sq-form-field\" /><label for=\"q4838_q1_3\">Hardware</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_4\" value=\"4\" class=\"sq-form-field\" /><label for=\"q4838_q1_4\">Software</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_5\" value=\"5\" class=\"sq-form-field\" /><label for=\"q4838_q1_5\">Email</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_6\" value=\"6\" class=\"sq-form-field\" /><label for=\"q4838_q1_6\">Other</label></li>\n</ul>\n</fieldset>\n <fieldset id=\"delete-account\" style=\"display: block;\">\n class=\"{required:'#checkboxid:checked', messages:{required:'required error message'}}\"\n <fieldset id=\"delete-account\" style=\"display: block;\">\n<legend>Delete Account</legend>\n\n<label for=\"q4832_q1\">Cessation date</label>\n<input type=\"text\" name=\"q4832:q1value[d]\" value=\"\" class=\"{required:'#q4838_q1_1:checked', messages:{required:'Enter Cessation Date'}}\" id=\"q4832:q1value[d]\" />\n\n<label for=\"q4832_q1\">List of assets</label>\n<input type=\"text\" name=\"q4832:q2\" value=\"\" class=\"{required:'#q4838_q1_1:checked', messages:{required:'Enter Cessation Date'}}\" id=\"q4832:q2\" />\n</fieldset>\n {required:'true', messages:{required:'This field is required'}} #checkboxid:checked 'true' 'false' class=\"{required:'true', minlength:1, messages:{required:'Please select a checkbox'}}\"\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38419/" ]
297,563
<p>I have a property defined in my HBM file like this:</p> <pre><code>&lt;property name="OwnerId" column="OwnerID" type="System.Int32" not-null="false" /&gt; </code></pre> <p>It is defined as a nullable field in the database also. If a record in the DB has the OwnerID column set to an integer, this object is correctly loaded by NHibernate. But if the record has it set to null, NHibernate bombs with seemingly random errors including:</p> <p>1) Column name 'ModuleAnchorID' appears more than once in the result column list:</p> <pre><code>[SqlException (0x80131904): Column name 'ModuleAnchorID' appears more than once in the result column list.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +925466 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800118 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +1005 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +149 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135 NHibernate.Impl.NonBatchingBatcher.AddToBatch(IExpectation expectation) +35 NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session) +1055 </code></pre> <p>2) not-null property references a null or transient value:</p> <pre><code>[PropertyValueException: not-null property references a null or transient value:] NHibernate.Impl.SessionImpl.CheckNullability(Object[] values, IEntityPersister persister, Boolean isUpdate) +224 NHibernate.Impl.SessionImpl.FlushEntity(Object obj, EntityEntry entry) +1019 NHibernate.Impl.SessionImpl.FlushEntities() +182 NHibernate.Impl.SessionImpl.FlushEverything() +90 NHibernate.Impl.SessionImpl.AutoFlushIfRequired(ISet querySpaces) +64 NHibernate.Impl.SessionImpl.Find(CriteriaImpl criteria, IList results) +217 NHibernate.Impl.SessionImpl.Find(CriteriaImpl criteria) +42 NHibernate.Impl.CriteriaImpl.List() +29 </code></pre> <p>Is OwnerID a reserved field name that is somehow confusing NHibernate?</p>
[ { "answer_id": 297597, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "$(document).ready( function() { $('form').validate(); } );\n\nfunction init_validation(divName)\n{\n $('div#' + divName).find('input').addClass( 'required' );\n $('div#inputs').children('div:not(#' + divName + ')')\n .find('input')\n .removeClass( 'required' );\n}\n <form>\n<div>\n <input type='radio'\n id='new_account_radio'\n name='interface_selector'\n value='new_account'\n selected=true\n onclick='init_validation(\"new_account\");' /> New Account\n\n <input type='radio'\n id='delete_account_radio'\n name='interface_selector'\n value='delete_account'\n onclick='init_validation(\"delete_account\");' /> Delete Account\n\n <input type='radio'\n id='new_software_radio'\n name='interface_selector'\n value='new_software'\n onclick='init_validation(\"new_software\");' /> New Software\n\n</div>\n\n<div id='inputs'>\n <div id='new_account'>\n <input type='text' id='new_account_name' class='required' />\n </div>\n\n <div id='delete_account'>\n <input type='text' id='delete_account_name' />\n </div>\n\n <div id='new_software'>\n <input type='text' id='new_software_name' />\n </div>\n</div>\n</form>\n" }, { "answer_id": 319290, "author": "justinavery", "author_id": 38419, "author_profile": "https://Stackoverflow.com/users/38419", "pm_score": 2, "selected": true, "text": "<fieldset id=\"request-type\">\n<legend>Type of Request</legend>\n<ul>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_0\" value=\"0\" class=\"sq-form-field\" /><label for=\"q4838_q1_0\">New account</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_1\" value=\"1\" class=\"sq-form-field\" /><label for=\"q4838_q1_1\">Delete account</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_2\" value=\"2\" class=\"sq-form-field\" /><label for=\"q4838_q1_2\">Change access/account transfer</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_3\" value=\"3\" class=\"sq-form-field\" /><label for=\"q4838_q1_3\">Hardware</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_4\" value=\"4\" class=\"sq-form-field\" /><label for=\"q4838_q1_4\">Software</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_5\" value=\"5\" class=\"sq-form-field\" /><label for=\"q4838_q1_5\">Email</label></li>\n<li><input type=\"checkbox\" name=\"q4838:q1[]\" id=\"q4838_q1_6\" value=\"6\" class=\"sq-form-field\" /><label for=\"q4838_q1_6\">Other</label></li>\n</ul>\n</fieldset>\n <fieldset id=\"delete-account\" style=\"display: block;\">\n class=\"{required:'#checkboxid:checked', messages:{required:'required error message'}}\"\n <fieldset id=\"delete-account\" style=\"display: block;\">\n<legend>Delete Account</legend>\n\n<label for=\"q4832_q1\">Cessation date</label>\n<input type=\"text\" name=\"q4832:q1value[d]\" value=\"\" class=\"{required:'#q4838_q1_1:checked', messages:{required:'Enter Cessation Date'}}\" id=\"q4832:q1value[d]\" />\n\n<label for=\"q4832_q1\">List of assets</label>\n<input type=\"text\" name=\"q4832:q2\" value=\"\" class=\"{required:'#q4838_q1_1:checked', messages:{required:'Enter Cessation Date'}}\" id=\"q4832:q2\" />\n</fieldset>\n {required:'true', messages:{required:'This field is required'}} #checkboxid:checked 'true' 'false' class=\"{required:'true', minlength:1, messages:{required:'Please select a checkbox'}}\"\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475/" ]
297,586
<p>I am having a lot of trouble finding good information on how to call a standard SOAP/WSDL web service with Android. All I've been able to find are either very convoluted documents and references to "kSoap2" and then some bit about parsing it all manually with <a href="http://en.wikipedia.org/wiki/Simple_API_for_XML" rel="noreferrer">SAX</a>. OK, that's fine, but it's 2008, so I figured there should be some good library for calling standard web services.</p> <p>The web service is just basically one created in <a href="http://en.wikipedia.org/wiki/NetBeans" rel="noreferrer">NetBeans</a>. I would like to have IDE support for generating the plumbing classes. I just need the easiest/most-elegant way to contact a <a href="http://en.wikipedia.org/wiki/Web_Services_Description_Language" rel="noreferrer">WSDL</a> based web service from an Android-based phone.</p>
[ { "answer_id": 426241, "author": "Neil", "author_id": 52115, "author_profile": "https://Stackoverflow.com/users/52115", "pm_score": 7, "selected": false, "text": "org.apache.http.impl.client.DefaultHttpClient HttpClient httpClient = new DefaultHttpClient();\nHttpContext localContext = new BasicHttpContext();\nHttpGet httpGet = new HttpGet(\"http://www.example.com/\" + URL);\nHttpResponse response = httpClient.execute(httpGet, localContext);\n" }, { "answer_id": 2199036, "author": "Priyanjan", "author_id": 266102, "author_profile": "https://Stackoverflow.com/users/266102", "pm_score": 5, "selected": false, "text": "HttpURLConnection getResonseCode ErrorInput" }, { "answer_id": 6041180, "author": "DEVANG SHARMA", "author_id": 705474, "author_profile": "https://Stackoverflow.com/users/705474", "pm_score": 4, "selected": false, "text": "private static String mNAMESPACE=null;\nprivate static String mURL=null;\npublic static Context context=null;\nSoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);\nenvelope.dotNet = true;\nenvelope.setOutputSoapObject(Request);\n\nenvelope.addMapping(mNAMESPACE, \"UserCredentials\",new UserCredendtials().getClass());\nAndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(mURL);\n androidHttpTransport.call(SOAP_ACTION, envelope);\nresult = (SoapPrimitive)envelope.getResponse();\n" }, { "answer_id": 9052974, "author": "Alex Gilleran", "author_id": 873670, "author_profile": "https://Stackoverflow.com/users/873670", "pm_score": 5, "selected": false, "text": "<Dictionary>\n <Id></Id>\n <Name></Name>\n</Dictionary>\n @XMLObject(\"//Dictionary\")\npublic class Dictionary {\n @XMLField(\"Id\")\n private String id;\n\n @XMLField(\"Name\")\n private String name;\n}\n" }, { "answer_id": 10537791, "author": "Asraful Haque", "author_id": 1266793, "author_profile": "https://Stackoverflow.com/users/1266793", "pm_score": 4, "selected": false, "text": "ComplexOperationService service = new ComplexOperationService( );\nComplexOperation port= service.getComplexOperationPort(); \nSomeComplexRequest request = --Get some complex request----; \nSomeComplexResp resp = port.operate( request );\n" }, { "answer_id": 10681697, "author": "Sachin D", "author_id": 1041044, "author_profile": "https://Stackoverflow.com/users/1041044", "pm_score": 3, "selected": false, "text": "obj2=(SoapObject) obj1.getProperty(\"NewDataSet\"); void callWebService(){ \n\nprivate static final String NAMESPACE = \"http://tempuri.org/\"; // for wsdl it may be package name i.e http://package_name\nprivate static final String URL = \"http://localhost/sample/services/MyService?wsdl\";\n// you can use IP address instead of localhost\nprivate static final String METHOD_NAME = \"Function_Name\";\nprivate static final String SOAP_ACTION = \"urn:\" + METHOD_NAME;\n\n SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);\n request.addProperty(\"parm_name\", prm_value);// Parameter for Method\n SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);\n envelope.dotNet = true;// **If your Webservice in .net otherwise remove it**\n envelope.setOutputSoapObject(request);\n HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);\n\n try {\n androidHttpTransport.call(SOAP_ACTION, envelope);// call the eb service\n // Method\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n // Next task is to get Response and format that response\n SoapObject obj, obj1, obj2, obj3;\n obj = (SoapObject) envelope.getResponse();\n obj1 = (SoapObject) obj.getProperty(\"diffgram\");\n obj2 = (SoapObject) obj1.getProperty(\"NewDataSet\");\n\n for (int i = 0; i < obj2.getPropertyCount(); i++) { \n// the method getPropertyCount() and return the number of rows\n obj3 = (SoapObject) obj2.getProperty(i);\n obj3.getProperty(0).toString();// value of column 1\n obj3.getProperty(1).toString();// value of column 2\n // like that you will get value from each column\n }\n }\n" }, { "answer_id": 10924061, "author": "Wajdi Hh", "author_id": 1103316, "author_profile": "https://Stackoverflow.com/users/1103316", "pm_score": 2, "selected": false, "text": "public class WsClient {\n private static final String SOAP_ACTION = \"somme\";\n private static final String OPERATION_NAME = \"somme\";\n private static final String WSDL_TARGET_NAMESPACE = \"http://example.ws\";\n private static final String SOAP_ADDRESS = \"http://192.168.1.2:8080/axis2/services/Calculatrice?wsdl\";\n\n public String caclculerSomme() {\n\n String res = null;\n SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,\n OPERATION_NAME);\n request.addProperty(\"a\", \"5\");\n request.addProperty(\"b\", \"2\");\n\n SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(\n SoapEnvelope.VER11);\n envelope.dotNet = true;\n envelope.setOutputSoapObject(request);\n HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);\n\n try {\n httpTransport.call(SOAP_ACTION, envelope);\n String result = envelope.getResponse().toString();\n res = result;\n System.out.println(\"############# resull is :\" + result);\n } catch (Exception exception) {\n System.out.println(\"########### ERRER\" + exception.getMessage());\n }\n\n return res;\n }\n}\n" }, { "answer_id": 10926979, "author": "Amit kumar", "author_id": 1190958, "author_profile": "https://Stackoverflow.com/users/1190958", "pm_score": 5, "selected": false, "text": "import org.ksoap2.SoapEnvelope;\nimport org.ksoap2.serialization.PropertyInfo;\nimport org.ksoap2.serialization.SoapObject;\nimport org.ksoap2.serialization.SoapPrimitive;\nimport org.ksoap2.serialization.SoapSerializationEnvelope;\nimport org.ksoap2.transport.HttpTransportSE;\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class WebserviceActivity extends Activity {\n\n private static final String NAMESPACE = \"https://api.authorize.net/soap/v1/\";\n private static final String URL =\"https://apitest.authorize.net/soap/v1/Service.asmx?wsdl\"; \n private static final String SOAP_ACTION = \"https://api.authorize.net/soap/v1/AuthenticateTest\";\n private static final String METHOD_NAME = \"AuthenticateTest\";\n private TextView lblResult;\n\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n\n lblResult = (TextView) findViewById(R.id.tv);\n\n SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); \n request.addProperty(\"name\",\"44vmMAYrhjfhj66fhJN\");\n request.addProperty(\"transactionKey\",\"9MDQ7fghjghjh53H48k7e7n\");\n SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); \n envelope.setOutputSoapObject(request);\n HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);\n try {\n androidHttpTransport.call(SOAP_ACTION, envelope);\n\n //SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();\n // SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();\n SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;\n\n\n lblResult.setText(resultsRequestSOAP.toString());\n System.out.println(\"Response::\"+resultsRequestSOAP.toString());\n\n\n } catch (Exception e) {\n System.out.println(\"Error\"+e);\n }\n\n }\n}\n" }, { "answer_id": 17938973, "author": "Arun", "author_id": 772761, "author_profile": "https://Stackoverflow.com/users/772761", "pm_score": 2, "selected": false, "text": "public final String WSDL_TARGET_NAMESPACE = \"http://tempuri.org/\";\npublic final String METHOD_NAME = \"FahrenheitToCelsius\";\npublic final String PROPERTY_NAME = \"Fahrenheit\";\npublic final String SOAP_ACTION = \"http://tempuri.org/FahrenheitToCelsius\";\npublic final String SOAP_ADDRESS = \"http://www.w3schools.com/webservices/tempconvert.asmx\";\n\n\nprivate class TestAsynk extends AsyncTask<String, Void, String> {\n\n @Override\n protected void onPostExecute(String result) {\n\n super.onPostExecute(result);\n Toast.makeText(getApplicationContext(),\n String.format(\"%.2f\", Float.parseFloat(result)),\n Toast.LENGTH_SHORT).show();\n }\n\n @Override\n protected String doInBackground(String... params) {\n SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,\n METHOD_NAME);\n request.addProperty(PROPERTY_NAME, params[0]);\n\n SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(\n SoapEnvelope.VER11);\n envelope.dotNet = true;\n\n envelope.setOutputSoapObject(request);\n\n HttpTransportSE androidHttpTransport = new HttpTransportSE(\n SOAP_ADDRESS);\n Object response = null;\n try {\n\n androidHttpTransport.call(SOAP_ACTION, envelope);\n response = envelope.getResponse();\n Log.e(\"Object response\", response.toString());\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n return response.toString();\n }\n}\n" }, { "answer_id": 34156613, "author": "lokesh s", "author_id": 4590662, "author_profile": "https://Stackoverflow.com/users/4590662", "pm_score": 2, "selected": false, "text": " String SOAP_ACTION = \"YOUR_ACTION_NAME\";\n String METHOD_NAME = \"YOUR_METHOD_NAME\";\n String NAMESPACE = \"YOUR_NAME_SPACE\";\n String URL = \"YOUR_URL\";\n SoapPrimitive resultString = null;\n\n try {\n SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);\n addPropertyForSOAP(Request);\n\n SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);\n soapEnvelope.dotNet = true;\n soapEnvelope.setOutputSoapObject(Request);\n\n HttpTransportSE transport = new HttpTransportSE(URL);\n\n transport.call(SOAP_ACTION, soapEnvelope);\n resultString = (SoapPrimitive) soapEnvelope.getResponse();\n\n Log.i(\"SOAP Result\", \"Result Celsius: \" + resultString);\n } catch (Exception ex) {\n Log.e(\"SOAP Result\", \"Error: \" + ex.getMessage());\n }\n if(resultString != null) {\n return resultString.toString();\n }\n else{\n return \"error\";\n }\n" }, { "answer_id": 37524542, "author": "Mani", "author_id": 6382129, "author_profile": "https://Stackoverflow.com/users/6382129", "pm_score": 1, "selected": false, "text": "ksoap2-android-assembly-3.2.0-jar-with-dependencies.jar HashMap < String, String > str1,\n HashMap < String, String > str2,\n HashMap < String, String > str3) {\n\n Object response = null;\n String METHOD_NAME = \"CollectMoney\";\n String NAMESPACE = \"http://xxx/yyy/xxx\";\n String URL = \"http://www.w3schools.com/webservices/tempconvert.asmx\";\n String SOAP_ACTION = \"\";\n\n try {\n\n SoapObject RequestParent = new SoapObject(NAMESPACE, METHOD_NAME);\n\n SoapObject Request1 = new SoapObject(NAMESPACE, \"req\");\n\n PropertyInfo pi = new PropertyInfo();\n\n Set mapSet1 = (Set) str1.entrySet();\n\n Iterator mapIterator1 = mapSet1.iterator();\n\n while (mapIterator1.hasNext()) {\n\n Map.Entry mapEntry = (Map.Entry) mapIterator1.next();\n\n String keyValue = (String) mapEntry.getKey();\n\n String value = (String) mapEntry.getValue();\n\n pi = new PropertyInfo();\n\n pi.setNamespace(\"java:com.xxx\");\n\n pi.setName(keyValue);\n\n pi.setValue(value);\n\n Request1.addProperty(pi);\n }\n\n mapSet1 = (Set) str3.entrySet();\n\n mapIterator1 = mapSet1.iterator();\n\n while (mapIterator1.hasNext()) {\n\n Map.Entry mapEntry = (Map.Entry) mapIterator1.next();\n\n // getKey Method of HashMap access a key of map\n String keyValue = (String) mapEntry.getKey();\n\n // getValue method returns corresponding key's value\n String value = (String) mapEntry.getValue();\n\n pi = new PropertyInfo();\n\n pi.setNamespace(\"java:com.xxx\");\n\n pi.setName(keyValue);\n\n pi.setValue(value);\n\n Request1.addProperty(pi);\n }\n\n SoapObject HeaderRequest = new SoapObject(NAMESPACE, \"XXX\");\n\n Set mapSet = (Set) str2.entrySet();\n\n Iterator mapIterator = mapSet.iterator();\n\n while (mapIterator.hasNext()) {\n\n Map.Entry mapEntry = (Map.Entry) mapIterator.next();\n\n // getKey Method of HashMap access a key of map\n String keyValue = (String) mapEntry.getKey();\n\n // getValue method returns corresponding key's value\n String value = (String) mapEntry.getValue();\n\n pi = new PropertyInfo();\n\n pi.setNamespace(\"java:com.xxx\");\n\n pi.setName(keyValue);\n\n pi.setValue(value);\n\n HeaderRequest.addProperty(pi);\n }\n\n Request1.addSoapObject(HeaderRequest);\n\n RequestParent.addSoapObject(Request1);\n\n SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(\n SoapEnvelope.VER10);\n\n soapEnvelope.dotNet = false;\n\n soapEnvelope.setOutputSoapObject(RequestParent);\n\n HttpTransportSE transport = new HttpTransportSE(URL, 120000);\n\n transport.debug = true;\n\n transport.call(SOAP_ACTION, soapEnvelope);\n\n response = (Object) soapEnvelope.getResponse();\n\n int cols = ((SoapObject) response).getPropertyCount();\n\n Object objectResponse = (Object) ((SoapObject) response)\n .getProperty(\"Resp\");\n\n SoapObject subObject_Resp = (SoapObject) objectResponse;\n\n\n modelObject = new ResposeXmlModel();\n\n String MsgId = subObject_Resp.getProperty(\"MsgId\").toString();\n\n\n modelObject.setMsgId(MsgId);\n\n String OrgId = subObject_Resp.getProperty(\"OrgId\").toString();\n\n\n modelObject.setOrgId(OrgId);\n\n String ResCode = subObject_Resp.getProperty(\"ResCode\").toString();\n\n\n modelObject.setResCode(ResCode);\n\n String ResDesc = subObject_Resp.getProperty(\"ResDesc\").toString();\n\n\n modelObject.setResDesc(ResDesc);\n\n String TimeStamp = subObject_Resp.getProperty(\"TimeStamp\")\n .toString();\n\n\n modelObject.setTimestamp(ResDesc);\n\n return response.toString();\n\n } catch (Exception ex) {\n\n ex.printStackTrace();\n\n return null;\n }\n\n}\n" }, { "answer_id": 39031827, "author": "Lapenkov Vladimir", "author_id": 4404269, "author_profile": "https://Stackoverflow.com/users/4404269", "pm_score": 2, "selected": false, "text": "private static HashMap<String,String> mHeaders = new HashMap<>();\n\nstatic {\n mHeaders.put(\"Accept-Encoding\",\"gzip,deflate\");\n mHeaders.put(\"Content-Type\", \"application/soap+xml\");\n mHeaders.put(\"Host\", \"35.15.85.55:8080\");\n mHeaders.put(\"Connection\", \"Keep-Alive\");\n mHeaders.put(\"User-Agent\",\"AndroidApp\");\n mHeaders.put(\"Authorization\",\"Basic Q2xpZW50NTkzMzppMjR3s2U=\"); // optional\n}public final static InputStream receiveCurrentShipments(String stringUrlShipments)\n{\n int status=0;\n String xmlstring= \"<soap:Envelope xmlns:soap=\\\"http://www.w3.org/2003/05/soap-envelope\\\" xmlns:ser=\\\"http://35.15.85.55:8080/ServiceTransfer\\\">\\n\" +\n \" <soap:Header/>\\n\" +\n \" <soap:Body>\\n\" +\n \" <ser:GetAllOrdersOfShipment>\\n\" +\n \" <ser:CodeOfBranch></ser:CodeOfBranch>\\n\" +\n \" </ser:GetAllOrdersOfShipment>\\n\" +\n \" </soap:Body>\\n\" +\n \"</soap:Envelope>\";\n StringBuffer chaine = new StringBuffer(\"\");\n\n HttpURLConnection connection = null;\n try {\n URL url = new URL(stringUrlShipments);\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestProperty(\"Content-Length\", xmlstring.getBytes().length + \"\");\n connection.setRequestProperty(\"SOAPAction\", \"http://35.15.85.55:8080/ServiceTransfer/GetAllOrdersOfShipment\");\n\n for(Map.Entry<String, String> entry : mHeaders.entrySet()) {\n String key = entry.getKey();\n String value = entry.getValue();\n connection.setRequestProperty(key,value);\n\n }\n\n connection.setRequestMethod(\"POST\");\n connection.setDoInput(true);\n\n OutputStream outputStream = connection.getOutputStream();\n outputStream.write(xmlstring.getBytes(\"UTF-8\"));\n outputStream.close();\n\n connection.connect();\n status = connection.getResponseCode();\n } catch (ProtocolException e) {\n e.printStackTrace();\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n\n Log.i(\"HTTP Client\", \"HTTP status code : \" + status);\n }\n\n InputStream inputStream = null;\n try {\n inputStream = connection.getInputStream();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return inputStream;\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38426/" ]
297,609
<p>What is the simplest way to get the NT-ID of a user in a C# application? I would probably need to get it only having a name of the user, or maybe an email address.</p>
[ { "answer_id": 297805, "author": "DylanW", "author_id": 13463, "author_profile": "https://Stackoverflow.com/users/13463", "pm_score": 2, "selected": true, "text": "SPPrincipalInfo pi = SPUtility.ResolveWindowsPrincipal(SPContext.Current.Site.WebApplication, \"MYDOMAIN\\\\myusername\", SPPrincipalType.All, false);\n" }, { "answer_id": 298202, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 2, "selected": false, "text": "string login = SPContext.Current.Web.CurrentUser.LoginName\nstring mail = SPContext.Current.Web.CurrentUser.Email\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29227/" ]
297,615
<p>I'm having the hardest time trying to get this to work, hoping one of you has done this before.</p> <p>I have a C# console app that is running a child process which inherits its console. I want a ctrl-c caught by the outer app to be passed along to the inner app so that it can have a chance to shut down nicely.</p> <p>I have some very simple code. I start a Process, then poll it with WaitForExit(10). I also have a CancelKeyPress handler registered, which sets a bool to true when it fires. The polling loop also checks this, and when it's true, it calls GenerateConsoleCtrlEvent() (which I have mapped through pinvoke).</p> <p>I've tried a lot of combinations of params to GenerateConsoleCtrlEvent(). 0 or 1 for the first param, and either 0 or the child process's ID for the second param. Nothing seems to work. Sometimes I get a false back and Marshal.GetLastWin32Error() returns 0, and sometimes I get true back. But none cause the child app to receive a ctrl-c.</p> <p>To be absolutely sure, I wrote a test C# app to be the child app which prints out what's going on with it and verified that manually typing ctrl-c when it runs does properly cause it to quit.</p> <p>I've been banging my head against this for a couple hours. Can anyone give me some pointers on where to go with this?</p>
[ { "answer_id": 297637, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 2, "selected": false, "text": "CreateProcess() Process.ExitCode" }, { "answer_id": 1802908, "author": "Weeble", "author_id": 2283, "author_profile": "https://Stackoverflow.com/users/2283", "pm_score": 2, "selected": false, "text": "using System;\n\npublic class MyClass\n{\n public static void CtrlCHandler(object sender, ConsoleCancelEventArgs args)\n {\n Console.WriteLine(\"Child killed by CTRL+C.\");\n }\n public static void Main()\n {\n Console.WriteLine(\"Child start.\");\n Console.CancelKeyPress += CtrlCHandler;\n System.Threading.Thread.Sleep(4000);\n Console.WriteLine(\"Child finish.\");\n }\n}\n using System;\n\npublic class MyClass\n{\n public static void CtrlCHandler(object sender, ConsoleCancelEventArgs args)\n {\n Console.WriteLine(\"Parent killed by CTRL+C.\");\n }\n public static void Main()\n {\n Console.CancelKeyPress += CtrlCHandler;\n Console.WriteLine(\"Parent start.\");\n System.Diagnostics.Process child = new System.Diagnostics.Process();\n child.StartInfo.UseShellExecute = false;\n child.StartInfo.FileName = \"child.exe\";\n child.Start();\n child.WaitForExit();\n Console.WriteLine(\"Parent finish.\");\n }\n}\n Y:\\>parent\nParent start.\nChild start.\nParent killed by CTRL+C.\nChild killed by CTRL+C.\n^C\nY:\\>parent\nParent start.\nChild start.\nChild finish.\nParent finish.\n" }, { "answer_id": 50311340, "author": "user8128167", "author_id": 351154, "author_profile": "https://Stackoverflow.com/users/351154", "pm_score": 1, "selected": false, "text": "GenerateConsoleCtrlEvent using System;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class ConsoleAppManager\n{\n private readonly string appName;\n private readonly Process process = new Process();\n private readonly object theLock = new object();\n private SynchronizationContext context;\n private string pendingWriteData;\n\n public ConsoleAppManager(string appName)\n {\n this.appName = appName;\n\n this.process.StartInfo.FileName = this.appName;\n this.process.StartInfo.RedirectStandardError = true;\n this.process.StartInfo.StandardErrorEncoding = Encoding.UTF8;\n\n this.process.StartInfo.RedirectStandardInput = true;\n this.process.StartInfo.RedirectStandardOutput = true;\n this.process.EnableRaisingEvents = true;\n this.process.StartInfo.CreateNoWindow = true;\n\n this.process.StartInfo.UseShellExecute = false;\n\n this.process.StartInfo.StandardOutputEncoding = Encoding.UTF8;\n\n this.process.Exited += this.ProcessOnExited;\n }\n\n public event EventHandler<string> ErrorTextReceived;\n public event EventHandler ProcessExited;\n public event EventHandler<string> StandartTextReceived;\n\n public int ExitCode\n {\n get { return this.process.ExitCode; }\n }\n\n public bool Running\n {\n get; private set;\n }\n\n public void ExecuteAsync(params string[] args)\n {\n if (this.Running)\n {\n throw new InvalidOperationException(\n \"Process is still Running. Please wait for the process to complete.\");\n }\n\n string arguments = string.Join(\" \", args);\n\n this.process.StartInfo.Arguments = arguments;\n\n this.context = SynchronizationContext.Current;\n\n this.process.Start();\n this.Running = true;\n\n new Task(this.ReadOutputAsync).Start();\n new Task(this.WriteInputTask).Start();\n new Task(this.ReadOutputErrorAsync).Start();\n }\n\n public void Write(string data)\n {\n if (data == null)\n {\n return;\n }\n\n lock (this.theLock)\n {\n this.pendingWriteData = data;\n }\n }\n\n public void WriteLine(string data)\n {\n this.Write(data + Environment.NewLine);\n }\n\n protected virtual void OnErrorTextReceived(string e)\n {\n EventHandler<string> handler = this.ErrorTextReceived;\n\n if (handler != null)\n {\n if (this.context != null)\n {\n this.context.Post(delegate { handler(this, e); }, null);\n }\n else\n {\n handler(this, e);\n }\n }\n }\n\n protected virtual void OnProcessExited()\n {\n EventHandler handler = this.ProcessExited;\n if (handler != null)\n {\n handler(this, EventArgs.Empty);\n }\n }\n\n protected virtual void OnStandartTextReceived(string e)\n {\n EventHandler<string> handler = this.StandartTextReceived;\n\n if (handler != null)\n {\n if (this.context != null)\n {\n this.context.Post(delegate { handler(this, e); }, null);\n }\n else\n {\n handler(this, e);\n }\n }\n }\n\n private void ProcessOnExited(object sender, EventArgs eventArgs)\n {\n this.OnProcessExited();\n }\n\n private async void ReadOutputAsync()\n {\n var standart = new StringBuilder();\n var buff = new char[1024];\n int length;\n\n while (this.process.HasExited == false)\n {\n standart.Clear();\n\n length = await this.process.StandardOutput.ReadAsync(buff, 0, buff.Length);\n standart.Append(buff.SubArray(0, length));\n this.OnStandartTextReceived(standart.ToString());\n Thread.Sleep(1);\n }\n\n this.Running = false;\n }\n\n private async void ReadOutputErrorAsync()\n {\n var sb = new StringBuilder();\n\n do\n {\n sb.Clear();\n var buff = new char[1024];\n int length = await this.process.StandardError.ReadAsync(buff, 0, buff.Length);\n sb.Append(buff.SubArray(0, length));\n this.OnErrorTextReceived(sb.ToString());\n Thread.Sleep(1);\n }\n while (this.process.HasExited == false);\n }\n\n private async void WriteInputTask()\n {\n while (this.process.HasExited == false)\n {\n Thread.Sleep(1);\n\n if (this.pendingWriteData != null)\n {\n await this.process.StandardInput.WriteLineAsync(this.pendingWriteData);\n await this.process.StandardInput.FlushAsync();\n\n lock (this.theLock)\n {\n this.pendingWriteData = null;\n }\n }\n }\n }\n}\n DateTime maxStartDateTime = //... some date time;\n DateTime maxEndDateTime = //... some later date time\n var duration = maxEndDateTime.Subtract(maxStartDateTime);\n ConsoleAppManager appManager = new ConsoleAppManager(\"myapp.exe\");\n string[] args = new string[] { \"args here\" };\n appManager.ExecuteAsync(args);\n await Task.Delay(Convert.ToInt32(duration.TotalSeconds * 1000) + 20000);\n\n if (appManager.Running)\n {\n // If stilll running, send CTRL-C\n appManager.Write(\"\\x3\");\n }\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14582/" ]
297,654
<p>I'm learning about Win32 programming, and the <code>WinMain</code> prototype looks like:</p> <pre><code>int WINAPI WinMain ( HINSTANCE instance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show ) </code></pre> <p>I was confused as to what this <code>WINAPI</code> identifier was for and found:</p> <pre><code>#define WINAPI __stdcall </code></pre> <p>What does this do? I'm confused by this having something at all after a return type. What is <code>__stdcall</code> for? What does it mean when there is something between the return type and function name?</p>
[ { "answer_id": 297661, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 9, "selected": true, "text": "__stdcall __cdecl __thiscall __fastcall __declspec(naked) __stdcall" }, { "answer_id": 758972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "void __stdcall fnname ( int, int* )\n{\n ...\n}\n\nint main()\n{\n CreateThread ( NULL, 0, fnname, int, int*...... )\n}\n" }, { "answer_id": 37382115, "author": "Katianie", "author_id": 389832, "author_profile": "https://Stackoverflow.com/users/389832", "pm_score": 1, "selected": false, "text": "_beginthreadex(NULL, 0, ExecuteCommand, currCommand, 0, 0);\n unsigned int __stdcall Scene::ExecuteCommand(void* command)\n{\n return system(static_cast<char*>(command));\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30529/" ]
297,656
<p>I'm having a syntax error. I want to take the floor of a function that returns a floating point number.</p> <p>I <em>thought</em> this would give me the right answer</p> <pre><code>let cyclesPerInterrupt bps bpw cpu factor = floor (fudge (float(factor) cyclesPerWord cpu wordsPerSec bps bpw)) </code></pre> <p>But it doesn't. I've tried everything I can think of, and it's just not coming together for me. I know it's something stupid, but I can't think of it.</p> <p>For reference, fudge takes a float and an integer, cyclesPerWord takes 2 integers and wordsPerSec takes 2 integers. Floor takes a generic and returns a float.</p>
[ { "answer_id": 297752, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "...(cyclesPerWord cpu (wordsPerSec bps bpw))\n" }, { "answer_id": 298538, "author": "simonuk", "author_id": 28136, "author_profile": "https://Stackoverflow.com/users/28136", "pm_score": 2, "selected": false, "text": "let fudge (a : float) (b : int) =\n a\n\nlet cyclesPerWord (a : int) (b : int) =\n a\n\nlet wordsPerSec (a : int) (b : int) =\n a\n\nlet cyclesPerInterrupt bps bpw cpu factor =\n wordsPerSec bps bpw\n |> cyclesPerWord cpu\n |> fudge factor\n |> floor\n" }, { "answer_id": 359485, "author": "Rich McCollister", "author_id": 9306, "author_profile": "https://Stackoverflow.com/users/9306", "pm_score": 0, "selected": false, "text": " let cyclesPerInterrupt bps bpw cpu factor = \n (floor (fudge (float factor) (cyclesPerWord cpu (wordsPerSec bps bpw) ) ) )\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26227/" ]
297,671
<p>I have read a book whose title is "Oracle PL SQL Programming" (2nd ed.) by Steven Feuerstein &amp; Bill Pribyl. On page 99, there is a point suggested that </p> <p><strong>Do not "SELECT COUNT(*)" from a table unless you really need to know the total number of "hits." If you only need to know whether there is more than one match, simply fetch twice with an explicit cursor.</strong></p> <p>Could you anyone explain this point more to me by providing example? Thank you.</p> <h3>Update:</h3> <p>As Steven Feuerstein &amp; Bill Pribyl recommends us not to use SELECT COUNT() to check whether records in a table exist or not, could anyone help me edit the code below in order to avoid using SELECT COUNT(*) by using explicit cursor instead? This code is written in the Oracle stored procedure.</p> <p>I have a table emp(emp_id, emp_name, ...), so to check the provided employee ID corret or not:</p> <pre><code>CREATE OR REPLACE PROCEDURE do_sth ( emp_id_in IN emp.emp_id%TYPE ) IS v_rows INTEGER; BEGIN ... SELECT COUNT(*) INTO v_rows FROM emp WHERE emp_id = emp_id_in; IF v_rows &gt; 0 THEN /* do sth */ END; /* more statements */ ... END do_sth; </code></pre>
[ { "answer_id": 297699, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "SELECT COUNT(*) >= 2 EXISTS WITH CustomersWith2OrMoreOrders AS (\n SELECT CustomerID\n FROM Orders\n GROUP BY CustomerID\n HAVING COUNT(*) >= 2\n)\nSELECT Customer.*\nFROM Customer\nINNER JOIN CustomersWith2OrMoreOrders\n ON Customer.CustomerID = CustomersWith2OrMoreOrders.CustomerID\n COUNT(*) IF EXISTS (SELECT COUNT(*) FROM table_name HAVING COUNT(*) >= 2)\nBEGIN\nEND\n DECLARE CURSOR c IS SELECT something FROM table_name;\nBEGIN\n OPEN c\n FETCH c INTO etc. x 2 and count rows and handle exceptions\nEND;\n\nIF rc >= 2 THEN BEGIN\nEND\n" }, { "answer_id": 297761, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 2, "selected": false, "text": "if ((select count(*) from orders where customerid = :customerid) > 1)\n{\n ....\n}\n if ((select 1 from (select 1 from orders where customerid = :customerid) where rownum = 2) == 1)\n{\n ....\n}\n" }, { "answer_id": 297807, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 3, "selected": false, "text": "SELECT 'THERE ARE AT LEAST TWO ROWS IN THE TABLE'\nFROM DUAL\nWHERE 2 =\n(\n SELECT COUNT(*)\n FROM TABLE\n WHERE ROWNUM < 3\n)\n" }, { "answer_id": 297816, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": -1, "selected": false, "text": "if 2 = (\n select count(*) from (\n select top 2 * from (\n select T = 1 union\n select T = 2 union\n select T = 3 ) t) t)\n print 'At least two'\n" }, { "answer_id": 298378, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 5, "selected": false, "text": "DECLARE\n CURSOR c IS SELECT '1' dummy FROM mytable WHERE ...;\n v VARCHAR2(1);\nBEGIN\n OPEN c;\n FETCH c INTO v;\n IF c%FOUND THEN\n -- A row exists\n ...\n ELSE\n -- No row exists\n ...\n END IF;\nEND;\n DECLARE\n v VARCHAR2(1);\nBEGIN\n SELECT '1' INTO v FROM mytable \n WHERE ... \n AND ROWNUM=1; -- Stop fetching if 1 found\n -- At least one row exists\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n -- No row exists\nEND;\n DECLARE\n cnt INTEGER;\nBEGIN\n SELECT COUNT(*) INTO cnt FROM mytable \n WHERE ... \n AND ROWNUM=1; -- Stop counting if 1 found\n IF cnt = 0 THEN\n -- No row found\n ELSE\n -- Row found\n END IF;\nEND;\n DECLARE\n CURSOR c IS SELECT '1' dummy FROM mytable WHERE ...;\n v VARCHAR2(1);\nBEGIN\n OPEN c;\n FETCH c INTO v;\n FETCH c INTO v;\n IF c%FOUND THEN\n -- 2 or more rows exists\n ...\n ELSE\n -- 1 or 0 rows exist\n ...\n END IF;\nEND;\n DECLARE\n v VARCHAR2(1);\nBEGIN\n SELECT '1' INTO v FROM mytable \n WHERE ... ;\n -- Exactly 1 row exists\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n -- No row exists\n WHEN TOO_MANY_ROWS THEN\n -- More than 1 row exists\nEND;\n DECLARE\n cnt INTEGER;\nBEGIN\n SELECT COUNT(*) INTO cnt FROM mytable \n WHERE ... \n AND ROWNUM <= 2; -- Stop counting if 2 found\n IF cnt = 0 THEN\n -- No row found\n IF cnt = 1 THEN\n -- 1 row found\n ELSE\n -- More than 1 row found\n END IF;\nEND;\n CREATE OR REPLACE PROCEDURE do_sth ( emp_id_in IN emp.emp_id%TYPE )\nIS\nv_rows INTEGER;\nBEGIN\n ...\n\n SELECT COUNT(*) INTO v_rows\n FROM emp\n WHERE emp_id = emp_id_in;\n\n IF v_rows > 0 THEN\n /* do sth */\n END;\n\n /* more statements */\n ...\n\nEND do_sth;\n CREATE OR REPLACE PROCEDURE do_sth ( emp_id_in IN emp.emp_id%TYPE )\nIS\n CURSOR c IS SELECT 1\n FROM emp\n WHERE emp_id = emp_id_in;\n v_dummy INTEGER;\nBEGIN\n ...\n\n OPEN c; \n FETCH c INTO v_dummy;\n IF c%FOUND > 0 THEN\n /* do sth */\n END;\n CLOSE c;\n\n /* more statements */\n ...\n\nEND do_sth;\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1602746/" ]
297,678
<p>I am implementing an asynchronous command pattern for the "client" class in a client/server application. I have done some socket coding in the past and I like the new Async pattern that they used in the Socket / SocketAsyncEventArgs classes.</p> <p>My async method looks like this: <code>public bool ExecuteAsync(Command cmd);</code> It returns true if the execution is pending and false if it completed synchronously. <strong>My question is: Should I always call the callback (cmd.OnCompleted), even in the event of an exception? Or should I throw exceptions right from ExecuteAsync?</strong></p> <p>Here are some more details if you need them. This is similar to using SocketAsyncEventArgs, but instead of SocketAsyncEventArgs my class is called SomeCmd.</p> <pre><code>SomeCmd cmd = new SomeCmd(23, 14, 10, "hike!"); cmd.OnCompleted += this.SomeCmd_OnCompleted; this.ConnectionToServer.ExecuteAsync(cmd); </code></pre> <p>As with the Socket class, if you need to coordinate with your callback method (SomeCmd_OnCompleted in this case), you can use the return value of ExecuteAsync to know if the operation is pending (true) or if the operation completed synchronously.</p> <pre><code>SomeCmd cmd = new SomeCmd(23, 14, 10, "hike!"); cmd.OnCompleted += this.SomeCmd_OnCompleted; if( this.ConnectionToServer.ExecuteAsync(cmd) ) { Monitor.Wait( this.WillBePulsedBy_SomeCmd_OnCompleted ); } </code></pre> <p>Here is a greatly simplified version of my base classes, but you can see how it works:</p> <pre><code>class Connection { public bool ExecuteAsync(Command cmd) { /// CONSIDER: If you don't catch every exception here /// then every caller of this method must have 2 sets of /// exception handling: /// One in the handler of Command.OnCompleted and one where ExecuteAsync /// is called. try { /// Some possible exceptions here: /// 1) remote is disposed. happens when the other side disconnects (WCF). /// 2) I do something wrong in TrackCommand (a bug that I want to fix!) this.TrackCommand(cmd); remote.ServerExecuteAsync( cmd.GetRequest() ); return true; } catch(Exception ex) { /// Command completing synchronously. cmd.Completed(ex, true); return false; } } /// &lt;summary&gt;This is what gets called by some magic when the server returns a response.&lt;/summary&gt; internal CommandExecuteReturn(CommandResponse response) { Command cmd = this.GetTrackedCommand(response.RequestId); /// Command completing asynchronously. cmd.Completed(response, false); } private IServer remote; } abstract class Command: EventArgs { internal void Completed(Exception ex, bool synchronously) { this.Exception = ex; this.CompletedSynchronously = synchronously; if( this.OnCompleted != null ) { this.OnCompleted(this); } } internal void Completed(CommandResponse response, bool synchronously) { this.Response = response; this.Completed(response.ExceptionFromServer, synchronously) } public bool CompletedSynchronously{ get; private set; } public event EventHandler&lt;Command&gt; OnCompleted; public Exception Exception{ get; private set; } internal protected abstract CommandRequest GetRequest(); } </code></pre>
[ { "answer_id": 297937, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 3, "selected": false, "text": "BackgroundWorker BeginInvoke()/EndInvoke() \nprivate delegate int CommandDelegate(string number);\n\nprivate void ExecuteCommandAsync()\n{\n CommandDelegate del = new CommandDelegate(BeginExecuteCommand);\n del.BeginInvoke(\"four\", new AsyncCallback(EndExecuteCommand), null);\n}\n\nprivate int BeginExecuteCommand(string number)\n{\n if (number == \"five\")\n {\n return 5;\n }\n else\n {\n throw new InvalidOperationException(\"I only understand the number five!\");\n }\n}\n\nprivate void EndExecuteCommand(IAsyncResult result)\n{\n CommandDelegate del;\n int retVal;\n\n del = (CommandDelegate)((AsyncResult)result).AsyncDelegate;\n\n try\n {\n // Here's where we get the return value\n retVal = del.EndInvoke(result);\n }\n catch (InvalidOperationException e)\n {\n // See, we had EndExecuteCommand called, but the exception\n // from the Begin method got tossed here\n }\n}\n ExecuteCommandAsync() BeginExecuteCommand() EndInvoke() IAsyncResult AsyncResult" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16387/" ]
297,680
<p>I have a code sample that gets a <code>SEL</code> from the current object, </p> <pre><code>SEL callback = @selector(mymethod:parameter2); </code></pre> <p>And I have a method like </p> <pre><code> -(void)mymethod:(id)v1 parameter2;(NSString*)v2 { } </code></pre> <p>Now I need to move <code>mymethod</code> to another object, say <code>myDelegate</code>.</p> <p>I have tried:</p> <pre><code>SEL callback = @selector(myDelegate, mymethod:parameter2); </code></pre> <p>but it won't compile. </p>
[ { "answer_id": 297695, "author": "Grant Limberg", "author_id": 27314, "author_profile": "https://Stackoverflow.com/users/27314", "pm_score": 4, "selected": false, "text": "[object setCallbackObject:self withSelector:@selector(myMethod:)];\n -(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {\n [anObject performSelector:selector];\n}\n" }, { "answer_id": 297720, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 8, "selected": true, "text": "-(void)methodWithNoParameters;\nSEL noParameterSelector = @selector(methodWithNoParameters);\n\n-(void)methodWithOneParameter:(id)parameter;\nSEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here\n\n-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;\nSEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted\n -(void)someMethod:(NSTimer*)timer;\n @implementation MyObject\n\n-(void)myTimerCallback:(NSTimer*)timer\n{\n // do some computations\n if( timerShouldEnd ) {\n [timer invalidate];\n }\n}\n\n@end\n\n// ...\n\nint main(int argc, const char **argv)\n{\n // do setup stuff\n MyObject* obj = [[MyObject alloc] init];\n SEL mySelector = @selector(myTimerCallback:);\n [NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];\n // do some tear-down\n return 0;\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32096/" ]
297,686
<p>Is there a good <strong>cross-browser</strong> way to set a <code>max-height</code> property of a DIV and when that DIV goes beyond the <code>max-height</code>, it turns into an overflow with scrollbars?</p>
[ { "answer_id": 297802, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 5, "selected": false, "text": " div{\n _height: expression( this.scrollHeight > 332 ? \"333px\" : \"auto\" ); /* sets max-height for IE6 */\n max-height: 333px; /* sets max-height value for all standards-compliant browsers */\n overflow:scroll;\n}\n" }, { "answer_id": 1197332, "author": "Mottie", "author_id": 145346, "author_profile": "https://Stackoverflow.com/users/145346", "pm_score": 4, "selected": false, "text": "selector {\n max-height:500px;\n height:auto !important;\n height:500px;\n}\n" }, { "answer_id": 6542904, "author": "KrisK", "author_id": 824110, "author_profile": "https://Stackoverflow.com/users/824110", "pm_score": 3, "selected": false, "text": "selector\n{\n max-height:900px;\n _height:expression(this.scrollHeight>899?\"900px\":\"auto\");\n overflow:auto;\n overflow-x:hidden;\n}\n" }, { "answer_id": 15143050, "author": "Zhou", "author_id": 2120853, "author_profile": "https://Stackoverflow.com/users/2120853", "pm_score": -1, "selected": false, "text": "<style type=\"text/css\">\n.scroll{\n display:block;\n border: 1px solid red;\n padding:5px;\n margin-top:5px;\n width:300px;\n\n max-height:100px;\n overflow:scroll;\n}\n.auto{\n display:block;\n border: 1px solid red;\n padding:5px;\n margin-top:5px;\n width:300px;\n height: 100px !important;\n max-height:110px;\n overflow:hidden;\n overflow-y:auto;\n}\n</style>\n<p>Example of scroll value:</p>\n\n<div class=\"scroll\">\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/> \n </div>\n\n<br />\n<p>Example of auto value:</p>\n\n<div class=\"auto\">\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n </div>\n" }, { "answer_id": 15167760, "author": "gordon", "author_id": 778294, "author_profile": "https://Stackoverflow.com/users/778294", "pm_score": 0, "selected": false, "text": ".divMax{width:550px;height:200px;overflow-Y:auto;position:absolute;}\n.divInner{border:1px solid navy;background-color:white;}\n position:absolute" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
297,687
<p>I haven't worked much with Visual Studio before. I've started a personal project in my spare time and I would like to use test-driven development since it has been a huge benefit to me in my Java development. I started this project quite a while ago, and I used CppUnit. I know there are probably other frameworks that are better, but this is what's already in place.</p> <p>My Visual Stuido 2005 solution has 2 projects in it. It worked fine when the unit tests resided right alongside the application code. As the project grew in size, this became quite cumbersome and inelegant. I created a new project under my solution to house the unit tests (so it now has 3 projects). Everything went fine until I tried to build the solution. Everything compiled, but the unit test project failed to link. The output gives me 51 "unresolved external symbol" errors (LNK2019) for what seems like every function that my tests call.</p> <p>As far as I can deduce, the problem is the directory structure that Visual Studio creates. Each project gets its own directory, and then below that are the object files and executables that get created. I think the problem is that, while the header files are properly included in each unit test, the linker can't find the cpp files because they are in a different directory. When it fails to find the implementation of a called function, it gives me the 2019 error.</p> <p>Am I right in my evaluation of the problem? How can I fix it? Do I need to completely reorganize my projects or is it a simple configuration of the linker?</p> <p>Thanks</p>
[ { "answer_id": 297802, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 5, "selected": false, "text": " div{\n _height: expression( this.scrollHeight > 332 ? \"333px\" : \"auto\" ); /* sets max-height for IE6 */\n max-height: 333px; /* sets max-height value for all standards-compliant browsers */\n overflow:scroll;\n}\n" }, { "answer_id": 1197332, "author": "Mottie", "author_id": 145346, "author_profile": "https://Stackoverflow.com/users/145346", "pm_score": 4, "selected": false, "text": "selector {\n max-height:500px;\n height:auto !important;\n height:500px;\n}\n" }, { "answer_id": 6542904, "author": "KrisK", "author_id": 824110, "author_profile": "https://Stackoverflow.com/users/824110", "pm_score": 3, "selected": false, "text": "selector\n{\n max-height:900px;\n _height:expression(this.scrollHeight>899?\"900px\":\"auto\");\n overflow:auto;\n overflow-x:hidden;\n}\n" }, { "answer_id": 15143050, "author": "Zhou", "author_id": 2120853, "author_profile": "https://Stackoverflow.com/users/2120853", "pm_score": -1, "selected": false, "text": "<style type=\"text/css\">\n.scroll{\n display:block;\n border: 1px solid red;\n padding:5px;\n margin-top:5px;\n width:300px;\n\n max-height:100px;\n overflow:scroll;\n}\n.auto{\n display:block;\n border: 1px solid red;\n padding:5px;\n margin-top:5px;\n width:300px;\n height: 100px !important;\n max-height:110px;\n overflow:hidden;\n overflow-y:auto;\n}\n</style>\n<p>Example of scroll value:</p>\n\n<div class=\"scroll\">\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/> \n </div>\n\n<br />\n<p>Example of auto value:</p>\n\n<div class=\"auto\">\n I am going to keep lot of content here just to show\n you how scrollbars works if there is an overflow in\n an element box. This provides your horizontal as well\n as vertical scrollbars.<br/>\n </div>\n" }, { "answer_id": 15167760, "author": "gordon", "author_id": 778294, "author_profile": "https://Stackoverflow.com/users/778294", "pm_score": 0, "selected": false, "text": ".divMax{width:550px;height:200px;overflow-Y:auto;position:absolute;}\n.divInner{border:1px solid navy;background-color:white;}\n position:absolute" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,701
<p>Every time that I create a new form in my application, it uses the "Microsoft Sans Serif, 8.25pt" font by default. I'm not changing it because I know that in this case my form <em>should</em> pick up whatever the default font is for the system. However, when I run my application, the font that is used is still anything but Segoe UI (my default system font in my Windows Vista OS).</p> <p>Why does this happen? How do I make sure that my application looks like a normal Windows application?</p>
[ { "answer_id": 300081, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 4, "selected": false, "text": "GetStockObject(DEFAULT_GUI_FONT)" }, { "answer_id": 461126, "author": "CS.", "author_id": 57085, "author_profile": "https://Stackoverflow.com/users/57085", "pm_score": 5, "selected": false, "text": "this.Font = SystemFonts.MessageBoxFont;\n" }, { "answer_id": 4076183, "author": "Cody Gray", "author_id": 366904, "author_profile": "https://Stackoverflow.com/users/366904", "pm_score": 6, "selected": false, "text": "SystemFonts.MessageBoxFont myControl.Font = New Font(Me.Font, FontStyle.Bold)\n" }, { "answer_id": 7853540, "author": "David", "author_id": 1007641, "author_profile": "https://Stackoverflow.com/users/1007641", "pm_score": 2, "selected": false, "text": " foreach (Control ctr in this.Controls)\n {\n ctr.Font = SystemFonts.IconTitleFont;\n\n // controls in groupboxes are not child of main form\n if (ctr.HasChildren)\n {\n foreach (Control childControl in ctr.Controls)\n {\n childControl.Font = SystemFonts.IconTitleFont;\n }\n } \n }\n" }, { "answer_id": 33775246, "author": "Adrian Rus", "author_id": 497423, "author_profile": "https://Stackoverflow.com/users/497423", "pm_score": 1, "selected": false, "text": "Control.DefaultFont Type settingsType = typeof(Control);\nvar defaultFontField = settingsType.GetField(\"defaultFont\", BindingFlags.Static | BindingFlags.NonPublic);\ndefaultFontField.SetValue(null, new Font(\"Segoe UI\", 8.25F));\n" }, { "answer_id": 61547974, "author": "Kirsan", "author_id": 6075536, "author_profile": "https://Stackoverflow.com/users/6075536", "pm_score": 0, "selected": false, "text": "net472/net48 netcoreapp3.1 Control.DefaultFont Control.DefaultFont" }, { "answer_id": 71098332, "author": "Olia Gavrysh", "author_id": 18193630, "author_profile": "https://Stackoverflow.com/users/18193630", "pm_score": 2, "selected": false, "text": "<PropertyGroup> <ApplicationDefaultFont>Curlz MT, 18pt</ApplicationDefaultFont>\n Application.SetDefaultFont() Main() static void Main()\n{\n ApplicationConfiguration.Initialize();\n\n Application.SetDefaultFont(new Font(new FontFamily(\"Curlz MT\"), 18f));\n\n Application.Run(new AirQualityForm());\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21952/" ]
297,713
<p>I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. How would I do this?</p>
[ { "answer_id": 297719, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 4, "selected": false, "text": "implode(',', $array);\n" }, { "answer_id": 298245, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 5, "selected": true, "text": "'\"' . implode('\",\"', array_map('mysql_real_escape_string', $data)) . '\"'\n" }, { "answer_id": 348910, "author": "OIS", "author_id": 36175, "author_profile": "https://Stackoverflow.com/users/36175", "pm_score": 0, "selected": false, "text": "$ids = array_filter($ids, 'is_int');\nif (!$ids) {\n //no valid ids returned.\n die('or something');\n}\n$sql .= '(' . implode(',', $ids) . ')';\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,743
<p>Does anyone think it is possible to build a Google Docs style PDF document viewer, which will convert a document to a format that doesn't require Adobe Reader on the client machine?</p> <p>If so, any references to point to? Either a place that had done it, or an explanation of how to do it.</p>
[ { "answer_id": 2199297, "author": "Tom van Enckevort", "author_id": 108816, "author_profile": "https://Stackoverflow.com/users/108816", "pm_score": 1, "selected": false, "text": "http://docs.google.com/viewer?embedded=true&url=http%3A%2F%2Fwww.domain.com%2Fdocument.pdf\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24126/" ]
297,749
<p>Given:</p> <pre><code>CR = %0d = \r LF = %0a = \n </code></pre> <p>What does</p> <p>%3E, %3C </p> <p>Mean?</p>
[ { "answer_id": 297757, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 3, "selected": false, "text": "javascript:alert(unescape(\"%3E\"))\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
297,762
<p><strong>Does anyone know of an algorithm (or search terms / descriptions) to locate a known image within a larger image?</strong></p> <p>e.g.</p> <p>I have an image of a single desktop window containing various buttons and areas (target). I also have code to capture a screen shot of the current desktop. I would like an algorithm that will help me find the target image within the larger desktop image (what exact x and y coordinates the window is located at). The target image may be located anywhere in the larger image and may not be 100% exactly the same (very similar but not exact possibly b/c of OS display differences)</p> <p>Does anyone know of such an algorithm or class of algorithms?</p> <p>I have found various image segmentation and computer vision algorithms but they seem geared to "fuzzy" classification of regions and not locating a specific image within another.</p> <p>** <em>My goal is to create a framework that, given some seed target images, can find "look" at the desktop, find the target area and "watch" it for changes.</em> **</p>
[ { "answer_id": 297820, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 3, "selected": false, "text": "// look for all (x,y) positions where target appears in desktop\nList<Loc> findMatches(Image desktop, Image target, float threshold) {\n List<Loc> locs;\n for (int y=0; y<desktop.height()-target.height(); y++) {\n for (int x=0; x<desktop.width()-target.width(); x++) {\n if (imageDistance(desktop, x, y, target) < threshold) {\n locs.append(Loc(x,y));\n }\n }\n }\n return locs;\n}\n\n// computes the root mean squared error between a rectangular window in \n// bigImg and target.\nfloat imageDistance(Image bigImg, int bx, int by, Image target) {\n float sum_dist2 = 0.0;\n for (int y=0; y<target.height(); y++) {\n for (int x=0; x<target.width(); x++) {\n // assume RGB images...\n for (int colorChannel=0; colorChannel<3; colorChannel++) {\n float dist = target.getPixel(x,y) - bigImg.getPixel(bx+x,by+y);\n sum_dist2 += dist * dist;\n }\n }\n }\n return Math.sqrt(sum_dist2 / target.width() / target.height());\n}\n" }, { "answer_id": 21102960, "author": "example", "author_id": 1365260, "author_profile": "https://Stackoverflow.com/users/1365260", "pm_score": 0, "selected": false, "text": "O(width * height * patter_width * pattern_height) dx dy x = x + dx DY = min(DY, dy) x > width dx = max(dx(red), dx(green), dx(blue))" }, { "answer_id": 22350138, "author": "xamid", "author_id": 3410351, "author_profile": "https://Stackoverflow.com/users/3410351", "pm_score": 1, "selected": false, "text": "using System.Diagnostics;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\n\nusing FFTWSharp;\n\nusing unsigned1 = System.Byte;\nusing signed2 = System.Int16;\nusing signed8 = System.Int64;\n\npublic class Subimage\n{\n /**\n * This program finds a subimage in a larger image. It expects two arguments.\n * The first is the image in which it must look. The secon dimage is the\n * image that is to be found. The program relies on a number of different\n * steps to perform the calculation.\n *\n * It will first normalize the input images in order to improve the\n * crosscorrelation matching. Once the best crosscorrelation is found\n * a sad-matchers is applied in a grid over the larger image.\n *\n * The following two article explains the details:\n *\n * Werner Van Belle; An Adaptive Filter for the Correct Localization\n * of Subimages: FFT based Subimage Localization Requires Image\n * Normalization to work properly; 11 pages; October 2007.\n * http://werner.yellowcouch.org/Papers/subimg/\n *\n * Werner Van Belle; Correlation between the inproduct and the sum\n * of absolute differences is -0.8485 for uniform sampled signals on\n * [-1:1]; November 2006\n */\n unsafe public static Point FindSubimage_fftw(string[] args)\n {\n if (args == null || args.Length != 2)\n {\n Console.Write(\"Usage: subimg\\n\" + \"\\n\" + \" subimg is an image matcher. It requires two arguments. The first\\n\" + \" image should be the larger of the two. The program will search\\n\" + \" for the best position to superimpose the needle image over the\\n\" + \" haystack image. The output of the the program are the X and Y\\n\" + \" coordinates.\\n\\n\" + \" http://werner.yellowouch.org/Papers/subimg/\\n\");\n return new Point();\n }\n\n /**\n * The larger image will be called A. The smaller image will be called B.\n *\n * The code below relies heavily upon fftw. The indices necessary for the\n * fast r2c and c2r transforms are at best confusing. Especially regarding\n * the number of rows and colums (watch our for Asx vs Asx2 !).\n *\n * After obtaining all the crosscorrelations we will scan through the image\n * to find the best sad match. As such we make a backup of the original data\n * in advance\n *\n */\n int Asx = 0, Asy = 0;\n signed2[] A = read_image(args[0], ref Asx, ref Asy);\n int Asx2 = Asx / 2 + 1;\n\n int Bsx = 0, Bsy = 0;\n signed2[] B = read_image(args[1], ref Bsx, ref Bsy);\n\n unsigned1[] Asad = new unsigned1[Asx * Asy];\n unsigned1[] Bsad = new unsigned1[Bsx * Bsy];\n\n for (int i = 0; i < Bsx * Bsy; i++)\n {\n Bsad[i] = (unsigned1)B[i];\n Asad[i] = (unsigned1)A[i];\n }\n for (int i = Bsx * Bsy; i < Asx * Asy; i++)\n Asad[i] = (unsigned1)A[i];\n\n /**\n * Normalization and windowing of the images.\n *\n * The window size (wx,wy) is half the size of the smaller subimage. This\n * is useful to have as much good information from the subimg.\n */\n int wx = Bsx / 2;\n int wy = Bsy / 2;\n normalize(ref B, Bsx, Bsy, wx, wy);\n normalize(ref A, Asx, Asy, wx, wy);\n\n /**\n * Preparation of the fourier transforms.\n * Aa is the amplitude of image A. Af is the frequence of image A\n * Similar for B. crosscors will hold the crosscorrelations.\n */\n IntPtr Aa = fftw.malloc(sizeof(double) * Asx * Asy);\n IntPtr Af = fftw.malloc(sizeof(double) * 2 * Asx2 * Asy);\n IntPtr Ba = fftw.malloc(sizeof(double) * Asx * Asy);\n IntPtr Bf = fftw.malloc(sizeof(double) * 2 * Asx2 * Asy);\n\n /**\n * The forward transform of A goes from Aa to Af\n * The forward tansform of B goes from Ba to Bf\n * In Bf we will also calculate the inproduct of Af and Bf\n * The backward transform then goes from Bf to Aa again. That\n * variable is aliased as crosscors;\n */\n //#original: fftw_plan_dft_r2c_2d\n //IntPtr forwardA = fftwf.dft(2, new int[] { Asy, Asx }, Aa, Af, fftw_direction.Forward, fftw_flags.Estimate);//equal results\n IntPtr forwardA = fftwf.dft_r2c_2d(Asy, Asx, Aa, Af, fftw_flags.Estimate);\n //#original: fftw_plan_dft_r2c_2d\n //IntPtr forwardB = fftwf.dft(2, new int[] { Asy, Asx }, Ba, Bf, fftw_direction.Forward, fftw_flags.Estimate);//equal results\n IntPtr forwardB = fftwf.dft_r2c_2d(Asy, Asx, Ba, Bf, fftw_flags.Estimate);\n double* crosscorrs = (double*)Aa;\n //#original: fftw_plan_dft_c2r_2d\n //IntPtr backward = fftwf.dft(2, new int[] { Asy, Asx }, Bf, Aa, fftw_direction.Backward, fftw_flags.Estimate);//equal results\n IntPtr backward = fftwf.dft_c2r_2d(Asy, Asx, Bf, Aa, fftw_flags.Estimate);\n\n /**\n * The two forward transforms of A and B. Before we do so we copy the normalized\n * data into the double array. For B we also pad the data with 0\n */\n for (int row = 0; row < Asy; row++)\n for (int col = 0; col < Asx; col++)\n ((double*)Aa)[col + Asx * row] = A[col + Asx * row];\n fftw.execute(forwardA);\n\n for (int j = 0; j < Asx * Asy; j++)\n ((double*)Ba)[j] = 0;\n for (int row = 0; row < Bsy; row++)\n for (int col = 0; col < Bsx; col++)\n ((double*)Ba)[col + Asx * row] = B[col + Bsx * row];\n fftw.execute(forwardB);\n\n /**\n * The inproduct of the two frequency domains and calculation\n * of the crosscorrelations\n */\n double norm = Asx * Asy;\n for (int j = 0; j < Asx2 * Asy; j++)\n {\n double a = ((double*)Af)[j * 2];//#Af[j][0];\n double b = ((double*)Af)[j * 2 + 1];//#Af[j][1];\n double c = ((double*)Bf)[j * 2];//#Bf[j][0];\n double d = ((double*)Bf)[j * 2 + 1];//#-Bf[j][1];\n double e = a * c - b * d;\n double f = a * d + b * c;\n ((double*)Bf)[j * 2] = (double)(e / norm);//#Bf[j][0] = (fftw_real)(e / norm);\n ((double*)Bf)[j * 2 + 1] = (double)(f / norm);//Bf[j][1] = (fftw_real)(f / norm);\n }\n fftw.execute(backward);\n\n /**\n * We now have a correlation map. We can spent one more pass\n * over the entire image to actually find the best matching images\n * as defined by the SAD.\n * We calculate this by gridding the entire image according to the\n * size of the subimage. In each cel we want to know what the best\n * match is.\n */\n int sa = 1 + Asx / Bsx;\n int sb = 1 + Asy / Bsy;\n int sadx = 0;\n int sady = 0;\n signed8 minsad = Bsx * Bsy * 256L;\n for (int a = 0; a < sa; a++)\n {\n int xl = a * Bsx;\n int xr = xl + Bsx;\n if (xr > Asx) continue;\n for (int b = 0; b < sb; b++)\n {\n int yl = b * Bsy;\n int yr = yl + Bsy;\n if (yr > Asy) continue;\n\n // find the maximum correlation in this cell\n int cormxat = xl + yl * Asx;\n double cormx = crosscorrs[cormxat];\n for (int x = xl; x < xr; x++)\n for (int y = yl; y < yr; y++)\n {\n int j = x + y * Asx;\n if (crosscorrs[j] > cormx)\n cormx = crosscorrs[cormxat = j];\n }\n int corx = cormxat % Asx;\n int cory = cormxat / Asx;\n\n // We dont want subimages that fall of the larger image\n if (corx + Bsx > Asx) continue;\n if (cory + Bsy > Asy) continue;\n\n signed8 sad = 0;\n for (int x = 0; sad < minsad && x < Bsx; x++)\n for (int y = 0; y < Bsy; y++)\n {\n int j = (x + corx) + (y + cory) * Asx;\n int i = x + y * Bsx;\n sad += Math.Abs((int)Bsad[i] - (int)Asad[j]);\n }\n\n if (sad < minsad)\n {\n minsad = sad;\n sadx = corx;\n sady = cory;\n // printf(\"* \");\n }\n // printf(\"Grid (%d,%d) (%d,%d) Sip=%g Sad=%lld\\n\",a,b,corx,cory,cormx,sad);\n }\n }\n //Console.Write(\"{0:D}\\t{1:D}\\n\", sadx, sady);\n /**\n * Aa, Ba, Af and Bf were allocated in this function\n * crosscorrs was an alias for Aa and does not require deletion.\n */\n fftw.free(Aa);\n fftw.free(Ba);\n fftw.free(Af);\n fftw.free(Bf);\n return new Point(sadx, sady);\n }\n\n private static void normalize(ref signed2[] img, int sx, int sy, int wx, int wy)\n {\n /**\n * Calculate the mean background. We will subtract this\n * from img to make sure that it has a mean of zero\n * over a window size of wx x wy. Afterwards we calculate\n * the square of the difference, which will then be used\n * to normalize the local variance of img.\n */\n signed2[] mean = boxaverage(img, sx, sy, wx, wy);\n signed2[] sqr = new signed2[sx * sy];\n for (int j = 0; j < sx * sy; j++)\n {\n img[j] -= mean[j];\n signed2 v = img[j];\n sqr[j] = (signed2)(v * v);\n }\n signed2[] var = boxaverage(sqr, sx, sy, wx, wy);\n /**\n * The normalization process. Currenlty still\n * calculated as doubles. Could probably be fixed\n * to integers too. The only problem is the sqrt\n */\n for (int j = 0; j < sx * sy; j++)\n {\n double v = Math.Sqrt(Math.Abs((double)var[j]));//#double v = sqrt(fabs(var[j])); <- ambigous\n Debug.Assert(!double.IsInfinity(v) && v >= 0);\n if (v < 0.0001) v = 0.0001;\n img[j] = (signed2)(img[j] * (32 / v));\n if (img[j] > 127) img[j] = 127;\n if (img[j] < -127) img[j] = -127;\n }\n /**\n * As a last step in the normalization we\n * window the sub image around the borders\n * to become 0\n */\n window(ref img, sx, sy, wx, wy);\n }\n\n private static signed2[] boxaverage(signed2[] input, int sx, int sy, int wx, int wy)\n {\n signed2[] horizontalmean = new signed2[sx * sy];\n\n Debug.Assert(horizontalmean != null);\n int wx2 = wx / 2;\n int wy2 = wy / 2;\n int from = (sy - 1) * sx;\n int to = (sy - 1) * sx;\n int initcount = wx - wx2;\n if (sx < initcount) initcount = sx;\n int xli = -wx2;\n int xri = wx - wx2;\n for (; from >= 0; from -= sx, to -= sx)\n {\n signed8 sum = 0;\n int count = initcount;\n for (int c = 0; c < count; c++)\n sum += (signed8)input[c + from];\n horizontalmean[to] = (signed2)(sum / count);\n int xl = xli, x = 1, xr = xri;\n /**\n * The area where the window is slightly outside the\n * left boundary. Beware: the right bnoundary could be\n * outside on the other side already\n */\n for (; x < sx; x++, xl++, xr++)\n {\n if (xl >= 0) break;\n if (xr < sx)\n {\n sum += (signed8)input[xr + from];\n count++;\n }\n horizontalmean[x + to] = (signed2)(sum / count);\n }\n /**\n * both bounds of the sliding window\n * are fully inside the images\n */\n for (; xr < sx; x++, xl++, xr++)\n {\n sum -= (signed8)input[xl + from];\n sum += (signed8)input[xr + from];\n horizontalmean[x + to] = (signed2)(sum / count);\n }\n /**\n * the right bound is falling of the page\n */\n for (; x < sx; x++, xl++)\n {\n sum -= (signed8)input[xl + from];\n count--;\n horizontalmean[x + to] = (signed2)(sum / count);\n }\n }\n\n /**\n * The same process as aboe but for the vertical dimension now\n */\n int ssy = (sy - 1) * sx + 1;\n from = sx - 1;\n signed2[] verticalmean = new signed2[sx * sy];\n Debug.Assert(verticalmean != null);\n to = sx - 1;\n initcount = wy - wy2;\n if (sy < initcount) initcount = sy;\n int initstopat = initcount * sx;\n int yli = -wy2 * sx;\n int yri = (wy - wy2) * sx;\n for (; from >= 0; from--, to--)\n {\n signed8 sum = 0;\n int count = initcount;\n for (int d = 0; d < initstopat; d += sx)\n sum += (signed8)horizontalmean[d + from];\n verticalmean[to] = (signed2)(sum / count);\n int yl = yli, y = 1, yr = yri;\n for (; y < ssy; y += sx, yl += sx, yr += sx)\n {\n if (yl >= 0) break;\n if (yr < ssy)\n {\n sum += (signed8)horizontalmean[yr + from];\n count++;\n }\n verticalmean[y + to] = (signed2)(sum / count);\n }\n for (; yr < ssy; y += sx, yl += sx, yr += sx)\n {\n sum -= (signed8)horizontalmean[yl + from];\n sum += (signed8)horizontalmean[yr + from];\n verticalmean[y + to] = (signed2)(sum / count);\n }\n for (; y < ssy; y += sx, yl += sx)\n {\n sum -= (signed8)horizontalmean[yl + from];\n count--;\n verticalmean[y + to] = (signed2)(sum / count);\n }\n }\n return verticalmean;\n }\n\n private static void window(ref signed2[] img, int sx, int sy, int wx, int wy)\n {\n int wx2 = wx / 2;\n int sxsy = sx * sy;\n int sx1 = sx - 1;\n for (int x = 0; x < wx2; x++)\n for (int y = 0; y < sxsy; y += sx)\n {\n img[x + y] = (signed2)(img[x + y] * x / wx2);\n img[sx1 - x + y] = (signed2)(img[sx1 - x + y] * x / wx2);\n }\n\n int wy2 = wy / 2;\n int syb = (sy - 1) * sx;\n int syt = 0;\n for (int y = 0; y < wy2; y++)\n {\n for (int x = 0; x < sx; x++)\n {\n /**\n * here we need to recalculate the stuff (*y/wy2)\n * to preserve the discrete nature of integers.\n */\n img[x + syt] = (signed2)(img[x + syt] * y / wy2);\n img[x + syb] = (signed2)(img[x + syb] * y / wy2);\n }\n /**\n * The next row for the top rows\n * The previous row for the bottom rows\n */\n syt += sx;\n syb -= sx;\n }\n }\n\n private static signed2[] read_image(string filename, ref int sx, ref int sy)\n {\n Bitmap image = new Bitmap(filename);\n sx = image.Width;\n sy = image.Height;\n signed2[] GreyImage = new signed2[sx * sy];\n BitmapData bitmapData1 = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);\n unsafe\n {\n byte* imagePointer = (byte*)bitmapData1.Scan0;\n\n for (int y = 0; y < bitmapData1.Height; y++)\n {\n for (int x = 0; x < bitmapData1.Width; x++)\n {\n GreyImage[x + y * sx] = (signed2)((imagePointer[0] + imagePointer[1] + imagePointer[2]) / 3.0);\n //4 bytes per pixel\n imagePointer += 4;\n }//end for x\n //4 bytes per pixel\n imagePointer += bitmapData1.Stride - (bitmapData1.Width * 4);\n }//end for y\n }//end unsafe\n image.UnlockBits(bitmapData1);\n return GreyImage;\n }\n}\n" }, { "answer_id": 40895168, "author": "Gabriel Ambrósio Archanjo", "author_id": 2420599, "author_profile": "https://Stackoverflow.com/users/2420599", "pm_score": 2, "selected": false, "text": "import static marvin.MarvinPluginCollection.*;\n\npublic class FindSubimageWindow {\n public FindSubimageWindow(){\n MarvinImage window = MarvinImageIO.loadImage(\"./res/window.png\");\n MarvinImage eclipse = MarvinImageIO.loadImage(\"./res/eclipse_icon.png\");\n MarvinImage progress = MarvinImageIO.loadImage(\"./res/progress_icon.png\");\n\n MarvinSegment seg1, seg2;\n seg1 = findSubimage(eclipse, window, 0, 0);\n drawRect(window, seg1.x1, seg1.y1, seg1.x2-seg1.x1, seg1.y2-seg1.y1);\n\n seg2 = findSubimage(progress, window, 0, 0);\n drawRect(window, seg2.x1, seg2.y1, seg2.x2-seg2.x1, seg2.y2-seg2.y1);\n\n drawRect(window, seg1.x1-10, seg1.y1-10, (seg2.x2-seg1.x1)+25, (seg2.y2-seg1.y1)+20);\n\n MarvinImageIO.saveImage(window, \"./res/window_out.png\");\n }\n private void drawRect(MarvinImage image, int x, int y, int width, int height){\n x-=4; y-=4; width+=8; height+=8;\n image.drawRect(x, y, width, height, Color.red);\n image.drawRect(x+1, y+1, width-2, height-2, Color.red);\n image.drawRect(x+2, y+2, width-4, height-4, Color.red);\n }\n public static void main(String[] args) {\n new FindSubimageWindow();\n } \n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29009/" ]
297,804
<p>How are the java API thread priorities (1-10) gets translated to the OS level priorities since most OS don't have thread priority levels (in terms of number) which match this.</p> <p>So keeping in mind , can there be a scenario when two or more threads with different priorities eventually get the same priority at OS level.</p> <p>Please clarify, if I there is some correction in my understanding.</p>
[ { "answer_id": 297835, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "nice THREAD_PRIORITY_LOWEST THREAD_PRIORITY_BELOW_NORMAL THREAD_PRIORITY_NORMAL THREAD_PRIORITY_ABOVE_NORMAL THREAD_PRIORITY_HIGHEST" }, { "answer_id": 1648281, "author": "Jé Queue", "author_id": 199305, "author_profile": "https://Stackoverflow.com/users/199305", "pm_score": 1, "selected": false, "text": "$uname -r && grep bogomips /proc/cpuinfo\n2.4.33.3\nbogomips : 4312.26\n$java -version 2>&1 |head -1\nJava version \"1.6.0_01\"\n$javac T.java && java -Xmx32m T\n1:3112\n2:2636\n3:2662\n4:3118\n5:2870\n6:3319\n7:3412\n8:3304\n9:3299\n10:3069\n $uname -r && grep bogomips /proc/cpuinfo\n2.6.9-67.ELsmp\nbogomips : 3992.93\nbogomips : 3990.00\n$java -version 2>&1 |head -1\njava version \"1.4.2_14\"\n$javac T.java && java -Xmx32m T\n1:63200\n2:64388\n3:62532\n4:58529\n5:62292\n6:64872\n7:64885\n8:64584\n9:61653\n10:61575\n C:\\>java -version\njava version \"1.6.0_11\"\nC:\\>java -Xmx32m T\n1:12578\n2:12625\n3:11469\n4:11453\n5:10781\n6:8937\n7:10516\n8:8406\n9:9953\n10:7391\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11614/" ]
297,822
<p>As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)).</p>
[ { "answer_id": 297847, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "// myclass.h\n\nclass MyClass {\npublic:\n MyClass();\n void foo();\n // ...\n};\n\nextern MyClass g_MyClassInstance;\n\n// myclass.cpp\n\nMyClass g_MyClassInstance;\n\nMyClass::MyClass()\n{\n // ...\n}\n myclass.h g_MyClassInstance" }, { "answer_id": 297927, "author": "Cyber Oliveira", "author_id": 9793, "author_profile": "https://Stackoverflow.com/users/9793", "pm_score": 0, "selected": false, "text": "\n#include <iostream>\n\nclass MySingleton {\npublic:\n static MySingleton& Instance() {\n static MySingleton singleton;\n return singleton;\n }\n void HelloWorld() { std::cout << \"Hello World!\\n\"; }\n};\n\nint main() {\n MySingleton::Instance().HelloWorld();\n}\n" }, { "answer_id": 297992, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "class MyVar\n{\n public:\n static MyVar& getGlobal1()\n {\n static MyVar global1;\n return global1;\n }\n static MyVar& getGlobal2()\n {\n static MyVar global2;\n return global2;\n }\n // .. etc\n}\n" }, { "answer_id": 298056, "author": "deft_code", "author_id": 28817, "author_profile": "https://Stackoverflow.com/users/28817", "pm_score": 0, "selected": false, "text": "template< typename T >\nT& singleton( void )\n{\n static char buffer[sizeof(T)];\n static T* single = new(buffer)T;\n return *single;\n}\n\nFoo& instance = singleton<Foo>();\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37181/" ]
297,840
<p>Right now I have a few new applications being developed against an Oracle Database, and sometimes they crash or fail to end correctly, etc... anyways the problem is they sometimes seem to leave their connections open, and I need to cleanup after them. My question is if there is a way from the database-side of things to determine dead connections and clean them up?</p>
[ { "answer_id": 297917, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "SELECT 'alter system kill session ''' || sid || ',' || serial# || '''; ' || sql_id death\nFROM v$session\n/\n" }, { "answer_id": 24306610, "author": "Andrew Spencer", "author_id": 587365, "author_profile": "https://Stackoverflow.com/users/587365", "pm_score": 1, "selected": false, "text": "sys_context('userenv','sid') SELECT s.inst_id,\n s.sid,\n s.serial#,\n p.spid,\n s.username,\n s.osuser,\n s.program\nFROM gv$session s\nJOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id\nWHERE s.type != 'BACKGROUND';\n alter system kill session '[sid],[serial#]' alter system kill session ORA-00031 Session marked for kill SELECT s.username,\n s.osuser,\n s.sid,\n s.serial#,\n t.used_ublk,\n t.used_urec,\n rs.segment_name,\n r.rssize,\n r.status\nFROM v$transaction t,\n v$session s,\n v$rollstat r,\n dba_rollback_segs rs\nWHERE s.saddr = t.ses_addr\nAND t.xidusn = r.usn\nAND rs.segment_id = t.xidusn\nORDER BY t.used_ublk DESC;\n ALTER SYSTEM DISCONNECT SESSION '[sid],[serial#]' IMMEDIATE;" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
297,850
<p>I have spent several hours trying to find a means of writing a cross platform password prompt in php that hides the password that is input by the user. While this is easily accomplished in Unix environments through the use of stty -echo, I have tried various means of passthru() and system() calls to make windows do the same thing to no avail.</p> <p>I have tried:</p> <pre><code>passthru('set /p pass=Password: '); system('echo %pass% &gt; out.txt'); $pass = file_get_contents('out.txt', 'r'); </code></pre> <p>This seems to hang on the passthru('set /p pass=Password: '); line without allowing me to input any text and must be killed with a Ctrl-c.</p> <p>I have also tried various methods of fgetc and fgets and printing backspace characters to hide the input since this works in other languages. However, PHP does not appear to be able to interact with text prior to a carriage return.</p> <p>I would really like to find a way to make this work, is this an impossible task or is this something that can be done?</p> <p>Note that I am aware that I could wrap the php script in a batch file and pass the password as a command line argument, but that doesn't work for me in this case.</p>
[ { "answer_id": 297943, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "<?php\necho 'Password: ';\n$pwd = preg_replace('/\\r?\\n$/', '', `stty -echo; head -n1 ; stty echo`);\necho \"\\n\";\necho \"Your password was: {$pwd}.\\n\";\n?>\n" }, { "answer_id": 299328, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": true, "text": "<?php\n\n$pwObj = new Com('ScriptPW.Password');\n\nprint \"Password: \";\n$passwd = $pwObj->getPassword();\n\necho \"Your password is $passwd\\n\";\n\n?>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
297,855
<p><em>Overview</em></p> <p>I'm working on some Emergency Services reporting and mapping application for California (kind of weird, considering the fires there, right now...). We need to map demographic and emergency data for an internal govt unit.</p> <p>What we have are <em>all</em> the streets, cities and neighborhoods in California. Each neighborhood also has it's relevant shapefile (lat long that defines it's boundaries). This was given to us by the US Census board (all public domain stuff) website.</p> <p><em>Problem</em></p> <p>I'm not sure how to best design the DB tables. We haven't been told what type of DB we need to use .. so we're open to suggestions if that helps. We have experience with MS SQL 2005 and 2008 (and the spatial stuff in '08).</p> <p>We can have the following legit data.</p> <ul> <li>Street, City, State</li> <li>City, State</li> <li>Neighborhood, State</li> <li>State</li> </ul> <p>The reason why State is a legit location is because we're told this might be sold to other states, so we need to plan for that now.</p> <p>So, originally, i thought of this...</p> <ul> <li>LocationId INTEGER PK Identity</li> <li>Street NVARCHAR(100)</li> <li>Neighbourhood NVARCHAR(100)</li> <li>City NVARCHAR(100)</li> <li>State NVARCHAR(100)</li> <li>Latitude VARCHAR(15)</li> <li>Longitude VARCHAR(15)</li> <li>Shapefile </li> </ul> <p>None of those are nullable, btw. But after a short while, i thought that it was a waste to have so many 'California' text or 'San Diego' text in the fields. So i changed the table to be more normalised by making the Neighborhood, City and State fields a foreign key to their own new table (eg. lookups) .. and those two fields are now NULLABLE.</p> <p>So .. that all works fine. except when i try and do some Sql statements on them. Because of the NULLABLE FK's, it's a nightmare to make all these outer join queries :(</p> <p>What about having the main table, the sub-lookup tables (eg. Neighbourhoods, Cities and States) linked via ID's and then place all this in a view? Remember, NeighborhoodID and CitiyID would be NULLABLE.. ???</p> <p>I just want to see people's thoughts on this and the <em>reasons</em> they made their suggestions, please. I'm really worried and confused but are eager to learn.</p> <p>Please help!</p> <hr> <p>edit 1: I need to stick to an RDBMS Database.</p> <p>edit 2: I'm thinking about going a single table (de-normalized) with constraints to keep the sum of the fields unqiue OR multi-tables with nullable FK's on the main table (eg. Locations (main table), Neighborhoods, Cities, States ... normalized db schema).</p> <p>edit 3: Added City to the sample, second list.</p> <p>edit 4: Added view question.</p>
[ { "answer_id": 310662, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 2, "selected": false, "text": "- la Maison des Fou\n- 24500 Eymet\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
297,889
<p>I have an MDI application that allows me to open different types of child windows. I can open multiple (but different) instances of the same type of child window. (Example: I can open 3 instances of child window type A and 2 instances of child window type B. All 5 windows are distinct entities and do not share data until unless the user explicitly drags the same data onto multiple windows.) Each child window has a ToolStripContainer with one or more ToolStrips. How do I prevent:</p> <ol> <li>the user from dragging a ToolStrip from a child window of type A to a ToolStripContainer in a child window of type B?</li> <li>the user from dragging a ToolStrip from one instance of child window A to a ToolStripContainer in another instances of the same type of window?</li> </ol> <p>I'm trying to prevent the user from dragging a ToolStrip from instance 1 of type A to instance 2 of type A, selecting some stuff on instance 2, and then clicking a button on the toolbar only to have something weird happen to some other window. Similarly it doesn't make sense to drag a ToolStrip from a window of type A to a window of type B -- the actions don't apply to that type, but to the user it looks like everything is fine because I let them do the drag.</p> <p>Is it as simple as adding my own handler for the ControlAdded event or is there a better way to do this? I'm using WinForms in .NET 3.0.</p> <p>edit: Steps to reproduce</p> <ol> <li>Create a new Windows Application project.</li> <li>Add a new user control. Give the control a ToolStripContainer that contains one ToolStrip with a single button.</li> <li>Repeat step 2, giving you a UserControl2 class.</li> <li>Compile the solution so UserControl1 and UserControl2 show up in your toolbox.</li> <li>Drag UserControl1 and UserControl2 onto the form. Set the borders so you know where the boundaries are.</li> <li>Run the app.</li> <li>It's now possible to drag the ToolStrip from the container in UserControl1 and drop it into the container in UserControl2 (leaving zero ToolStrips in UC1 and two ToolStrips in UC2.)</li> <li>Now imagine you only have access to the code in UserControl1. How do you prevent the user from dragging the ToolStrip out of that instance of the ToolStripContainer?</li> </ol>
[ { "answer_id": 838981, "author": "Pondidum", "author_id": 1500, "author_profile": "https://Stackoverflow.com/users/1500", "pm_score": 1, "selected": false, "text": "Public Class UserControl2\n\n Private Sub tsMainMenu_BeginDrag(ByVal sender As Object, ByVal e As System.EventArgs) Handles tsMainMenu.BeginDrag\n\n tsMainMenu.Tag = tsMainMenu.Parent\n\n End Sub\n\n Private Sub ToolStrip1_EndDrag(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsMainMenu.EndDrag\n\n\n If Not tsMainMenu.Parent.Parent.Equals(CType(tsMainMenu.Tag, ToolStripPanel).Parent) Then\n\n CType(ToolStrip1.Tag, ToolStripPanel).Controls.Add(tsMainMenu)\n End If\n\n End Sub\n\nEnd Class\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20788/" ]
297,899
<p>I am trying to import an existing PDF as a template with FPDI. The template is in landscape format. If I import the template into a new document the template page is inserted in portrait form with the content rotated 90 degrees. If my new document is in portrait the full content appears, but if the new document is also landscape, the content is cropped.</p> <p>Is it possible to use a landscape template with FPDI? </p>
[ { "answer_id": 300565, "author": "crono", "author_id": 1462, "author_profile": "https://Stackoverflow.com/users/1462", "pm_score": 6, "selected": true, "text": "<?php\nrequire_once('fpdf.php');\nrequire_once('fpdi.php');\n\n$pdf =& new FPDI();\n$pdf->addPage('L');\n$pagecount = $pdf->setSourceFile('template.pdf');\n$tplIdx = $pdf->importPage(1); \n$pdf->useTemplate($tplIdx); \n$pdf->SetFont('Arial'); \n$pdf->SetTextColor(255,0,0); \n$pdf->SetXY(25, 25); \n$pdf->Write(0, \"This is just a test\"); \n$pdf->Output('newpdf.pdf', 'F');\n\n?>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38458/" ]
297,909
<p>I have a question about variable initialization in MASM's assembly. </p> <p>How can I initialize 2^32 to a variable and to what kind of variable should I initialize? DWORD or REAL4?</p> <p>I try to do it like:</p> <pre><code>val DWORD 2.0E+32 </code></pre> <p>When I assign var to a register(e.g. mov eax,val) and try to write the value, I see something that is not 2^32. I also tried it with REAL4 type. Result is still same. </p> <p>So What I am doing wrong here?</p> <p>Thanks in advance...</p>
[ { "answer_id": 297957, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 2, "selected": false, "text": "2.0E+32 0x100000000" }, { "answer_id": 297975, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 2, "selected": false, "text": "0 <= dword < 2^32\n0 <= qword < 2^64\n-2^31 <= sdword < 2^31\n-2^63 <= sqword < 2^63\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26379/" ]
297,938
<p>In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application? I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings. Truly this can't be the only way to do it?.. or is it?</p>
[ { "answer_id": 297948, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 8, "selected": true, "text": "Window import javax.swing.JFrame;\nimport javax.swing.JLabel;\n\npublic class Annoying {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Hello!!\");\n\n // Set's the window to be \"always on top\"\n frame.setAlwaysOnTop( true );\n\n frame.setLocationByPlatform( true );\n frame.add( new JLabel(\" Isn't this annoying?\") );\n frame.pack();\n frame.setVisible( true );\n }\n}\n" }, { "answer_id": 20923379, "author": "pinkpanther", "author_id": 2354099, "author_profile": "https://Stackoverflow.com/users/2354099", "pm_score": 4, "selected": false, "text": "setAlwaysOnTop(true) setAlwaysOnTop(false) setAlwaysOnTop(true) wordweb windows AlwaysOnTop OS import java.awt.event.*;\n\nimport javax.swing.*;\n\npublic class MainWindow extends JFrame implements WindowFocusListener\n{\n public MainWindow()\n {\n addWindowFocusListener(this);\n setAlwaysOnTop(true);\n this.setFocusable(true);\n // this.setFocusableWindowState(true);\n panel = new JPanel();\n //setSize(WIDTH,HEIGHT);\n setUndecorated(true);\n setLocation(X,Y);\n setExtendedState(MAXIMIZED_BOTH);\n setVisible(true);\n }\n\n public void windowGainedFocus(WindowEvent e){}\n public void windowLostFocus(WindowEvent e)\n {\n if(e.getNewState()!=e.WINDOW_CLOSED){\n //toFront();\n //requestFocus();\n setAlwaysOnTop(false);\n setAlwaysOnTop(true);\n //requestFocusInWindow();\n System.out.println(\"focus lost\");\n }\n\n }\n\n private JPanel panel;\n private static final int WIDTH = 200;\n private static final int HEIGHT = 200;\n private static final int X = 100;\n private static final int Y = 100;\n\n public static void main(String args[]){\n new MainWindow();}\n }\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14204/" ]
297,951
<p>my goal is to get lots of rows from a translation table. I use an ID to get a subset of the table (say 50 rows) then I use another ID to the rows I want from this subset. Using typed datasets I do the following to get the main dataset: </p> <pre><code>funderTextsDS.tbl_funderTextsDataTable fd = (funderTextsDS.tbl_funderTextsDataTable)(new funderTextsDSTableAdapters.tbl_funderTextsTableAdapter()).GetData(); </code></pre> <p>Then for each value I want to get: </p> <pre><code>fd.Select("eng_code = '" + element + "' and funderID = '" + funderID + "'")[0]["funderText"].ToString(); </code></pre> <p>Using ANTS profiler to check the code I found that this method used about 170ms over 10 page refreshes (220 calls to the fd.select...) </p> <p>When I rewrote this to LINQ it took more than 2000ms to do the same work. Here is the LINQ code I used: </p> <pre><code>IrmDatabaseContext irmDB = new IrmDatabaseContext(); irmDB.tbl_funderTexts.Single(f =&gt; f.funderID == funderId &amp;&amp; f.eng_code == element).funderText; </code></pre> <p>Anyone have a good way of doing this with LINQ? By looking into sql server profiler i saw that the LINQ actually generated a single select for each text i retrieved. (ie LINQ= 220 selects from the db, tableadapter method = 10 selects) </p> <p>Solution: After having read around the net I found that David B was on the right track, although the for loop threw me off for quite a while. Anyway, the trick as he said, is to use a list as this actually forces linq to run the query against the DB and cache it localy. <a href="http://blogs.msdn.com/wriju/archive/2007/07/17/linq-to-sql-caching-the-query-execution.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/wriju/archive/2007/07/17/linq-to-sql-caching-the-query-execution.aspx</a>. </p> <p>So my solution ended up like this: </p> <pre><code>List&lt;tbl_funderText&gt; fd = (from tf in irmDB.tbl_funderTexts where tf.funderID == (int)cpcrow.cpc_fundingPartnerID select tf).ToList(); </code></pre> <p>Then everytime I want an element I do: </p> <pre><code>fd.Single(f =&gt; f.eng_code == element).funderText; </code></pre> <p>Analyzing with ANTS I then found that time was reduced to 150ms (about the same as the tableAdapter. SQL query analyzer shows that the SQL is run only one time.</p>
[ { "answer_id": 297979, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 0, "selected": false, "text": "var data = mDB.tbl_funderTexts.where(f => f.funderID == funderid && f.eng_code == element)\nvar fundertext = data.single().funderText\n" }, { "answer_id": 297980, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": "myDataContext dc = new myDataContext();\nList<FunderText> myList = myDataContext.tbl_funderTexts.ToList();\n\nList<string> result1 = new List<string>();\nforeach(var theValue in myValues)\n{\n result1.Add(\n myList.First(f => f.funderID == theValue.funderId && f.eng_code == element).funderText\n );\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37083/" ]
297,954
<p>I have this form in my view: </p> <pre><code>&lt;!-- Bug (extra 'i') right here-----------v --&gt; &lt;!-- was: &lt;form method="post" enctype="mulitipart/form-data" action="/Task/SaveFile"&gt; --&gt; &lt;form method="post" enctype="multipart/form-data" action="/Task/SaveFile"&gt; &lt;input type="file" id="FileBlob" name="FileBlob"/&gt; &lt;input type="submit" value="Save"/&gt; &lt;input type="button" value="Cancel" onclick="window.location.href='/'" /&gt; &lt;/form&gt; </code></pre> <p>And this code in my controller: </p> <pre><code>public ActionResult SaveFile( FormCollection forms ) { bool errors = false; //this field is never empty, it contains the selected filename if ( string.IsNullOrEmpty( forms["FileBlob"] ) ) { errors = true; ModelState.AddModelError( "FileBlob", "Please upload a file" ); } else { string sFileName = forms["FileBlob"]; var file = Request.Files["FileBlob"]; //'file' is always null, and Request.Files.Count is always 0 ??? if ( file != null ) { byte[] buf = new byte[file.ContentLength]; file.InputStream.Read( buf, 0, file.ContentLength ); //do stuff with the bytes } else { errors = true; ModelState.AddModelError( "FileBlob", "Please upload a file" ); } } if ( errors ) { return ShowTheFormAgainResult(); } else { return View(); } } </code></pre> <p>Based on every code sample I've been able to find, this seems like the way to do it. I've tried with small and large files, with no difference in the result. The form field always contains the filename which matches what I've chosen, and the Request.Files collection is always empty. </p> <p>I don't think it's relevant, but I'm using the VS Development Web Server. AFAIK it supports file uploads the same as IIS. </p> <p>It's getting late and there's a chance I'm missing something obvious. I'd be grateful for any advice. </p>
[ { "answer_id": 297966, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 2, "selected": false, "text": "var file = Request.Files[sFileName];\n var file = Request.Files[\"FileBlob\"];\n Request.Files.Count" }, { "answer_id": 298010, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 7, "selected": true, "text": "enctype=\"mulitipart/form-data\"\n i enctype=\"multipart/form-data\"\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187/" ]
297,955
<p>I am developing a .NET CF based Graphics Application, my project involves a lot of drawing images, We have decided to go for porting the application on different handset resolution.(240 X 240 , 480 X 640) etc. </p> <p>How would i go onto achieve this within single solution/project?</p> <p>Is there a need to create different projects based on resolutions? How would i handle common files? and i need the changes in one of the common classes to occur across all devices.</p> <p>Thank you, Cronos</p>
[ { "answer_id": 298025, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "[DllImport(\"coredll.dll\", EntryPoint = (\"GetSystemMetrics\"))]\npublic static extern int GetSystemMetrics(int nIndex);\n\nprivate const int SM_CXSCREEN = 0;\nprivate const int SM_CYSCREEN = 1;\n\nprivate int width = GetSystemMetrics(SM_CXSCREEN);\nprivate int height = GetSystemMetrics(SM_CYSCREEN);\n" }, { "answer_id": 298937, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": false, "text": "int screenWidth = Screen.PrimaryScreen.Bounds.Width;\nint workingHeight = Screen.PrimaryScreen.WorkingArea.Height;\n" }, { "answer_id": 322544, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 4, "selected": true, "text": "public partial class frmDialog240x240: frmDialog\n public partial class frmDialog240x240: Form\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13046/" ]
297,960
<p>I have some code on my PHP powered site that creates a random hash (using <code>sha1()</code>) and I use it to match records in the database.</p> <p>What are the chances of a collision? Should I generate the hash, then check first if it's in the database (I'd rather avoid an extra query) or automatically insert it, based on the probability that it <em>probably</em> won't collide with another.</p>
[ { "answer_id": 298133, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "id = 5;\nhash = hash(\"My Private String \" + id)\nlink = \"http://mySite.com/resource?id=\" + id + \"&hash=\" + hash\n" }, { "answer_id": 298601, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": false, "text": "$salt = \"salty\";\n$key = sha1($salt . $id) . \"-\" . $id;\n// 0c9ab85f8f9670a5ef2ac76beae296f47427a60a-5\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
297,970
<p>There are a number of great Javascript libraries\frameworks out there (jQuery, Prototype, MooTools, etc.), but they all seem to focus on DOM interaction and AJAX functionality. I haven't found any that focus on extending the built-in data types (String, Date, Number, etc.). And by "Extending" I mean methods to solve typical work-a-day problems we all have. </p> <p>An example would be the .NET String.Format() method. Not only more convenient, but makes reading and trouble-shooting string concatenation better. While I have already created a String prototype method for this, I'd like to see if a good library has already been developed to address similar productivity issues before launching into a library of my own.</p> <p>Prototype has a few interesting methods in this regard, but since I've already settled on jQuery for DOM work, I really don't need to duplicate functionality on every page.</p> <p>Is anyone aware of a good, lean data type productivity library for Javascript?</p>
[ { "answer_id": 298019, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "$.trim(String), $.inArray(value, Array)" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30214/" ]
297,996
<p>I'm currently working on a very short project on Prolog, and just got stuck trying to apply a "filter" I have created to a list. I have what you could call the filter ready, but I can't apply it. It'd be better if I illustrate:</p> <pre><code>filter(A, B) </code></pre> <p>...outputs 'true' if certain conditions are met.</p> <pre><code>filterList(A, [X, Y, Z]) </code></pre> <p>...outputs a list which includes all elements from the second argument that make the filter output <strong>false</strong>. (So if filter(A, X) is true, the output is [Y, Z] ).</p> <p>I have the "filter" function ready, but now I need to apply it to a list as shown on the second example, excluding all elements for which the filter returns true when applied with the first argument. </p> <p>So, if the filter is a simple A == B, the function is supposed to receive A [A,B,A,C,D,A] and output [B,C,D], having removed all the elements for which the filter applies, obviously.</p> <p>I'm having trouble with the basic structure of the function, so if anyone could supply a basic outline for a function such as this it would be of great help. I've simplified my situation as much as possible so I can take whatever you may be able to provide and modify it for my needs.</p> <p>Thanks in advance!</p>
[ { "answer_id": 298022, "author": "Sergio Morales", "author_id": 9506, "author_profile": "https://Stackoverflow.com/users/9506", "pm_score": 0, "selected": false, "text": "filterList(_,[],R,R). % Returns answer when the list is exhausted.\nfilterList(L,[A|List],Temp,Res) :-\n filterList(L,List,New,Res), % Recursive call, New is either the same list\n ( filter(L,A), % in case the filter outputs true, or the list\n New = Temp\n ; New = [A|Temp] % plus the current element otherwise.\n ).\n" }, { "answer_id": 299648, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 4, "selected": true, "text": "filter/3 filter/4 \nfilter(_,[],[]).\nfilter(P, A0-As0, As) :-\n (\n call(P, A0) -> As = A0-As1\n ;\n As = As1\n )\n , filter(P, As0, As1).\n map foldr compose call/3 apply =.." }, { "answer_id": 338774, "author": "Kaarel", "author_id": 12547, "author_profile": "https://Stackoverflow.com/users/12547", "pm_score": 4, "selected": false, "text": "exclude/3 are_identical(X, Y) :-\n X == Y.\n\nfilterList(A, In, Out) :-\n exclude(are_identical(A), In, Out).\n ?- filterList(A, [A, B, A, C, D, A], Out).\nOut = [B, C, D].\n" }, { "answer_id": 22053194, "author": "false", "author_id": 772868, "author_profile": "https://Stackoverflow.com/users/772868", "pm_score": 2, "selected": false, "text": "if_/3 tfilter(_CT_2, [], []).\ntfilter(CT_2, [E|Es], Fs0) :-\n if_(call(CT_2,E), Fs0 = [E|Fs], Fs0 = Fs ),\n tfilter(CT_2, Es, Fs).\n =(X,X,true).\n=(X,Y,false) :- dif(X,Y).\n ?- tfilter(=(X),[A,B],Xs).\n X = A, B = X, Xs = [X,X]\n; X = A, Xs = [X], dif(X,B)\n; X = B, Xs = [X], dif(X,A)\n; Xs = [], dif(X,A), dif(X,B).\n X" }, { "answer_id": 46475885, "author": "Jesus Ledesma", "author_id": 8691565, "author_profile": "https://Stackoverflow.com/users/8691565", "pm_score": 0, "selected": false, "text": "habitants(USA, [juan, pedro, david])\n\nadults(Adults, Country) :-\n findall(Person, (habitants(Country,People), member(People, Person), adult(Person)), Adults)\n" }, { "answer_id": 54470630, "author": "Bill McEnaney", "author_id": 10998476, "author_profile": "https://Stackoverflow.com/users/10998476", "pm_score": 0, "selected": false, "text": "filter(_,[],[]).\nfilter(Predicate,[First|Rest],[First|Tail]) :-\n filter(Predicate,Rest,Tail).\nfilter(Predicate,[_|Rest],Result) :-\n filter(Predicate,Rest,Result).\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/297996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9506/" ]
298,004
<p>Is there a neat archiving library that automatically handles archiving a folder or directories for you out there? I am using Jython, so Java libs are also open for use. -UPDATE- Also Im looking for timestamp archiving. ie </p> <p>archive-dir/2008/11/16/zipfilebypreference.zip</p> <p>then the next day call it again and it creates another folder. Im sure there is something out there on the internet, who knows?</p>
[ { "answer_id": 298030, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "import javax.servlet.http.HttpServlet\n\nimport cStringIO\nimport gzip\nimport string\n\ndef compressBuf(buf):\n zbuf = cStringIO.StringIO()\n zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 6)\n zfile.write(buf)\n zfile.close()\n return zbuf.getvalue()\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
298,009
<p>Is there any way to direct C# to ignore <code>NullReferenceException</code> (or any specific exception for that matter) for a set of statements. This is useful when trying to read properties from a deserialized object that may contain many null objects in it. Having a helper method to check for null could be one way but I'm looking for something close to 'On Error Resume Next' (from VB) at a block of statement level.</p> <p>EDIT:Try-Catch will skip the succeeding statements on exception</p> <pre><code>try { stmt 1;// NullReferenceException here, will jump to catch - skipping stmt2 and stmt 3 stmt 2; stmt 3; } catch (NullReferenceException) { } </code></pre> <p>For Example: I'm deserializing an XML message to an object and then try to access a property like</p> <pre><code>Message.instance[0].prop1.prop2.ID </code></pre> <p>now prop2 could be a null object (because it doesn't exists in XML Message - an optional element in XSD). right now I need to check for null for each element in the hierarchy before accessing the leaf element. i.e I've to check if instance[0], prop1, prop2 are not null, before accessing 'ID'.</p> <p>Is there a better way that avoids null-checking for each element in the hierarchy?</p>
[ { "answer_id": 298012, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "string foo = null;\nfoo.Spooky();\n...\npublic static void Spooky(this string bar) {\n Console.WriteLine(\"boo!\");\n}\n string name = obj == null ? \"\" : obj.Name;\n" }, { "answer_id": 298014, "author": "Chris Fulstow", "author_id": 38126, "author_profile": "https://Stackoverflow.com/users/38126", "pm_score": 0, "selected": false, "text": "try\n{\n // exceptions thrown here...\n}\ncatch (NullReferenceException) { }\n" }, { "answer_id": 298037, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 3, "selected": false, "text": "string str = myItem.MyProperty == null ? \"\" : myItem.MyProperty.GetValue();\n string str = myItem.MyProperty.GetValue() ?? \"<Unknown>\";\n string str = myItem.MyProperty == null \n ? \"\" \n : (myItem.MyProperty.GetValue() ?? \"<Unknown>\");\n" }, { "answer_id": 366484, "author": "usman shaheen", "author_id": 7722, "author_profile": "https://Stackoverflow.com/users/7722", "pm_score": 2, "selected": true, "text": "public delegate string SD();//declare before class definition\n\nstring X = GetValue(() => Message.instance[0].prop1.prop2.ID); //usage\n\n//GetValue defintion\nprivate string GetValue(SD d){\n try\n {\n return d();\n }\n catch (NullReferenceException) {\n return \"\";\n }\n\n }\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7722/" ]