qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
205,660
<p>It seems that Groovy does not support <code>break</code> and <code>continue</code> from within a closure. What is the best way to simulate this?</p> <pre><code>revs.eachLine { line -&gt; if (line ==~ /-{28}/) { // continue to next line... } } </code></pre>
[ { "answer_id": 205764, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 7, "selected": true, "text": "revs.eachLine { line -> \n if (line ==~ /-{28}/) {\n return // returns from the closure\n }\n}\n revs.eachLine { line -> \n if (!(line ==~ /-{28}/)) {\n // do what you would normally do\n }\n}\n revs.eachLine { line -> \n while (true) {\n if (line ==~ /-{28}/) {\n break\n }\n // rest of normal code\n break\n }\n\n}\n try {\n revs.eachLine { line -> \n if (line ==~ /-{28}/) {\n throw new Exception(\"Break\")\n }\n }\n} catch (Exception e) { } // just drop the exception\n" }, { "answer_id": 214443, "author": "Cliff", "author_id": 10631, "author_profile": "https://Stackoverflow.com/users/10631", "pm_score": 4, "selected": false, "text": "revs.eachLine { line -> \n if (line ==~ /-{28}/) {\n return\n }\n\n}\n class FileSupport {\n public static String findLineMatching(File f, Closure c) {\n f.withInputStream {\n def r = new BufferedReader(new InputStreamReader(it))\n for(def l = r.readLine(); null!=l; l = r.readLine())\n if(c.call(l)) return l\n return null\n }\n }\n}\n\nusing(FileSupport) { new File(\"/home/me/some.txt\").findLineMatching { line ==~ /-{28}/ }\n" }, { "answer_id": 2897895, "author": "Ralph", "author_id": 96233, "author_profile": "https://Stackoverflow.com/users/96233", "pm_score": 4, "selected": false, "text": "final static BREAK = new Exception();\n//...\ntry {\n ... { throw BREAK; }\n} catch (Exception ex) { /* ignored */ }\n" }, { "answer_id": 9882399, "author": "0rt", "author_id": 1294411, "author_profile": "https://Stackoverflow.com/users/1294411", "pm_score": 2, "selected": false, "text": "find()" }, { "answer_id": 19413873, "author": "Michal Zmuda", "author_id": 1113929, "author_profile": "https://Stackoverflow.com/users/1113929", "pm_score": 3, "selected": false, "text": "1\n2\n----------------------------\n3\n4\n5\n new FileReader('myfile.txt').any { line ->\n if (line =~ /-+/)\n return // continue\n\n println line\n\n if (line == \"3\")\n true // break\n}\n 1\n2\n3\n" }, { "answer_id": 30592478, "author": "frhack", "author_id": 3360759, "author_profile": "https://Stackoverflow.com/users/3360759", "pm_score": 2, "selected": false, "text": "import rx.Observable\n\nObservable.from(1..100000000000000000)\n .filter { it % 2 != 1} \n .takeWhile { it<10 } \n .forEach {println it}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20103/" ]
205,666
<p>I have an alert script that I am trying to keep from spamming me so I'd like to place a condition that if an alert has been sent within, say the last hour, to not send another alert. Now I have a cron job that checks the condition every minute because I need to be alerted quickly when the condition is met but I don't need to get the email every munite until I get the issue under control. What is the best way to compare time in bash to accomplish this?</p>
[ { "answer_id": 205681, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 4, "selected": false, "text": "if test file1 -nt file2; then\n # file1 is newer than file2\nfi\n" }, { "answer_id": 205694, "author": "jonathan-stafford", "author_id": 27587, "author_profile": "https://Stackoverflow.com/users/27587", "pm_score": 4, "selected": false, "text": "last = cat /tmp/.lastrun\ncurr = date '+%s'\n\ndiff = $(($curr - $last))\nif [ $diff -gt 3600 ]; then\n # ...\nfi\n\necho \"$curr\" >/tmp/.lastrun\n" }, { "answer_id": 205710, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 7, "selected": true, "text": "touch date -nt -ot touch -d '-1 hour' limit\nif [ limit -nt last_notification ]; then\n #send notification...\n touch last_notification\nfi\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27247/" ]
205,668
<p>I'm copying a file from folder A to folder B and then trying to copy the file permissions. Here are the basic steps I'm using:</p> <ol> <li>CopyFile(source, target)</li> <li>GetNamedSecurityInfo(source, GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION)</li> <li>Print source SD using ConvertSecurityDescriptorToStringSecurityDescriptor</li> <li>SetNamedSecurityInfo(target, GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION)</li> <li>GetNamedSecurityInfo(target, GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION)</li> <li>Print target SD using ConvertSecurityDescriptorToStringSecurityDescriptor</li> </ol> <p>At #3 I get this SD:</p> <pre><code>G:S-1-5-21-1454471165-1482476501-839522115-513D:AI(A;ID;0x1200a9;;;BU)(A;ID;0x1301bf;;;PU)(A;ID;FA;;;BA)(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-1454471165-1482476501-839522115-1004) </code></pre> <p>At #6 I get</p> <pre><code>G:S-1-5-21-1454471165-1482476501-839522115-513D:AI(A;ID;0x1301bf;;;PU)(A;ID;FA;;;BA)(A;ID;FA;;;SY) </code></pre> <p>The call to SetNamedSecurityInfo returns ERROR_SUCCESS, yet the results are the source and target file do not have the same SDs. Why is that? What am I doing wrong here?</p>
[ { "answer_id": 206671, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": true, "text": "SHFileOperation" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24898/" ]
205,688
<p>What is the best technique for catching ALL exceptions thrown within JavaScript?</p> <p>Obviously, the best technique is to use try...catch. But with ansynchronous callbacks and so forth, that can get tricky.</p> <p>I know IE and Gecko browsers support window.onerror, but what about Opera and Safari?</p> <p>Here are a bunch of test-cases that I would like to have a central exception handling solution for:</p> <pre><code>// ErrorHandler-Test1 var test = null; test.arg = 5; // ErrorHandler-Test2 throw (new Error("Hello")); // ErrorHandler-Test3 throw "Hello again"; // ErrorHandler-Test4 throw { myMessage: "stuff", customProperty: 5, anArray: [1, 2, 3] }; // ErrorHandler-Test5 try { var test2 = null; test2.arg = 5; } catch(e) { ErrorHandler.handleError(e); } // ErrorHandler-Test6 try { throw (new Error("Goodbye")); } catch(e) { ErrorHandler.handleError(e); } // ErrorHandler-Test7 try { throw "Goodbye again"; } catch(e) { ErrorHandler.handleError(e); } // ErrorHandler-Test8 try { throw { myMessage: "stuff", customProperty: 5, anArray: [1, 2, 3] }; } catch(e) { ErrorHandler.handleError(e); } </code></pre> <p>If you think of any other test-cases, please mention them. Several of these cases mention a ErrorHandler.handleError method. This is just a suggested guideline when using try...catch.</p>
[ { "answer_id": 205884, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 4, "selected": false, "text": "onerror onerror" }, { "answer_id": 205982, "author": "Karl", "author_id": 2932, "author_profile": "https://Stackoverflow.com/users/2932", "pm_score": 5, "selected": false, "text": "window.onerror window.onerror" }, { "answer_id": 471851, "author": "adamfisk", "author_id": 426961, "author_profile": "https://Stackoverflow.com/users/426961", "pm_score": 3, "selected": false, "text": "$(window).error(function(msg, url, line){\n $.post(\"js_error_log.php\", { msg: msg, url: url, line: line });\n});\n" }, { "answer_id": 4376524, "author": "wolfgang", "author_id": 533639, "author_profile": "https://Stackoverflow.com/users/533639", "pm_score": 2, "selected": false, "text": "try-catch" }, { "answer_id": 13285023, "author": "MyounghoonKim", "author_id": 1115332, "author_profile": "https://Stackoverflow.com/users/1115332", "pm_score": 3, "selected": false, "text": "$(\"inuput\").live({\n click : function (event) {\n try {\n if (somethingGoesWrong) {\n throw new MyException();\n }\n } catch (Exception) {\n new MyExceptionHandler(Exception);\n }\n\n }\n});\n\nfunction MyExceptionHandler(Exception) {\n if (Exception instanceof TypeError || \n Exception instanceof ReferenceError || \n Exception instanceof RangeError || \n Exception instanceof SyntaxError || \n Exception instanceof URIError ) {\n throw Exception; // native error\n } else {\n // handle exception\n }\n}\n" }, { "answer_id": 31742744, "author": "Fizer Khan", "author_id": 1154350, "author_profile": "https://Stackoverflow.com/users/1154350", "pm_score": 2, "selected": false, "text": "window.onerror window.onerror // Only Chrome & Opera pass the error object.\nwindow.onerror = function (message, file, line, col, error) {\n console.log(message, \"from\", error.stack);\n // You can send data to your server\n // sendData(data);\n};\n// Only Chrome & Opera have an error attribute on the event.\nwindow.addEventListener(\"error\", function (e) {\n console.log(e.error.message, \"from\", e.error.stack);\n // You can send data to your server\n // sendData(data);\n})\n window.onerror try{ }catch(e){ } function wrap(func) {\n // Ensure we only wrap the function once.\n if (!func._wrapped) {\n func._wrapped = function () {\n try{\n func.apply(this, arguments);\n } catch(e) {\n console.log(e.message, \"from\", e.stack);\n // You can send data to your server\n // sendData(data);\n throw e;\n }\n }\n }\n return func._wrapped;\n};\n function sendData(data) {\n var img = newImage(),\n src = http://yourserver.com/jserror + '&data=' + encodeURIComponent(JSON.stringify(data));\n\n img.crossOrigin = 'anonymous';\n img.onload = function success() {\n console.log('success', data);\n };\n img.onerror = img.onabort = function failure() {\n console.error('failure', data);\n };\n img.src = src;\n}\n" }, { "answer_id": 32642352, "author": "K. Craven", "author_id": 5348220, "author_profile": "https://Stackoverflow.com/users/5348220", "pm_score": 1, "selected": false, "text": "window.addEventListener('error', callback) window.attachEvent('onerror', callback) window.onerror <script type=\"text/javascript\" src=\"//cdn.raygun.io/raygun4js/raygun.min.js\" </script>\n<script>\n Raygun.init('yourApiKey').attach();\n</script>" }, { "answer_id": 68584769, "author": "Rodrigo Alvaro Santo SD 6", "author_id": 15448375, "author_profile": "https://Stackoverflow.com/users/15448375", "pm_score": 0, "selected": false, "text": "try {\n // something\n} catch(e) {\n window.location.href = \"https://stackoverflow.com/search?q=[js] + \" + e.message\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26259/" ]
205,689
<p>Say I have a class that's meant to perform a single function. After performing the function, it can be destroyed. Is there any reason to prefer one of these approaches?</p> <pre><code>// Initialize arguments in constructor MyClass myObject = new MyClass(arg1, arg2, arg3); myObject.myMethod(); // Pass arguments to method MyClass myObject = new MyClass(); myObject.myMethod(arg1, arg2, arg3); // Pass arguments to static method MyClass.myMethod(arg1, arg2, arg3); </code></pre> <p>I was being intentionally vague about the details, to try to get guidelines for different situations. But I didn't really have in mind simple library functions like Math.random(). I'm thinking more of classes that perform some specific, complex task, but only require one (public) method to do it.</p>
[ { "answer_id": 205859, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "new MyClass(arg1, arg2, arg3);// the constructor does everything.\n MyClass my_object(arg1, arg2, arg3);\n" }, { "answer_id": 2073743, "author": "Sam Harwell", "author_id": 138304, "author_profile": "https://Stackoverflow.com/users/138304", "pm_score": 2, "selected": false, "text": "internal I[ServiceName]Service public interface ISettingsService\n{\n string ReadSetting(string name);\n\n void WriteSetting(string name, string value);\n}\n\n[Export]\npublic class ObjectRequiringSettings\n{\n [Import]\n private ISettingsService SettingsService\n {\n get;\n set;\n }\n\n private void Foo()\n {\n if (SettingsService.ReadSetting(\"PerformFooAction\") == bool.TrueString)\n {\n // whatever\n }\n }\n}\n" }, { "answer_id": 14624287, "author": "Hugo Wood", "author_id": 1067260, "author_profile": "https://Stackoverflow.com/users/1067260", "pm_score": 0, "selected": false, "text": "arg1.myMethod1(arg2, arg3) class Arg1Decorator\n private final T1 arg1;\n public Arg1Decorator(T1 arg1) {\n this.arg1 = arg1;\n }\n public T myMethod(T2 arg2, T3 arg3) {\n ...\n }\n }\n\n arg1d = new Arg1Decorator(arg1)\n arg1d.myMethod(arg2, arg3)\n" }, { "answer_id": 61806856, "author": "Mark Walsh", "author_id": 1890742, "author_profile": "https://Stackoverflow.com/users/1890742", "pm_score": 0, "selected": false, "text": "public abstract class DoSomethingClass<T>\n{\n protected abstract void doSomething(T arg1, T arg2, T arg3);\n}\n\npublic abstract class ReturnSomethingClass<T, V>\n{\n public T value;\n protected abstract void returnSomething(V arg1, V arg2, V arg3);\n}\n\npublic class DoSomethingInt extends DoSomethingClass<Integer>\n{\n public DoSomethingInt(int arg1, int arg2, int arg3)\n {\n doSomething(arg1, arg2, arg3);\n }\n\n @Override\n protected void doSomething(Integer arg1, Integer arg2, Integer arg3)\n {\n // ...\n }\n}\n\npublic class ReturnSomethingString extends ReturnSomethingClass<String, Integer>\n{\n public ReturnSomethingString(int arg1, int arg2, int arg3)\n {\n returnSomething(arg1, arg2, arg3);\n }\n\n @Override\n protected void returnSomething(Integer arg1, Integer arg2, Integer arg3)\n {\n String retValue;\n // ...\n value = retValue;\n }\n}\n\npublic class MainClass\n{\n static void main(String[] args)\n {\n int a = 3, b = 4, c = 5;\n\n Object dummy = new DoSomethingInt(a,b,c); // doSomething was called, dummy is still around though\n String myReturn = (new ReturnSomethingString(a,b,c)).value; // returnSomething was called and immediately destroyed\n }\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4321/" ]
205,697
<p>I have a query that has a list of base values and a list of language values. Each value has a key that matches to the other. The base values are stored in one table and the language values in another. My problem is that I need to get all matching base values removed from the QUERY except for one. Then, I export that query into an Excel spreadsheet (I can do this portion fine) and allow the user to edit the language values.</p> <p>When the user edits and/or inserts new language values, I need to update the database except now writing over any matching values in the database (like those that were removed the first time).</p> <p>In simplicity, the client pays for translations and if I can generate a sheet that has fewer translations needed (like phrases that reappear often) then they can save money, hence the project to begin with. I realize the downside is that it is not a true linked list, where all matching values all belong to one row in the language table (which would have been easy). Instead, there are multiple values that are identical that need to be updated as described above.</p> <hr> <p>Yeah, I'm confused on it which is why it might seem a little vague. Here's a sample:</p> <pre><code>Table 1 Item Description1 Item Description2 Item Description3 Item Description2 Item Description2 Item Description4 Item Description5 Item Description6 Item Description3 Table 2 Item Desc in other Language1 Item Desc in other Language2 Item Desc in other Language3 (blank) Item Desc in other Language3 Item Desc in other Language4 Item Desc in other Language5 *blank* </code></pre> <p>Desired Result (when queried)</p> <p>Table 1 Item Description1 Item Description2 Item Description3 Item Description4 Item Description5 Item Description6</p> <pre><code>Table 2 Item Desc in other Language1 Item Desc in other Language2 Item Desc in other Language3 (filled by matching row in Table 2) Item Desc in other Language4 Item Desc in other Language5 Item Desc in other Language6 (blank, returned as empty string) </code></pre> <p>The user makes their modifications, including inserting data into blank rows (like row 6 for the language) then reuploads:</p> <pre><code>Table 1 Item Description1 Item Description2 Item Description3 Item Description2 Item Description2 Item Description4 Item Description5 Item Description6 Item Description3 Table 2 Item Desc in other Language1 Item Desc in other Language2 Item Desc in other Language3 (now matches row below) Item Desc in other Language3 Item Desc in other Language4 Item Desc in other Language5 Item Desc in other Language6 (new value entered by user) </code></pre> <p>There is also a resource key that matches each "Item Description" to a single "Item Desc in other Language". The only time they are ever going to see each other is during this translation process, all other times the values may be different, so the resource keys can't simply be changed to all point at one translation permanently.</p> <p>I should also add, there should be no alteration of the structure of the tables or removing rows of the table.</p> <hr> <p>Ok, here's an updated revisal of what I would LIKE the query to do, but obviously does not do since I actually need the values of the joined table:</p> <pre><code>SELECT pe.prodtree_element_name_l, rs.resource_value, pe.prodtree_element_name_l_rk FROM prodtree_element pe LEFT JOIN resource_shortstrings rs ON pe.prodtree_element_name_l_rk = rs.resource_key WHERE rs.language_id = '5' AND pe.prodtree_element_name_l &lt;&gt; '' GROUP BY pe.prodtree_element_name_l </code></pre>
[ { "answer_id": 205798, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 0, "selected": false, "text": "delete from matchtable where (id1 = 12 and id2 = 13) or (id1 = 13 and id2 = 13);\ninsert into matchtable (id1, id2) values (12, 13);\n" }, { "answer_id": 206464, "author": "Organiccat", "author_id": 16631, "author_profile": "https://Stackoverflow.com/users/16631", "pm_score": 1, "selected": true, "text": "<cfquery name=\"getRows\" datasource=\"XXXX\">\n SELECT pe.prodtree_element_name_l, MAX(rs.resource_value) AS resource_value\n FROM prodtree_element pe\n LEFT JOIN resource_shortstrings rs\n ON pe.prodtree_element_name_l_rk = rs.resource_key\n WHERE rs.language_id = '5'\n AND pe.prodtree_element_name_l <> ''\n GROUP BY prodtree_element_name_l\n</cfquery>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16631/" ]
205,704
<p>Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?</p>
[ { "answer_id": 207059, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 2, "selected": false, "text": "python -c 'import x' .py" }, { "answer_id": 207593, "author": "Matt Curtis", "author_id": 17221, "author_profile": "https://Stackoverflow.com/users/17221", "pm_score": 0, "selected": false, "text": "compile M-x compile recompile" }, { "answer_id": 8584325, "author": "Matt Joiner", "author_id": 149482, "author_profile": "https://Stackoverflow.com/users/149482", "pm_score": 4, "selected": false, "text": "python -m py_compile script.py\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
205,731
<p>I need the values of form inputs to be populated by the sql database. My code works great for all text and textarea inputs but I can't figure out how to assign the database value to the drop down lists eg. 'Type of property' below. It revolves around getting the 'option selected' to represent the value held in the database.</p> <p>Here is my code:</p> <pre><code>$result = $db-&gt;sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'"); $row = $db-&gt;sql_fetchrow($result); echo "&lt;center&gt;&lt;font class=\"title\"&gt;"._CHANGE_MY_INFORMATION."&lt;/font&gt;&lt;/center&gt;&lt;br&gt;\n"; echo "&lt;center&gt;".All." ".fields." ".must." ".be." ".filled." &lt;form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\"&gt; &lt;table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\"&gt; &lt;tr&gt; &lt;td align=\"right\"&gt;".Telephone." :&lt;/td&gt; &lt;td&gt; &lt;input type=\"text\" name=\"telephone\" size=\"27\" value=\"$row[telephone]\"&gt; Inc. dialing codes &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align=\"right\"&gt;".Type." ".of." ".property." ".required." :&lt;/td&gt; &lt;td&gt;Select from list: &lt;select name=\"req_type\" value=\"$row[req_type]\"&gt; &lt;option&gt;House&lt;/option&gt; &lt;option&gt;Bungalow&lt;/option&gt; &lt;option&gt;Flat/Apartment&lt;/option&gt; &lt;option&gt;Studio&lt;/option&gt; &lt;option&gt;Villa&lt;/option&gt; &lt;option&gt;Any&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; .... </code></pre>
[ { "answer_id": 205778, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<?php\n $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n\n foreach($options as $option) {\n if ($option == $row['req_type']) {\n print '<option selected=\"selected\">'.$option.'</option>'.\"\\n\";\n } else {\n print '<option>'.$option.'</option>'.\"\\n\";\n }\n }\n?>\n $row['req_type'] $options $row['req_type'] $row[req_type] error_reporting(E_ALL) htmlentities()" }, { "answer_id": 206006, "author": "Brad", "author_id": 26130, "author_profile": "https://Stackoverflow.com/users/26130", "pm_score": -1, "selected": false, "text": "<?php\n$query = \"SELECT * FROM \".$prefix.\"_users WHERE userid='$userid'\";\n$result = mysql_query($query); ?>\n$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n<select name=\"venue\">\n<?php\n while($row = mysql_fetch_array($result)) {\n print '<option value=\"'.$option.'\"';\n if($row['req_type'] == $option) {\n print 'selected';\n }\n print '>'.$option.'</option>';\n } \n?>\n</select>\n" }, { "answer_id": 206817, "author": "user24632", "author_id": 24632, "author_profile": "https://Stackoverflow.com/users/24632", "pm_score": 0, "selected": false, "text": "$dropdown = str_replace(\"<option value=\\\"\".$row[column].\"\\\">\",\"<option value=\\\"\".$row[column].\"\\\" selected>\",$dropdown);\n" }, { "answer_id": 207126, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<td>Select from list: <select name=\\\"req_type\\\"> \n\n$option = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n\nforeach($option as $option) { \nif ($option == $row[req_type]) { \n <option selected>$option</option>} \nelse { \n<option>$option</option>}};\n</select></td>\n" }, { "answer_id": 207303, "author": "andyk", "author_id": 26721, "author_profile": "https://Stackoverflow.com/users/26721", "pm_score": 0, "selected": false, "text": " <?php\n $result = $db->sql_query(\"SELECT * FROM \".$prefix.\"_users WHERE userid='$userid'\"); \n $row = $db->sql_fetchrow($result);\n\n // options defined here\n $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');\n\n ?> \n <center><font class=\"title\"><?php echo _CHANGE_MY_INFORMATION; ?></font></center><br />\n\n <center> All fields must be filled </center> \n <form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\"> \n <table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\"> \n <tr> \n <td align=\"right\">Telephone :</td> \n <td>\n <input type=\"text\" name=\"telephone\" size=\"27\" value=\"<?php echo htmlentities($row['telephone']); ?>\" /> Inc. dialing codes\n </td> \n </tr> \n <tr> \n <td align=\"right\">Type of property required :</td> \n <td>Select from list:\n <select name=\"req_type\">\n <?php foreach($options as $option): ?> \n <option value=\"<?php echo $option; ?>\" <?php if($row['req_type'] == $option) echo 'selected=\"selected\"'; ?>><?php echo $option; ?></option> \n <?php endforeach; ?>\n </select> \n </td> \n </tr>\n\n...\n" }, { "answer_id": 209169, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if ($row[$req_type]=='House'){\n $sel_req_type1='selected';\n}\nelse if ($row[$req_type]=='Bugalow'){\n $sel_req_type2='selected';\n}\n <option $sel_req_type1>House</option>\n<option $sel_req_type2>Bulgalow</option>\n $row['req_type'] $row[req_type]" }, { "answer_id": 2931535, "author": "BKCOHEN", "author_id": 350231, "author_profile": "https://Stackoverflow.com/users/350231", "pm_score": 1, "selected": false, "text": "$query9 = \"SELECT *\n FROM vehicles\n WHERE VID = '\".$VID.\"'\n \";\n\n$result9=mysql_query($query9);\nwhile($row9 = mysql_fetch_array($result9)){\n $vdate=$row9['DateBid'];\n $vmodelid=$row9['ModelID'];\n $vMileage=$row9['Mileage'];\n $vHighBid=$row9['HighBid'];\n $vPurchased=$row9['Purchased'];\n $vDamage=$row9['Damage'];\n $vNotes=$row9['Notes'];\n $vKBBH=$row9['KBBH'];\n $vKBBM=$row9['KBBM'];\n $vKBBL=$row9['KBBL'];\n $vKBBR=$row9['KBBR'];\n $vYID=$row9['YID'];\n $vMID=$row9['MID'];\n $vModelID=$row9['ModelID'];\n $vELID=$row9['ELID'];\n $vECID=$row9['ECID'];\n $vEFID=$row9['EFID'];\n $vColorID=$row9['ColorID'];\n $vRID=$row9['RID'];\n $vFID=$row9['FID'];\n $vDID=$row9['DID'];\n $vTID=$row9['TID'];\n}\n\n$query1 = \"SELECT * FROM year ORDER BY Year ASC\";\n$result1=mysql_query($query1);\necho \"<select name='Year'>\";\nwhile($row1 = mysql_fetch_array($result1)){\n echo \"<option value = '{$row1['YID']}'\";\n if ($vYID == $row1['YID'])\n echo \"selected = 'selected'\";\n echo \">{$row1['Year']}</option>\";\n}\necho \"</select>\";\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
205,733
<p>Is it possible to call a class's static property to set the navigateurl property?</p> <blockquote> <pre><code>&lt;asp:HyperLink ID="hlRegister" NavigateUrl="&lt;%= SomeClass.Property %&gt;" runat="server" /&gt; </code></pre> </blockquote> <p><b>without using codebehind ofcourse!</b></p>
[ { "answer_id": 205742, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": "hl.NavigateUrl = Class.Static().ToString();\n" }, { "answer_id": 205767, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 1, "selected": false, "text": "public static class SomeClass\n{\n public static string Property\n {\n get { return \"http://www.google.com\"; }\n }\n}\n <asp:HyperLink ID=\"hlRegister\" NavigateUrl='<%= SomeClass.Property.ToString() %>' Text=\"Goooooogle\" runat=\"server\" />\n" }, { "answer_id": 205865, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": " <asp:HyperLink ID=\"hlRegister\" \n NavigateUrl='<%= SomeClass.Property %>' runat=\"server\" />\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
205,735
<p>My knowledge of matlab is merely on a need to know basis, so this is probably an elementary question. Nevertheless here it comes:</p> <p>I have got a file containing data (16-bit integers) stored in binary format. How do I read it into a vector /an array in matlab? How do I write this data to a file in matlab? Is there any smart tweak to increase the performance speed when reading/writing a huge amount of data (gigabytes)?</p>
[ { "answer_id": 205819, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "fid = fopen('data.bin','rb')\nA = fread(fid, count, 'int16')\n fid = fopen('data.bin','w')\ncount = fwrite(fid, A, 'int16')\n" }, { "answer_id": 206199, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 5, "selected": true, "text": ">> fid=fopen('data.bin','rb') % opens the file for reading\n>> A = fread(fid, count, 'int16') % reads _count_ elements and stores them in A.\n >> A = fread(fid, count, 'int16', 'ieee-be');\n >> count=inf;\n >> count=[n inf];\n >> dlmwrite('data.csv',A,',');\n >> A = int16(fread(fid,count,precision,machineFormat));\n >> fseek(fid,0,'bof');\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044/" ]
205,736
<p>How do I query an Oracle database to display the names of all tables in it?</p>
[ { "answer_id": 205746, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 11, "selected": true, "text": "SELECT owner, table_name\n FROM dba_tables\n DBA_TABLES SELECT ANY DICTIONARY SELECT_CATALOG_ROLE SYS SYSTEM DBA_TABLES ALL_TABLES SELECT owner, table_name\n FROM all_tables\n ALL_TABLES USER_TABLES SELECT table_name\n FROM user_tables\n USER_TABLES OWNER TAB DICT TABS CAT TAB CAT [DBA|ALL|USER]_TABLES CAT TABLE_TYPE DICT" }, { "answer_id": 205811, "author": "vitule", "author_id": 1287, "author_profile": "https://Stackoverflow.com/users/1287", "pm_score": 8, "selected": false, "text": "user_tables dba_tables select table_name from all_tables \n" }, { "answer_id": 1377725, "author": "stealth_angoid", "author_id": 167171, "author_profile": "https://Stackoverflow.com/users/167171", "pm_score": 6, "selected": false, "text": "SELECT table_name, column_name\nFROM cols\nWHERE table_name LIKE 'EST%'\nAND column_name LIKE '%CALLREF%';\n" }, { "answer_id": 10320765, "author": "Mahmoud Ahmed El-Sayed", "author_id": 1323891, "author_profile": "https://Stackoverflow.com/users/1323891", "pm_score": 4, "selected": false, "text": "tabs\ndba_tables\nall_tables\nuser_tables\n" }, { "answer_id": 11946866, "author": "praveen2609", "author_id": 1479168, "author_profile": "https://Stackoverflow.com/users/1479168", "pm_score": 3, "selected": false, "text": "select * from dba_tables\n sysdba" }, { "answer_id": 13993788, "author": "Israel Margulies", "author_id": 1346806, "author_profile": "https://Stackoverflow.com/users/1346806", "pm_score": 5, "selected": false, "text": " SELECT table_name FROM user_tables;\n" }, { "answer_id": 22257585, "author": "Van Gogh", "author_id": 3241616, "author_profile": "https://Stackoverflow.com/users/3241616", "pm_score": 3, "selected": false, "text": "SELECT DISTINCT OWNER, OBJECT_NAME \n FROM DBA_OBJECTS \n WHERE OBJECT_TYPE = 'TABLE' AND OWNER='SOME_SCHEMA_NAME';\n\nSELECT DISTINCT OWNER, OBJECT_NAME \n FROM ALL_OBJECTS \n WHERE OBJECT_TYPE = 'TABLE' AND OWNER='SOME_SCHEMA_NAME';\n" }, { "answer_id": 24808745, "author": "cwd", "author_id": 288032, "author_profile": "https://Stackoverflow.com/users/288032", "pm_score": 6, "selected": false, "text": "sqlplus sqlplus sqlplus set colsep '|'\nset linesize 167\nset pagesize 30\nset pagesize 1000\n SELECT table_name, owner, tablespace_name FROM all_tables;\n SELECT table_name FROM user_tables;\n SELECT view_name FROM all_views;\n" }, { "answer_id": 26253523, "author": "Harshil", "author_id": 1636874, "author_profile": "https://Stackoverflow.com/users/1636874", "pm_score": 4, "selected": false, "text": " select object_name from user_objects where object_type='TABLE';\n select * from tab;\n select table_name from user_tables;\n" }, { "answer_id": 26828225, "author": "Mateen", "author_id": 3156006, "author_profile": "https://Stackoverflow.com/users/3156006", "pm_score": 2, "selected": false, "text": "select table_name from user_tables;\n" }, { "answer_id": 37936871, "author": "Prashant Mishra", "author_id": 4534585, "author_profile": "https://Stackoverflow.com/users/4534585", "pm_score": 2, "selected": false, "text": "-- need to have select catalog role\nSELECT * FROM dba_tables;\n\n-- to see tables of your schema\nSELECT * FROM user_tables;\n\n-- tables inside your schema and tables of other schema which you possess select grants on\nSELECT * FROM all_tables;\n" }, { "answer_id": 39945684, "author": "Slava Babin", "author_id": 3001523, "author_profile": "https://Stackoverflow.com/users/3001523", "pm_score": 2, "selected": false, "text": "select * \nfrom dba_tables\n select * \nfrom dba_objects \nwhere object_type = 'TABLE' \n select * \nfrom dba_tab_columns\n select * \nfrom dba_dependencies\nwhere referenced_type='TABLE' and referenced_name=:t_name \n select * from dba_source\n USER ALL DBA" }, { "answer_id": 40551167, "author": "Rusty", "author_id": 2235483, "author_profile": "https://Stackoverflow.com/users/2235483", "pm_score": 3, "selected": false, "text": "DBA_ALL_TABLES (ALL_ALL_TABLES/USER_ALL_TABLES)\n" }, { "answer_id": 46931566, "author": "Punnerud", "author_id": 2326672, "author_profile": "https://Stackoverflow.com/users/2326672", "pm_score": 2, "selected": false, "text": "SELECT owner, table_name as table_view\n FROM dba_tables\nUNION ALL\nSELECT owner, view_name as table_view\n FROM DBA_VIEWS\n" }, { "answer_id": 47395677, "author": "aim_thebest", "author_id": 1515049, "author_profile": "https://Stackoverflow.com/users/1515049", "pm_score": 2, "selected": false, "text": "SELECT * FROM user_tab_columns;\n" }, { "answer_id": 49891879, "author": "Rakesh Narang", "author_id": 5140709, "author_profile": "https://Stackoverflow.com/users/5140709", "pm_score": 1, "selected": false, "text": "SELECT COLUMN_NAME\nFROM ALL_TAB_COLUMNS\nWHERE OWNER = 'schema_owner_username' AND TABLE_NAME='table_name'\nORDER BY COLUMN_ID ASC;\n" }, { "answer_id": 55442651, "author": "Kaushik Nayak", "author_id": 7998591, "author_profile": "https://Stackoverflow.com/users/7998591", "pm_score": 3, "selected": false, "text": "Tables sql sql.exe SQL> set sqlformat ansiconsole -- resizes the columns to the width of the \n -- data to save space \n SQL> tables TABLES\n-----------\nREGIONS\nLOCATIONS\nDEPARTMENTS\nJOBS\nEMPLOYEES\nJOB_HISTORY\n..\n tables alias list <alias> SQL> alias list tables\ntables - tables <schema> - show tables from schema\n--------------------------------------------------\n\n select table_name \"TABLES\" from user_tables\n SQL> alias tables_schema = select owner, table_name, last_analyzed from all_tables where owner = :ownr; SQL> tables_schema HR OWNER TABLE_NAME LAST_ANALYZED\nHR DUMMY1 18-10-18\nHR YOURTAB2 16-11-18\nHR YOURTABLE 01-12-18\nHR ID_TABLE 05-12-18\nHR REGIONS 26-05-18\nHR LOCATIONS 26-05-18\nHR DEPARTMENTS 26-05-18\nHR JOBS 26-05-18\nHR EMPLOYEES 12-10-18\n..\n..\n Tables2 SQL> tables2\n\nTables\n======\nTABLE_NAME NUM_ROWS BLOCKS UNFORMATTED_SIZE COMPRESSION INDEX_COUNT CONSTRAINT_COUNT PART_COUNT LAST_ANALYZED\nAN_IP_TABLE 0 0 0 Disabled 0 0 0 > Month\nPARTTABLE 0 0 0 1 0 1 > Month\nTST2 0 0 0 Disabled 0 0 0 > Month\nTST3 0 0 0 Disabled 0 0 0 > Month\nMANAGE_EMPLYEE 0 0 0 Disabled 0 0 0 > Month\nPRODUCT 0 0 0 Disabled 0 0 0 > Month\nALL_TAB_X78EHRYFK 0 0 0 Disabled 0 0 0 > Month\nTBW 0 0 0 Disabled 0 0 0 > Month\nDEPT 0 0 0 Disabled 0 0 0 > Month\n alias list tables2\n column" }, { "answer_id": 59158938, "author": "dealwithit", "author_id": 12189197, "author_profile": "https://Stackoverflow.com/users/12189197", "pm_score": -1, "selected": false, "text": "select * from all_all_tables\n OBJECT_ID_TYPE\nTABLE_TYPE_OWNER\nTABLE_TYPE\n" }, { "answer_id": 62666104, "author": "The AG", "author_id": 8692957, "author_profile": "https://Stackoverflow.com/users/8692957", "pm_score": 0, "selected": false, "text": "Select owner, table_name from all_tables;\n Select owner, table_name from dba_tables;\n" }, { "answer_id": 63919871, "author": "Prasenjit Mahato", "author_id": 10282780, "author_profile": "https://Stackoverflow.com/users/10282780", "pm_score": 3, "selected": false, "text": "sql> SELECT table_name FROM dba_tables; sql> SELECT table_name FROM user_tables; sql> SELECT table_name FROM all_tables ORDER BY table_name;" }, { "answer_id": 64717930, "author": "Ejrr1085", "author_id": 2825284, "author_profile": "https://Stackoverflow.com/users/2825284", "pm_score": -1, "selected": false, "text": "select * from tabs;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1287/" ]
205,749
<p>What are you using for binding XML to Java? JAXB, Castor, and XMLBeans are some of the available choices. The comparisons that I've seen are all three or four years old. I'm open to other suggestions. Marshalling / unmarshalling performance and ease of use are of particular interest.</p> <p>Clarification: I'd like to see not just what framework you use, but your reasoning for using one over the others.</p>
[ { "answer_id": 206236, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 2, "selected": false, "text": "EmployeesDocument empDoc = EmployeesDocument.Factory.parse(xmlFile); \n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
205,793
<p>I need to make changes to an in-use production database. Just adding a few columns. I've made the changes to the dev database with migrations. What is the best way to update the production database while preserving the existing data and not disrupting operation too much?</p> <p>It's MYSQL and I will be needing to add data to the columns as well for already existing records. One column can have a default value (it's boolean) but the other is a timestamp and should have an arbitrary backdated value. The row counts are not huge.</p> <p>So if I use migrations how do I add data and how do I get it to just do the two (or three - I add data -latest migrations on the production db when it wasn't initially built via migrations (I believe they used the schema instead)?</p>
[ { "answer_id": 206330, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "add_column" }, { "answer_id": 272673, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 4, "selected": true, "text": "class AddSomeColumnsToUserTable < ActiveRecord::Migration\n class User < ActiveRecord::Base; end\n def self.up\n add_column :users, :super_cool, :boolean, :default => :false\n u = User.find_by_login('cameron')\n u.super_cool = true\n u.save\n end\n\n def self.down\n remove_column :users, :super_cool\n end\nend\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6805/" ]
205,794
<p>For my C# RichTextBox, I want to programmatically do the same thing as clicking the up arrow at the top of a vertical scroll bar, which moves the RichTextBox display up by one line. What is the code for this? Thanks!</p>
[ { "answer_id": 205904, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 5, "selected": true, "text": "using System.Runtime.InteropServices;\n\n[DllImport(\"user32.dll\")]\nstatic extern int SendMessage(IntPtr hWnd, uint wMsg, \n UIntPtr wParam, IntPtr lParam);\n SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));\n" }, { "answer_id": 206216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "RichEdit.SelectionStart = SendMessage(RichEdit.Handle, EM_LINEINDEX, ScrollTo, 0);\nRichEdit.ScrollToCaret();\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27109/" ]
205,797
<p>I have a database with DateTime fields that are currently stored in local time. An upcoming project will require all these dates to be converted to universal time. Rather than writing a c# app to convert these times to universal time, I'd rather use available sqlserver/sql features to accurately convert these dates to universal time so I only need an update script. To be accurate, the conversion would need to account for Daylight savings time fluctuations, etc.</p>
[ { "answer_id": 205904, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 5, "selected": true, "text": "using System.Runtime.InteropServices;\n\n[DllImport(\"user32.dll\")]\nstatic extern int SendMessage(IntPtr hWnd, uint wMsg, \n UIntPtr wParam, IntPtr lParam);\n SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));\n" }, { "answer_id": 206216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "RichEdit.SelectionStart = SendMessage(RichEdit.Handle, EM_LINEINDEX, ScrollTo, 0);\nRichEdit.ScrollToCaret();\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18313/" ]
205,822
<p>I'm running PHP 5.2.6 on a Windows Server 2003 Enterprise box. IIS is set to deny anonymous access and use Integrated Windows authentication.</p> <p>I'm using a PHP script to save a file uploaded from a web form. The file is uploaded to a temp folder, the script creates a file name and path depending on other variables from the web form, and then the script uses PHP's move&#95;uploaded&#95;file() to move the temp file to the final location. All that works fine. In short, people are uploading files so everyone in the group can see them and the files are organized by the script.</p> <p>My problem is that the file in the final location has odd permissions. It is not ending up with permissions from either the temp location or the final location. Both the temp location and final location have the same permissions: full rights for owner and administrations; read and read/execute for 2 specific AD security groups. The final file ends up with only: full rights for owner and administrations. So while the admins and the original uploader have no problem viewing the file, all others in the group get "permission denied" when trying to access it.</p> <p>Any ideas or suggestions will be greatly appreciated! Thanks!</p>
[ { "answer_id": 205941, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": 3, "selected": true, "text": "move_uploaded_file() move_uploaded_file" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13414/" ]
205,853
<p>I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?</p> <p>(I'm not asking about <code>$('p.foo')</code> syntax that you see in jQuery and others, but normal variables like <code>$name</code> and <code>$order</code>)</p>
[ { "answer_id": 205974, "author": "cic", "author_id": 4771, "author_profile": "https://Stackoverflow.com/users/4771", "pm_score": 8, "selected": false, "text": "$ _ $ _" }, { "answer_id": 206843, "author": "Benry", "author_id": 28408, "author_profile": "https://Stackoverflow.com/users/28408", "pm_score": 6, "selected": false, "text": "$ var $get = function(id) { return document.getElementById(id); }\n" }, { "answer_id": 553734, "author": "jonstjohn", "author_id": 67009, "author_profile": "https://Stackoverflow.com/users/67009", "pm_score": 12, "selected": true, "text": "var $email = $(\"#email\"); // refers to the jQuery object representation of the dom object\nvar email_field = $(\"#email\").get(0); // refers to the dom object itself\n" }, { "answer_id": 1247605, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "var _ = function() { alert(\"hello from _\"); }\nvar \\u0024 = function() { alert(\"hello from $ defined as u0024\"); }\nvar Ø = function() { alert(\"hello from Ø\"); }\nvar $$$$$ = function() { alert(\"hello from $$$$$\"); }\n" }, { "answer_id": 6769114, "author": "RussellW", "author_id": 321739, "author_profile": "https://Stackoverflow.com/users/321739", "pm_score": -1, "selected": false, "text": "$$('div');\n// -> all DIVs in the document. Same as document.getElementsByTagName('div')!\n\n$$('#contents');\n// -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document).\n\n$$('li.faux');\n// -> all LI elements with class 'faux'\n" }, { "answer_id": 12206716, "author": "Travis Watson", "author_id": 897559, "author_profile": "https://Stackoverflow.com/users/897559", "pm_score": 6, "selected": false, "text": "$ $ $$ $ $$ $ $$" }, { "answer_id": 23457623, "author": "Brett Zamir", "author_id": 271577, "author_profile": "https://Stackoverflow.com/users/271577", "pm_score": 2, "selected": false, "text": "_ $ $J $ $P" }, { "answer_id": 28063827, "author": "Satyabrata Mishra", "author_id": 4477545, "author_profile": "https://Stackoverflow.com/users/4477545", "pm_score": 2, "selected": false, "text": "${varname} {varname} ${varname} {varname} var $blah = $(this).parents('.blahblah');\n $blah" }, { "answer_id": 32416910, "author": "Naga Srinu Kapusetti", "author_id": 1676634, "author_profile": "https://Stackoverflow.com/users/1676634", "pm_score": 2, "selected": false, "text": "Ex:\nvar name = 'jQuery';\nvar lib = {name:'jQuery',version:1.6};\n\nvar $dataDiv = $('#myDataDiv');" }, { "answer_id": 48558883, "author": "Michael Geary", "author_id": 1202830, "author_profile": "https://Stackoverflow.com/users/1202830", "pm_score": 6, "selected": false, "text": "var $email = $(\"#email\"); // refers to the jQuery object representation of the dom object\nvar email_field = $(\"#email\").get(0); // refers to the dom object itself\n $ email email_field $ email_field names_with_underscores field var email = $(\"#email\"), emailElement = $(\"#email\")[0];\n// Now email is a jQuery object and emailElement is the first/only DOM element in it\n id // email is a DOM element passed into this function\nfunction doSomethingWithEmail( email ) {\n var emailJQ = $(email);\n // Now email is the DOM element and emailJQ is a jQuery object for it\n}\n email emailElement email emailJQ email emailElement emailJQ var email = $(\"#email\");\nvar emailJQ = $(email);\n $ $(whatever) $(...) $(\"#email\") $(email) $email\n emailElement emailJQ $(whatever) $whatever var $email = $(\"#email\"), email = $email[0];\n// $email is the jQuery object and email is the DOM object\n // email is a DOM element passed into this function\nfunction doSomethingWithEmail( email ) {\n var $email = $(email);\n // $email is the jQuery object and email is the DOM object\n // Same names as in the code above. Yay!\n}\n $ $ $('#email').click( ... );\n var $email = $('#email');\n// Maybe do some other stuff with $email here\n$email.click( ... );\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20074/" ]
205,871
<p>How can I find out, which keyboard layout the user of my ruby application is using? My aim is to have a game, where you can move the player on a map. To go one step down and one step left you press "Y" on a german keyboard. On an American keyboard, you would press "Z". We optimized the game for windows and mac, so I would like a solution for both platforms (and we don't use any command/shift/control-keys).</p>
[ { "answer_id": 207492, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 1, "selected": true, "text": "ä" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25017/" ]
205,893
<p>Let's have a list of some good interview questions for SharePoint developers. Please provide one question per entry, and if possible, the answers.</p> <p>Also, please feel free to suggest corrections if the provided answers are wrong.</p> <p>I will go first: </p> <p>Q: How does SharePoint store pages?</p> <p>A: <a href="https://stackoverflow.com/questions/125805/how-to-locate-sharepoint-document-library-source-page-on-the-server#127138">How-to-locate-sharepoint-document-library-source-page-on-the-server?</a></p>
[ { "answer_id": 205969, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 4, "selected": false, "text": "System.Web.UI.WebControls.WebParts.WebPart Microsoft.SharePoint.WebPartPages.WebPart Microsoft.SharePoint.WebPartPages.WebPart System.Web.UI.WebControls.WebParts.WebPart" }, { "answer_id": 1363082, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 3, "selected": false, "text": "RunWithElevatedPrivileges RunWithElevatedPrivileges" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
205,911
<p>I had a nasty typo that wasted my time and my colleague's time, it was something like this:</p> <pre><code>for (i = 0; i &lt; blah; i++); // &lt;- I had a semi-colon here, that's the bug! { // Some awesome logic here } </code></pre> <p>First of all, it's very embarrassing, second thing, I should never repeat this. I'm relatively new to C. In Java, I guess I can use <a href="http://findbugs.sourceforge.net/" rel="noreferrer">FindBugs</a> to catch errors like these, what tool should I use for C code? Lint?</p>
[ { "answer_id": 205930, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "/W4 -Wall for" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7205/" ]
205,913
<p>I have a simple event handler with a ItemAdding event that changes a column value that I need in the ItemUpdated method. After uploading a word 2007 document (*.docx, *.pptx or xlsx) the value of the column is changed, but when I protect the document the value of the column disappears in the ItemUpdated method. This only happens for office 2007 documents, other files don't clear the value.</p> <p>The event handler runs in a document library in MOSS 2007.</p> <p>Thanks</p>
[ { "answer_id": 209375, "author": "Esteban Lalinde", "author_id": 28333, "author_profile": "https://Stackoverflow.com/users/28333", "pm_score": 0, "selected": false, "text": "properties.ListItem.Web.ParserEnabled = false;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28333/" ]
205,923
<p>We have a high security application and we want to allow users to enter URLs that other users will see.</p> <p>This introduces a high risk of XSS hacks - a user could potentially enter javascript that another user ends up executing. Since we hold sensitive data it's essential that this never happens.</p> <p>What are the best practices in dealing with this? Is any security whitelist or escape pattern alone good enough? </p> <p>Any advice on dealing with redirections ("this link goes outside our site" message on a warning page before following the link, for instance)</p> <p>Is there an argument for not supporting user entered links at all?</p> <hr> <p>Clarification:</p> <p>Basically our users want to input: </p> <blockquote> <p>stackoverflow.com</p> </blockquote> <p>And have it output to another user:</p> <pre><code>&lt;a href="http://stackoverflow.com"&gt;stackoverflow.com&lt;/a&gt; </code></pre> <p>What I really worry about is them using this in a XSS hack. I.e. they input:</p> <blockquote> <p>alert('hacked!');</p> </blockquote> <p>So other users get this link:</p> <pre><code>&lt;a href="javascript:alert('hacked!');"&gt;stackoverflow.com&lt;/a&gt; </code></pre> <p>My example is just to explain the risk - I'm well aware that javascript and URLs are different things, but by letting them input the latter they may be able to execute the former.</p> <p>You'd be amazed how many sites you can break with this trick - HTML is even worse. If they know to deal with links do they also know to sanitise <code>&lt;iframe&gt;</code>, <code>&lt;img&gt;</code> and clever CSS references?</p> <p>I'm working in a high security environment - a single XSS hack could result in very high losses for us. I'm happy that I could produce a Regex (or use one of the excellent suggestions so far) that could exclude everything that I could think of, but would that be enough?</p>
[ { "answer_id": 205967, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 7, "selected": true, "text": "/// <summary>\n/// returns \"safe\" URL, stripping anything outside normal charsets for URL\n/// </summary>\npublic static string SanitizeUrl(string url)\n{\n return Regex.Replace(url, @\"[^-A-Za-z0-9+&@#/%?=~_|!:,.;\\(\\)]\", \"\");\n}\n" }, { "answer_id": 205968, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 2, "selected": false, "text": "javascript:" }, { "answer_id": 15825812, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 4, "selected": false, "text": "$url = \"http://stackoverflow.com\"; // e.g., $_GET[\"user-homepage\"];\n$esapi = new ESAPI( \"/etc/php5/esapi/ESAPI.xml\" ); // Modified copy of ESAPI.xml\n$sanitizer = ESAPI::getSanitizer();\n$sanitized_url = $sanitizer->getSanitizedURL( \"user-homepage\", $url );\n $url = \"http://stackoverflow.com\"; // e.g., $_GET[\"user-homepage\"];\n$sanitized_url = filter_var($url, FILTER_SANITIZE_URL);\n filter_var http https file:/// telnet://" }, { "answer_id": 52804099, "author": "jcubic", "author_id": 387194, "author_profile": "https://Stackoverflow.com/users/387194", "pm_score": 0, "selected": false, "text": " url.match(/^((https?|ftp):\\/\\/|\\.{0,2}\\/)/)\n" }, { "answer_id": 69307257, "author": "babakansari", "author_id": 3621442, "author_profile": "https://Stackoverflow.com/users/3621442", "pm_score": 0, "selected": false, "text": "AntiXssEncoder.UrlEncode QueryBuilder public sealed class AntiXssUrlEncoder\n {\n public string EncodeUri(Uri uri, bool isEncoded = false)\n {\n // Encode the Query portion of URL to prevent XSS attack if is not already encoded. Otherwise let UriBuilder take care code it.\n var encodedQuery = isEncoded ? uri.Query.TrimStart('?') : AntiXssEncoder.UrlEncode(uri.Query.TrimStart('?'));\n var encodedUri = new UriBuilder\n {\n Scheme = uri.Scheme,\n Host = uri.Host,\n Path = uri.AbsolutePath,\n Query = encodedQuery.Trim(),\n Fragment = uri.Fragment\n };\n if (uri.Port != 80 && uri.Port != 443)\n {\n encodedUri.Port = uri.Port;\n }\n\n return encodedUri.ToString();\n }\n\n public static string Encode(string uri)\n {\n var baseUri = new Uri(uri);\n var antiXssUrlEncoder = new AntiXssUrlEncoder();\n return antiXssUrlEncoder.EncodeUri(baseUri);\n }\n }\n AntiXssEncoder.UrlEncode AntiXssEncoder.EncodeForUrl" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
205,945
<p>Why does the C++ STL not provide any "tree" containers, and what's the best thing to use instead?</p> <p>I want to store a hierarchy of objects as a tree, rather than use a tree as a performance enhancement...</p>
[ { "answer_id": 205985, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 9, "selected": true, "text": "std::map std::multimap std::set std::multiset" }, { "answer_id": 15230597, "author": "bobobobo", "author_id": 111307, "author_profile": "https://Stackoverflow.com/users/111307", "pm_score": 2, "selected": false, "text": "TreeNode TreeNode template <typename T>\nstruct TreeNode\n{\n T* DATA ; // data of type T to be stored at this TreeNode\n\n vector< TreeNode<T>* > children ;\n\n // insertion logic for if an insert is asked of me.\n // may append to children, or may pass off to one of the child nodes\n void insert( T* newData ) ;\n\n} ;\n\ntemplate <typename T>\nstruct Tree\n{\n TreeNode<T>* root;\n\n // TREE LEVEL functions\n void clear() { delete root ; root=0; }\n\n void insert( T* data ) { if(root)root->insert(data); } \n} ;\n" }, { "answer_id": 15473485, "author": "Brent Bradburn", "author_id": 86967, "author_profile": "https://Stackoverflow.com/users/86967", "pm_score": 6, "selected": false, "text": "std::tree template< typename T >\nstruct tree_node\n {\n T t;\n std::vector<tree_node> children;\n };\n template< typename T >\nvoid tree_node<T>::walk_depth_first() const\n {\n cout<<t;\n for ( auto & n: children ) n.walk_depth_first();\n }\n" }, { "answer_id": 43431807, "author": "tjl", "author_id": 4780650, "author_profile": "https://Stackoverflow.com/users/4780650", "pm_score": 3, "selected": false, "text": "template<class A>\nstruct unordered_tree : std::set<unordered_tree>, A\n{};\n\ntemplate<class A>\nstruct b_tree : std::vector<b_tree>, A\n{};\n\ntemplate<class A>\nstruct planar_tree : std::list<planar_tree>, A\n{};\n template<class TREE>\nstruct node_iterator : std::stack<TREE::iterator>{\noperator*() {return *back();}\n...};\n container<B> B" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
205,950
<p>I'm writing SQL (for Oracle) like:</p> <pre> INSERT INTO Schema1.tableA SELECT * FROM Schema2.tableA; </pre> <p>where Schema1.tableA and Schema2.tableA have the same columns. However, it seems like this is unsafe, since the order of the columns coming back in the SELECT is undefined. What I should be doing is:</p> <pre> INSERT INTO Schema1.tableA (col1, col2, ... colN) SELECT (col1, col2, ... colN) FROM Schema2.tableA; </pre> <p>I'm doing this for lots of tables using some scripts, so what I'd like to do is write something like:</p> <pre> INSERT INTO Schema1.tableA (foo(Schema1.tableA)) SELECT (foo(Schema1.tableA)) FROM Schema2.tableA; </pre> <p>Where foo is some nifty magic that extracts the column names from table one and packages them in the appropriate syntax. Thoughts?</p>
[ { "answer_id": 206102, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 4, "selected": true, "text": "declare\n l_cols long;\n l_sql long;\nbegin\n for r in (select column_name from all_tab_columns\n where table_name = 'TABLEA'\n and owner = 'SCHEMA1'\n )\n loop\n l_cols := l_cols || ',' || r.column_name;\n end loop;\n\n -- Remove leading comma\n l_cols := substr(l_cols, 2);\n\n l_sql := 'insert into schema1.tableA (' || l_cols || ') select ' \n || l_cols || ' from schema2.tableA';\n\n execute immediate l_sql;\n\nend;\n/\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25915/" ]
205,975
<p>I have an ASP page which will fetch records from a SQL server DB table. The table "order_master" has a field called order_date. I want to frame a select query to fetch order date > a date entered by user(ex : 07/01/2008)</p> <p>I tried with convert and cast, but both are not working. The sample data in order_date column is 4/10/2008 8:27:41 PM. Actually, I dont know what type it is (varchar/datetime).</p> <p>Is there any way to do that?</p>
[ { "answer_id": 205984, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE GetOrders\n @OrderDate DATETIME\nAS\nSELECT\n *\nFROM order_master\nWHERE Order_Date > @OrderDate\n\nGO\n sp_help order_master\n" }, { "answer_id": 206022, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 1, "selected": false, "text": "SELECT myColumn FROM myTable WHERE myDateField >= convert(datetime, '07/01/2008 00:00:00', 103)" }, { "answer_id": 207879, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 0, "selected": false, "text": "SELECT DATA_TYPE\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME = 'Order_Master' AND\n COLUMN_NAME = 'Order_Date'\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
205,977
<p><a href="https://stackoverflow.com/questions/205887/postback-security">Related Article</a></p> <p>On a similar topic to the above article, but of a more specific note. How exactly do you handle items that are in the viewstate (so they are included on submit), but can also be changed via AJAX. For instance, say we had a dropdown list that was populated through an AJAX web service call (not an update panel). How can I get the page to validate once the dropdownlist's items have been changed?</p>
[ { "answer_id": 206503, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 3, "selected": true, "text": "myAjaxDropDown <asp:RequiredFieldValidator id=\"dropdownRequiredFieldValidator\"\n ControlToValidate=\"myAjaxDropDown\"\n Display=\"Static\"\n InitialValue=\"\" runat=server>\n *\n </asp:RequiredFieldValidator>\n <asp:CustomValidator ID=\"myCustomValidator\" runat=\"server\" \n onservervalidate=\"myCustomValidator_ServerValidate\" \n ErrorMessage=\"Bad Value\" />\n SumbitButton protected void myCustomValidator_ServerValidate(object source, ServerValidateEventArgs e)\n{\n // determine validity for this custom validator\n e.IsValid = DropdownValueInRange(myAjaxDropDown.SelectedItem.Value); \n}\n\nprotected void SubmitButton_Click( object source, EventArgs e )\n{\n Validate(); \n if( !IsValid )\n return;\n\n // validators pass. Continue processing.\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8873/" ]
205,986
<p>I'm using the following syntax to loop through a list collection:</p> <pre><code>For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors i = IndexOf(PropertyActor) Next </code></pre> <p>How do I get the index of the current object within the loop? I'm using IndexOf(PropertyActor) but this seems inefficient as it searches the collection when I already have the object available!</p>
[ { "answer_id": 205994, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 2, "selected": false, "text": "Dim i as Integer \nFor Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors\n i++\nNext\n" }, { "answer_id": 206000, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "i = 0\nFor Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors\n ...\n i = i + 1\nNext\n for i, x in enumerate(a):\n print \"object at index \", i, \" is \", x\n" }, { "answer_id": 206007, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "foreach for (int i=0;i<MyProperty.PropertyActors.Length;i++)\n{\n //...\n}\n" }, { "answer_id": 206069, "author": "John Chuckran", "author_id": 25511, "author_profile": "https://Stackoverflow.com/users/25511", "pm_score": 1, "selected": false, "text": "MyProperty.PropertyActors.FindIndex(Function(propActor As JCPropertyActor) propActor = JCPropertyActor)\n Dim PropertyActor As JCPropertyActor\nFor i As Integer = 0 To MyProperty.PropertyActors.Count - 1\n PropertyActor = MyProperty.PropertyActors.Item(i)\nNext\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20048/" ]
206,009
<p>I have SQL data that looks like this:</p> <pre><code>events id name capacity 1 Cooking 10 2 Swimming 20 3 Archery 15 registrants id name 1 Jimmy 2 Billy 3 Sally registrant_event registrant_id event_id 1 3 2 3 3 2 </code></pre> <p>I would like to select all of the fields in 'events' as well as an additional field that is the number of people who are currently registered for that event. In this case Archery would have 2 registrants, Swimming would have 1, and Cooking would have 0.</p> <p>I imagine this could be accomplished in a single query but I'm not sure of the correct syntax. <strong>How would a query be written to get that data?</strong></p>
[ { "answer_id": 206017, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 5, "selected": true, "text": "SELECT e.*, ISNULL(ec.TotalRegistrants, 0) FROM events e LEFT OUTER JOIN\n(\n SELECT event_id, Count(registrant_id) AS TotalRegistrants\n FROM registrant_event\n GROUP BY event_id\n) ec ON e.id = ec.event_id\n" }, { "answer_id": 206028, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "SELECT Events.ID, Events.Name, Events.Capacity, \n ISNULL(COUNT(Registrant_Event.Registrant_ID), 0)\nFROM Events\nLEFT OUTER JOIN Registrant_Event ON Events.ID = Registrant_Event.Event_ID\nGROUP BY Events.ID, Events.Name, Events.Capacity\n" }, { "answer_id": 206029, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 0, "selected": false, "text": "select e.id, e.name, e.capacity, IsNull(re.eventCount,0) from events e\nleft join (\n select count(event_id) as eventCount, event_id from registrant_event group by event_id\n ) re \non e.id = re.event_id" }, { "answer_id": 206030, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": -1, "selected": false, "text": "SELECT\n events.*\n, COUNT(registrant_event.registrant_id) AS registrantsCount\nFROM events\nLEFT JOIN registrant_event ON events.id = registrant_event.event_id\nGROUP BY events.id\n" }, { "answer_id": 206033, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "SELECT e.id, count(*) AS NumRegistrants\nFROM events e\nLEFT JOIN registrant_event re ON re.event_id=e.id\nGROUP BY e.id\n SELECT *,\n (SELECT COUNT(*) FROM registrant_event WHERE event_id=id) AS NumRegistrants\nFROM events\n" }, { "answer_id": 206090, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 0, "selected": false, "text": "SELECT e.id, e.name, e.capacity, COUNT(re.event_id)\nFROM events e\nLEFT JOIN registrant_event re\n ON e.id = re.event_id\nGROUP BY e.id, e.name, e.capacity\n" }, { "answer_id": 5074928, "author": "majesty", "author_id": 627836, "author_profile": "https://Stackoverflow.com/users/627836", "pm_score": 1, "selected": false, "text": "select d.id1, d.name, d.cappacity, count(d.b_id) as number_of_people\nfrom (select eve.id1,eve.name,eve.cappacity,re_eve.b_id\n from eve left join re_eve on eve.id1 = re_eve.b_id) d\ngroup by d.id1, d.name, d.cappacity\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3238/" ]
206,024
<p>I have an ASP.Net 2.0 page that contains two UpdatePanels. The first panel contains a TreeView. The second panel contains a label and is triggered by a selection in the tree. When I select a node the label gets updated as expected and the <code>TreeNode</code> that I clicked on becomes highlighted and the previously selected node is no longer highlighted. However if a node is original highlighted(selected) in the code-behind the highlight is not removed when selecting another node.</p> <p>The markup</p> <pre><code>&lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional"&gt; &lt;ContentTemplate&gt; &lt;asp:TreeView ID="TreeView1" runat="server" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged"&gt; &lt;SelectedNodeStyle BackColor="Pink" /&gt; &lt;/asp:TreeView&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="True"&gt; &lt;ContentTemplate&gt; &lt;asp:Label ID="Label1" runat="server" Text=" - "&gt;&lt;/asp:Label&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="SelectedNodeChanged" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p>The code behind</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { TreeView1.Nodes.Add(new TreeNode("Test 1", "Test One")); TreeView1.Nodes.Add(new TreeNode("Test 2", "Test Two")); TreeView1.Nodes.Add(new TreeNode("Test 3", "Test Three")); TreeView1.Nodes.Add(new TreeNode("Test 4", "Test Four")); TreeView1.Nodes[0].Selected = true; } } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { Label1.Text = TreeView1.SelectedValue; } </code></pre> <p>The at the start the first node is selected. Why is its highlight not removed when selecting another node?</p> <p>Also, I asked a different <a href="https://stackoverflow.com/questions/205114/why-is-my-asptreeview-selected-node-reset-when-in-an-updatepanel">question about the same setup</a> that I haven't got an answer for. Any help would appreciated. </p> <p><strong>Edit</strong> I know that setting <code>ChildrenAsTriggers="false"</code> will work but I want to avoid rendering the tree again as it can be very large.</p>
[ { "answer_id": 207382, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 1, "selected": false, "text": "public void RefreshSelection(string guid)\n{\n if (guid == string.Empty)\n ClearNodes(tvCategories.Nodes);\n else\n SelectNode(guid, tvCategories.Nodes);\n\n}\n\nprivate void ClearNodes(TreeNodeCollection tnc)\n{\n foreach (TreeNode n in tnc)\n {\n n.Selected = false;\n ClearNodes(n.ChildNodes);\n }\n}\nprivate bool SelectNode(string guid, TreeNodeCollection tnc)\n{\n foreach (TreeNode n in tnc)\n {\n if (n.Value == guid)\n {\n n.Selected = true;\n return true;\n }\n else\n {\n SelectNode(guid, n.ChildNodes);\n }\n }\n\n return false;\n}\n" }, { "answer_id": 208013, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 1, "selected": true, "text": "Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function BeginRequestHandler(sender, args)\n {\n var elem = args.get_postBackElement();\n var selectedClassName = elem.id + '_1';\n\n var arrAllElements = GetElementsByClassName(selectedClassName, elem);\n var selectedNode = $get(elem.id + '_SelectedNode').value;\n\n for(var i = 0; i < arrAllElements.length; i++)\n {\n if(arrAllElements[i].childNodes[0].id != selectedNode)\n RemoveClassName(arrAllElements[i], selectedClassName );\n }\n }\n);\n GetElementsByClassName RemoveClassName" }, { "answer_id": 4544137, "author": "Newborn", "author_id": 555702, "author_profile": "https://Stackoverflow.com/users/555702", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// Remove selection from TreeView\n /// </summary>\n /// <param name=\"tree\"></param>\n public static void ClearTreeView(TreeView tree)\n {\n\n if (tree.SelectedNode != null)\n {\n tree.SelectedNode.Selected = false;\n }\n }\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
206,045
<p>I have code like this:</p> <pre><code>template &lt;typename T, typename U&gt; struct MyStruct { T aType; U anotherType; }; class IWantToBeFriendsWithMyStruct { friend struct MyStruct; //what is the correct syntax here ? }; </code></pre> <p>What is the correct syntax to give friendship to the template ?</p>
[ { "answer_id": 206054, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": true, "text": "class IWantToBeFriendsWithMyStruct\n{\n template <typename T, typename U>\n friend struct MyStruct;\n};\n" }, { "answer_id": 206073, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 3, "selected": false, "text": "class IWantToBeFriendsWithMyStruct\n{\n template <typename T, typename U> friend struct MyStruct; \n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28275/" ]
206,055
<p>I am a SQL Server user .</p> <p>I am on a project that is using oracle (which I rarely use) I need to create an ODBC connection so I can access the some data via MS Access I have a application on my machine called oraHome90. It seems to allow a configuration of something called a listener in a “net configuration utility”, I think that a “Local Net Service Name Configuration” needs to also be done. The IT support gave me this information to set up the ODBC connection . I have tried every combination that I can think of. I can get past a test that successfully passes a test to “login“ to the oracle server database. When I try to create the ODBC connection I get the following error: ORA-12154: TNS: Could not resolve service name.</p> <p>Assuming that I want to start from scratch and the following information is supposed to allow for me to connect to the database….. Any suggestions or comment ? Note: ultimately the project will have a website .ASP page query the data, but I have to first prove that I can see the data using the ODBC connection via MS Access</p> <pre><code>Service name: SERVICENAME HOST = HOST.XYZi.com User Id: MYUSERID Password: MYPASSWORD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'Oracle Connection Dim ocst Dim oconn ocst = "Provider=OraOLEDB.Oracle;" &amp; _ "Data Source=DATASOURCE;" &amp; _ "User ID=CHIJXL;" &amp; _ "Password=password;" set oconn = CreateObject("ADODB.Connection") </code></pre>
[ { "answer_id": 206883, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 3, "selected": false, "text": "> SERVICENAME_alias =\n> (DESCRIPTION =\n> (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.XYZi.com)(PORT = 1521))\n> (CONNECT_DATA = (SERVICE_NAME = SERVICENAME))\n" }, { "answer_id": 206930, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 2, "selected": false, "text": "tnsping" }, { "answer_id": 8818766, "author": "Sertan", "author_id": 1143102, "author_profile": "https://Stackoverflow.com/users/1143102", "pm_score": 2, "selected": false, "text": "tnsnames.ora" }, { "answer_id": 32123008, "author": "stantont", "author_id": 28810, "author_profile": "https://Stackoverflow.com/users/28810", "pm_score": 1, "selected": false, "text": "$ chmod +r tnsnames.ora\n" }, { "answer_id": 33007863, "author": "Jeremy Thompson", "author_id": 495455, "author_profile": "https://Stackoverflow.com/users/495455", "pm_score": 2, "selected": false, "text": "rem Progra~2 is short path name for \"Program Files (x86)\" and works around an Oracle client bug that doesn't like the ()'s in the path\nstart /B \"C:\\Progra~2\\Microsoft Visual Studio 9.0\\Common7\\IDE\" \"C:\\Progra~2\\Microsoft Visual Studio 9.0\\Common7\\IDE\\devenv.exe\"\n mklink /J \"C:\\Program Files (x86)\\\" \"C:\\Program Files x86\\\"\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26883/" ]
206,059
<p>I've been looking for a simple regex for URLs, does anybody have one handy that works well? I didn't find one with the zend framework validation classes and have seen several implementations.</p>
[ { "answer_id": 206087, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 7, "selected": true, "text": "$text = preg_replace(\n '#((https?|ftp)://(\\S*?\\.\\S*?))([\\s)\\[\\]{},;\"\\':<]|\\.\\s|$)#i',\n \"'<a href=\\\"$1\\\" target=\\\"_blank\\\">$3</a>$4'\",\n $text\n);\n http://domain.example." }, { "answer_id": 206107, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "$pattern = \"/\\b(?:(?:https?|ftp):\\/\\/|www\\.)[-a-z0-9+&@#\\/%?=~_|!:,.;]*[-a-z0-9+&@#\\/%=~_|]/i\";\n" }, { "answer_id": 207627, "author": "Stanislav", "author_id": 21504, "author_profile": "https://Stackoverflow.com/users/21504", "pm_score": 8, "selected": false, "text": "filter_var() var_dump(filter_var('example.com', FILTER_VALIDATE_URL));\n" }, { "answer_id": 395032, "author": "catchdave", "author_id": 49366, "author_profile": "https://Stackoverflow.com/users/49366", "pm_score": 5, "selected": false, "text": "filter_var('example.com', FILTER_VALIDATE_URL) parse_url() filter_var() http://..." }, { "answer_id": 639598, "author": "Frankie", "author_id": 67945, "author_profile": "https://Stackoverflow.com/users/67945", "pm_score": 3, "selected": false, "text": "// Checks if string is a URL\n// @param string $url\n// @return bool\nfunction isURL($url = NULL) {\n if($url==NULL) return false;\n\n $protocol = '(http://|https://)';\n $allowed = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';\n\n $regex = \"^\". $protocol . // must include the protocol\n '(' . $allowed . '{1,63}\\.)+'. // 1 or several sub domains with a max of 63 chars\n '[a-z]' . '{2,6}'; // followed by a TLD\n if(eregi($regex, $url)==true) return true;\n else return false;\n}\n" }, { "answer_id": 929053, "author": "joedevon", "author_id": 110337, "author_profile": "https://Stackoverflow.com/users/110337", "pm_score": 0, "selected": false, "text": "^(http://|https://)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\\.)+[a-z]{2,6}\n (\\S*?\\.\\S*?)\n [a-z0-9]\n" }, { "answer_id": 4969311, "author": "Roger", "author_id": 559742, "author_profile": "https://Stackoverflow.com/users/559742", "pm_score": 4, "selected": false, "text": "function url_exist($url){//se passar a URL existe\n $c=curl_init();\n curl_setopt($c,CURLOPT_URL,$url);\n curl_setopt($c,CURLOPT_HEADER,1);//get the header\n curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header\n curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it\n curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url\n if(!curl_exec($c)){\n //echo $url.' inexists';\n return false;\n }else{\n //echo $url.' exists';\n return true;\n }\n //$httpcode=curl_getinfo($c,CURLINFO_HTTP_CODE);\n //return ($httpcode<400);\n}\n" }, { "answer_id": 5289151, "author": "abhiomkar", "author_id": 235453, "author_profile": "https://Stackoverflow.com/users/235453", "pm_score": 4, "selected": false, "text": "(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\\\".,<>?«»“”‘’]))\n preg_match(\"/(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\\\".,<>?«»“”‘’]))/\", $url)\n (?xi)\n\\b\n( # Capture 1: entire matched URL\n (?:\n https?:// # http or https protocol\n | # or\n www\\d{0,3}[.] # \"www.\", \"www1.\", \"www2.\" … \"www999.\"\n | # or\n [a-z0-9.\\-]+[.][a-z]{2,4}/ # looks like domain name followed by a slash\n )\n (?: # One or more:\n [^\\s()<>]+ # Run of non-space, non-()<>\n | # or\n \\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\) # balanced parens, up to 2 levels\n )+\n (?: # End with:\n \\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\) # balanced parens, up to 2 levels\n | # or\n [^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’] # not a space or one of these punct chars\n )\n)\n" }, { "answer_id": 5492163, "author": "jini", "author_id": 323698, "author_profile": "https://Stackoverflow.com/users/323698", "pm_score": 2, "selected": false, "text": "function is_valid_url ($url=\"\") {\n\n if ($url==\"\") {\n $url=$this->url;\n }\n\n $url = @parse_url($url);\n\n if ( ! $url) {\n\n\n return false;\n }\n\n $url = array_map('trim', $url);\n $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];\n $path = (isset($url['path'])) ? $url['path'] : '';\n\n if ($path == '') {\n $path = '/';\n }\n\n $path .= ( isset ( $url['query'] ) ) ? \"?$url[query]\" : '';\n\n\n\n if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) ) {\n if ( PHP_VERSION >= 5 ) {\n $headers = get_headers(\"$url[scheme]://$url[host]:$url[port]$path\");\n }\n else {\n $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);\n\n if ( ! $fp ) {\n return false;\n }\n fputs($fp, \"HEAD $path HTTP/1.1\\r\\nHost: $url[host]\\r\\n\\r\\n\");\n $headers = fread ( $fp, 128 );\n fclose ( $fp );\n }\n $headers = ( is_array ( $headers ) ) ? implode ( \"\\n\", $headers ) : $headers;\n return ( bool ) preg_match ( '#^HTTP/.*\\s+[(200|301|302)]+\\s#i', $headers );\n }\n\n return false;\n }\n" }, { "answer_id": 5968861, "author": "promaty", "author_id": 748745, "author_profile": "https://Stackoverflow.com/users/748745", "pm_score": 3, "selected": false, "text": "if (preg_match(\"#^https?://.+#\", $link) and @fopen($link,\"r\")) echo \"OK\";\n preg_match" }, { "answer_id": 11820924, "author": "Jeremy Moore", "author_id": 1522312, "author_profile": "https://Stackoverflow.com/users/1522312", "pm_score": -1, "selected": false, "text": "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$\n" }, { "answer_id": 12910990, "author": "Vikash Kumar", "author_id": 1749440, "author_profile": "https://Stackoverflow.com/users/1749440", "pm_score": 3, "selected": false, "text": " function validateURL($URL) {\n $pattern_1 = \"/^(http|https|ftp):\\/\\/(([A-Z0-9][A-Z0-9_-]*)(\\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\\d+))?\\/?/i\";\n $pattern_2 = \"/^(www)((\\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\\d+))?\\/?/i\"; \n if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){\n return true;\n } else{\n return false;\n }\n }\n" }, { "answer_id": 13756384, "author": "George Milonas", "author_id": 1172788, "author_profile": "https://Stackoverflow.com/users/1172788", "pm_score": 3, "selected": false, "text": "function link_validate_url($text) {\n$LINK_DOMAINS = 'aero|arpa|asia|biz|com|cat|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|mobi|local';\n $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode(\"\", array( // @TODO completing letters ...\n \"&#x00E6;\", // æ\n \"&#x00C6;\", // Æ\n \"&#x00C0;\", // À\n \"&#x00E0;\", // à\n \"&#x00C1;\", // Á\n \"&#x00E1;\", // á\n \"&#x00C2;\", // Â\n \"&#x00E2;\", // â\n \"&#x00E5;\", // å\n \"&#x00C5;\", // Å\n \"&#x00E4;\", // ä\n \"&#x00C4;\", // Ä\n \"&#x00C7;\", // Ç\n \"&#x00E7;\", // ç\n \"&#x00D0;\", // Ð\n \"&#x00F0;\", // ð\n \"&#x00C8;\", // È\n \"&#x00E8;\", // è\n \"&#x00C9;\", // É\n \"&#x00E9;\", // é\n \"&#x00CA;\", // Ê\n \"&#x00EA;\", // ê\n \"&#x00CB;\", // Ë\n \"&#x00EB;\", // ë\n \"&#x00CE;\", // Î\n \"&#x00EE;\", // î\n \"&#x00CF;\", // Ï\n \"&#x00EF;\", // ï\n \"&#x00F8;\", // ø\n \"&#x00D8;\", // Ø\n \"&#x00F6;\", // ö\n \"&#x00D6;\", // Ö\n \"&#x00D4;\", // Ô\n \"&#x00F4;\", // ô\n \"&#x00D5;\", // Õ\n \"&#x00F5;\", // õ\n \"&#x0152;\", // Œ\n \"&#x0153;\", // œ\n \"&#x00FC;\", // ü\n \"&#x00DC;\", // Ü\n \"&#x00D9;\", // Ù\n \"&#x00F9;\", // ù\n \"&#x00DB;\", // Û\n \"&#x00FB;\", // û\n \"&#x0178;\", // Ÿ\n \"&#x00FF;\", // ÿ \n \"&#x00D1;\", // Ñ\n \"&#x00F1;\", // ñ\n \"&#x00FE;\", // þ\n \"&#x00DE;\", // Þ\n \"&#x00FD;\", // ý\n \"&#x00DD;\", // Ý\n \"&#x00BF;\", // ¿\n )), ENT_QUOTES, 'UTF-8');\n\n $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode(\"\", array(\n \"&#x00DF;\", // ß\n )), ENT_QUOTES, 'UTF-8');\n $allowed_protocols = array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal');\n\n // Starting a parenthesis group with (?: means that it is grouped, but is not captured\n $protocol = '((?:'. implode(\"|\", $allowed_protocols) .'):\\/\\/)';\n $authentication = \"(?:(?:(?:[\\w\\.\\-\\+!$&'\\(\\)*\\+,;=\" . $LINK_ICHARS . \"]|%[0-9a-f]{2})+(?::(?:[\\w\". $LINK_ICHARS .\"\\.\\-\\+%!$&'\\(\\)*\\+,;=]|%[0-9a-f]{2})*)?)?@)\";\n $domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9'. $LINK_ICHARS_DOMAIN . '\\-_\\[\\]])*)(\\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\\-_\\[\\]])+\\.)*('. $LINK_DOMAINS .'|[a-z]{2}))?)';\n $ipv4 = '(?:[0-9]{1,3}(\\.[0-9]{1,3}){3})';\n $ipv6 = '(?:[0-9a-fA-F]{1,4}(\\:[0-9a-fA-F]{1,4}){7})';\n $port = '(?::([0-9]{1,5}))';\n\n // Pattern specific to external links.\n $external_pattern = '/^'. $protocol .'?'. $authentication .'?('. $domain .'|'. $ipv4 .'|'. $ipv6 .' |localhost)'. $port .'?';\n\n // Pattern specific to internal links.\n $internal_pattern = \"/^(?:[a-z0-9\". $LINK_ICHARS .\"_\\-+\\[\\]]+)\";\n $internal_pattern_file = \"/^(?:[a-z0-9\". $LINK_ICHARS .\"_\\-+\\[\\]\\.]+)$/i\";\n\n $directories = \"(?:\\/[a-z0-9\". $LINK_ICHARS .\"_\\-\\.~+%=&,$'#!():;*@\\[\\]]*)*\";\n // Yes, four backslashes == a single backslash.\n $query = \"(?:\\/?\\?([?a-z0-9\". $LINK_ICHARS .\"+_|\\-\\.~\\/\\\\\\\\%=&,$'():;*@\\[\\]{} ]*))\";\n $anchor = \"(?:#[a-z0-9\". $LINK_ICHARS .\"_\\-\\.~+%=&,$'():;*@\\[\\]\\/\\?]*)\";\n\n // The rest of the path for a standard URL.\n $end = $directories .'?'. $query .'?'. $anchor .'?'.'$/i';\n\n $message_id = '[^@].*@'. $domain;\n $newsgroup_name = '(?:[0-9a-z+-]*\\.)*[0-9a-z+-]*';\n $news_pattern = '/^news:('. $newsgroup_name .'|'. $message_id .')$/i';\n\n $user = '[a-zA-Z0-9'. $LINK_ICHARS .'_\\-\\.\\+\\^!#\\$%&*+\\/\\=\\?\\`\\|\\{\\}~\\'\\[\\]]+';\n $email_pattern = '/^mailto:'. $user .'@'.'(?:'. $domain .'|'. $ipv4 .'|'. $ipv6 .'|localhost)'. $query .'?$/';\n\n if (strpos($text, '<front>') === 0) {\n return false;\n }\n if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {\n return false;\n }\n if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {\n return false;\n }\n if (preg_match($internal_pattern . $end, $text)) {\n return false;\n }\n if (preg_match($external_pattern . $end, $text)) {\n return false;\n }\n if (preg_match($internal_pattern_file, $text)) {\n return false;\n }\n\n return true;\n}\n" }, { "answer_id": 21872143, "author": "Tim Groeneveld", "author_id": 2143004, "author_profile": "https://Stackoverflow.com/users/2143004", "pm_score": 1, "selected": false, "text": "function is_valid_url($url) {\n // First check: is the url just a domain name? (allow a slash at the end)\n $_domain_regex = \"|^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})/?$|\";\n if (preg_match($_domain_regex, $url)) {\n return true;\n }\n\n // Second: Check if it's a url with a scheme and all\n $_regex = '#^([a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))$#';\n if (preg_match($_regex, $url, $matches)) {\n // pull out the domain name, and make sure that the domain is valid.\n $_parts = parse_url($url);\n if (!in_array($_parts['scheme'], array( 'http', 'https' )))\n return false;\n\n // Check the domain using the regex, stops domains like \"-example.com\" passing through\n if (!preg_match($_domain_regex, $_parts['host']))\n return false;\n\n // This domain looks pretty valid. Only way to check it now is to download it!\n return true;\n }\n\n return false;\n}\n var_dump(is_valid_url('google.com')); // true\nvar_dump(is_valid_url('google.com/')); // true\nvar_dump(is_valid_url('http://google.com')); // true\nvar_dump(is_valid_url('http://google.com/')); // true\nvar_dump(is_valid_url('https://google.com')); // true\n" }, { "answer_id": 25422556, "author": "Thomas Venturini", "author_id": 1401296, "author_profile": "https://Stackoverflow.com/users/1401296", "pm_score": 0, "selected": false, "text": "$pattern = \"#((http|https)://(\\S*?\\.\\S*?))(\\s|\\;|\\)|\\]|\\[|\\{|\\}|,|”|\\\"|'|:|\\<|$|\\.\\s)#i\";\n $text = preg_replace_callback($pattern,function($m){\n return \"<a href=\\\"$m[1]\\\" target=\\\"_blank\\\">$m[1]</a>$m[4]\";\n },\n $text);\n" }, { "answer_id": 30238322, "author": "Fredmat", "author_id": 1466704, "author_profile": "https://Stackoverflow.com/users/1466704", "pm_score": -1, "selected": false, "text": "$url = 'http://www.yoururl.co.uk/sub1/sub2/?param=1&param2/';\n\nif ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {\n // Wrong\n}\nelse {\n // Valid\n}\n" }, { "answer_id": 41132408, "author": "Xavi Montero", "author_id": 1315009, "author_profile": "https://Stackoverflow.com/users/1315009", "pm_score": 2, "selected": false, "text": "if( ! preg_match( \"/^([a-z][a-z0-9+.-]*):(?:\\\\/\\\\/((?:(?=((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*))(\\\\3)@)?(?=(\\\\[[0-9A-F:.]{2,}\\\\]|(?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*))\\\\5(?::(?=(\\\\d*))\\\\6)?)(\\\\/(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\8)?|(\\\\/?(?!\\\\/)(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\10)?)(?:\\\\?(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\11)?(?:#(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\12)?$/i\", $uri ) )\n{\n throw new \\RuntimeException( \"URI has not a valid format.\" );\n}\n Uri UriTest <?php\n\ndeclare( strict_types = 1 );\n\nnamespace XaviMontero\\ThrasherPortage\\Tests\\Tour;\n\nuse XaviMontero\\ThrasherPortage\\Tour\\Uri;\n\nclass UriTest extends \\PHPUnit_Framework_TestCase\n{\n private $sut;\n\n public function testCreationIsOfProperClassWhenUriIsValid()\n {\n $sut = new Uri( 'http://example.com' );\n $this->assertInstanceOf( 'XaviMontero\\\\ThrasherPortage\\\\Tour\\\\Uri', $sut );\n }\n\n /**\n * @dataProvider urlIsValidProvider\n * @dataProvider urnIsValidProvider\n */\n public function testGetUriAsStringWhenUriIsValid( string $uri )\n {\n $sut = new Uri( $uri );\n $actual = $sut->getUriAsString();\n\n $this->assertInternalType( 'string', $actual );\n $this->assertEquals( $uri, $actual );\n }\n\n public function urlIsValidProvider()\n {\n return\n [\n [ 'http://example-server' ],\n [ 'http://example.com' ],\n [ 'http://example.com/' ],\n [ 'http://subdomain.example.com/path/?parameter1=value1&parameter2=value2' ],\n [ 'random-protocol://example.com' ],\n [ 'http://example.com:80' ],\n [ 'http://example.com?no-path-separator' ],\n [ 'http://example.com/pa%20th/' ],\n [ 'ftp://example.org/resource.txt' ],\n [ 'file://../../../relative/path/needs/protocol/resource.txt' ],\n [ 'http://example.com/#one-fragment' ],\n [ 'http://example.edu:8080#one-fragment' ],\n ];\n }\n\n public function urnIsValidProvider()\n {\n return\n [\n [ 'urn:isbn:0-486-27557-4' ],\n [ 'urn:example:mammal:monotreme:echidna' ],\n [ 'urn:mpeg:mpeg7:schema:2001' ],\n [ 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66' ],\n [ 'rare-urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66' ],\n [ 'urn:FOO:a123,456' ]\n ];\n }\n\n /**\n * @dataProvider urlIsNotValidProvider\n * @dataProvider urnIsNotValidProvider\n */\n public function testCreationThrowsExceptionWhenUriIsNotValid( string $uri )\n {\n $this->expectException( 'RuntimeException' );\n $this->sut = new Uri( $uri );\n }\n\n public function urlIsNotValidProvider()\n {\n return\n [\n [ 'only-text' ],\n [ 'http//missing.colon.example.com/path/?parameter1=value1&parameter2=value2' ],\n [ 'missing.protocol.example.com/path/' ],\n [ 'http://example.com\\\\bad-separator' ],\n [ 'http://example.com|bad-separator' ],\n [ 'ht tp://example.com' ],\n [ 'http://exampl e.com' ],\n [ 'http://example.com/pa th/' ],\n [ '../../../relative/path/needs/protocol/resource.txt' ],\n [ 'http://example.com/#two-fragments#not-allowed' ],\n [ 'http://example.edu:portMustBeANumber#one-fragment' ],\n ];\n }\n\n public function urnIsNotValidProvider()\n {\n return\n [\n [ 'urn:mpeg:mpeg7:sch ema:2001' ],\n [ 'urn|mpeg:mpeg7:schema:2001' ],\n [ 'urn?mpeg:mpeg7:schema:2001' ],\n [ 'urn%mpeg:mpeg7:schema:2001' ],\n [ 'urn#mpeg:mpeg7:schema:2001' ],\n ];\n }\n}\n <?php\n\ndeclare( strict_types = 1 );\n\nnamespace XaviMontero\\ThrasherPortage\\Tour;\n\nclass Uri\n{\n /** @var string */\n private $uri;\n\n public function __construct( string $uri )\n {\n $this->assertUriIsCorrect( $uri );\n $this->uri = $uri;\n }\n\n public function getUriAsString()\n {\n return $this->uri;\n }\n\n private function assertUriIsCorrect( string $uri )\n {\n // https://stackoverflow.com/questions/30847/regex-to-validate-uris\n // http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/\n\n if( ! preg_match( \"/^([a-z][a-z0-9+.-]*):(?:\\\\/\\\\/((?:(?=((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*))(\\\\3)@)?(?=(\\\\[[0-9A-F:.]{2,}\\\\]|(?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*))\\\\5(?::(?=(\\\\d*))\\\\6)?)(\\\\/(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\8)?|(\\\\/?(?!\\\\/)(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/]|%[0-9A-F]{2})*))\\\\10)?)(?:\\\\?(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\11)?(?:#(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\\\/?]|%[0-9A-F]{2})*))\\\\12)?$/i\", $uri ) )\n {\n throw new \\RuntimeException( \"URI has not a valid format.\" );\n }\n }\n}\n xavi@bromo:~/custom_www/hello-trip/mutant-migrant$ vendor/bin/phpunit\nPHPUnit 5.7.3 by Sebastian Bergmann and contributors.\n\n.............................................. 46 / 46 (100%)\n\nTime: 82 ms, Memory: 4.00MB\n\nOK (46 tests, 65 assertions)\n" }, { "answer_id": 42117926, "author": "Kitson88", "author_id": 6574422, "author_profile": "https://Stackoverflow.com/users/6574422", "pm_score": 0, "selected": false, "text": "require 'URLValidation.php';\n require 'URLValidation.php';\n$urlVal = new UrlValidation(); //Create Object Instance\n domain() $urlArray = ['http://www.bokranzr.com/test.php?test=foo&test=dfdf', 'https://en-gb.facebook.com', 'https://www.google.com'];\nforeach ($urlArray as $k=>$v) {\n\n echo var_dump($urlVal->domain($v)) . ' URL: ' . $v . '<br>';\n\n}\n bool(false) URL: http://www.bokranzr.com/test.php?test=foo&test=dfdf\nbool(true) URL: https://en-gb.facebook.com\nbool(true) URL: https://www.google.com\n" }, { "answer_id": 51441301, "author": "Some_North_korea_kid", "author_id": 9994228, "author_profile": "https://Stackoverflow.com/users/9994228", "pm_score": 2, "selected": false, "text": "\"/(http(s?):\\/\\/)([a-z0-9\\-]+\\.)+[a-z]{2,4}(\\.[a-z]{2,4})*(\\/[^ ]+)*/i\"\n 2.1 (+) means the character can be one or more ex: a1w, \n a9-,c559s, f)\n\n 2.2 \\. is (.)sign\n\n 2.3. the (+) sign after ([a-z0-9\\-]+\\.) mean do 2.1,2.2,2.3 \n at least 1 time \n ex: abc.defgh0.ig, aa.b.ced.f.gh. also in case www.yyy.com\n\n 3.[a-z]{2,4} mean a-z at least 2 character but not more than \n 4 characters for check that there will not be \n the case \n ex: https://www.google.co.kr.asdsdagfsdfsf\n\n 4.(\\.[a-z]{2,4})*(\\/[^ ]+)* mean \n\n 4.1 \\.[a-z]{2,4} means like number 3 but start with \n (.)sign \n\n 4.2 * means (\\.[a-z]{2,4})can be use or not use never mind\n\n 4.3 \\/ means \\\n 4.4 [^ ] means any character except blank\n 4.5 (+) means do 4.3,4.4,4.5 at least 1 times\n 4.6 (*) after (\\/[^ ]+) mean use 4.3 - 4.5 or not use \n no problem\n\n use for case https://stackoverflow.com/posts/51441301/edit\n\n 5. when you use regex write in \"/ /\" so it come\n 6. almost forgot: letter i on the back mean ignore case of \n Big letter or small letter ex: A same as a, SoRRy same \n as sorry.\n" }, { "answer_id": 52120682, "author": "thespacecamel", "author_id": 1493883, "author_profile": "https://Stackoverflow.com/users/1493883", "pm_score": 1, "selected": false, "text": "esc_url_raw($url) === $url\n esc_url_raw filter_var($url, FILTER_VALIDATE_URL) filter_var" }, { "answer_id": 56791522, "author": "Fred Vanelli", "author_id": 3335893, "author_profile": "https://Stackoverflow.com/users/3335893", "pm_score": 3, "selected": false, "text": "function valid_URL($url){\n return preg_match('%^(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@|\\d{1,3}(?:\\.\\d{1,3}){3}|(?:(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)(?:\\.(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)*(?:\\.[a-z\\x{00a1}-\\x{ffff}]{2,6}))(?::\\d+)?(?:[^\\s]*)?$%iu', $url);\n}\n valid_URL('https://twitter.com'); // true\nvalid_URL('http://twitter.com'); // true\nvalid_URL('http://twitter.co'); // true\nvalid_URL('http://t.co'); // true\nvalid_URL('http://twitter.c'); // false\nvalid_URL('htt://twitter.com'); // false\n\nvalid_URL('http://example.com/?a=1&b=2&c=3'); // true\nvalid_URL('http://127.0.0.1'); // true\nvalid_URL(''); // false\nvalid_URL(1); // false\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26577/" ]
206,062
<p>In MySQL 5.0 why does the following error occur when trying to create a view with a subquery in the FROM clause?</p> <blockquote> <p>ERROR 1349 (HY000): View's SELECT contains a subquery in the FROM clause</p> </blockquote> <p>If this is a limitation of the MySQL engine, then why haven't they implemented this feature yet?</p> <p>Also, what are some good workarounds for this limitation?</p> <p>Are there any workarounds that work for any subquery in the FROM clause or are there some queries that can not be expressed without using a subquery in the FROM clause?</p> <hr> <p>An example query (was buried in a comment):</p> <pre><code>SELECT temp.UserName FROM (SELECT u1.name as UserName, COUNT(m1.UserFromId) as SentCount FROM Message m1, User u1 WHERE u1.uid = m1.UserFromId Group BY u1.name HAVING SentCount &gt; 3 ) as temp </code></pre>
[ { "answer_id": 206118, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 3, "selected": false, "text": "SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)\n SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID\n SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)\n SELECT FOO.* FROM FOO \nLEFT OUTER JOIN FOO2 \nON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL\n" }, { "answer_id": 206164, "author": "Grant Limberg", "author_id": 27314, "author_profile": "https://Stackoverflow.com/users/27314", "pm_score": 5, "selected": true, "text": "SELECT u1.name as UserName from Message m1, User u1 \n WHERE u1.uid = m1.UserFromID GROUP BY u1.name HAVING count(m1.UserFromId)>3\n" }, { "answer_id": 3520552, "author": "Json on Linux Apache MySQL", "author_id": 425039, "author_profile": "https://Stackoverflow.com/users/425039", "pm_score": 6, "selected": false, "text": "SELECT a.* \nFROM a \nJOIN ( \n SELECT a.alias, MAX(a.year) as max_year \n FROM a \n GROUP BY a.alias\n) b \nON a.alias=b.alias and a.year=b.max_year\n CREATE VIEW v_max_year AS \n SELECT alias, MAX(year) as max_year \n FROM a \n GROUP BY a.alias;\n\nCREATE VIEW v_latest_info AS \n SELECT a.* \n FROM a \n JOIN v_max_year b \n ON a.alias=b.alias and a.year=b.max_year;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8784/" ]
206,092
<p>I need to let end users specify a time range, to be stored and used internally as a starting date/time and ending date/time. The range could be minutes or it could be days.</p> <p><strong>Has anyone discovered an interactive control that can handle this elegantly?</strong></p> <p>Most GUI toolkits have a calendar control, so I could specify "start" with a calendar for the day and a text field for the time...and the same for "end".</p> <p>I could also replace the "end" controls with a single text field or slider that simply describes how many seconds/minutes/hours after start "end" is.</p> <p>What I don't like about these ideas is how much clicking, typing, and more clicking is required to describe such a simple concept. Also I have to slap the user's hand if a time is typed in that isn't recognizable as a time.</p> <p>Is there a cleaner implementation that I'm overlooking?</p>
[ { "answer_id": 227741, "author": "Roark Fan", "author_id": 25362, "author_profile": "https://Stackoverflow.com/users/25362", "pm_score": 2, "selected": false, "text": "[20 Oct | 21 OCT | 22 Oct ] [11:15 .. 11:30 .. 11:45..]\n [20 Oct | 21 OCT | 22 Oct ] [11 .. 12 .. 1pm] [12:31 .. 12:32 .. 12:33]\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16287/" ]
206,094
<p>I've been working through a recent Computer Science homework involving recursion and big-O notation. I believe I understand this pretty well (certainly not perfectly, though!) But there is one question in particular that is giving me the most problems. The odd thing is that by looking it, it looks to be the most simple one on the homework.</p> <p>Provide the best rate of growth using the big-Oh notation for the solution to the following recurrence?</p> <p>T(1) = 2</p> <p>T(n) = 2T(n - 1) + 1 for n>1 </p> <p>And the choices are:</p> <ul> <li>O(n log n)</li> <li>O(n^2)</li> <li>O(2^n)</li> <li>O(n^n)</li> </ul> <p>I understand that big O works as an upper bound, to describe the most amount of calculations, or the highest running time, that program or process will take. I feel like this particular recursion should be O(n), since, at most, the recursion only occurs once for each value of n. Since n isn't available, it's either better than that, O(nlogn), or worse, being the other three options.</p> <p>So, my question is: Why isn't this O(n)?</p>
[ { "answer_id": 206110, "author": "Roman Plášil", "author_id": 16590, "author_profile": "https://Stackoverflow.com/users/16590", "pm_score": 2, "selected": false, "text": "T(2) = 2 * T(1) = 4\nT(3) = 2 * T(2) = 2 * 4\n...\n def fn(x):\n if (x == 1):\n return # a constant time\n # do the calculation for n - 1 twice\n fn(x - 1)\n fn(x - 1)\n" }, { "answer_id": 206129, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": " 1 -> 2\n 2 -> 5\n 3 -> 11\n 4 -> 23\n 5 -> 47\n" }, { "answer_id": 206687, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "int T( int N )\n{\n if (N == 1) return 2;\n return( 2*T(N-1) + 1);\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23323/" ]
206,096
<p>I'm stuck in .NET 2.0 Windows Forms.</p> <p>It doesn't look like the ability to select multiple nodes exists in the standard <code>TreeView</code> control.</p> <p>I'm trying to do this for a context menu selection. So check boxes aren't an acceptable UI paradigm here.</p> <p>What's the best way to provide that very necessary functionality?</p>
[ { "answer_id": 9864875, "author": "Oliver Bock", "author_id": 249548, "author_profile": "https://Stackoverflow.com/users/249548", "pm_score": 3, "selected": false, "text": "protected override void WndProc(ref Message m)\n{\n switch (m.Msg) {\n // WM_REFLECT is added because WM_NOTIFY is normally sent just\n // to the parent window, but Windows.Form will reflect it back\n // to us, MFC-style.\n case Win32.WM_REFLECT + Win32.WM_NOTIFY: {\n Win32.NMHDR nmhdr = (Win32.NMHDR)m.GetLParam(typeof(Win32.NMHDR));\n switch((int)nmhdr.code) {\n case Win32.NM_CUSTOMDRAW:\n base.WndProc(ref m);\n Win32.NMTVCUSTOMDRAW nmTvDraw = (Win32.NMTVCUSTOMDRAW)m.GetLParam(typeof(Win32.NMTVCUSTOMDRAW));\n switch (nmTvDraw.nmcd.dwDrawStage) {\n case Win32.CDDS_ITEMPREPAINT:\n // Find the node being painted.\n TreeNode n = TreeNode.FromHandle(this, nmTvDraw.nmcd.lItemlParam);\n if (allSelected.Contains(n))\n // Override its background colour.\n nmTvDraw.clrTextBk = ColorTranslator.ToWin32(SystemColors.Highlight);\n m.Result = (IntPtr)Win32.CDRF_DODEFAULT; // Continue rest of painting as normal\n break;\n }\n Marshal.StructureToPtr(nmTvDraw, m.LParam, false); // copy changes back\n return;\n }\n break;\n }\n }\n base.WndProc(ref m);\n}\n\n// WM_NOTIFY notification message header.\n[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]\npublic class NMHDR\n{\n private IntPtr hwndFrom;\n public IntPtr idFrom;\n public uint code;\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct NMCUSTOMDRAW\n{\n public NMHDR hdr;\n public int dwDrawStage;\n public IntPtr hdc;\n public RECT rc;\n public IntPtr dwItemSpec;\n public int uItemState;\n public IntPtr lItemlParam;\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct NMTVCUSTOMDRAW\n{\n public NMCUSTOMDRAW nmcd;\n public int clrText;\n public int clrTextBk;\n public int iLevel;\n}\n\npublic const int CDIS_SELECTED = 0x0001;\npublic const int CDIS_FOCUS = 0x0010;\npublic const int CDDS_PREPAINT = 0x00000001;\npublic const int CDDS_POSTPAINT = 0x00000002;\npublic const int CDDS_PREERASE = 0x00000003;\npublic const int CDDS_POSTERASE = 0x00000004;\npublic const int CDDS_ITEM = 0x00010000; // item specific \npublic const int CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT);\npublic const int CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT);\npublic const int CDDS_ITEMPREERASE = (CDDS_ITEM | CDDS_PREERASE);\npublic const int CDDS_ITEMPOSTERASE = (CDDS_ITEM | CDDS_POSTERASE);\npublic const int CDDS_SUBITEM = 0x00020000;\npublic const int CDRF_DODEFAULT = 0x00000000;\npublic const int CDRF_NOTIFYITEMDRAW = 0x00000020;\npublic const int CDRF_NOTIFYSUBITEMDRAW = 0x00000020; // flags are the same, we can distinguish by context\n\npublic const int WM_USER = 0x0400;\npublic const int WM_NOTIFY = 0x4E;\npublic const int WM_REFLECT = WM_USER + 0x1C00;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5062/" ]
206,106
<p><em>[This question is related to but not the same as <a href="https://stackoverflow.com/questions/206564/what-is-the-performance-implication-of-converting-to-bool-in-c">this one</a>.]</em></p> <p>If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (<code>?:</code>) to convert to a bool. Using two not operators (<code>!!</code>) seems to do the same thing.</p> <p>Here's what I mean:</p> <pre><code>typedef long T; // similar warning with void * or double T t = 0; bool b = t; // performance warning: forcing 'long' value to 'bool' b = t ? true : false; // ok b = !!t; // any different? </code></pre> <p>So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with <code>void *</code> or <code>double</code> for <code>T</code>)?</p> <p>I'm not asking if <code>!!t</code> is good style. I am asking if it is semantically different than <code>t ? true : false</code>.</p>
[ { "answer_id": 206122, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 5, "selected": false, "text": "bool b = (t != 0)" }, { "answer_id": 206127, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 2, "selected": false, "text": "bool b = (bool)t;" }, { "answer_id": 206139, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": -1, "selected": false, "text": "#define LONGTOBOOL(x) (!!(x))\n" }, { "answer_id": 206200, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 7, "selected": true, "text": "b = (t != 0);\n" }, { "answer_id": 206219, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "bool b = !!t;\n bool b = t ? true : false;\nif (b)\n{\n doSomething();\n}\n if (t)\n{\n doSomething();\n}\n bool b = t ? true : false; // Short and too the point.\n // But not everybody groks this especially beginners.\nbool b = (t != 0); // Gives the exact meaning of what you want to do.\nbool b = static_cast<bool>(t); // Implies that t has no semantic meaning\n // except as a bool in this context.\n" }, { "answer_id": 206345, "author": "edgar.holleis", "author_id": 24937, "author_profile": "https://Stackoverflow.com/users/24937", "pm_score": 5, "selected": false, "text": "b = (t != 0);" }, { "answer_id": 206947, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "c = 3 + !!extra; //3 or 4\n bool b = !!extra;\n if (!!extra) { ... }\n" }, { "answer_id": 50522954, "author": "Jay K", "author_id": 5751393, "author_profile": "https://Stackoverflow.com/users/5751393", "pm_score": 2, "selected": false, "text": "class foo { public: explicit operator bool () ; };\n\nfoo f;\n\nauto a = f != 0; // invalid operands to binary expression ('foo' and 'int')\nauto b = f ? true : false; // ok\nauto c = !!f; // ok\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
206,112
<p>I'm working with <a href="http://pear.php.net/package/Log" rel="nofollow noreferrer">logging in PHP with Pear</a>, and I get into a standard problem: can I use file-based logging when the DB is not available? I don't mind if it's slow due to concurrency issues, but it cannot fail to work due to multiple, simultaneous hits. </p> <p>I'm asking this question in general (for other web technologies) and specifically for Pear for PHP.</p> <p>Thanks!</p>
[ { "answer_id": 206223, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "require_once 'DB.php';\n$db = &DB::connect('pgsql://jon@localhost+unix/logs');\n\n$conf['db'] = $db;\n$logger = &Log::singleton('sql', 'log_table', 'ident', $conf);\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
206,114
<p>How you can read a file (text or binary) from a batch file? There is a way to read it in a binary mode or text mode?</p>
[ { "answer_id": 206137, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 6, "selected": false, "text": "FOR /F %%i IN (file.txt) DO @echo %%i\n" }, { "answer_id": 206145, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 6, "selected": true, "text": "FOR /F \"eol=; tokens=2,3* delims=, \" %i in (myfile.txt) do @echo %i %j %k\n for /?\n" }, { "answer_id": 4531090, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 6, "selected": false, "text": "@echo off\nSETLOCAL DisableDelayedExpansion\nFOR /F \"usebackq delims=\" %%a in (`\"findstr /n ^^ t.txt\"`) do (\n set \"var=%%a\"\n SETLOCAL EnableDelayedExpansion\n set \"var=!var:*:=!\"\n echo(!var!\n ENDLOCAL\n)\n ! ^^^xy!z set \"var=%%a\" var call %%var%% \"&\"& set /p @echo off\nsetlocal EnableDelayedExpansion\nset \"file=%~1\"\n\nfor /f \"delims=\" %%n in ('find /c /v \"\" %file%') do set \"len=%%n\"\nset \"len=!len:*: =!\"\n\n<%file% (\n for /l %%l in (1 1 !len!) do (\n set \"line=\"\n set /p \"line=\"\n echo(!line!\n )\n)\n" }, { "answer_id": 39479326, "author": "NetvorMcWolf", "author_id": 6828401, "author_profile": "https://Stackoverflow.com/users/6828401", "pm_score": 1, "selected": false, "text": "findstr /v \"randomtextthatnoonewilluse\" filename.txt" }, { "answer_id": 45624844, "author": "J. Bond", "author_id": 7811378, "author_profile": "https://Stackoverflow.com/users/7811378", "pm_score": 4, "selected": false, "text": "set /p mytextfile=< %pathtotextfile%\\textfile.txt\necho %mytextfile%\n type %pathtotextfile%\\textfile.txt\n" }, { "answer_id": 56600202, "author": "Celes", "author_id": 9086531, "author_profile": "https://Stackoverflow.com/users/9086531", "pm_score": 0, "selected": false, "text": "setlocal enabledelayedexpansion\nfor /f \"usebackq eol= tokens=* delims= \" %%a in (`findstr /n ^^^^ \"name with spaces.txt\"`) do (\n set line=%%a\n set \"line=!line:*:=!\"\n echo(!line!\n)\nendlocal\npause\n" }, { "answer_id": 72460077, "author": "Kuza Grave", "author_id": 7806306, "author_profile": "https://Stackoverflow.com/users/7806306", "pm_score": 1, "selected": false, "text": "name=\"John\"\nlastName=\"Doe\"\n @echo off\nfor /f \"tokens=1,2 delims==\" %%a in (settings.ini) do (\n if %%a==name set %%a=%%b\n if %%a==lastName set %%a=%%b\n)\n\necho %name% %lastName%\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20601/" ]
206,132
<p>Platform: IIS 6, ASP.Net 2.0 (.Net 3.5), Server 2003.</p> <p>I'm building an application that accepts files from a user, processes them, and returns a result. The file is uploaded using HTTP POST to an ASP.Net web form. The application is expecting some large files (hundreds of MB).</p> <p>I'm using SWFUpload to accomplish the upload with a nice progress bar, but that's not contributing to the issue, because when I bypass it using a standard HTML form pointing at my upload accepter page, I get the exact same error. When using the progress bar, the upload continues to 100%, then fails. With a standard form, the behavior appears to be the same. </p> <p>I'm having a problem right now uploading a file that's about 150MB. I've changed every settings I can find, but still no luck. </p> <p>Here's a summary of what I've changed so far:</p> <p>In Web.config: Added this inside system.web:</p> <pre><code>&lt;httpRuntime executionTimeout="3600" maxRequestLength="1536000"/&gt; </code></pre> <p>In machine.config: Inside system.web, changed:</p> <pre><code>&lt;processModel autoConfig="true" /&gt; </code></pre> <p>to: </p> <pre><code>&lt;processModel autoConfig="true" responseDeadlockInterval="00:30:00" responseRestartDeadlockInterval="00:30:00" /&gt; </code></pre> <p>and in MetaBase.xml: Changed:</p> <pre><code>AspMaxRequestEntityAllowed="204800" </code></pre> <p>to:</p> <pre><code>AspMaxRequestEntityAllowed="200000000" </code></pre> <p>When the upload fails, I get a 404 error from IIS. My web form does not begin processing, or at least, it doesn't make it to the Page_Load event. I threw an exception at the beginning of that handler, and it doesn't execute at all on large files. </p> <p>Everything works fine with smaller files (I've tested up to about 5.5MB). I'm not exactly sure what file size is the limit, but I know that my limit needs to be higher than 150MB, since this is not the largest file that the client will need to upload. </p> <p>Can anyone help?</p>
[ { "answer_id": 8568011, "author": "Manish Jain", "author_id": 486867, "author_profile": "https://Stackoverflow.com/users/486867", "pm_score": 2, "selected": false, "text": "<system.serviceModel> <system.webServer>\n <security>\n <requestFiltering><requestLimits maxAllowedContentLength=\"262144000\" /></requestFiltering> <!-- maxAllowedContentLength is in bytes. Defaults to 30,000,000 -->\n </security>\n</system.webServer>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28358/" ]
206,142
<p>I have a full text catalog with two tables in it.</p> <p>tableA has 4 columns (a1, a2, a3, a4) of which 3 are indexed in the catalog, a2,a3,a4. a1 is the primary key.</p> <p>tableB has 3 columns (b1, b2, b3, b4), two of which are indexed in the catalog, b3 and b4. b1 is the PK of this table, b2 is the FK to tableA.</p> <p>I want to do something like</p> <pre><code>SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank FROM tableA INNER JOIN tableB ON tableA.a1=tableB.b2 INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY] INNER JOIN FREETEXTTABLE(tableB, (b3,b4), 'search term') as ftTableB ON tableB.11=ftTableB.[KEY] </code></pre> <p>But this does not work... I can get a single table to work, eg.</p> <pre><code>SELECT *, (ftTableA.[RANK] + ftTableB.[RANK]) AS total_rank FROM tableA INNER JOIN FREETEXTTABLE(tableA, (a2,a3,a4), 'search term') as ftTableA ON tableA.a1=ftTableA.[KEY] </code></pre> <p>but never more than one table.</p> <p>Could someone give an explanation and/or example of the steps required to full-text search over multiple tables.</p>
[ { "answer_id": 209809, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "SELECT *, (ISNULL(ftTableA.[RANK], 0) + ISNULL(ftTableB.[RANK], 0)) AS total_rank \n WHERE ftTableA.Key IS NOT NULL OR ftTableB.Key IS NOT NULL\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1741868/" ]
206,154
<p>I've never used <a href="http://en.wikipedia.org/wiki/SOAP" rel="noreferrer">SOAP</a> before and I'm sort of new to Python. I'm doing this to get myself acquainted with both technologies. I've installed <a href="http://trac.optio.webfactional.com/wiki/soaplib" rel="noreferrer">SOAPlib</a> and I've tried to read their <a href="http://trac.optio.webfactional.com/wiki/Client" rel="noreferrer">Client</a> documentation, but I don't understand it too well. Is there anything else I can look into which is more suited for being a SOAP Client library for Python?</p> <p>Edit: Just in case it helps, I'm using Python 2.6.</p>
[ { "answer_id": 206167, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": "wsdl python" }, { "answer_id": 1237630, "author": "sstock", "author_id": 58926, "author_profile": "https://Stackoverflow.com/users/58926", "pm_score": 6, "selected": false, "text": "urllib2 urllib2 CONNECT abort: error: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28360/" ]
206,161
<p>How would I get the length of an <code>ArrayList</code> using a JSF EL expression? </p> <pre><code>#{MyBean.somelist.length} </code></pre> <p>does not work.</p>
[ { "answer_id": 206252, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 8, "selected": true, "text": "size() length getSize() getLength()" }, { "answer_id": 208093, "author": "Damo", "author_id": 2955, "author_profile": "https://Stackoverflow.com/users/2955", "pm_score": 6, "selected": false, "text": "#{MyBean.somelist.size()}\n" }, { "answer_id": 1361935, "author": "James McMahon", "author_id": 20774, "author_profile": "https://Stackoverflow.com/users/20774", "pm_score": 4, "selected": false, "text": "fn:length(MyBean.somelist) <c_rt:out value='<%= list[list.size()-1] %>'/>\n public class CollectionWrapper {\n\n Collection collection;\n\n public CollectionWrapper(Collection collection) {\n this.collection = collection;\n }\n\n public Collection getCollection() {\n return collection;\n }\n\n public int getSize() {\n return collection.size();\n }\n}\n" }, { "answer_id": 15131294, "author": "UdayKiran Pulipati", "author_id": 1624035, "author_profile": "https://Stackoverflow.com/users/1624035", "pm_score": 3, "selected": false, "text": "<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\"%>\n\n<h:outputText value=\"Table Size = #{fn:length(SystemBean.list)}\"/>\n Table Size = 5" }, { "answer_id": 43083011, "author": "Arry", "author_id": 3204788, "author_profile": "https://Stackoverflow.com/users/3204788", "pm_score": 2, "selected": false, "text": "xmlns:fn=\"http://java.sun.com/jsp/jstl/functions\" #{fn:length(myBean.someList)} <ui:fragment rendered=\"#{fn:length(myBean.someList) gt 0}\">\n <!-- Do something here-->\n</ui:fragment>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17614/" ]
206,170
<p>I would like to use the API to return all tweets that match my search query, but only tweets posted within the last five seconds.</p> <p>With Twitter's Search API, I can use the since_id to grab all tweets from a specific ID. However, I can't really see a good way to find the tweet ID to begin from.</p> <p>I'm also aware that you can use "since:" in the actual query to use a date, but you cannot enter a time.</p> <p>Can someone with Twitter API experience offer me any advice? Thanks for reading and your time!</p> <p><a href="http://apiwiki.twitter.com/Search-API-Documentation" rel="noreferrer">http://apiwiki.twitter.com/Search-API-Documentation</a></p>
[ { "answer_id": 1891825, "author": "Dustin", "author_id": 230067, "author_profile": "https://Stackoverflow.com/users/230067", "pm_score": 2, "selected": false, "text": " <script type=\"text/javascript\" charset=\"utf-8\">\n // JavaScript Document\n $(document).ready(function(){\n\n // start twitter API \n $.getJSON('http://twitter.com/status/user_timeline/YOUR_NAME.json?count=10&callback=?', function(data){\n $.each(data, function(index, item){\n $('#twitter').append('<div class=\"tweet\"><p>' + item.text.linkify() + '</p><p><strong>' + relative_time(item.created_at) + '</strong></p></div>');\n });\n\n });\n\n\n function relative_time(time_value) {\n var values = time_value.split(\" \");\n time_value = values[1] + \" \" + values[2] + \", \" + values[5] + \" \" + values[3];\n var parsed_date = Date.parse(time_value);\n var relative_to = (arguments.length > 1) ? arguments[1] : new Date();\n var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);\n delta = delta + (relative_to.getTimezoneOffset() * 60);\n\n var r = '';\n if (delta < 60) {\n r = 'a minute ago';\n } else if(delta < 120) {\n r = 'couple of minutes ago';\n } else if(delta < (45*60)) {\n r = (parseInt(delta / 60)).toString() + ' minutes ago';\n } else if(delta < (90*60)) {\n r = 'an hour ago';\n } else if(delta < (24*60*60)) {\n r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';\n } else if(delta < (48*60*60)) {\n r = '1 day ago';\n } else {\n r = (parseInt(delta / 86400)).toString() + ' days ago';\n }\n\n return r;\n }\n\n String.prototype.linkify = function() {\n return this.replace(/[A-Za-z]+:\\/\\/[A-Za-z0-9-_]+\\.[A-Za-z0-9-_:%&\\?\\/.=]+/, function(m) {\n return m.link(m);\n });\n };// end twitter API\n\n\n\n\n}); // ***** end functions *****\n </script>\n\n <div id=\"twitter\">\n Target Div \n\n </div>\n" }, { "answer_id": 3177220, "author": "Abhay Dandekar", "author_id": 383380, "author_profile": "https://Stackoverflow.com/users/383380", "pm_score": 0, "selected": false, "text": "* Valid values include:\n\n\n o mixed: In a future release this will become the default value. Include both popular and real time results in the response.\n o recent: The current default value. Return only the most recent results in the response.\n o popular: Return only the most popular results in the response.\n* Example: http://search.twitter.com/search.atom?q=Twitter&result_type=mixed\n* Example: http://search.twitter.com/search.json?q=twitterapi&result_type=popular\n* Example: http://search.twitter.com/search.atom?q=justin+bieber&result_type=recent\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ]
206,172
<p>I need a way to determine whether the computer running my program is joined to any domain. It doesn't matter what specific domain it is part of, just whether it is connected to anything. I'm coding in vc++ against the Win32 API.</p>
[ { "answer_id": 206209, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 0, "selected": false, "text": "domain\\name" }, { "answer_id": 206228, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "SV_TYPE_DOMAIN_CTRL" }, { "answer_id": 206467, "author": "kgriffs", "author_id": 21784, "author_profile": "https://Stackoverflow.com/users/21784", "pm_score": 2, "selected": false, "text": "bool ComputerBelongsToDomain()\n{\n bool ret = false;\n\n LSA_OBJECT_ATTRIBUTES objectAttributes;\n LSA_HANDLE policyHandle;\n NTSTATUS status;\n PPOLICY_PRIMARY_DOMAIN_INFO info;\n\n // Object attributes are reserved, so initialize to zeros.\n ZeroMemory(&objectAttributes, sizeof(objectAttributes));\n\n status = LsaOpenPolicy(NULL, &objectAttributes, GENERIC_READ | POLICY_VIEW_LOCAL_INFORMATION, &policyHandle);\n if (!status)\n {\n status = LsaQueryInformationPolicy(policyHandle, PolicyPrimaryDomainInformation, (LPVOID*)&info);\n if (!status)\n {\n if (info->Sid)\n ret = true;\n\n LsaFreeMemory(info);\n }\n\n LsaClose(policyHandle);\n }\n\n return ret;\n}\n" }, { "answer_id": 35495235, "author": "Ryan Ries", "author_id": 1301738, "author_profile": "https://Stackoverflow.com/users/1301738", "pm_score": 2, "selected": false, "text": "TCHAR UserDnsDomain[128] = { 0 }; \nDWORD Result = 0;\n\nResult = GetEnvironmentVariable(\"USERDNSDOMAIN\", UserDnsDomain, sizeof(UserDnsDomain));\n\nif (Result == 0 || Result >= sizeof(UserDnsDomain) || GetLastError() == ERROR_ENVVAR_NOT_FOUND)\n{\n return(FALSE); // Not logged in to a domain\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
206,183
<p>I want subversion to commit a file even if it's unchanged. Is there a way to do this?</p>
[ { "answer_id": 206856, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 7, "selected": true, "text": "svn:" }, { "answer_id": 253086, "author": "endian", "author_id": 25462, "author_profile": "https://Stackoverflow.com/users/25462", "pm_score": -1, "selected": false, "text": "svn ci -force <filename>\n" }, { "answer_id": 4334768, "author": "Sergiy Sokolenko", "author_id": 131337, "author_profile": "https://Stackoverflow.com/users/131337", "pm_score": 0, "selected": false, "text": "index.html svn update index.html -r 650 svn update svn merge -r 680:650 index.html svn ci -m \"Reverted to r650\" index.html" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15992/" ]
206,198
<p>i have a class with a static public property called "Info". via reflection i want to get this properties value, so i call:</p> <pre><code>PropertyInfo pi myType.GetProperty("Info"); string info = (string) pi.GetValue(null, null); </code></pre> <p>this works fine as long as the property is of type string. but actually my property is of type IPluginInfo and a PluginInfo type (implementing IPluginInfo) is instatiated and returned in the Info properties get accessor, like this:</p> <pre><code>public static IPluginInfo PluginInfo { get { IPluginInfo Info = new PluginInfo(); Info.Name = "PluginName"; Info.Version = "PluginVersion"; return Info; } } </code></pre> <p>like this when i call:</p> <pre><code>IPluginInfo info = pi.GetValue(null, null) as IPluginInfo; </code></pre> <p>info is always null, whiel PropertyInfo pi is still valid. am i missing something obvious here?</p>
[ { "answer_id": 206227, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "pi.GetValue object" }, { "answer_id": 206253, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "private static PluginInfo _PluginInfo = null;\npublic static IPluginInfo PluginInfo\n{\n get\n {\n if (_PluginInfo == null)\n {\n _PluginInfo = new PluginInfo();\n _PluginInfo.Name = \"PluginName\";\n _PluginInfo.Version = \"PluginVersion\";\n }\n return _PluginInfo;\n }\n}\n" }, { "answer_id": 206254, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 0, "selected": false, "text": "object info = pi.GetValue(null, null);\nConsole.WriteLine(info.GetType().ToString());\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6368/" ]
206,221
<p>I've successfully used the Windows SendMessage method to help me do various things in my text editor, but each time I am just copying and pasting code suggested by others, and I don't really know what it means. There is always a cryptic message number that is a parameter. How do I know what these code numbers mean so that I can actually understand what is happening and (hopefully) be a little more self-sufficient in the future? Thanks.</p> <p>Recent example:</p> <pre><code>using System.Runtime.InteropServices; [DllImport("user32.dll")] static extern int SendMessage(IntPtr hWnd, uint wMsg,UIntPtr wParam, IntPtr lParam); SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1)); </code></pre>
[ { "answer_id": 2494625, "author": "Pedro", "author_id": 299266, "author_profile": "https://Stackoverflow.com/users/299266", "pm_score": 1, "selected": false, "text": "using System.Runtime.InteropServices using System.Runtime.InteropServices; \n\n[DllImport(\"user32.dll\")] \nstatic extern int SendMessage(IntPtr hWnd, uint wMsg,UIntPtr wParam, IntPtr lParam); \n\nSendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1)); \n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27109/" ]
206,222
<p>I'm attempting to fulfill a rather difficult reporting request from a client, and I need to find away to get the difference between two DateTime columns in minutes. I've attempted to use trunc and round with various <a href="http://www.ss64.com/orasyntax/fmt.html" rel="noreferrer">formats</a> and can't seem to come up with a combination that makes sense. Is there an elegant way to do this? If not, is there <b>any</b> way to do this?</p>
[ { "answer_id": 206232, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 7, "selected": true, "text": "SELECT date1 - date2\n FROM some_table\n SELECT (date1 - date2) * 24 * 60 difference_in_minutes\n FROM some_table\n" }, { "answer_id": 206243, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": false, "text": "select\n round((second_date - first_date) * (60 * 24),2) as time_in_minutes\nfrom\n (\n select\n to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date\n ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date\n from\n dual\n ) test_data\n" }, { "answer_id": 67058433, "author": "Raghavendra", "author_id": 15611654, "author_profile": "https://Stackoverflow.com/users/15611654", "pm_score": 0, "selected": false, "text": "timestampdiff where Select * from tavle1,table2 where timestampdiff(mi,col1,col2).\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27457/" ]
206,224
<p>I'm trying to emulate the file upload code from the grails website, and I'm running into some problems. I'm using the same code as found <a href="http://grails.org/Controllers+-+File+Uploads" rel="nofollow noreferrer">here</a>. Here is my code:</p> <pre><code> &lt;g:form action="upload" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="myFile" /&gt; &lt;input type="submit" value="Upload" /&gt; &lt;/g:form&gt; </code></pre> <p>and</p> <pre><code>def upload = { def f = request.getFile('myFile') if(!f.empty) { flash.message = 'success' } else { flash.message = 'file cannot be empty' } } </code></pre> <p>I'm receiving the following error at runtime:</p> <pre><code>Message: No signature of method: org.mortbay.jetty.Request.getFile() is applicable for argument types: (java.lang.String) values: {"myFile"} Caused by: groovy.lang.MissingMethodException: No signature of method: org.mortbay.jetty.Request.getFile() is applicable for argument types: (java.lang.String) values: {"myFile"} </code></pre> <p>It appears to be related to some Spring configuration. Spring does not appear to be injecting <code>MultipartHttpServletRequest</code>, so my request doesn't have the appropriate method. I just created this applications using <code>grails create-app</code>. I have not modified the resources.groovy file. I'm using grails 1.0.3.</p> <p>Any help is much appreciated. The grails website makes this look so easy.</p>
[ { "answer_id": 206259, "author": "codeLes", "author_id": 3030, "author_profile": "https://Stackoverflow.com/users/3030", "pm_score": 2, "selected": false, "text": "<g:form action=\"upload\" method=\"post\" enctype=\"multipart/form-data\">\n" }, { "answer_id": 206513, "author": "anschoewe", "author_id": 21832, "author_profile": "https://Stackoverflow.com/users/21832", "pm_score": 5, "selected": true, "text": "if(request instanceof MultipartHttpServletRequest)\n{\n MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request; \n CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile(\"myFile\");\n if(!f.empty)\n flash.message = 'success'\n else\n flash.message = 'file cannot be empty'\n} \nelse\n flash.message = 'request is not of type MultipartHttpServletRequest'\n" }, { "answer_id": 17109379, "author": "Carleto", "author_id": 2347491, "author_profile": "https://Stackoverflow.com/users/2347491", "pm_score": 3, "selected": false, "text": "<g:uploadForm name=\"upload\" action=\"upload\" method=\"POST\">\n <input type=\"file\" name=\"file\" />\n</g:uploadForm>\n\ndef upload = {\n def file = request.getFile('file')\n assert file instanceof CommonsMultipartFile\n\n if(!file.empty){ //do something }\n else { //do something }\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21832/" ]
206,239
<p>i know this is an age old question, but this is my scenario</p> <p>This is in C# 2.0</p> <p>Have a windows application which has a datagridview control. This needs to be populates by making a webservice call.</p> <p>I want to achive the same functionality on the data if i were to use a direct connection and if i were using datasets, namely like paging and applying filters to returned data. i know returning datasets is a bad idea and am looking to find a good solution.</p>
[ { "answer_id": 206269, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 1, "selected": false, "text": "List<MyDataItem>" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,248
<p>How do you programmatically eject(safely remove) an USB mass storage device in Windows (XP)?</p>
[ { "answer_id": 16114537, "author": "Víctor", "author_id": 2300340, "author_profile": "https://Stackoverflow.com/users/2300340", "pm_score": 2, "selected": false, "text": "private void btnExpulsar_Click(object sender, RoutedEventArgs e)\n {\n //Expulsa todas las unidades\n VolumeDeviceClass volumeDeviceClass = new VolumeDeviceClass(); //Enlista las unidades\n foreach (var item in volumeDeviceClass.Devices.ToList())\n {\n if (item.IsUsb)//Verifica que sean unidades USB\n {\n item.Eject(true); //Expulsa las unidades\n }\n }\n } \n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4528/" ]
206,255
<p>I'm using the <a href="http://libodbcxx.sourceforge.net/" rel="nofollow noreferrer">freeodbc++</a> library to access data on a MS SQL Server 2000 database (SP3? SP4?). In particular, I'm running a particularly long and nasty stored procedure. I can watch the procedure execute in SQL Profiler, however, it tends to stop processing at a certain point. No error codes or exceptions thrown. If I comment out the nested statement that is always the last statement, it just ends slightly before the comment. I haven't tried radically commenting out the whole darn thing... I'm setting the query timeout to 300 seconds. The callable statement usually returns in under 1 sec, without actually finishing the SP.</p> <p>Any ideas?</p> <p><strong>UPDATE0:</strong> If I run the SP via Query Analyzer or some other tool... it works. It's just via my ODBC connection that it fails.</p> <p><strong>UPDATE1:</strong> As I comment out code, the execution ends further into the SP. Makes me think there is a timeout or buffer limit that I'm running into.</p>
[ { "answer_id": 16114537, "author": "Víctor", "author_id": 2300340, "author_profile": "https://Stackoverflow.com/users/2300340", "pm_score": 2, "selected": false, "text": "private void btnExpulsar_Click(object sender, RoutedEventArgs e)\n {\n //Expulsa todas las unidades\n VolumeDeviceClass volumeDeviceClass = new VolumeDeviceClass(); //Enlista las unidades\n foreach (var item in volumeDeviceClass.Devices.ToList())\n {\n if (item.IsUsb)//Verifica que sean unidades USB\n {\n item.Eject(true); //Expulsa las unidades\n }\n }\n } \n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/809/" ]
206,257
<p>I am declaring an array of void pointers. Each of which points to a value of arbitary type.<br> <code>void **values; // Array of void pointers to each value of arbitary type</code></p> <p>Initializing values as follows:</p> <pre><code> values = (void**)calloc(3,sizeof(void*)); //can initialize values as: values = new void* [3]; int ival = 1; float fval = 2.0; char* str = "word"; values[0] = (void*)new int(ival); values[1] = (void*)new float(fval); values[2] = (void*)str; //Trying to Clear the memory allocated free(*values); //Error: *** glibc detected *** simpleSQL: free(): invalid pointer: 0x080611b4 //Core dumped delete[] values*; //warning: deleting 'void*' is undefined //Similar Error. </code></pre> <p>Now how do I free/delete the memory allocated for values ( the array of void pointers)?</p>
[ { "answer_id": 206289, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": "int ct = 3;\nvalues = (void*)calloc(ct,sizeof(void));\n//can initialize values as: values = new void* [3];\nint ival = 1;\nfloat fval = 2.0;\nchar* str = \"word\";\nvalues[0] = (void*)new int(ival);\nvalues[1] = (void*)new float(fval);\nvalues[2] = (void*)str;\n\nfor ( int i = 0; i < ct; i++ ) [\n delete( values[i] );\n}\nfree( values );\n" }, { "answer_id": 206299, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "values values = (void*)calloc(3,sizeof( void )) sizeof(void *) sizeof(void) new delete malloc free delete malloc free new" }, { "answer_id": 206308, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": true, "text": "delete reinterpret_cast<int*>( values[0]); \ndelete reinterpret_cast<float*>( values[1]);\n\nfree( values); // I'm not sure why this would have failed in your example, \n // but it would have leaked the 2 items that you allocated \n // with new\n str sizeof(void) sizeof(void*)" }, { "answer_id": 206496, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "std::vector<boost::any> data;\nboost::any i1 = 1; // add integer\ndata.push_back(i1);\n\nboost::any f1 = 1.0; // add double\ndata.push_back(f1);\n\ndata.push_back(\"PLOP\"); // add a char *\n\nstd:: cout << boost::any_cast<int>(data[0]) + boost::any_cast<double>(data[1])\n << std::endl;\n values = (void*)calloc(3,sizeof(void));\n\n// This should have been\nvoid** values = (void**)calloc(3,sizeof(void*));\n\n// Freeing the members needs care as you need to cast them\n// back to the correct type before you release the memory.\n\n// now you can free the array with\nfree(values);\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27221/" ]
206,320
<p>I'm trying to traverse through all the subdirectories of the current directory in Perl, and get data from those files. I'm using grep to get a list of all files and folders in the given directory, but I don't know which of the values returned is a folder name and which is a file with no file extention. </p> <p>How can I tell the difference? </p>
[ { "answer_id": 206339, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": false, "text": "print \"$file is a directory\\n\" if ( -d $file );\n" }, { "answer_id": 206354, "author": "catfood", "author_id": 12802, "author_profile": "https://Stackoverflow.com/users/12802", "pm_score": 2, "selected": false, "text": "File::Find" }, { "answer_id": 206364, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 3, "selected": false, "text": "perldoc -f -X\n use File::Next;\n\nmy $iterator = File::Next::files( '/tmp' );\n\nwhile ( defined ( my $file = $iterator->() ) ) {\n print $file, \"\\n\";\n}\n\n# Prints...\n/tmp/foo.txt\n/tmp/bar.pl\n/tmp/baz/1\n/tmp/baz/2.txt\n/tmp/baz/wango/tango/purple.txt\n" }, { "answer_id": 206399, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 6, "selected": true, "text": "-d sub wanted {\n if (-d) { \n print $File::Find::name.\" is a directory\\n\";\n }\n}\n\nfind(\\&wanted, $mydir);\n" }, { "answer_id": 223245, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 3, "selected": false, "text": "my @files = grep { -f } @all;\nmy @dirs = grep { -d } @all;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21539/" ]
206,323
<p>How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and write the results to a text box.</p>
[ { "answer_id": 206347, "author": "Ray Jezek", "author_id": 28309, "author_profile": "https://Stackoverflow.com/users/28309", "pm_score": 10, "selected": true, "text": "// Start the child process.\n Process p = new Process();\n // Redirect the output stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.FileName = \"YOURBATCHFILE.bat\";\n p.Start();\n // Do not wait for the child process to exit before\n // reading to the end of its redirected stream.\n // p.WaitForExit();\n // Read the output stream first and then wait.\n string output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();\n" }, { "answer_id": 206348, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "ProcessStartInfo RedirectStandardOutput" }, { "answer_id": 206361, "author": "Jeff Mc", "author_id": 25521, "author_profile": "https://Stackoverflow.com/users/25521", "pm_score": 4, "selected": false, "text": " System.Diagnostics.ProcessStartInfo psi =\n new System.Diagnostics.ProcessStartInfo(@\"program_to_call.exe\");\n psi.RedirectStandardOutput = true;\n psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n psi.UseShellExecute = false;\n System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////\n System.IO.StreamReader myOutput = proc.StandardOutput;\n proc.WaitForExit(2000);\n if (proc.HasExited)\n {\n string output = myOutput.ReadToEnd();\n }\n" }, { "answer_id": 206366, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 7, "selected": false, "text": "//Create process\nSystem.Diagnostics.Process pProcess = new System.Diagnostics.Process();\n\n//strCommand is path and file name of command to run\npProcess.StartInfo.FileName = strCommand;\n\n//strCommandParameters are parameters to pass to program\npProcess.StartInfo.Arguments = strCommandParameters;\n\npProcess.StartInfo.UseShellExecute = false;\n\n//Set output of program to be written to process output stream\npProcess.StartInfo.RedirectStandardOutput = true; \n\n//Optional\npProcess.StartInfo.WorkingDirectory = strWorkingDirectory;\n\n//Start the process\npProcess.Start();\n\n//Get program output\nstring strOutput = pProcess.StandardOutput.ReadToEnd();\n\n//Wait for process to finish\npProcess.WaitForExit();\n" }, { "answer_id": 1488639, "author": "Peter Du", "author_id": 162429, "author_profile": "https://Stackoverflow.com/users/162429", "pm_score": 7, "selected": false, "text": "pProcess.StartInfo.CreateNoWindow = true;\n" }, { "answer_id": 10072082, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 7, "selected": false, "text": "// usage\nconst string ToolFileName = \"example.exe\";\nstring output = RunExternalExe(ToolFileName);\n\npublic string RunExternalExe(string filename, string arguments = null)\n{\n var process = new Process();\n\n process.StartInfo.FileName = filename;\n if (!string.IsNullOrEmpty(arguments))\n {\n process.StartInfo.Arguments = arguments;\n }\n\n process.StartInfo.CreateNoWindow = true;\n process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n process.StartInfo.UseShellExecute = false;\n\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.RedirectStandardOutput = true;\n var stdOutput = new StringBuilder();\n process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.\n\n string stdError = null;\n try\n {\n process.Start();\n process.BeginOutputReadLine();\n stdError = process.StandardError.ReadToEnd();\n process.WaitForExit();\n }\n catch (Exception e)\n {\n throw new Exception(\"OS error while executing \" + Format(filename, arguments)+ \": \" + e.Message, e);\n }\n\n if (process.ExitCode == 0)\n {\n return stdOutput.ToString();\n }\n else\n {\n var message = new StringBuilder();\n\n if (!string.IsNullOrEmpty(stdError))\n {\n message.AppendLine(stdError);\n }\n\n if (stdOutput.Length != 0)\n {\n message.AppendLine(\"Std output:\");\n message.AppendLine(stdOutput.ToString());\n }\n\n throw new Exception(Format(filename, arguments) + \" finished with exit code = \" + process.ExitCode + \": \" + message);\n }\n}\n\nprivate string Format(string filename, string arguments)\n{\n return \"'\" + filename + \n ((string.IsNullOrEmpty(arguments)) ? string.Empty : \" \" + arguments) +\n \"'\";\n}\n" }, { "answer_id": 45817364, "author": "Kitson88", "author_id": 6574422, "author_profile": "https://Stackoverflow.com/users/6574422", "pm_score": 2, "selected": false, "text": "List<string[]> results = new List<string[]>();\n\n using (Process p = new Process())\n {\n p.StartInfo.CreateNoWindow = true;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.Arguments = \"/c arp -a\";\n p.StartInfo.FileName = @\"C:\\Windows\\System32\\cmd.exe\";\n p.Start();\n\n string line;\n\n while ((line = p.StandardOutput.ReadLine()) != null)\n {\n if (line != \"\" && !line.Contains(\"Interface\") && !line.Contains(\"Physical Address\"))\n {\n var lineArr = line.Trim().Split(' ').Select(n => n).Where(n => !string.IsNullOrEmpty(n)).ToArray();\n var arrResult = new string[]\n {\n lineArr[0],\n lineArr[1],\n lineArr[2]\n };\n results.Add(arrResult);\n }\n }\n\n p.WaitForExit();\n }\n" }, { "answer_id": 47003136, "author": "Tyrrrz", "author_id": 2205454, "author_profile": "https://Stackoverflow.com/users/2205454", "pm_score": 3, "selected": false, "text": "using CliWrap;\nusing CliWrap.Buffered;\n\nvar result = await Cli.Wrap(\"target.exe\")\n .WithArguments(\"arguments\")\n .ExecuteBufferedAsync();\n\nvar stdout = result.StandardOutput;\n" }, { "answer_id": 47382540, "author": "Cameron", "author_id": 86375, "author_profile": "https://Stackoverflow.com/users/86375", "pm_score": 5, "selected": false, "text": " var p = new Process();\n p.StartInfo.FileName = \"cmd.exe\";\n p.StartInfo.Arguments = \"/c mycmd.exe 2>&1\";\n var p = new Process();\n p.StartInfo.FileName = \"cmd.exe\";\n p.StartInfo.Arguments = @\"/c dir \\windows\";\n p.StartInfo.CreateNoWindow = true;\n p.StartInfo.RedirectStandardError = true;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.RedirectStandardInput = false;\n p.OutputDataReceived += (a, b) => Console.WriteLine(b.Data);\n p.ErrorDataReceived += (a, b) => Console.WriteLine(b.Data);\n p.Start();\n p.BeginErrorReadLine();\n p.BeginOutputReadLine();\n p.WaitForExit();\n" }, { "answer_id": 49048917, "author": "Dave", "author_id": 1451197, "author_profile": "https://Stackoverflow.com/users/1451197", "pm_score": 0, "selected": false, "text": " private void butPython(object sender, EventArgs e)\n {\n llHello.Text = \"Calling Python...\";\n this.Refresh();\n Tuple<String,String> python = GoPython(@\"C:\\Users\\BLAH\\Desktop\\Code\\Python\\BLAH.py\");\n llHello.Text = python.Item1; // Show result.\n if (python.Item2.Length > 0) MessageBox.Show(\"Sorry, there was an error:\" + Environment.NewLine + python.Item2);\n }\n\n public Tuple<String,String> GoPython(string pythonFile, string moreArgs = \"\")\n {\n ProcessStartInfo PSI = new ProcessStartInfo();\n PSI.FileName = \"py.exe\";\n PSI.Arguments = string.Format(\"\\\"{0}\\\" {1}\", pythonFile, moreArgs);\n PSI.CreateNoWindow = true;\n PSI.UseShellExecute = false;\n PSI.RedirectStandardError = true;\n PSI.RedirectStandardOutput = true;\n using (Process process = Process.Start(PSI))\n using (StreamReader reader = process.StandardOutput)\n {\n string stderr = process.StandardError.ReadToEnd(); // Error(s)!!\n string result = reader.ReadToEnd(); // What we want.\n return new Tuple<String,String> (result,stderr); \n }\n }\n" }, { "answer_id": 58286629, "author": "Dan Stevens", "author_id": 660896, "author_profile": "https://Stackoverflow.com/users/660896", "pm_score": 3, "selected": false, "text": "new Process() { StartInfo = new ProcessStartInfo(\"echo\", \"Hello, World\") }.Start();\n var cliProcess = new Process() {\n StartInfo = new ProcessStartInfo(\"echo\", \"Hello, World\") {\n UseShellExecute = false,\n RedirectStandardOutput = true\n }\n };\n cliProcess.Start();\n string cliOut = cliProcess.StandardOutput.ReadToEnd();\n cliProcess.WaitForExit();\n cliProcess.Close();\n" }, { "answer_id": 59987509, "author": "Konard", "author_id": 710069, "author_profile": "https://Stackoverflow.com/users/710069", "pm_score": 3, "selected": false, "text": "// Start the child process.\nProcess p = new Process();\n// Redirect the output stream of the child process.\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = \"cmd.exe\";\np.StartInfo.Arguments = \"/C vol\";\np.Start();\n// Read the output stream first and then wait.\nstring output = p.StandardOutput.ReadToEnd();\np.WaitForExit();\nConsole.WriteLine(output);\n StandardInput StartInfo.Arguments // Start the child process.\nProcess p = new Process();\n// Redirect the output stream of the child process.\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardInput = true;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = \"cmd.exe\";\np.Start();\n// Read the output stream first and then wait.\np.StandardInput.WriteLine(\"vol\");\np.StandardInput.WriteLine(\"exit\");\nstring output = p.StandardOutput.ReadToEnd();\np.WaitForExit();\nConsole.WriteLine(output);\n" }, { "answer_id": 61867172, "author": "Julian", "author_id": 9479890, "author_profile": "https://Stackoverflow.com/users/9479890", "pm_score": 2, "selected": false, "text": "using IDisposable // Start a process with the filename or path with filename e.g. \"cmd\". Please note the \n//using statemant\nusing myProcess.StartInfo.FileName = \"cmd\";\n// add the arguments - Note add \"/c\" if you want to carry out tge argument in cmd and \n// terminate\nmyProcess.StartInfo.Arguments = \"/c dir\";\n// Allows to raise events\nmyProcess.EnableRaisingEvents = true;\n//hosted by the application itself to not open a black cmd window\nmyProcess.StartInfo.UseShellExecute = false;\nmyProcess.StartInfo.CreateNoWindow = true;\n// Eventhander for data\nmyProcess.Exited += OnOutputDataRecived;\n// Eventhandler for error\nmyProcess.ErrorDataReceived += OnErrorDataReceived;\n// Eventhandler wich fires when exited\nmyProcess.Exited += OnExited;\n// Starts the process\nmyProcess.Start();\n//read the output before you wait for exit\nmyProcess.BeginOutputReadLine();\n// wait for the finish - this will block (leave this out if you dont want to wait for \n// it, so it runs without blocking)\nprocess.WaitForExit();\n\n// Handle the dataevent\nprivate void OnOutputDataRecived(object sender, DataReceivedEventArgs e)\n{\n //do something with your data\n Trace.WriteLine(e.Data);\n}\n\n//Handle the error\nprivate void OnErrorDataReceived(object sender, DataReceivedEventArgs e)\n{ \n Trace.WriteLine(e.Data);\n //do something with your exception\n throw new Exception();\n} \n\n// Handle Exited event and display process information.\nprivate void OnExited(object sender, System.EventArgs e)\n{\n Trace.WriteLine(\"Process exited\");\n}\n" }, { "answer_id": 62823078, "author": "Frank", "author_id": 2324547, "author_profile": "https://Stackoverflow.com/users/2324547", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Text; //StringBuilder\nusing System.Diagnostics;\nusing System.IO;\n\n\nclass Program\n{\n private static bool redirectStandardOutput = true;\n\n private static string buildargument(string[] args)\n {\n StringBuilder arg = new StringBuilder();\n for (int i = 0; i < args.Length; i++)\n {\n arg.Append(\"\\\"\" + args[i] + \"\\\" \");\n }\n\n return arg.ToString();\n }\n\n static void Main(string[] args)\n {\n Process prc = new Process();\n prc.StartInfo = //new ProcessStartInfo(\"cmd.exe\", String.Format(\"/c \\\"\\\"{0}\\\" {1}\", Path.Combine(Environment.CurrentDirectory, \"mapTargetIDToTargetNameA3.bat\"), buildargument(args)));\n //new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, \"mapTargetIDToTargetNameA3.bat\"), buildargument(args));\n new ProcessStartInfo(\"mapTargetIDToTargetNameA3.bat\");\n prc.StartInfo.Arguments = buildargument(args);\n\n prc.EnableRaisingEvents = true;\n\n if (redirectStandardOutput == true)\n {\n prc.StartInfo.UseShellExecute = false;\n }\n else\n {\n prc.StartInfo.UseShellExecute = true;\n }\n\n prc.StartInfo.CreateNoWindow = true;\n\n prc.OutputDataReceived += OnOutputDataRecived;\n prc.ErrorDataReceived += OnErrorDataReceived;\n //prc.Exited += OnExited;\n\n prc.StartInfo.RedirectStandardOutput = redirectStandardOutput;\n prc.StartInfo.RedirectStandardError = redirectStandardOutput;\n\n try\n {\n prc.Start();\n prc.BeginOutputReadLine();\n prc.BeginErrorReadLine();\n prc.WaitForExit();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"OS error: \" + e.Message);\n }\n\n prc.Close();\n }\n\n // Handle the dataevent\n private static void OnOutputDataRecived(object sender, DataReceivedEventArgs e)\n {\n //do something with your data\n Console.WriteLine(e.Data);\n }\n\n //Handle the error\n private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)\n {\n Console.WriteLine(e.Data);\n }\n\n // Handle Exited event and display process information.\n //private static void OnExited(object sender, System.EventArgs e)\n //{\n // var process = sender as Process;\n // if (process != null)\n // {\n // Console.WriteLine(\"ExitCode: \" + process.ExitCode);\n // }\n // else\n // {\n // Console.WriteLine(\"Process exited\");\n // }\n //}\n}\n" }, { "answer_id": 66798326, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Diagnostics;\n\nclass Program\n{\n static void Main(string[] args)\n {\n var p = Process.Start(\n new ProcessStartInfo(\"git\", \"branch --show-current\")\n {\n CreateNoWindow = true,\n UseShellExecute = false,\n RedirectStandardError = true,\n RedirectStandardOutput = true,\n WorkingDirectory = Environment.CurrentDirectory\n }\n );\n\n p.WaitForExit();\n string branchName =p.StandardOutput.ReadToEnd().TrimEnd();\n string errorInfoIfAny =p.StandardError.ReadToEnd().TrimEnd();\n\n if (errorInfoIfAny.Length != 0)\n {\n Console.WriteLine($\"error: {errorInfoIfAny}\");\n }\n else { \n Console.WriteLine($\"branch: {branchName}\");\n }\n\n }\n}\n p.ExitCode" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/958/" ]
206,324
<p>I want to check for empty arrays. Google gave me varied solutions but nothing worked. Maybe I am not applying them correctly.</p> <pre><code>Function GetBoiler(ByVal sFile As String) As String 'Email Signature Dim fso As Object Dim ts As Object Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2) GetBoiler = ts.ReadAll ts.Close End Function Dim FileNamesList As Variant, i As Integer ' activate the desired startfolder for the filesearch FileNamesList = CreateFileList("*.*", False) ' Returns File names ' performs the filesearch, includes any subfolders ' present the result ' If there are Signatures then populate SigString Range("A:A").ClearContents For i = 1 To UBound(FileNamesList) Cells(i + 1, 1).Formula = FileNamesList(i) Next i SigString = FileNamesList(3) If Dir(SigString) &lt;&gt; "" Then Signature = GetBoiler(SigString) Else Signature = "" End If </code></pre> <p>Here if <code>FileNamesList</code> array is empty, <code>GetBoiler(SigString)</code> should not get called at all. When <code>FileNamesList</code> array is empty, <code>SigString</code> is also empty and this calls <code>GetBoiler()</code> function with empty string. I get an error at line </p> <pre><code>Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2) </code></pre> <p>since <code>sFile</code> is empty. Any way to avoid that?</p>
[ { "answer_id": 206523, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 2, "selected": false, "text": "If Dir(SigString) <> \"\" Then\n Signature = GetBoiler(SigString) \nElse\n Signature = \"\" \nEnd If\n \"\" vbNullString Dir CurDir$ SigString If True Dir GetBoiler SigString fso.GetFile SigString FileSystemObject.FileExists Dir Dir Scripting.FileSystemObject Dir FileExists True False FileExists Dir SigString If SigString <> \"\" And Dir(SigString) <> \"\" Then\n Signature = GetBoiler(SigString) \nElse\n Signature = \"\" \nEnd If\n FileSystemObject.FileExists Dim fso As Object\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\nIf fso.FileExists(SigString) Then\n Signature = GetBoiler(SigString) \nElse\n Signature = \"\" \nEnd If\n" }, { "answer_id": 206526, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 6, "selected": false, "text": "If Len(Join(FileNamesList)) > 0 Then\n" }, { "answer_id": 284967, "author": "jpinto3912", "author_id": 11567, "author_profile": "https://Stackoverflow.com/users/11567", "pm_score": 0, "selected": false, "text": "Function IsVarArrayEmpty(anArray as Variant)\nDim aVar as Variant\n\nIsVarArrayEmpty=False\nOn error resume next\naVar=anArray(1)\nIf Err.number then '...still, it might not start at this index\n aVar=anArray(0)\n If Err.number then IsVarArrayEmpty=True ' neither 0 or 1 yields good assignment\nEndIF\nEnd Function\n" }, { "answer_id": 620052, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 5, "selected": false, "text": "Function IsVarArrayEmpty(anArray As Variant)\n\nDim i As Integer\n\nOn Error Resume Next\n i = UBound(anArray,1)\nIf Err.number = 0 Then\n IsVarArrayEmpty = False\nElse\n IsVarArrayEmpty = True\nEnd If\n\nEnd Function\n" }, { "answer_id": 5511769, "author": "BBQ Chef", "author_id": 684098, "author_profile": "https://Stackoverflow.com/users/684098", "pm_score": 3, "selected": false, "text": "Private Function IsArrayEmpty(arr As Variant)\n ' This function returns true if array is empty\n Dim l As Long\n\n On Error Resume Next\n l = Len(Join(arr))\n If l = 0 Then\n IsArrayEmpty = True\n Else\n IsArrayEmpty = False\n End If\n\n If Err.Number > 0 Then\n IsArrayEmpty = True\n End If\n\n On Error GoTo 0\nEnd Function\n\nPrivate Sub IsArrayEmptyTest()\n Dim a As Variant\n a = Array()\n Debug.Print \"Array is Empty is \" & IsArrayEmpty(a)\n If IsArrayEmpty(a) = False Then\n Debug.Print \" \" & Join(a)\n End If\nEnd Sub\n" }, { "answer_id": 11491235, "author": "irm", "author_id": 1526761, "author_profile": "https://Stackoverflow.com/users/1526761", "pm_score": -1, "selected": false, "text": "if UBound(ar) < LBound(ar) then msgbox \"Your array is empty!\"\n if -1 = UBound(ar) then msgbox \"Your array is empty!\"\n ' Filtering ar2 out of strings that exists in ar1\n\nFor i = 0 To UBound(ar1)\n\n ' filter out any ar2.string that exists in ar1\n ar2 = Filter(ar2 , ar1(i), False) \n\n If UBound(ar2) < LBound(ar2) Then\n MsgBox \"All strings are the same.\", vbExclamation, \"Operation ignored\":\n Exit Sub\n\n End If\n\nNext\n\n' At this point, we know that ar2 is not empty and it is filtered \n'\n" }, { "answer_id": 13211736, "author": "Stefanos Kargas", "author_id": 350061, "author_profile": "https://Stackoverflow.com/users/350061", "pm_score": -1, "selected": false, "text": "Public Function arrayIsEmpty(arrayToCheck() As Variant) As Boolean\n On Error GoTo Err:\n Dim forCheck\n forCheck = arrayToCheck(0)\n arrayIsEmpty = False\n Exit Function\nErr:\n arrayIsEmpty = True\nEnd Function\n" }, { "answer_id": 14382846, "author": "ahuth", "author_id": 1430871, "author_profile": "https://Stackoverflow.com/users/1430871", "pm_score": 6, "selected": false, "text": "If (Not Not FileNamesList) <> 0 Then\n ' Array has been initialized, so you're good to go.\nElse\n ' Array has NOT been initialized\nEnd If\n If (Not FileNamesList) = -1 Then\n ' Array has NOT been initialized\nElse\n ' Array has been initialized, so you're good to go.\nEnd If\n Not myArray Not (Not myArray) (Not Not myArray)\nUninitialized -1 0\nInitialized -someBigNumber someOtherBigNumber\n" }, { "answer_id": 15668372, "author": "Jim Snyder", "author_id": 2047486, "author_profile": "https://Stackoverflow.com/users/2047486", "pm_score": 0, "selected": false, "text": "if UBound(ar) > LBound(ar) Then\n" }, { "answer_id": 19096020, "author": "sancho.s ReinstateMonicaCellio", "author_id": 2707864, "author_profile": "https://Stackoverflow.com/users/2707864", "pm_score": 2, "selected": false, "text": "Public Function IsArrayEmpty(Arr As Variant) As Boolean\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' IsArrayEmpty\n' This function tests whether the array is empty (unallocated). Returns TRUE or FALSE.\n'\n' The VBA IsArray function indicates whether a variable is an array, but it does not\n' distinguish between allocated and unallocated arrays. It will return TRUE for both\n' allocated and unallocated arrays. This function tests whether the array has actually\n' been allocated.\n'\n' This function is really the reverse of IsArrayAllocated.\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\n Dim LB As Long\n Dim UB As Long\n\n err.Clear\n On Error Resume Next\n If IsArray(Arr) = False Then\n ' we weren't passed an array, return True\n IsArrayEmpty = True\n End If\n\n ' Attempt to get the UBound of the array. If the array is\n ' unallocated, an error will occur.\n UB = UBound(Arr, 1)\n If (err.Number <> 0) Then\n IsArrayEmpty = True\n Else\n ''''''''''''''''''''''''''''''''''''''''''\n ' On rare occasion, under circumstances I\n ' cannot reliably replicate, Err.Number\n ' will be 0 for an unallocated, empty array.\n ' On these occasions, LBound is 0 and\n ' UBound is -1.\n ' To accommodate the weird behavior, test to\n ' see if LB > UB. If so, the array is not\n ' allocated.\n ''''''''''''''''''''''''''''''''''''''''''\n err.Clear\n LB = LBound(Arr)\n If LB > UB Then\n IsArrayEmpty = True\n Else\n IsArrayEmpty = False\n End If\n End If\n\nEnd Function\n" }, { "answer_id": 21150293, "author": "Zhenya", "author_id": 1916997, "author_profile": "https://Stackoverflow.com/users/1916997", "pm_score": 1, "selected": false, "text": "Public Function IsEmptyArray(InputArray As Variant) As Boolean\n\n On Error GoTo ErrHandler:\n IsEmptyArray = Not (UBound(InputArray) >= 0)\n Exit Function\n\n ErrHandler:\n IsEmptyArray = True\n\nEnd Function\n" }, { "answer_id": 22941963, "author": "Mike Bethany", "author_id": 2611793, "author_profile": "https://Stackoverflow.com/users/2611793", "pm_score": 2, "selected": false, "text": "option explicit\nFunction foo() As Variant\n\n Dim bar() As String\n\n If (Not Not bar) Then\n ReDim Preserve bar(0 To UBound(bar) + 1)\n Else\n ReDim Preserve bar(0 To 0)\n End If\n\n bar(UBound(bar)) = \"it works!\"\n\n foo = bar\n\nEnd Function\n" }, { "answer_id": 26490424, "author": "Robert S.", "author_id": 4166543, "author_profile": "https://Stackoverflow.com/users/4166543", "pm_score": 2, "selected": false, "text": "Dim exampleArray() As Variant 'Any Type\n\nIf ((Not Not exampleArray) = 0) Then\n 'Array is Empty\nElse\n 'Array is Not Empty\nEnd If\n" }, { "answer_id": 30025972, "author": "Vignesh Subramanian", "author_id": 848841, "author_profile": "https://Stackoverflow.com/users/848841", "pm_score": 1, "selected": false, "text": "Function IsArrayAllocated(Arr As Variant) As Boolean\n On Error Resume Next\n IsArrayAllocated = IsArray(Arr) And _\n Not IsError(LBound(Arr, 1)) And _\n LBound(Arr, 1) <= UBound(Arr, 1)\nEnd Function\n Public Function test()\nDim Arr(1) As String\nArr(0) = \"d\"\nDim x As Boolean\nx = IsArrayAllocated(Arr)\nEnd Function\n" }, { "answer_id": 31082392, "author": "Perposterer", "author_id": 3246731, "author_profile": "https://Stackoverflow.com/users/3246731", "pm_score": 3, "selected": false, "text": "Public Function arrayLength(arr As Variant) As Long\n On Error GoTo handler\n\n Dim lngLower As Long\n Dim lngUpper As Long\n\n lngLower = LBound(arr)\n lngUpper = UBound(arr)\n\n arrayLength = (lngUpper - lngLower) + 1\n Exit Function\n\nhandler:\n arrayLength = 0 'error occured. must be zero length\nEnd Function\n" }, { "answer_id": 37191574, "author": "Surya", "author_id": 6326466, "author_profile": "https://Stackoverflow.com/users/6326466", "pm_score": 2, "selected": false, "text": "Function IsArrayEmpty(arr As Variant) As Boolean\n\nDim index As Integer\n\nindex = -1\n On Error Resume Next\n index = UBound(arr)\n On Error GoTo 0\n\nIf (index = -1) Then IsArrayEmpty = True Else IsArrayEmpty = False\n\nEnd Function\n" }, { "answer_id": 38787339, "author": "omegastripes", "author_id": 2165759, "author_profile": "https://Stackoverflow.com/users/2165759", "pm_score": 0, "selected": false, "text": "VBArray() Sub Test()\n\n Dim a() As Variant\n Dim b As Variant\n Dim c As Long\n\n ' Uninitialized array of variant\n ' MsgBox UBound(a) ' gives 'Subscript out of range' error\n MsgBox GetElementsCount(a) ' 0\n\n ' Variant containing an empty array\n b = Array()\n MsgBox GetElementsCount(b) ' 0\n\n ' Any other types, eg Long or not Variant type arrays\n MsgBox GetElementsCount(c) ' -1\n\nEnd Sub\n\nFunction GetElementsCount(aSample) As Long\n\n Static oHtmlfile As Object ' instantiate once\n\n If oHtmlfile Is Nothing Then\n Set oHtmlfile = CreateObject(\"htmlfile\")\n oHtmlfile.parentWindow.execScript (\"function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}\"), \"jscript\"\n End If\n GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)\n\nEnd Function\n ScriptControl" }, { "answer_id": 39795399, "author": "Pierre", "author_id": 6903657, "author_profile": "https://Stackoverflow.com/users/6903657", "pm_score": 1, "selected": false, "text": "Function IsVarArrayEmpty(anArray As Variant) as boolean\n On Error Resume Next\n IsVarArrayEmpty = true\n IsVarArrayEmpty = UBound(anArray) < LBound(anArray)\nEnd Function\n ubound ubound < lbound" }, { "answer_id": 40326677, "author": "Fuzzier", "author_id": 2597989, "author_profile": "https://Stackoverflow.com/users/2597989", "pm_score": 1, "selected": false, "text": "StrPtr() StrPtr() 0 Dim ar() As Byte\nDebug.Assert StrPtr(ar) = 0\n\nReDim ar(0 to 3) As Byte\nDebug.Assert StrPtr(ar) <> 0\n" }, { "answer_id": 40909581, "author": "Dave Poole", "author_id": 987776, "author_profile": "https://Stackoverflow.com/users/987776", "pm_score": 0, "selected": false, "text": "if Ubound(yourArray)>-1 then\n debug.print \"The array is not empty\"\nelse\n debug.print \"EMPTY\"\nend if\n" }, { "answer_id": 45123278, "author": "user425678", "author_id": 425678, "author_profile": "https://Stackoverflow.com/users/425678", "pm_score": 2, "selected": false, "text": "Function AryLen(ary() As Variant, Optional idx_dim As Long = 1) As Long\n If (Not ary) = -1 Then\n AryLen = 0\n Else\n AryLen = UBound(ary, idx_dim) - LBound(ary, idx_dim) + 1\n End If\nEnd Function\n is_empty = AryLen(some_array)=0" }, { "answer_id": 50933250, "author": "Mantej Singh", "author_id": 2304478, "author_profile": "https://Stackoverflow.com/users/2304478", "pm_score": 0, "selected": false, "text": "if (jsonObject(\"result\")(\"cid\").Count) = 0 them\nMsgBox \"Empty Array\"\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26927/" ]
206,384
<p>I'm taking my first crack at <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:</p> <pre><code>/Date(1224043200000)/ </code></pre> <p>From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the <code>jQuery.UI.datepicker</code> plugin using <code>$.datepicker.formatDate()</code> without any success.</p> <p>FYI: Here's the solution I came up with using a combination of the answers here:</p> <pre><code>function getMismatch(id) { $.getJSON("Main.aspx?Callback=GetMismatch", { MismatchId: id }, function (result) { $("#AuthMerchId").text(result.AuthorizationMerchantId); $("#SttlMerchId").text(result.SettlementMerchantId); $("#CreateDate").text(formatJSONDate(Date(result.AppendDts))); $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts))); $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts))); $("#LastUpdatedBy").text(result.LastUpdateNt); $("#ProcessIn").text(result.ProcessIn); } ); return false; } function formatJSONDate(jsonDate) { var newDate = dateFormat(jsonDate, "mm/dd/yyyy"); return newDate; } </code></pre> <p>This solution got my object from the callback method and displayed the dates on the page properly using the date format library.</p>
[ { "answer_id": 206416, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 6, "selected": false, "text": "var thedate = new Date(1224043200000);\nalert(thedate);\n" }, { "answer_id": 206527, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 7, "selected": false, "text": "var date = eval(jsonDate.replace(/\\/Date\\((\\d+)\\)\\//gi, \"new Date($1)\"));\n" }, { "answer_id": 207370, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "\"{ myDate : Date(1224043200000) }\"\n $.get(\n \"myJSONFile.php\",\n function (data) {\n // data.myDate will be a date object.\n\n // to show in a short date format (eg: dd/mm/yyyy)\n alert (\n data.myDate.getDate() + \"/\"\n + (data.myDate.getMonth() + 1) + \"/\"\n + data.myDate.getFullYear()\n ); // alerts: \"15/10/2008\"\n }\n);\n" }, { "answer_id": 304747, "author": "Thomas Hansen", "author_id": 29746, "author_profile": "https://Stackoverflow.com/users/29746", "pm_score": 3, "selected": false, "text": "yyyy.MM.ddThh:mm\n 2008.11.20T22:18" }, { "answer_id": 1471134, "author": "Bilgin Kılıç", "author_id": 173718, "author_profile": "https://Stackoverflow.com/users/173718", "pm_score": 4, "selected": false, "text": "var newDate = dateFormat(jsonDate, \"mm/dd/yyyy\"); \n" }, { "answer_id": 1541350, "author": "Chris Woodward", "author_id": 177527, "author_profile": "https://Stackoverflow.com/users/177527", "pm_score": 5, "selected": false, "text": "protected string JsonObject { get { return jsSerialiser.Serialize(_myObject); }}\n <script type=\"text/javascript\">\n var myObject = '<%= JsonObject %>';\n</script>\n var myObject = '{\"StartDate\":\"\\/Date(1255131630400)\\/\"}';\n myObject = myObject.replace(/\"\\/Date\\((\\d+)\\)\\/\"/g, 'new Date($1)');\n String.prototype.evalJSONWithDates = function() {\n var jsonWithDates = this.replace(/\"\\/Date\\((\\d+)\\)\\/\"/g, 'new Date($1)');\n return jsonWithDates.evalJSON(true);\n}\n" }, { "answer_id": 1611713, "author": "Ray Linder", "author_id": 444000, "author_profile": "https://Stackoverflow.com/users/444000", "pm_score": 3, "selected": false, "text": " [Authorize(Roles = \"Administrator\")]\n [Authorize(Roles = \"Director\")]\n [Authorize(Roles = \"Human Resources\")]\n [HttpGet]\n public ActionResult GetUserData(string UserIdGuidKey)\n {\n if (UserIdGuidKey!= null)\n {\n var guidUserId = new Guid(UserIdGuidKey);\n var memuser = Membership.GetUser(guidUserId);\n var profileuser = Profile.GetUserProfile(memuser.UserName);\n var list = new {\n UserName = memuser.UserName,\n Email = memuser.Email ,\n IsApproved = memuser.IsApproved.ToString() ,\n IsLockedOut = memuser.IsLockedOut.ToString() ,\n LastLockoutDate = memuser.LastLockoutDate.ToString() ,\n CreationDate = memuser.CreationDate.ToString() ,\n LastLoginDate = memuser.LastLoginDate.ToString() ,\n LastActivityDate = memuser.LastActivityDate.ToString() ,\n LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,\n IsOnline = memuser.IsOnline.ToString() ,\n FirstName = profileuser.FirstName ,\n LastName = profileuser.LastName ,\n NickName = profileuser.NickName ,\n BirthDate = profileuser.BirthDate.ToString() ,\n };\n return Json(list, JsonRequestBehavior.AllowGet);\n }\n return Redirect(\"Index\");\n }\n" }, { "answer_id": 1977936, "author": "Aaron", "author_id": 2742, "author_profile": "https://Stackoverflow.com/users/2742", "pm_score": 6, "selected": false, "text": "/Date(1224043200000)/ \n [OperationContract]\n[WebInvoke(\n RequestFormat = WebMessageFormat.Json,\n ResponseFormat = WebMessageFormat.Json,\n BodyStyle = WebMessageBodyStyle.WrappedRequest\n )]\nApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );\n public class ApptVisitLinkInfo {\n string Field1 { get; set; }\n DateTime Field2 { get; set; }\n ...\n}\n /Date(1224043200000-0600)/\n /\\/Date\\((.*?)\\)\\//gi\n replace(/\\/Date\\((.*?)\\)\\//gi, \"new Date($1)\");\n" }, { "answer_id": 2091162, "author": "Jason Jong", "author_id": 209254, "author_profile": "https://Stackoverflow.com/users/209254", "pm_score": 7, "selected": false, "text": "IsoDateTimeConverter() string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());\n \"fieldName\": \"2009-04-12T20:44:55\"\n function isoDateReviver(value) {\n if (typeof value === 'string') {\n var a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)(?:([\\+-])(\\d{2})\\:(\\d{2}))?Z?$/.exec(value);\n if (a) {\n var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);\n return new Date(utcMilliseconds);\n }\n }\n return value;\n}\n $(\"<span />\").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo(\"#\" + divName);\n" }, { "answer_id": 2316066, "author": "Roy Tinker", "author_id": 163227, "author_profile": "https://Stackoverflow.com/users/163227", "pm_score": 12, "selected": true, "text": "eval() var date = new Date(parseInt(jsonDate.substr(6)));\n substr() /Date( parseInt() )/ Date parseInt Date var date = new Date(jsonDate); //no ugly parsing needed; full timezone support\n" }, { "answer_id": 2825210, "author": "Midhat", "author_id": 9425, "author_profile": "https://Stackoverflow.com/users/9425", "pm_score": 3, "selected": false, "text": "new Date(Date(result.AppendDts)).format('%x')\n" }, { "answer_id": 3797510, "author": "Michael Vashchinsky", "author_id": 260240, "author_profile": "https://Stackoverflow.com/users/260240", "pm_score": 3, "selected": false, "text": "\"/Date(1276290000000+0300)/\"\n \"/Date(12762900000000300)/\"\n\"Date(1276290000000-0300)\"\n /\\/+Date\\(([\\d+]+)\\)\\/+/\n var myDate = new Date(parseInt(jsonWcfDate.replace(/\\/+Date\\(([\\d+-]+)\\)\\/+/, '$1')));\n" }, { "answer_id": 3797545, "author": "Dan Beam", "author_id": 234201, "author_profile": "https://Stackoverflow.com/users/234201", "pm_score": 4, "selected": false, "text": "var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));\nalert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));\n" }, { "answer_id": 3930211, "author": "StarTrekRedneck", "author_id": 181865, "author_profile": "https://Stackoverflow.com/users/181865", "pm_score": 3, "selected": false, "text": "{\"myDate\":Date(123456789)}" }, { "answer_id": 4540069, "author": "Robert Koritnik", "author_id": 75642, "author_profile": "https://Stackoverflow.com/users/75642", "pm_score": 6, "selected": false, "text": "$.parseJSON() $.parseJSON() /Date(12348721342)/ 2010-01-01T12.34.56.789Z" }, { "answer_id": 4928137, "author": "Chris Moschini", "author_id": 176877, "author_profile": "https://Stackoverflow.com/users/176877", "pm_score": 5, "selected": false, "text": "/Date(msecs)/ 2014-06-22T00:00:00.0 Date // Handling of Microsoft AJAX Dates, formatted like '/Date(01238329348239)/'\nfunction looksLikeMSDate(s) {\n return /^\\/Date\\(/.test(s);\n}\n var isoDateRegex = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d\\d?\\d?)?([\\+-]\\d\\d:\\d\\d|Z)?$/;\n\nfunction looksLikeIsoDate(s) {\n return isoDateRegex.test(s);\n}\n function parseMSDate(s) {\n // Jump forward past the /Date(, parseInt handles the rest\n return new Date(parseInt(s.substr(6)));\n}\n function parseIsoDate(s) {\n var m = isoDateRegex.exec(s);\n\n // Is this UTC, offset, or undefined? Treat undefined as UTC.\n if (m.length == 7 || // Just the y-m-dTh:m:s, no ms, no tz offset - assume UTC\n (m.length > 7 && (\n !m[7] || // Array came back length 9 with undefined for 7 and 8\n m[7].charAt(0) != '.' || // ms portion, no tz offset, or no ms portion, Z\n !m[8] || // ms portion, no tz offset\n m[8] == 'Z'))) { // ms portion and Z\n // JavaScript's weirdo date handling expects just the months to be 0-based, as in 0-11, not 1-12 - the rest are as you expect in dates.\n var d = new Date(Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]));\n } else {\n // local\n var d = new Date(m[1], m[2]-1, m[3], m[4], m[5], m[6]);\n }\n\n return d;\n}\n function parseIsoDate(s) {\n return new Date(s);\n}\n function hasTime(d) {\n return !!(d.getUTCHours() || d.getUTCMinutes() || d.getUTCSeconds());\n}\n\nfunction zeroFill(n) {\n if ((n + '').length == 1)\n return '0' + n;\n\n return n;\n}\n\nfunction formatDate(d) {\n if (hasTime(d)) {\n var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();\n s += ' ' + d.getHours() + ':' + zeroFill(d.getMinutes()) + ':' + zeroFill(d.getSeconds());\n } else {\n var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();\n }\n\n return s;\n}\n function parseDate(s) {\n var d;\n if (looksLikeMSDate(s))\n d = parseMSDate(s);\n else if (looksLikeIsoDate(s))\n d = parseIsoDate(s);\n else\n return null;\n\n return formatDate(d);\n}\n // Once\njQuery.parseJSON = function(d) {return eval('(' + d + ')');};\n\n$.ajax({\n ...\n dataFilter: function(d) {\n return d.replace(/\"\\\\\\/(Date\\(-?\\d+\\))\\\\\\/\"/g, 'new $1');\n },\n ...\n});\n parseJSON" }, { "answer_id": 5589633, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 5, "selected": false, "text": "(function () {\n var DATE_START = \"/Date(\";\n var DATE_START_LENGTH = DATE_START.length;\n\n function isDateString(x) {\n return typeof x === \"string\" && x.startsWith(DATE_START);\n }\n\n function deserializeDateString(dateString) {\n var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));\n var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);\n return utcDate;\n }\n\n function convertJSONDates(key, value) {\n if (isDateString(value)) {\n return deserializeDateString(value);\n }\n return value;\n }\n\n window.jQuery.ajaxSetup({\n converters: {\n \"text json\": function(data) {\n return window.JSON.parse(data, convertJSONDates);\n }\n }\n });\n}());\n Date getUTCHours() getHours()" }, { "answer_id": 6381155, "author": "Nick Perkins", "author_id": 138939, "author_profile": "https://Stackoverflow.com/users/138939", "pm_score": 4, "selected": false, "text": "{ \"name\":\"Nick\",\n \"birthdate\":[1968,6,9] }\n" }, { "answer_id": 6545263, "author": "在路上", "author_id": 824464, "author_profile": "https://Stackoverflow.com/users/824464", "pm_score": 3, "selected": false, "text": "var obj = eval('(' + \"{Date: \\/Date(1278903921551)\\/}\".replace(/\\/Date\\((\\d+)\\)\\//gi, \"new Date($1)\") + ')');\nvar dateValue = obj[\"Date\"];\n" }, { "answer_id": 7241202, "author": "dominic", "author_id": 919395, "author_profile": "https://Stackoverflow.com/users/919395", "pm_score": 4, "selected": false, "text": "$.datepicker.formatDate('MM d, yy', new Date(parseInt('/Date(1224043200000)/'.substr(6)))); \n" }, { "answer_id": 10743718, "author": "Scott Willeke", "author_id": 51061, "author_profile": "https://Stackoverflow.com/users/51061", "pm_score": 4, "selected": false, "text": "new MyInfo {\n CreationDate = r.CreationDate.ToString(\"o\"),\n};\n $.getJSON(\n \"MyRestService.svc/myinfo\",\n function (data) {\n $.each(data.myinfos, function (r) {\n this.CreatedOn = new Date(this.CreationDate);\n });\n // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).\n alert(data.myinfos[0].CreationDate.toLocaleString());\n }\n)\n" }, { "answer_id": 11261404, "author": "Thulasiram", "author_id": 1085778, "author_profile": "https://Stackoverflow.com/users/1085778", "pm_score": 3, "selected": false, "text": "function DateFormate(dateConvert) {\n return $.datepicker.formatDate(\"dd/MM/yyyy\", eval('new ' + dateConvert.slice(1, -1)));\n};\n" }, { "answer_id": 11883218, "author": "Umar Malik", "author_id": 1423894, "author_profile": "https://Stackoverflow.com/users/1423894", "pm_score": 3, "selected": false, "text": "function JSONDate(dateStr) {\n var m, day;\n jsonDate = dateStr;\n var d = new Date(parseInt(jsonDate.substr(6)));\n m = d.getMonth() + 1;\n if (m < 10)\n m = '0' + m\n if (d.getDate() < 10)\n day = '0' + d.getDate()\n else\n day = d.getDate();\n return (m + '/' + day + '/' + d.getFullYear())\n}\n\nfunction JSONDateWithTime(dateStr) {\n jsonDate = dateStr;\n var d = new Date(parseInt(jsonDate.substr(6)));\n var m, day;\n m = d.getMonth() + 1;\n if (m < 10)\n m = '0' + m\n if (d.getDate() < 10)\n day = '0' + d.getDate()\n else\n day = d.getDate();\n var formattedDate = m + \"/\" + day + \"/\" + d.getFullYear();\n var hours = (d.getHours() < 10) ? \"0\" + d.getHours() : d.getHours();\n var minutes = (d.getMinutes() < 10) ? \"0\" + d.getMinutes() : d.getMinutes();\n var formattedTime = hours + \":\" + minutes + \":\" + d.getSeconds();\n formattedDate = formattedDate + \" \" + formattedTime;\n return formattedDate;\n}\n" }, { "answer_id": 13798318, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var s = Response.StartDate; \ns = s.replace('/Date(', '');\n\ns = s.replace(')/', '');\n\nvar expDate = new Date(parseInt(s));\n" }, { "answer_id": 15463979, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "var = MyDate_String_Value = \"/Date(1224043200000)/\"\nvar value = new Date\n (\n parseInt(MyDate_String_Value.replace(/(^.*\\()|([+-].*$)/g, ''))\n );\nvar dat = value.getMonth() +\n 1 +\n \"/\" +\n value.getDate() +\n \"/\" +\n value.getFullYear();\n" }, { "answer_id": 16558140, "author": "martinoss", "author_id": 551698, "author_profile": "https://Stackoverflow.com/users/551698", "pm_score": 3, "selected": false, "text": "function getMismatch(id) {\n $.getJSON(\"Main.aspx?Callback=GetMismatch\",\n { MismatchId: id },\n\n function (result) {\n $(\"#AuthMerchId\").text(result.AuthorizationMerchantId);\n $(\"#SttlMerchId\").text(result.SettlementMerchantId);\n $(\"#CreateDate\").text(moment(result.AppendDts).format(\"L\"));\n $(\"#ExpireDate\").text(moment(result.ExpiresDts).format(\"L\"));\n $(\"#LastUpdate\").text(moment(result.LastUpdateDts).format(\"L\"));\n $(\"#LastUpdatedBy\").text(result.LastUpdateNt);\n $(\"#ProcessIn\").text(result.ProcessIn);\n }\n );\n return false;\n}\n moment.lang('de');\n" }, { "answer_id": 16558354, "author": "Venemo", "author_id": 202919, "author_profile": "https://Stackoverflow.com/users/202919", "pm_score": 5, "selected": false, "text": "var d = moment(yourdatestring)\n" }, { "answer_id": 18858181, "author": "Juan Carlos Puerto", "author_id": 823784, "author_profile": "https://Stackoverflow.com/users/823784", "pm_score": 3, "selected": false, "text": "return DateTime.Now.ToString(\"u\"); //\"2013-09-17 15:18:53Z\"\n var x = new Date(\"2013-09-17 15:18:53Z\");\n" }, { "answer_id": 20237879, "author": "Safeer Hussain", "author_id": 826611, "author_profile": "https://Stackoverflow.com/users/826611", "pm_score": 2, "selected": false, "text": "var newDate = kendo.parseDate(jsonDate);\n" }, { "answer_id": 25490561, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 2, "selected": false, "text": "var date = new Date(parseInt(/^\\/Date\\((.*?)\\)\\/$/.exec(jsonDate)[1], 10));\n" }, { "answer_id": 31854756, "author": "Luminous", "author_id": 2567273, "author_profile": "https://Stackoverflow.com/users/2567273", "pm_score": 2, "selected": false, "text": "var mydate = json.date\nvar date = new Date(parseInt(mydate.replace(/\\/Date\\((-?\\d+)\\)\\//, '$1');\nmydate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();\n date.getMonth()" }, { "answer_id": 35152855, "author": "Ravi Mehta", "author_id": 2504151, "author_profile": "https://Stackoverflow.com/users/2504151", "pm_score": 4, "selected": false, "text": " function ToJavaScriptDate(value) { //To Parse Date from the Returned Parsed Date\n var pattern = /Date\\(([^)]+)\\)/;\n var results = pattern.exec(value);\n var dt = new Date(parseFloat(results[1]));\n return (dt.getMonth() + 1) + \"/\" + dt.getDate() + \"/\" + dt.getFullYear();\n }\n" }, { "answer_id": 47657364, "author": "Reuel Ribeiro", "author_id": 2561091, "author_profile": "https://Stackoverflow.com/users/2561091", "pm_score": 2, "selected": false, "text": "JS //Only use [0] if you are sure that the string matches the pattern\n//Otherwise, verify if 'match' returns something\n\"/Date(1512488018202)/\".match(/\\d+/)[0] \n" }, { "answer_id": 49189419, "author": "Harun Diluka Heshan", "author_id": 9208617, "author_profile": "https://Stackoverflow.com/users/9208617", "pm_score": 3, "selected": false, "text": "Int Date var dateString = \"/Date(1224043200000)/\";\nvar seconds = parseInt(dateString.replace(/\\/Date\\(([0-9]+)[^+]\\//i, \"$1\"));\nvar date = new Date(seconds);\nconsole.log(date);" }, { "answer_id": 50292370, "author": "Vignesh Subramanian", "author_id": 848841, "author_profile": "https://Stackoverflow.com/users/848841", "pm_score": 2, "selected": false, "text": "function getDateValue(dateVal) {\n return new Date(parseInt(dateVal.replace(/\\D+/g, '')));\n};\n replace(/\\D+/g, '') parseInt $scope.ReturnDate = getDateValue(result.JSONDateVariable)\n" }, { "answer_id": 51208640, "author": "Noor All Safaet", "author_id": 4859275, "author_profile": "https://Stackoverflow.com/users/4859275", "pm_score": 2, "selected": false, "text": "function formatJSONDate(jsonDate) {\n var date = jsonDate;\n var parsedDate = new Date(parseInt(date.toString().substring(6)));\n var newDate = new Date(parsedDate);\n var getMonth = newDate.getMonth() + 1;\n var getDay = newDate.getDay();\n var getYear = newDate.getFullYear(); \n\n var standardDate = (getMonth<10 ? '0' : '') + getMonth + '/' + (getDay<10 ? '0' : '') + getDay + '/' + getYear;\n return standardDate;\n }\n" }, { "answer_id": 56401104, "author": "b_levitt", "author_id": 852208, "author_profile": "https://Stackoverflow.com/users/852208", "pm_score": 3, "selected": false, "text": "/Date(1224043200000)/\n new Date(1224043200000)\n (DateTimeOffset.Parse(\"10/15/2008 00:00:00Z\") - DateTimeOffset.Parse(\"1/1/1970 00:00:00Z\")).TotalMilliseconds;\n function adjustToLocalMidnight(serverMidnight){ \n var serverOffset=-240; //injected from model? <-- DateTimeOffset.Now.Offset.TotalMinutes\n var localOffset=-(new Date()).getTimezoneOffset(); \n return new Date(date.getTime() + (serverOffset-localOffset) * 60 * 1000)\n}\n\nvar localMidnightDate = adjustToLocalMidnight(new Date(parseInt(jsonDate.substr(6))));\n" }, { "answer_id": 61235930, "author": "suhas sasuke", "author_id": 9129689, "author_profile": "https://Stackoverflow.com/users/9129689", "pm_score": 0, "selected": false, "text": "val dataString = \"/Date(1586583441106)/\"\nval date = Date(Long.parseLong(dataString.substring(6, dataString.length - 2)))\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
206,400
<p>Is there a way to specify which monitor a application appears on in Delphi or C++Builder? </p> <p>I am developing a simple program for a customer, which displays kitchen orders on a secondary monitor, generated by a hospitality system. Currently they need to manually drag the window onto the second monitor after it starts.</p>
[ { "answer_id": 206658, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 5, "selected": false, "text": "// Put the form in the upper left corner of the 2nd monitor\n// if more then one monitor is present.\nif Screen.MonitorCount > 1 then\nbegin\n Left := Screen.Monitors[1].Left;\n Top := Screen.Monitors[1].Top;\nend;\n" }, { "answer_id": 209131, "author": "Uwe Raabe", "author_id": 26833, "author_profile": "https://Stackoverflow.com/users/26833", "pm_score": -1, "selected": false, "text": "procedure TForm18.FormCreate(Sender: TObject);\nvar\n Mon: TMonitor;\n MonitorIdx: Integer;\nbegin\n MonitorIdx := 1; // better read from configuration\n if (MonitorIdx <> Monitor.MonitorNum) and (MonitorIdx < Screen.MonitorCount) then begin\n Mon := Screen.Monitors[MonitorIdx];\n Left := Left + Mon.Left - Monitor.Left;\n Top := Top + Mon.Top - Monitor.Top;\n end;\nend;\n" }, { "answer_id": 5001063, "author": "sukhoy", "author_id": 617390, "author_profile": "https://Stackoverflow.com/users/617390", "pm_score": 2, "selected": false, "text": "procedure TMDIChild.btnShowMonClick(Sender: TObject);\nbegin\n if Screen.MonitorCount > 1 then\n begin\n FormShow.Left:=Screen.Monitors[1].Left;\n FormShow.Top:=Screen.Monitors[1].Top;\n FormShow.Width:=Screen.Monitors[1].Width;\n FormShow.Height:=Screen.Monitors[1].Height;\n end\n else\n begin\n FormShow.Show;\n end;\nend;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5891/" ]
206,401
<p>i want to call a series of .sql scripts to create the initial database structure</p> <ol> <li>script1.sql</li> <li>script2.sql etc.</li> </ol> <p>is there any way of doing this without sqlcmd or stored procedures <strong>or any other kind of code that is not sql</strong> ? just inside a .sql file.</p>
[ { "answer_id": 273079, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 2, "selected": false, "text": "Sub ExecuteSqlScript(FilePath As String)\n\n Dim Script As String\n Dim FileNumber As Integer\n Dim Delimiter As String\n Dim aSubscript() As String\n Dim Subscript As String\n Dim i As Long\n\n Delimiter = \";\"\n FileNumber = FreeFile\n Script = String(FileLen(FilePath), vbNullChar)\n\n ' Grab the scripts inside the file\n Open FilePath For Binary As #FileNumber\n Get #FileNumber, , Script\n Close #FileNumber\n\n ' Put the scripts into an array\n aSubscript = Split(Script, Delimiter)\n\n ' Run each script in the array\n For i = 0 To UBound(aSubscript) - 1\n aSubscript(i) = Trim(aSubscript(i))\n Subscript = aSubscript(i)\n CurrentProject.Connection.Execute Subscript\n\n Next i\n\nEnd Sub\n" }, { "answer_id": 433701, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 4, "selected": false, "text": "exec master..xp_cmdshell 'osql -E -ix:\\path\\filename.sql'\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15193/" ]
206,402
<p>Every morning we have a process that issues numerous queries (~10000) to DB2 on an AS400/iSeries/i6 (whatever IBM calls it nowadays), in the last 2 months, the operators have been complaining that our query locks a couple of files preventing them from completing their nightly processing. The queries are very simplisitic, e.g</p> <pre><code>Select [FieldName] from OpenQuery('&lt;LinkedServerName&gt;', 'Select [FieldName] from [LibraryName].[FieldName] where [SomeField]=[SomeParameter]') </code></pre> <p>I am not an expert on the iSeries side of the house and was wondering if anyone had any insight on lock escalation from an AS400/Db2 perspective. The ID that is causing the lock has been confirmed to be the ID we registered our linked server as and we know its most likely us because the [Library] and [FileName] are consistent with the query we are issuing.</p> <p>This has just started happening recently. Is it possible that our select statements which are causing the AS400 to escalate locks? The problem is they are not being released without manual intervention. </p>
[ { "answer_id": 231823, "author": "Paul Morgan", "author_id": 16322, "author_profile": "https://Stackoverflow.com/users/16322", "pm_score": 0, "selected": false, "text": "<linkedServerName>" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7280/" ]
206,405
<p>I like to have my code warning free for VS.NET and GCC, and I like to have my code 64-bit ready.</p> <p>Today I wrote a little module that deals with in memory buffers and provides access to the data via a file-style interface (e.g. you can read bytes, write bytes, seek around etc.).</p> <p>As the data-type for current read position and size I used size_t since that seems to be the most natural choice. I get around the warnings and it ought to work in 64-bit as well. </p> <p>Just in case: My structure looks like this:</p> <pre><code>typedef struct { unsigned char * m_Data; size_t m_CurrentReadPosition; size_t m_DataSize; } MyMemoryFile; </code></pre> <p>The signedness of <code>size_t</code> seems not to be defined in practice. A Google code-search proved that.</p> <p>Now I'm in a dilemma: I want to check additions with <code>size_t</code> for overflows because I have to deal with user supplied data and third party libraries will use my code. However, for the overflow check I have to know the sign-ness. It makes a huge difference in the implementation. </p> <p>So - how the heck should I write such a code in a platform and compiler independent way? </p> <p>Can I check the signedness of <code>size_t</code> at run or compile-time? That would solve my problem. Or maybe <code>size_t</code> wasn't the best idea in the first place.</p> <p>Any ideas?</p> <p><strong>EDIT</strong>: I'm looking for a solution for the C-language!</p>
[ { "answer_id": 206422, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 3, "selected": false, "text": "size_t ssize_t" }, { "answer_id": 206442, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "char CouldBlowUp(char a, char b, char c)\n{\n SafeInt<char> sa(a), sb(b), sc(c);\n\n try\n {\n return (sa * sb + sc).Value();\n }\n catch(SafeIntException err)\n {\n ComplainLoudly(err.m_code);\n }\n\n return 0;\n}\n" }, { "answer_id": 206460, "author": "Francisco Soto", "author_id": 3695, "author_profile": "https://Stackoverflow.com/users/3695", "pm_score": -1, "selected": false, "text": "temp = value_to_be_added_to;\n\nvalue_to_be_added_to += value_to_add;\n\nif (temp > value_to_be_added_to)\n{\n overflow...\n}\n" }, { "answer_id": 206494, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 3, "selected": false, "text": "size_t size_t if (a + b < a) size_t" }, { "answer_id": 206584, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "size size_t size_t size_t stddef.h sys/types.h size_t sys/types.h size_t size_t size_t size_t sys/types.h size_t size_t size_t ptrdiff_t ssize_t" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
206,420
<p>I am building a simple HTTP server for a project. Most websites have custom 404 error pages. Sometimes though, you'll see Firefox spitting a generic 404 page (or 405, etc...). How does it decide what to do? What should the HTTP response be? Is "HTTP/1.0 404 NOT FOUND" enough?</p> <p>Thanks</p>
[ { "answer_id": 206562, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 3, "selected": false, "text": "<HTML>\n<head>\n<meta HTTP-EQUIV=\"Refresh\" CONTENT=\"5; URL=not404.htm\">\n</head>\n</HTML>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25645/" ]
206,438
<p>I have a business requirement that forces me to store a customer's full credit card details (number, name, expiry date, CVV2) for a short period of time.</p> <p>Rationale: If a customer calls to order a product and their credit card is declined on the spot you are likely to lose the sale. If you take their details, thank them for the transaction and then find that the card is declined, you can phone them back and they are more likely to find another way of paying for the product. If the credit card is accepted you clear the details from the order.</p> <p>I cannot change this. The existing system stores the credit card details in clear text, and in the new system I am building to replace this I am clearly <em>not</em> going to replicate this!</p> <p>My question, then, is how I can securely store a credit card for a short period of time. I obviously want some kind of encryption, but what's the best way to do this?</p> <p>Environment: C#, WinForms, SQL-Server.</p>
[ { "answer_id": 206810, "author": "sallen", "author_id": 15002, "author_profile": "https://Stackoverflow.com/users/15002", "pm_score": 3, "selected": false, "text": "// Make a SecureString\nSecureString sPassphrase = new SecureString();\nConsole.WriteLine(\"Please enter your passphrase\");\nConsoleKeyInfo input = Console.ReadKey(true);\nwhile (input.Key != ConsoleKey.Enter)\n{\n sPassphrase.AppendChar(input.KeyChar);\n Console.Write('*');\n input = Console.ReadKey(true);\n}\nsPassphrase.MakeReadOnly();\n\n// Recover plaintext from a SecureString\n// Marshal is in the System.Runtime.InteropServices namespace\ntry {\n IntPtr ptrPassphrase = Marshal.SecureStringToBSTR(sPassphrase);\n string uPassphrase = Marshal.PtrToStringUni(ptrPassphrase);\n // ... use the string ...\n}\ncatch {\n // error handling\n} \nfinally {\n Marshal.ZeroFreeBSTR(ptrPassphrase);\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/826/" ]
206,440
<p>Are there any classes in the .NET framework I can use to throw an event if time has caught up with a specified DateTime object?</p> <p>If there isn't, what are the best practices when checking this? Create a new thread constantly checking? A timer (heaven forbid ;) )?</p>
[ { "answer_id": 206487, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 0, "selected": false, "text": " DateTime future = DateTime.Now.Add(TimeSpan.FromSeconds(30));\n new Thread(() =>\n {\n Thread.Sleep(future - DateTime.Now);\n //RaiseEvent();\n }).Start();\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ]
206,441
<p>What are the best online code beautifier and formatter out there? I'm not asking for highlighters. Any language will do.</p>
[ { "answer_id": 206457, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "indent" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70/" ]
206,447
<p>I am trying to use a class from a C# assembly in vb.net. The class has ambiguous members because vb.net is case insensitive. The class is something like this:</p> <pre> public class Foo { public enum FORMAT {ONE, TWO, THREE}; public FORMAT Format { get {...} set {...} } } </pre> <p>I try to access the enum: Foo.FORMAT.ONE</p> <p>This is not possible because there is also a property named 'format'.</p> <p>I can not change the C# assembly. How can I get around this and reference the enum from vb.net?</p>
[ { "answer_id": 206475, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": true, "text": "CLSCompliant(true)" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10034/" ]
206,469
<p>Need a refresher on bits/bytes, hex notation and how it relates to programming (C# preferred).</p> <p>Looking for a good reading list (online preferably).</p>
[ { "answer_id": 1128731, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": "[0,5], [-3.3, 3], [-5, 5], [0, 1.3] 1111 1111 F & outputByte 15 & outputByte char a, b, c; \nc = a ^ b; //XOR\nc = a & b; //AND\nc = a | b; //OR\nc = ~(a & b); //NOT AND(NAND)\nc = ~a; //NOT\nc = a << 2; //Left shift 2 places\nc = a >> 2; //Right shift 2 places.\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,473
<p>Is there a way to compile an Eclipse-based Java project from the command line? </p> <p>I'm trying to automate my build (using FinalBuilder not ant), and I'm neither a Java nor Eclipse expert. I can probably figure out how to do this with straight java command line options, but then the Eclipse project feels like a lot of wasted effort. </p> <p>In the event that there is no way to compile an Eclipse project via the command line, is there a way to generate the required java command line from within Eclipse? Or are there some files I can poke around to find the compile steps it is doing behind the scenes? </p> <hr> <p>Guys, I'm looking for an answer that does <em>NOT</em> include ant. Let me re-iterate the original question ....... Is there a way to build an Eclipse project from the command line?</p> <p>I don't think this is an unreasonable question given that I can do something like this for visual studio:</p> <pre><code>devenv.exe /build "Debug|Any CPU" "C:\Projects\MyProject\source\MyProject.sln" </code></pre>
[ { "answer_id": 206587, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": false, "text": " <javac\n srcdir=\"${src}\"\n destdir=\"${build.dir}/classes\"> \n <compilerarg \n compiler=\"org.eclipse.jdt.core.JDTCompilerAdapter\" \n line=\"-warn:+unused -Xemacs\"/>\n <classpath refid=\"compile.classpath\" />\n </javac>\n java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data \"C:\\Documents and Settings\\Administrator\\workspace\" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose\n java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java\n java -jar ecj.jar -classpath rt.jar A.java\n" }, { "answer_id": 1433396, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 7, "selected": true, "text": "eclipsec.exe -noSplash -data \"D:\\Source\\MyProject\\workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n jdt apt java -cp startup.jar -noSplash -data \"D:\\Source\\MyProject\\workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n startup.jar java -jar /Applications/Eclipse.app/Contents/Eclipse/plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar -noSplash -data \"workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n -data" }, { "answer_id": 19099609, "author": "Charles Thomas", "author_id": 2812597, "author_profile": "https://Stackoverflow.com/users/2812597", "pm_score": 3, "selected": false, "text": "android list targets (to get target id used below)\n\nandroid update project --target target_id --name project_name --path top_level_directory\n\n ** my sample project had a target_id of 1 and a project name of 't1', and \n I am building from the top level directory of project\n my command line looks like android update project --target 1 --name t1 --path `pwd`\n ant target\n\n this confused me a little bit, because i thought they were talking about the\n android device, but they're not. It's the mode (debug/release)\n my command line looks like ant debug\n ant target install\n\n ** my command line looked like ant debug install\n adb shell 'am start -n your.project.name/.activity'\n\n ** Again there was some confusion as to what exactly I had to use for project \n My command line looked like adb shell 'am start -n com.example.t1/.MainActivity'\n I also found that if you type 'adb shell' you get put to a cli shell interface\n where you can do just about anything from there.\n adb logcat\n" }, { "answer_id": 30632723, "author": "jkwinn26", "author_id": 2157385, "author_profile": "https://Stackoverflow.com/users/2157385", "pm_score": 1, "selected": false, "text": "java -cp startup.jar -noSplash -data \"D:\\Source\\MyProject\\workspace\" -application org.eclipse.jdt.apt.core.aptBuild\n $ECLIPSE_HOME/eclipse -nosplash -application org.eclipse.jdt.apt.core.aptBuild startup.jar -data ~/workspace\n Building workspace\nBuilding '/RemoteSystemsTempFiles'\nBuilding '/test'\nInvoking 'Java Builder' on '/test'.\nCleaning output folder for test\nBuild done\nBuilding workspace\nBuilding '/RemoteSystemsTempFiles'\nBuilding '/test'\nInvoking 'Java Builder' on '/test'.\nPreparing to build test\nCleaning output folder for test\nCopying resources to the output folder\nAnalyzing sources\nCompiling test/src/com/company/test/tool\nBuild done\n" }, { "answer_id": 72432790, "author": "Ashkan Ansarifard", "author_id": 19231107, "author_profile": "https://Stackoverflow.com/users/19231107", "pm_score": 1, "selected": false, "text": "\"%ECLIPSE_IDE%\\eclipsec.exe\" -noSplash -data \"YOUR_WORKSPACE\" -application org.eclipse.jdt.apt.core.aptBuild\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5208/" ]
206,484
<p>I tried searching around, but I couldn't find anything that would help me out.</p> <p>I'm trying to do this in SQL:</p> <pre><code>declare @locationType varchar(50); declare @locationID int; SELECT column1, column2 FROM viewWhatever WHERE CASE @locationType WHEN 'location' THEN account_location = @locationID WHEN 'area' THEN xxx_location_area = @locationID WHEN 'division' THEN xxx_location_division = @locationID </code></pre> <p>I know that I shouldn't have to put '= @locationID' at the end of each one, but I can't get the syntax even close to being correct. SQL keeps complaining about my '=' on the first WHEN line...</p> <p>How can I do this?</p>
[ { "answer_id": 206500, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 9, "selected": true, "text": "declare @locationType varchar(50);\ndeclare @locationID int;\n\nSELECT column1, column2\nFROM viewWhatever\nWHERE\n@locationID = \n CASE @locationType\n WHEN 'location' THEN account_location\n WHEN 'area' THEN xxx_location_area \n WHEN 'division' THEN xxx_location_division \n END\n" }, { "answer_id": 206518, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 3, "selected": false, "text": "SELECT\n *\nFROM\n Test\nWHERE\n Account_Location = (\n CASE LocationType\n WHEN 'location' THEN @locationID\n ELSE Account_Location\n END\n )\n AND\n Account_Location_Area = (\n CASE LocationType\n WHEN 'area' THEN @locationID\n ELSE Account_Location_Area\n END\n )\n" }, { "answer_id": 206520, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 3, "selected": false, "text": "WHERE account_location = CASE @locationType\n WHEN 'business' THEN 45\n WHEN 'area' THEN 52\n END\n" }, { "answer_id": 206712, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 6, "selected": false, "text": "SELECT\n column1, \n column2\nFROM\n viewWhatever\nWHERE\nCASE \n WHEN @locationType = 'location' AND account_location = @locationID THEN 1\n WHEN @locationType = 'area' AND xxx_location_area = @locationID THEN 1\n WHEN @locationType = 'division' AND xxx_location_division = @locationID THEN 1\n ELSE 0\nEND = 1\n" }, { "answer_id": 858666, "author": "Lukek", "author_id": 106180, "author_profile": "https://Stackoverflow.com/users/106180", "pm_score": 6, "selected": false, "text": "SELECT column1, column2\nFROM viewWhatever\nWHERE\n (@locationType = 'location' AND account_location = @locationID)\n OR\n (@locationType = 'area' AND xxx_location_area = @locationID)\n OR\n (@locationType = 'division' AND xxx_location_division = @locationID)\n" }, { "answer_id": 6183682, "author": "Durre Najaf", "author_id": 777162, "author_profile": "https://Stackoverflow.com/users/777162", "pm_score": 2, "selected": false, "text": "select @msgID, account_id\n from viewMailAccountsHeirachy\n where \n CASE @smartLocationType\n WHEN 'store' THEN account_location\n WHEN 'area' THEN xxx_location_area \n WHEN 'division' THEN xxx_location_division \n WHEN 'company' THEN xxx_location_company \n END = @smartLocation\n" }, { "answer_id": 9031189, "author": "shah134pk", "author_id": 1173161, "author_profile": "https://Stackoverflow.com/users/1173161", "pm_score": 2, "selected": false, "text": "WHERE (\n @smartLocationType IS NULL \n OR account_location = (\n CASE\n WHEN @smartLocationType IS NOT NULL \n THEN @smartLocationType\n ELSE account_location \n END\n )\n)\n" }, { "answer_id": 28297668, "author": "Mike Clark", "author_id": 4261022, "author_profile": "https://Stackoverflow.com/users/4261022", "pm_score": -1, "selected": false, "text": "CREATE TABLE PersonsDetail(FirstName nvarchar(20), LastName nvarchar(20), GenderID int);\nGO\n\nINSERT INTO PersonsDetail VALUES(N'Gourav', N'Bhatia', 2),\n (N'Ramesh', N'Kumar', 1),\n (N'Ram', N'Lal', 2),\n (N'Sunil', N'Kumar', 3),\n (N'Sunny', N'Sehgal', 1),\n (N'Malkeet', N'Shaoul', 3),\n (N'Jassy', N'Sohal', 2);\nGO\n\nSELECT FirstName, LastName, Gender =\n CASE GenderID\n WHEN 1 THEN 'Male'\n WHEN 2 THEN 'Female'\n ELSE 'Unknown'\n END\nFROM PersonsDetail\n" }, { "answer_id": 30701950, "author": "kavitha Reddy", "author_id": 3073215, "author_profile": "https://Stackoverflow.com/users/3073215", "pm_score": -1, "selected": false, "text": "Case Statement in SQL Server Example\n\nSyntax\n\nCASE [ expression ]\n\n WHEN condition_1 THEN result_1\n WHEN condition_2 THEN result_2\n ...\n WHEN condition_n THEN result_n\n\n ELSE result\n\nEND\n\nExample\n\nSELECT contact_id,\nCASE website_id\n WHEN 1 THEN 'TechOnTheNet.com'\n WHEN 2 THEN 'CheckYourMath.com'\n ELSE 'BigActivities.com'\nEND\nFROM contacts;\n\nOR\n\nSELECT contact_id,\nCASE\n WHEN website_id = 1 THEN 'TechOnTheNet.com'\n WHEN website_id = 2 THEN 'CheckYourMath.com'\n ELSE 'BigActivities.com'\nEND\nFROM contacts;\n" }, { "answer_id": 32334349, "author": "Mohammad Atiour Islam", "author_id": 1077346, "author_profile": "https://Stackoverflow.com/users/1077346", "pm_score": 3, "selected": false, "text": "ALTER PROCEDURE [dbo].[RPT_340bClinicDrugInventorySummary]\n -- Add the parameters for the stored procedure here\n @ClinicId BIGINT = 0,\n @selecttype int,\n @selectedValue varchar (50)\nAS\nBEGIN\n-- SET NOCOUNT ON added to prevent extra result sets from\n-- interfering with SELECT statements.\nSET NOCOUNT ON;\nSELECT\n drugstock_drugname.n_cur_bal,drugname.cdrugname,clinic.cclinicname\n\nFROM drugstock_drugname\nINNER JOIN drugname ON drugstock_drugname.drugnameid_FK = drugname.drugnameid_PK\nINNER JOIN drugstock_drugndc ON drugname.drugnameid_PK = drugstock_drugndc.drugnameid_FK\nINNER JOIN drugndc ON drugstock_drugndc.drugndcid_FK = drugndc.drugid_PK\nLEFT JOIN clinic ON drugstock_drugname.clinicid_FK = clinic.clinicid_PK\n\nWHERE (@ClinicId = 0 AND 1 = 1)\n OR (@ClinicId != 0 AND drugstock_drugname.clinicid_FK = @ClinicId)\n\n -- Alternative Case When You can use OR\n AND ((@selecttype = 1 AND 1 = 1)\n OR (@selecttype = 2 AND drugname.drugnameid_PK = @selectedValue)\n OR (@selecttype = 3 AND drugndc.drugid_PK = @selectedValue)\n OR (@selecttype = 4 AND drugname.cdrugclass = 'C2')\n OR (@selecttype = 5 AND LEFT(drugname.cdrugclass, 1) = 'C'))\n\nORDER BY clinic.cclinicname, drugname.cdrugname\nEND\n" }, { "answer_id": 62828645, "author": "Darshan Balar", "author_id": 13903887, "author_profile": "https://Stackoverflow.com/users/13903887", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE [dbo].[Temp_Proc_Select_City]\n @StateId INT\nAS \n BEGIN \n SELECT * FROM tbl_City \n WHERE \n @StateID = CASE WHEN ISNULL(@StateId,0) = 0 THEN 0 ELSE StateId END ORDER BY CityName\n END\n" }, { "answer_id": 64345237, "author": "Omid Karami", "author_id": 4519223, "author_profile": "https://Stackoverflow.com/users/4519223", "pm_score": 0, "selected": false, "text": "USE tempdb\nGO\n\nIF NOT OBJECT_ID('Tempdb..Contacts') IS NULL\n DROP TABLE Contacts\n\nCREATE TABLE Contacts(ID INT, FirstName VARCHAR(100), LastName VARCHAR(100))\nINSERT INTO Contacts (ID, FirstName, LastName)\nSELECT 1, 'Omid', 'Karami'\nUNION ALL\nSELECT 2, 'Alen', 'Fars'\nUNION ALL\nSELECT 3, 'Sharon', 'b'\nUNION ALL\nSELECT 4, 'Poja', 'Kar'\nUNION ALL\nSELECT 5, 'Ryan', 'Lasr'\nGO\n \nDECLARE @FirstName VARCHAR(100)\nSET @FirstName = 'Omid'\n \nDECLARE @LastName VARCHAR(100)\nSET @LastName = '' \n \nSELECT FirstName, LastName\nFROM Contacts\nWHERE \n FirstName = CASE\n WHEN LEN(@FirstName) > 0 THEN @FirstName \n ELSE FirstName \n END\nAND\n LastName = CASE\n WHEN LEN(@LastName) > 0 THEN @LastName \n ELSE LastName\n END\nGO\n" }, { "answer_id": 66486829, "author": "Mark Longmire", "author_id": 933260, "author_profile": "https://Stackoverflow.com/users/933260", "pm_score": -1, "selected": false, "text": "\nCREATE TABLE PER_CAL ( CAL_YEAR INT, CAL_PER INT )\nINSERT INTO PER_CAL( CAL_YEAR, CAL_PER ) VALUES ( 20,1 ), ( 20,2 ), ( 20,3 ), ( 20,4 ), ( 20,5 ), ( 20,6 ), ( 20,7 ), ( 20,8 ), ( 20,9 ), ( 20,10 ), ( 20,11 ), ( 20,12 ), \n( 99,1 ), ( 99,2 ), ( 99,3 ), ( 99,4 ), ( 99,5 ), ( 99,6 ), ( 99,7 ), ( 99,8 ), ( 99,9 ), ( 99,10 ), ( 99,11 ), ( 99,12 )\n \n-- 1st quarter of 2020\nSELECT * FROM PER_CAL WHERE (( CASE WHEN CAL_YEAR > 50 THEN 1900 ELSE 2000 END + CAL_YEAR ) * 100 + CAL_PER ) BETWEEN 202001 AND 202003\n-- 4th quarter of 1999\nSELECT * FROM PER_CAL WHERE (( CASE WHEN CAL_YEAR > 50 THEN 1900 ELSE 2000 END + CAL_YEAR ) * 100 + CAL_PER ) BETWEEN 199910 AND 199912\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21828/" ]
206,490
<p>I need to index a varchar field on my table in MS SQL Server 2005, but it's not clear to me how to do so. If I try to add a non-clustered index on the field, it says "Column 'xxxx' in table 'mytable' is of a type that is invalid for use as a key column in an index"</p> <p>My table has an auto-increment int ID that is set as the primary key on the table. If I set this property as the index, and then add my varchar column as an "included column", the index goes through. But I'm not sure that's what I want - I want to be able to search the table based on the varchar field alone, and my understanding of indexes was that all indexed elements had to be provided to actually see a speedup in the query, but I don't want to have to included the int ID (because I don't know what it is, at the time of this given query).</p> <p>Am I trying to do this incorrectly? Would the ID + my varchar as an included column accomplish what I am looking for?</p>
[ { "answer_id": 206530, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": true, "text": "varchar(max) CREATE TABLE varchar" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
206,495
<p>I have a listbox containing and image and a button. By default the button is hidden. I want to make the button visible whenever I hover over an item in the listbox. The XAML I am using is below. Thanks</p> <pre><code>&lt;Window.Resources&gt; &lt;Style TargetType="{x:Type ListBox}"&gt; &lt;Setter Property="ItemTemplate"&gt; &lt;Setter.Value&gt; &lt;DataTemplate&gt; &lt;Border BorderBrush="Black" BorderThickness="1" Margin="6"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Image Source="{Binding Path=FullPath}" Height="150" Width="150"/&gt; &lt;Button x:Name="sideButton" Width="20" Visibility="Hidden"/&gt; &lt;/StackPanel&gt; &lt;/Border&gt; &lt;/DataTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/Window.Resources&gt; </code></pre>
[ { "answer_id": 206537, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": false, "text": "<Button x:Name=\"sideButton\" Width=\"20\">\n <Button.Style>\n <Style TargetType=\"{x:Type Button}\">\n <Setter Property=\"Visibility\" Value=\"Hidden\" />\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsMouseOver}\" Value=\"True\">\n <Setter Property=\"Visibility\" Value=\"Visible\" />\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </Button.Style>\n</Button>\n ListBoxItem IsMouseOver True button Visible" }, { "answer_id": 207670, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 4, "selected": false, "text": "Style ListBoxItem TemplatedParent IsMouseOver TargetName Setter Button <Style TargetType=\"{x:Type ListBoxItem}\">\n <Setter Property=\"ContentTemplate\">\n <Setter.Value>\n <DataTemplate>\n <Border BorderBrush=\"Black\"\n BorderThickness=\"1\"\n Margin=\"6\">\n <StackPanel Orientation=\"Horizontal\">\n <Image Source=\"{Binding Path=FullPath}\"\n Height=\"150\"\n Width=\"150\" />\n <Button x:Name=\"sideButton\"\n Width=\"20\"\n Visibility=\"Hidden\" />\n </StackPanel>\n </Border>\n <DataTemplate.Triggers>\n <DataTrigger Binding=\"{Binding IsMouseOver,RelativeSource={RelativeSource TemplatedParent}}\"\n Value=\"True\">\n <Setter Property=\"Visibility\"\n TargetName=\"sideButton\"\n Value=\"Visible\" />\n </DataTrigger>\n </DataTemplate.Triggers>\n </DataTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n" }, { "answer_id": 207860, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 3, "selected": false, "text": " <Style TargetType=\"{x:Type ListBoxItem}\">\n <Setter Property=\"ContentTemplate\">\n <Setter.Value>\n <DataTemplate>\n <Border BorderBrush=\"Black\"\n BorderThickness=\"1\"\n Margin=\"6\">\n <StackPanel Orientation=\"Horizontal\">\n <Image Source=\"{Binding Path=FullPath}\"\n Height=\"150\"\n Width=\"150\" /> \n </StackPanel>\n </Border>\n </DataTemplate>\n </Setter.Value>\n </Setter> \n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type ListBoxItem}\">\n <Grid Background=\"Transparent\">\n <Button x:Name=\"sideButton\" Width=\"20\" HorizontalAlignment=\"Right\" Visibility=\"Hidden\" />\n <ContentPresenter/> \n </Grid>\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsMouseOver\" Value=\"True\">\n <Setter Property=\"Visibility\"\n TargetName=\"sideButton\"\n Value=\"Visible\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter> \n </Style>\n" }, { "answer_id": 2242456, "author": "donovan", "author_id": 533213, "author_profile": "https://Stackoverflow.com/users/533213", "pm_score": 0, "selected": false, "text": " DependencyObject dep = (DependencyObject)e.OriginalSource;\n while ((dep != null) && !(dep is ListBoxItem))\n {\n dep = VisualTreeHelper.GetParent(dep);\n }\n\n if (dep != null)\n {\n // TODO: do stuff with the item here.\n }\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,528
<p>I have this function in my Javascript Code that updates html fields with their new values whenever it is called. The problem cannot be with the function itself because it works brilliantly in every section except for one. Here is the JS function:</p> <pre><code> function updateFields() { document.getElementById('bf').innerHTML = bill.time[breakfast][bill.pointPartOfWeek]; document.getElementById('ln').innerHTML = bill.time[lunch][bill.pointPartOfWeek]; document.getElementById('dn').innerHTML = bill.time[dinner][bill.pointPartOfWeek]; document.getElementById('se').innerHTML = bill.time[special][bill.pointPartOfWeek]; document.getElementById('fdr').innerHTML = bill.time[full][bill.pointPartOfWeek]; document.getElementById('cost').innerHTML = bill.cost; } </code></pre> <p>And it executes fine in the following instance:</p> <pre><code> &lt;select onchange='if(this.selectedIndex == 0) {bill.unholiday();updateFields()} else { bill.holiday();updateFields()}' id='date' name='date'&gt; &lt;option value='else'&gt;Jan. 02 - Nov. 20&lt;/option&gt; &lt;option value='christmas'&gt;Nov. 20 - Jan. 01&lt;/option&gt; &lt;/select&gt; </code></pre> <p>but in this very similar code, the last line of the function doesn't seem to execute (it doesn't update the cost field, but updates everything else)</p> <pre><code> &lt;select onchange='if(this.selectedIndex == 0) {bill.pointPartOfWeek = 1;} else { bill.pointPartOfWeek = 2;}updateFields();alert(updateFields());' id='day' name='day'&gt; &lt;option value='0'&gt;Monday thru Thursday&lt;/option&gt; &lt;option value='1'&gt;Friday, Saturday, or Sunday&lt;/option&gt; &lt;/select&gt; &lt;br /&gt; </code></pre> <p>Strangely enough, the total cost variable itself is updated, but the field that represents the variable is not. If you use another section of the page that wouldn't change the value of the total cost but calls the updateFields function again, the cost field then updates correctly. It must be an issue with the function called. </p> <p>Note: we know that the function executes because it does 5 out of 6 of the things it is supposed to do. This is a strange issue. </p> <p>Edit: The pastebin for the entire page my be helpful. Here it is:</p> <p><a href="http://pastebin.com/f70d584d3" rel="nofollow noreferrer">http://pastebin.com/f70d584d3</a></p>
[ { "answer_id": 206653, "author": "DocileWalnut", "author_id": 28302, "author_profile": "https://Stackoverflow.com/users/28302", "pm_score": 1, "selected": false, "text": "document.getElementById('bf')\n $('bf')\n $('bf').update(bill.time[breakfast][bill.pointPartOfWeek]);\n" }, { "answer_id": 206895, "author": "objectivesea", "author_id": 27763, "author_profile": "https://Stackoverflow.com/users/27763", "pm_score": 0, "selected": false, "text": "this.setRoom(this.pointPartOfDay,this.pointPartOfWeek);\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27763/" ]
206,558
<p>I continually get these errors when I try to update tables based on another table. I end up rewriting the query, change the order of joins, change some groupings and then it eventually works, but I just don't quite get it.</p> <p>What is a 'multi-part identifier'?<br> When is a 'multi-part identifier' not able to be bound?<br> What is it being bound to anyway?<br> In what cases will this error occur?<br> What are the best ways to prevent it? </p> <p>The specific error from SQL Server 2005 is:</p> <blockquote> <p>The multi-part identifier "..." could not be bound.</p> </blockquote> <p>Here is an example:</p> <pre><code>UPDATE [test].[dbo].[CompanyDetail] SET Mnemonic = [dbBWKMigration].[dbo].[Company].[MNEMONIC], [Company Code] = [dbBWKMigration].[dbo].[Company].[COMPANYCODE] WHERE [Company Name] = **[dbBWKMigration].[dbo].[Company].[COMPANYNAME]** </code></pre> <p>The actual error:</p> <blockquote> <p>Msg 4104, Level 16, State 1, Line 3 The multi-part identifier "dbBWKMigration.dbo.Company.COMPANYNAME" could not be bound.</p> </blockquote>
[ { "answer_id": 6143015, "author": "jo-mso", "author_id": 771804, "author_profile": "https://Stackoverflow.com/users/771804", "pm_score": 3, "selected": false, "text": "Table1 t1, Table2 t2 \nwhere t1.ID = t2.ID\n Table1, Table2 \nwhere Table1.ID = Table2.ID\n" }, { "answer_id": 6414061, "author": "amadelle", "author_id": 806967, "author_profile": "https://Stackoverflow.com/users/806967", "pm_score": 6, "selected": false, "text": "Update Table1\nSet SomeField = t2.SomeFieldValue \nFrom Table1 t1 \nInner Join Table2 as t2\n On t1.ID = t2.ID\n SomeField t1 t1.SomeField SomeField t1.SomeField" }, { "answer_id": 11111430, "author": "Upio", "author_id": 1467869, "author_profile": "https://Stackoverflow.com/users/1467869", "pm_score": 2, "selected": false, "text": "update [page] \nset p.pagestatusid = 1\nfrom [page] p\njoin seed s on s.seedid = p.seedid\nwhere s.providercode = 'agd'\nand p.pagestatusid = 0\n update [page] \nset pagestatusid = 1\nfrom [page] p\njoin seed s on s.seedid = p.seedid\nwhere s.providercode = 'agd'\nand p.pagestatusid = 0\n" }, { "answer_id": 14902629, "author": "unnknown", "author_id": 614263, "author_profile": "https://Stackoverflow.com/users/614263", "pm_score": 2, "selected": false, "text": "SELECT * FROM schema.CustomerOrders co\nWHERE schema.co.ID = 1 -- oops!\n" }, { "answer_id": 44765141, "author": "Andrew Day", "author_id": 3200163, "author_profile": "https://Stackoverflow.com/users/3200163", "pm_score": 1, "selected": false, "text": "P.PayeeName AS 'Payer' --," }, { "answer_id": 46045037, "author": "MT_Shikomba", "author_id": 7652487, "author_profile": "https://Stackoverflow.com/users/7652487", "pm_score": 1, "selected": false, "text": " CREATE VIEW reserved_passangers AS\n SELECT dbo.Passenger.PassName, dbo.Passenger.Address1, dbo.Passenger.Phone\n FROM dbo.Passenger, dbo.Reservation, dbo.Flight\n WHERE (dbo.Passenger.PassNum = dbo.Reservation.PassNum) and\n (dbo.Reservation.Flightdate = 'January 15 2004' and Flight.FlightNum =562)\n CREATE VIEW reserved_passangers AS\n SELECT dbo.Passenger.PassName, dbo.Passenger.Address1, dbo.Passenger.Phone\n FROM dbo.Passenger, dbo.Reservation\n WHERE (dbo.Passenger.PassNum = dbo.Reservation.PassNum) and\n (dbo.Reservation.Flightdate = 'January 15 2004' and Flight.FlightNum = 562)\n" }, { "answer_id": 48294922, "author": "Onkar Vidhate", "author_id": 8765669, "author_profile": "https://Stackoverflow.com/users/8765669", "pm_score": 1, "selected": false, "text": "FROM \n dbo.Category C LEFT OUTER JOIN \n dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN \n dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN \n dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN \n dbo.trainer ON dbo.trainer.TopicID =dbo.SubModule.subModuleID \n FROM \n dbo.Category C LEFT OUTER JOIN \n dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN \n dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN \n dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN \n dbo.trainer ON dbo.trainer.TopicID = SM.subModuleID \n dbo.SubModule dbo.SubModule" }, { "answer_id": 53438852, "author": "Malhaar Punjabi", "author_id": 6918303, "author_profile": "https://Stackoverflow.com/users/6918303", "pm_score": 2, "selected": false, "text": "Update Table1\nSet SomeField = t2.SomeFieldValue \nFrom Table1 t1 \nInner Join Table2 as t2\n On t1.ID = t2.ID\n Update Table1\nSet t1.SomeField = t2.SomeFieldValue \nFrom Table1 t1 \nInner Join Table2 as t2\n On t1.ID = t2.ID\n" }, { "answer_id": 60162574, "author": "Neloy Sarothi", "author_id": 12461803, "author_profile": "https://Stackoverflow.com/users/12461803", "pm_score": 1, "selected": false, "text": " select * from tbTest where email = sakira@gmail.com\n select * from tbTest where email = 'sakira@gmail.com'\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73794/" ]
206,564
<p><em>[This question is related to but not the same as <a href="https://stackoverflow.com/questions/206106/is-a-safe-way-to-convert-to-bool-in-c">this one</a>.]</em></p> <p>My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning:</p> <pre><code>long t = 0; bool b = false; b = t; // performance warning: forcing long to bool b = (bool)t; // performance warning b = bool(t); // performance warning b = static_cast&lt;bool&gt;(t); // performance warning b = t ? true : false; // ok, no warning b = t != 0; // ok b = !!t; // ok </code></pre> <p>This is with Visual C++ 2008 but I suspect other compilers may have similar warnings.</p> <p>So my question is: what is the performance implication of casting/converting to <code>bool</code>? Does explicit conversion have better performance in some circumstance (e.g., for certain target architectures or processors)? Does implicit conversion somehow confuse the optimizer?</p> <p>Microsoft's <a href="http://msdn.microsoft.com/en-us/library/b6801kcy.aspx" rel="noreferrer">explanation</a> of their warning is not particularly helpful. They imply that there is a good reason but they don't explain it.</p>
[ { "answer_id": 206570, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "cmp DWORD PTR [whatever], 0\nsetne al\n" }, { "answer_id": 206575, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "template <typename T>\ninline bool to_bool (const T& t)\n { return t ? true : false; }\n" }, { "answer_id": 1064428, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "long t;\nbool b;\nint i;\nsigned char c;\n...\n bool operator!(long) b = t; i = b; isn't the same as c = t; i = c; it's i = !!t; instead of i = t & 0xff ; isn't the same as c = t; i = c; it's i = !!t; c = t; i = c;" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
206,574
<p>Lets say I've got two interchangeable pieces of code and I want to figure out which one of them takes less processor time to execute. How would I do this?</p> <p>To get a very rough estimation I could just put NSLog() calls on either side of the code I wanted to profile, but it seems like the processor being otherwise very busy could skew the results.</p>
[ { "answer_id": 207975, "author": "Ken", "author_id": 17320, "author_profile": "https://Stackoverflow.com/users/17320", "pm_score": 2, "selected": false, "text": "Sampling > Programmatic (Remote) uint64_t startTime, stopTime;\nstartTime = mach_absolute_time();\n\n< work to time goes here >\n\nstopTime = mach_absolute_time();\nlogMachTime_withIdentifier_(stopTime - startTime, @\"10000000 class messages\");\n logMachTime_withIdentifier_ #import <mach/mach_time.h>\nvoid logMachTime_withIdentifier_(uint64_t machTime, NSString *identifier) {\n static double timeScaleSeconds = 0.0;\n if (timeScaleSeconds == 0.0) {\n mach_timebase_info_data_t timebaseInfo;\n if (mach_timebase_info(&timebaseInfo) == KERN_SUCCESS) { // returns scale factor for ns\n double timeScaleMicroSeconds = ((double) timebaseInfo.numer / (double) timebaseInfo.denom) / 1000;\n timeScaleSeconds = timeScaleMicroSeconds / 1000000;\n }\n }\n\n NSLog(@\"%@: %g seconds\", identifier, timeScaleSeconds*machTime);\n}\n" }, { "answer_id": 209569, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 1, "selected": false, "text": "man dtrace NSLog" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
206,577
<p>We are trying to move from using SQL DMO to SMO in our COM+ based application, as we are dropping support for SQL Server 2000 and adding support for SQL Server 2008 in addition to SQL Server 2005. </p> <p>I have been reading around on this, and found this particular quip on <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=289491&amp;SiteID=1" rel="nofollow noreferrer">this microsoft forum:</a></p> <blockquote>"SMO is only supported in VB/C#.Net 2005. It requires the .Net 2.0 Framework, which isn't available in VB/VC 6."</blockquote> <p>Is it true? Googling in general and googling stackoverflow did not throw up and definitive answers.</p> <p>Is it possible to implement SQL SMO using VB6?</p> <p><strong>Edit: I used a COM Wrapper to get around this... check out my answer below for some more details.</strong></p>
[ { "answer_id": 207056, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 2, "selected": false, "text": "param (\n [string] $ServerName,\n [string] $DatabaseName,\n [string] $Backuptype,\n [string] $BackupPath,\n [int] $NumDays\n)\nGet-ChildItem $BackupPath | where {$_.LastWriteTime -le (Get-Date).AddDays(-$NumDays)} | remove-item\n[System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SqlServer.Smo\") | out-null\n[System.IO.Directory]::CreateDirectory($BackupPath) | out-null\n$srv=New-Object \"Microsoft.SqlServer.Management.Smo.Server\" \"$servername\"\n$bck=new-object \"Microsoft.SqlServer.Management.Smo.Backup\"\n\nif ($Backuptype -eq \"FULL\") \n{\n$bck.Action = 'Database' \n$extenstion=\".BAK\" \n$text1=\"Full Backup\"\n}\n\nif ($Backuptype -eq \"TRAN\") \n{\n$bck.Action = 'Log' \n$bck.LogTruncation = 2\n$extenstion=\".TRN\" \n$text1=\"Transactional Log Backup\"\n}\n\nif ($Backuptype -eq \"DIFF\") \n{ \n$bck.Incremental = 1 \n$extenstion=\".DIFF\" \n$text1=\"Differential Backup\"\n}\n\n$fil=new-object \"Microsoft.SqlServer.Management.Smo.BackupDeviceItem\"\n$fil.DeviceType='File'\n$fil.Name=[System.IO.Path]::Combine($BackupPath, $DatabaseName+ \"_\"+ [DateTime]::Now.ToString(\"yyyy_MM_dd_HH_mm\")+$extenstion)\n$bck.Devices.Add($fil)\n$bck.Database=$DatabaseName\n$bck.SqlBackup($srv)\nwrite-host $text1 of $Databasename done\n .\\Backup.ps1 INSTANCENAME DATABASENAME FULL|TRAN|DIFF PATH DAYSTOKEEP\n .\\Backup.ps1 SQLEXPRESS Northwind FULL C:\\TempHold\\Test 30\n.\\Backup.ps1 SQLEXPRESS Northwind TRAN C:\\TempHold\\Test 30\n.\\Backup.ps1 SQLEXPRESS Northwind DIFF C:\\TempHold\\Test 30\n powershell c:\\temphold\\test\\backup.ps1 \"SQLEXPRESS Northwind DIFF C:\\TempHold\\Test 30\"\n" }, { "answer_id": 227659, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 3, "selected": true, "text": "[ComVisible(true)]\n\n[GuidAttribute(\"{guid here}\")]\n\n[ClassInterface(ClassInterfaceType.AutoDual)] // <--- Not recommended, but well...\n" }, { "answer_id": 31995074, "author": "Ved", "author_id": 2484025, "author_profile": "https://Stackoverflow.com/users/2484025", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n [System.Runtime.InteropServices.ComVisible(true)]\n\n[GuidAttribute(\"1d93750c-7465-4a3e-88d1-5e538afe7145\")]\n\n\n\n[ClassInterface(ClassInterfaceType.AutoDual)]\npublic class Class1\n{\n public Class1() { }\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12881/" ]
206,600
<p>This is happening on Vista. I created a new dialog based MFC project to test this. I added a CEdit control to my dialog. I called SetLimitText to let my CEdit receive 100000 characters. I tried both:</p> <pre><code>this-&gt;m_cedit1.SetLimitText(100000); UpdateData(FALSE); </code></pre> <p>and </p> <pre><code>static_cast&lt;CEdit*&gt;(GetDlgItem(IDC_EDIT1))-&gt;LimitText(100000); </code></pre> <p>I placed these calls on InitDialog.</p> <p>after I paste 5461 characters into my CEdit, it becomes empty and unresponsive. Any ideas as to what is causing this and workarounds to be able to paste long strings of text in a CEdit or any other control?</p> <p>note: 5461 is 0x1555 or 1010101010101 in binary, which i find quite odd.</p> <p>if I paste 5460 characters I have no problems.</p>
[ { "answer_id": 421845, "author": "rec", "author_id": 14022, "author_profile": "https://Stackoverflow.com/users/14022", "pm_score": 4, "selected": true, "text": " BOOL ClongeditXPDlg::OnInitDialog()\n {\n CDialog::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n UINT limit = m_longEdit.GetLimitText();\n m_longEdit.SetLimitText(240000);\n UINT limit2 = m_longEdit.GetLimitText();\n\n CString str;\n str = _T(\"\");\n for(int i = 0; i < 250000; i++)\n str += _T(\"a\");\n\n m_longEdit.SetWindowText(str);\n\n return TRUE; // return TRUE unless you set the focus to a control\n }\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14022/" ]
206,608
<p>I'm trying to see if the user has pressed a decimal separator in a text box, and either allow or suppress it depending on other parameters.</p> <p>The NumberdecimalSeparator returns as 46, or '.' on my US system. Many other countries use ',' as the separator. The KeyDown event sets the KeyValue to 190 when I press the period.</p> <p>Do I just continue to look for commas/periods, or is there a better way?</p>
[ { "answer_id": 206649, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator\n CultureInfo.GetCultures(CultureTypes.SpecificCultures).Count() var seps = CultureInfo.GetCultures(CultureTypes.SpecificCultures)\n .Select(ci => ci.NumberFormat.NumberDecimalSeparator)\n .Distinct()\n .ToList();\n keyCode modifiers private bool IsDecimalSeparator(Keys keyCode, Keys modifiers)\n {\n Keys fullKeyCode = keyCode | modifiers;\n if (fullKeyCode.Equals(Keys.Decimal)) // value=110\n return true;\n\n string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;\n if (uiSep.Equals(\".\"))\n return fullKeyCode.Equals(Keys.OemPeriod); // value=190\n else if (uiSep.Equals(\",\"))\n return fullKeyCode.Equals(Keys.Oemcomma); // value=188\n throw new ApplicationException(string.Format(\"Unknown separator found {0}\", uiSep));\n }\n" }, { "answer_id": 207403, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "KeyEventArgs KeyPress KeyPressEventArgs NumberDecimalSeparator" }, { "answer_id": 59545576, "author": "Leonardo Hernández", "author_id": 5848216, "author_profile": "https://Stackoverflow.com/users/5848216", "pm_score": 0, "selected": false, "text": "private void Control_KeyPress(object sender, KeyPressEventArgs e)\n{\n char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];\n if (e.KeyCahr == separador)\n {\n // true\n }\n else\n {\n // false\n }\n}\n private bool decimalSeparator = false;\n private void Control_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.KeyCode == Keys.Decimal)\n decimalSeparator = true;\n }\n\n private void Control_KeyPress(object sender, KeyPressEventArgs e)\n {\n if (decimalSeparator)\n {\n e.KeyChar = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];\n decimalSeparator = false;\n }\n }\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,611
<p>How can I setup a default value to a property defined as follow:</p> <pre><code>public int MyProperty { get; set; } </code></pre> <p>That is using "prop" [tab][tab] in VS2008 (code snippet).</p> <p>Is it possible without falling back in the "old way"?:</p> <pre><code>private int myProperty = 0; // default value public int MyProperty { get { return myProperty; } set { myProperty = value; } } </code></pre> <p>Thanks for your time. Best regards.</p>
[ { "answer_id": 206615, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 4, "selected": true, "text": "public class Person\n{\n public Person()\n {\n this.FirstName = string.Empty;\n }\n\n public string FirstName { get; set; }\n}\n" }, { "answer_id": 34060547, "author": "AllDayPiano", "author_id": 1451100, "author_profile": "https://Stackoverflow.com/users/1451100", "pm_score": 2, "selected": false, "text": "public int MyInt { get; set; } = 0;\npublic string MyString { get; set; } = \"Lorem Ipsum\";\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
206,614
<p><strong>Preface</strong></p> <p>I'm using the newly released Microsoft Virtual Earth SDK v6.2 which has built-in support for pushpin clustering. I realize there are custom ways of doing clustering where my question is easy to answer, but I'd like to leverage the built-in support as much as possible, so this question is specifically related to using the clustering feature of the VE 6.2 SDK.</p> <p><strong>The Problem</strong></p> <p>After enabling the built-in clustering (via VEShapeLayer.SetClusteringConfiguration), the clusters are created as expected, however, they have the default information in them which says something like "X items located here - zoom in to see details". In the app I'm working on, I need to display more information than that - I either need to allow the user to click on the pushpin and VE will automatically zoom in so that the points are now distinct OR display the names of the points in the infobox attached to the cluster pushpin. The catch is that cluster shape that VE creates for me does not appear to be editable until after all of the clustering logic has run...at that point, I don't know what original pushpins belong to that particular cluster. Is there a way to make this happen without resorting to creating a custom clustering implementation?</p>
[ { "answer_id": 206615, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 4, "selected": true, "text": "public class Person\n{\n public Person()\n {\n this.FirstName = string.Empty;\n }\n\n public string FirstName { get; set; }\n}\n" }, { "answer_id": 34060547, "author": "AllDayPiano", "author_id": 1451100, "author_profile": "https://Stackoverflow.com/users/1451100", "pm_score": 2, "selected": false, "text": "public int MyInt { get; set; } = 0;\npublic string MyString { get; set; } = \"Lorem Ipsum\";\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25886/" ]
206,652
<p>I'm working on moving from using tables for layout purposes to using divs (yes, yes the great debate). I've got 3 divs, a header, content and footer. The header and footer are 50px each. How do I get the footer div to stay at the bottom of the page, and the content div to fill the space in between? I don't want to hard code the content divs height because the screen resolution can change.</p>
[ { "answer_id": 209508, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": -1, "selected": false, "text": "#footer {\n clear: both;\n}\n" }, { "answer_id": 210603, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 5, "selected": false, "text": "html, body \n{ \n height: 100%; \n} \n\n#divHeader\n{\n height: 100px;\n}\n\n#divContent\n{\n min-height: 100%; \n height: auto !important; /*Cause footer to stick to bottom in IE 6*/\n height: 100%; \n margin: 0 auto -100px; /*Allow for footer height*/\n vertical-align:bottom;\n}\n\n#divFooter, #divPush\n{\n height: 100px; /*Push must be same height as Footer */\n}\n\n<div id=\"divContent\">\n <div id=\"divHeader\">\n Header\n </div>\n\n Content Text\n\n <div id=\"divPush\"></div>\n</div>\n<div id=\"divFooter\">\n Footer\n</div>\n" }, { "answer_id": 38627224, "author": "Reggie Pinkham", "author_id": 2927114, "author_profile": "https://Stackoverflow.com/users/2927114", "pm_score": 6, "selected": true, "text": "<body>\n <header>\n ...\n </header>\n <main>\n ...\n </main>\n <footer>\n ...\n </footer>\n</body> \n html, body {\n margin: 0;\n height: 100%;\n min-height: 100%;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n}\n\nheader,\nfooter {\n flex: none;\n}\n\nmain {\n overflow-y: scroll;\n -webkit-overflow-scrolling: touch;\n flex: auto;\n}\n" }, { "answer_id": 51147756, "author": "Allen", "author_id": 667335, "author_profile": "https://Stackoverflow.com/users/667335", "pm_score": 2, "selected": false, "text": "<html>\n <head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link href=\"main.css\" rel=\"stylesheet\">\n </head>\n <body>\n <main>\n <header>Header</header>\n <section>Content</section>\n <footer>Footer</footer>\n </main>\n </body>\n</html>\n body {\n margin: 0;\n}\nmain {\n height: 100%;\n display: grid;\n grid-template-rows: 100px auto 100px;\n}\nsection {\n height: 100%;\n}\n" }, { "answer_id": 62364679, "author": "Sumit Yadav", "author_id": 8216693, "author_profile": "https://Stackoverflow.com/users/8216693", "pm_score": 0, "selected": false, "text": "html{\n height: 100%;\n}\nbody{\n margin: 0;\n padding: 0;\n height: 100%;\n}\n\n.main-body{\n display: grid;\n /* let content auto to occupy remaining height and pass value in fit-content with min-height for header and footer */\n grid-template-rows: fit-content(8rem) auto fit-content(8rem);\n grid-template-areas: \"header\" \"main\" \"footer\";\n}\n\n.main-header{\n background-color: yellow;\n grid-area: header;\n}\n\n.main-content{\n grid-area: main;\n}\n\n.main-footer{\n background-color: green;\n grid-area: footer;\n} <body class=\"main-body\">\n <header class=\"main-header\">\n HEADER\n </header>\n <main class=\"main-content\">\n this is content\n </main>\n <footer class=\"main-footer\">\n this is footer\n </footer>\n</body>" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
206,661
<p>Yes, <a href="http://en.wikipedia.org/wiki/There_is_more_than_one_way_to_do_it" rel="noreferrer">There's More Than One Way To Do It</a> but there must be a canonical or most efficient or most concise way. I'll add answers I know of and see what percolates to the top.</p> <p>To be clear, the question is how best to read the contents of a file into a string. One solution per answer.</p>
[ { "answer_id": 206681, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 5, "selected": false, "text": "open(my $f, '<', $filename) or die \"OPENING $filename: $!\\n\";\n$string = do { local($/); <$f> };\nclose($f);\n" }, { "answer_id": 206682, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 7, "selected": true, "text": "use File::Slurp;\nmy $text = read_file($filename);\n use File::Slurper 'read_text';\nmy $text = read_text($filename);\n use Path::Tiny;\npath($filename)->slurp_utf8;\n" }, { "answer_id": 206683, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "{\n open F, $filename or die \"Can't read $filename: $!\";\n local $/; # enable slurp mode, locally.\n $file = <F>;\n close F;\n}\n" }, { "answer_id": 206688, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 1, "selected": false, "text": "open(F, $filename) or die \"OPENING $filename: $!\\n\";\n@lines = <F>;\nclose(F);\n$string = join('', @lines);\n" }, { "answer_id": 206778, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 6, "selected": false, "text": "do @ARGV my $contents = do { local(@ARGV, $/) = $file; <> };\n my $contents = do {\n open my $fh, '<:encoding(UTF-8)', $file or die '...';\n local $/;\n <$fh>;\n };\n" }, { "answer_id": 206794, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 4, "selected": false, "text": "my $contents = do {\n local $/;\n open my $fh, $filename or die \"Can't open $filename: $!\";\n <$fh>\n};\n" }, { "answer_id": 207438, "author": "dwarring", "author_id": 2105284, "author_profile": "https://Stackoverflow.com/users/2105284", "pm_score": 3, "selected": false, "text": "#!/usr/bin/perl\nuse warnings; use strict;\n\nuse IO::File;\nuse Sys::Mmap;\n\nsub sip {\n\n my $file_name = shift;\n my $fh;\n\n open ($fh, '+<', $file_name)\n or die \"Unable to open $file_name: $!\";\n\n my $str;\n\n mmap($str, 0, PROT_READ|PROT_WRITE, MAP_SHARED, $fh)\n or die \"mmap failed: $!\";\n\n return $str;\n}\n\nmy $str = sip('/tmp/words');\n\nprint substr($str, 100,20);\n #!/usr/bin/perl\nuse warnings; use strict;\n\nuse File::Map qw{map_file};\n\nmap_file(my $str => '/tmp/words', '+<');\n\nprint substr($str, 100, 20);\n" }, { "answer_id": 207611, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": " my $contents = `cat $file`;\n" }, { "answer_id": 348597, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "use Path::Class;\nfile('/some/path')->slurp;\n" }, { "answer_id": 7017092, "author": "Prakash K", "author_id": 159470, "author_profile": "https://Stackoverflow.com/users/159470", "pm_score": 3, "selected": false, "text": "use IO::All;\n\n# read into a string (scalar context)\n$contents = io($filename)->slurp;\n\n# read all lines an array (array context)\n@lines = io($filename)->slurp;\n" }, { "answer_id": 10106476, "author": "Trizen", "author_id": 1326646, "author_profile": "https://Stackoverflow.com/users/1326646", "pm_score": 2, "selected": false, "text": "my $string;\n{\n open my $fh, '<', $file or die \"Can't open $file: $!\";\n read $fh, $string, -s $file; # or sysread\n close $fh;\n}\n" }, { "answer_id": 26608540, "author": "Qtax", "author_id": 107152, "author_profile": "https://Stackoverflow.com/users/107152", "pm_score": 2, "selected": false, "text": "-0 -n perl -n0e 'print \"content is in $_\\n\"' filename\n -0777 perl -n0777e 'print length' filename\n" }, { "answer_id": 30518178, "author": "user4951120", "author_id": 4951120, "author_profile": "https://Stackoverflow.com/users/4951120", "pm_score": 1, "selected": false, "text": "$/ undef $/;\nopen FH, '<', $filename or die \"$!\\n\";\nmy $contents = <FH>;\nclose FH;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
206,689
<p>I have a menu that I am using and it will change the background color when I hover using <code>a:hover</code> but I want to know how to change the <code>class=line</code> so that it sticks. </p> <p>So from the home if they click contacts the home pages </p> <blockquote> <p>from (a href="#" class="clr") to (a href="#")</p> </blockquote> <p>and Contacts would change </p> <blockquote> <p>from (a href="#") to (a href="#" class="clr")</p> </blockquote> <p>any help?</p> <p>JD</p>
[ { "answer_id": 206705, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 1, "selected": false, "text": "document.getElementById(\"element\").className='myClass';\n" }, { "answer_id": 206706, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 2, "selected": false, "text": "<li id=\"homeNav\">home</li>\n<li id=\"blogNav\">blog</li>\n <body id=\"home\">\n<body id=\"blog\">\n #home #homeNav {background-image:url(homeNav-on.jpg);}\n#blog #blogNav {background-image:url(blogNav-on.jpg);}\n" }, { "answer_id": 207719, "author": "PHLAK", "author_id": 27025, "author_profile": "https://Stackoverflow.com/users/27025", "pm_score": 0, "selected": false, "text": "<?php\n // Get current page file name\n $url = Explode('/', $_SERVER[\"PHP_SELF\"]);\n $page = $parts[count($url) - 1];\n?>\n <?php if ($page == \"index.php\") echo ' class=\"current\"' ?>\n <div id=\"navigation\">\n <ul>\n <li><a href=\"index.php\"<?php if ($page == \"index.php\") echo ' class=\"current\"' ?>>Home</a></li>\n <li><a href=\"page1.php\"<?php if ($page == \"page1.php\") echo ' class=\"current\"' ?>>Resume</a></li>\n <li><a href=\"page2.php\"<?php if ($page == \"page2.php\") echo ' class=\"current\"' ?>>Photography</a></li>\n </ul>\n</div>\n #navigation ul li a.current {\n background-color: #FFF;\n}\n" }, { "answer_id": 207942, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 1, "selected": false, "text": "<html>\n <head>\n <script>\n document.onclick = function(evt) {\n var el = window.event? event.srcElement : evt.target;\n if (el && el.className == \"unselected\") {\n el.className = \"selected\";\n var siblings = el.parentNode.childNodes;\n for (var i = 0, l = siblings.length; i < l; i++) {\n var sib = siblings[i];\n if (sib != el && sib.className == \"selected\")\n sib.className = \"unselected\";\n }\n }\n }\n </script>\n <style>\n .selected { background: #f00; }\n </style>\n </head>\n <body>\n <a href=\"#\" class=\"selected\">One</a> \n <a href=\"#\" class=\"unselected\">Two</a> \n <a href=\"#\" class=\"unselected\">Three</a>\n </body>\n</html>\n" }, { "answer_id": 207998, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 0, "selected": false, "text": "$('#link-id').addClass('your-class');\n $('#link-id').mouseover(\n function(){\n $(this).addClass('your-class');\n }\n);\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,717
<p>How can I replace multiple spaces in a string with only one space in C#?</p> <p>Example:</p> <pre><code>1 2 3 4 5 </code></pre> <p>would be:</p> <pre><code>1 2 3 4 5 </code></pre>
[ { "answer_id": 206720, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 10, "selected": true, "text": "string sentence = \"This is a sentence with multiple spaces\";\nRegexOptions options = RegexOptions.None;\nRegex regex = new Regex(\"[ ]{2,}\", options); \nsentence = regex.Replace(sentence, \" \");\n" }, { "answer_id": 206724, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": false, "text": "string xyz = \"1 2 3 4 5\";\nxyz = string.Join( \" \", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));\n" }, { "answer_id": 206799, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "Regex.Replace() string s = Regex.Replace (\n \" 1 2 4 5\", \n @\"[ ]{2,}\", \n \" \"\n );\n String.Split() static class StringExtensions\n{\n public static string Join(this IList<string> value, string separator)\n {\n return string.Join(separator, value.ToArray());\n }\n}\n\n//...\n\nstring s = \" 1 2 4 5\".Split (\n \" \".ToCharArray(), \n StringSplitOptions.RemoveEmptyEntries\n ).Join (\" \");\n" }, { "answer_id": 206917, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": "while(str.Contains(\" \")) str = str.Replace(\" \", \" \");\n" }, { "answer_id": 206946, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 10, "selected": false, "text": "myString = Regex.Replace(myString, @\"\\s+\", \" \");\n" }, { "answer_id": 219268, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "Join public static string Join<T>(this IEnumerable<T> source, string separator)\n{\n return string.Join(separator, source.Select(e => e.ToString()).ToArray());\n}\n //...\n\nstring s = \" 1 2 4 5\".Split (\n \" \".ToCharArray(), \n StringSplitOptions.RemoveEmptyEntries\n ).Join (\" \");\n" }, { "answer_id": 304547, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 4, "selected": false, "text": "myString = Regex.Replace(myString, \" {2,}\", \" \");\n" }, { "answer_id": 2878200, "author": "Brenda Bell", "author_id": 346589, "author_profile": "https://Stackoverflow.com/users/346589", "pm_score": 5, "selected": false, "text": "myString = Regex.Replace(myString, @\"\\s+\", \" \", RegexOptions.Multiline);\n" }, { "answer_id": 11947581, "author": "cuongle", "author_id": 783681, "author_profile": "https://Stackoverflow.com/users/783681", "pm_score": 5, "selected": false, "text": " var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));\n str = string.Join(\" \", list);\n" }, { "answer_id": 13642266, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 0, "selected": false, "text": "string oldText = \" 1 2 3 4 5 \";\nstring newText = oldText\n .Replace(\" \", \" \" + (char)22 )\n .Replace( (char)22 + \" \", \"\" )\n .Replace( (char)22 + \"\", \"\" );\n\nAssert.That( newText, Is.EqualTo( \" 1 2 3 4 5 \" ) );\n" }, { "answer_id": 16776096, "author": "Nolonar", "author_id": 1169228, "author_profile": "https://Stackoverflow.com/users/1169228", "pm_score": 4, "selected": false, "text": "Regex StringBuilder public static string FilterWhiteSpaces(string input)\n {\n if (input == null)\n return string.Empty;\n\n StringBuilder stringBuilder = new StringBuilder(input.Length);\n for (int i = 0; i < input.Length; i++)\n {\n char c = input[i];\n if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))\n stringBuilder.Append(c);\n }\n return stringBuilder.ToString();\n }\n" }, { "answer_id": 24847573, "author": "Paul Easter", "author_id": 3583929, "author_profile": "https://Stackoverflow.com/users/3583929", "pm_score": 2, "selected": false, "text": "pattern: (?m:^ +| +$|( ){2,})\nreplacement: $1\n pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.\n" }, { "answer_id": 28896999, "author": "ravish.hacker", "author_id": 1367413, "author_profile": "https://Stackoverflow.com/users/1367413", "pm_score": 3, "selected": false, "text": "string s = \"welcome to london\";\ns.Replace(\" \", \"()\").Replace(\")(\", \"\").Replace(\"()\", \" \");\n" }, { "answer_id": 30230993, "author": "somebody", "author_id": 3323231, "author_profile": "https://Stackoverflow.com/users/3323231", "pm_score": 3, "selected": false, "text": "Regex temp = new Regex(\" {2,}\").Replace(temp, \" \"); \n {2,} .Replace(temp, \" \") Regex singleSpacify = new Regex(\" {2,}\", RegexOptions.Compiled);\ntemp = singleSpacify.Replace(temp, \" \");\n" }, { "answer_id": 33817748, "author": "ScubaSteve", "author_id": 787958, "author_profile": "https://Stackoverflow.com/users/787958", "pm_score": 5, "selected": false, "text": "string public static class StringExtension\n {\n public static String ReduceWhitespace(this String value)\n {\n var newString = new StringBuilder();\n bool previousIsWhitespace = false;\n for (int i = 0; i < value.Length; i++)\n {\n if (Char.IsWhiteSpace(value[i]))\n {\n if (previousIsWhitespace)\n {\n continue;\n }\n\n previousIsWhitespace = true;\n }\n else\n {\n previousIsWhitespace = false;\n }\n\n newString.Append(value[i]);\n }\n\n return newString.ToString();\n }\n }\n string testValue = \"This contains too much whitespace.\"\ntestValue = testValue.ReduceWhitespace();\n// testValue = \"This contains too much whitespace.\"\n" }, { "answer_id": 34953510, "author": "Ahmed Aljaff", "author_id": 3995545, "author_profile": "https://Stackoverflow.com/users/3995545", "pm_score": 1, "selected": false, "text": "private string removeNestedWhitespaces(char[] st)\n{\n StringBuilder sb = new StringBuilder();\n int indx = 0, length = st.Length;\n while (indx < length)\n {\n sb.Append(st[indx]);\n indx++;\n while (indx < length && st[indx] == ' ')\n indx++;\n if(sb.Length > 1 && sb[0] != ' ')\n sb.Append(' ');\n }\n return sb.ToString();\n}\n string test = removeNestedWhitespaces(\"1 2 3 4 5\".toCharArray());\n" }, { "answer_id": 35336638, "author": "Learner1947", "author_id": 3528695, "author_profile": "https://Stackoverflow.com/users/3528695", "pm_score": 1, "selected": false, "text": "while word.contains(\" \") //double space\n word = word.Replace(\" \",\" \"); //replace double space by single space.\nword = word.trim(); //to remove single whitespces from start & end.\n" }, { "answer_id": 35440518, "author": "Tom Gullen", "author_id": 356635, "author_profile": "https://Stackoverflow.com/users/356635", "pm_score": 1, "selected": false, "text": "while (myString.IndexOf(\" \", StringComparison.CurrentCulture) != -1)\n{\n myString = myString.Replace(\" \", \" \");\n}\n" }, { "answer_id": 48326219, "author": "Stephen du Buis", "author_id": 4035321, "author_profile": "https://Stackoverflow.com/users/4035321", "pm_score": 3, "selected": false, "text": "string myString = \" 0 1 2 3 4 5 \";\nmyString = string.Join(\" \", myString.Split(new char[] { ' ' }, \nStringSplitOptions.RemoveEmptyEntries));\n" }, { "answer_id": 49017046, "author": "The_Black_Smurf", "author_id": 315493, "author_profile": "https://Stackoverflow.com/users/315493", "pm_score": 2, "selected": false, "text": "public static string MergeSpaces(this string str)\n{\n\n if (str == null)\n {\n return null;\n }\n else\n {\n StringBuilder stringBuilder = new StringBuilder(str.Length);\n\n int i = 0;\n foreach (char c in str)\n {\n if (c != ' ' || i == 0 || str[i - 1] != ' ')\n stringBuilder.Append(c);\n i++;\n }\n return stringBuilder.ToString();\n }\n\n}\n" }, { "answer_id": 51988575, "author": "M.Hassan", "author_id": 3142139, "author_profile": "https://Stackoverflow.com/users/3142139", "pm_score": 2, "selected": false, "text": " [ ]+ #only space\n\n var text = Regex.Replace(inputString, @\"[ ]+\", \" \");\n" }, { "answer_id": 53520268, "author": "Patrick Artner", "author_id": 7505395, "author_profile": "https://Stackoverflow.com/users/7505395", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Linq;\nusing System.Text;\n\npublic static class StringExtension\n{\n public static string CondenseSpaces(this string s)\n {\n return s.Aggregate(new StringBuilder(), (acc, c) =>\n {\n if (c != ' ' || acc.Length == 0 || acc[acc.Length - 1] != ' ')\n acc.Append(c);\n return acc;\n }).ToString();\n }\n\n public static void Main()\n {\n const string input = \" (five leading spaces) (five internal spaces) (five trailing spaces) \";\n \n Console.WriteLine(\" Input: \\\"{0}\\\"\", input);\n Console.WriteLine(\"Output: \\\"{0}\\\"\", StringExtension.CondenseSpaces(input));\n }\n}\n Input: \" (five leading spaces) (five internal spaces) (five trailing spaces) \"\nOutput: \" (five leading spaces) (five internal spaces) (five trailing spaces) \"\n" }, { "answer_id": 56180189, "author": "Code", "author_id": 9787173, "author_profile": "https://Stackoverflow.com/users/9787173", "pm_score": 3, "selected": false, "text": "// Mysample string\nstring str =\"hi you are a demo\";\n\n//Split the words based on white sapce\nvar demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));\n \n//Join the values back and add a single space in between\nstr = string.Join(\" \", demo);\n// output: string str =\"hi you are a demo\";\n" }, { "answer_id": 58849324, "author": "Reap", "author_id": 8705563, "author_profile": "https://Stackoverflow.com/users/8705563", "pm_score": 1, "selected": false, "text": "public static string FilterWhiteSpaces(string input)\n{\n if (input == null)\n return string.Empty;\n\n var stringBuilder = new StringBuilder(input.Length);\n for (int i = 0; i < input.Length; i++)\n {\n char c = input[i];\n if (i == 0 || !char.IsWhiteSpace(c) || (char.IsWhiteSpace(c) && \n !char.IsWhiteSpace(strValue[i - 1])))\n stringBuilder.Append(c);\n }\n return stringBuilder.ToString();\n}\n" }, { "answer_id": 66389169, "author": "Giedrius", "author_id": 212121, "author_profile": "https://Stackoverflow.com/users/212121", "pm_score": -1, "selected": false, "text": "Regex.Replace(input, @\"\\s+\", \" \") \\n \\n Regex.Replace(source, @\"(\\s)\\s+\", \"$1\") Regex.Replace(source, @\"[ ]{2,}\", \" \") \"\\t \\t \" Regex.Replace(input, @\"\\s+\", \n(match) => match.Value.IndexOf('\\n') > -1 ? \"\\n\" : \" \", RegexOptions.Multiline)\n" }, { "answer_id": 69616112, "author": "Demetris Leptos", "author_id": 314320, "author_profile": "https://Stackoverflow.com/users/314320", "pm_score": 1, "selected": false, "text": "public static string MinimizeWhiteSpace(\n this string _this)\n {\n if (_this != null)\n {\n var returned = new StringBuilder();\n var inWhiteSpace = false;\n var length = _this.Length;\n for (int i = 0; i < length; i++)\n {\n var character = _this[i];\n if (char.IsWhiteSpace(character))\n {\n if (!inWhiteSpace)\n {\n inWhiteSpace = true;\n returned.Append(' ');\n }\n }\n else\n {\n inWhiteSpace = false;\n returned.Append(character);\n }\n }\n return returned.ToString();\n }\n else\n {\n return null;\n }\n }\n" }, { "answer_id": 70113294, "author": "Bibin Gangadharan", "author_id": 11225521, "author_profile": "https://Stackoverflow.com/users/11225521", "pm_score": -1, "selected": false, "text": " public string RemoveMultipleSpacesToSingle(string str)\n {\n string text = str;\n do\n {\n //text = text.Replace(\" \", \" \");\n text = Regex.Replace(text, @\"\\s+\", \" \");\n } while (text.Contains(\" \"));\n return text;\n }\n" }, { "answer_id": 71204719, "author": "Vasilis Plavos", "author_id": 6996666, "author_profile": "https://Stackoverflow.com/users/6996666", "pm_score": -1, "selected": false, "text": "public static string RemoveDoubleSpaces(this string value) \n{\n Regex regex = new Regex(\"[ ]{2,}\", RegexOptions.None);\n value = regex.Replace(value, \" \");\n\n // this removes space at the end of the value (like \"demo \")\n // and space at the start of the value (like \" hi\")\n value = value.Trim(' ');\n\n return value;\n}\n string stringInput =\" hi here is a demo \";\n\nstring stringCleaned = stringInput.RemoveDoubleSpaces();\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
206,718
<p>I want to load the data into session so that when the next button is clicked in crystal report viewer then in should load the data from the datatable instead retrieving the data again from the database. Here goes my code... </p> <pre><code> ReportDocument rpt = new ReportDocument(); DataTable resultSet = new DataTable(); string reportpath = null; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Request.QueryString.Get("id") == "5") { string publication = Request.QueryString.Get("pub"); DateTime date = DateTime.Parse(Request.QueryString.Get("date")); int pages = int.Parse(Request.QueryString.Get("pages")); int sort = int.Parse(Request.QueryString.Get("sort")); if (sort == 0) { reportpath = Server.MapPath("IssuesReport.rpt"); rpt.Load(reportpath); DataTable resultSet1 = RetrievalProcedures.IssuesReport(date, publication, pages); Session["Record"] = resultSet1; } DataTable report = (DataTable)Session["Record"]; rpt.SetDataSource(report); CrystalReportViewer1.ReportSource = rpt; </code></pre> <p>I am trying this code but when i clicked the next button it gives me the error that invalid report source..i guess the session is null thats why its giving me this error.</p> <p>Any sugesstions how can I solve this...</p>
[ { "answer_id": 206739, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": true, "text": "var data = Cache[\"Record_999\"] as DataTable;\nif (data == null) {\n // get from db\n // insert into cache\n}\nSetDataSource(data);\n" }, { "answer_id": 207116, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "if (!Page.IsPostBack)\n{\n if (Request.QueryString.Get(\"id\") == \"5\")\n {\n string publication = Request.QueryString.Get(\"pub\");\n DateTime date = DateTime.Parse(Request.QueryString.Get(\"date\"));\n int pages = int.Parse(Request.QueryString.Get(\"pages\"));\n int sort = int.Parse(Request.QueryString.Get(\"sort\"));\n // fixed the statement below to key off of session\n if (Session[\"Record\"] == null)\n {\n reportpath = Server.MapPath(\"IssuesReport.rpt\");\n rpt.Load(reportpath);\n Session[\"Record\"] = RetrievalProcedures.IssuesReport(date, publication, pages);\n }\n\n rpt.SetDataSource((DataTable)Session[\"Record\"]);\n CrystalReportViewer1.ReportSource = rpt;\n // ....\n }\n} \n" }, { "answer_id": 207155, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if(sort==0 || Session[\"Record\"] == null)\n{\n// do your magic\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
206,719
<p>My junk mail folder has been filling up with messages composed in what appears to be the Cyrillic alphabet. If a message body or a message subject is in Cyrillic, I want to permanently delete it.</p> <p>On my screen I see Cyrillic characters, but when I iterate through the messages in VBA within Outlook, the "Subject" property of the message returns question marks.</p> <p>How can I determine if the subject of the message is in Cyrillic characters?</p> <p>(Note: I have examined the "InternetCodepage" property - it's usually Western European.)</p>
[ { "answer_id": 207326, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 3, "selected": true, "text": "String IsCyrillic String True IsCyrillic Test IsCyrillic Option Explicit\n\nPublic Const errInvalidArgument = 5\n\n' Returns True if sText contains at least one Cyrillic character'\n' NOTE: Assumes UTF-16 encoding'\n\nPublic Function IsCyrillic(ByVal sText As String) As Boolean\n\n Dim i As Long\n\n ' Loop through each char. If we hit a Cryrillic char, return True.'\n\n For i = 1 To Len(sText)\n\n If IsCharCyrillic(Mid(sText, i, 1)) Then\n IsCyrillic = True\n Exit Function\n End If\n\n Next\n\nEnd Function\n\n' Returns True if the given character is part of the Cyrillic alphabet'\n' NOTE: Assumes UTF-16 encoding'\n\nPrivate Function IsCharCyrillic(ByVal sChar As String) As Boolean\n\n ' According to the first few Google pages I found, '\n ' Cyrillic is stored at U+400-U+52f '\n\n Const CYRILLIC_START As Integer = &H400\n Const CYRILLIC_END As Integer = &H52F\n\n ' A (valid) single Unicode char will be two bytes long'\n\n If LenB(sChar) <> 2 Then\n Err.Raise errInvalidArgument, _\n \"IsCharCyrillic\", _\n \"sChar must be a single Unicode character\"\n End If\n\n ' Get Unicode value of character'\n\n Dim nCharCode As Integer\n nCharCode = AscW(sChar)\n\n ' Is char code in the range of the Cyrillic characters?'\n\n If (nCharCode >= CYRILLIC_START And nCharCode <= CYRILLIC_END) Then\n IsCharCyrillic = True\n End If\n\nEnd Function\n ' On my box, this code iterates through my Inbox. On your machine,'\n' you may have to switch to your Inbox in Outlook before running this code.'\n' I placed this code in `ThisOutlookSession` in the VBA editor. I called'\n' it in the Immediate window by typing `ThisOutlookSession.TestIsCyrillic`'\n\nPublic Sub TestIsCyrillic()\n\n Dim oItem As Object\n Dim oMailItem As MailItem\n\n For Each oItem In ThisOutlookSession.ActiveExplorer.CurrentFolder.Items\n\n If TypeOf oItem Is MailItem Then\n\n Set oMailItem = oItem\n\n If IsCyrillic(oMailItem.Subject) Then\n\n ' I just printed out the offending subject line '\n ' (it will display as ? marks, but I just '\n ' wanted to see it output something) '\n ' In your case, you could change this line to: '\n ' '\n ' oMailItem.Delete '\n ' '\n ' to actually delete the message '\n\n Debug.Print oMailItem.Subject\n\n End If\n\n End If\n\n Next\n\nEnd Sub\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
206,734
<p>The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from <code>the_base_class</code>.</p> <pre><code>class the_base_class: somedata = {} somedata['was_false_in_base'] = False class subclassthing(the_base_class): def __init__(self): print self.somedata first = subclassthing() {'was_false_in_base': False} first.somedata['was_false_in_base'] = True second = subclassthing() {'was_false_in_base': True} &gt;&gt;&gt; del first &gt;&gt;&gt; del second &gt;&gt;&gt; third = subclassthing() {'was_false_in_base': True} </code></pre> <p>Defining <code>self.somedata</code> in the <code>__init__</code> function is obviously the correct way to get around this (so each class has it's own <code>somedata</code> dict) - but when is such behavior desirable?</p>
[ { "answer_id": 206765, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 6, "selected": true, "text": "somedata somedata = {}\nsomedata['was_false_in_base'] = False\n class import sys\n class Test(object):\n if sys.platform == \"linux2\":\n def hello(self):\n print \"Hello Linux\"\n else:\n def hello(self):\n print \"Hello ~Linux\"\n Test().hello() Hello Linux __init__ self class Test(object):\n def __init__(self):\n self.inst_var = [1, 2, 3]\n class SomeClass(object):\n __instances__ = {}\n\n def __new__(cls, v1, v2, v3):\n try:\n return cls.__insts__[(v1, v2, v3)]\n except KeyError:\n return cls.__insts__.setdefault(\n (v1, v2, v3), \n object.__new__(cls, v1, v2, v3))\n" }, { "answer_id": 206800, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 4, "selected": false, "text": "somedata dict bool class the_base_class:\n somedata = False\n\nclass subclassthing(the_base_class):\n def __init__(self):\n print self.somedata\n\n\n>>> first = subclassthing()\nFalse\n>>> first.somedata = True\n>>> print first.somedata\nTrue\n>>> second = subclassthing()\nFalse\n>>> print first.somedata\nTrue\n>>> del first\n>>> del second\n>>> third = subclassthing()\nFalse\n first.somedata True first.somedata" }, { "answer_id": 206840, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 2, "selected": false, "text": "somedata somedata" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
206,735
<p>I need a SQL query that returns ContactDate, SortName, City, ContactType, and Summary from the tables below. If any value is null, I need it to return the text “No Entry”.</p> <p><strong>ContactTable</strong></p> <ul> <li><em>ContactID</em></li> <li>ContactDate </li> <li>UserID </li> <li>Summary </li> <li>ContactType</li> <li>SortName</li> </ul> <p><strong>UserTable</strong></p> <ul> <li><em>UserID</em></li> <li>FirstName</li> <li>LastName </li> <li>AddressID</li> </ul> <p><strong>AddressTable</strong></p> <ul> <li><em>AddressID</em></li> <li>City</li> <li>Street </li> <li>State</li> <li>Zip</li> </ul>
[ { "answer_id": 206752, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 5, "selected": true, "text": "SELECT COALESCE(CAST(CONVERT(VARCHAR(10), ContactTable.ContactDate, 101) AS VARCHAR(10)), 'No Entry') AS ContactDate,\n COALESCE(ContactTable.SortName, 'No Entry') AS SortName,\n COALESCE(AddressTable.City, 'No Entry') AS City,\n COALESCE(ContactTable.ContactType, 'No Entry') AS ContactType\nFROM ContactTable\nLEFT OUTER JOIN UserTable ON ContactTable.UserID = UserTable.UserID\nLEFT OUTER JOIN AddressTable ON UserTable.AddressID = AddressTable.AddressID\n" }, { "answer_id": 206754, "author": "Craig", "author_id": 27294, "author_profile": "https://Stackoverflow.com/users/27294", "pm_score": 2, "selected": false, "text": "SELECT \n ISNULL(ContactDate, 'No Entry') AS ContactDate\nFROM Table\n" }, { "answer_id": 206761, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 3, "selected": false, "text": "--(SQL Server)\nSELECT\n C.ContactID,\n COALESCE(CAST(CONVERT(varchar(10), C.ContactDate, 101) AS varchar(10), 'No Entry') AS ContactDate,\n COALESCE(SorName, 'No Entry') AS SortName\n" }, { "answer_id": 206993, "author": "Dhaust", "author_id": 242, "author_profile": "https://Stackoverflow.com/users/242", "pm_score": 0, "selected": false, "text": "SELECT IIF(IsNull(Foo), 'No Entry' ,Foo), IIF(IsNull(Bar), 'No Entry' ,Bar) From TableName \n" }, { "answer_id": 207005, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 1, "selected": false, "text": "nvl SELECT nvl(col_name, desired_value) FROM foo decode" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8900/" ]
206,736
<p>Occasionally my MS Access reports: </p> <blockquote> <p>The search key was not found in any record</p> </blockquote> <p>After this happens the solution is to close Access, compact and repair the backend and then delete the record.</p> <p>What causes this and how can I avoid it?</p>
[ { "answer_id": 13538132, "author": "mwolfe02", "author_id": 154439, "author_profile": "https://Stackoverflow.com/users/154439", "pm_score": 1, "selected": false, "text": "HKLM\\Software\\Microsoft\\Office\\12.0\\Access Connectivity Engine\\Engines\n SandboxMode (DWORD Value)\n SETTING DESCRIPTION\n 0 Sandbox mode is disabled at all times.\n 1 Sandbox mode is used for Access, but not for non-Access programs.\n 2 Sandbox mode is used for non-Access programs, but not for Access.\n 3 Sandbox mode is used at all times. This is the default value.\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,746
<p>FxCop has the <a href="http://msdn.microsoft.com/en-ca/ms182327.aspx" rel="nofollow noreferrer">CollectionPropertiesShouldBeReadOnly rule</a> that complains if your class has some kind of collection property that clients can set. Instead, it suggests making the property read-only and supplying a Clear() method and Add() or AddRange() methods for changing the contents of the collection.</p> <p>I agree that makes for a cleaner and more controlled interface, but I'm struggling to make that interface work with the Spring framework. If I want to configure an object with a collection of collaborators, I have to expose some collection property to inject the collaborators into. I've looked through <a href="http://springframework.net/docs/1.1.2/reference/html/index.html" rel="nofollow noreferrer">the Spring documentation</a>, and I can't see any way to tell Spring to call the AddRange() method, am I missing something?</p> <p>For now, I'm going to exclude the warning with a note that it's necessary for Spring configuration.</p> <p><strong>Update:</strong> since I didn't get any nibbles here in the last two months, I posted the same question on the <a href="http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/1f9c8929-01eb-4388-89e8-8462b61975f1" rel="nofollow noreferrer">FxCop forum</a>.</p>
[ { "answer_id": 396850, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "public List<Foo> Items { get; set; }\n myInstance.Items = new List<Foo>();\n private List<Foo> _items = new List<Foo>();\npublic List<Foo> Items { get { return _items; } }\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
206,751
<p>I have a couple tables in which I created an object ID as either an Int or Bigint, and in both cases, they seem to autoincrement by 10 (ie, the first insert is object ID 1, the second is object ID 11, the third is object ID 21, etc). Two questions:</p> <ol> <li><p>Why does it do that?</p></li> <li><p>Is that a problem?</p></li> </ol>
[ { "answer_id": 206769, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 6, "selected": false, "text": "SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want';\n SET @@auto_increment_increment=1;\n ALTER TABLE tbl AUTO_INCREMENT = 100;\n" }, { "answer_id": 20558038, "author": "user427969", "author_id": 427969, "author_profile": "https://Stackoverflow.com/users/427969", "pm_score": 4, "selected": false, "text": "SHOW VARIABLES LIKE 'auto_inc%';\n\n+--------------------------+-------+\n| Variable_name | Value |\n+--------------------------+-------+\n| auto_increment_increment | 10 |\n| auto_increment_offset | 4 |\n+--------------------------+-------+\n" }, { "answer_id": 31969004, "author": "user1709374", "author_id": 1709374, "author_profile": "https://Stackoverflow.com/users/1709374", "pm_score": 6, "selected": false, "text": "auto_increment_increment" }, { "answer_id": 41527360, "author": "kimon", "author_id": 7389111, "author_profile": "https://Stackoverflow.com/users/7389111", "pm_score": 1, "selected": false, "text": "insert IGNORE into my_table set column=1\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,767
<p>I want to implement forms authentication on an ASP.NET website, the site should seek the user on the database to get some data and then authenticate against LDAP (Active Directory) to validate the user/password combo.</p> <p>After that I need to keep a instance of class that represents the user to use it in various forms.</p> <p>I tried to do it before with a login control, that checks the previous conditions and do an <code>AuthenticateEventArgs.Authenticated = true</code> and placed the object inside the session: <code>Session ["user"] = authenticatedUser;</code> but I had problem synchronizing both of them (the session expired before the auth cookie and I got NullReferenceExceptions when the pages tried to use the now defunct session object).</p> <p>Which is the best way to accomplish this? Is there some way to sync the session timeout with the cookie lifespan? The user object should be saved in any other way? Did I miss the point?</p> <p><b>UPDATE: I cannot use windows auth provider because the site should be accesible from outside out priate network. </b></p>
[ { "answer_id": 206773, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": true, "text": "if (session[\"user\"] == null)\n{\n Authentication.SignOut();\n}\n" }, { "answer_id": 211451, "author": "Bryan", "author_id": 22033, "author_profile": "https://Stackoverflow.com/users/22033", "pm_score": 0, "selected": false, "text": "<sessionState timeout=\"XX\" />\n<authentication mode=\"Forms\">\n <forms loginUrl=\"Login.aspx\" timeout=\"XX\" />\n</authentication>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23020/" ]
206,770
<p>In a previous question, I learned how to keep a footer div at the bottom of the page. (<a href="https://stackoverflow.com/questions/206652/how-to-create-div-to-fill-all-space-between-header-and-footer-div">see other question</a>)</p> <p>Now I'm trying to vertically center content between the header and footer divs.</p> <p>so what I've got is:</p> <pre><code>#divHeader { height: 50px; } #divContent { position:absolute; } #divFooter { height: 50px; position:absolute; bottom:0; width:100%; } &lt;div id="divHeader"&gt; Header &lt;/div&gt; &lt;div id="divContent"&gt; Content &lt;/div&gt; &lt;div id="divFooter"&gt; Footer &lt;/div&gt; </code></pre> <p>I've tried creating a parent div to house the existing 3 divs and giving that div a vertical-align:middle; but that gets me nowhere.</p>
[ { "answer_id": 206812, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "height top:50%; left:50%" }, { "answer_id": 209729, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": true, "text": "html,body {height:100%;}\nbody {display:table;}\ndiv {display:table-row;}\n#content {\n display:table-cell;\n vertical-align:middle;\n}\n <body>\n<div>header</div>\n<div id=\"content\">content</div>\n<div>footer</div>\n</body>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
206,775
<p>I am trying to detect which web in sharepoint that the user is looking at right now. One approach could be to read the URls from the browser and try to compare them to a reference URL to the sharepoint solution. I have not yet been able to locate any solution that works in both IE and Firefox.</p> <p>The idea is to write a small C# app that will harvest the URLs and do the comparing. </p> <p>TIA</p>
[ { "answer_id": 206829, "author": "Parappa", "author_id": 9974, "author_profile": "https://Stackoverflow.com/users/9974", "pm_score": 3, "selected": true, "text": "float GetCalcResult(void)\n{\n float retval = 0.0f;\n\n HWND calc= FindWindow(\"SciCalc\", \"Calculator\");\n if (calc == NULL) {\n calc= FindWindow(\"Calc\", \"Calculator\");\n }\n if (calc == NULL) {\n MessageBox(NULL, \"calculator not found\", \"Error\", MB_OK);\n return 0.0f;\n }\n HWND calcEdit = FindWindowEx(calc, 0, \"Edit\", NULL);\n if (calcEdit == NULL) {\n MessageBox(NULL, \"error finding calc edit box\", \"Error\", MB_OK);\n return 0.0f;\n }\n\n long len = SendMessage(calcEdit, WM_GETTEXTLENGTH, 0, 0) + 1;\n char* temp = (char*) malloc(len);\n SendMessage(calcEdit, WM_GETTEXT, len, (LPARAM) temp);\n retval = atof(temp);\n free(temp);\n\n return retval;\n}\n" }, { "answer_id": 13121936, "author": "Sameer", "author_id": 1782948, "author_profile": "https://Stackoverflow.com/users/1782948", "pm_score": 2, "selected": false, "text": "function GetURL()\n{\n var oShell = new ActiveXObject('shell.application');\n var oColl = oShell.Windows();\n for (var i = 0;i<oColl.count;i++)\n {\n try\n {\n var Title = oColl(i).document.title;\n if (Title.indexOf('DesiredTitle') != -1)\n {\n alert ('Title-'+oColl(i).document.title);\n alert ('Location-'+oColl(i).location);\n }\n }\n catch (err)\n {\n alert (err);\n }\n }\n}\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23499/" ]
206,783
<p>I have a JavaScript resource that has the possibility of being edited at any time. Once it is edited I would want it to be propagated to the user's browser relatively quickly (like maybe 15 minutes or so), however, the frequency of this resource being editing is few and far between (maybe 2 a month).</p> <p>I'd rather the resource to be cached in the browser, since it will be retrieved frequently, but I'd also like the cache to get reset on the browser at a semi-regular interval.</p> <p>I know I can pass a no-cache header when I request for the resource, but I was wondering when the cache would automatically reset itself on the browser if I did not pass no-cache.</p> <p>I imagine this would be independent for each browser, but I'm not sure.</p> <p>I tried to Google this, but most of the hits I found were about clearing the browser's cache... which isn't what I'm looking for.</p>
[ { "answer_id": 206789, "author": "Craig", "author_id": 27294, "author_profile": "https://Stackoverflow.com/users/27294", "pm_score": 4, "selected": false, "text": "<script src=\"/code.js?ver=123\" type=\"text/javascript\"></script>\n" }, { "answer_id": 207861, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 7, "selected": true, "text": "<script src=\"/script.js?time_stamp=1224147832156\" type=\"text/javascript\"></script>\n<script src=\"/script.js?svn_version=678\" type=\"text/javascript\"></script>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ]
206,787
<p>When I dump a Sybase database, it doesn't seem to matter whether there's data in the tables or not, the file size is the same. I've been told that this is down to the fact that my dump file is binary and not logical, so the file of the dump file is based on the allocated size of the database. I know that Oracle can use logical dump files, but can I get Sybase to do the something similar, or is there any other sneaky ways of getting the dump file size down?</p>
[ { "answer_id": 555666, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 2, "selected": false, "text": "gunzip -c pubs_1.dmp | bzip2 > pubs.dmp.bz2\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
206,788
<p>I've installed the Windows XAMPP package on three separate computers, 2 running Windows Vista 32 bit ( 1 Ultimate / 1 Home Premium ) and 1 running Windows Vista 64 Home Premium.</p> <p>After enabling xdebug in php.ini and restarting apache, viewing the default XAMPP localhost index causes apache to crash in the same way every time, reporting 'php_xdebug.dll' as the Fault Module Name.</p> <p>Here's the full report from the Windows Crash Reporter thing:</p> <pre><code>Problem signature: Problem Event Name: APPCRASH Application Name: apache.exe Application Version: 2.2.9.0 Application Timestamp: 4853f994 Fault Module Name: php_xdebug.dll Fault Module Version: 2.0.3.0 Fault Module Timestamp: 47fcd9b9 Exception Code: c0000005 Exception Offset: 00008493 OS Version: 6.0.6001.2.1.0.768.3 Locale ID: 1033 Additional Information 1: a34a Additional Information 2: c9c5f4fd744690d388ab9d5b3eb051a7 Additional Information 3: cb2e Additional Information 4: 650bb5690556a17e911375b94d3e16f0 </code></pre> <p>I've tried Googling this issue but haven't found any resolution, only reports of similar errors. </p> <p>EDIT: I enabled the extension line for php_xdebug.dll and that seems to have stopped the crashing so far. </p>
[ { "answer_id": 567318, "author": "cyberhobo", "author_id": 68638, "author_profile": "https://Stackoverflow.com/users/68638", "pm_score": 1, "selected": false, "text": "extension=php_xdebug-2.0.4-5.2.8.dll\n [XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension_ts=\"\\xampplite\\php\\ext\\php_xdebug-2.0.4-5.2.8.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=127.0.0.1\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"\\xampplite\\tmp\"\nxdebug.trace_output_dir=\"\\xampplite\\tmp\"\n" }, { "answer_id": 585894, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "[Zend]\n;zend_extension_ts = \"C:\\xampp\\php\\zendOptimizer\\lib\\ZendExtensionManager.dll\"\n;zend_extension_manager.optimizer_ts = \"C:\\xampp\\php\\zendOptimizer\\lib\\Optimizer\"\n;zend_optimizer.enable_loader = 0\n;zend_optimizer.optimization_level=15\n;;zend_optimizer.license_path =\n; Local Variables:\n; tab-width: 4\n; End:\n\n[XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension_ts=\"C:\\xampp\\php\\ext\\php_xdebug-2.0.2-5.2.5.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=127.0.0.1\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"C:\\xampp\\tmp\"\n ;extension=php_xdebug-2.0.2-5.2.5.dll\n" }, { "answer_id": 665813, "author": "MrFox", "author_id": 32726, "author_profile": "https://Stackoverflow.com/users/32726", "pm_score": 0, "selected": false, "text": "php.ini ;xdebug.profiler_enable=1\n;xdebug.profiler_output_dir=\"(temp_dir)\"\n" }, { "answer_id": 833805, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "implicit_flush implicit_flush = On [Zend] zend_extension = \"c:\\xampp\\php\\ext\\php_xdebug.dll\" [XDebug] [XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension_ts=\"C:\\xampp\\php\\ext\\php_xdebug.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=localhost\nxdebug.remote_port=10000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"C:\\xampp\\tmp\"\n" }, { "answer_id": 886059, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": ";extension=php_xdebug-2.0.4-5.2.8.dll\n [XDebug]\n; Only Zend OR (!) XDebug\nzend_extension_ts=\"C:/Program Files (x86)/wamp/bin/php/php5.2.9-2/ext/php_xdebug-2.0.4-5.2.8.dll\"\nxdebug.remote_enable=on\nxdebug.remote_host=localhost\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=0\nxdebug.profiler_output_dir=\"C:/Program Files (x86)/wamp/tmp\"\n" }, { "answer_id": 1174342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\\xampp\\php\\ext C:\\xampp\\php\\php.ini [XDebug] zend_extension_ts=\"C:\\xampp\\php\\ext\\php_xdebug.dll\"\n zend_extension=\"C:\\xampp\\php\\ext\\php_xdebug-2.0.5-5.2-nts.dll\"\n [XDebug]\n;; Only Zend OR (!) XDebug\nzend_extension=\"C:\\xampp\\php\\ext\\php_xdebug-2.0.5-5.2-nts.dll\"\nxdebug.remote_enable=true\nxdebug.remote_host=127.0.0.1\nxdebug.remote_port=9000\nxdebug.remote_handler=dbgp\nxdebug.profiler_enable=1\nxdebug.profiler_output_dir=\"C:\\xampp\\tmp\"\n" }, { "answer_id": 4558299, "author": "Dane", "author_id": 557647, "author_profile": "https://Stackoverflow.com/users/557647", "pm_score": 1, "selected": false, "text": "zend_extension = C:\\xampp\\php\\ext\\php_xdebug.dll" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,790
<p>Since I've started to use jQuery, I have been doing a lot more JavaScript development.</p> <p>I have the need to parse different date formats and then to display them into another format.</p> <p>Do you know of any good tool to do this?</p> <p>Which one would you recommend?</p>
[ { "answer_id": 4566577, "author": "Brian Ellis", "author_id": 3129, "author_profile": "https://Stackoverflow.com/users/3129", "pm_score": 3, "selected": false, "text": "$.parseDate('yy-mm-dd', '2007-01-26');\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ]
206,793
<p>Why won't my connection string to SQL server work with Windows authentication? A sql user works fine, acme\administrator or administrator@acme.com won't work. This is a Win Form app written in C#.</p> <pre><code> { OdbcConnection cn = null; String connectionString; connectionString = "Driver={SQL Server};Server=" + cbxDataSources.Text +";Database=" + strDatabase + ";"; connectionString += "UID=" + textBoxUserName.Text + ";"; connectionString += "PWD=" + textBoxPassword.Text + ";"; cn = new OdbcConnection(connectionString); return cn; } </code></pre> <p>Thanks guys</p>
[ { "answer_id": 206825, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 3, "selected": false, "text": "Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;\n Driver={SQL Server};Server=myServerAddress;Database=myDataBase;Trusted_Connection=Yes;\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]