qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
351,360
<p>I've got this small question - given a bitmask of weekdays (e.g., <code>Sunday = 0x01, Monday = 0x02, Tuesday = 0x04</code>, etc...) and today's day (in a form of <code>Sunday = 1, Monday = 2, Tuesday = 3</code>, etc...) - what's the most elegant way to find out the next day from today, that's set in the bitmask? By elegant I mean, is there a way to do this without if/switch/etc..., because I know the non-elegant way?</p> <p><strong>Edit</strong> I probably should've mentioned (to make this more clear) that the variable holding the bitmask can have several of the days set, so for example (roughly):</p> <pre><code>uDay = Sunday | Monday; today = Tuesday; </code></pre> <p>I need to get "Sunday"</p>
[ { "answer_id": 351387, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "// returns t (today) if no weekday is set in the mask.\nint getNextDay(int m, int t) {\n int i, idx;\n for(i = 0, idx=t%7; i<7 && !((1<<idx)&m); i++, idx=(idx+1)%7)\n /* body empty */ ;\n return (i == 7) ? t : (idx + 1);\n}\n\n// getNextDay(8|2, 2) == 4, getNextDay(64, 2) == 7\n// getNextDay(128, 2) == 2\n" }, { "answer_id": 351414, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 3, "selected": true, "text": "int getNextDay(int days_mask, int today) {\n if (!days_mask) return -1; // no days set\n days_mask |= days_mask << 7; // duplicate days into next week\n mask = 1 << (today % 7); // keep track of the day\n while (!(mask & days_mask)) {\n mask <<= 1;\n ++today;\n }\n return today % 7;\n}\n" }, { "answer_id": 351705, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 2, "selected": false, "text": "t-1 (t-1+1)%7 t%7 int getNextDay(int m, int t) {\n if((m&127)==0) return t; //If no day is set, return today\n t=t%7; //Start with tomorrow\n while((m&(1<<t))==0) t = (t+1)%7; //Try successive days\n return t+1; //Change back to Sunday=1, etc.\n}\n t=t-1 --t" }, { "answer_id": 351857, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 1, "selected": false, "text": "static unsigned next_day_set (unsigned today, unsigned set) {\n unsigned arev = bitreverse (highest_bit_set (bitreverse ((set << 7) | set)\n & (bitreverse (today) - 1)));\n return ((arev >> 7) | arev) & 0x7f;\n}\n enum {\n Sunday = 1 << 6\n Monday = 1 << 5\n Tuesday = 1 << 4,\n /* etc */\n Saturday = 1 << 0\n};\n\nstatic unsigned next_day_set (unsigned today, unsigned set) {\n unsigned a = highest_bit_set (((set << 7) | set) & ((today << 7) - 1));\n return ((a >> 7) | a) & 0x7f;\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/351360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
351,368
<p>I have an asp page that uses jQuery ajax to load member counts into a bunch of <code>div</code>s after a page is loaded.</p> <p>It works perfectly well in FireFox, and with clients that have a small number of groups.</p> <p>For the small number of clients that have many groups (500+), I am getting an error in IE. The ajax calls seem to be running synchronously, because the click events won't register until every ajax call has returned.</p> <p>The series of ajax requests is just 1 request for most clients. It is only broken up into multiple requests for clients with a VERY large number of groups.</p> <p>Now, I've seen the bug where <code>$("a").click</code> functions are not bound if links are added after the DOM is loaded. The links that aren't working are not being loaded by AJAX, they do not fall into this category.</p> <p>Here is the pseudocode:</p> <pre><code>ready() { // count the number of groups that this user has, adding the ids to a list if( count &lt; 50 ) { runAjax(); } else { // this calls the ajax request on groups of 50 ids // it pauses briefly after each request by using setTimeout to call the next runAjaxRecursively(); } } </code></pre> <p>And here is the ajax request:</p> <pre><code>// run the HTTPRequest $.ajax({ async: true, type: "POST", url: "emailcatcount.asp?idList="+idList, data: "idList="+idList, dataType: "html", success: function(html) { // blah blah blah } }); </code></pre> <p>Anyway, the code works fine, so please consider any errors as typos. The only problem is that, in IE, click events won't fire until every single ajax call has returned.</p> <p>Does anyone know why this would occur? Notice that I am setting <code>async</code> to true.</p> <p>Does it have anything to do with how jQuery's ready event is processed in IE?</p> <p>I am bewildered, and have spent a few days on this, so any ideas are appreciated.</p>
[ { "answer_id": 351387, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "// returns t (today) if no weekday is set in the mask.\nint getNextDay(int m, int t) {\n int i, idx;\n for(i = 0, idx=t%7; i<7 && !((1<<idx)&m); i++, idx=(idx+1)%7)\n /* body empty */ ;\n return (i == 7) ? t : (idx + 1);\n}\n\n// getNextDay(8|2, 2) == 4, getNextDay(64, 2) == 7\n// getNextDay(128, 2) == 2\n" }, { "answer_id": 351414, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 3, "selected": true, "text": "int getNextDay(int days_mask, int today) {\n if (!days_mask) return -1; // no days set\n days_mask |= days_mask << 7; // duplicate days into next week\n mask = 1 << (today % 7); // keep track of the day\n while (!(mask & days_mask)) {\n mask <<= 1;\n ++today;\n }\n return today % 7;\n}\n" }, { "answer_id": 351705, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 2, "selected": false, "text": "t-1 (t-1+1)%7 t%7 int getNextDay(int m, int t) {\n if((m&127)==0) return t; //If no day is set, return today\n t=t%7; //Start with tomorrow\n while((m&(1<<t))==0) t = (t+1)%7; //Try successive days\n return t+1; //Change back to Sunday=1, etc.\n}\n t=t-1 --t" }, { "answer_id": 351857, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 1, "selected": false, "text": "static unsigned next_day_set (unsigned today, unsigned set) {\n unsigned arev = bitreverse (highest_bit_set (bitreverse ((set << 7) | set)\n & (bitreverse (today) - 1)));\n return ((arev >> 7) | arev) & 0x7f;\n}\n enum {\n Sunday = 1 << 6\n Monday = 1 << 5\n Tuesday = 1 << 4,\n /* etc */\n Saturday = 1 << 0\n};\n\nstatic unsigned next_day_set (unsigned today, unsigned set) {\n unsigned a = highest_bit_set (((set << 7) | set) & ((today << 7) - 1));\n return ((a >> 7) | a) & 0x7f;\n}\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/351368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311247/" ]
351,371
<p>You may have seen JavaScript sliders before:</p> <p><a href="http://dev.jquery.com/view/tags/ui/1.5b2/demos/ui.slider.html" rel="nofollow noreferrer">http://dev.jquery.com/view/tags/ui/1.5b2/demos/ui.slider.html</a></p> <p>What I'm envisioning is a circular slider. It would consist of a draggable button at one point on the circle -- and that button can be dragged anywhere along the ring. The value depends on what position the button is at (think of a clock).</p>
[ { "answer_id": 351384, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": true, "text": "var dx = m.x-c.x;\nvar dy = m.y-c.y;\n\nvar scale = radius/Math.sqrt(dx*dx+dy*dy);\n\nslider.x = dx*scale + c.x;\nslider.y = dy*scale + c.y;\n" }, { "answer_id": 31371120, "author": "Soundar", "author_id": 1845801, "author_profile": "https://Stackoverflow.com/users/1845801", "pm_score": 0, "selected": false, "text": "jsFiddle" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/351371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32881/" ]
351,373
<p>In the context of creating a custom Eclipse distribution for a development team.</p> <p>How would I go about building a custom Eclipse distribution containing a specific set of plugins? Would it be difficult to also add a kind of update site to put specific versions of the plug-ins from which the customized eclipse would update?</p>
[ { "answer_id": 15806377, "author": "Paul Verest", "author_id": 482717, "author_profile": "https://Stackoverflow.com/users/482717", "pm_score": 2, "selected": false, "text": "<?xml version='1.0' encoding='UTF-8'?>\n<?p2f version='1.0.0'?>\n<p2f version='1.0.0'>\n <ius size='5'>\n <iu id='org.chromium.sdk.feature.group' name='ChromeDevTools SDK' version='0.3.9.201302091448'>\n <repositories size='1'>\n <repository location='http://www.tomotaro1065.com/nodeclipse/updates/'/>\n </repositories>\n </iu>\n <iu id='org.chromium.debug.feature.group' name='Chromium JavaScript Remote Debugger' version='0.3.9.201302091448'>\n <repositories size='1'>\n <repository location='http://www.tomotaro1065.com/nodeclipse/updates/'/>\n </repositories>\n </iu>\n <iu id='com.eclipsesource.jshint.feature.feature.group' name='JSHint Eclipse Integration' version='0.9.6.20130319-2128'>\n <repositories size='1'>\n <repository location='http://github.eclipsesource.com/jshint-eclipse/updates/'/>\n </repositories>\n </iu>\n <iu id='markdown.editor.feature.feature.group' name='Markdown Editor' version='0.2.3'>\n <repositories size='1'>\n <repository location='http://winterwell.com/software/updatesite/'/>\n </repositories>\n </iu>\n <iu id='org.nodeclipse.feature.group' name='Nodeclipse' version='0.2.0.201302091448'>\n <repositories size='1'>\n <repository location='http://www.tomotaro1065.com/nodeclipse/updates/'/>\n </repositories>\n </iu>\n </ius>\n</p2f>\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/351373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39057/" ]
351,375
<p>So we've been told that one source of <code>TM Enq</code> contention can be unindexed FK's. My question is which one.</p> <p>I have an <code>INSERT INTO Table_B</code> that is recording <code>TM Enq Wait</code>.</p> <p>It contains a <code>PK</code> that is the parent to other tables and it has columns that are <code>FK</code> constrained to other <code>PK</code>s.</p> <p>So which <code>FK</code>s need indexed: that table's columns or its children?</p> <p>NB: I know that this isn't the only cause of TM Contention. Can you explain why it couldn't possibly be this if that's the case.</p>
[ { "answer_id": 351637, "author": "derobert", "author_id": 27727, "author_profile": "https://Stackoverflow.com/users/27727", "pm_score": 2, "selected": false, "text": "SELECT o.something\n FROM oltp_tab o JOIN lookup l ON (o.lookup_no = l.lookup_no)\n WHERE l.lookup_name = ?\n" } ]
2008/12/08
[ "https://Stackoverflow.com/questions/351375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,380
<p>Starting recently, some of my new web pages (XHTML 1.1) are setup to do a regex of the request header <code>Accept</code> and send the right HTTP response headers if the user agent accepts XML (Firefox and Safari do).</p> <p>IE (or any other browser that doesn't accept it) will just get the plain <code>text/html</code> content type. </p> <p>Will Google bot (or any other search bot) have any problems with this? Is there any negatives to my approach I have looked over? Would you think this header sniffer would have much effect on performance?</p>
[ { "answer_id": 351411, "author": "Alohci", "author_id": 42585, "author_profile": "https://Stackoverflow.com/users/42585", "pm_score": 4, "selected": true, "text": "application/xhtml+xml text/html text/html application/xhtml+xml text/html" }, { "answer_id": 413536, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "<script/> text/html </script> text/html <default:h1> <script> <script>if (a &amp;&amp; b)</script> & href <br> application/xml <[CDATA[ ]]>" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
351,409
<p>How do I append an object (such as a string or number) to an array in JavaScript? </p>
[ { "answer_id": 351421, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 13, "selected": true, "text": "Array.prototype.push // initialize array\nvar arr = [\n \"Hi\",\n \"Hello\",\n \"Bonjour\"\n];\n\n// append new value to the array\narr.push(\"Hola\");\n\nconsole.log(arr); push() // initialize array\nvar arr = [\"Hi\", \"Hello\", \"Bonjour\", \"Hola\"];\n\n// append multiple values to the array\narr.push(\"Salut\", \"Hey\");\n\n// display all values\nfor (var i = 0; i < arr.length; i++) {\n console.log(arr[i]);\n} firstArray.concat(secondArray) var arr = [\n \"apple\",\n \"banana\",\n \"cherry\"\n];\n\n// Do not forget to assign the result as, unlike push, concat does not change the existing array\narr = arr.concat([\n \"dragonfruit\",\n \"elderberry\",\n \"fig\"\n]);\n\nconsole.log(arr); Array.prototype.unshift var arr = [1, 2, 3];\narr.unshift(0);\nconsole.log(arr); push const arr = [\n \"Hi\",\n \"Hello\",\n \"Bonjour\",\n];\n\nconst newArr = [\n ...arr,\n \"Salut\",\n];\n\nconsole.log(newArr);" }, { "answer_id": 351444, "author": "MK_Dev", "author_id": 39843, "author_profile": "https://Stackoverflow.com/users/39843", "pm_score": 10, "selected": false, "text": "push() concat() var ar1 = [1, 2, 3];\nvar ar2 = [4, 5, 6];\n\nvar ar3 = ar1.concat(ar2);\n\nalert(ar1);\nalert(ar2);\nalert(ar3); ar1 ar2 var ar1 = [1, 2, 3];\nvar ar2 = [4, 5, 6];\n\nar1 = ar1.concat(ar2);\nalert(ar1);" }, { "answer_id": 3826423, "author": "Jens Roland", "author_id": 57068, "author_profile": "https://Stackoverflow.com/users/57068", "pm_score": 9, "selected": false, "text": "arr[arr.length] = b arr.push(b) arr[arr.length] = b arr[arr.length] = b arr.push() arr[arr.length] function arrpush_small() {\n var arr1 = [];\n for (a = 0; a < 100; a++)\n {\n arr1 = [];\n for (i = 0; i < 5000; i++)\n {\n arr1.push('elem' + i);\n }\n }\n}\n\nfunction arrlen_small() {\n var arr2 = [];\n for (b = 0; b < 100; b++)\n {\n arr2 = [];\n for (j = 0; j < 5000; j++)\n {\n arr2[arr2.length] = 'elem' + j;\n }\n }\n}\n\n\nfunction arrpush_large() {\n var arr1 = [];\n for (i = 0; i < 500000; i++)\n {\n arr1.push('elem' + i);\n }\n}\n\nfunction arrlen_large() {\n var arr2 = [];\n for (j = 0; j < 500000; j++)\n {\n arr2[arr2.length] = 'elem' + j;\n }\n}\n" }, { "answer_id": 6925930, "author": "rjmunro", "author_id": 3408, "author_profile": "https://Stackoverflow.com/users/3408", "pm_score": 6, "selected": false, "text": "arr val arr.push(val);\n var arr = ['a', 'b', 'c'];\narr.push('d');\nconsole.log(arr);" }, { "answer_id": 7047800, "author": "Mαzen", "author_id": 239639, "author_profile": "https://Stackoverflow.com/users/239639", "pm_score": 6, "selected": false, "text": "concat a = [1, 2, 3];\nb = [3, 4, 5];\na = a.concat(b);\nconsole.log(a);" }, { "answer_id": 11975486, "author": "yoel halb", "author_id": 640195, "author_profile": "https://Stackoverflow.com/users/640195", "pm_score": 4, "selected": false, "text": "myArray[i + 1] = someValue;\n myArray.push(someValue);\n myArray[myArray.length] = someValue;\n myArray[myArray.length + 1000] = someValue;\n if(myArray[i] === \"undefined\"){ continue; }\n if(!myArray[i]){ continue; }\n i" }, { "answer_id": 12190371, "author": "Omnimike", "author_id": 960483, "author_profile": "https://Stackoverflow.com/users/960483", "pm_score": 8, "selected": false, "text": "var arr = ['first'];\narr.push('second', 'third');\nconsole.log(arr); var arr = ['first'];\narr.push('second', 'third');\narr.push.apply(arr, ['forth', 'fifth']);\nconsole.log(arr); apply var arr = ['first'];\narr.push('second', 'third');\n\narr.push(...['fourth', 'fifth']);\nconsole.log(arr) ;" }, { "answer_id": 22459894, "author": "Fizer Khan", "author_id": 1154350, "author_profile": "https://Stackoverflow.com/users/1154350", "pm_score": 6, "selected": false, "text": "push apply var array1 = [11, 32, 75];\nvar array2 = [99, 67, 34];\n\nArray.prototype.push.apply(array1, array2);\nconsole.log(array1); array2 array1 array1 [11, 32, 75, 99, 67, 34] for" }, { "answer_id": 25569194, "author": "Pawan Singh", "author_id": 2767509, "author_profile": "https://Stackoverflow.com/users/2767509", "pm_score": 5, "selected": false, "text": "var a = ['a', 'b'];\nvar b = ['c', 'd'];\n var c = a.concat(b);\n g var a=[] a.push('g');\n" }, { "answer_id": 25920074, "author": "9ete", "author_id": 574823, "author_profile": "https://Stackoverflow.com/users/574823", "pm_score": 4, "selected": false, "text": "myarray[myarray.length] = 'new element value added to the end of the array';\n var myarray = [0, 1, 2, 3],\n myarrayLength = myarray.length; // myarrayLength is set to 4\n" }, { "answer_id": 30103251, "author": "Maarten Peels", "author_id": 3636345, "author_profile": "https://Stackoverflow.com/users/3636345", "pm_score": 5, "selected": false, "text": "push() var fruits = [\"Banana\", \"Orange\", \"Apple\", \"Mango\"];\nfruits.push(\"Kiwi\");\n\n// The result of fruits will be:\nBanana, Orange, Apple, Mango, Kiwi\n unshift() var fruits = [\"Banana\", \"Orange\", \"Apple\", \"Mango\"];\nfruits.unshift(\"Lemon\", \"Pineapple\");\n\n// The result of fruits will be:\nLemon, Pineapple, Banana, Orange, Apple, Mango\n concat() var fruits = [\"Banana\", \"Orange\"];\nvar moreFruits = [\"Apple\", \"Mango\", \"Lemon\"];\nvar allFruits = fruits.concat(moreFruits);\n\n// The values of the children array will be:\nBanana, Orange, Apple, Mango, Lemon\n" }, { "answer_id": 30734348, "author": "CodingIntrigue", "author_id": 571194, "author_profile": "https://Stackoverflow.com/users/571194", "pm_score": 6, "selected": false, "text": "push var arr = [1, 2, 3, 4, 5];\nvar arr2 = [6, 7, 8, 9, 10];\narr.push(...arr2);\nconsole.log(arr); arr2 arr" }, { "answer_id": 31542177, "author": "Danil Gaponov", "author_id": 1646982, "author_profile": "https://Stackoverflow.com/users/1646982", "pm_score": 4, "selected": false, "text": "var newArr = oldArr.concat([newEl]);\n" }, { "answer_id": 33386880, "author": "Karl", "author_id": 863264, "author_profile": "https://Stackoverflow.com/users/863264", "pm_score": 4, "selected": false, "text": "concat() var a = [\n [1, 2],\n [3, 4] ];\n\nvar b = [\n [\"a\", \"b\"],\n [\"c\", \"d\"] ];\n\nb = b.concat(a);\n\nalert(b[2][1]); // Result: 2\n" }, { "answer_id": 33985550, "author": "Downhillski", "author_id": 2161568, "author_profile": "https://Stackoverflow.com/users/2161568", "pm_score": 5, "selected": false, "text": "apply() array1 array2 var array1 = [3, 4, 5];\nvar array2 = [1, 2];\n\nArray.prototype.push.apply(array2, array1);\n\nconsole.log(array2); // [1, 2, 3, 4, 5]\n spread \"use strict\";\nlet array1 = [3, 4, 5];\nlet array2 = [1, 2];\n\narray2.push(...array1);\n\nconsole.log(array2); // [1, 2, 3, 4, 5]\n spread array2.push(...array1); array2.push(3, 4, 5); var combinedArray = array1.concat(array2); const combinedArray = [...array1, ...array2] ..." }, { "answer_id": 35464842, "author": "Satyapriya Mishra", "author_id": 5814477, "author_profile": "https://Stackoverflow.com/users/5814477", "pm_score": 2, "selected": false, "text": "arr=['a','b','c'];\narr.push('d');\n//now print the array in console.log and it will contain 'a','b','c','d' as elements.\nconsole.log(array);\n" }, { "answer_id": 36079433, "author": "Emil Reña Enriquez", "author_id": 1418771, "author_profile": "https://Stackoverflow.com/users/1418771", "pm_score": 3, "selected": false, "text": "array_merge = function (arr1, arr2) {\n return arr1.concat(arr2.filter(function(item){\n return arr1.indexOf(item) < 0;\n }))\n}\n array1 = ['1', '2', '3']\narray2 = ['2', '3', '4', '5']\ncombined_array = array_merge(array1, array2)\n" }, { "answer_id": 39780803, "author": "JmLavoier", "author_id": 4178612, "author_profile": "https://Stackoverflow.com/users/4178612", "pm_score": 4, "selected": false, "text": "var arr = [\n \"apple\",\n \"banana\",\n \"cherry\"\n];\n\nvar arr2 = [\n \"dragonfruit\",\n \"elderberry\",\n \"fig\"\n];\n\narr.push(...arr2);\n" }, { "answer_id": 40929580, "author": "Taufiq Rahman", "author_id": 5401681, "author_profile": "https://Stackoverflow.com/users/5401681", "pm_score": 5, "selected": false, "text": "push() var a = [1, 2, 3];\na.push(4, 5);\nconsole.log(a);\n [1, 2, 3, 4, 5]\n unshift() var a = [1, 2, 3];\na.unshift(4, 5);\nconsole.log(a); \n [4, 5, 1, 2, 3]\n concat() var arr1 = [\"a\", \"b\", \"c\"];\nvar arr2 = [\"d\", \"e\", \"f\"];\nvar arr3 = arr1.concat(arr2);\nconsole.log(arr3);\n [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" ]\n .length var ar = ['one', 'two', 'three'];\nar[ar.length] = 'four';\nconsole.log( ar ); \n [\"one\", \"two\", \"three\", \"four\"]\n splice() var myFish = [\"angel\", \"clown\", \"mandarin\", \"surgeon\"];\nmyFish.splice(4, 0, \"nemo\");\n//array.splice(start, deleteCount, item1, item2, ...)\nconsole.log(myFish);\n [\"angel\", \"clown\", \"mandarin\", \"surgeon\",\"nemo\"]\n var ar = ['one', 'two', 'three'];\nar[3] = 'four'; // add new element to ar\nconsole.log(ar);\n [\"one\", \"two\",\"three\",\"four\"]\n" }, { "answer_id": 42391906, "author": "José Antonio Postigo", "author_id": 2940802, "author_profile": "https://Stackoverflow.com/users/2940802", "pm_score": 5, "selected": false, "text": "let array = [1, 2];\nconsole.log([...array, 3]);\n" }, { "answer_id": 43963804, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 2, "selected": false, "text": "var arr = [1, 2, 3, 4, 5];\n arr.push(6); // Returns [1, 2, 3, 4, 5, 6];\n arr.unshift(0); // Returns [0, 1, 2, 3, 4, 5];\n" }, { "answer_id": 46908439, "author": "Hoque MD Zahidul", "author_id": 4307338, "author_profile": "https://Stackoverflow.com/users/4307338", "pm_score": 4, "selected": false, "text": "// Initialize the array\n\nvar arr = [\n \"Hi\",\n \"Hello\",\n \"Bangladesh\"\n];\n\n// Append a new value to the array\n\narr = [...arr, \"Feni\"]; \n\n// Or you can add a variable value\n\nvar testValue = \"Cool\";\n\narr = [...arr, testValue ];\n\nconsole.log(arr);\n\n// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]\n" }, { "answer_id": 48298499, "author": "Sanu Uthaiah Bollera", "author_id": 2804790, "author_profile": "https://Stackoverflow.com/users/2804790", "pm_score": 1, "selected": false, "text": "Array.prototype.append = function(destArray){\n destArray = destArray || [];\n this.push.call(this, ...destArray);\n return this;\n}\nvar arr = [1,2,5,67];\nvar arr1 = [7,4,7,8];\nconsole.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]\nconsole.log(arr.append(\"Hola\")) // [1, 2, 5, 67, 7, 4, 7, 8, \"H\", \"o\", \"l\", \"a\"]\n" }, { "answer_id": 50547355, "author": "Lior Elrom", "author_id": 1843451, "author_profile": "https://Stackoverflow.com/users/1843451", "pm_score": 3, "selected": false, "text": "const arr = [1, 2, 3];\nconst val = 4;\n\narr.concat([val]); // [1, 2, 3, 4]\n [...arr, val] // [1, 2, 3, 4]\n" }, { "answer_id": 50601536, "author": "Harun Or Rashid", "author_id": 4724147, "author_profile": "https://Stackoverflow.com/users/4724147", "pm_score": 1, "selected": false, "text": "push() pop() array.push(toAppend);\n" }, { "answer_id": 50931987, "author": "Flavio Copes", "author_id": 205039, "author_profile": "https://Stackoverflow.com/users/205039", "pm_score": 3, "selected": false, "text": "push() const fruits = ['banana', 'pear', 'apple']\nfruits.push('mango')\nconsole.log(fruits)\n push() concat() const fruits = ['banana', 'pear', 'apple']\nconst allfruits = fruits.concat('mango')\nconsole.log(allfruits)\n concat() let const const fruits = ['banana', 'pear', 'apple']\nconst allfruits = fruits.concat('mango')\nconsole.log(allfruits)\n let fruits = ['banana', 'pear', 'apple']\nfruits = fruits.concat('mango')\n push() const fruits = ['banana', 'pear', 'apple']\nfruits.push('mango', 'melon', 'avocado')\nconsole.log(fruits)\n concat() const fruits = ['banana', 'pear', 'apple']\nconst allfruits = fruits.concat('mango', 'melon', 'avocado')\nconsole.log(allfruits)\n const fruits = ['banana', 'pear', 'apple']\nconst allfruits = fruits.concat(['mango', 'melon', 'avocado'])\nconsole.log(allfruits)\n" }, { "answer_id": 51089708, "author": "Srikrushna", "author_id": 5852550, "author_profile": "https://Stackoverflow.com/users/5852550", "pm_score": 4, "selected": false, "text": "// Append to the end\narrName.push('newName1');\n\n// Prepend to the start\narrName.unshift('newName1');\n\n// Insert at index 1\narrName.splice(1, 0,'newName1');\n// 1: index number, 0: number of element to remove, newName1: new element\n\n\n// Replace index 3 (of exists), add new element otherwise.\narrName[3] = 'newName1';\n // Insert from index number 1\narrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');\n// 1: index number from where insert starts,\n// 0: number of element to remove,\n//newElemenet1,2,3: new elements\n // Join two or more arrays\narrName.concat(newAry1, newAry2);\n//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array\n" }, { "answer_id": 51723769, "author": "Ir Calif", "author_id": 6320551, "author_profile": "https://Stackoverflow.com/users/6320551", "pm_score": 2, "selected": false, "text": "let fruits = [\"orange\", \"banana\", \"apple\", \"lemon\"]; /* Array declaration */\n\nfruits.push(\"avacado\"); /* Adding an element to the array */\n\n/* Displaying elements of the array */\n\nfor(var i=0; i < fruits.length; i++){\n console.log(fruits[i]);\n}\n" }, { "answer_id": 51960083, "author": "Aditya", "author_id": 3280682, "author_profile": "https://Stackoverflow.com/users/3280682", "pm_score": 2, "selected": false, "text": "arr.push(\"Test1\", \"Test2\"); Array1.concat(Array2) array[aray.length] = 'test';" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ]
351,415
<p>I need to programatically find the users name using C#. Specifically, I want to get the system/network user attached to the current process. I'm writing a web application that uses windows integrated security.</p>
[ { "answer_id": 351876, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "IPrincipal IIdentity IPrincipal principal = Thread.CurrentPrincipal;\nIIdentity identity = principal == null ? null : principal.Identity;\nstring name = identity == null ? \"\" : identity.Name;\n Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());\n string userName = \"Fred\"; // todo\nstring[] roles = { \"User\", \"Admin\" }; // todo\nThread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), roles);\n" }, { "answer_id": 28427047, "author": "Mehdi Bugnard", "author_id": 1429232, "author_profile": "https://Stackoverflow.com/users/1429232", "pm_score": 2, "selected": false, "text": "string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name ;\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
351,443
<p>The "Application Icon" of my application is wrong.</p> <p>My application shows in taskbar a different icon than the classic Delphi icon. Instead is shows the icon of one of my VCL's. That specific VCL from which the icon was "stolen" is not used in my application but other VCL's in the same package are used.</p> <p>Related info: - The icon looks ok if I drag and drop my app on Desktop. - The icon looks ok in Windows Commander when I put the cursor on it. - The icon does not look ok in Windows Commander when I drag and drop it in "Button Bar". Conclusion: the icon is not accidentally changed at the runtime (the problem is there even if the application is not running).</p> <p>I use Delphi 7. I disabled EurekaLog and FastMM just to be sure, and rebuild the application. The problem still persists. I have not even the slightest clue why the compiler inserts the wrong icon. I really need some hints. Thanks.</p>
[ { "answer_id": 351914, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": false, "text": "{$R *.RES} $R $R $R" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,456
<p>The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call <code>os.system()</code>. Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(<code>0</code>). Alternately somebody could show be how to properly use <code>urllib</code>.</p>
[ { "answer_id": 351475, "author": "Sean", "author_id": 44133, "author_profile": "https://Stackoverflow.com/users/44133", "pm_score": 4, "selected": true, "text": "import urllib\nsock = urllib.urlopen(\"http://en.wikipedia.org/wiki/Python_(programming_language)\")\nhtmlsource = sock.read()\nsock.close()\nprint htmlsource\n import urllib2\nf = urllib2.urlopen('http://www.python.org/')\nprint f.read(100)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26659/" ]
351,473
<pre><code>class Child { private override void Check_CheckedChanged(object sender, EventArgs e) { if (Check.Checked) { this.addName(this.FirstName); this.disableControls(); } else { this.addAddress(this.address); //this.activatecontrols();// gives error since it's private method in parent. } } } class Parent { private void Check_CheckedChanged(object sender, EventArgs e) { if (Check.Checked) { this.disablecontrols(); } else { this.addAddress(this.address); this.activatecontrols(); } } } </code></pre> <p>I want to fire the the child event if it satisfies if condition. But if can not I need to call the base's else condition as I activatecontrols() is private in Parent. So, how do I call the event? </p>
[ { "answer_id": 351494, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 2, "selected": false, "text": "ActivateControls protected Check_CheckedChanged virtual // Parent.cs\n\nprivate void Check_CheckedChanged(object sender, EventArgs e)\n{\n OnCheckedChanged();\n}\n\nprotected virtual void OnCheckedChanged()\n{\n if (Check.Checked)\n {\n this.disablecontrols();\n }\n else\n {\n this.addAddress(this.address);\n this.activatecontrols();\n }\n}\n Parent Child // Child.cs\n\nprotected override void OnCheckedChanged()\n{\n if (Check.Checked)\n {\n this.addName(this.FirstName);\n }\n\n base.OnCheckedChanged(); // Same outcome\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42564/" ]
351,479
<p>Not sure if this is intended behavior or a bug or a wrong function that I'm using, but the problem is that PathCombine() returns a wrong path on a Vista box.</p> <p>The relative path is (as exported by the WMP to a playlist):</p> <p><code>..\..\..\Public\Music\Sample Music\Amanda.wma</code></p> <p>The path it's relative to is:</p> <p><code>C:\Users\userX\Music\Playlists\playlist.wpl</code></p> <p>and PathCombine() returns:</p> <p><code>C:\Users\userX\Public\Music\Sample Music\Amanda.wma</code></p> <p>however, the file is actually located here (judging by the Explorer and the fact that I can't open it from the code):</p> <p><code>C:\Users\Public\Music\Sample Music\Amanda.wma</code></p> <p>Is this a known issue? Is there some other function I should be using?</p>
[ { "answer_id": 351614, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "C:\\Users\\userX\\Music\\Playlists\\playlist.wpl\\..\\..\\..\\Public\\Music\\Sample Music\\Amanda.wma\n .. C:\\Users\\userX\\Music\\Playlists\\playlist.wpl\\..\\..\\..\\Public\\Music\\Sample Music\\Amanda.wma\nC:\\Users\\userX\\Music\\Playlists\\..\\..\\Public\\Music\\Sample Music\\Amanda.wma\nC:\\Users\\userX\\Music\\..\\Public\\Music\\Sample Music\\Amanda.wma\nC:\\Users\\userX\\Public\\Music\\Sample Music\\Amanda.wma\n PathCombine() .. . playlist.wpl .." } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
351,483
<p>How do I create a ListBox in ASP.NET MVC with single selection mode?</p>
[ { "answer_id": 351579, "author": "Jeffrey Meyer", "author_id": 2323, "author_profile": "https://Stackoverflow.com/users/2323", "pm_score": 6, "selected": true, "text": "<%= Html.DropDownList(\"list1\", \n new Dictionary<string, object> {{\"size\", \"5\"}} ) %>\n" }, { "answer_id": 24702738, "author": "NoWar", "author_id": 196919, "author_profile": "https://Stackoverflow.com/users/196919", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n $(document).ready(function () {\n $('select').removeAttr('multiple');\n });\n</script>\n" }, { "answer_id": 31010738, "author": "Ferrell Carr", "author_id": 342569, "author_profile": "https://Stackoverflow.com/users/342569", "pm_score": 3, "selected": false, "text": "@Html.DropDownList(\"PropertyID\", null, htmlAttributes: new {size=5, @class=\"form-control\" })\n ViewBag.PropertyID = new SelectList(db.EntityItems);\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31624/" ]
351,484
<p>I have an application the will load usercontrols dynamically depending on the user. You will see in the example below that I am casting each user control via switch/case statements. Is there a better way to do this? Reflection? (I must be able to add an event handler Bind in each control.)</p> <pre><code>override protected void OnInit(EventArgs e) { cc2007.IndividualPageSequenceCollection pages = new IndividualPageSequenceCollection().Load(); pages.Sort("displayIndex", true); foreach (IndividualPageSequence page in pages) { Control uc = Page.LoadControl(page.PageName); View view = new View(); int viewNumber = Convert.ToInt32(page.DisplayIndex) -1; switch(page.PageName) { case "indStart.ascx": IndStart = (indStart) uc; IndStart.Bind += new EventHandler(test_handler); view.Controls.Add(IndStart); MultiView1.Views.AddAt(viewNumber, view); break; case "indDemographics.ascx": IndDemographics = (indDemographics)uc; IndDemographics.Bind += new EventHandler(test_handler); view.Controls.Add(IndDemographics); MultiView1.Views.AddAt(viewNumber, view); break; case "indAssetSurvey.ascx": IndAssetSurvey = (indAssetSurvey)uc; IndAssetSurvey.Bind += new EventHandler(test_handler); view.Controls.Add(IndAssetSurvey); MultiView1.Views.AddAt(viewNumber, view); break; } } base.OnInit(e); } </code></pre> <p>Thanks in advance!</p>
[ { "answer_id": 351505, "author": "Jeroen Landheer", "author_id": 44056, "author_profile": "https://Stackoverflow.com/users/44056", "pm_score": 1, "selected": false, "text": " \n\nType t = uc.GetType();\nEventInfo evtInfo = t.GetEvent(\"Bind\");\nevtInfo.AddEventHandler(this, new EventHandler(test_handler));\n\n\n " }, { "answer_id": 351542, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 1, "selected": false, "text": "public interface IBindable\n{\n event EventHandler Bind;\n}\n foreach (IndividualPageSequence page in pages)\n{\n IBindable uc = Page.LoadControl(page.PageName) as IBindable;\n if( uc != null )\n {\n uc.Bind += new EventHandler(test_handler);\n View view = new View();\n view.Controls.Add(page);\n int viewNumber = Convert.ToInt32(page.DisplayIndex) -1;\n MultiView1.Views.AddAt(viewNumber, view);\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4888/" ]
351,487
<p>I am a Delphi novice, but I'm trying to understand the relationship between TApplication and TfrmMain windows using Spy++. It seems that the TfrmMain window is the real window that has proper screen coordinates, but the TApplication window is the one that appears in the Windows taskbar. Also, they don't seem to be related to each other at all. One isn't the parent window of the other, so how are the windows linked together? And why is the non-UI window the one that gets the Windows taskbar button? Can any Delphi experts help me understand this?</p>
[ { "answer_id": 351504, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 4, "selected": true, "text": "program Project1;\nuses\n Forms,\n Unit1 in 'Unit1.pas' {Form1};\n{$R *.RES}\nbegin\n Application.Initialize;\n Application.CreateForm(TfrmMain, frmMain) ;\n Application.Run;\nend.\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
351,489
<p>How can I get a PL/SQL block to output the results of a <code>SELECT</code> statement the same way as if I had done a plain <code>SELECT</code>?</p> <p>For example how to do a <code>SELECT</code> like:</p> <pre><code>SELECT foo, bar FROM foobar; </code></pre> <p>Hint :</p> <pre><code>BEGIN SELECT foo, bar FROM foobar; END; </code></pre> <p>doesn't work.</p>
[ { "answer_id": 351752, "author": "Sergey Stadnik", "author_id": 10557, "author_profile": "https://Stackoverflow.com/users/10557", "pm_score": 6, "selected": false, "text": "DECLARE\n v_foo foobar.foo%TYPE;\n v_bar foobar.bar%TYPE;\nBEGIN\n SELECT foo,bar FROM foobar INTO v_foo, v_bar;\n -- Print the foo and bar values\n dbms_output.put_line('foo=' || v_foo || ', bar=' || v_bar);\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n -- No rows selected, insert your exception handler here\n WHEN TOO_MANY_ROWS THEN\n -- More than 1 row seleced, insert your exception handler here\nEND;\n DECLARE\n CURSOR cur_foobar IS\n SELECT foo, bar FROM foobar;\n\n v_foo foobar.foo%TYPE;\n v_bar foobar.bar%TYPE;\nBEGIN\n -- Open the cursor and loop through the records\n OPEN cur_foobar;\n LOOP\n FETCH cur_foobar INTO v_foo, v_bar;\n EXIT WHEN cur_foobar%NOTFOUND;\n -- Print the foo and bar values\n dbms_output.put_line('foo=' || v_foo || ', bar=' || v_bar);\n END LOOP;\n CLOSE cur_foobar;\nEND;\n BEGIN\n -- Open the cursor and loop through the records\n FOR v_rec IN (SELECT foo, bar FROM foobar) LOOP \n -- Print the foo and bar values\n dbms_output.put_line('foo=' || v_rec.foo || ', bar=' || v_rec.bar);\n END LOOP;\nEND;\n" }, { "answer_id": 351877, "author": "Igor Zelaya", "author_id": 22769, "author_profile": "https://Stackoverflow.com/users/22769", "pm_score": 3, "selected": false, "text": "FUNCTION Function1 return SYS_REFCURSOR IS \n l_cursor SYS_REFCURSOR;\n BEGIN\n open l_cursor for SELECT foo,bar FROM foobar; \n return l_cursor; \nEND Function1;\n" }, { "answer_id": 353639, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 3, "selected": false, "text": "CREATE PACKAGE pkg1 AS\n TYPE numset_t IS TABLE OF NUMBER;\n FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED;\nEND pkg1;\n/\n\nCREATE PACKAGE BODY pkg1 AS\n-- FUNCTION f1 returns a collection of elements (1,2,3,... x)\nFUNCTION f1(x NUMBER) RETURN numset_t PIPELINED IS\n BEGIN\n FOR i IN 1..x LOOP\n PIPE ROW(i);\n END LOOP;\n RETURN;\n END;\nEND pkg1;\n/\n\n-- pipelined function is used in FROM clause of SELECT statement\nSELECT * FROM TABLE(pkg1.f1(5));\n" }, { "answer_id": 40354386, "author": "David דודו Markovitz", "author_id": 6336479, "author_profile": "https://Stackoverflow.com/users/6336479", "pm_score": 2, "selected": false, "text": "begin\n select 1+1\n select 2+2\n select 3+3\nend\n SQL> begin\n 2 select * from dual;\n 3 end;\n 4 /\nselect * from dual;\n*\nERROR at line 2:\nORA-06550: line 2, column 1:\nPLS-00428: an INTO clause is expected in this SELECT statement\n" }, { "answer_id": 40360471, "author": "William Robertson", "author_id": 230471, "author_profile": "https://Stackoverflow.com/users/230471", "pm_score": 6, "selected": false, "text": "declare\n rc sys_refcursor;\nbegin\n open rc for select * from dual;\n dbms_sql.return_result(rc);\nend;\n set autoprint on\n\nvar rc refcursor\n\nbegin\n open :rc for select count(*) from dual;\nend;\n/\n\nPL/SQL procedure successfully completed.\n\n\n COUNT(*)\n----------\n 1\n\n1 row selected.\n" }, { "answer_id": 40387789, "author": "Art", "author_id": 1934744, "author_profile": "https://Stackoverflow.com/users/1934744", "pm_score": 2, "selected": false, "text": "declare\n l_tabname VARCHAR2(100) := 'dual';\n l_val1 VARCHAR2(100):= '''foo''';\n l_val2 VARCHAR2(100):= '''bar''';\n l_sql VARCHAR2(1000); \nbegin\n l_sql:= 'SELECT '||l_val1||','||l_val2||' FROM '||l_tabname;\n execute immediate l_sql;\n dbms_output.put_line(l_sql);\nend;\n/\n\nOutput:\n SELECT 'foo','bar' FROM dual\n" }, { "answer_id": 40407315, "author": "Vamsi Praveen Karanam", "author_id": 4461313, "author_profile": "https://Stackoverflow.com/users/4461313", "pm_score": 1, "selected": false, "text": "declare\n var1 integer;\nvar2 varchar2(200)\nbegin\n execute immediate 'select emp_id,emp_name from emp'\n into var1,var2;\n dbms_output.put_line(var1 || var2);\nend;\n" }, { "answer_id": 40416165, "author": "Dinesh Katwal", "author_id": 6527431, "author_profile": "https://Stackoverflow.com/users/6527431", "pm_score": 2, "selected": false, "text": "DBMS_OUTPUT.PUT_LINE BEGIN\n DBMS_OUTPUT.put_line ('Hello World!');\nEND;\n" }, { "answer_id": 40438837, "author": "Ahsan Habib", "author_id": 6865527, "author_profile": "https://Stackoverflow.com/users/6865527", "pm_score": 3, "selected": false, "text": "set serveroutput on;\ndeclare\ncursor c1 is\n select foo, bar from foobar;\nbegin\n for i in c1 loop\n dbms_output.put_line(i.foo || ' ' || i.bar);\n end loop;\nend;\n" }, { "answer_id": 51043255, "author": "Issam El omri", "author_id": 6039215, "author_profile": "https://Stackoverflow.com/users/6039215", "pm_score": 0, "selected": false, "text": "SET SERVEROUTPUT ON;\n\nDECLARE\n RC SYS_REFCURSOR;\n Result1 varchar2(25);\n Result2 varchar2(25);\nBEGIN\n OPEN RC FOR SELECT foo, bar into Result1, Result2 FROM foobar;\n DBMS_SQL.RETURN_RESULT(RC);\nEND;\n" }, { "answer_id": 58257774, "author": "Himanshu", "author_id": 10497483, "author_profile": "https://Stackoverflow.com/users/10497483", "pm_score": 0, "selected": false, "text": " Create Procedure sample(id \n varchar2(20))as \n Select count(*) into x from table \n where \n Userid=id;\n End ;\n Begin\n sample(20);\n End\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26659/" ]
351,495
<p>All the documentation I've found so far is to update keys that are already created:</p> <pre><code> arr['key'] = val; </code></pre> <p>I have a string like this: <code>&quot; name = oscar &quot; </code></p> <p>And I want to end up with something like this:</p> <pre><code>{ name: 'whatever' } </code></pre> <p>That is, split the string and get the first element, and then put that in a dictionary.</p> <h3>Code</h3> <pre><code>var text = ' name = oscar ' var dict = new Array(); var keyValuePair = text.split(' = '); dict[ keyValuePair[0] ] = 'whatever'; alert( dict ); // Prints nothing. </code></pre>
[ { "answer_id": 351507, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 8, "selected": true, "text": "var a = new Array();\na['name'] = 'oscar';\nalert(a['name']);\n var text = 'name = oscar'\nvar dict = new Array()\nvar keyValuePair = text.replace(/ /g,'').split('=');\ndict[ keyValuePair[0] ] = keyValuePair[1];\nalert( dict[keyValuePair[0]] );\n" }, { "answer_id": 351538, "author": "Danny", "author_id": 26630, "author_profile": "https://Stackoverflow.com/users/26630", "pm_score": 3, "selected": false, "text": "var myArray = new Array();\nmyArray['one'] = 1;\nmyArray['two'] = 2;\nmyArray['three'] = 3;\n\n// Show the values stored\nfor (var i in myArray) {\n alert('key is: ' + i + ', value is: ' + myArray[i]);\n}\n" }, { "answer_id": 351553, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": false, "text": "var f = new Object(); f.name = 'orion';\nvar f = new Object(); f['name'] = 'orion';\nvar f = new Array(); f.name = 'orion';\nvar f = new Array(); f['name'] = 'orion';\nvar f = new XMLHttpRequest(); f['name'] = 'orion';\n Array Object var text = '{ name = oscar }'\nvar dict = new Object();\n\n// Remove {} and spaces\nvar cleaned = text.replace(/[{} ]/g, '');\n\n// Split into key and value\nvar kvp = cleaned.split('=');\n\n// Put in the object\ndict[ kvp[0] ] = kvp[1];\nalert( dict.name ); // Prints oscar.\n" }, { "answer_id": 351723, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 9, "selected": false, "text": "new Array() new Object() // Create an empty associative array (in JavaScript it is called ... Object)\nvar dict = {}; // Huh? {} is a shortcut for \"new Object()\"\n\n// Add a key named fred with value 42\ndict.fred = 42; // We can do that because \"fred\" is a constant\n // and conforms to id rules\n\n// Add a key named 2bob2 with value \"twins!\"\ndict[\"2bob2\"] = \"twins!\"; // We use the subscript notation because\n // the key is arbitrary (not id)\n\n// Add an arbitrary dynamic key with a dynamic value\nvar key = ..., // Insanely complex calculations for the key\n val = ...; // Insanely complex calculations for the value\ndict[key] = val;\n\n// Read value of \"fred\"\nval = dict.fred;\n\n// Read value of 2bob2\nval = dict[\"2bob2\"];\n\n// Read value of our cool secret key\nval = dict[key];\n // Change the value of fred\ndict.fred = \"astra\";\n// The assignment creates and/or replaces key-value pairs\n\n// Change the value of 2bob2\ndict[\"2bob2\"] = [1, 2, 3]; // Any legal value can be used\n\n// Change value of our secret key\ndict[key] = undefined;\n// Contrary to popular beliefs, assigning \"undefined\" does not remove the key\n\n// Go over all keys and values in our dictionary\nfor (key in dict) {\n // A for-in loop goes over all properties, including inherited properties\n // Let's use only our own properties\n if (dict.hasOwnProperty(key)) {\n console.log(\"key = \" + key + \", value = \" + dict[key]);\n }\n}\n // Let's delete fred\ndelete dict.fred;\n// fred is removed, but the rest is still intact\n\n// Let's delete 2bob2\ndelete dict[\"2bob2\"];\n\n// Let's delete our secret key\ndelete dict[key];\n\n// Now dict is empty\n\n// Let's replace it, recreating all original data\ndict = {\n fred: 42,\n \"2bob2\": \"twins!\"\n // We can't add the original secret key because it was dynamic, but\n // we can only add static keys\n // ...\n // oh well\n temp1: val\n};\n// Let's rename temp1 into our secret key:\nif (key != \"temp1\") {\n dict[key] = dict.temp1; // Copy the value\n delete dict.temp1; // Kill the old key\n} else {\n // Do nothing; we are good ;-)\n}\n" }, { "answer_id": 1590505, "author": "Andrea", "author_id": 192635, "author_profile": "https://Stackoverflow.com/users/192635", "pm_score": 3, "selected": false, "text": "1 var text = ' name = oscar '\n2 var dict = new Array();\n3 var keyValuePair = text.split(' = ');\n4 dict[ keyValuePair[0] ] = 'whatever';\n5 alert( dict ); // Prints nothing.\n trim name = oscar trim = key = keyValuePair[0];`\n dict[key] = keyValuePair[1];\n alert( dict['name'] ); // It will print out 'oscar'\n dict[keyValuePair[0]] keyValuePair[0]" }, { "answer_id": 9826281, "author": "Sasinda Rukshan", "author_id": 1286433, "author_profile": "https://Stackoverflow.com/users/1286433", "pm_score": 1, "selected": false, "text": "var myArray = new Array();\nmyArray['one'] = 1;\nmyArray['two'] = 2;\nmyArray['three'] = 3;\n\n// Show the values stored\nfor (var i in myArray) {\n alert('key is: ' + i + ', value is: ' + myArray[i]);\n}\n myArray['one'] = 1;\nmyArray['two'] = 2;\nmyArray['three'] = 3;\nmyArray.push(\"one\");\nmyArray.push(\"two\");\nmyArray.push(\"three\");\nfor(var i=0;i<maArray.length;i++){\n console.log(myArray[myArray[i]])\n}\n" }, { "answer_id": 30091043, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 2, "selected": false, "text": "var myMap = new Map();\n\nvar keyObj = {},\n keyFunc = function () {},\n keyString = \"a string\";\n\nmyMap.set(keyString, \"value associated with 'a string'\");\nmyMap.set(keyObj, \"value associated with keyObj\");\nmyMap.set(keyFunc, \"value associated with keyFunc\");\n\nmyMap.size; // 3\n\nmyMap.get(keyString); // \"value associated with 'a string'\"\nmyMap.get(keyObj); // \"value associated with keyObj\"\nmyMap.get(keyFunc); // \"value associated with keyFunc\"\n" }, { "answer_id": 30604974, "author": "Karim Samir", "author_id": 402285, "author_profile": "https://Stackoverflow.com/users/402285", "pm_score": 2, "selected": false, "text": "var arr = [];\n\narr = {\n key1: 'value1',\n key2:'value2'\n};\n" }, { "answer_id": 32450738, "author": "user2266928", "author_id": 2266928, "author_profile": "https://Stackoverflow.com/users/2266928", "pm_score": 1, "selected": false, "text": "var obj = {};\n\nfor (i = 0; i < data.length; i++) {\n if(i%2==0) {\n var left = data[i].substring(data[i].indexOf('.') + 1);\n var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);\n\n obj[left] = right;\n count++;\n }\n}\n\nconsole.log(\"obj\");\nconsole.log(obj);\n\n// Show the values stored\nfor (var i in obj) {\n console.log('key is: ' + i + ', value is: ' + obj[i]);\n}\n\n\n}\n};\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
351,499
<p>I need to make a pop-up window for users to log-in to my website from other websites.</p> <p>I need to use a pop-up window to show the user the address bar so that they know it is a secure login, and not a spoof. For example, if I used a floating iframe, websites could spoof my login window and record the user's login information.</p> <p>Thanks</p> <p>Additional details: My pop-up will come from javascript code from within an iframe in any domain. I know this sounds like I'm creating adverts.. but really I'm not. If it makes any difference, the iframe domain and the pop-up domain are the same.</p> <p>1 more detail, I'm looking to do the same thing "Facebook Connect" does... if you aren't logged into facebook, they allow you to login to facebook from any domain by showing a pop-up on that domain's site. For an example, go to any article at techcrunch.com and use Facebook Connect to comment. Make sure you're logged out of facebook and you'll see what I'm talking about.</p>
[ { "answer_id": 351513, "author": "Sean", "author_id": 44133, "author_profile": "https://Stackoverflow.com/users/44133", "pm_score": 3, "selected": true, "text": "<script language=\"javascript\" type=\"text/javascript\">\n<!--\nfunction popitup(url) {\n newwindow=window.open(url,'name','height=200,width=150'); \n if(!newindow){\n alert('We have detected that you are using popup blocking software...');}\n if (window.focus) {newwindow.focus()}\n return false;\n}\n\n// -->\n</script>\n <a href=\"popupex.html\" onclick=\"return popitup('popupex.html')\">Link to popup</a> \n" }, { "answer_id": 352331, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 1, "selected": false, "text": "<script language=\"javascript\" type=\"text/javascript\">\n<!--\nfunction popitup(url) {\nnewwindow=window.open(url,'name','height=200,width=150');\nif(!newwindow){\n alert('We have detected that you are using popup blocking software...');}\n\nif (window.focus) {newwindow.focus()}\nreturn false;\n}\n\n// -->\n</script>\n" }, { "answer_id": 38765589, "author": "Daniel J Abraham", "author_id": 6564546, "author_profile": "https://Stackoverflow.com/users/6564546", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html>\n<html>\n<body>\n\n<button onclick=\"openWin()\">Open \"myWindow\"</button>\n<button onclick=\"closeWin()\">Close \"myWindow\"</button>\n\n<script>\nvar myWindow;\n\nfunction openWin() {\n myWindow = window.open(\"\", \"myWindow\", \"width=200,height=100\");\n myWindow.document.write(\"<p>This is 'myWindow'</p>\");\n}\n\nfunction closeWin() {\n myWindow.close();\n}\n</script>\n\n</body>\n</html>\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43005/" ]
351,519
<pre><code>typedef union { uint ui[4]; } md5hash; void main(void) { int opt; while ((opt = getopt(argc, argv, "c:t:s:h:")) != -1) { switch (opt) { case 'h': hash = optarg; break; default: /* '?' */ exit(EXIT_FAILURE); } } md5hash hash; sscanf(hash, "%x%x%x%x", &amp;hash.ui); } </code></pre> <p>./program -h ffffffffffffffffffffffffffffffff</p> <p>I want to do the above, but sscanf does not accept the md5sum properly...</p>
[ { "answer_id": 351566, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 3, "selected": false, "text": "sscanf hash %x hashString int fieldsScanned = sscanf (hashString, \"%8x%8x%8x%8x\", &hash.ui[0], &hash.ui[1], &hash.ui[2], &hash.ui[3]);\n\nif (fieldsScanned == 4)\n{\n // MD5 sum is in hash variable.\n}\n" }, { "answer_id": 351968, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "int\nparse_hex(char *s, unsigned char *hex, int len)\n{\n int i, r = 0;\n\n len *= 2;\n for (i = 0; ; i++, s++)\n {\n if (*s == 0 && !(i & 1))\n return i / 2;\n if (i == len)\n {\n fprintf(stderr, \"parsehex: string too long\\n\");\n //exit(1);\n }\n if (*s >= '0' && *s <= '9')\n r = (r << 4) | (*s - '0');\n else if (*s >= 'a' && *s <= 'f')\n r = (r << 4) | (*s - ('a' - 10));\n else if (*s >= 'A' && *s <= 'F')\n r = (r << 4) | (*s - ('a' - 10));\n else\n {\n fprintf(stderr, \"parsehex: bad string\\n\");\n //exit(1);\n }\n if ((i & 1) != 0)\n {\n hex[i / 2] = r;\n r = 0;\n }\n }\n}\n\nvoid\nparse_md5(char *s, unsigned char *md5)\n{\n if (!*s)\n {\n memset(md5, 0, 16);\n return;\n }\n if (parse_hex(s, md5, 16) != 16)\n {\n fprintf(stderr, \"parsemd5: bad md5\\n\");\n //exit(1);\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,520
<p>Greetings!</p> <p>I have an XML value that I'd like to use as a boolean value to toggle the visibility of a Panel. I have something like this:</p> <pre><code>&lt;asp:FormView id="MyFormView" runat="server" DataSourceID="MyXmlDataSource"&gt; &lt;ItemTemplate&gt; &lt;!-- some stuff --&gt; &lt;asp:Panel id="MyPanel" runat="server" Visible='&lt;%# (bool)XPath("Menu/Show") %&gt;'&gt; &lt;/asp:Panel&gt; &lt;!-- some more stuff --&gt; &lt;/ItemTemplate&gt; &lt;/asp:FormView&gt; &lt;asp:XmlDataSource id="MyXmlDataSource" runat="sever" DataFile="MyFile.xml" /&gt; </code></pre> <p>However, this throws an exception. I've tried setting the value of Show in my XML to "true", "True", "0", but to no avail. Is this even possible? My XPath definitely works because I've tried moving &lt;%# (bool)XPath("Menu/Show") %> outside so that I can see its value and it is correct. I have tried this:</p> <pre><code>&lt;%#((bool)XPath("Menu/Show")).ToString() %&gt; </code></pre> <p>But this also throws an exception.</p> <p>Thanks.</p>
[ { "answer_id": 351529, "author": "Andrew Rollings", "author_id": 40410, "author_profile": "https://Stackoverflow.com/users/40410", "pm_score": 1, "selected": false, "text": "<%#(Convert.ToBoolean(XPath(\"Menu/Show\"))) %>" }, { "answer_id": 351568, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 1, "selected": false, "text": "System.Xml.XmlConvert.ToBoolean()\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
351,522
<p>basically, I've got my Huffman table as </p> <pre><code>std::map&lt;std::string, char&gt; ciMap; </code></pre> <p>Where string is the bit pattern and char is the value represented by said pattern. The problem is how do I store that as a header of my compressed file so I can build again the same map when I want to decode it?</p> <p>Trying to store it as binary:</p> <pre><code>size_t mapLen = ciMap.size(); outFile.write(reinterpret_cast&lt;char*&gt;(&amp;mapLen), sizeof(size_t)); outFile.write(reinterpret_cast&lt;char*&gt;(&amp;ciMap), sizeof(ciMap)); </code></pre> <p>And later building with:</p> <pre><code>inFile.read(reinterpret_cast&lt;char*&gt;(&amp;mapLen), sizeof(size_t)); inFile.read(reinterpret_cast&lt;char*&gt;(&amp;ciMap), sizeof(mapLen)); </code></pre> <p>Doesn't work, I get string initilization error... something to do with NULL. Any suggestions? If you have better way of storing the bits and values I'd like to hear.</p>
[ { "answer_id": 351535, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "std::map << reads writes template<typename K, typename V>\nstd::ostream &operator << (std::ostream &out, const std::map<K,V> &map) {\n out << \"map \" << map.size() << \"\\n\";\n for (typename std::map<K,V>::const_iterator i = map.begin(); i != map.end(); ++i) {\n out << (*i).first << \"\\n\" << (*i).second << \"\\n\";\n }\n return out;\n}\n\ntemplate<typename K, typename V>\nstd::istream &operator >> (std::istream &in, std::map<K,V> &map) {\n std::string mapkeyword;\n size_t num;\n in >> mapkeyword >> num;\n for (size_t i = 0; i < num; ++i) {\n K key; V value;\n in >> key >> value;\n map[key] = value;\n }\n return in;\n}\n" }, { "answer_id": 351548, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": true, "text": "typedef std::map<std::string, char> my_map;\nmy_map ciMap;\n\n// saving\nstd::ofstream stream(\"file.txt\");\nfor(my_map::const_iterator it = ciMap.begin(); it != ciMap.end(); ++it) {\n stream << it->first << \" \" << it->second << std::endl;\n}\n\n// loading\nchar c;\nstd::string bits;\nstd::ifstream stream(\"file.txt\");\nwhile(stream >> bits >> c)\n ciMap.insert(std::make_pair(bits, c));\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
351,546
<p>I'm trying to show in the screen a table...</p> <p>Basically I create a custom UITableViewController with the methods needed for the UITableView delegate and data source which is self since UITableViewController does it for you.</p> <p>When I put it in the <code>-initWithRootView:</code> controller, and add the nav's bar view to the window it doesn't show! With debugging, the table is being created and all, but the delegate methods are never called!</p> <p>Any ideas?</p>
[ { "answer_id": 351535, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "std::map << reads writes template<typename K, typename V>\nstd::ostream &operator << (std::ostream &out, const std::map<K,V> &map) {\n out << \"map \" << map.size() << \"\\n\";\n for (typename std::map<K,V>::const_iterator i = map.begin(); i != map.end(); ++i) {\n out << (*i).first << \"\\n\" << (*i).second << \"\\n\";\n }\n return out;\n}\n\ntemplate<typename K, typename V>\nstd::istream &operator >> (std::istream &in, std::map<K,V> &map) {\n std::string mapkeyword;\n size_t num;\n in >> mapkeyword >> num;\n for (size_t i = 0; i < num; ++i) {\n K key; V value;\n in >> key >> value;\n map[key] = value;\n }\n return in;\n}\n" }, { "answer_id": 351548, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": true, "text": "typedef std::map<std::string, char> my_map;\nmy_map ciMap;\n\n// saving\nstd::ofstream stream(\"file.txt\");\nfor(my_map::const_iterator it = ciMap.begin(); it != ciMap.end(); ++it) {\n stream << it->first << \" \" << it->second << std::endl;\n}\n\n// loading\nchar c;\nstd::string bits;\nstd::ifstream stream(\"file.txt\");\nwhile(stream >> bits >> c)\n ciMap.insert(std::make_pair(bits, c));\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,547
<p>I've used the Views Theming Wizard to output a template and it gave me the following chunk of code to go in template.php.</p> <p>I'd prefer to just maintain the one template, so all my functions will be calling the same one, and rather than writing numerous versions of the same function, I'm wondering if there's a way to string function names together? Something like:</p> <pre><code>function phptemplate_views_view_list_recent_articles($view, $nodes, $type), phptemplate_views_view_list_popular_articles($view, $nodes, $type) { $fields = _views_get_fields(); $taken = array(); // Set up the fields in nicely named chunks. foreach ($view-&gt;field as $id =&gt; $field) { $field_name = $field['field']; if (isset($taken[$field_name])) { $field_name = $field['queryname']; } $taken[$field_name] = true; $field_names[$id] = $field_name; } // Set up some variables that won't change. $base_vars = array( 'view' =&gt; $view, 'view_type' =&gt; $type, ); foreach ($nodes as $i =&gt; $node) { $vars = $base_vars; $vars['node'] = $node; $vars['count'] = $i; $vars['stripe'] = $i % 2 ? 'even' : 'odd'; foreach ($view-&gt;field as $id =&gt; $field) { $name = $field_names[$id]; $vars[$name] = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view); if (isset($field['label'])) { $vars[$name . '_label'] = $field['label']; } } $items[] = _phptemplate_callback('views-list-first-with-abstract', $vars); } if ($items) { return theme('item_list', $items); } } </code></pre> <p>Thanks,<br /> Steve</p>
[ { "answer_id": 353285, "author": "pdemarest", "author_id": 40332, "author_profile": "https://Stackoverflow.com/users/40332", "pm_score": 3, "selected": true, "text": "function phptemplate_views_view_list_recent_articles($view, $nodes, $type){\n actual_template_function($view, $nodes, $type);\n}\n\nfunction phptemplate_views_view_list_popular_articles($view, $nodes, $type){\n actual_template_function($view, $nodes, $type);\n}\n" }, { "answer_id": 496914, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "return actual_template_function($view, $nodes, $type);\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16124/" ]
351,557
<p>I'm trying to insert a column into an existing DataSet using C#.</p> <p>As an example I have a DataSet defined as follows:</p> <pre><code>DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("column_1", typeof(string)); ds.Tables[0].Columns.Add("column_2", typeof(int)); ds.Tables[0].Columns.Add("column_4", typeof(string)); </code></pre> <p>later on in my code I am wanting to insert a column between column 2 and column 4.</p> <p>DataSets have methods for adding a column but I can't seem to find the best way in insert one.</p> <p>I'd like to write something like the following...</p> <pre><code>...Columns.InsertAfter("column_2", "column_3", typeof(string)) </code></pre> <p>The end result should be a data set that has a table with the following columns: column_1 column_2 column_3 column_4</p> <p>rather than: column_1 column_2 column_4 column_3 which is what the add method gives me</p> <p>surely there must be a way of doing something like this.</p> <p><strong>Edit</strong>...Just wanting to clarify what I'm doing with the DataSet based on some of the comments below:</p> <blockquote> <p>I am getting a data set from a stored procedure. I am then having to add additional columns to the data set which is then converted into an Excel document. I do not have control over the data returned by the stored proc so I have to add columns after the fact.</p> </blockquote>
[ { "answer_id": 351631, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 7, "selected": true, "text": "DataSet ds = new DataSet();\nds.Tables.Add(new DataTable());\nds.Tables[0].Columns.Add(\"column_1\", typeof(string));\nds.Tables[0].Columns.Add(\"column_2\", typeof(int));\nds.Tables[0].Columns.Add(\"column_4\", typeof(string));\nds.Tables[0].Columns.Add(\"column_3\", typeof(string));\n//set column 3 to be before column 4\nds.Tables[0].Columns[3].SetOrdinal(2);\n" }, { "answer_id": 351799, "author": "mezoid", "author_id": 39532, "author_profile": "https://Stackoverflow.com/users/39532", "pm_score": 3, "selected": false, "text": "public static void InsertAfter(this DataColumnCollection columns, \n DataColumn currentColumn, DataColumn newColumn)\n{\n if (!columns.Contains(currentColumn.ColumnName))\n throw new ArgumentException(/** snip **/);\n\n columns.Add(newColumn);\n //add the new column after the current one\n columns[newColumn.ColumnName].SetOrdinal(currentColumn.Ordinal + 1); \n}\n dt = ds.Tables[0];\n dt.Columns.InsertAfter(dt.Columns[\"column_2\"], new DataColumn(\"column_3\"));\n" }, { "answer_id": 39992239, "author": "sashoalm", "author_id": 492336, "author_profile": "https://Stackoverflow.com/users/492336", "pm_score": 0, "selected": false, "text": "bar foo table.Columns.Add(\"bar\").SetOrdinal(table.Columns.IndexOf(\"foo\"));\n foo +1 table.Columns.Add(\"bar\").SetOrdinal(table.Columns.IndexOf(\"foo\")+1);\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
351,565
<h2><strong>Accuracy Vs. Precision</strong></h2> <p>What I would like to know is whether I should use <strong>System.currentTimeMillis()</strong> or <strong>System.nanoTime()</strong> when updating my object's positions in my game? Their change in movement is directly proportional to the elapsed time since the last call and I want to be as precise as possible.</p> <p>I've read that there are some serious time-resolution issues between different operating systems (namely that Mac / Linux have an almost 1 ms resolution while Windows has a 50ms resolution??). I'm primarly running my apps on windows and 50ms resolution seems pretty inaccurate.</p> <p>Are there better options than the two I listed?</p> <p>Any suggestions / comments?</p>
[ { "answer_id": 351571, "author": "dancavallaro", "author_id": 42891, "author_profile": "https://Stackoverflow.com/users/42891", "pm_score": 9, "selected": true, "text": "System.nanoTime() System.currentTimeMillis() System.nanoTime() public static long nanoTime()\n long startTime = System.nanoTime(); \n// ... the code being measured ... \nlong estimatedTime = System.nanoTime() - startTime;\n" }, { "answer_id": 351572, "author": "Paul Morel", "author_id": 1311247, "author_profile": "https://Stackoverflow.com/users/1311247", "pm_score": 4, "selected": false, "text": "System.nanoTime() currentTimeMillis currentTimeMillis()" }, { "answer_id": 351600, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 3, "selected": false, "text": "System.nanoTime() private void test() {\n System.out.println(\"currentTimeMillis: \"+System.currentTimeMillis());\n System.out.println(\"nanoTime : \"+System.nanoTime());\n System.out.println();\n\n testNano(false); // to sync with currentTimeMillis() timer tick\n for(int xa=0; xa<10; xa++) {\n testNano(true);\n }\n }\n\nprivate void testNano(boolean shw) {\n long strMS=System.currentTimeMillis();\n long strNS=System.nanoTime();\n long curMS;\n while((curMS=System.currentTimeMillis()) == strMS) {\n if(shw) { System.out.println(\"Nano: \"+(System.nanoTime()-strNS)); }\n }\n if(shw) { System.out.println(\"Nano: \"+(System.nanoTime()-strNS)+\", Milli: \"+(curMS-strMS)); }\n }\n" }, { "answer_id": 351921, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": false, "text": "System.currentTimeMillis() System.currentTimeMillis() System.nanoTime() Thread.sleep()" }, { "answer_id": 9314616, "author": "gub", "author_id": 2453638, "author_profile": "https://Stackoverflow.com/users/2453638", "pm_score": 7, "selected": false, "text": "System.nanoTime() System.currentTimeMillis() nanoTime() currentTimeMillis()" }, { "answer_id": 45725702, "author": "Thomas W", "author_id": 768795, "author_profile": "https://Stackoverflow.com/users/768795", "pm_score": 2, "selected": false, "text": "System.nanoTime() System.currentTimeMillis() nanoTime()" }, { "answer_id": 47535594, "author": "Ricardo Gasca", "author_id": 6268218, "author_profile": "https://Stackoverflow.com/users/6268218", "pm_score": 2, "selected": false, "text": "System.currentTimeMillis() System.nanoTime System.currentTimeMillis()" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
351,578
<p>I need to make OK and Cancel buttons in my HTML, and I'd like them to be a fixed width so the two buttons are the same size. For example, like this:</p> <pre><code>&lt;style&gt; button.ok_cancel { width: 50px; background-color: #4274af; font-size: 9px; line-height: 12px; color: #fff; cursor: pointer; text-transform: uppercase; padding: 1px; border: 0px; margin: 0 0 0 5px; text-align: center; letter-spacing: 1px; } &lt;/style&gt; &lt;button class="ok_cancel" onclick="do_cancel()"&gt;Cancel&lt;/button&gt; </code></pre> <p>But now I'm localizing the text, and the translation for "Cancel" can be too wide for the button. I want the button to be its fixed width of 50 pixels if the string fits, but to expand in width if the string is wider. A fixed amount of side padding would be used to keep the button looking good.</p> <p>I know I probably can't do this with pure CSS, but what's the simplest HTML I can use that will give me the effect I want? </p>
[ { "answer_id": 354820, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 3, "selected": true, "text": "/* Browser hack! This is for everyone: */\nbutton {\n display: inline;\n cursor: pointer;\n padding: 6px 6px;\n width: 50px;\n overflow: visible;\n}\n/* and this is for non-IE browsers: */\nhtml>body button {\n min-width: 50px;\n width: auto;\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14343/" ]
351,602
<p>Just curious, did I overlook somewhere in the API to display a chat bubble type image as found in the iPhone's SMS application? There's a few applications out there that use bubbles that look verbatim to the iPhone's and I'm wondering if they're using a native widget or their own image.</p> <p>This is also seen in the Tweetie application where the content of the tweets are.</p>
[ { "answer_id": 698871, "author": "Jab", "author_id": 29676, "author_profile": "https://Stackoverflow.com/users/29676", "pm_score": 5, "selected": true, "text": "[UIImage stretchableImageWithLeftCapWidth:15 topCapHeight:13]\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40882/" ]
351,627
<p>I'm building an iPhone application that talks to a Ruby on Rails backend. The Ruby on Rails application will also service web users. The restful_authentication plugin is an excellent way to provide quick and customizable user authentication. However, I would like users of the iPhone application to have an account created automatically by the phone's unique identifier ([[UIDevice device] uniqueIdentifier]) stored in a new column. Later, when users are ready to create a username/password, the account will be updated to contain the username and password, leaving the iPhone unique identifier intact. Users should not be able to access the website until they've setup their username/password. They can however, use the iPhone application, since the application can authenticate itself using it's identifier.</p> <p>What is the best way to modify restful_authentication to do this? Create a plugin? Or modify the generated code?</p> <p>What about alternative frameworks, such as AuthLogic. What is the best way to allow iPhones to get a generated auth token locked to their UUID's, but then let the user create a username/password later?</p>
[ { "answer_id": 2570066, "author": "Leandro Ardissone", "author_id": 42565, "author_profile": "https://Stackoverflow.com/users/42565", "pm_score": 0, "selected": false, "text": "salt = 'afG553Dvbf3'\n\nudid = '1234567890'\npass = Digest::MD5.hexdigest(udid + salt)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44482/" ]
351,633
<p>I currently have issues in Webkit(Safari and Chrome) were I try to load dynamically (innerHTML) some html into a div, the html contains css rules (...), after the html gets rendered the style definitions are not loaded (so visually I can tell the styles are not there and also if I search with javascript for them no styles are found). I have tried using a jquery plugin tocssRule(), it works but it is just too slow. Is there another way of getting webkit to load the styles dynamically? Thanks. Patrick</p>
[ { "answer_id": 352060, "author": "I.devries", "author_id": 6388, "author_profile": "https://Stackoverflow.com/users/6388", "pm_score": 4, "selected": true, "text": "var link = document.createElement('link');\n\nlink.setAttribute('rel', 'stylesheet');\n\nlink.type = 'text/css';\n\nlink.href = 'http://example.com/stylesheet.css';\n\ndocument.head.appendChild(link);\n var style = document.createElement('style');\n\nstyle.innerHTML = 'body { background-color: #F00; }';\n\ndocument.head.appendChild(style);\n" }, { "answer_id": 353748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var cssDefinitions = '..my style chunk goes here';\nvar style = document.createElement('style');'\n$(style).html(cssDefinitions);\n$('head').append(style);" }, { "answer_id": 952733, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " var ref = document.createElement('style');\nref.setAttribute(\"rel\", \"stylesheet\");\nref.setAttribute(\"type\", \"text/css\");\ndocument.getElementsByTagName(\"head\")[0].appendChild(ref);\nif(!!(window.attachEvent && !window.opera)) ref.styleSheet.cssText = asd;//this one's for ie\nelse ref.appendChild(document.createTextNode(asd));\n" }, { "answer_id": 1230529, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var cssLink = $('<link />');\ncssLink.attr(\"rel\",\"stylesheet\")\ncssLink.attr(\"type\", \"text/css\");\ncssLink.attr(\"href\",\"url/to.css\");\n" }, { "answer_id": 1948571, "author": "jeffreypriebe", "author_id": 1592, "author_profile": "https://Stackoverflow.com/users/1592", "pm_score": 2, "selected": false, "text": "$(\"head\").append(\"<link />\");\nvar CSS = $(\"head\").children(\":last\");\nCSS.attr({\n\"rel\": \"stylesheet\",\n\"type\": \"text/css\",\n\"href\": \"url/to.css\"\n});\n" }, { "answer_id": 2986369, "author": "tstanis", "author_id": 359897, "author_profile": "https://Stackoverflow.com/users/359897", "pm_score": 0, "selected": false, "text": "var style = document.getElementById('some-style-tag');\nvar sheet = style.sheet;\nsheet.insertRule('.mydiv { background-color: ' + color + '; }', sheet.cssRules.length);\n" }, { "answer_id": 17034579, "author": "Kirk B.", "author_id": 1367983, "author_profile": "https://Stackoverflow.com/users/1367983", "pm_score": 0, "selected": false, "text": "var oStyle = $(\"<style />\");\n\noStyle.append(\"@import url(\" + sTemplateCssUrl + \");\");\noStyle.attr(\"type\", \"text/css\");\n\n$(document.head).append(oStyle);\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,635
<p>Is there anyone already implement memcached for production use in Windows environment? Because many blogs that I've read, it's not recommended to run memcached in Windows especially for production use, for example <a href="http://latebound.blogspot.com/2008/10/running-memcached-on-windows.html" rel="noreferrer">running memcached on windows</a>.</p> <p>And one more thing, which memcached client that is good to use with c# and .net 3.5 ? I've found many alternate such as <a href="http://www.codeplex.com/memcachedproviders" rel="noreferrer">Memcached Providers @ Codeplex</a>, <a href="http://code.google.com/p/beitmemcached/" rel="noreferrer">Beitmemcached</a>, and <a href="http://sourceforge.net/projects/memcacheddotnet" rel="noreferrer">memcached provider @ Sourceforge</a></p>
[ { "answer_id": 1112675, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 4, "selected": false, "text": "Cache*" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37509/" ]
351,640
<p>What is the proper way to install Hibernate Tools in Eclipse as a plugin? The <a href="http://www.hibernate.org/255.html" rel="noreferrer" title="Hibernate site">Hibernate site</a> doesn't really give any instructions.</p> <p>Looking at the Hibernate Tools binary <code>HibernateTools-3.2.4.Beta1-R200810311334.zip</code>, it appears that I can just unzip this in my eclipse directory. Do I just unzip it in my eclipse directory? This seems like a hacky was to install it.</p>
[ { "answer_id": 352429, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "[eclipse\\dropins\\HibernateTools-3.2.4.Beta1-R20081031133] [eclipse\\dropins\\HibernateTools-3.2.4.Beta1-R20081031133\\eclipse] name=QuickRex\nid=org.hibernate.eclipse\nversion=3.2.4b1\n eclipse\n dropins\n HibernateTools-3.2.4.Beta1-R20081031133\n eclipse\n .eclipseextension\n features\n plugins\n eclipse\\dropins" }, { "answer_id": 35099192, "author": "Divyesh Kanzariya", "author_id": 5246706, "author_profile": "https://Stackoverflow.com/users/5246706", "pm_score": 2, "selected": false, "text": "Eclipse_Version HibernateTools-5.X.zip" }, { "answer_id": 41742879, "author": "Luís de Sousa", "author_id": 2066215, "author_profile": "https://Stackoverflow.com/users/2066215", "pm_score": 3, "selected": false, "text": "Help Install New Software Add http://download.jboss.org/jbosstools/neon/stable/updates/ \n JBoss Web and Java EE Development Hibernate Tools Next > Window Perspective Open Perspective Others" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
351,644
<p>I'm using ADO.NET dataservices in a Silverlight application and since the silverlight libraries don't support the ToList() call on the IQueryable I thought it might be possible to create an extension method around this called SilverlightToList(). So in this method I'm calling the BeginExecute method on my context as shown below: </p> <pre><code> var result = context.BeginExecute&lt;T&gt;(currentRequestUri,null,context); result.AsyncWaitHandle.WaitOne(); return context.EndExecute&lt;T&gt;(result).ToList(); </code></pre> <p>The problem is that when I call the WaitOne() method this results in a deadlock. Is this a limitation of ADO.NET dataservices in Silverlight? Is there perhaps a workaround for this?</p>
[ { "answer_id": 351817, "author": "Boyan", "author_id": 38106, "author_profile": "https://Stackoverflow.com/users/38106", "pm_score": 1, "selected": false, "text": "context.BeginExecute<T>(currentRequestUri, resultCallback, context);\n\nprivate void resultCallback(IAsyncResult asyncResult)\n{\n DataServiceContext context = asyncResult.AsyncState as DataServiceContext;\n var result = context.EndExecute<T>(asyncResult);\n // Do whatever you need with the result here\n}\n" }, { "answer_id": 1536395, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 2, "selected": false, "text": "var ctx = new ModelEntities(new Uri(\"http://localhost:2115/Data.svc\"));\n\nManualResetEvent m1 = new ManualResetEvent(false);\nManualResetEvent m2 = new ManualResetEvent(false);\n\nvar q1 = (DataServiceQuery<Department>)(from e in ctx.Department select e);\nvar q2 = (DataServiceQuery<Person>)(from e in ctx.Person select e);\n\nDepartment[] r1 = null;\nPerson[] r2 = null;\n\nq1.BeginExecute(r =>\n{\n try { r1 = q1.EndExecute(r).ToArray(); }\n finally { m1.Set(); }\n}, null);\nq2.BeginExecute(r =>\n{\n try { r2 = q2.EndExecute(r).ToArray(); }\n finally { m2.Set(); }\n}, null);\n\nThreadPool.QueueUserWorkItem((o) =>\n{\n WaitHandle.WaitAll(new WaitHandle[] { m1, m2 });\n // do your thing..\n});\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36086/" ]
351,656
<p>I'm curious to know if there is an easy way to mock an IMAP server (a la the <code>imaplib</code> module) in Python, <em>without</em> doing a lot of work.</p> <p>Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure.</p> <p>Some background into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would <em>like</em> to create a proper testing environment, but given that it might <em>not</em> grow over time, I don't want to do much work to get the mock server running.</p>
[ { "answer_id": 35488764, "author": "Bruno Thomas", "author_id": 396155, "author_profile": "https://Stackoverflow.com/users/396155", "pm_score": 3, "selected": false, "text": "factory = loop.create_server(lambda: ImapProtocol(mailbox_map), 'localhost', 1143)\nserver = loop.run_until_complete(factory)\n class ImapHandler(object):\n def __init__(self, mailbox_map):\n self.mailbox_map = mailbox_map\n self.user_login = None\n # ...\n\n def connection_made(self, transport):\n self.transport = transport\n transport.write('* OK IMAP4rev1 MockIMAP Server ready\\r\\n'.encode())\n\n def data_received(self, data):\n command_array = data.decode().rstrip().split()\n tag = command_array[0]\n self.by_uid = False\n self.exec_command(tag, command_array[1:])\n\n def connection_lost(self, error):\n if error:\n log.error(error)\n else:\n log.debug('closing')\n self.transport.close()\n super().connection_lost(error)\n\n def exec_command(self, tag, command_array):\n command = command_array[0].lower()\n if not hasattr(self, command):\n return self.error(tag, 'Command \"%s\" not implemented' % command)\n getattr(self, command)(tag, *command_array[1:])\n\n def capability(self, tag, *args):\n # code for it...\n def login(self, tag, *args):\n # code for it...\n self.loop = asyncio.get_event_loop()\nself.server = self.loop.run_until_complete(self.loop.create_server(create_imap_protocol, 'localhost', 12345))\n imap_receive(Mail(to='dest@fakemail.org', mail_from='exp@pouet.com', subject='hello'))\n self.server.close()\nasyncio.wait_for(self.server.wait_closed(), 1)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
351,657
<p>By default sqlplus truncates column names to the length of the underlying data type. Many of the column names in our database are prefixed by the table name, and therefore look identical when truncated.</p> <p>I need to specify select * queries to remote DBAs in a locked down production environment, and drag back spooled results for diagnosis. There are too many columns to specify individual column formatting. Does sqlplus offer any option to uniformly defeat column name truncation?</p> <p>(I am using SET MARKUP HTML ON, though I could use some other modality, csv, etc. as long as it yields unabbreviated output.)</p>
[ { "answer_id": 353335, "author": "m0j0", "author_id": 31319, "author_profile": "https://Stackoverflow.com/users/31319", "pm_score": 1, "selected": false, "text": "ALL_TAB_COLS #!/usr/bin/python\n\nimport sys\nimport cx_Oracle\n\nresponse=raw_input(\"Enter schema.table_name: \")\n(schema, table) = response.split('.')\nschema = schema.upper()\ntable = table.upper()\nsqlstr = \"\"\"select column_name,\n data_type,\n data_length\n from all_tab_cols\n where owner = '%s'\n and table_name = '%s'\"\"\" % ( schema, table )\n\n## open a connection to databases...\ntry:\n oracle = cx_Oracle.Connection( oracleLogin )\n oracle_cursor = oracle.cursor()\n\nexcept cx_Oracle.DatabaseError, exc:\n print \"Cannot connect to Oracle database as\", oracleLogin\n print \"Oracle Error %d: %s\" % ( exc.args[0].code, exc.args[0].message )\n sys.exit(1)\n\ntry:\n oracle_cursor.execute( sqlstr )\n\n # fetch resultset from cursor\n for column_name, data_type, data_length in oracle_cursor.fetchmany(256):\n data_length = data_length + 0\n if data_length < len(column_name):\n if data_type == \"CHAR\" or data_type == \"VARCHAR2\":\n print \"column %s format a%d\" % ( column_name.upper(), len(column_name) )\n else:\n print \"-- Handle %s, %s, %d\" % (column_name, data_type, data_length)\n\nexcept cx_Oracle.DatabaseError, e:\n print \"[Oracle Error %d: %s]: %s\" % (e.args[0].code, e.args[0].message, sqlstr)\n sys.exit(1)\n\ntry:\n oracle_cursor.close()\n oracle.close()\nexcept cx_Oracle.DatabaseError, exc:\n print \"Warning: Oracle Error %d: %s\" % ( exc.args[0].code, exc.args[0].message )\n\nprint \"select *\"\nprint \"from %s.%s\" % ( schema, table )\n" }, { "answer_id": 354550, "author": "IK.", "author_id": 21283, "author_profile": "https://Stackoverflow.com/users/21283", "pm_score": 2, "selected": false, "text": "set termout off\nset feedback off\n\nspool t1.sql\nselect 'column ' || column_name || ' format a' || data_length\nfrom all_tab_cols\nwhere table_name='YOUR_TABLE'\n/\nspool off\n\n@t1.sql\nset pagesize 24\nset heading on\nspool result.txt\nselect * \nfrom YOUR_TABLE;\nand rownum < 30;\nspool off\n select 'column ' || column_name ||\n ' heading \"' ||\n chr(ascii('A') - 1 + column_id) ||\n '\"'\nfrom all_tab_cols\nwhere table_name='YOUR_TAB_NAME'\n column DEPT_NO heading \"A\"\ncolumn NAME heading \"B\"\ncolumn SUPERVIS_ID heading \"C\"\ncolumn ADD_DATE heading \"D\"\ncolumn REPORT_TYPE heading \"E\"\n" }, { "answer_id": 5722517, "author": "srmeyer", "author_id": 715982, "author_profile": "https://Stackoverflow.com/users/715982", "pm_score": 2, "selected": false, "text": "SELECT 'COLUMN ' || column_name || ' FORMAT ' ||\n CASE\n WHEN data_type = 'DATE' THEN\n 'A9'\n WHEN data_type LIKE '%CHAR%' THEN\n 'A' ||\n TRIM(TO_CHAR(LEAST(GREATEST(LENGTH(column_name),\n data_length), 40))) ||\n CASE\n WHEN data_length > 40 THEN\n ' TRUNC'\n ELSE\n NULL\n END\n WHEN data_type = 'NUMBER' THEN\n LPAD('0', GREATEST(LENGTH(column_name),\n NVL(data_precision, data_length)), '9') ||\n DECODE(data_scale, 0, NULL, NULL, NULL, '.' ||\n LPAD('0', data_scale, '0'))\n WHEN data_type IN ('RAW', 'LONG') THEN\n 'A1 NOPRINT'\n WHEN data_type LIKE '%LOB' THEN\n 'A1 NOPRINT'\n ELSE\n 'A' || TRIM(TO_CHAR(GREATEST(LENGTH(column_name), data_length)))\n END AS format_cols\n FROM dba_tab_columns\n WHERE owner = 'SYS'\n AND table_name = 'DBA_TAB_COLUMNS';\n" }, { "answer_id": 5722662, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 1, "selected": false, "text": "VARIABLE resultXML clob;\nSET LONG 100000; -- Set to the maximum size of the XML you want to display (in bytes) \nSET PAGESIZE 0;\n\nDECLARE\n qryCtx DBMS_XMLGEN.ctxHandle;\nBEGIN\n qryCtx := dbms_xmlgen.newContext('SELECT * from scott.emp');\n\n -- now get the result\n :resultXML := DBMS_XMLGEN.getXML(qryCtx);\n\n --close context\n DBMS_XMLGEN.closeContext(qryCtx);\nEND;\n/\n\nprint resultXML\n" }, { "answer_id": 6042470, "author": "talek", "author_id": 381815, "author_profile": "https://Stackoverflow.com/users/381815", "pm_score": 0, "selected": false, "text": "set feedback off \nset serveroutput on\ndeclare\n l_c number;\n l_col_cnt number;\n l_rec_tab DBMS_SQL.DESC_TAB2;\n l_col_metadata DBMS_SQL.DESC_REC2;\n l_col_num number;\nbegin\n l_c := dbms_sql.open_cursor;\n dbms_sql.parse(l_c, '<YOUR QUERY HERE>', DBMS_SQL.NATIVE);\n DBMS_SQL.DESCRIBE_COLUMNS2(l_c, l_col_cnt, l_rec_tab);\n for colidx in l_rec_tab.first .. l_rec_tab.last loop\n l_col_metadata := l_rec_tab(colidx);\n dbms_output.put_line('column ' || l_col_metadata.col_name || ' heading ' || l_col_metadata.col_name);\n end loop;\n DBMS_SQL.CLOSE_CURSOR(l_c);\nend;\n" }, { "answer_id": 24436121, "author": "user6856", "author_id": 3709116, "author_profile": "https://Stackoverflow.com/users/3709116", "pm_score": 2, "selected": false, "text": "SET ECHO OFF\nSET PAGESIZE 32766\nSET LINESIZE 32766\nSET NUMW 20\nSET VERIFY OFF\nSET TERM OFF\nSET UNDERLINE OFF\nSET MARKUP HTML ON\nSET PREFORMAT ON\nSET WORD_WRAP ON\nSET WRAP ON\nSET ENTMAP ON\nspool '/tmp/Example.html'\nselect \n (s.ID||' ') AS ID,\n (s.ORDER_ID||' ') AS ORDER_ID,\n (s.ORDER_NUMBER||' ') AS ORDER_NUMBER,\n (s.CONTRACT_ID||' ') AS CONTRACT_ID,\n (s.CONTRACT_NUMBER||' ') AS CONTRACT_NUMBER,\n (s.CONTRACT_START_DATE||' ') AS CONTRACT_START_DATE,\n (s.CONTRACT_END_DATE||' ') AS CONTRACT_END_DATE,\n (s.CURRENCY_ISO_CODE||' ') AS CURRENCY_ISO_CODE,\nfrom Example s\norder by s.order_number, s.contract_number;\nspool off;\n SET ECHO OFF\nSET TERMOUT OFF\nSET FEEDBACK OFF\nSET PAGESIZE 32766\nSET LINESIZE 32766\nSET MARKUP HTML OFF\nSET HEADING OFF\n\nspool /tmp/columns_EXAMPLE.sql\nselect 'column ' || column_name || ' format A32766' \nfrom all_tab_cols\nwhere data_type = 'VARCHAR2' and table_name = 'EXAMPLE'\n/\nspool off\n\nSET HEADING ON\nSET NUMW 40\nSET VERIFY OFF\nSET TERM OFF\nSET UNDERLINE OFF\nSET MARKUP HTML ON\nSET PREFORMAT ON\nSET WORD_WRAP ON\nSET WRAP ON\nSET ENTMAP ON\n@/tmp/columns_EXAMPLE.sql\nspool '/tmp/Example.html'\nselect *\nfrom Example s\norder by s.order_number, s.contract_number;\nspool off;\n" }, { "answer_id": 74226447, "author": "spioter", "author_id": 1279373, "author_profile": "https://Stackoverflow.com/users/1279373", "pm_score": 0, "selected": false, "text": "set colsep ',' chr(9) chr(44) /*google \"sqlplus OPTION\" to get the meaning */\n set colsep ' ' --literal TAB; can alter to taste\n set HEADING OFF\n set UNDERLINE OFF\n set PAGESIZE 50000\n set LINESIZE 32767\n set TERMOUT OFF\n set TRIMSPOOL ON\n set FEEDBACK OFF\n set WRAP OFF\n set NEWPAGE none\n\n/*first, write the column names to the file*/\n spool \"C:\\yourPath\\output.txt\"\n select listagg(column_name, chr(9) ) within group (order by column_id)\n FROM dba_tab_columns\n WHERE owner = 'SomeOwner'\n AND table_name = upper('ViewOrTable_Name')\n ;\n\n/*now append the data*/\n spool \"C:\\yourPath\\output.txt\" append\n\n select * from SomeOwner.ViewOrTable_Name\n where 1 = 1\n ;\n\n/*stop spooling*/\nspool OFF\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
351,661
<p>Can you store an Array ( that contains another two subarrays one being a string and another another array) into a single MutableArray object?</p>
[ { "answer_id": 351673, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 0, "selected": false, "text": "NSMutableArray * completeArray =\n [NSMutableArray arrayWithArray:\n [[myArray objectAtIndex:0] arrayByAddingObjectsFromArray:\n [myArray objectAtIndex:1]]]; myArray \nNSArray * stringArray = [NSArray arrayWithObjects:\n @\"one\", @\"two\", @\"three\", nil];\nNSArray * otherArray = [NSArray arrayWithObjects:\n someObj, otherObj, thirdObj, nil];\nNSArray * myArray = [NSArray arrayWithObjects:\n stringArray, otherArray, nil]; NSMutableArray @\"one, @\"two\", @\"three\", someObj, otherObj, thirdObj" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,690
<p>In order to write better code, is it worth to know deeply what the compiler does? </p> <p>Just how much would be enough? I'm not a bit scrubber, but I was thinking that knowing how the compiler operates would make me a better programmer. Am I wrong? </p> <p>If so, what resources would you recommend?</p>
[ { "answer_id": 352126, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 2, "selected": false, "text": " answer = answer .. strings[i] -- .. is string concatenation\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12423/" ]
351,720
<p>Is it a good idea to share views between different controllers (using the <em>Views/Shared</em> folder)?<br><br> I am creating my first MVC application and it requires some pieces of data that are similar to each other. They "explain" different things (and will therefore be stored in different tables) but they each have an <code>Id</code>, <code>Name</code> and <code>Status</code>. I can therefore use different controllers which then use the same View to display the data in a drop down list, allow the user to select one to edit or add a new one via a text box.<br><br> Obviously I lose the ability to have strongly typed ViewPage data but besides that, would this be considered a good way to do this or am I better off creating a View for each controller to use?</p>
[ { "answer_id": 351803, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 1, "selected": false, "text": "public class MyCustomViewData\n{\n public int Id {get; set;}\n public string Name {get; set;}\n public int Status {get; set;}\n}\n <% Html.RenderPartial(\"MyCustomView\", new MyCustomViewData ()\n{\n Id = ViewData.Model.SomeIdField,\n Name = ViewData.Model.SomeNameField,\n Status = ViewData.Model.SomeStatusField\n});\n public ActionResult Foo()\n{\n // get your model data\n\n return View(\"MyCustomView\", new MyCustomViewData ()\n {\n Id = model.SomeIdField,\n Name = model.SomeNameField,\n Status = model.SomeStatusField\n });\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17248/" ]
351,732
<p>How do you usually convert line breaks in a form textbox or input=text element to html line breaks?</p> <p>Thanks</p> <p>Edit: Is it always \r\n with all browsers?</p>
[ { "answer_id": 351735, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 2, "selected": false, "text": "Replace(vbcrlf, \"<br />\")\n" }, { "answer_id": 351747, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 3, "selected": false, "text": "myString.Replace(\"\\r\\n\", \"<br />\");\n myString.Replace(\"\\r\\n\", \"<br />\");\nmyString.Replace(\"\\n\", \"<br />\");\nmyString.Replace(\"\\r\", \"<br />\");\n" }, { "answer_id": 351762, "author": "ChadT", "author_id": 23300, "author_profile": "https://Stackoverflow.com/users/23300", "pm_score": 2, "selected": false, "text": "System.Environment.NewLine \n" }, { "answer_id": 2414080, "author": "JordanC", "author_id": 172330, "author_profile": "https://Stackoverflow.com/users/172330", "pm_score": 0, "selected": false, "text": "MyString.Replace(Chr(10), \"<br/>\")\n" }, { "answer_id": 11856439, "author": "roopalgarg", "author_id": 1462047, "author_profile": "https://Stackoverflow.com/users/1462047", "pm_score": 1, "selected": false, "text": "Regex.Replace(urString, \"\\r?\\n\", \"< br/>\");\n" }, { "answer_id": 20355984, "author": "hotdog", "author_id": 999769, "author_profile": "https://Stackoverflow.com/users/999769", "pm_score": -1, "selected": false, "text": "MyString.Replace(\"\\\\r\\\\n\", \"<br />\")\n MyString.Replace(\"\\\\r\\\\n\", Environment.NewLine)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676066/" ]
351,733
<p>What are some ways to write object-oriented code in C? Especially with regard to polymorphism.</p> <hr/> <p>See also this Stack Overflow question <em><a href="https://stackoverflow.com/questions/415452/object-orientation-in-c">Object-orientation in C</a></em>.</p>
[ { "answer_id": 351745, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 9, "selected": false, "text": "struct typedef struct {\n int (*open)(void *self, char *fspec);\n int (*close)(void *self);\n int (*read)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);\n int (*write)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);\n // And data goes here.\n} tCommClass;\n\ntCommClass commRs232;\ncommRs232.open = &rs232Open;\n: :\ncommRs232.write = &rs232Write;\n\ntCommClass commTcp;\ncommTcp.open = &tcpOpen;\n: :\ncommTcp.write = &tcpWrite;\n rs232Init() int stat = (commTcp.open)(commTcp, \"bigiron.box.com:5000\");\n #include <stdio.h>\n\n// The top-level class.\n\ntypedef struct sCommClass {\n int (*open)(struct sCommClass *self, char *fspec);\n} tCommClass;\n // Function for the TCP 'class'.\n\nstatic int tcpOpen (tCommClass *tcp, char *fspec) {\n printf (\"Opening TCP: %s\\n\", fspec);\n return 0;\n}\nstatic int tcpInit (tCommClass *tcp) {\n tcp->open = &tcpOpen;\n return 0;\n}\n // Function for the HTTP 'class'.\n\nstatic int httpOpen (tCommClass *http, char *fspec) {\n printf (\"Opening HTTP: %s\\n\", fspec);\n return 0;\n}\nstatic int httpInit (tCommClass *http) {\n http->open = &httpOpen;\n return 0;\n}\n // Test program.\n\nint main (void) {\n int status;\n tCommClass commTcp, commHttp;\n\n // Same 'base' class but initialised to different sub-classes.\n\n tcpInit (&commTcp);\n httpInit (&commHttp);\n\n // Called in exactly the same manner.\n\n status = (commTcp.open)(&commTcp, \"bigiron.box.com:5000\");\n status = (commHttp.open)(&commHttp, \"http://www.microsoft.com\");\n\n return 0;\n}\n Opening TCP: bigiron.box.com:5000\nOpening HTTP: http://www.microsoft.com\n" }, { "answer_id": 351766, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 3, "selected": false, "text": "#include<stdio.h>\n\nstruct foobarbaz{\n int one;\n int two;\n int three;\n int (*exampleMethod)(int, int);\n};\n\nint addTwoNumbers(int a, int b){\n return a+b;\n}\n\nint main()\n{\n // Define the function pointer\n int (*pointerToFunction)(int, int) = addTwoNumbers;\n\n // Let's make sure we can call the pointer\n int test = (*pointerToFunction)(12,12);\n printf (\"test: %u \\n\", test);\n\n // Now, define an instance of our struct\n // and add some default values.\n struct foobarbaz fbb;\n fbb.one = 1;\n fbb.two = 2;\n fbb.three = 3;\n\n // Now add a \"method\"\n fbb.exampleMethod = addTwoNumbers;\n\n // Try calling the method\n int test2 = fbb.exampleMethod(13,36);\n printf (\"test2: %u \\n\", test2);\n\n printf(\"\\nDone\\n\");\n return 0;\n}\n" }, { "answer_id": 352364, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 4, "selected": false, "text": "this this struct Animal_Vtable{\n typedef void (*Walk_Fun)(struct Animal *a_This);\n typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);\n\n Walk_Fun Walk;\n Dtor_Fun Dtor;\n};\n\nstruct Animal{\n Animal_Vtable vtable;\n\n char *Name;\n};\n\nstruct Dog{\n Animal_Vtable vtable;\n\n char *Name; // Mirror member variables for easy access\n char *Type;\n};\n\nvoid Animal_Walk(struct Animal *a_This){\n printf(\"Animal (%s) walking\\n\", a_This->Name);\n}\n\nstruct Animal* Animal_Dtor(struct Animal *a_This){\n printf(\"animal::dtor\\n\");\n return a_This;\n}\n\nAnimal *Animal_Alloc(){\n return (Animal*)malloc(sizeof(Animal));\n}\n\nAnimal *Animal_New(Animal *a_Animal){\n a_Animal->vtable.Walk = Animal_Walk;\n a_Animal->vtable.Dtor = Animal_Dtor;\n a_Animal->Name = \"Anonymous\";\n return a_Animal;\n}\n\nvoid Animal_Free(Animal *a_This){\n a_This->vtable.Dtor(a_This);\n\n free(a_This);\n}\n\nvoid Dog_Walk(struct Dog *a_This){\n printf(\"Dog walking %s (%s)\\n\", a_This->Type, a_This->Name);\n}\n\nDog* Dog_Dtor(struct Dog *a_This){\n // Explicit call to parent destructor\n Animal_Dtor((Animal*)a_This);\n\n printf(\"dog::dtor\\n\");\n\n return a_This;\n}\n\nDog *Dog_Alloc(){\n return (Dog*)malloc(sizeof(Dog));\n}\n\nDog *Dog_New(Dog *a_Dog){\n // Explict call to parent constructor\n Animal_New((Animal*)a_Dog);\n\n a_Dog->Type = \"Dog type\";\n a_Dog->vtable.Walk = (Animal_Vtable::Walk_Fun) Dog_Walk;\n a_Dog->vtable.Dtor = (Animal_Vtable::Dtor_Fun) Dog_Dtor;\n\n return a_Dog;\n}\n\nint main(int argc, char **argv){\n /*\n Base class:\n\n Animal *a_Animal = Animal_New(Animal_Alloc());\n */\n Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());\n\n a_Animal->vtable.Walk(a_Animal);\n\n Animal_Free(a_Animal);\n}\n" }, { "answer_id": 2732721, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 3, "selected": false, "text": "objc_msg_send" }, { "answer_id": 2732876, "author": "Patrick Schlüter", "author_id": 146377, "author_profile": "https://Stackoverflow.com/users/146377", "pm_score": 4, "selected": false, "text": "void * #ifndef FOO_H_\n#define FOO_H_\n\n...\n typedef struct FOO_type FOO_type; /* That's all the rest of the program knows about FOO */\n\n/* Declaration of accessors, functions */\nFOO_type *FOO_new(void);\nvoid FOO_free(FOO_type *this);\n...\nvoid FOO_dosomething(FOO_type *this, param ...):\nchar *FOO_getName(FOO_type *this, etc);\n#endif\n #include <stdlib.h>\n...\n#include \"FOO.h\"\n\nstruct FOO_type {\n whatever...\n};\n\n\nFOO_type *FOO_new(void)\n{\n FOO_type *this = calloc(1, sizeof (FOO_type));\n\n ...\n FOO_dosomething(this, );\n return this;\n}\n this" }, { "answer_id": 2733004, "author": "nategoose", "author_id": 299301, "author_profile": "https://Stackoverflow.com/users/299301", "pm_score": 7, "selected": false, "text": "stack_push(thing *)\n stack::push(thing *)\n class stack {\n public:\n stack();\n void push(thing *);\n thing * pop();\n static int this_is_here_as_an_example_only;\n private:\n ...\n};\n struct stack {\n struct stack_type * my_type;\n // Put the stuff that you put after private: here\n};\nstruct stack_type {\n void (* construct)(struct stack * this); // This takes uninitialized memory\n struct stack * (* operator_new)(); // This allocates a new struct, passes it to construct, and then returns it\n void (*push)(struct stack * this, thing * t); // Pushing t onto this stack\n thing * (*pop)(struct stack * this); // Pops the top thing off the stack and returns it\n int this_is_here_as_an_example_only;\n}Stack = {\n .construct = stack_construct,\n .operator_new = stack_operator_new,\n .push = stack_push,\n .pop = stack_pop\n};\n// All of these functions are assumed to be defined somewhere else\n struct stack * st = Stack.operator_new(); // Make a new stack\nif (!st) {\n // Do something about it\n} else {\n // You can use the stack\n stack_push(st, thing0); // This is a non-virtual call\n Stack.push(st, thing1); // This is like casting *st to a Stack (which it already is) and doing the push\n st->my_type.push(st, thing2); // This is a virtual call\n}\n" }, { "answer_id": 2733194, "author": "Ukko", "author_id": 321496, "author_profile": "https://Stackoverflow.com/users/321496", "pm_score": 2, "selected": false, "text": "#include<favorite_OO_Guru.h>" }, { "answer_id": 2733309, "author": "Brian Postow", "author_id": 53491, "author_profile": "https://Stackoverflow.com/users/53491", "pm_score": 0, "selected": false, "text": "foo->method(a,b,c) method(foo,a,b,c) FOO_method(foo,a,b,c)" }, { "answer_id": 7263545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n\nstruct Node {\n int somevar;\n};\n\nvoid print() {\n printf(\"Hello from an object-oriented C method!\");\n};\n\nstruct Tree {\n struct Node * NIL;\n void (*FPprint)(void);\n struct Node *root;\n struct Node NIL_t;\n} TreeA = {&TreeA.NIL_t,print};\n\nint main()\n{\n struct Tree TreeB;\n TreeB = TreeA;\n TreeB.FPprint();\n return 0;\n}\n" }, { "answer_id": 8385007, "author": "dameng", "author_id": 1081454, "author_profile": "https://Stackoverflow.com/users/1081454", "pm_score": 3, "selected": false, "text": "#include \"OOStd.h\"\n\nCLASS(Animal) {\n char *name;\n STATIC(Animal);\n vFn talk;\n};\nstatic int Animal_load(Animal *THIS,void *name) {\n THIS->name = name;\n return 0;\n}\nASM(Animal, Animal_load, NULL, NULL, NULL)\n\nCLASS_EX(Cat,Animal) {\n STATIC_EX(Cat, Animal);\n};\nstatic void Meow(Animal *THIS){\n printf(\"Meow!My name is %s!\\n\", THIS->name);\n}\n\nstatic int Cat_loadSt(StAnimal *THIS, void *PARAM){\n THIS->talk = (void *)Meow;\n return 0;\n}\nASM_EX(Cat,Animal, NULL, NULL, Cat_loadSt, NULL)\n\n\nCLASS_EX(Dog,Animal){\n STATIC_EX(Dog, Animal);\n};\n\nstatic void Woof(Animal *THIS){\n printf(\"Woof!My name is %s!\\n\", THIS->name);\n}\n\nstatic int Dog_loadSt(StAnimal *THIS, void *PARAM) {\n THIS->talk = (void *)Woof;\n return 0;\n}\nASM_EX(Dog, Animal, NULL, NULL, Dog_loadSt, NULL)\n\nint main(){\n Animal *animals[4000];\n StAnimal *f;\n int i = 0;\n for (i=0; i<4000; i++)\n {\n if(i%2==0)\n animals[i] = NEW(Dog,\"Jack\");\n else\n animals[i] = NEW(Cat,\"Lily\");\n };\n f = ST(animals[0]);\n for(i=0; i<4000; ++i) {\n f->talk(animals[i]);\n }\n for (i=0; i<4000; ++i) {\n DELETE0(animals[i]);\n }\n return 0;\n}\n" }, { "answer_id": 11350239, "author": "slkpg", "author_id": 1502467, "author_profile": "https://Stackoverflow.com/users/1502467", "pm_score": 2, "selected": false, "text": "typedef struct _peeker\n{\n log_t *log;\n symbols_t *sym;\n scanner_t scan; // inherited instance\n peek_t pk;\n int trace;\n\n void (*push) ( SELF *d, symbol_t *symbol );\n short (*peek) ( SELF *d, int level );\n short (*get) ( SELF *d );\n int (*get_line_number) ( SELF *d );\n\n} peeker_t, SlkToken;\n\n#define push(self,a) (*self).push(self, a)\n#define peek(self,a) (*self).peek(self, a)\n#define get(self) (*self).get(self)\n#define get_line_number(self) (*self).get_line_number(self)\n\nINSTANCE_METHOD\nint\n(get_line_number) ( peeker_t *d )\n{\n return d->scan.line_number;\n}\n\nPUBLIC\nvoid\nInitializePeeker ( peeker_t *peeker,\n int trace,\n symbols_t *symbols,\n log_t *log,\n list_t *list )\n{\n InitializeScanner ( &peeker->scan, trace, symbols, log, list );\n peeker->log = log;\n peeker->sym = symbols;\n peeker->pk.current = peeker->pk.buffer;\n peeker->pk.count = 0;\n peeker->trace = trace;\n\n peeker->get_line_number = get_line_number;\n peeker->push = push;\n peeker->get = get;\n peeker->peek = peek;\n}\n" }, { "answer_id": 11628545, "author": "rogergc", "author_id": 1548309, "author_profile": "https://Stackoverflow.com/users/1548309", "pm_score": 1, "selected": false, "text": "#include \"triangle.h\"\n#include \"rectangle.h\"\n#include \"polygon.h\"\n\n#include <stdio.h>\n\nint main()\n{\n Triangle tr1= CTriangle->new();\n Rectangle rc1= CRectangle->new();\n\n tr1->width= rc1->width= 3.2;\n tr1->height= rc1->height= 4.1;\n\n CPolygon->printArea((Polygon)tr1);\n\n printf(\"\\n\");\n\n CPolygon->printArea((Polygon)rc1);\n}\n\n/*output:\n6.56\n13.12\n*/\n" }, { "answer_id": 26766175, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "//private_class.h\nstruct private_class;\nextern struct private_class * new_private_class();\nextern int ret_a_value(struct private_class *, int a, int b);\nextern void delete_private_class(struct private_class *);\nvoid (*late_bind_function)(struct private_class *p);\n\n//private_class.c\nstruct inherited_class_1;\nstruct inherited_class_2;\n\nstruct private_class {\n int a;\n int b;\n struct inherited_class_1 *p1;\n struct inherited_class_2 *p2;\n};\n\nstruct inherited_class_1 * new_inherited_class_1();\nstruct inherited_class_2 * new_inherited_class_2();\n\nstruct private_class * new_private_class() {\n struct private_class *p;\n p = (struct private_class*) malloc(sizeof(struct private_class));\n p->a = 0;\n p->b = 0;\n p->p1 = new_inherited_class_1();\n p->p2 = new_inherited_class_2();\n return p;\n}\n\n int ret_a_value(struct private_class *p, int a, int b) {\n return p->a + p->b + a + b;\n }\n\n void delete_private_class(struct private_class *p) {\n //release any resources\n //call delete methods for inherited classes\n free(p);\n }\n //main.c\n struct private_class *p;\n p = new_private_class();\n late_bind_function = &implementation_function;\n delete_private_class(p);\n c_compiler main.c inherited_class_1.obj inherited_class_2.obj private_class.obj" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356/" ]
351,760
<p>I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing. Syntax like this for defining a data element seems quite convenient.</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>However, it does not support param names with spaces.</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>Python parser friendly versions can look as follows, but not very user friendly.</p> <pre><code>Allocation(("Param 1",Val1), ("Param 2",Val1) ) Allocation(**{"Param 1":Val1, "Param 2":Val1} ) </code></pre> <p>Is there a way to make this more readable in python?</p>
[ { "answer_id": 351776, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 1, "selected": false, "text": "def Allocation(**kwargs):\n print kwargs\n\nmyargs = {\"Param 1\":Val1, \"Param 2\":Val1}\nAllocation(**myargs)\n" }, { "answer_id": 351795, "author": "dreftymac", "author_id": 42223, "author_profile": "https://Stackoverflow.com/users/42223", "pm_score": 1, "selected": false, "text": "Allocation(\"Param 1=Check Up; Param 2=Mean Value Theorem;\")\n /\\s*;\\s*/\n /\\s*=\\s*/\n" }, { "answer_id": 351802, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "Allocation(Param1 = Val1, Param2 = Val2 )\n Allocation(Param 1 = Val1, Param 2 = Val2 )\n Allocation(\n { 'name1' : value1,\n 'name1' : value2, }\n)\n" }, { "answer_id": 353389, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": true, "text": "AllocationSet(\n Alloc( name=\"some name\", value=1.23 ),\n Alloc( name=\"another name\", value=2.34 ),\n Alloc( name=\"yet another name\", value=4.56 ),\n)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52490/" ]
351,784
<p>My requirement is to replace a set of words in a given text file with a second set of words, which might be given from the command line or another file. Wanting to use Perl to do this, as the rest of my code is also in Perl.</p> <p>So, if I have the following:</p> <pre><code>server name="${server1}" host="abc.com" server name="${server2}" host="webcs.com" server name="${server5}" host="httpvcs1.com" server name="${server6}" host="xyz.com" server name="${server7}" host="msg.com" </code></pre> <p>I wish to replace the strings 'server1', 'server2', 'server5', etc, with a different set of words. These might be placed in another file or given from the command line (whichever is more feasible).</p> <p>Also, if, instead of just 'server1', 'server2', etc, I want to replace the 'server' word with say 'file', how would i go about making a regex for this replacement?</p> <pre><code>perl -pie 's/server\d{1-3}/myword/g' loginOut.txt &gt; loginOut1.txt </code></pre> <p>The above will do a replacement for all words with 'myword'. But I want only the substring to be replaced. </p>
[ { "answer_id": 351831, "author": "George Stocker", "author_id": 16587, "author_profile": "https://Stackoverflow.com/users/16587", "pm_score": 0, "selected": false, "text": "perl -pie 's/\\{server/myword/g' loginOut.txt > loginOut1.txt\n" }, { "answer_id": 351853, "author": "user44511", "author_id": 44511, "author_profile": "https://Stackoverflow.com/users/44511", "pm_score": 2, "selected": false, "text": "s/server/myword/g; server1 abcd\nserver2 bcde\nserver3 cdef\netc.\n my %dict;\nwhile(<DICTFILE>){\n /(\\S+)\\s+(\\S+)/;\n $dict{$1}={$2};\n}\n while(my $line = <>){\n foreach my $s (keys %dict){\n $line =~ s/$s/$dict{$s}/g;\n }\n print $line;\n}\n" }, { "answer_id": 352179, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 1, "selected": false, "text": "perl -pe \"s/\\{server/\\{file/g\" in.txt > out.txt\n server name=\"${file1}\" host=\"abc.com\"\nserver name=\"${file2}\" host=\"webcs.com\"\nserver name=\"${file5}\" host=\"httpvcs1.com\"\nserver name=\"${file6}\" host=\"xyz.com\"\nserver name=\"${file7}\" host=\"msg.com\"\n" }, { "answer_id": 352308, "author": "Sudden Def", "author_id": 28121, "author_profile": "https://Stackoverflow.com/users/28121", "pm_score": 0, "selected": false, "text": "$what = 'server'; # The word to be replaced\n$with = 'file'; # Replacement\ns/(?<=\\${)$what(?=[^}]*})/$with/g;\n" }, { "answer_id": 353923, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": true, "text": "[% ... %] INTERPOLATE" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35416/" ]
351,797
<p>I know this maybe a very basic question but I'm having a bit of a mind blank at the moment. Should I be unit testing this class.</p> <pre><code>public class MapinfoWindowHandle : IWin32Window { IntPtr handle; public MapinfoWindowHandle(IntPtr mapinfoHandle) { this.handle = mapinfoHandle; } #region IWin32Window Members IntPtr IWin32Window.Handle { get { return this.handle; } } #endregion } </code></pre> <p>If I should be what should I be testing for? <bR> I use it like this:</p> <pre><code>IntPtr handle = new IntPtr(100); myform.show(new MapinfoWindowHandle(handle)); </code></pre>
[ { "answer_id": 351805, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": " [TestMethod]\n public void ConstructorTest()\n {\n IntPtr handle = new IntPtr(100);\n MapinfoWindowHandle winHandle = new MapinfoWindowHandle(handle);\n Assert.AreEqual( handle, ((IWin32Window)winHandle).Handle );\n }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
351,800
<p>Is it possible to create an inline delegate in vb.net like you can in c#?</p> <p>For example, I would like to be able to do something inline like this:</p> <pre><code>myObjects.RemoveAll(delegate (MyObject m) { return m.X &gt;= 10; }); </code></pre> <p>only in VB and without having to do something like this</p> <pre><code>myObjects.RemoveAll(AddressOf GreaterOrEqaulToTen) Private Function GreaterOrEqaulToTen(ByVal m as MyObject) If m.x &gt;= 10 Then Return true Else Return False End If End Function </code></pre> <p>-- edit -- I should have mentioned that I am still working in .net 2.0 so I won't be able to use lambdas.</p>
[ { "answer_id": 351820, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 3, "selected": false, "text": "myObjects.RemoveAll(Function(m) m.X >= 10)\n" }, { "answer_id": 351825, "author": "BlackMael", "author_id": 19377, "author_profile": "https://Stackoverflow.com/users/19377", "pm_score": 6, "selected": true, "text": "myObjects.RemoveAll(Function(m As MyObject) m.X >= 10)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
351,801
<p>I'm trying to get Unicode working properly in rails using MySQL. Now, Rails displays the text correctly, but it shows up as ??? in MySQL. Additionally, I am not able to filter the text.</p> <p>My MySQL database has been configured with the utf8 character set. My client character is also UTF8. Likewise, rails is set to use UTF8. </p> <p>If I enter the Unicode string directly from the MySQL client, it is stored properly in the table, but Rails does not correctly display it.</p> <p>How do I get the data in, properly formatted in the database?</p>
[ { "answer_id": 416539, "author": "sikachu", "author_id": 52035, "author_profile": "https://Stackoverflow.com/users/52035", "pm_score": 2, "selected": false, "text": "encoding: utf8" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,806
<p>I am curious to know where the "Don't Fragment" [DF] Bit of the IP Flags is used. As fragmentation is invisible to higher layers and they don't care too.</p> <p>I am also looking for an example. </p> <p>Thanks a lot in advance.</p>
[ { "answer_id": 352027, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": false, "text": "write()" }, { "answer_id": 355530, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 3, "selected": false, "text": "result = setsockopt(mysocket, IPPROTO_IP, \n IP_MTU_DISCOVER, IP_PMTUDISC_DO, sizeof(int));\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38038/" ]
351,823
<p>The following is a simplified version of what I'm trying to do, because I'm sure you don't want to wade through an entire set of structs and function prototypes for a particle system.</p> <pre><code>float const materials[24][4][4] = {{{...}}}; typedef struct EmitterStruct { float *material[4][4]; } Emitter; typedef struct ParticleStruct { float material[4][4]; } Particle; Emitter *myEmitter; Emitter * createEmitter(float *material[4][4]) { Emitter * newEmitter; newEmitter = (Emitter *)malloc(sizeof(Emitter)); newEmitter-&gt;material = materal; /* Returns "incompatable types in assignment" */ return newEmitter; /* I also tried newEmitter-&gt;material = &amp;material */ } int main(char *argv, int argc) { myEmitter = createEmitter(materials[0]); } </code></pre> <p>In essence, as the comment shows, I get a compile error. I've tried this several different ways, even using "float material[4][4]" in the Emitter struct and the signature of createEmitter. However, then later on when I try to copy values into a particle for modificaitons using:</p> <pre><code>for (i=0; i++; i&lt;4) { for (j=0; j++; j&lt;4) { particle-&gt;material[i][j] = emitter-&gt;material[i][j]; } } </code></pre> <p>I get another type mismatch when copying, even though <em>everything</em> is declared as type float[4][4]. In essence, I want to get a 4x4 array out of an array of 4x4 arrays, keep note of it in the emitter struct, then copy it into the particle struct. But I only want to actually copy the values one time.</p>
[ { "answer_id": 351843, "author": "AlfaZulu", "author_id": 44060, "author_profile": "https://Stackoverflow.com/users/44060", "pm_score": 1, "selected": false, "text": "memcpy particle->material[i][j] = emitter->material[i][j];\n material Emitter float* material Particle float particle->material[i][j] = *(emitter->material[i][j]);\n material Emitter" }, { "answer_id": 351849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "float const materials[24][4][4] = {{{...}}};\ntypedef struct EmitterStruct { float *material; } Emitter; /*Use just a plain pointer*/\ntypedef struct ParticleStruct { float material[4][4]; } Particle;\nEmitter *myEmitter;\n\nEmitter * createEmitter(float *material) /*Use a plain pointer here*/\n{\n Emitter * newEmitter;\n newEmitter = (Emitter *)malloc(sizeof(Emitter));\n newEmitter->material = material; \n return newEmitter; \n}\n\nint main(char *argv, int argc)\n{\n myEmitter = createEmitter(materials[0]);/*This decays into a pointer*/\n}\n for (i=0; i++; i<4)\n{\n for (j=0; j++; j<4)\n {\n particle->material[i][j] = *(emitter->material[i * 4 + j];\n }\n}\n" }, { "answer_id": 351862, "author": "Paul Morel", "author_id": 1311247, "author_profile": "https://Stackoverflow.com/users/1311247", "pm_score": 0, "selected": false, "text": "// get a color histogram of an image\nint ***colorHistogram(PIXEL *inputImage, HEADER *imageHeader)\n{\n int x, y, z;\n\n // a color histogram\n int ***histo;\n\n // allocate space for the histogram\n histo = (int ***)malloc(256 * sizeof(int**));\n for(x=0; x<256; x++)\n {\n histo[x]=(int **)malloc(256 * sizeof(int*));\n for(y=0; y<256; y++)\n {\n histo[x][y]=(int *)malloc(256 * sizeof(int));\n\n // initialize the histogram\n for(z=0; z<256; z++)\n histo[x][y][z] = 0;\n }\n }\n\n // fill the histogram\n for (x = 0; x < imageHeader->width * imageHeader->height; x++)\n {\n histo[((int) inputImage[x].r)][((int) inputImage[x].g)][((int) inputImage[x].b)]++;\n }\n\nreturn histo;\n" }, { "answer_id": 351913, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "float const materials[24][4][4] = {{{...}}};\ntypedef struct EmitterStruct { float *material; } Emitter; /*Use just a plain pointer*/\ntypedef struct ParticleStruct { float material[4][4]; } Particle;\nEmitter *myEmitter;\n\nEmitter * createEmitter(float *material) /*Use a plain pointer here*/\n{\n Emitter * newEmitter;\n newEmitter = (Emitter *)malloc(sizeof(Emitter));\n newEmitter->material = material; \n return newEmitter; \n}\n\nint main(char *argv, int argc)\n{\n myEmitter = createEmitter(materials[0]);/*This decays into a pointer*/\n}\n float const[4][4] float const(*)[4] float const materials[24][4][4] = {{{...}}};\n/*Use just a plain pointer to an array */\ntypedef struct EmitterStruct { float const (*material)[4]; } Emitter; \ntypedef struct ParticleStruct { float material[4][4]; } Particle;\nEmitter *myEmitter;\n\n/*Use a plain pointer here. Bet keep it float const, not only float!*/\nEmitter * createEmitter(float const (*material)[4])\n{\n Emitter * newEmitter;\n newEmitter = (Emitter *)malloc(sizeof(Emitter));\n newEmitter->material = material; \n return newEmitter; \n}\n\nint main(int argc, char ** argv) /* you swapped args here */\n{\n myEmitter = createEmitter(materials[0]); /* This decays into a pointer */\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,840
<p>I have the following Transact-Sql that I am trying to convert to LINQ ... and struggling. </p> <pre><code>SELECT * FROM Project WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155') </code></pre> <p>Any help would be greatly appreciated ... I would like to do it with Lambda expressions, if possible. </p> <p>Thanks in advance!</p>
[ { "answer_id": 351859, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": false, "text": "var projects = \nfrom p in db.Projects\nwhere db.ProjectMembers.Where(m => m.MemberId == \"a45bd16d-9be0-421b-b5bf-143d334c8155\").Select(pp => pp.ProjectID).Contains(p.ProjectID)\nselect p;\n" }, { "answer_id": 351886, "author": "gfrizzle", "author_id": 23935, "author_profile": "https://Stackoverflow.com/users/23935", "pm_score": 2, "selected": false, "text": "From p in db.Projects _\nJoin m in db.ProjectMember On p.ProjectId Equals m.ProjectId _\nWhere m.MemberId = \"a45bd16d-9be0-421b-b5bf-143d334c8155\" _\nSelect p\n" }, { "answer_id": 351896, "author": "Strelok", "author_id": 2788, "author_profile": "https://Stackoverflow.com/users/2788", "pm_score": 4, "selected": true, "text": "var projectsMemberWorkedOn = from p in Projects\n join projectMember in ProjectMembers on\n p.ProjectId equals projectMember.ProjectId\n where projectMember.MemberId == \"a45bd16d-9be0-421b-b5bf-143d334c8155\"\n select p;\n var projectsMemberWorkedOn =\n Projects.Join( ProjectMembers, p => p.ProjectId, projectMember => projectMember.ProjectId,\n ( p, projectMember ) => new { p, projectMember } )\n .Where( @t => @t.projectMember.MemberId == \"a45bd16d-9be0-421b-b5bf-143d334c8155\" )\n .Select(@t => @t.p );\n" }, { "answer_id": 351902, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "var q = db.Projects\n .Where(p => db.ProjectMembers\n .Where(pm => pm.MemberId == memberId)\n .Any (pm => p.ProjectId == pm.ProjectId)); \n db.ProjectMembers.Where(...) var projectMembers = db.ProjectMembers.Where(pm => pm.MemberId == memberId);\nvar q = db.Projects\n .Where(p => projectMembers\n .Any(pm => p.ProjectId == pm.ProjectId));\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
351,845
<p>I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.</p> <p>What is the best way to find out which type the object passed to my function is?</p>
[ { "answer_id": 351852, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 3, "selected": false, "text": "dynamic_cast<B*>(pointer)" }, { "answer_id": 351865, "author": "yesraaj", "author_id": 22076, "author_profile": "https://Stackoverflow.com/users/22076", "pm_score": 9, "selected": true, "text": "TYPE& dynamic_cast<TYPE&> (object);\nTYPE* dynamic_cast<TYPE*> (object);\n dynamic_cast bad_cast" }, { "answer_id": 352009, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 1, "selected": false, "text": "class A {};\nclass B : public A {};\n\nclass Foo {\npublic:\n void Bar(A& a) {\n // do something\n }\n void Bar(B& b) {\n Bar(static_cast<A&>(b));\n // do B specific stuff\n }\n};\n" }, { "answer_id": 4325139, "author": "Robocide", "author_id": 179744, "author_profile": "https://Stackoverflow.com/users/179744", "pm_score": 8, "selected": false, "text": "#include <typeinfo>\n\n...\nstring s = typeid(YourClass).name()\n" }, { "answer_id": 4817331, "author": "c64zottel", "author_id": 592307, "author_profile": "https://Stackoverflow.com/users/592307", "pm_score": 2, "selected": false, "text": "struct BaseClas { int base; virtual ~BaseClas(){} };\nclass Derived1 : public BaseClas { int derived1; };\n BaseClas" }, { "answer_id": 36341405, "author": "firebush", "author_id": 629530, "author_profile": "https://Stackoverflow.com/users/629530", "pm_score": 4, "selected": false, "text": "typeid #include <typeinfo>\n#include <iostream>\n\nusing namespace std;\n\nclass A {\npublic:\n virtual ~A() = default; // We're not polymorphic unless we\n // have a virtual function.\n};\nclass B : public A { } ;\nclass C : public A { } ;\n\nint\nmain(int argc, char* argv[])\n{\n B b;\n A& a = b;\n\n cout << \"a is B: \" << boolalpha << (typeid(a) == typeid(B)) << endl;\n cout << \"a is C: \" << boolalpha << (typeid(a) == typeid(C)) << endl;\n cout << \"b is B: \" << boolalpha << (typeid(b) == typeid(B)) << endl;\n cout << \"b is A: \" << boolalpha << (typeid(b) == typeid(A)) << endl;\n cout << \"b is C: \" << boolalpha << (typeid(b) == typeid(C)) << endl;\n}\n a is B: true\na is C: false\nb is B: true\nb is A: false\nb is C: false\n" }, { "answer_id": 47629801, "author": "Kehe CAI", "author_id": 3120528, "author_profile": "https://Stackoverflow.com/users/3120528", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <boost/type_index.hpp>\n\nint a;\nint& ff() \n{\n return a;\n}\n\nint main() {\n ff() = 10;\n using boost::typeindex::type_id_with_cvr;\n std::cout << type_id_with_cvr<int&>().pretty_name() << std::endl;\n std::cout << type_id_with_cvr<decltype(ff())>().pretty_name() << std::endl;\n std::cout << typeid(ff()).name() << std::endl;\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43463/" ]
351,848
<p>Ok another WPF question, well I guess this is just general .NET. I have an xml document retreived from a URL.</p> <p>I want to get multiple values out of the document (weather data, location, some other strings).</p> <p>When I use the XmlTextReader I can call my method to pull the values out. The first time I pass the method to search for the xml node and get the value (the XMLTextReader object) I get the right data back, but then the XMLTextReader is dead. Not sure why it gets nulled out. So I'm having to do this UGLY code below in the FindTags... method. I want to just keep passing the xtr (XMLTextreader) back to my find method. Is this the nature of the reader? I don't want to have to hit the URL each time either... that seems wrong too.</p> <p>Help.. this just all feels wrong.</p> <p>Thanks.</p> <pre><code> GetWeatherFeed("97229", "//weather//loc//dnam", "//weather//cc//tmp", "/weather/cc/icon"); </code></pre> <p>Get WeatherFeed method (snipped)</p> <pre><code> System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(Url that retuns xm); System.Collections.Hashtable ht = new System.Collections.Hashtable(); ht = FindTagsUsingXPthNaviatorAndXPathDocumentNew(xtr, location, temperature, iconid); lblLocation.Content = ht["Location"].ToString(); lblWeatherCondition.Content = ht["Weather"].ToString(); public System.Collections.Hashtable FindTagsUsingXPthNaviatorAndXPathDocumentNew(System.Xml.XmlTextReader xtr, string nodeToLocate1, string nodeToLocate2, string nodeToLocate3) { System.Xml.XPath.XPathDocument xpDoc = new System.Xml.XPath.XPathDocument(xtr); System.Xml.XPath.XPathNavigator xpNav = xpDoc.CreateNavigator(); System.Xml.XPath.XPathExpression xpExpression = xpNav.Compile(nodeToLocate1); System.Xml.XPath.XPathNodeIterator xpIter = xpNav.Select(xpExpression); System.Collections.Hashtable ht = new System.Collections.Hashtable(); while (xpIter.MoveNext()) { ht.Add("Location", xpIter.Current.Value); } xpExpression = xpNav.Compile(nodeToLocate2); xpIter = xpNav.Select(xpExpression); while (xpIter.MoveNext()) { ht.Add("Weather", xpIter.Current.Value); } xpExpression = xpNav.Compile(nodeToLocate3); xpIter = xpNav.Select(xpExpression); while (xpIter.MoveNext()) { ht.Add("Icon", xpIter.Current.Value); } return ht; } </code></pre>
[ { "answer_id": 351949, "author": "John Batdorf", "author_id": 22451, "author_profile": "https://Stackoverflow.com/users/22451", "pm_score": 1, "selected": false, "text": " System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(my xml url);\n System.Xml.XPath.XPathDocument xdoc = new System.Xml.XPath.XPathDocument(xtr);\n\n lblLocation.Content = getXmlNodeValue(xdoc, location);\n lblWeatherCondition.Content = getXmlNodeValue(xdoc, temperature);\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22451/" ]
351,903
<p>I have a GridView that has columns such as:</p> <pre><code>| A | B C | D E / F | </code></pre> <p>I want these to be wrapped in a particular way - that is, I do not want to leave it up to the browser to work out whether to wrap or not depending on the column width. So in the above example I may want the following:</p> <pre><code>| A | B | D | | | C | E / F | </code></pre> <p>I have tried using <code>\n</code> and also using <code>&lt;br/&gt;</code> however both of these did not work.</p> <p>Any ideas?</p>
[ { "answer_id": 352986, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 3, "selected": false, "text": "<asp:templatefield>\n <headertemplate>\n D<br />\n E / F\n </headertemplate>\n <itemtemplate>\n <%#Eval(\"MyField\")%>\n </itemtemplate>\n</asp:templatefield>\n" }, { "answer_id": 354063, "author": "Kelly Adams", "author_id": 12734, "author_profile": "https://Stackoverflow.com/users/12734", "pm_score": 4, "selected": true, "text": "<br /> <asp:GridView ID=\"GridView1\" runat=\"server\" DataSourceID=\"Data\">\n<Columns>\n <asp:BoundField HeaderText=\"First Line<br />Second Line\" DataField=\"ContactID\"\n HtmlEncode=\"False\" />\n <asp:BoundField HeaderText=\"Second\" DataField=\"FirstName\" />\n <asp:BoundField HeaderText=\"Third<br />Extra\" DataField=\"Title\" />\n</Columns>\n</asp:GridView>\n < &lt;" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
351,911
<p>Example:</p> <pre><code>public class Name { public string FirstName { get; private set; } public string LastName { get; private set; } private Name() { } public Name(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } </code></pre> <p>When trying to instantiate this c# class, intellisense shows both the private and the public constructor for new keyword even though one of the constructor is private! </p> <p>What is even more weird is that when I remove the second argument from the public constructor ( remove lastName as argument to public constructor), intellisense now shows just the public constructor with new keyword, correctly.</p> <p>Is this a bug or am I missing something here? I am using VS2008 SP1.</p> <p>edit: code clarity</p>
[ { "answer_id": 351924, "author": "Strelok", "author_id": 2788, "author_profile": "https://Stackoverflow.com/users/2788", "pm_score": 0, "selected": false, "text": "public abstract class BaseDomainObject{\n public BaseDomainObject() { }\n\n private int _id;\n\n public virtual int Id { get { return _id; } set { _id = value; } }\n\n}\n\npublic SomeDomainObject : BaseDomainObject{\n ...\n}\n" }, { "answer_id": 351928, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "class Outer {\n private Outer() {\n }\n public Outer Create() { return new Outer(); }\n class Inner() { \n void Function1() { new Outer(); }\n class DoubleInner() {\n void Function2() { new Outer(); }\n }\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23217/" ]
351,915
<p>I have written a function that gets a given number of random records from a list. Currently I can do something like:</p> <pre><code>IEnumerable&lt;City&gt; cities = db.Cites.GetRandom(5); </code></pre> <p>(where db is my DataContext connecting to a SQL Server DB)</p> <p>Currently, I have a function like this in every entity I need random records from:</p> <pre><code>public partial class City { public static IEnumerable&lt;City&gt; GetRandom(int count) { Random random = new Random(); IEnumerable&lt;City&gt; cities = DB.Context.Cities.OrderBy( c =&gt; random.Next() ).Take(count); return cities; } } </code></pre> <p>It works fine, but I'd like it to be generic, so it can work for any table, or even any list of items. I have tried an extension method like:</p> <pre><code> public static IEnumerable&lt;T&gt; GetRandom&lt;T&gt;( this Table&lt;T&gt; table, int count) { Random random = new Random(); IEnumerable&lt;T&gt; records = table.OrderBy(r =&gt; random.Next()).Take(count); return records; } </code></pre> <p>but I get:</p> <pre> Error 1 The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table' </pre> <p>which highlights <code>GetRandom&lt;T&gt;</code>.</p> <p>I don't understand what the problem is here. Can someone clear up the proper syntax?</p>
[ { "answer_id": 351922, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "public static IEnumerable<T> GetRandom<T>( this Table<T> table, int count) where T : class {\n ...\n}\n" }, { "answer_id": 351936, "author": "Strelok", "author_id": 2788, "author_profile": "https://Stackoverflow.com/users/2788", "pm_score": 3, "selected": true, "text": "public static IEnumerable<T> GetRandom<T>( this Table<T> table, int count) where T : class {\n ...\n}\n" }, { "answer_id": 352063, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 3, "selected": false, "text": "public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)\n{\n Random rnd = new Random();\n return source.OrderBy(t => rnd.Next());\n}\n\n...\n\nIEnumerable<City> cities = db.Cites.Randomize().Take(5);\n" }, { "answer_id": 352135, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": " [Function(Name=\"NEWID\", IsComposable=true)] \n public Guid Random() \n { \n return Guid.NewGuid(); \n } \n ctx.Log = Console.Out; \n var query = from x in ctx.Suppliers \n orderby ctx.Random() \n select x; \n var results = query.ToArray(); \n SELECT [t0].[SupplierID], [t0].[CompanyName], [t0].[ContactName], \n[t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], \n[t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax], [t0].[HomePage] \nFROM [dbo].[Suppliers] AS [t0] \nORDER BY NEWID() \n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30529/" ]
351,919
<p>I've had a lot of users complain that the little "i" info button is difficult to touch on the iPhone. Ok, simple enough -- I just stuck a big-fat invisible button behind it that you can't miss even with the sloppiest of finger touches and, when you touch it, it does the infoButtonAction.</p> <p>Thing is, I'd like to flash the info button, itself, for about .25 sec, just to give a visual "this is what's going on" type of feedback. I mean, I'm already assuming that you meant to hit the "i" button, so I'm just treating it as if you <em>DID</em> hit it.</p> <p>I tried this, but it doesn't work:</p> <pre><code> UIImage* normalImage = [_infoButton imageForState:UIControlStateNormal]; UIImage* highlighted = [_infoButton imageForState:UIControlStateHighlighted]; _infoButton.highlighted = YES; // flash the button [_infoButton setImage:highlighted forState:UIControlStateNormal]; [_infoButton setNeedsDisplay]; //* FIXME: No flash?! [(AppDelegate*)[[UIApplication sharedApplication] delegate] infoTap]; // do the info action _infoButton.highlighted = NO; [_infoButton setImage:normalImage forState:UIControlStateNormal]; [_infoButton setNeedsDisplay]; </code></pre> <p>Any ideas about how to get the behaviour I want?</p> <p>(I'm also open to alternate ideas about user feedback, but still curious how I'd do this. Imagine that, instead, I have a "game"/prank where you push the "ok" button and "cancel" flashes, and vice versa, or something equally silly.)</p>
[ { "answer_id": 351951, "author": "Matt Ball", "author_id": 43120, "author_profile": "https://Stackoverflow.com/users/43120", "pm_score": 0, "selected": false, "text": "infotap setImage: NSTimer" }, { "answer_id": 353245, "author": "Mike Abdullah", "author_id": 28768, "author_profile": "https://Stackoverflow.com/users/28768", "pm_score": 2, "selected": true, "text": "-setNeedsDisplay -performClick: -setSelected: -setHighlighted:" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34820/" ]
351,927
<p>I just ran into an issue with Python's imaplib and Gmail's authentication mechanism:</p> <pre><code>&gt;&gt;&gt; import imaplib &gt;&gt;&gt; imap = imaplib.IMAP4_SSL('imap.gmail.com', 993) &gt;&gt;&gt; imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!') Traceback (most recent call last): ... imaplib.error: AUTHENTICATE command error: BAD ['TODO (not supported yet) 31if3458825wff.5'] </code></pre> <p>If authentication is unsupported, how does one log in?</p>
[ { "answer_id": 351930, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 0, "selected": false, "text": ">>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')\n('OK', ['bobdole@gmail.com authenticated (Success)'])\n" }, { "answer_id": 351933, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "srv = imaplib.IMAP4_SSL(\"imap.gmail.com\")\nsrv.login(account, password)\n login()" }, { "answer_id": 351934, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 4, "selected": true, "text": ">>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')\n >>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')\n" }, { "answer_id": 49666113, "author": "Jatin Mahajan", "author_id": 4644917, "author_profile": "https://Stackoverflow.com/users/4644917", "pm_score": 0, "selected": false, "text": "import imaplib\nimap = imaplib.IMAP4_SSL('imap.gmail.com', 993)\nimap.login('bobdole@gmail.com', 'Bob Dole likes your style!') imap = imaplib.IMAP4_SSL('imap.gmail.com')" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
351,932
<p>How do you associate a <code>-mouseUp:</code> event with the <code>-add:</code> method of a NSArrayController? The <code>-mouseUp:</code> event lives in a different object but is <code>#import</code>'ed and instantiated in the object that holds the array being controlled.</p> <p>Usually, with an NSButton you command-drag from the button to the NSArrayController's <code>-add:</code> method but obviously this is not possible with a mouse event. <br /><br /> -- ADDED CONTENT --<br /> MATT: Thanks for the answer and on first read it made sense. Being a beginner to Obj-C/Cocoa with a procedural and NON-GUI language (PLM51 and C51 for embedded controllers) background, I'm having a hard time to grasp the practical implementation of IBOutlets and connecting. I have no problems with buttons and the like (i.e. visible things in IB) but here is what I understand: I need to declare <code>-IBOutlet NSArrayControler * arryCtrl;</code> in my myDocuments.h file. Now keep in mind, the object where I override the <code>-mouseUp</code> method is called Canvas and in myDocuments.h I have a <code>Canvas * canvas</code> declaration hence, I have a canvas object instantiated by myDocument at runtime. In IB, I drag from File's Owner (myDocument right) to ArrayController and a link is established BUT not to <code>-add:</code> as that option is not available. In the nib (myDocument) there is no object for Canvas But, in mouseUp (the canvas method), if I send a message to the IBOutput, i.e. <code>[arrayCtrl add:self]</code> arrayCtrl is not known. <br /><br /> Anyhow, I'm sure you guys are having a giggle as the answer is probably so obvious. However, I'm really trying to understand it all and realize that the problem is my novice coding. Thanks for pointing this newbie in the right direction</p>
[ { "answer_id": 351930, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 0, "selected": false, "text": ">>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')\n('OK', ['bobdole@gmail.com authenticated (Success)'])\n" }, { "answer_id": 351933, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "srv = imaplib.IMAP4_SSL(\"imap.gmail.com\")\nsrv.login(account, password)\n login()" }, { "answer_id": 351934, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 4, "selected": true, "text": ">>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')\n >>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')\n" }, { "answer_id": 49666113, "author": "Jatin Mahajan", "author_id": 4644917, "author_profile": "https://Stackoverflow.com/users/4644917", "pm_score": 0, "selected": false, "text": "import imaplib\nimap = imaplib.IMAP4_SSL('imap.gmail.com', 993)\nimap.login('bobdole@gmail.com', 'Bob Dole likes your style!') imap = imaplib.IMAP4_SSL('imap.gmail.com')" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41880/" ]
351,937
<p>I'm trying to write a html helper extension that outputs an image tag. I need to access (within C# code) something like Razor's @Url.Content() helper to get the proper URL for the current context. How does one do this?</p>
[ { "answer_id": 351955, "author": "Dave K", "author_id": 19864, "author_profile": "https://Stackoverflow.com/users/19864", "pm_score": -1, "selected": false, "text": "string fullUrl = HttpContext.Current.Request.Url.AbsoluteUri;\n" }, { "answer_id": 353057, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "public static string MyHelper(this HtmlHelper h)\n{\n string url = h.ViewContext.HttpContext.Request.Url.AbsoluteUri;\n}\n" }, { "answer_id": 363994, "author": "Curtis Buys", "author_id": 33533, "author_profile": "https://Stackoverflow.com/users/33533", "pm_score": 5, "selected": false, "text": "UrlHelper ViewContext public static string CustomImage(this HtmlHelper html)\n{\n var Url = new UrlHelper(html.ViewContext.RequestContext);\n}\n Url.Content() UrlHelper" }, { "answer_id": 597112, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 7, "selected": false, "text": "VirtualPathUtility.ToAbsolute(\"~/url/\");\n" }, { "answer_id": 3296449, "author": "takeshi", "author_id": 372879, "author_profile": "https://Stackoverflow.com/users/372879", "pm_score": 0, "selected": false, "text": "Url.Content var img_btn_edit = VirtualPathUtility.ToAbsolute(\"~/Content/images/pencil.png\");\n" }, { "answer_id": 7396627, "author": "Andrew Harry", "author_id": 30576, "author_profile": "https://Stackoverflow.com/users/30576", "pm_score": 2, "selected": false, "text": "this.Url.Content(\"~/Somerelativepath?somethingelse=true\");" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
351,954
<p>Is there a way using the iPhone SDK to get WiFi information? Things like Signal Strength, WiFi Channel and SSID are the main things I'm looking for.</p> <p>Only interested in Wifi info, not cellular.</p>
[ { "answer_id": 412548, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 5, "selected": true, "text": "Apple80211GetInfoCopy" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
351,971
<p>Hi I'm trying to use mono-service2 to run a stock Windows Service Project from visual studio. I'm running this on debian with mono 2.0 and compiling with.</p> <pre><code>gmcs *.cs -pkg:dotnet </code></pre> <p>I try and start with this (I've tried with -d set to the dir with the app and -n,-m set)</p> <pre><code>mono-service2 -l:service.lock --debug Program.exe </code></pre> <p>The only code change is to add writelines for testing</p> <p><strong>Service1.cs</strong></p> <pre><code>using System; using System.ServiceProcess; namespace spikes { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { Console.WriteLine("starting..."); } protected override void OnStop() { Console.WriteLine("stopping...."); } } } </code></pre> <p>The resulting is this error</p> <pre><code>Unhandled Exception: System.TypeInitializationException: An exception was thrown by the type initializer for Mono.Unix.Native.Syscall ---&gt; System.DllNotFoundException: libMonoPosixHelper.so at (wrapper managed-to-native) Mono.Unix.Native.Syscall:_L_ctermid () at Mono.Unix.Native.Syscall..cctor () [0x00000] --- End of inner exception stack trace --- at MonoServiceRunner.Main (System.String[] args) [0x00000] </code></pre> <p>Thanks for your help</p> <p><strong>Answer</strong></p> <p>I was missing the LD____LIBRARY____PATH env variable, so I added it in a csh for a test</p> <pre><code>#!/bin/csh setenv LD_LIBRARY_PATH .:/usr/local/lib mono-service2 -l:service.lock --debug Program.exe </code></pre>
[ { "answer_id": 352051, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "libMonoPosixHelper.so" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253/" ]
351,987
<p>I'm trying to grab an image from a web site using simpleXML and am getting a PHP error saying that I'm trying to call to a member function <code>xpath()</code> on a non-object.</p> <p>Below are the lines I'm trying to use to get the image's source tag: </p> <pre><code>$xpath = '/html/body/div/div/div[5]/div/div/div[2]/div/div[2]/img'; $html = new DOMDocument(); @$html-&gt;loadHTMLFile($target_URL); $xml = simplexml_import_dom($html); $source_image = $xml-&gt;xpath($xpath); $source_image = $source_image[0]['src']; </code></pre> <p>What am I doing wrong? It's pretty clear the second to last line has a problem, but I'm not sure what it is.</p>
[ { "answer_id": 352023, "author": "dancavallaro", "author_id": 42891, "author_profile": "https://Stackoverflow.com/users/42891", "pm_score": 3, "selected": false, "text": "$xpath = '/html/body/div/div/div[5]/div/div/div[2]/div/div[2]/img'; \n$html = new DOMDocument();\n@$html->loadHTMLFile($target_URL);\n$xml = simplexml_import_dom($html); \nif (!$xml) {\n echo 'Error while parsing the document';\n exit;\n}\n$source_image = $xml->xpath($xpath);\n$source_image = $source_image[0]['src'];\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/351987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,010
<p>I have 3 web projects in a Visual studio solution.I want to create a single web setup project which should install all 3 web projects in their virtual directories.So how to create a single web setup project which supports multiple web application installation?</p>
[ { "answer_id": 9357940, "author": "awe", "author_id": 109392, "author_profile": "https://Stackoverflow.com/users/109392", "pm_score": 0, "selected": false, "text": "Property C:\\intepub\\wwwroot\\ VirtualDirectory Property Property Installation Address Property Installation Address" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11039/" ]
352,032
<p>I'm just trying to do simple scripting with F#, and Math.PI seems to have 'disappeared'. I've referenced FSharp.PowerPack.dll, but still can't find it.</p>
[ { "answer_id": 352040, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "let PI = 3.141592653589\n" }, { "answer_id": 352041, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "open System\nMath.PI\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11410/" ]
352,039
<p>Please list <strong>one</strong> site which allows Flash/Silverlight access via crossdomain.xml file. Vote for your favorite sites.</p> <p>The goal is to build an up to date list of sites which can be directly accessed via Flash/Silverlight without a server-side proxy. </p>
[ { "answer_id": 7354974, "author": "puppybits", "author_id": 304499, "author_profile": "https://Stackoverflow.com/users/304499", "pm_score": 1, "selected": false, "text": "JSONP.get(\"http://api.twitter.com/statuses/user_timeline.json\", \n \"{screen_name:'puppybits', count:'1'}\", \n function(data):void{ \n trace('flash received cross-domain json:'+data)\n });\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ]
352,055
<p>What is the best approach in stripping leading and trailing spaces in C?</p>
[ { "answer_id": 352071, "author": "mcjabberz", "author_id": 30323, "author_profile": "https://Stackoverflow.com/users/30323", "pm_score": 1, "selected": false, "text": "int i = strlen(s) - 1;\nwhile (isspace(s[i]))\n s[i--] = '\\0';\nwhile (isspace(*s))\n s++;\n" }, { "answer_id": 352081, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "memmove()" }, { "answer_id": 352109, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 5, "selected": false, "text": "char *strstrip(char *s)\n{\n size_t size;\n char *end;\n\n size = strlen(s);\n\n if (!size)\n return s;\n\n end = s + size - 1;\n while (end >= s && isspace(*end))\n end--;\n *(end + 1) = '\\0';\n\n while (*s && isspace(*s))\n s++;\n\n return s;\n}\n" }, { "answer_id": 352119, "author": "AlfaZulu", "author_id": 44060, "author_profile": "https://Stackoverflow.com/users/44060", "pm_score": 4, "selected": true, "text": " void stripLeadingAndTrailingSpaces(char* string){\n\n assert(string);\n\n /* First remove leading spaces */\n\n const char* firstNonSpace = string;\n\n while(*firstNonSpace != '\\0' && isspace(*firstNonSpace))\n {\n ++firstNonSpace;\n }\n\n size_t len = strlen(firstNonSpace)+1; \n\n memmove(string, firstNonSpace, len);\n\n /* Now remove trailing spaces */\n\n char* endOfString = string + len;\n\n while(string < endOfString && isspace(*endOfString))\n {\n --endOfString ;\n }\n\n *endOfString = '\\0';\n\n}\n" }, { "answer_id": 352164, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "char * trim(char *c) {\n char * e = c + strlen(c) - 1;\n while(*c && isspace(*c)) c++;\n while(e > c && isspace(*e)) *e-- = '\\0';\n return c;\n}\n" }, { "answer_id": 352202, "author": "lakshmanaraj", "author_id": 44541, "author_profile": "https://Stackoverflow.com/users/44541", "pm_score": 2, "selected": false, "text": "char *strstrip(char *s)\n{\n char *end;\n\n while ( (*s) && isspace( *s))\n s++;\n\n if(!( *s) )\n return s;\n end = s;\n\n while( ! *end)\n end++;\n end--;\n\n while (end ! = s && isspace( *end))\n end--;\n *(end + 1) = '\\0';\n\n return s;\n}\n void strstrip(char *s)\n{\n char *start;\n char *end;\n\n start = s; \n while ( (*start) && isspace( *start))\n start++;\n\n if(!( *start) ) \n {\n *s='\\0';\n return ;\n }\n end = start;\n\n while( ! *end)\n end++;\n end--;\n\n while (end ! = start && isspace( *end))\n end--;\n *(end + 1) = '\\0';\n\n memmove(s, start, end-start+1);\n\n return;\n}\n" }, { "answer_id": 412384, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 1, "selected": false, "text": "g_strstrip()" }, { "answer_id": 412684, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#include <ctype.h>\nchar *mytrim(char *s)\n{\n if(s) { /* Don't forget to check for NULL! */\n while(*s && isspace(*s))\n ++s;\n if(*s) {\n register char *p = s;\n while(*p)\n ++p;\n do {\n --p;\n } while((p != s) && isspace(*p));\n *(p + 1) = '\\0';\n }\n }\n return(s);\n}\n" }, { "answer_id": 4611430, "author": "Enlightenment", "author_id": 564889, "author_profile": "https://Stackoverflow.com/users/564889", "pm_score": 2, "selected": false, "text": "void strstrip( char *s )\n{\n char *start;\n char *end;\n\n // Exit if param is NULL pointer\n if (s == NULL)\n return;\n\n // Skip over leading whitespace\n start = s;\n while ((*start) && isspace(*start))\n start++; \n\n // Is string just whitespace?\n if (!(*start)) \n { \n *s = 0x00; // Truncate entire string\n return; \n } \n\n // Find end of string\n end = start;\n while (*end) \n end++; \n\n // Step back from NUL\n end--; \n\n // Step backward until first non-whitespace\n while ((end != start) && isspace(*end)) \n end--; \n\n // Chop off trailing whitespace\n *(end + 1) = 0x00;\n\n // If had leading whitespace, then move entire string back to beginning\n if (s != start)\n memmove(s, start, end-start+1); \n\n return; \n} \n" }, { "answer_id": 17309582, "author": "Indinfer", "author_id": 843604, "author_profile": "https://Stackoverflow.com/users/843604", "pm_score": 2, "selected": false, "text": "static char* trim_left_ptr(char* str)\n{\n if (*str == 0)\n {\n // no more in string. It is an empty string\n return str;\n }\n\n if (*str == ' ' || *str == '\\t')\n {\n // it is space or tab. Try next.\n return trim_left_ptr(str + 1);\n }\n\n\n // found left side of string\n return str;\n}\n\n\nstatic char* trim_right_ptr(char* str)\n{\n if (*str == 0)\n {\n // found end of string\n return str;\n }\n\n // try next (recursion)\n char* ptr = trim_right_ptr( str + 1 );\n\n // on the return from recursion.\n // ptr == str until a nonspace/nontab is found.\n if (*(ptr - 1) == ' ' || *(ptr - 1) == '\\t')\n {\n // is space or tab. Have not yet found right side\n return ptr - 1;\n }\n\n // found right side of string\n return ptr;\n}\n\n\n\nchar* trim(char* str)\n{\n char* L_Ptr = trim_left_ptr(str);\n char* R_Ptr = trim_right_ptr(str);\n\n // calculate characters to store in new buffer\n _int32 sz = R_Ptr - L_Ptr;\n\n // allocate buffer\n char* newstr = (char*) malloc(sz + 1);\n\n // copy trimmed string\n memcpy(newstr, L_Ptr, sz);\n\n // terminate string\n *(newstr + sz) = 0;\n\n return newstr;\n}\n" }, { "answer_id": 21194222, "author": "Rajendra", "author_id": 1996099, "author_profile": "https://Stackoverflow.com/users/1996099", "pm_score": 1, "selected": false, "text": "char *strip(char *string)\n{\n char *start = string;\n while(isblank(*start)) start++;\n int end = strlen(start);\n if(start != string) {\n memmove(string, start, end);\n string[end] = '\\0';\n }\n while(isblank(*(string+end-1))) end--;\n string[end] = '\\0';\n return string;\n}\n" }, { "answer_id": 23232063, "author": "R.H.", "author_id": 3562412, "author_profile": "https://Stackoverflow.com/users/3562412", "pm_score": 1, "selected": false, "text": "void trimWhitespace(char *string) {\n const char* firstNonSpace = string;\n char* endOfString;\n size_t len;\n\n if (string[0] == '\\0') {\n return;\n }\n\n /* First remove leading spaces */\n while(*firstNonSpace != '\\0' && isspace(*firstNonSpace)) {\n ++firstNonSpace;\n }\n len = strlen(firstNonSpace) + 1;\n memmove(string, firstNonSpace, len);\n\n /* Now remove trailing spaces */\n endOfString = string + len;\n\n while(string < endOfString && (isspace(*endOfString) || *endOfString == '\\0')) {\n --endOfString ;\n }\n\n *(endOfString + 1) = '\\0';\n}\n" }, { "answer_id": 33179030, "author": "JamesAD-0", "author_id": 4718990, "author_profile": "https://Stackoverflow.com/users/4718990", "pm_score": 1, "selected": false, "text": "char *x;\nchar *y = \"somestring \"; \n\nx = strtok(y,\" \");\n" }, { "answer_id": 35616915, "author": "fnisi", "author_id": 1884351, "author_profile": "https://Stackoverflow.com/users/1884351", "pm_score": 1, "selected": false, "text": "char *zstring_trim(char *s) char *zstring_ltrim(char *s) char *zstring_ltrim(char *s) /* trim */\nchar *zstring_trim(char *str){\n char *src=str; /* save the original pointer */\n char *dst=str; /* result */\n char c;\n int is_space=0;\n int in_word=0; /* word boundary logical check */\n int index=0; /* index of the last non-space char*/\n\n /* validate input */\n if (!str)\n return str;\n\n while ((c=*src)){\n is_space=0;\n\n if (c=='\\t' || c=='\\v' || c=='\\f' || c=='\\n' || c=='\\r' || c==' ')\n is_space=1;\n\n if(is_space == 0){\n /* Found a word */\n in_word = 1;\n *dst++ = *src++; /* make the assignment first\n * then increment\n */\n } else if (is_space==1 && in_word==0) {\n /* Already going through a series of white-spaces */\n in_word=0;\n ++src;\n } else if (is_space==1 && in_word==1) {\n /* End of a word, dont mind copy white spaces here */\n in_word=0;\n *dst++ = *src++;\n index = (dst-str)-1; /* location of the last char */\n }\n }\n\n /* terminate the string */\n *(str+index)='\\0';\n\n return str;\n}\n\n/* right trim */\nchar *zstring_rtrim(char *str){\n char *src=str; /* save the original pointer */\n char *dst=str; /* result */\n char c;\n int is_space=0;\n int index=0; /* index of the last non-space char */\n\n /* validate input */\n if (!str)\n return str;\n\n /* copy the string */\n while(*src){\n *dst++ = *src++;\n c = *src;\n\n if (c=='\\t' || c=='\\v' || c=='\\f' || c=='\\n' || c=='\\r' || c==' ')\n is_space=1;\n else\n is_space=0;\n\n if (is_space==0 && *src)\n index = (src-str)+1;\n }\n\n /* terminate the string */\n *(str+index)='\\0';\n\n return str;\n}\n\n/* left trim */\nchar *zstring_ltrim(char *str){\n char *src=str; /* save the original pointer */\n char *dst=str; /* result */\n char c;\n int index=0; /* index of the first non-space char */\n\n /* validate input */\n if (!str)\n return str;\n\n /* skip leading white-spaces */\n while((c=*src)){ \n if (c=='\\t' || c=='\\v' || c=='\\f' || c=='\\n' || c=='\\r' || c==' '){\n ++src;\n ++index;\n } else\n break;\n }\n\n /* copy rest of the string */\n while(*src)\n *dst++ = *src++;\n\n /* terminate the string */\n *(src-index)='\\0';\n\n return str;\n}\n" }, { "answer_id": 45620263, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "stripLeadingAndTrailingSpaces() static str_strip() strdup() str_strip() <string.h> str mem wcs <string.h> #include <assert.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <string.h>\n\n/* Code verbatim from answer by AlfaZulu (except for static) — which has problems */\nstatic\nvoid stripLeadingAndTrailingSpaces(char* string){\n\n assert(string);\n\n /* First remove leading spaces */\n\n const char* firstNonSpace = string;\n\n while(*firstNonSpace != '\\0' && isspace(*firstNonSpace))\n {\n ++firstNonSpace;\n }\n\n size_t len = strlen(firstNonSpace)+1;\n\n memmove(string, firstNonSpace, len);\n\n /* Now remove trailing spaces */\n\n char* endOfString = string + len;\n\n while(string < endOfString && isspace(*endOfString))\n {\n --endOfString ;\n }\n\n *endOfString = '\\0';\n\n}\n\nstatic void str_strip(char *string)\n{\n assert(string);\n //printf(\"-->> %s(): [%s]\\n\", __func__, string);\n\n /* First remove leading spaces */\n const char *firstNonSpace = string;\n\n while (isspace((unsigned char)*firstNonSpace))\n ++firstNonSpace;\n //printf(\"---- %s(): [%s]\\n\", __func__, firstNonSpace);\n\n size_t len = strlen(firstNonSpace) + 1;\n memmove(string, firstNonSpace, len);\n //printf(\"---- %s(): [%s]\\n\", __func__, string);\n\n /* Now remove trailing spaces */\n char *endOfString = string + len - 1;\n //printf(\"---- %s(): EOS [%s]\\n\", __func__, endOfString);\n\n while (string < endOfString && isspace((unsigned char)endOfString[-1]))\n --endOfString;\n *endOfString = '\\0';\n //printf(\"<<-- %s(): [%s]\\n\", __func__, string);\n}\n\nstatic void chk_stripper(const char *str)\n{\n char *copy1 = strdup(str);\n printf(\"V1 Before: [%s]\\n\", copy1);\n stripLeadingAndTrailingSpaces(copy1);\n printf(\"V1 After: [%s]\\n\", copy1);\n free(copy1);\n fflush(stdout);\n\n char *copy2 = strdup(str);\n printf(\"V2 Before: [%s]\\n\", copy2);\n str_strip(copy2);\n printf(\"V2 After: [%s]\\n\", copy2);\n free(copy2);\n fflush(stdout);\n}\n\nint main(void)\n{\n char *str[] =\n {\n \" \\t ABC DEF \\t \",\n \" \\t \\t \",\n \" \",\n \"\",\n };\n enum { NUM_STR = sizeof(str) / sizeof(str[0]) };\n for (int i = 0; i < NUM_STR; i++)\n chk_stripper(str[i]);\n return 0;\n}\n $ valgrind --suppressions=etc/suppressions-macos-10.12.5 -- ./slts59\n==26999== Memcheck, a memory error detector\n==26999== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n==26999== Using Valgrind-3.13.0.SVN and LibVEX; rerun with -h for copyright info\n==26999== Command: ./slts59\n==26999== \nV1 Before: [ ABC DEF ]\nV1 After: [ABC DEF ]\nV2 Before: [ ABC DEF ]\nV2 After: [ABC DEF]\nV1 Before: [ ]\nV1 After: []\nV2 Before: [ ]\nV2 After: []\nV1 Before: [ ]\nV1 After: []\nV2 Before: [ ]\nV2 After: []\n==26999== Invalid read of size 1\n==26999== at 0x100000B81: stripLeadingAndTrailingSpaces (slts59.c:28)\n==26999== by 0x100000CB0: chk_stripper (slts59.c:67)\n==26999== by 0x100000DA2: main (slts59.c:91)\n==26999== Address 0x100b7df01 is 0 bytes after a block of size 1 alloc'd\n==26999== at 0x100096861: malloc (vg_replace_malloc.c:302)\n==26999== by 0x1002DC938: strdup (in /usr/lib/system/libsystem_c.dylib)\n==26999== by 0x100000C88: chk_stripper (slts59.c:65)\n==26999== by 0x100000DA2: main (slts59.c:91)\n==26999== \n==26999== Invalid write of size 1\n==26999== at 0x100000B96: stripLeadingAndTrailingSpaces (slts59.c:33)\n==26999== by 0x100000CB0: chk_stripper (slts59.c:67)\n==26999== by 0x100000DA2: main (slts59.c:91)\n==26999== Address 0x100b7df01 is 0 bytes after a block of size 1 alloc'd\n==26999== at 0x100096861: malloc (vg_replace_malloc.c:302)\n==26999== by 0x1002DC938: strdup (in /usr/lib/system/libsystem_c.dylib)\n==26999== by 0x100000C88: chk_stripper (slts59.c:65)\n==26999== by 0x100000DA2: main (slts59.c:91)\n==26999== \nV1 Before: []\nV1 After: []\nV2 Before: []\nV2 After: []\n==26999== \n==26999== HEAP SUMMARY:\n==26999== in use at exit: 34,572 bytes in 162 blocks\n==26999== total heap usage: 186 allocs, 24 frees, 40,826 bytes allocated\n==26999== \n==26999== LEAK SUMMARY:\n==26999== definitely lost: 0 bytes in 0 blocks\n==26999== indirectly lost: 0 bytes in 0 blocks\n==26999== possibly lost: 0 bytes in 0 blocks\n==26999== still reachable: 0 bytes in 0 blocks\n==26999== suppressed: 34,572 bytes in 162 blocks\n==26999== \n==26999== For counts of detected and suppressed errors, rerun with: -v\n==26999== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)\n$\n str_strip() stripLeadingAndTrailingSpaces() strstrip()" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16139/" ]
352,059
<p>do you know any good algorithms that match two strings and then return a percentage in how many percent those two strings match?</p> <p>And are there some, that work with databases too?</p>
[ { "answer_id": 352881, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 2, "selected": false, "text": "Levenstein(\"copy\", \"cpoy\") == 2\n levenstein() contrib" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9535/" ]
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
[ { "answer_id": 352105, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 0, "selected": false, "text": "result = [blah(blah(blah(x)))\n for x in list]\n" }, { "answer_id": 352121, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 1, "selected": false, "text": "def operation(x):\n x0 = h(x)\n x1 = g(x0)\n x2 = f(x1)\n return x2\nresult = [ operation(x) for x in list]\n" }, { "answer_id": 352219, "author": "rob", "author_id": 43927, "author_profile": "https://Stackoverflow.com/users/43927", "pm_score": 2, "selected": false, "text": "result = [f(\n g(\n h(x)\n )\n )\n for x in list]\n result = [h(x) for x in list]\nresult = [g(x) for x in result]\nresult = [f(x) for x in result]\n" }, { "answer_id": 353060, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": ">>> def comp( a, b ):\n def compose( args ):\n return a( b( args ) )\n return compose\n\n>>> def times2(x): return x*2\n\n>>> def plus1(x): return x+1\n\n>>> comp( times2, plus1 )(32)\n66\n" }, { "answer_id": 353147, "author": "dagw", "author_id": 41326, "author_profile": "https://Stackoverflow.com/users/41326", "pm_score": 2, "selected": false, "text": "def seriesoffncs(fncs,x):\n for f in fncs[::-1]:\n x=f(x)\n return x\n" }, { "answer_id": 353729, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 1, "selected": false, "text": "def chained_apply(*args):\n val = args[-1]\n for f in fncs[:-1:-1]:\n val=f(val)\n return val\n result = chained_apply(foo, bar, baz, x)\n" }, { "answer_id": 406944, "author": "Steve Losh", "author_id": 13498, "author_profile": "https://Stackoverflow.com/users/13498", "pm_score": 1, "selected": false, "text": "def compose(*f):\n return f[0] if len(f) == 1 else lambda *args: f[0](compose(*f[1:])(*args))\n\ndef f(x): \n return 'o ' + str(x)\n\ndef g(x): \n return 'hai ' + str(x)\n\ndef h(x, y): \n return 'there ' + str(x) + str(y) + '\\n'\n\naction = compose(f, g, h)\nprint [action(\"Test \", item) for item in [1, 2, 3]]\n print [compose(f, g, h)(\"Test \", item) for item in [1, 2, 3]]\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37984/" ]
352,079
<p>I'm using the appengine webapp framework (<a href="http://code.google.com/appengine/docs/webapp/" rel="nofollow noreferrer">link</a>). Is it possible to add Django middleware? I can't find any examples. I'm currently trying to get the FirePython middleware to work (<a href="http://github.com/woid/firepython/tree/master" rel="nofollow noreferrer">link</a>).</p>
[ { "answer_id": 548865, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 0, "selected": false, "text": "session environ['beaker.session'] main.py" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37575/" ]
352,089
<p>Why isn't there a bit structure in C#?</p>
[ { "answer_id": 25684299, "author": "Konamiman", "author_id": 4574, "author_profile": "https://Stackoverflow.com/users/4574", "pm_score": 5, "selected": false, "text": "int bool /// <summary>\n/// Represents a single bit that can be implicitly cast to/from and compared\n/// with booleans and integers.\n/// </summary>\n/// <remarks>\n/// <para>\n/// An instance with a value of one is equal to any non-zero integer and is true,\n/// an instance with a value of zero is equal to the integer zero and is false.\n/// </para>\n/// <para>\n/// Arithmetic and logical AND, OR and NOT, as well as arithmetic XOR, are supported.\n/// </para>\n/// </remarks>\npublic struct Bit\n{\n /// <summary>\n /// Creates a new instance with the specified value.\n /// </summary>\n /// <param name=\"value\"></param>\n public Bit(int value) : this()\n {\n Value = value == 0 ? 0 : 1;\n }\n\n /// <summary>\n /// Gets the value of the bit, 0 or 1.\n /// </summary>\n public int Value { get; private set; }\n\n #region Implicit conversions\n\n public static implicit operator Bit(int value)\n {\n return new Bit(value);\n }\n\n public static implicit operator int(Bit value)\n {\n return value.Value;\n }\n\n public static implicit operator bool(Bit value)\n {\n return value.Value == 1;\n }\n\n public static implicit operator Bit(bool value)\n {\n return new Bit(value ? 1 : 0);\n }\n\n #endregion\n\n #region Arithmetic operators\n\n public static Bit operator |(Bit value1, Bit value2)\n {\n return value1.Value | value2.Value;\n }\n\n public static Bit operator &(Bit value1, Bit value2)\n {\n return value1.Value & value2.Value;\n }\n\n public static Bit operator ^(Bit value1, Bit value2)\n {\n return value1.Value ^ value2.Value;\n }\n\n public static Bit operator ~(Bit value)\n {\n return new Bit(value.Value ^ 1);\n }\n\n public static Bit operator !(Bit value)\n {\n return ~value;\n }\n\n #endregion\n\n #region The true and false operators\n\n public static bool operator true(Bit value)\n {\n return value.Value == 1;\n }\n\n public static bool operator false(Bit value)\n {\n return value.Value == 0;\n }\n\n #endregion\n\n #region Comparison operators\n\n public static bool operator ==(Bit bitValue, int intValue)\n {\n return \n (bitValue.Value == 0 && intValue == 0) || \n (bitValue.Value == 1 && intValue != 0);\n }\n\n public static bool operator !=(Bit bitValue, int intValue)\n {\n return !(bitValue == intValue);\n }\n\n public override bool Equals(object obj)\n {\n if(obj is int)\n return this == (int)obj;\n else\n return base.Equals(obj);\n }\n\n #endregion\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44527/" ]
352,098
<p>Is there a (Unix) shell script to format JSON in human-readable form?</p> <p>Basically, I want it to transform the following:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;foo&quot;: &quot;lorem&quot;, &quot;bar&quot;: &quot;ipsum&quot; } </code></pre> <p>... into something like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;foo&quot;: &quot;lorem&quot;, &quot;bar&quot;: &quot;ipsum&quot; } </code></pre>
[ { "answer_id": 352160, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": false, "text": "$ echo '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }' \\\n> | python -c'import fileinput, json;\n> print(json.dumps(json.loads(\"\".join(fileinput.input())),\n> sort_keys=True, indent=4))'\n{\n \"bar\": \"ipsum\",\n \"foo\": \"lorem\"\n}\n $ cat json.txt \\\n> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}), \n> {pretty=>1})'\n{\n \"bar\" : \"ipsum\",\n \"foo\" : \"lorem\"\n}\n echo '{ \"Düsseldorf\": \"lorem\", \"bar\": \"ipsum\" }' \\\n| python -c'import fileinput, json;\nprint(json.dumps(json.loads(\"\".join(fileinput.input())),\n sort_keys=True, indent=4))'\n {\n \"D\\u00fcsseldorf\": \"lorem\", \n \"bar\": \"ipsum\"\n}\n ensure_ascii=False echo '{ \"Düsseldorf\": \"lorem\", \"bar\": \"ipsum\" }' \\\n| python -c'import fileinput, json;\nprint json.dumps(json.loads(\"\".join(fileinput.input())),\n sort_keys=True, indent=4, ensure_ascii=False)'\n {\n \"Düsseldorf\": \"lorem\", \n \"bar\": \"ipsum\"\n}\n" }, { "answer_id": 354464, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "#!/usr/bin/python\n\n\"\"\"\nConvert JSON data to human-readable form.\n\nUsage:\n prettyJSON.py inputFile [outputFile]\n\"\"\"\n\nimport sys\nimport simplejson as json\n\n\ndef main(args):\n try:\n if args[1] == '-':\n inputFile = sys.stdin\n else:\n inputFile = open(args[1])\n input = json.load(inputFile)\n inputFile.close()\n except IndexError:\n usage()\n return False\n if len(args) < 3:\n print json.dumps(input, sort_keys = False, indent = 4)\n else:\n outputFile = open(args[2], \"w\")\n json.dump(input, outputFile, sort_keys = False, indent = 4)\n outputFile.close()\n return True\n\n\ndef usage():\n print __doc__\n\n\nif __name__ == \"__main__\":\n sys.exit(not main(sys.argv))\n" }, { "answer_id": 1060535, "author": "pimlottc", "author_id": 101189, "author_profile": "https://Stackoverflow.com/users/101189", "pm_score": 3, "selected": false, "text": "perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), \"\\n\";'\n" }, { "answer_id": 1210163, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 6, "selected": false, "text": "#!/usr/bin/env python\n\"\"\"\nConvert JSON data to human-readable form.\n\n(Reads from stdin and writes to stdout)\n\"\"\"\n\nimport sys\ntry:\n import simplejson as json\nexcept:\n import json\n\nprint json.dumps(json.loads(sys.stdin.read()), indent=4)\nsys.exit(0)\n chmod +x" }, { "answer_id": 1599617, "author": "darscan", "author_id": 53303, "author_profile": "https://Stackoverflow.com/users/53303", "pm_score": 5, "selected": false, "text": "echo '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }' | ruby -r json -e 'jj JSON.parse gets'\n" }, { "answer_id": 1920585, "author": "B Bycroft", "author_id": 233648, "author_profile": "https://Stackoverflow.com/users/233648", "pm_score": 12, "selected": false, "text": "echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | python -m json.tool\n python -m json.tool my_json.json\n curl http://my_url/ | python -m json.tool\n alias prettyjson='python -m json.tool'\n prettyjson_s() {\n echo \"$1\" | python -m json.tool\n}\n\nprettyjson_f() {\n python -m json.tool \"$1\"\n}\n\nprettyjson_w() {\n curl \"$1\" | python -m json.tool\n}\n .bashrc prettyjson_s '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' --sort-keys ... | python -m json.tool --sort-keys" }, { "answer_id": 1975540, "author": "Paul Horsfall", "author_id": 99265, "author_profile": "https://Stackoverflow.com/users/99265", "pm_score": 6, "selected": false, "text": "sudo gem install json\necho '{ \"foo\": \"bar\" }' | prettify_json.rb\n" }, { "answer_id": 3150232, "author": "knb", "author_id": 202553, "author_profile": "https://Stackoverflow.com/users/202553", "pm_score": 6, "selected": false, "text": "JSON::XS json_xs json_xs -t null < myfile.json\n src.json pretty.json < src.json json_xs > pretty.json\n json_xs json_pp" }, { "answer_id": 3228727, "author": "Somu", "author_id": 389489, "author_profile": "https://Stackoverflow.com/users/389489", "pm_score": 9, "selected": false, "text": "JSON.stringify // Indent with 4 spaces\nJSON.stringify({\"foo\":\"lorem\",\"bar\":\"ipsum\"}, null, 4);\n\n// Indent with tabs\nJSON.stringify({\"foo\":\"lorem\",\"bar\":\"ipsum\"}, null, '\\t');\n $ node -e \"console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\\t'));\" \\\n '{\"foo\":\"lorem\",\"bar\":\"ipsum\"}'\n {\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n $ node -e \"console.log(JSON.stringify(JSON.parse(require('fs') \\\n .readFileSync(process.argv[1])), null, 4));\" filename.json\n echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | node -e \\\n\"\\\n s=process.openStdin();\\\n d=[];\\\n s.on('data',function(c){\\\n d.push(c);\\\n });\\\n s.on('end',function(){\\\n console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\\\n });\\\n\"\n" }, { "answer_id": 4797459, "author": "Mike Conigliaro", "author_id": 115635, "author_profile": "https://Stackoverflow.com/users/115635", "pm_score": 5, "selected": false, "text": "gem install jazor\njazor --help\n" }, { "answer_id": 4840445, "author": "isaacs", "author_id": 352493, "author_profile": "https://Stackoverflow.com/users/352493", "pm_score": 7, "selected": false, "text": "npm install -g json json json -h -i curl -s http://search.twitter.com/search.json?q=node.js | json\n" }, { "answer_id": 4880453, "author": "htaccess", "author_id": 599390, "author_profile": "https://Stackoverflow.com/users/599390", "pm_score": 4, "selected": false, "text": "sudo apt-get install libjson-xs-perl\n $ curl -s http://page.that.serves.json.com/json/ | json_xs\n $ wget -q -O - http://page.that.serves.json.com/json/ | json_xs\n $ json_xs < file-full-of.json\n $ json_xs -t yaml < file-full-of.json\n" }, { "answer_id": 5006476, "author": "Bryan Larsen", "author_id": 91365, "author_profile": "https://Stackoverflow.com/users/91365", "pm_score": 3, "selected": false, "text": "$ sudo apt-get install edit-json\n$ prettify_json myfile.json\n" }, { "answer_id": 6047998, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": false, "text": "yajl json_reformat .json vim .vimrc autocmd FileType json setlocal equalprg=json_reformat\n" }, { "answer_id": 6066102, "author": "yar", "author_id": 730123, "author_profile": "https://Stackoverflow.com/users/730123", "pm_score": 5, "selected": false, "text": "echo $COMPACTED_JSON_TEXT | jshon\n" }, { "answer_id": 7691365, "author": "Philip Durbin", "author_id": 19464, "author_profile": "https://Stackoverflow.com/users/19464", "pm_score": 5, "selected": false, "text": "[pdurbin@beamish ~]$ echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | json_pp\n{\n \"bar\" : \"ipsum\",\n \"foo\" : \"lorem\"\n}\n json_pp /usr/bin/json_pp" }, { "answer_id": 7961562, "author": "jassinm", "author_id": 239007, "author_profile": "https://Stackoverflow.com/users/239007", "pm_score": 8, "selected": false, "text": "echo '{\"test\":1,\"test2\":2}' | python -mjson.tool\n echo '{\"test\":1,\"test2\":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data[\"test\"]'\n python -mjson.tool filename.json\n curl curl -X GET -H \"Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53\" http://testsite/api/ | python -mjson.tool\n" }, { "answer_id": 8438023, "author": "numan salati", "author_id": 909956, "author_profile": "https://Stackoverflow.com/users/909956", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env groovy\n\nimport groovy.json.JsonOutput\n\nSystem.in.withReader { println JsonOutput.prettyPrint(it.readLine()) }\n chmod +x pretty-print\n echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | ./pretty-print\n" }, { "answer_id": 8813967, "author": "Wu Yongzheng", "author_id": 248571, "author_profile": "https://Stackoverflow.com/users/248571", "pm_score": 2, "selected": false, "text": "$ echo '{\"a\": 1, \"b\": 2}' | json-liner\n/%a 1\n/%b 2\n$ echo '[\"foo\", \"bar\", \"baz\"]' | json-liner\n/@0 foo\n/@1 bar\n/@2 baz\n" }, { "answer_id": 9599906, "author": "nelaaro", "author_id": 619760, "author_profile": "https://Stackoverflow.com/users/619760", "pm_score": 1, "selected": false, "text": "{id:'name',label:'Name',type:'string'}\n {\"id\": \"name\", \"label\": \"Name\", \"type\": \"string\"}\n" }, { "answer_id": 10349115, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 5, "selected": false, "text": "npm install jsonlint -g\n jsonlint -p myfile.json\n curl -s \"http://api.twitter.com/1/users/show/user.json\" | jsonlint | less\n" }, { "answer_id": 10401134, "author": "Dave Dopson", "author_id": 407731, "author_profile": "https://Stackoverflow.com/users/407731", "pm_score": 8, "selected": false, "text": "underscore -i data.json print\n cat data.json | underscore print\n cat data.json | underscore print --outfmt pretty\n" }, { "answer_id": 13414671, "author": "Roberto", "author_id": 667825, "author_profile": "https://Stackoverflow.com/users/667825", "pm_score": -1, "selected": false, "text": "JSON.stringfy(JSON.parse(str), null, 4)\n { \"c\": 1, \"a\": {\"b1\": 2, \"a1\":1 }, \"b\": 1},\n {\n \"b\": 1,\n \"c\": 1,\n \"a\": {\n \"a1\": 1,\n \"b1\": 2\n }\n}\n {\n \"a\": {\n \"a1\": 1,\n \"b1\": 2\n },\n \"b\": 1,\n \"c\": 1\n}\n" }, { "answer_id": 13530149, "author": "Uma sankar pradhan", "author_id": 1847666, "author_profile": "https://Stackoverflow.com/users/1847666", "pm_score": 4, "selected": false, "text": "sudo apt-get install yajl-tools\n echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | json_reformat\n" }, { "answer_id": 14582809, "author": "Johann Philipp Strathausen", "author_id": 284708, "author_profile": "https://Stackoverflow.com/users/284708", "pm_score": 6, "selected": false, "text": "pjson pip ⚡ pip install pjson\n pjson" }, { "answer_id": 15231463, "author": "Vita Pluvia", "author_id": 866516, "author_profile": "https://Stackoverflow.com/users/866516", "pm_score": 10, "selected": false, "text": "jq $ jq --color-output . file1.json file1.json | less -R\n\n$ command_with_json_output | jq .\n\n$ jq # stdin/\"interactive\" mode, just enter some JSON\n\n$ jq <<< '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }'\n{\n \"bar\": \"ipsum\",\n \"foo\": \"lorem\"\n}\n jq $ jq '.foo' <<< '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }'\n\"lorem\"\n" }, { "answer_id": 16090784, "author": "svidgen", "author_id": 779572, "author_profile": "https://Stackoverflow.com/users/779572", "pm_score": 3, "selected": false, "text": "alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'\necho '{\"a\":1,\"b\":2}' | prettify_json\n" }, { "answer_id": 16666351, "author": "jordelver", "author_id": 120615, "author_profile": "https://Stackoverflow.com/users/120615", "pm_score": 6, "selected": false, "text": "jq curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp\n jsonpp data/long_malformed.json\n brew install jsonpp $PATH" }, { "answer_id": 18077286, "author": "Pablo Fernandez heelhook", "author_id": 828290, "author_profile": "https://Stackoverflow.com/users/828290", "pm_score": 3, "selected": false, "text": "colorful_json gem install colorful_json\necho '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | cjson\n{\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n" }, { "answer_id": 25274120, "author": "Orest Ivasiv", "author_id": 548512, "author_profile": "https://Stackoverflow.com/users/548512", "pm_score": 2, "selected": false, "text": "echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'\n" }, { "answer_id": 28891596, "author": "slashmili", "author_id": 683247, "author_profile": "https://Stackoverflow.com/users/683247", "pm_score": 3, "selected": false, "text": "$ pip install httpie\n $ http PUT localhost:8001/api/v1/ports/my \n HTTP/1.1 200 OK\n Connection: keep-alive\n Content-Length: 93\n Content-Type: application/json\n Date: Fri, 06 Mar 2015 02:46:41 GMT\n Server: nginx/1.4.6 (Ubuntu)\n X-Powered-By: HHVM/3.5.1\n\n {\n \"data\": [], \n \"message\": \"Failed to manage ports in 'my'. Request body is empty\", \n \"success\": false\n }\n" }, { "answer_id": 32246520, "author": "Shubham Chaudhary", "author_id": 2670370, "author_profile": "https://Stackoverflow.com/users/2670370", "pm_score": 5, "selected": false, "text": "echo '{\"foo\": \"bar\"}' | python -m json.tool | pygmentize -g\n" }, { "answer_id": 33707171, "author": "adius", "author_id": 1850340, "author_profile": "https://Stackoverflow.com/users/1850340", "pm_score": 3, "selected": false, "text": "cat file.json | node -e \"process.stdin.pipe(new require('stream').Writable({write: chunk => {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))\"\n" }, { "answer_id": 34222057, "author": "lev", "author_id": 1991051, "author_profile": "https://Stackoverflow.com/users/1991051", "pm_score": 2, "selected": false, "text": "gem install jsonpretty\necho '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | jsonpretty\n" }, { "answer_id": 38607019, "author": "Evgeny Karpov", "author_id": 889745, "author_profile": "https://Stackoverflow.com/users/889745", "pm_score": 6, "selected": false, "text": "#/bin/bash\n\ngrep -Eo '\"[^\"]*\" *(: *([0-9]*|\"[^\"]*\")[^{}\\[\"]*|,)?|[^\"\\]\\[\\}\\{]*|\\{|\\},?|\\[|\\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\\]]/ ) offset-=4; printf \"%*c%s\\n\", offset, \" \", $0; if ($0 ~ /^[{\\[]/) offset+=4}'\n cat file.json | json_pretty.sh\n" }, { "answer_id": 38686090, "author": "josch", "author_id": 784669, "author_profile": "https://Stackoverflow.com/users/784669", "pm_score": 3, "selected": false, "text": "ydump $ ydump my_data.json\n{\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n $ echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | ydump\n{\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n jq yojson libyojson-ocaml-dev yojson" }, { "answer_id": 39841974, "author": "Ackshaey Singh", "author_id": 1768876, "author_profile": "https://Stackoverflow.com/users/1768876", "pm_score": 5, "selected": false, "text": "jq . twurl -H ads-api.twitter.com '.......' | jq .\n" }, { "answer_id": 40059751, "author": "Yada", "author_id": 45066, "author_profile": "https://Stackoverflow.com/users/45066", "pm_score": 2, "selected": false, "text": "curl -XPOST https://jsonprettyprint.org/api -d '{\"user\" : 1}'\n" }, { "answer_id": 41976229, "author": "Nikhil Ranjan", "author_id": 1125824, "author_profile": "https://Stackoverflow.com/users/1125824", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env node\n\nconsole.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));\n #!/usr/bin/env node\n\nconsole.log(JSON.stringify(require(\"./\" + process.argv[2]), null, 2));\n" }, { "answer_id": 42012541, "author": "Tadej", "author_id": 7199922, "author_profile": "https://Stackoverflow.com/users/7199922", "pm_score": 6, "selected": false, "text": "curl yourUri | json_pp\n" }, { "answer_id": 42336622, "author": "aidanmelen", "author_id": 3894599, "author_profile": "https://Stackoverflow.com/users/3894599", "pm_score": 2, "selected": false, "text": "from __future__ import unicode_literals\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport json\nimport jsonschema\n\ndef _validate(data):\n schema = {\"$schema\": \"http://json-schema.org/draft-04/schema#\"}\n try:\n jsonschema.validate(data, schema,\n format_checker=jsonschema.FormatChecker())\n except jsonschema.exceptions.ValidationError as ve:\n sys.stderr.write(\"Whoops, the data you provided does not seem to be \" \\\n \"valid JSON.\\n{}\".format(ve))\n\ndef pprint(data, python_obj=False, **kwargs):\n _validate(data)\n kwargs[\"indent\"] = kwargs.get(\"indent\", 4)\n pretty_data = json.dumps(data, **kwargs)\n if python_obj:\n print(pretty_data)\n else:\n repls = ((\"u'\",'\"'),\n (\"'\",'\"'),\n (\"None\",'null'),\n (\"True\",'true'),\n (\"False\",'false'))\n print(reduce(lambda a, kv: a.replace(*kv), repls, pretty_data))\n" }, { "answer_id": 44052370, "author": "Olexandr Minzak", "author_id": 5879663, "author_profile": "https://Stackoverflow.com/users/5879663", "pm_score": 7, "selected": false, "text": "cat xxx | jq .\n" }, { "answer_id": 46247168, "author": "alexanderjsingleton", "author_id": 3854705, "author_profile": "https://Stackoverflow.com/users/3854705", "pm_score": 4, "selected": false, "text": "brew install jq command + | jq curl localhost:5000/blocks | jq" }, { "answer_id": 46968956, "author": "Fangxing", "author_id": 5615038, "author_profile": "https://Stackoverflow.com/users/5615038", "pm_score": 4, "selected": false, "text": "echo '{\"test\":1,\"test2\":2}' | ruby -e \"require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))\"\n alias to_j=\"ruby -e \\\"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\\\"\"\n echo '{\"test\":1,\"test2\":2}' | to_j\n\n{\n \"test\": 1,\n \"test2\": 2\n}\n awesome_print gem install awesome_print\n alias to_j=\"ruby -e \\\"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\\\"\"\n echo '{\"test\":1,\"test2\":2, \"arr\":[\"aa\",\"bb\",\"cc\"] }' | to_j\n" }, { "answer_id": 48974193, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 4, "selected": false, "text": "jj -p # for reading from STDIN\n jj -p -i input.json\n" }, { "answer_id": 51361510, "author": "Arpit Rathod", "author_id": 6374273, "author_profile": "https://Stackoverflow.com/users/6374273", "pm_score": 5, "selected": false, "text": "echo \"{ \\\"foo\\\": \\\"lorem\\\", \\\"bar\\\": \\\"ipsum\\\" }\"|python -m json.tool\n" }, { "answer_id": 52144816, "author": "Grav", "author_id": 202538, "author_profile": "https://Stackoverflow.com/users/202538", "pm_score": 4, "selected": false, "text": "bat cat echo '{\"bignum\":1e1000}' | bat -p -l json\n -p -l" }, { "answer_id": 52492098, "author": "harish2704", "author_id": 1677234, "author_profile": "https://Stackoverflow.com/users/1677234", "pm_score": 4, "selected": false, "text": "$ node -e \"console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))\"\n $ cat test.json | node -e \"console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))\"\n" }, { "answer_id": 54245596, "author": "Reino", "author_id": 2703456, "author_profile": "https://Stackoverflow.com/users/2703456", "pm_score": 1, "selected": false, "text": "$ xidel -se '$json' <<< '{\"foo\":\"lorem\",\"bar\":\"ipsum\"}'\n{\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n $ echo '{\"foo\":\"lorem\",\"bar\":\"ipsum\"}' | xidel -se '$json'\n{\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n" }, { "answer_id": 58168631, "author": "Schmitzi", "author_id": 8140579, "author_profile": "https://Stackoverflow.com/users/8140579", "pm_score": 5, "selected": false, "text": "echo '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }' | json_pp echo '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }' | jq {\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n" }, { "answer_id": 61119751, "author": "Ulysse BN", "author_id": 6320039, "author_profile": "https://Stackoverflow.com/users/6320039", "pm_score": 3, "selected": false, "text": "jj -p < my.json function bench {\n time (\n for i in {1..1000}; do\n echo '{ \"foo\" : { \"bar\": { \"dolorem\" : \"ipsum\", \"quia\" : { \"dolor\" : \"sit\"} } } }' \\\n | $@ > /dev/null\n done\n )\n}\n bench python -m json.tool\n# 8.39s user 12.31s system 42% cpu 48.536 total\nbench jq\n# 13.12s user 1.28s system 87% cpu 16.535 total\nbench bat -p -l json # NOTE: only syntax colorisation.\n# 1.87s user 1.47s system 66% cpu 5.024 total\nbench jj -p\n# 1.94s user 2.44s system 57% cpu 7.591 total\nbench xidel -s - -e '$json' --printed-json-format=pretty \n# 4.32s user 1.89s system 76% cpu 8.101 total\n" }, { "answer_id": 65560343, "author": "calbertts", "author_id": 1599681, "author_profile": "https://Stackoverflow.com/users/1599681", "pm_score": 2, "selected": false, "text": "# this in your bash profile\njsonprettify() {\n curl -Ss -X POST -H \"Content-Type: text/plain\" --data-binary @- https://jsonprettify.vercel.app/api/server?indent=$@\n}\n echo '{\"prop\": true, \"key\": [1,2]}' | jsonprettify 4\n# {\n# \"prop\": true,\n# \"key\": [\n# 1,\n# 2\n# ]\n# }\n" }, { "answer_id": 66882961, "author": "Rafiek", "author_id": 833105, "author_profile": "https://Stackoverflow.com/users/833105", "pm_score": 4, "selected": false, "text": "echo '{\"test\":1,\"test2\":2}' | npx json\n\n{\n \"test\": 1,\n \"test2\": 2\n}\n" }, { "answer_id": 69821438, "author": "Techie", "author_id": 6764110, "author_profile": "https://Stackoverflow.com/users/6764110", "pm_score": 5, "selected": false, "text": "sudo apt-get update\nsudo apt-get install jq\n echo '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }' | jq\n {\n \"foo\": \"lorem\",\n \"bar\": \"ipsum\"\n}\n" }, { "answer_id": 70848724, "author": "Gagan", "author_id": 713573, "author_profile": "https://Stackoverflow.com/users/713573", "pm_score": 0, "selected": false, "text": "npm install -g munia-pretty-json\n {\"time\":\"2021-06-09T02:50:22Z\",\"level\":\"info\",\"message\":\"Log for pretty JSON\",\"module\":\"init\",\"hostip\":\"192.168.0.138\",\"pid\":123}\n{\"time\":\"2021-06-09T03:27:43Z\",\"level\":\"warn\",\"message\":\"Here is warning message\",\"module\":\"send-message\",\"hostip\":\"192.168.0.138\",\"pid\":123}\n munia-pretty-json app-log.json\n '{time} {level -c} {message}' munia-pretty-json -t '{module -c} - {level} - {message}' app-log.json\n" }, { "answer_id": 71697588, "author": "Adam Erickson", "author_id": 2058131, "author_profile": "https://Stackoverflow.com/users/2058131", "pm_score": 0, "selected": false, "text": "jq $HOME/.bashrc jqless () {\n args=$1\n shift\n jq --color-output . $args \"$@\" | less --raw-control-chars\n}\n" }, { "answer_id": 73152798, "author": "Caleb Koch", "author_id": 3987765, "author_profile": "https://Stackoverflow.com/users/3987765", "pm_score": 2, "selected": false, "text": "npx prettier <JSON file> npx prettier --write <JSON file>" }, { "answer_id": 74374304, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | yq -o json\n echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | yq -o json --indent 3\n echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | yq -o json --colors\n echo '{\"foo\": \"lorem\", \"bar\": \"ipsum\"}' | yq -o json --no-colors\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,103
<p>On this page (<a href="http://www.bonniesphere.com/blog/elsewhere/" rel="nofollow noreferrer">http://www.bonniesphere.com/blog/elsewhere/</a>) the "li" items have an image instead of a bullet. But the image is centered vertically, and in multi-line entries it doesn't look good. Can anyone tell me if there is something in the CSS that should be changed?</p> <p>Here's the relative code:</p> <p>.entry ul {list-style-type:none;} .entry ul li{padding: 0 0 0 15px;background: url(img/ol.gif) no-repeat left center;margin-left:10px;}</p> <p>Many thanks for your help...</p>
[ { "answer_id": 352106, "author": "Kablam", "author_id": 42389, "author_profile": "https://Stackoverflow.com/users/42389", "pm_score": 0, "selected": false, "text": ".entry ul {list-style-type:none;} \n.entry ul li{padding: 0 0 0 15px;\nbackground: url(img/ol.gif) no-repeat left top center;\nmargin-left:10px;}\n" }, { "answer_id": 352123, "author": "BlackMael", "author_id": 19377, "author_profile": "https://Stackoverflow.com/users/19377", "pm_score": 0, "selected": false, "text": ".entry ul li{padding: 0 0 0 15px;background: url(img/ol.gif) no-repeat left 4pt;margin-left:10px;}\n" }, { "answer_id": 352127, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 2, "selected": false, "text": "background: transparent url(img/ol.gif) no-repeat scroll left top;\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,117
<p>I've been lately trying to learn more and generally test Java's serialization for both work and personal projects and I must say that the more I know about it, the less I like it. This may be caused by misinformation though so that's why I'm asking these two things from you all:</p> <p><strong>1:</strong> On byte level, how does serialization know how to match serialized values with some class?</p> <p>One of my problems right here is that I made a small test with ArrayList containing values "one", "two", "three". After serialization the byte array took 78 bytes which seems awfully lot for such low amount of information(19+3+3+4 bytes). Granted there's bound to be some overhead but this leads to my second question:</p> <p><strong>2:</strong> Can serialization be considered a good method for persisting objects at all? Now obviously if I'd use some homemade XML format the persistence data would be something like this</p> <pre class="lang-xml prettyprint-override"><code>&lt;object&gt; &lt;class="java.util.ArrayList"&gt; &lt;!-- Object array inside Arraylist is called elementData --&gt; &lt;field name="elementData"&gt; &lt;value&gt;One&lt;/value&gt; &lt;value&gt;Two&lt;/value&gt; &lt;value&gt;Three&lt;/value&gt; &lt;/field&gt; &lt;/object&gt; </code></pre> <p>which, like XML in general, is a bit bloated and takes 138 bytes(without whitespaces, that is). The same in JSON could be </p> <pre class="lang-json prettyprint-override"><code>{ "java.util.ArrayList": { "elementData": [ "one", "two", "three" ] } } </code></pre> <p>which is 75 bytes so already slightly smaller than Java's serialization. With these text-based formats it's of course obvious that there has to be a way to represent your basic data as text, numbers or any combination of both.</p> <p>So to recap, how does serialization work on byte/bit level, when it should be used and when it shouldn't be used and what are real benefits of serialization besides that it comes standard in Java?</p>
[ { "answer_id": 366739, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 0, "selected": false, "text": "implements Serializable" }, { "answer_id": 34623934, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 2, "selected": false, "text": "private void writeObject(java.io.ObjectOutputStream stream)\n throws IOException {\n stream.writeObject(name); // object property\n stream.writeObject(address); // object property\n }\n\n private void readObject(java.io.ObjectInputStream stream)\n throws IOException, ClassNotFoundException {\n name = (String) stream.readObject(); // object property\n address = (String) stream.readObject();// object property\n }\n Serialization" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44523/" ]
352,118
<p>I place using namespace in a view code behind but i can't call any class of this name space in aspx.</p> <p>In codebehind:</p> <pre><code>using MVCTest.Controller; </code></pre>
[ { "answer_id": 352138, "author": "mookid8000", "author_id": 6560, "author_profile": "https://Stackoverflow.com/users/6560", "pm_score": 2, "selected": false, "text": "// system.web / compilation / assemblies\n<add assembly=\"Microsoft.Web.Mvc\"/>\n" }, { "answer_id": 352142, "author": "JSC", "author_id": 37311, "author_profile": "https://Stackoverflow.com/users/37311", "pm_score": 6, "selected": true, "text": "<%@ import namespace='your namespace' %>\n <system.web>\n <pages>\n <namespaces>\n <add namespace='you namespace' />\n </namespaces>\n </pages>\n</system.web>\n" }, { "answer_id": 352169, "author": "Samiksha", "author_id": 29515, "author_profile": "https://Stackoverflow.com/users/29515", "pm_score": 0, "selected": false, "text": "public class Utility\n\n{ \n public static void func1()\n {} \n}\n" }, { "answer_id": 8214437, "author": "undeniablyrob", "author_id": 943002, "author_profile": "https://Stackoverflow.com/users/943002", "pm_score": 3, "selected": false, "text": "<%@ Import Namespace=\"My.Namespace.Path\" %>\n\n<html goes here>\n ...\n</html>\n @using My.Namespace.Path\n\n@{\n ViewBag.Title = \"My Page\";\n ...\n}\n\n<html goes here>\n ...\n</html goes here>\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44533/" ]
352,152
<p>I was wondering if there is an iterator in the STL that dereferences the object pointed before returning it. This could be very useful when manipulating containers aggregating pointers. Here's an example of what I would like to be able to do:</p> <pre><code>#include &lt;vector&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; using namespace std; int main() { vector&lt;int*&gt; vec; int i = 1; int j = 2; int k = 3; vec.push_back(&amp;i); vec.push_back(&amp;j); vec.push_back(&amp;k); copy(deref_iterator(vec.begin()), deref_iterator(vec.end()), ostream_iterator&lt;int&gt;(cout, " ")); // prints "1 2 3" return 0; } </code></pre>
[ { "answer_id": 352162, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 2, "selected": false, "text": "#include <iterator>\n\ntemplate <typename T>\nstruct PointedType;\n\ntemplate <typename T>\nstruct PointedType<T*>\n{\n typedef T value_type;\n};\n\ntemplate <typename InputIterator>\nstruct DerefIterator\n{\n typedef input_iterator_tag iterator_category;\n typedef typename PointedType<\n typename iterator_traits<InputIterator>::value_type>::value_type\n value_type;\n typedef typename iterator_traits<InputIterator>::difference_type\n difference_type;\n typedef value_type* pointer;\n typedef value_type& reference;\n\n public:\n explicit DerefIterator(const InputIterator& ii)\n : it(ii) {}\n\n // Returns the object pointed by the object referenced by it\n reference operator*() const { return **it; }\n pointer operator->() const { return *it; }\n\n DerefIterator& operator++()\n {\n ++it;\n return *this;\n }\n\n DerefIterator operator++(int)\n {\n DerefIterator tmp = *this;\n ++it;\n return tmp;\n }\n\n bool equals(const DerefIterator<InputIterator> & di) const\n {\n return di.it == it;\n }\n\n private:\n InputIterator it;\n};\n\n// Equality functions\n\ntemplate <typename InputIterator>\ninline bool operator==(const DerefIterator<InputIterator>& di1, \n const DerefIterator<InputIterator>& di2)\n{\n return di1.equals(di2);\n}\n\ntemplate <typename InputIterator>\ninline bool operator!=(const DerefIterator<InputIterator>& di1, \n const DerefIterator<InputIterator>& di2)\n{\n return ! (di1 == di2);\n}\n\n//Helper function\n\ntemplate <typename InputIterator>\nDerefIterator<InputIterator> deref_iterator(const InputIterator& ii)\n{\n return DerefIterator<InputIterator>(ii);\n}\n" }, { "answer_id": 352235, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 5, "selected": true, "text": "indirect_iterator indirect_iterator indirect_iterator<int**>" }, { "answer_id": 352762, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "#include <boost/ptr_container/ptr_vector.hpp>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n boost::ptr_vector<int> vec;\n\n vec.push_back(new int(1));\n vec.push_back(new int(2));\n vec.push_back(new int(3));\n\n copy(vec.begin(),vec.end(),\n ostream_iterator<int>(std::cout, \" \")); // prints \"1 2 3 \"\n\n return 0;\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20984/" ]
352,174
<pre><code> [SoapRpcMethod(Action = "http://cyberindigo/TempWebService/InsertXML", RequestNamespace = "http://cyberindigo/TempWebService/Request", RequestElementName = "InsertXMLRequest", ResponseNamespace = "http://cyberindigo/TempWebService/Response", ResponseElementName = "InsertXMLResponse", Use = System.Web.Services.Description.SoapBindingUse.Literal)] [WebMethod] public string InsertXML(string Jobs) { return "Hi"; } </code></pre> <p>The Problem when I am accessing it using XMLHttpRequest it gives following error Server did not recognize the value of HTTP Header SOAPAction: <a href="http://Cyberindigo/TempWebService/InsertXML" rel="noreferrer">http://Cyberindigo/TempWebService/InsertXML</a></p>
[ { "answer_id": 2109100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "SOAPAction http://yournamespace.com/blah http://foo.com/servicename http://bar.com/servicename http://foo.com/servicename" }, { "answer_id": 5745476, "author": "Ben", "author_id": 719114, "author_profile": "https://Stackoverflow.com/users/719114", "pm_score": 3, "selected": false, "text": "[WebMethod(MessageName = \"foo\")]\npublic string bar()\n{\n\n}\n [WebMethod(MessageName = \"foo\")]\npublic string foo()\n{\n\n}\n" }, { "answer_id": 9237445, "author": "Shivanand Mitkari", "author_id": 1203293, "author_profile": "https://Stackoverflow.com/users/1203293", "pm_score": 3, "selected": false, "text": "[WebService(Namespace = \"http://MyDomain.com/TestService\")] \npublic class FooClass : System.Web.Services.WebService \n{\n [WebMethod] \n public bool Foo( string name) \n {\n\n ...... \n }\n\n }\n <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <Foo xmlns=\"http://MyDomain.com/TestService\">\n <name>string</name> \n </Foo>\n </soap:Body> \n</soap:Envelope>\n" }, { "answer_id": 14084341, "author": "the_marcelo_r", "author_id": 1677299, "author_profile": "https://Stackoverflow.com/users/1677299", "pm_score": 3, "selected": false, "text": "Caused by: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: .\n <wsdl:operation soapAction <wsdl:binding name=\"CCCheckerSoap\" type=\"tns:CCCheckerSoap\">\n <soap:binding transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name=\"ValidateCardNumber\">\n <soap:operation soapAction=\"http://www.webservicex.net/ValidateCardNumber\" style=\"document\"/>\n <wsdl:input>\n <soap:body use=\"literal\"/>\n</wsdl:input>\n...\n soapAction <binding name=\"casaBinding1\" type=\"ns:CCCheckerSoap\">\n <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <operation name=\"ValidateCardNumber\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <input>\n <soap:body use=\"literal\"/>\n </input>\n <soap:operation soapAction=\"http://www.webservicex.net/ValidateCardNumber\" style=\"document\"/>\n" }, { "answer_id": 28595873, "author": "Graeme Black", "author_id": 4581755, "author_profile": "https://Stackoverflow.com/users/4581755", "pm_score": 0, "selected": false, "text": "System.Web.Services.Protocols.SoapException: SOAPAction" }, { "answer_id": 36967420, "author": "Zolfaghari", "author_id": 2155778, "author_profile": "https://Stackoverflow.com/users/2155778", "pm_score": 2, "selected": false, "text": "1) [WebService(Namespace = \"http://tempuri.org/\")]\n 2) [WebService(Namespace = \"http://newvalue.com/\")]\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42070/" ]
352,176
<p>The following SQL separates tables according to their relationship. The problem is with the tables that sort under the 3000 series. Tables that are part of foreign keys and that use foreign keys. Anyone got some clever recursive CTE preferably or a stored procedure to do the necessary sorting?? Programs connectiong to the database are not considered a solution. </p> <p>Edit: I posted the answer in the "answers" based on the first solution Free "right answer" to be had for anyone reposting my own "right" answer!</p> <pre><code>WITH AllTables(TableName) AS ( SELECT OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) FROM dbo.sysobjects so INNER JOIN sys.all_columns ac ON so.ID = ac.object_id WHERE so.type = 'U' AND ac.is_rowguidcol = 1 ), Relationships(ReferenceTableName, ReferenceColumnName, TableName, ColumnName) AS ( SELECT OBJECT_SCHEMA_NAME (fkey.referenced_object_id) + '.' + OBJECT_NAME (fkey.referenced_object_id) AS ReferenceTableName ,COL_NAME(fcol.referenced_object_id, fcol.referenced_column_id) AS ReferenceColumnName ,OBJECT_SCHEMA_NAME (fkey.parent_object_id) + '.' + OBJECT_NAME(fkey.parent_object_id) AS TableName ,COL_NAME(fcol.parent_object_id, fcol.parent_column_id) AS ColumnName FROM sys.foreign_keys AS fkey INNER JOIN sys.foreign_key_columns AS fcol ON fkey.OBJECT_ID = fcol.constraint_object_id ), NotReferencedOrReferencing(TableName) AS ( SELECT TableName FROM AllTables EXCEPT SELECT TableName FROM Relationships EXCEPT SELECT ReferenceTableName FROM Relationships ), OnlyReferenced(Tablename) AS ( SELECT ReferenceTableName FROM Relationships EXCEPT SELECT TableName FROM Relationships ), -- These need to be sorted based on theire internal relationships ReferencedAndReferencing(TableName, ReferenceTableName) AS ( SELECT r1.Tablename, r2.ReferenceTableName FROM Relationships r1 INNER JOIN Relationships r2 ON r1.TableName = r2.ReferenceTableName ), OnlyReferencing(TableName) AS ( SELECT Tablename FROM Relationships EXCEPT SELECT ReferenceTablename FROM Relationships ) SELECT TableName, 1000 AS Sorting FROM NotReferencedOrReferencing UNION SELECT TableName, 2000 AS Sorting FROM OnlyReferenced UNION SELECT TableName, 3000 AS Sorting FROM ReferencedAndReferencing UNION SELECT TableName, 4000 AS Sorting FROM OnlyReferencing ORDER BY Sorting </code></pre>
[ { "answer_id": 352294, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "declare @level int -- Current depth\n ,@count int \n\n-- Step 1: Start with tables that have no FK dependencies\n-- \nif object_id ('tempdb..#Tables') is not null\n drop table #Tables\n\nselect s.name + '.' + t.name as TableName\n ,t.object_id as TableID\n ,0 as Ordinal\n into #Tables\n from sys.tables t\n join sys.schemas s\n on t.schema_id = s.schema_id\n where not exists\n (select 1\n from sys.foreign_keys f\n where f.parent_object_id = t.object_id)\n\nset @count = @@rowcount \nset @level = 0\n\n\n-- Step 2: For a given depth this finds tables joined to \n-- tables at this given depth. A table can live at multiple \n-- depths if it has more than one join path into it, so we \n-- filter these out in step 3 at the end.\n--\nwhile @count > 0 begin\n\n insert #Tables (\n TableName\n ,TableID\n ,Ordinal\n ) \n select s.name + '.' + t.name as TableName\n ,t.object_id as TableID\n ,@level + 1 as Ordinal\n from sys.tables t\n join sys.schemas s\n on s.schema_id = t.schema_id\n where exists\n (select 1\n from sys.foreign_keys f\n join #Tables tt\n on f.referenced_object_id = tt.TableID\n and tt.Ordinal = @level\n and f.parent_object_id = t.object_id\n and f.parent_object_id != f.referenced_object_id)\n -- The last line ignores self-joins. You'll\n -- need to deal with these separately\n\n set @count = @@rowcount\n set @level = @level + 1\nend\n\n-- Step 3: This filters out the maximum depth an object occurs at\n-- and displays the deepest first.\n--\nselect t.Ordinal\n ,t.TableID\n ,t.TableName\n from #Tables t\n join (select TableName as TableName\n ,Max (Ordinal) as Ordinal\n from #Tables\n group by TableName) tt\n on t.TableName = tt.TableName\n and t.Ordinal = tt.Ordinal\n order by t.Ordinal desc\n" }, { "answer_id": 358841, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 4, "selected": true, "text": "WITH \n TablesCTE(TableName, TableID, Ordinal) AS\n (\n SELECT \n OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) AS TableName,\n so.id AS TableID,\n 0 AS Ordinal\n FROM dbo.sysobjects so INNER JOIN sys.all_columns ac ON so.ID = ac.object_id\n WHERE\n so.type = 'U'\n AND\n ac.is_rowguidcol = 1\n UNION ALL\n SELECT \n OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) AS TableName,\n so.id AS TableID,\n tt.Ordinal + 1 AS Ordinal\n FROM \n dbo.sysobjects so \n INNER JOIN sys.all_columns ac ON so.ID = ac.object_id\n INNER JOIN sys.foreign_keys f \n ON (f.parent_object_id = so.id AND f.parent_object_id != f.referenced_object_id)\n INNER JOIN TablesCTE tt ON f.referenced_object_id = tt.TableID\n WHERE\n so.type = 'U'\n AND\n ac.is_rowguidcol = 1\n) \nSELECT DISTINCT \n t.Ordinal,\n t.TableName\n FROM TablesCTE t\n INNER JOIN \n (\n SELECT \n TableName as TableName,\n Max (Ordinal) as Ordinal\n FROM TablesCTE\n GROUP BY TableName\n ) tt ON (t.TableName = tt.TableName AND t.Ordinal = tt.Ordinal)\nORDER BY t.Ordinal, t.TableName\n" }, { "answer_id": 2118587, "author": "Andrew Ryan", "author_id": 256875, "author_profile": "https://Stackoverflow.com/users/256875", "pm_score": 0, "selected": false, "text": "INNER JOIN sys.foreign_keys f \n ON (f.parent_object_id = so.id AND f.parent_object_id != f.referenced_object_id)\n\n /* Manually exclude self-referencing tables - they cause recursion problems*/ \n and f.object_id not in /*Below are IDs of foreign keys*/\n ( 1847729685, \n 1863729742, \n 1879729799 \n ) \nINNER JOIN TablesCTE tt\n" }, { "answer_id": 4388547, "author": "NTDLS", "author_id": 61934, "author_profile": "https://Stackoverflow.com/users/61934", "pm_score": 4, "selected": false, "text": "WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS\n(\n SELECT\n OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n 0 AS Ordinal\n FROM\n sys.objects AS so\n WHERE\n so.type = 'U'\n AND so.is_ms_Shipped = 0\n UNION ALL\n SELECT\n OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n tt.Ordinal + 1 AS Ordinal\n FROM\n sys.objects AS so\n INNER JOIN sys.foreign_keys AS f\n ON f.parent_object_id = so.object_id\n AND f.parent_object_id != f.referenced_object_id\n INNER JOIN TablesCTE AS tt\n ON f.referenced_object_id = tt.TableID\n WHERE\n so.type = 'U'\n AND so.is_ms_Shipped = 0\n)\n\nSELECT DISTINCT\n t.Ordinal,\n t.SchemaName,\n t.TableName,\n t.TableID\n FROM\n TablesCTE AS t\n INNER JOIN\n (\n SELECT\n itt.SchemaName as SchemaName,\n itt.TableName as TableName,\n itt.TableID as TableID,\n Max(itt.Ordinal) as Ordinal\n FROM\n TablesCTE AS itt\n GROUP BY\n itt.SchemaName,\n itt.TableName,\n itt.TableID\n ) AS tt\n ON t.TableID = tt.TableID\n AND t.Ordinal = tt.Ordinal\nORDER BY\n t.Ordinal,\n t.TableName\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13219/" ]
352,177
<p>Fun with enums in C#. Take one generic list that is created to store some Enum that you had defined previously and add few items in it. Iterate with foreach or <code>GetEnumerator&lt;T&gt;()</code> but specify some other enum then the original and see what happens. I was expecting InvalidCastException or something like that but it perfectly works :). </p> <p> For the illustration let's take a simple console application and create two enums there: Cars and Animals: </p> <pre><code> public enum Cars { Honda = 0, Toyota = 1, Chevrolet = 2 } public enum Animals { Dog = 0, Cat = 1, Tiger = 2 } </code></pre> <p>And do this in main method:</p> <pre><code> public static void Main() { List&lt;Cars&gt; cars = new List&lt;Cars&gt;(); List&lt;Animals&gt; animals = new List&lt;Animals&gt;(); cars.Add(Cars.Chevrolet); cars.Add(Cars.Honda); cars.Add(Cars.Toyota); foreach (Animals isItACar in cars) { Console.WriteLine(isItACar.ToString()); } Console.ReadLine(); } </code></pre> <p>It will print this in console:</p> <blockquote> <pre><code>Tiger Dog Cat </code></pre> </blockquote> <p>Why is this happening? My first guess was that enum is not actually a Type by himself it's just and int but that's not true: If we write:</p> <p><code>Console.WriteLine(Animals.Tiger.GetType().FullName);</code> We will get his fully qualified name printed! So why this?</p>
[ { "answer_id": 352196, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "ToString() GetType() int bool int" }, { "answer_id": 352210, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "public static void Main()\n{\n List<Cars> cars = new List<Cars>();\n List<Animals> animals = new List<Animals>();\n cars.Add(Cars.Chevrolet);\n cars.Add(Cars.Honda);\n cars.Add(Cars.Toyota);\n\n foreach (Cars value in cars)\n {\n // This time the cast is explicit.\n Animals isItACar = (Animals) value;\n Console.WriteLine(isItACar.ToString());\n }\n Console.ReadLine();\n}\n foreach foreach (V v in x) embedded-statement \n {\n E e = ((C)(x)).GetEnumerator();\n try {\n V v;\n while (e.MoveNext()) {\n v = (V)(T)e.Current;\n embedded-statement\n }\n }\n finally {\n ... // Dispose e\n }\n}\n" }, { "answer_id": 353390, "author": "Steven Behnke", "author_id": 42588, "author_profile": "https://Stackoverflow.com/users/42588", "pm_score": 0, "selected": false, "text": "public enum Cats : byte { ... }\npublic enum Dogs : int { ... }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29511/" ]
352,178
<p>I have a <code>MultipleChoiceField</code> on a form holding car makes. I want to filter my database of cars to the makes that were checked but this causes a problem. How do I get all the <code>Q(make=...)</code> statements in dynamically?</p> <p>How I start: <code>['value1', 'value2', ...]</code></p> <p>How I want to end: <code>Q(col='value1') | Q(col='value2') | ...</code></p> <p>I've couple of other methods. I've tried appending querysets for each make and doing it the other way around (doing multiple excludes) but they were both really slow.</p>
[ { "answer_id": 352208, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 4, "selected": true, "text": "Model.objects.filter(make__in=list_of_makes) MultipleChoiceField __in" }, { "answer_id": 352262, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "reduce(lambda x,y: x | y, [Q1, Q2, Q3, ...])\n" }, { "answer_id": 4189833, "author": "ulysses", "author_id": 270394, "author_profile": "https://Stackoverflow.com/users/270394", "pm_score": 2, "selected": false, "text": "# These are the fields I want to search with an OR clause\nsearch_fields = ['title__icontains', 'publisher__name__icontains', 'authors__name__icontains']\n\nsearch = 'search string'\nclauses = []\nfor item in search_fields:\n clauses.append(queryset.filter(**{item: search}))\n queryset = reduce(lambda x, y: x | y, clauses).distinct()\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
352,203
<p>I'm looking for an algorithm to generate permutations of a set in such a way that I could make a lazy list of them in Clojure. i.e. I'd like to iterate over a list of permutations where each permutation is not calculated until I request it, and all of the permutations don't have to be stored in memory at once.</p> <p>Alternatively I'm looking for an algorithm where given a certain set, it will return the "next" permutation of that set, in such a way that repeatedly calling the function on its own output will cycle through all permutations of the original set, in some order (what the order is doesn't matter).</p> <p>Is there such an algorithm? Most of the permutation-generating algorithms I've seen tend to generate them all at once (usually recursively), which doesn't scale to very large sets. An implementation in Clojure (or another functional language) would be helpful but I can figure it out from pseudocode.</p>
[ { "answer_id": 352226, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 2, "selected": false, "text": "C# iterator yield index" }, { "answer_id": 353248, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 8, "selected": true, "text": "next_permutation /usr/include/c++/4.0.0/bits/stl_algo.h false template <class BidirectionalIterator>\nbool next_permutation(BidirectionalIterator first,\n BidirectionalIterator last) {\n if (first == last) return false;\n BidirectionalIterator i = first;\n ++i;\n if (i == last) return false;\n i = last;\n --i;\n for(;;) {\n BidirectionalIterator ii = i--;\n if (*i <*ii) {\n BidirectionalIterator j = last;\n while (!(*i <*--j));\n iter_swap(i, j);\n reverse(ii, last);\n return true;\n }\n if (i == first) {\n reverse(first, last);\n return false;\n }\n }\n}\n" }, { "answer_id": 362714, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 5, "selected": false, "text": "n n 1. scan the array from right-to-left (indices descending from N-1 to 0)\n1.1. if the current element is less than its right-hand neighbor,\n call the current element the pivot,\n and stop scanning\n1.2. if the left end is reached without finding a pivot,\n reverse the array and return\n (the permutation was the lexicographically last, so its time to start over)\n2. scan the array from right-to-left again,\n to find the rightmost element larger than the pivot\n (call that one the successor)\n3. swap the pivot and the successor\n4. reverse the portion of the array to the right of where the pivot was found\n5. return\n 1. scanning from the right finds A as the pivot in position 1\n2. scanning again finds B as the successor in position 3\n3. swapping pivot and successor gives CBDA\n4. reversing everything following position 1 (i.e. positions 2..3) gives CBAD\n5. CBAD is the next permutation after CADB\n n N! N N (N-1)! (N-1)! To find permutation x of array A, where A has N elements:\n0. if A has one element, return it\n1. set p to ( x / (N-1)! ) mod N\n2. the desired permutation will be A[p] followed by\n permutation ( x mod (N-1)! )\n of the elements remaining in A after position p is removed\n perm 13 of ABCD: {p = (13 / 3!) mod 4 = (13 / 6) mod 4 = 2; ABCD[2] = C}\nC followed by perm 1 of ABD {because 13 mod 3! = 13 mod 6 = 1}\n perm 1 of ABD: {p = (1 / 2!) mod 3 = (1 / 2) mod 2 = 0; ABD[0] = A}\n A followed by perm 1 of BD {because 1 mod 2! = 1 mod 2 = 1}\n perm 1 of BD: {p = (1 / 1!) mod 2 = (1 / 1) mod 2 = 1; BD[1] = D}\n D followed by perm 0 of B {because 1 mod 1! = 1 mod 1 = 0}\n B (because there's only one element)\n DB\n ADB\nCADB\n" }, { "answer_id": 440134, "author": "Carlos Eduardo Olivieri", "author_id": 449425, "author_profile": "https://Stackoverflow.com/users/449425", "pm_score": 2, "selected": false, "text": "\nPROGRAM TestFikePerm;\nCONST marksize = 5;\nVAR\n marks : ARRAY [1..marksize] OF INTEGER;\n ii : INTEGER;\n permcount : INTEGER;\n\nPROCEDURE WriteArray;\nVAR i : INTEGER;\nBEGIN\nFOR i := 1 TO marksize\nDO Write ;\nWriteLn;\npermcount := permcount + 1;\nEND;\n\nPROCEDURE FikePerm ;\n{Outputs permutations in nonlexicographic order. This is Fike.s algorithm}\n{ with tuning by J.S. Rohl. The array marks[1..marksizn] is global. The }\n{ procedure WriteArray is global and displays the results. This must be}\n{ evoked with FikePerm(2) in the calling procedure.}\nVAR\n dn, dk, temp : INTEGER;\nBEGIN\nIF \nTHEN BEGIN { swap the pair }\n WriteArray;\n temp :=marks[marksize];\n FOR dn := DOWNTO 1\n DO BEGIN\n marks[marksize] := marks[dn];\n marks [dn] := temp;\n WriteArray;\n marks[dn] := marks[marksize]\n END;\n marks[marksize] := temp;\n END {of bottom level sequence }\nELSE BEGIN\n FikePerm;\n temp := marks[k];\n FOR dk := DOWNTO 1\n DO BEGIN\n marks[k] := marks[dk];\n marks[dk][ := temp;\n FikePerm;\n marks[dk] := marks[k];\n END; { of loop on dk }\n marks[k] := temp;l\n END { of sequence for other levels }\nEND; { of FikePerm procedure }\n\nBEGIN { Main }\nFOR ii := 1 TO marksize\nDO marks[ii] := ii;\npermcount := 0;\nWriteLn ;\nWrieLn;\nFikePerm ; { It always starts with 2 }\nWriteLn ;\nReadLn;\nEND.\n\n \nPROGRAM TestLexPerms;\nCONST marksize = 5;\nVAR\n marks : ARRAY [1..marksize] OF INTEGER;\n ii : INTEGER;\n permcount : INTEGER;\n\nPROCEDURE WriteArray;\nVAR i : INTEGER;\nBEGIN\nFOR i := 1 TO marksize\nDO Write ;\npermcount := permcount + 1;\nWriteLn;\nEND;\n\nPROCEDURE LexPerm ;\n{ Outputs permutations in lexicographic order. The array marks is global }\n{ and has n or fewer marks. The procedure WriteArray () is global and }\n{ displays the results. }\nVAR \n work : INTEGER:\n mp, hlen, i : INTEGER;\nBEGIN\nIF \nTHEN BEGIN { Swap the pair }\n work := marks[1];\n marks[1] := marks[2];\n marks[2] := work;\n WriteArray ;\n END\nELSE BEGIN\n FOR mp := DOWNTO 1\n DO BEGIN\n LexPerm<>;\n hlen := DIV 2;\n FOR i := 1 TO hlen\n DO BEGIN { Another swap }\n work := marks[i];\n marks[i] := marks[n - i];\n marks[n - i] := work\n END;\n work := marks[n]; { More swapping }\n marks[n[ := marks[mp];\n marks[mp] := work;\n WriteArray;\n END;\n LexPerm<>\n END;\nEND;\n\nBEGIN { Main }\nFOR ii := 1 TO marksize\nDO marks[ii] := ii;\npermcount := 1; { The starting position is permutation }\nWriteLn < Starting position: >;\nWriteLn\nLexPerm ;\nWriteLn < PermCount is , permcount>;\nReadLn;\nEND.\n \nPROGRAM TestAllPerms;\nCONST marksize = 5;\nVAR\n marks : ARRAY [1..marksize] of INTEGER;\n ii : INTEGER;\n permcount : INTEGER;\n\nPROCEDURE WriteArray;\nVAR i : INTEGER;\nBEGIN\nFOR i := 1 TO marksize\nDO Write ;\nWriteLn;\npermcount := permcount + 1;\nEND;\n\nPROCEDURE AllPerm (n : INTEGER);\n{ Outputs permutations in nonlexicographic order. The array marks is }\n{ global and has n or few marks. The procedure WriteArray is global and }\n{ displays the results. }\nVAR\n work : INTEGER;\n mp, swaptemp : INTEGER;\nBEGIN\nIF \nTHEN BEGIN { Swap the pair }\n work := marks[1];\n marks[1] := marks[2];\n marks[2] := work;\n WriteArray;\n END\nELSE BEGIN\n FOR mp := DOWNTO 1\n DO BEGIN\n ALLPerm<< n - 1>>;\n IF > \n THEN swaptemp := 1\n ELSE swaptemp := mp;\n work := marks[n];\n marks[n] := marks[swaptemp};\n marks[swaptemp} := work;\n WriteArray;\n AllPerm< n-1 >;\n END;\nEND;\n\nBEGIN { Main }\nFOR ii := 1 TO marksize\nDO marks[ii] := ii\npermcount :=1;\nWriteLn < Starting position; >;\nWriteLn;\nAllperm < marksize>;\nWriteLn < Perm count is , permcount>;\nReadLn;\nEND.\n" }, { "answer_id": 73608757, "author": "triclosan", "author_id": 532208, "author_profile": "https://Stackoverflow.com/users/532208", "pm_score": 0, "selected": false, "text": "next_permutation (println (lazy-seq (iterator-seq (NextPermutationIterator. (list 'a 'b 'c)))))\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23070/" ]
352,236
<p>Is there a way for a Windows application to access another applications data, more specifically a text input field in the GUI, and grab the text there for processing in our own application?</p> <p>If it is possible, is there a way to &quot;shield&quot; your application to prevent it?</p> <hr /> <p><strong>EDIT:</strong> The three first answers seem to be about getting the another applications window title, not a specific text input field in that window.</p> <p>I'm no Windows API expert, so could you be more exact how do I find a certain text field in that window, what are the prerequisites for it (seems like knowing a window handle something is required, does it require knowing the text field handle as well? How do I get that? etc...)</p> <p>Code snippets in C++ really would be really appreciated. MSDN help is hard to browse since Win32-API has such horrible naming conventions.</p> <hr /> <p><strong>Completed!</strong> See my answer below for a how-to in C++.</p>
[ { "answer_id": 352246, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 0, "selected": false, "text": "Private Declare Function GetWindowText Lib \"user32\" Alias \"GetWindowTextA\" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long \nPrivate Declare Function GetWindowTextLength Lib \"user32\" Alias \"GetWindowTextLengthA\" (ByVal hwnd As Long) As Long \n Dim MyStr As String\nMyStr = String(GetWindowTextLength(TextBoxHandle) + 1, Chr$(0))\nGetWindowText TextBoxHandle, MyStr, Len(MyStr)\nMsgBox MyStr\n" }, { "answer_id": 360247, "author": "Raj", "author_id": 8080, "author_profile": "https://Stackoverflow.com/users/8080", "pm_score": 5, "selected": true, "text": "HWND hwnd = (HWND)0x00310E3A;\nchar szBuf[2048];\nLONG lResult;\n\nlResult = SendMessage( hwnd, WM_GETTEXT, sizeof( szBuf ) / sizeof( szBuf[0] ), (LPARAM)szBuf );\nprintf( \"Copied %d characters. Contents: %s\\n\", lResult, szBuf );\n" }, { "answer_id": 362107, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 3, "selected": false, "text": "...\nEnumWindows((WNDENUMPROC)on_enumwindow_cb, 0);\n...\n BOOL CALLBACK on_enumwindow_cb(HWND hwndWindow, LPARAM lParam) {\n TCHAR wsTitle[2048];\n LRESULT result;\nresult = SendMessage(hwndWindow, WM_GETTEXT, (WPARAM) 2048, (LPARAM) wsTitle);\n ...\n hwndEdit = FindWindowEx(hwndWindow, NULL, L\"RichEdit20W\", NULL);\n result = SendMessage(hwndEdit, WM_GETTEXT, (WPARAM) 4096, (LPARAM) wsText);\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40657/" ]
352,259
<p>I want to use the standard ADO connection string dialog box in MS Access. How can I do that?</p>
[ { "answer_id": 352751, "author": "John Mo", "author_id": 38988, "author_profile": "https://Stackoverflow.com/users/38988", "pm_score": 1, "selected": false, "text": "Dim dl As MSDASC.DataLinks\nDim cn As ADODB.Connection\n\nSet dl = New MSDASC.DataLinks\nSet cn = New ADODB.Connection\n\nSet cn = dl.PromptNew\ncn.Open\n" }, { "answer_id": 354364, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 1, "selected": false, "text": "m_connectionString Function connectToDababase(Optional m_connectionString As String) As String\nDim dl As MSDASC.DataLinks\nDim cn As ADODB.Connection\n\nSet dl = New MSDASC.DataLinks\nSet cn = New ADODB.Connection\n\nIf IsMissing(m_connectionString) Then\n Set cn = dl.PromptNew\nElse\n cn.ConnectionString = m_connectionString\n dl.PromptEdit cn\nEnd If\n\nconnectToDababase = cn.ConnectionString\nEnd Function\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,311
<p>I'm using this database where the date colomn is a numeric value instead of a Date value. </p> <p>Yes, I know I can change that with a mouseclick, but all the applications using that database were made by one of my predecessors (and everyone after him just ignored it and built on). So if I'd change it to Date a lot af applications would fail. :(</p> <p>Well, I am making an overview of that database, ranging from one specfic date to another. I tried using a dropdown list but as you can tell, a thousand options in one list is terribly inconvenient, even ugly. </p> <p>I rather have small inputfields for day - month - year, but there comes waltzing in the numeric date in the database. I would have to calculate the date back to the numeric value somehow... </p> <p>There must be an easy solution to this. Right?<br /><br /><br /><br /> I'm using ASP(vbscript) for the application, it's for an intraweb, and I have an Access Database.</p>
[ { "answer_id": 352436, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": true, "text": "Dim rs As DAO.Recordset\n\nSet rs = CurrentDb.OpenRecordset(\"TestTable\")\nrs.AddNew\nrs!NumberDate = Now() 'Value stored, eg, 39791.4749074074 '\nrs.Update\n\nrs.MoveLast\n\n'To show that it converts back to the correct date / time '\nDebug.Print Format(rs!NumberDate, \"dd/mm/yyyy hh:nn:ss\")\n Set cn = CreateObject(\"ADODB.Connection\")\nSet rs = CreateObject(\"ADODB.Recordset\")\n\nstrFile = \"C:\\Docs\\LTD.mdb\"\n\ncn.Open \"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n \"Data Source=\" & strFile & \";\" & _\n \"Persist Security Info=False\"\n\nstrSQL = \"SELECT NumberDate FROM TestTable WHERE NumberDate= #2008/12/7#\"\n\nrs.Open strSQL, cn, 3, 3\nrs.MoveLast\n\nMsgBox rs.RecordCount\n" }, { "answer_id": 352593, "author": "Kablam", "author_id": 42389, "author_profile": "https://Stackoverflow.com/users/42389", "pm_score": 1, "selected": false, "text": "Function DateToNumeric(dayDate)\n DateToNumeric=DateDiff(\"d\",\"31/12/1899\",dayDate) +1 //yup\nEnd Function\n \n response.Write(\"9/12/2008, should be 39791.<br /><br />\")\n response.write(\"DateToNumeric('9/12/2008') gives: \" &DateToNumeric(\"9/12/2008\")& \"<br />\")\n response.write(\"CDate('39791') gives: \" &CDate(39791)&\"<br /><br />\")\n response.write(\"BECAUSE CDate('1') gives: \" &CDate(1))\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42389/" ]
352,321
<p>I am testing the application in the debug mode under several conditions. Now I'm doing it by writing some of the states and executed functions on the piece of paper and then comparing the scenarios.</p> <p>Does anyone know if there is any built-in functionality in VS2008 or any additional tool that could record the selected states and executed functions?</p> <p>Thanks!</p>
[ { "answer_id": 352436, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": true, "text": "Dim rs As DAO.Recordset\n\nSet rs = CurrentDb.OpenRecordset(\"TestTable\")\nrs.AddNew\nrs!NumberDate = Now() 'Value stored, eg, 39791.4749074074 '\nrs.Update\n\nrs.MoveLast\n\n'To show that it converts back to the correct date / time '\nDebug.Print Format(rs!NumberDate, \"dd/mm/yyyy hh:nn:ss\")\n Set cn = CreateObject(\"ADODB.Connection\")\nSet rs = CreateObject(\"ADODB.Recordset\")\n\nstrFile = \"C:\\Docs\\LTD.mdb\"\n\ncn.Open \"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n \"Data Source=\" & strFile & \";\" & _\n \"Persist Security Info=False\"\n\nstrSQL = \"SELECT NumberDate FROM TestTable WHERE NumberDate= #2008/12/7#\"\n\nrs.Open strSQL, cn, 3, 3\nrs.MoveLast\n\nMsgBox rs.RecordCount\n" }, { "answer_id": 352593, "author": "Kablam", "author_id": 42389, "author_profile": "https://Stackoverflow.com/users/42389", "pm_score": 1, "selected": false, "text": "Function DateToNumeric(dayDate)\n DateToNumeric=DateDiff(\"d\",\"31/12/1899\",dayDate) +1 //yup\nEnd Function\n \n response.Write(\"9/12/2008, should be 39791.<br /><br />\")\n response.write(\"DateToNumeric('9/12/2008') gives: \" &DateToNumeric(\"9/12/2008\")& \"<br />\")\n response.write(\"CDate('39791') gives: \" &CDate(39791)&\"<br /><br />\")\n response.write(\"BECAUSE CDate('1') gives: \" &CDate(1))\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
352,334
<p>I'm using GDOME.pm and in my script I have this line:</p> <pre><code>my $doc = XML::GDOME-&gt;createDocument("","",""); </code></pre> <p>I can't for the life of me figure out why it's coming out with this error:</p> <pre><code>NAMESPACE_ERR at /usr/lib/perl5/site_perl/5.6.1/i586-linux/XML/GDOME.pm line 103. </code></pre> <p>which basically points to:</p> <pre><code>sub createDocument { my $class = shift; return $di-&gt;createDocument(@_); ## it points to this LINE!! } </code></pre> <p>Is there a tool or something that would provide me more look into which namespaces is actually causing this error?</p> <p>In the meantime, my solution goes along the lines of my forehead meeting the keyboard, but that doesn't seem to be working except for causing some headache, and random shapes appearing on my forehead.</p> <p>thanks ~steve</p>
[ { "answer_id": 352567, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": true, "text": "$doc = XML::GDOME->createDocument( $nsURI, $name, $dtd );\n \"\" undef my $doc = XML::GDOME->createDocument(undef,\"\",\"\");\n" }, { "answer_id": 352571, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": " perl -we'use XML::GDOME; XML::GDOME->createDocument(\"\",\"\",\"\")'\n" }, { "answer_id": 354873, "author": "melaos", "author_id": 38124, "author_profile": "https://Stackoverflow.com/users/38124", "pm_score": 0, "selected": false, "text": "my $doc = XML::GDOME->createDocument(undef,\"\",\"\");\n ** CRITICAL **: file gdome-xml-element.c: line 235 (gdome_xml_el_setAttribute): assertion `value != NULL' failed.\n\n** CRITICAL **: file gdome-xml-element.c: line 235 (gdome_xml_el_setAttribute): assertion `value != NULL' failed.\n\n** CRITICAL **: file gdome-xml-element.c: line 235 (gdome_xml_el_setAttribute): assertion `value != NULL' failed.\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38124/" ]
352,335
<p>I am using an open source client to programmatically process incoming emails (on Windows 2003). The only way to prevent receiving previously read emails is to delete them from the server. This is less than ideal. As far as I know, there is no command in Pop3 to set emails as being read. So how do you go about this? </p>
[ { "answer_id": 352347, "author": "xahtep", "author_id": 42184, "author_profile": "https://Stackoverflow.com/users/42184", "pm_score": 5, "selected": true, "text": "UIDL" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
352,340
<p>Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV</p>
[ { "answer_id": 352497, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": true, "text": "from cherrypy.lib.static import serve_file\n import glob\nimport os.path\n\nimport cherrypy\nfrom cherrypy.lib.static import serve_file\n\n\nclass Root:\n def index(self, directory=\".\"):\n html = \"\"\"<html><body><h2>Here are the files in the selected directory:</h2>\n <a href=\"index?directory=%s\">Up</a><br />\n \"\"\" % os.path.dirname(os.path.abspath(directory))\n\n for filename in glob.glob(directory + '/*'):\n absPath = os.path.abspath(filename)\n if os.path.isdir(absPath):\n html += '<a href=\"/index?directory=' + absPath + '\">' + os.path.basename(filename) + \"</a> <br />\"\n else:\n html += '<a href=\"/download/?filepath=' + absPath + '\">' + os.path.basename(filename) + \"</a> <br />\"\n\n html += \"\"\"</body></html>\"\"\"\n return html\n index.exposed = True\n\nclass Download:\n def index(self, filepath):\n return serve_file(filepath, \"application/x-download\", \"attachment\")\n index.exposed = True\n\nif __name__ == '__main__':\n root = Root()\n root.download = Download()\n cherrypy.quickstart(root)\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
352,341
<p>I often find myself using Integers to represent values in different "spaces". For example...</p> <pre><code>int arrayIndex; int usersAge; int daysToChristmas; </code></pre> <p>Ideally, I'd like to have separate classes for each of these types "Index","Years" and "Days", which should prevent me accidentally mixing them up. Typedefs are a help from a documnentation perspective, but aren't type-safe enough.</p> <p>I've tried wrapper classes, but end up with too much boilerplate for my liking. Is there a straightforward template-based solution, or maybe something ready-to-go in Boost?</p> <p>EDIT: Several people have talked about bounds-checking in their answers. That maybe a handy side-effect, but is NOT a key requirement. In particular, I don't just want to prevent out-of-bound assignments, but assignments between "inappropriate" types.</p>
[ { "answer_id": 352363, "author": "Joris Timmermans", "author_id": 33987, "author_profile": "https://Stackoverflow.com/users/33987", "pm_score": 3, "selected": false, "text": "template<unsigned i>\nclass t_integer_wrapper\n {\n private:\n int m_value;\n public:\n // Constructors, accessors, operators, etc.\n };\n\ntypedef t_integer_wrapper<1> ArrayIndex;\ntypedef t_integer_wrapper<2> UsersAge;\n" }, { "answer_id": 352366, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "Int<0, 365> daysToChristmas;\nInt<0, 150> usersAge;\nInt<0, 6> dayOfWeek;\n class DayOfYear: public Int<0, 365> {}\n" }, { "answer_id": 352379, "author": "David Allan Finch", "author_id": 27417, "author_profile": "https://Stackoverflow.com/users/27417", "pm_score": 1, "selected": false, "text": "class DayType \n {\n public:\n static int const low = 1;\n static int const high = 365;\n };\n\ntemplate<class TYPE>\nclass Int\n {\n private:\n int m_value;\n public:\n operator int () { return m_value; }\n operator = ( int i ) { /* check and set*/ }\n };\n\n Int<DayType> day;\n int d = day;\n day = 23;\n" }, { "answer_id": 352411, "author": "AlfaZulu", "author_id": 44060, "author_profile": "https://Stackoverflow.com/users/44060", "pm_score": 0, "selected": false, "text": "int arrayIndex;\n std::size_t int usersAge;\n unsigned int int daysToChristmas;\n assert( 0 < daysToChristmas && daysToChristmas < 366 )\n assert" }, { "answer_id": 352412, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 2, "selected": false, "text": "template <typename ValueType, class Tag> class StrongType {\npublic:\n inline StrongType() : m_value(){}\n inline explicit StrongType(ValueType const &val) : m_value(val) {}\n inline operator ValueType () const {return m_value; }\n inline StrongType & operator=(StrongType const &newVal) {\n m_value = newVal.m_value;\n return *this;\n }\nprivate:\n //\n // data\n ValueType m_value;\n};\n class ArrayIndexTag;\ntypedef StringType<int, ArrayIndexTag> StrongArrayIndex;\nStringArrayIndex arrayIndex;\n" }, { "answer_id": 352466, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 0, "selected": false, "text": "enum YearDay {\n FirstJan = 0,\n LastDecInLeapYear = 365\n};\n" }, { "answer_id": 352583, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": true, "text": "boost/strong_typedef.hpp // macro used to implement a strong typedef. strong typedef\n// guarentees that two types are distinguised even though the\n// share the same underlying implementation. typedef does not create\n// a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new type named D\n// that operates as a type T.\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
352,343
<p>I'm developing a web app. In it I have a section called categories that every time a user clicks one of the categories an update panel loads the appropriate content. </p> <p>After the user clicked the category I want to change the browser's address bar url from</p> <pre><code>www.mysite.com/products </code></pre> <p>to something like </p> <pre><code>www.mysite.com/products/{selectedCat} </code></pre> <p>without refreshing the page.<br> Is there some kind of JavaScript API I can use to achieve this?</p>
[ { "answer_id": 352387, "author": "roborourke", "author_id": 42147, "author_profile": "https://Stackoverflow.com/users/42147", "pm_score": 5, "selected": false, "text": "window.location.hash = 'category-name'; // address bar would become http://example.com/#category-name\n" }, { "answer_id": 4059844, "author": "Alfred", "author_id": 291727, "author_profile": "https://Stackoverflow.com/users/291727", "pm_score": 7, "selected": false, "text": "window.history.pushState('Object', 'Title', '/new-url');\n window.history.replaceState('Object', 'Title', '/another-new-url');\n window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');\n\nwindow.onpopstate = function (e) {\n var id = e.state.id;\n load_item(id);\n};\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,348
<p>In answering this question (<a href="https://stackoverflow.com/questions/352317/c-coding-question#352327">https://stackoverflow.com/questions/352317/c-coding-question#352327</a>), it got me wondering...</p> <p>Is there any danger in regarding a static class as being equivalent to a non-static class instatiation that implements the singleton pattern?</p>
[ { "answer_id": 352391, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Comparer<T>.Default EqualityComparer<T>.Default" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14357/" ]
352,350
<p>This is a question for a WSS/SharePoint guru. </p> <p>Consider this scenario: I have an ASP.Net web service which links our corporate CRM system and WSS-based intranet together. What I am trying to do is provision a new WSS site collection whenever a new client is added to the CRM system. In order to make this work, I need to programmatically add the managed path to the new site collection. I know that this is possible via the Object Model, but when I try it in my own web service, it fails. Sample code extract below:</p> <pre><code> Dim _ClientSiteUrl As String = "http://myintranet/clients/sampleclient" Using _RootWeb As SPSite = New SPSite("http://myintranet") Dim _ManagedPaths As SPPrefixCollection = _RootWeb.WebApplication.Prefixes If Not (_ManagedPaths.Contains(_ClientSiteUrl)) Then _ManagedPaths.Add(_ClientSiteUrl, SPPrefixType.ExplicitInclusion) End If End Using </code> </pre> <p>This code fails with a NullReferenceException on SPUtility.ValidateFormDigest(). Research suggested that this may be due to insufficient privileges, I tried running the code within an elevated privileges block using SPSecurity.RunWithElevatedPrivileges(AddressOf AddManagedPath), where AddManagedPath is a Sub procedure containing the above code sample.</p> <p>This then fails with an InvalidOperationException, "Operation is not valid due to the current state of the object."</p> <p>Where am I going wrong?</p> <p>One workaround I have managed to do is to call out to STSADM.EXE via Process.Start(), supplying the requisite parameters, and this works.</p> <p><strong>Update:</strong> whilst developing the web service, I am running it using the built-in Visual Studio 2005 web server - what security context will this be running under? Can I change the security context by putting entries in web.config?</p> <p><strong>Update:</strong> I think the problem is definitely to do with not running the web service within the correct SharePoint security context. I decided to go with the workaround I suggested and shell out to STSADM, although to do this, the application pool identity that the web service runs under must be a member of the SharePoint administrators.</p>
[ { "answer_id": 354261, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": true, "text": "Dim clientSiteUrl As String = \"http://myintranet/clients/sampleclient\"\nUsing SPSite = new SPSite(clientSiteUrl) \n webApp As SPWebApplication = SPWebApplication.Lookup(new Uri(clientSiteUrl));\n If Not (webApp.Prefixes.Contains(clientSiteUrl)) Then\n webApp.Prefixes.Add(clientSiteUrl, SPPrefixType.ExplicitInclusion)\n End If\nEnd Using\n" }, { "answer_id": 5071772, "author": "Eric Schrader", "author_id": 627364, "author_profile": "https://Stackoverflow.com/users/627364", "pm_score": 1, "selected": false, "text": "using (SPSite site = new SPSite(\"http://dev-moss07-eric/PathHere\")) {\n SPWebApplication webApp = SPWebApplication.Lookup(new Uri(\"http://dev-moss07-eric\"));\n if (webApp.Prefixes.Contains(\"PathHere\"))\n {\n //\n }\n else\n {\n webApp.Prefixes.Add(\"PathHere\", SPPrefixType.ExplicitInclusion);\n }\n}\n" }, { "answer_id": 5072545, "author": "Eric Schrader", "author_id": 627364, "author_profile": "https://Stackoverflow.com/users/627364", "pm_score": 0, "selected": false, "text": "using (SPSite site = new SPSite(\"http://dev-moss07-eric\")) {\n SPWebApplication webApp = SPWebApplication.Lookup(new Uri(\"http://dev-moss07-eric\"));\n if (webApp.Prefixes.Contains(\"ManagedPathHere\"))\n {\n //\n }\n else\n {\n webApp.Prefixes.Add(\"ManagedPathHere\", SPPrefixType.ExplicitInclusion);\n }\n using (SPWeb web = site.OpenWeb())\n {\n SPWebApplication webApplication = web.Site.WebApplication;\n try\n {\n webApplication.Sites.Add(\"ManagedPathHere\",\"Site Title Here\",\"This site is used for hosting styling assets.\", 1033, \"STS#1\", \"6scdev\\\\eric.schrader\", \"Eric Schrader\", \"eric.schrader@6sc.com\");\n }\n catch (Exception ex)\n {\n //ex.ToString;\n }\n }\n }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052/" ]
352,354
<p>I need to match a string holiding html using a regex to pull out all the nested spans, I assume I assume there is a way to do this using a regex but have had no success all morning. </p> <p>So for a sample input string of </p> <pre><code>&lt;DIV id=c445c9c2-a02e-4cec-b254-c134adfa4192 style="BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid; BACKGROUND-COLOR: #eeeeee"&gt; &lt;SPAN id=b8db8cd1-f600-448f-be26-2aa56ea09a9c&gt; &lt;SPAN id=304ccd38-8161-4def-a557-1a048c963df4&gt; &lt;IMG src="http://avis.co.uk/Assets/build/menu.gif"&gt; &lt;/SPAN&gt; &lt;/SPAN&gt; &lt;SPAN id=bc88c866-5370-4c72-990b-06fbe22038d5&gt; &lt;SPAN id=55b88bbe-15ca-49c9-ad96-cecc6ca7004e&gt;UK&lt;BR&gt;&lt;/SPAN&gt; &lt;/SPAN&gt; &lt;SPAN id=52bb62ca-8f0a-42f1-a13b-9b263225ff1d&gt; &lt;SPAN id=0e1c3eb6-046d-4f07-96c1-d1ac099d5f1c&gt; &lt;IMG src="http://avis.co.uk/Assets/build/menu.gif"&gt; &lt;/SPAN&gt; &lt;/SPAN&gt; &lt;SPAN id=4c29eef2-cd77-4d33-9828-e442685a25cb&gt; &lt;SPAN id=0d5a266a-14ae-4a89-9263-9e0ab57f7ad2&gt;Italy&lt;/SPAN&gt; &lt;/SPAN&gt; &lt;SPAN id=f0a72eea-fddd-471e-89e6-56e9b9efbece&gt; &lt;SPAN id=b7d9ada7-ade0-49fe-aa5f-270237e87c2b&gt; &lt;IMG src="http://avis.co.uk/Assets/build/menu.gif"&gt; &lt;/SPAN&gt; &lt;/SPAN&gt; &lt;SPAN id=7604df94-34ba-4c89-bf11-125df01731ff&gt; &lt;SPAN id=330d6429-4f1b-46a2-a485-9001e2c6b8c1&gt;Netherlands&lt;/SPAN&gt; &lt;/SPAN&gt; &lt;SPAN id=a18fb516-451e-4c32-ab31-3e3be29235f6&gt; &lt;SPAN id=6c70238d-78f9-468f-bb8d-370fff13c909&gt; &lt;IMG src="http://avis.co.uk/Assets/build/menu.gif"&gt; &lt;/SPAN&gt; &lt;/SPAN&gt; &lt;SPAN id=5a2465eb-b337-4f94-a4f8-6f5001dfbd75&gt; &lt;SPAN id=47877a9e-a7d5-4f13-a41e-6948f899e385&gt;Malta &amp;amp; Gozo </code></pre> <p>i would want to get each outer span and its containing span so in the above text there should be Eight results</p> <p>Any help gladly accepted</p>
[ { "answer_id": 352907, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "Pattern p = Pattern.compile(\"(<SPAN id.*?<SPAN id.*?</SPAN></SPAN>)\");\nMatcher m = p.matcher(html);\nwhile (m.find())\n{\n System.out.println(m.group(1));\n}\n" }, { "answer_id": 353350, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 2, "selected": true, "text": "@\"(?is)<SPAN\\b[^>]*>\\s*(<SPAN\\b[^>]*>.*?</SPAN>)\\s*</SPAN>\"\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87783/" ]
352,365
<p>What is the difference between the concepts of <strong>"Code Re-entrancy"</strong> and <strong>"Thread Safety"</strong>? As per the link mentioned below, a piece of code can be either of them, both of them or neither of them. </p> <p><a href="http://encyclopedia.thefreedictionary.com/reentrant+code" rel="noreferrer">Reentrant and Thread safe code</a></p> <p>I was not able to understand the explaination clearly. Help would be appreciated. </p>
[ { "answer_id": 352645, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "take_global_lock();\nint i = get_global_counter();\ndo_callback(i);\nset_global_counter(i+1);\nrelease_global_lock();\n int i = get_global_counter();\ndo_callback(i);\nset_global_counter(get_global_counter()+1);\n int i = get_global_counter();\ndo_callback(i);\ndisable_signals(); // and any other kind of interrupts on your system\nset_global_counter(get_global_counter()+1);\nrestore_signal_state();\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40981/" ]
352,389
<p>We have this set of data that we need to get the average of a column. a <code>select avg(x) from y</code> does the trick. However we need a more accurate figure.</p> <p>I figured that there must be a way of filtering records that has either too high or too low values(spikes) so that we can exclude them in calculating the average.</p>
[ { "answer_id": 352530, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 3, "selected": true, "text": "select name, \n (select top 1 h.run_duration\n from sysjobhistory h\n where h.step_id = 0\n and h.job_id = j.job_id\n group by h.run_duration\n order by count(*) desc) run_duration\nfrom sysjobs j\n select oh.job_id, avg(oh.run_duration) from sysjobhistory oh\ninner join (select job_id, avg(h.run_duration) avgduration, \n stdev(h.run_duration) stdev_duration \n from sysjobhistory h \n group by job_id) as m on m.job_id = oh.job_id\nwhere oh.step_id = 0\nand abs(oh.run_duration - m.avgduration) < m.stdev_duration\ngroup by oh.job_id\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300/" ]
352,408
<p>A colleague of mine and I have been discussing how to declare variables in a function.</p> <p>Let's say you have a class called TStrings (using Delphi for the sake of explanation) that has at least one abstract method and a descendant class called TStringList which obviously implements the abstract method, but it introduces nothing else you need that is not already implemented in the ancestor, how would you declare a function variable of type TStringList?</p> <p>Here are two examples. Which is considered better practice and why?</p> <pre><code>procedure AddElements; var aList: TStringList; begin aList := TStringList.Create; try aList.Add('Apple'); aList.Add('Pear'); finally aList.free; end; end; procedure AddElementsII; var aList: TStrings; begin aList := TStringList.Create; try aList.Add('Apple'); aList.Add('Pear'); finally aList.free; end; end; </code></pre>
[ { "answer_id": 352454, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "procedure TMyClass.MyMethod(const AList: TStrings);\nbegin\nend;\n" }, { "answer_id": 352823, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "Collection list = new ArrayList();\n[loop] list.add(someItem); [end loop]\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1264322/" ]
352,415
<p>I am reorganizing my source files into a single solution with a single project, due to various reasons:</p> <ul> <li>a paranoic configured antivirus software;</li> <li><a href="http://codebetter.com/blogs/patricksmacchia/archive/2008/12/08/advices-on-partitioning-code-through-net-assemblies.aspx" rel="nofollow noreferrer">Advices on partitioning code through .NET assemblies</a></li> <li><a href="http://www.theserverside.net/tt/articles/showarticle.tss?id=ControllingDependencies" rel="nofollow noreferrer">Control component dependencies to gain clean architecture</a></li> <li><a href="http://codebetter.com/blogs/patricksmacchia/archive/2007/06/20/benefit-from-the-c-and-vb-net-compilers-perf.aspx" rel="nofollow noreferrer">Benefit from the C# and VB.NET compilers perf</a></li> </ul> <p>This leaves me with many namespaces, which are splitted across multiple files. So far, I am using this convention: given the namespace <code>Company.Project.A</code>, the files are named <code>A.f1.cs</code>, <code>A.f2.cs</code> and so on, and the <code>Company.Project.B</code> namespace is splitted across <code>B.f1.cs</code>, <code>B.f2.cs</code>, etc.</p> <p>Given the single project restriction, are there any better ways to organize multiple files in multiple namespaces?</p>
[ { "answer_id": 352421, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "using System; // Etc\n\nnamespace Company.Project.Foo\n{\n class Bar\n {\n }\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19756/" ]
352,420
<p>I just wanted to know what's the difference between clear() and str("");</p> <p>For example:</p> <pre><code>stringstream ss("Stack Overflow"); ss.clear(); ss.str(""); </code></pre> <p>I wanted to know the underlying technical difference.</p>
[ { "answer_id": 352426, "author": "AlfaZulu", "author_id": 44060, "author_profile": "https://Stackoverflow.com/users/44060", "pm_score": 5, "selected": true, "text": "clear() stringstream goodbit str(\"\")" }, { "answer_id": 352443, "author": "yesraaj", "author_id": 22076, "author_profile": "https://Stackoverflow.com/users/22076", "pm_score": 3, "selected": false, "text": "void clear ( iostate state = goodbit ) //clears and sets error flag passed as parameter\n\nstring str ( ) const; //to get value from string stream\nvoid str ( const string & s ); //to set value to string stream\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38038/" ]
352,434
<p>I have a long "binary string" like the output of PHPs pack function.</p> <p>How can I convert this value to base62 (0-9a-zA-Z)? The built in maths functions overflow with such long inputs, and BCmath doesn't have a base_convert function, or anything that specific. I would also need a matching "pack base62" function.</p>
[ { "answer_id": 364626, "author": "david", "author_id": 27600, "author_profile": "https://Stackoverflow.com/users/27600", "pm_score": 1, "selected": false, "text": "base64_encode()\nbase64_decode()\n" }, { "answer_id": 1743486, "author": "Jay Dansand", "author_id": 198299, "author_profile": "https://Stackoverflow.com/users/198299", "pm_score": 3, "selected": false, "text": "base64_encode(...) base64_encode(1234) = \"MTIzNA==\"\nbase64_convert(1234) = \"TS\" //if the base64_convert function existed\n base64_encode() base64_encode() base64_convert()" }, { "answer_id": 4848526, "author": "Core Xii", "author_id": 95108, "author_profile": "https://Stackoverflow.com/users/95108", "pm_score": 2, "selected": false, "text": "base_conv() function base_conv($val, &$baseTo, &$baseFrom)\n {\n return base_arr_to_str(base_conv_arr(base_str_to_arr((string) $val, $baseFrom), count($baseTo), count($baseFrom)), $baseTo);\n }\n\nfunction base_conv_arr($val, $baseToDigits, $baseFromDigits)\n {\n $valCount = count($val);\n $result = array();\n do\n {\n $divide = 0;\n $newlen = 0;\n for ($i = 0; $i < $valCount; ++$i)\n {\n $divide = $divide * $baseFromDigits + $val[$i];\n if ($divide >= $baseToDigits)\n {\n $val[$newlen ++] = (int) ($divide / $baseToDigits);\n $divide = $divide % $baseToDigits;\n }\n else if ($newlen > 0)\n {\n $val[$newlen ++] = 0;\n }\n }\n $valCount = $newlen;\n array_unshift($result, $divide);\n }\n while ($newlen != 0);\n return $result;\n }\n\nfunction base_arr_to_str($arr, &$base)\n {\n $str = '';\n foreach ($arr as $digit)\n {\n $str .= $base[$digit];\n }\n return $str;\n }\n\nfunction base_str_to_arr($str, &$base)\n {\n $arr = array();\n while ($str === '0' || !empty($str))\n {\n foreach ($base as $index => $digit)\n {\n if (mb_substr($str, 0, $digitLen = mb_strlen($digit)) === $digit)\n {\n $arr[] = $index;\n $str = mb_substr($str, $digitLen);\n continue 2;\n }\n }\n throw new Exception();\n }\n return $arr;\n }\n $baseDec = str_split('0123456789');\n$baseHex = str_split('0123456789abcdef');\n\necho base_conv(255, $baseHex, $baseDec); // ff\necho base_conv('ff', $baseDec, $baseHex); // 255\n\n// multi-character base:\n$baseHelloworld = array('hello ', 'world ');\necho base_conv(37, $baseHelloworld, $baseDec); // world hello hello world hello world \necho base_conv('world hello hello world hello world ', $baseDec, $baseHelloworld); // 37\n\n// ambiguous base:\n// don't do this! base_str_to_arr() won't know how to decode e.g. '11111'\n// (well it does, but the result might not be what you'd expect;\n// It matches digits sequentially so '11111' would be array(0, 0, 1)\n// here (matched as '11', '11', '1' since they come first in the array))\n$baseAmbiguous = array('11', '1', '111');\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
352,452
<p>I have this code </p> <p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22580" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22580</a> </p> <p>which is part of a small ajax application. I would like to know a better, more efficient way to assign $query, instead of copying the sql each time with a different query or a bunch of if clauses. Basically the query will be dependant on the link clicked, but I am not sure how to show that in the logic. I am also unsure why my SQL query in $result fails.</p>
[ { "answer_id": 352483, "author": "markus", "author_id": 11995, "author_profile": "https://Stackoverflow.com/users/11995", "pm_score": 3, "selected": true, "text": "<?php\nsession_start(); //ommit, no session var used\n\n//use braces, always!\n//you may write such statements with the short form like\nif (isset($_GET['cmd'])) : $cmd = $_GET['cmd']; else : die (_MSG_NO_PARAM); endif;\n\n$query = '';\n//escpae your input - very important for security! sql injection!\nif ( isset ($_GET[\"query\"]))\n{\n $query = mysql_real_escape_string($_GET[\"query\"]);\n}\n//no need for the other part you had here\n\n$con = mysql_connect(\"localhost\", \"root\", \"geheim\");\n\nif (!$con) : die ('Connection failed. Error: '.mysql_error()); endif;\n\nmysql_select_db(\"ebay\", $con);\n\nif ($cmd == \"GetRecordSet\")\n{\n $table = 'Auctions';\n $rows = getRowsByArticleSearch($searchString, $table);\n\n //use PHP_EOL instead of \\n in order to make your script more portable\n\n echo \"<h1>Table: {$table}</h1>\".PHP_EOL;\n echo \"<table border='1' width='100%'><tr>\".PHP_EOL;\n echo \"<td width='33%'>Seller ID</td>\".PHP_EOL;\n echo \"<td width='33%'>Start Date</td>\".PHP_EOL;\n echo \"<td width='33%'>Description</td>\".PHP_EOL;\n echo \"</tr>\\n\";\n\n // printing table rows\n foreach ($rows as $row)\n {\n $pk = $row['ARTICLE_NO'];\n echo '<tr>'.PHP_EOL;\n echo '<td><a href=\"#\" onclick=\"GetAuctionData(\\''.$pk.'\\')\">'.$row['USERNAME'].'</a></td>'.PHP_EOL;\n echo '<td><a href=\"#\" onclick=\"GetAuctionData(\\''.$pk.'\\')\">'.$row['ACCESSSTARTS'].'</a></td>'.PHP_EOL;\n echo '<td><a href=\"#\" onclick=\"GetAuctionData(\\''.$pk.'\\')\">'.$row['ARTICLE_NAME'].'</a></td>'.PHP_EOL;\n echo '</tr>'.PHP_EOL;\n }\n}\nmysql_free_result($result);\n//mysql_close($con); no need to close connection, you better don't\n\n\nfunction getRowsByArticleSearch($searchString, $table) \n{\n $searchString = mysql_real_escape_string($searchString);\n $result = mysql_query(\"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME FROM {$table} WHERE upper ARTICLE_NAME LIKE '%\" . $searchString . \"%'\");\n if($result === false) {\n return mysql_error();\n }\n $rows = array();\n while($row = mysql_fetch_assoc($result)) {\n $rows[] = $row;\n }\n return $rows;\n}\n\n// ?> ommit closing php tag\n" }, { "answer_id": 352495, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "\"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME\nFROM {$table} WHERE upper ARTICLE_NAME LIKE'%$query%'\"\n upper \"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME\nFROM {$table} WHERE upper(ARTICLE_NAME) LIKE'%$query%'\"\n" }, { "answer_id": 352504, "author": "Irmantas", "author_id": 43182, "author_profile": "https://Stackoverflow.com/users/43182", "pm_score": 2, "selected": false, "text": "$result = mysql_query($sql_query) or die(mysql_error());\n" }, { "answer_id": 352521, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 2, "selected": false, "text": "function searchQuery($text) {\n $text = mysql_real_escape_string($text);\n $result = mysql_query(\"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME FROM {$table} WHERE upper ARTICLE_NAME LIKE '%\" . $text . \"%'\");\n if($result === false) {\n return mysql_error();\n }\n $rows = array();\n while($row = mysql_fetch_assoc($result)) {\n $rows[] = $row;\n }\n return $rows;\n}\n $result = searchQuery($_GET['query']);\n if(!is_array($result) ) {\n echo 'An error has occurred:' . $result;\n } else {\n //iterate over rows\n }\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
352,463
<p>I have a JSON as follows</p> <pre><code>{ columns : [RULE_ID,COUNTRY_CODE], RULE_ID : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30], COUNTRY_CODE : [US,US,CA,US,FR,GB,GB,UM,AF,AF,AL,CA,US,US,US] } </code></pre> <p>I need to retrive the column names from the columns entry and then use it to search the rest of the entries using jquery. For example I get each column using </p> <pre><code>jQuery.each(data.columns, function(i,column)) </code></pre> <p>I need to loop throgh the rest of the entries using the values I get from the previous loop. ie <strong>without hardcoding COUNTRY_CODE or RULE_ID</strong>. What is the best way to do that using Jquery?</p>
[ { "answer_id": 352533, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 4, "selected": true, "text": "jQuery.each(data.columns, function(i,column) {\n jQuery.each(data[column], function(i, row) {\n ....\n });\n});\n" }, { "answer_id": 354545, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 2, "selected": false, "text": "jQuery.each(data.columns, function(iCol,column) {\n jQuery.each(data[column], function(iRow, row) {\n ....\n });\n});\n for( var column in data )\n{\n jQuery.each(data[column], function(i, row) {\n ....\n });\n}\n {\n \"columns\" : [\"RULE_ID\",\"COUNTRY_CODE\"],\n \"RULE_ID\" : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30], \n \"COUNTRY_CODE\" : [\"US\",\"US\",\"CA\",\"US\",\"FR\",\"GB\",\"GB\",\"UM\",\"AF\",\"AF\",\"AL\",\"CA\",\"US\",\"US\",\"US\"]\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16488/" ]
352,467
<p>I am currently doing the front end for a site with looooads of forms, all styled up and looking pretty in IE, but I've just noticed that in Firefox the file input fields aren't responding to any of my styles, all the other types of input fields are fine. I've checked it in Firebug and its associating the correct styles to it, but not changing how it looks.</p> <p>If this isn't a complete brain fart on my behalf, then is this a known issue in Firefox? And if so, how have I never noticed it before?</p> <p>Here is a sample of the code.</p> <p>CSS:</p> <pre><code>form.CollateralForm input, form.CollateralForm textarea { width:300px; font-size:1em; border: solid 1px #979797; font-family: Verdana, Helvetica, Sans-Serif; } </code></pre> <p>HTML:</p> <pre><code>&lt;form method="bla" action="blah" class="CollateralForm"&gt; &lt;input type="file" name="descriptionFileUpload" id="descriptionFileUpload" /&gt; &lt;/form&gt; </code></pre> <p>I've also tried applying a class to it but that doesn't work either.</p>
[ { "answer_id": 352512, "author": "Samiksha", "author_id": 29515, "author_profile": "https://Stackoverflow.com/users/29515", "pm_score": -1, "selected": false, "text": "form.CollateralForm input,\nform.CollateralForm textarea\n{\n width:300px; //for firefox\n #width:200px; //for IE7\n _width:100px; //for IE6\n font-size:1em;\n border: solid 1px #979797;\n font-family: Verdana, Helvetica, Sans-Serif;\n}\n" }, { "answer_id": 14605593, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 5, "selected": false, "text": "<label> for=\"someid\" <input id=\"someid\">" }, { "answer_id": 24800763, "author": "Gaurav Gupta", "author_id": 279680, "author_profile": "https://Stackoverflow.com/users/279680", "pm_score": 2, "selected": false, "text": "<input style=\"display:none\" id=\"js-choose-file\" type=\"file\">\n <a id=\"js-choose-computer\" href=\"javascript:void(0);\">From Computer</a>\n $(\"#js-choose-computer\").on(\"click\", function() {\n $(\"#js-choose-file\").click();\n return false;\n});\n" }, { "answer_id": 64691161, "author": "karolus", "author_id": 2976571, "author_profile": "https://Stackoverflow.com/users/2976571", "pm_score": 1, "selected": false, "text": "::-webkit-file-upload-button <form>\n <label for=\"fileUpload\">Upload file</label>\n <input type=\"file\" id=\"fileUpload\">\n</form>\n input[type=file]::file-selector-button {\n border: 2px solid #6c5ce7;\n padding: .2em .4em;\n border-radius: .2em;\n background-color: #a29bfe;\n transition: 1s;\n}\n \ninput[type=file]::file-selector-button:hover {\n background-color: #81ecec;\n border: 2px solid #00cec9;\n}\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31109/" ]
352,471
<p>I am working on creating an immutable class.<br> I have marked all the properties as read-only. </p> <p>I have a list of items in the class.<br> Although if the property is read-only the list can be modified. </p> <p>Exposing the IEnumerable of the list makes it immutable.<br> I wanted to know what is the basic rules one has to follow to make a class immutable ? </p>
[ { "answer_id": 352490, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": false, "text": "public class MyClass\n{\n public MyClass(..., IList<MyType> items)\n {\n ...\n _myReadOnlyList = new List<MyType>(items).AsReadOnly();\n }\n\n public IList<MyType> MyReadOnlyList\n {\n get { return _myReadOnlyList; }\n }\n private IList<MyType> _myReadOnlyList\n\n}\n" }, { "answer_id": 352529, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 4, "selected": false, "text": "public readonly object[] MyObjects;\n" }, { "answer_id": 352678, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": 3, "selected": false, "text": "ReadOnlyCollection System.Collections.ObjectModel using System.Collections.ObjectModel;\n\n...\n\npublic MyClass(..., List<ListItemType> theList, ...)\n{\n ...\n this.myListItemCollection= theList.AsReadOnly();\n ...\n}\n\npublic ReadOnlyCollection<ListItemType> ListItems\n{\n get { return this.myListItemCollection; }\n}\n" }, { "answer_id": 64794074, "author": "KUTlime", "author_id": 4553982, "author_profile": "https://Stackoverflow.com/users/4553982", "pm_score": 2, "selected": false, "text": "record public record Customer(string FirstName, string LastName, IEnumerable<string> Items);\n\n//...\n\nvar person = new Customer(\"Test\", \"test\", new List<string>() { \"Test1\", \"Test2\", \"Test3\" });\n// you can't change anything within person variable\n// person.FirstName = \"NewName\";\n FirstName LastName Items IEnumerable<T> ReadOnlyCollection<T> System.Collections.Immutable" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41968/" ]
352,472
<p>I was curiious to know what type of structures you use for your project references?</p> <p>Where I work the developers have a shared folder called AssemblyCache (\\MACHINENAME\AssemblyCache) which is mapped to an R:\ via GPO in Windows 2008 AD (tied to the Developers AD group).</p> <p>Our shared components have post-build events that copy them to something like this:</p> <p>R:\.Net %VERSION%\Project\%SOMETHING%</p> <p>Sometimes it's followed by either 'Common' if it's common to the project or something specific. There's also a common directory for shared stuff under the .Net version folder.</p> <p>This is so large projects over multiple solutions can reference the assemblies from a common place.</p> <p>The build machine also has a shared drive of the same share name which the developers have mapped to S:. This allows them to get the latest working build should they need it.</p> <p>All this is so someone can get on a new PC, and open a project without having to copy references to varying locations, and ensuring that dev a is referencing the assembly from the same place as dev b etc...</p> <p>This solution works well for us, so I was wondering what, if any, solutions you have in-place for ensuring all developers reference assemblies from the same path?</p>
[ { "answer_id": 352524, "author": "Sandeep Datta", "author_id": 39648, "author_profile": "https://Stackoverflow.com/users/39648", "pm_score": 2, "selected": true, "text": "subst R: \"C:\\.Net %VERSION%\\Project\\%SOMETHING%\"\n" } ]
2008/12/09
[ "https://Stackoverflow.com/questions/352472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791/" ]