qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
105,034
<p>How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.</p> <p>I'm not sure what routines are available on all browsers, how &quot;random&quot; and seeded the built-in random number generator is, etc.</p>
[ { "answer_id": 105074, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 12, "selected": true, "text": "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx Math.random" }, { "answer_id": 105078, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 6, "selected": false, "text": "function generateGuid() {\n var result, i, j;\n result = '';\n for(j=0; j<32; j++) {\n if( j == 8 || j == 12 || j == 16 || j == 20)\n result = result + '-';\n i = Math.floor(Math.random()*16).toString(16).toUpperCase();\n result = result + i;\n }\n return result;\n}\n" }, { "answer_id": 873856, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 8, "selected": false, "text": "function createUUID() {\n // http://www.ietf.org/rfc/rfc4122.txt\n var s = [];\n var hexDigits = \"0123456789abcdef\";\n for (var i = 0; i < 36; i++) {\n s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);\n }\n s[14] = \"4\"; // bits 12-15 of the time_hi_and_version field to 0010\n s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01\n s[8] = s[13] = s[18] = s[23] = \"-\";\n\n var uuid = s.join(\"\");\n return uuid;\n}\n" }, { "answer_id": 1323308, "author": "Mathieu Pagé", "author_id": 5861, "author_profile": "https://Stackoverflow.com/users/5861", "pm_score": 5, "selected": false, "text": "function uuid()\n{\n var chars = '0123456789abcdef'.split('');\n\n var uuid = [], rnd = Math.random, r;\n uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';\n uuid[14] = '4'; // version 4\n\n for (var i = 0; i < 36; i++)\n {\n if (!uuid[i])\n {\n r = 0 | rnd()*16;\n\n uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];\n }\n }\n\n return uuid.join('');\n}\n 682db637-0f31-4847-9cdf-25ba9613a75c\n97d19478-3ab2-4aa1-b8cc-a1c3540f54aa\n2eed04c9-2692-456d-a0fd-51012f947136\n" }, { "answer_id": 2117523, "author": "broofa", "author_id": 109538, "author_profile": "https://Stackoverflow.com/users/109538", "pm_score": 12, "selected": false, "text": "uuid crypto.randomUUID() localhost 127.0.0.1 crypto.randomUUID() function uuidv4() {\n return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>\n (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n );\n}\n\nconsole.log(uuidv4()); Math.random() Math.random()" }, { "answer_id": 3251361, "author": "jablko", "author_id": 392146, "author_profile": "https://Stackoverflow.com/users/392146", "pm_score": 5, "selected": false, "text": " // RFC 4122\n //\n // A UUID is 128 bits long\n //\n // String representation is five fields of 4, 2, 2, 2, and 6 bytes.\n // Fields represented as lowercase, zero-filled, hexadecimal strings, and\n // are separated by dash characters\n //\n // A version 4 UUID is generated by setting all but six bits to randomly\n // chosen values\n var uuid = [\n Math.random().toString(16).slice(2, 10),\n Math.random().toString(16).slice(2, 6),\n\n // Set the four most significant bits (bits 12 through 15) of the\n // time_hi_and_version field to the 4-bit version number from Section\n // 4.1.3\n (Math.random() * .0625 /* 0x.1 */ + .25 /* 0x.4 */).toString(16).slice(2, 6),\n\n // Set the two most significant bits (bits 6 and 7) of the\n // clock_seq_hi_and_reserved to zero and one, respectively\n (Math.random() * .25 /* 0x.4 */ + .5 /* 0x.8 */).toString(16).slice(2, 6),\n\n Math.random().toString(16).slice(2, 14)].join('-');\n" }, { "answer_id": 7061193, "author": "Jed Schmidt", "author_id": 87702, "author_profile": "https://Stackoverflow.com/users/87702", "pm_score": 6, "selected": false, "text": "UUIDv4 = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}\n UUIDv4 =\n\nfunction b(\n a // placeholder\n){\n return a // if the placeholder was passed, return\n ? ( // a random number from 0 to 15\n a ^ // unless b is 8,\n Math.random() // in which case\n * 16 // a random number from\n >> a/4 // 8 to 11\n ).toString(16) // in hexadecimal\n : ( // or otherwise a concatenated string:\n [1e7] + // 10000000 +\n -1e3 + // -1000 +\n -4e3 + // -4000 +\n -8e3 + // -80000000 +\n -1e11 // -100000000000,\n ).replace( // replacing\n /[018]/g, // zeroes, ones, and eights with\n b // random hex digits\n )\n}\n" }, { "answer_id": 7221797, "author": "sleeplessnerd", "author_id": 616486, "author_profile": "https://Stackoverflow.com/users/616486", "pm_score": 5, "selected": false, "text": "var uuid = function() {\n var buf = new Uint32Array(4);\n window.crypto.getRandomValues(buf);\n var idx = -1;\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n idx++;\n var r = (buf[idx>>3] >> ((idx%8)*4))&15;\n var v = c == 'x' ? r : (r&0x3|0x8);\n return v.toString(16);\n });\n};\n" }, { "answer_id": 8472700, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 6, "selected": false, "text": "generateGUID = (typeof(window.crypto) != 'undefined' &&\n typeof(window.crypto.getRandomValues) != 'undefined') ?\n function() {\n // If we have a cryptographically secure PRNG, use that\n // https://stackoverflow.com/questions/6906916/collisions-when-generating-uuids-in-javascript\n var buf = new Uint16Array(8);\n window.crypto.getRandomValues(buf);\n var S4 = function(num) {\n var ret = num.toString(16);\n while(ret.length < 4){\n ret = \"0\"+ret;\n }\n return ret;\n };\n return (S4(buf[0])+S4(buf[1])+\"-\"+S4(buf[2])+\"-\"+S4(buf[3])+\"-\"+S4(buf[4])+\"-\"+S4(buf[5])+S4(buf[6])+S4(buf[7]));\n }\n\n :\n\n function() {\n // Otherwise, just use Math.random\n // https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);\n return v.toString(16);\n });\n };\n" }, { "answer_id": 8809472, "author": "Briguy37", "author_id": 508537, "author_profile": "https://Stackoverflow.com/users/508537", "pm_score": 10, "selected": false, "text": "Math.random Math.random function generateUUID() { // Public Domain/MIT\n var d = new Date().getTime();//Timestamp\n var d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random() * 16;//random number between 0 and 16\n if(d > 0){//Use timestamp until depleted\n r = (d + r)%16 | 0;\n d = Math.floor(d/16);\n } else {//Use microseconds since page-load if supported\n r = (d2 + r)%16 | 0;\n d2 = Math.floor(d2/16);\n }\n return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);\n });\n}\n\nvar onClick = function(){\n document.getElementById('uuid').textContent = generateUUID();\n}\nonClick(); #uuid { font-family: monospace; font-size: 1.5em; } <p id=\"uuid\"></p>\n<button id=\"generateUUID\" onclick=\"onClick();\">Generate UUID</button> const generateUUID = () => {\n let\n d = new Date().getTime(),\n d2 = (performance && performance.now && (performance.now() * 1000)) || 0;\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n let r = Math.random() * 16;\n if (d > 0) {\n r = (d + r) % 16 | 0;\n d = Math.floor(d / 16);\n } else {\n r = (d2 + r) % 16 | 0;\n d2 = Math.floor(d2 / 16);\n }\n return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);\n });\n};\n\nconst onClick = (e) => document.getElementById('uuid').textContent = generateUUID();\n\ndocument.getElementById('generateUUID').addEventListener('click', onClick);\n\nonClick(); #uuid { font-family: monospace; font-size: 1.5em; } <p id=\"uuid\"></p>\n<button id=\"generateUUID\">Generate UUID</button>" }, { "answer_id": 8857806, "author": "Tracker1", "author_id": 43906, "author_profile": "https://Stackoverflow.com/users/43906", "pm_score": 4, "selected": false, "text": "//UUID/Guid Generator\n// use: UUID.create() or UUID.createSequential()\n// convenience: UUID.empty, UUID.tryParse(string)\n(function(w){\n // From http://baagoe.com/en/RandomMusings/javascript/\n // Johannes Baagøe <baagoe@baagoe.com>, 2010\n //function Mash() {...};\n\n // From http://baagoe.com/en/RandomMusings/javascript/\n //function Kybos() {...};\n\n var rnd = Kybos();\n\n //UUID/GUID Implementation from http://frugalcoder.us/post/2012/01/13/javascript-guid-uuid-generator.aspx\n var UUID = {\n \"empty\": \"00000000-0000-0000-0000-000000000000\"\n ,\"parse\": function(input) {\n var ret = input.toString().trim().toLowerCase().replace(/^[\\s\\r\\n]+|[\\{\\}]|[\\s\\r\\n]+$/g, \"\");\n if ((/[a-f0-9]{8}\\-[a-f0-9]{4}\\-[a-f0-9]{4}\\-[a-f0-9]{4}\\-[a-f0-9]{12}/).test(ret))\n return ret;\n else\n throw new Error(\"Unable to parse UUID\");\n }\n ,\"createSequential\": function() {\n var ret = new Date().valueOf().toString(16).replace(\"-\",\"\")\n for (;ret.length < 12; ret = \"0\" + ret);\n ret = ret.substr(ret.length-12,12); //only least significant part\n for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));\n return [ret.substr(0,8), ret.substr(8,4), \"4\" + ret.substr(12,3), \"89AB\"[Math.floor(Math.random()*4)] + ret.substr(16,3), ret.substr(20,12)].join(\"-\");\n }\n ,\"create\": function() {\n var ret = \"\";\n for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));\n return [ret.substr(0,8), ret.substr(8,4), \"4\" + ret.substr(12,3), \"89AB\"[Math.floor(Math.random()*4)] + ret.substr(16,3), ret.substr(20,12)].join(\"-\");\n }\n ,\"random\": function() {\n return rnd();\n }\n ,\"tryParse\": function(input) {\n try {\n return UUID.parse(input);\n } catch(ex) {\n return UUID.empty;\n }\n }\n };\n UUID[\"new\"] = UUID.create;\n\n w.UUID = w.Guid = UUID;\n}(window || this));" }, { "answer_id": 10725965, "author": "Andrea Turri", "author_id": 498688, "author_profile": "https://Stackoverflow.com/users/498688", "pm_score": 4, "selected": false, "text": "function(\n a, b // Placeholders\n){\n for( // Loop :)\n b = a = ''; // b - result , a - numeric variable\n a++ < 36; //\n b += a*51&52 // If \"a\" is not 9 or 14 or 19 or 24\n ? // return a random number or 4\n (\n a^15 // If \"a\" is not 15,\n ? // generate a random number from 0 to 15\n 8^Math.random() *\n (a^20 ? 16 : 4) // unless \"a\" is 20, in which case a random number from 8 to 11,\n :\n 4 // otherwise 4\n ).toString(16)\n :\n '-' // In other cases, (if \"a\" is 9,14,19,24) insert \"-\"\n );\n return b\n }\n function(a,b){for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b}\n" }, { "answer_id": 13403498, "author": "joelpt", "author_id": 313177, "author_profile": "https://Stackoverflow.com/users/313177", "pm_score": 6, "selected": false, "text": "function generateQuickGuid() {\n return Math.random().toString(36).substring(2, 15) +\n Math.random().toString(36).substring(2, 15);\n}\n >>> generateQuickGuid()\n\"nvcjf1hs7tf8yyk4lmlijqkuo9\"\n\"yq6gipxqta4kui8z05tgh9qeel\"\n\"36dh5sec7zdj90sk2rx7pjswi2\"\nruntime: 32.5s\n\n>>> GUID() // John Millikin\n\"7a342ca2-e79f-528e-6302-8f901b0b6888\"\nruntime: 57.8s\n\n>>> regexGuid() // broofa\n\"396e0c46-09e4-4b19-97db-bd423774a4b3\"\nruntime: 91.2s\n\n>>> createUUID() // Kevin Hakanson\n\"403aa1ab-9f70-44ec-bc08-5d5ac56bd8a5\"\nruntime: 65.9s\n\n>>> UUIDv4() // Jed Schmidt\n\"f4d7d31f-fa83-431a-b30c-3e6cc37cc6ee\"\nruntime: 282.4s\n\n>>> Math.uuid() // broofa\n\"5BD52F55-E68F-40FC-93C2-90EE069CE545\"\nruntime: 225.8s\n\n>>> Math.uuidFast() // broofa\n\"6CB97A68-23A2-473E-B75B-11263781BBE6\"\nruntime: 92.0s\n\n>>> Math.uuidCompact() // broofa\n\"3d7b7a06-0a67-4b67-825c-e5c43ff8c1e8\"\nruntime: 229.0s\n\n>>> bitwiseGUID() // jablko\n\"baeaa2f-7587-4ff1-af23-eeab3e92\"\nruntime: 79.6s\n\n>>>> betterWayGUID() // Andrea Turri\n\"383585b0-9753-498d-99c3-416582e9662c\"\nruntime: 60.0s\n\n>>>> UUID() // John Fowler\n\"855f997b-4369-4cdb-b7c9-7142ceaf39e8\"\nruntime: 62.2s\n var r;\nconsole.time('t'); \nfor (var i = 0; i < 10000000; i++) { \n r = FuncToTest(); \n};\nconsole.timeEnd('t');\n" }, { "answer_id": 13423320, "author": "John Fowler", "author_id": 1720704, "author_profile": "https://Stackoverflow.com/users/1720704", "pm_score": 4, "selected": false, "text": "var rand = Math.random;\n\nfunction UUID() {\n var nbr, randStr = \"\";\n do {\n randStr += (nbr = rand()).toString(16).substr(3, 6);\n } while (randStr.length < 30);\n return (\n randStr.substr(0, 8) + \"-\" +\n randStr.substr(8, 4) + \"-4\" +\n randStr.substr(12, 3) + \"-\" +\n ((nbr*4|0)+8).toString(16) + // [89ab]\n randStr.substr(15, 3) + \"-\" +\n randStr.substr(18, 12)\n );\n}\n\nconsole.log( UUID() );" }, { "answer_id": 14663381, "author": "kayz1", "author_id": 1127843, "author_profile": "https://Stackoverflow.com/users/1127843", "pm_score": 5, "selected": false, "text": "var crypto = window.crypto || window.msCrypto || null; // IE11 fix\n\nvar Guid = Guid || (function() {\n\n var EMPTY = '00000000-0000-0000-0000-000000000000';\n\n var _padLeft = function(paddingString, width, replacementChar) {\n return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' ');\n };\n\n var _s4 = function(number) {\n var hexadecimalResult = number.toString(16);\n return _padLeft(hexadecimalResult, 4, '0');\n };\n\n var _cryptoGuid = function() {\n var buffer = new window.Uint16Array(8);\n crypto.getRandomValues(buffer);\n return [_s4(buffer[0]) + _s4(buffer[1]), _s4(buffer[2]), _s4(buffer[3]), _s4(buffer[4]), _s4(buffer[5]) + _s4(buffer[6]) + _s4(buffer[7])].join('-');\n };\n\n var _guid = function() {\n var currentDateMilliseconds = new Date().getTime();\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(currentChar) {\n var randomChar = (currentDateMilliseconds + Math.random() * 16) % 16 | 0;\n currentDateMilliseconds = Math.floor(currentDateMilliseconds / 16);\n return (currentChar === 'x' ? randomChar : (randomChar & 0x7 | 0x8)).toString(16);\n });\n };\n\n var create = function() {\n var hasCrypto = crypto != 'undefined' && crypto !== null,\n hasRandomValues = typeof(window.crypto.getRandomValues) != 'undefined';\n return (hasCrypto && hasRandomValues) ? _cryptoGuid() : _guid();\n };\n\n return {\n newGuid: create,\n empty: EMPTY\n };\n})();\n\n// DEMO: Create and show GUID\nconsole.log('1. New Guid: ' + Guid.newGuid());\n\n// DEMO: Show empty GUID\nconsole.log('2. Empty Guid: ' + Guid.empty);" }, { "answer_id": 16693578, "author": "Slavik Meltser", "author_id": 1291121, "author_profile": "https://Stackoverflow.com/users/1291121", "pm_score": 7, "selected": false, "text": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /**\n * Generates a GUID string.\n * @returns {string} The generated GUID.\n * @example af8a8416-6e18-a307-bd9c-f2c947bbb3aa\n * @author Slavik Meltser.\n * @link http://slavik.meltser.info/?p=142\n */\nfunction guid() {\n function _p8(s) {\n var p = (Math.random().toString(16)+\"000000000\").substr(2,8);\n return s ? \"-\" + p.substr(0,4) + \"-\" + p.substr(4,4) : p ;\n }\n return _p8() + _p8(true) + _p8(true) + _p8();\n}\n console.time('t');\nfor (var i = 0; i < 10000000; i++) {\n guid();\n};\nconsole.timeEnd('t');\n Math.random() 0.4363923368509859 0.6fb7687f Math.random().toString(16) 0. 0.6fb7687f 6fb7687f (Math.random().toString(16).substr(2,8) Math.random() 0.4363 0.4363000000000000 \"000000000\" substr() Math.random() \"0\"+\"000000000\" \"1\"+\"000000000\" Math.random().toString(16)+\"000000000\").substr(2,8) XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX XXXXXXXX -XXXX-XXXX XXXXXXXX -XXXX-XXXX -XXXX-XXXX XXXXXXXX _p8(s) s _p8() + _p8(true) + _p8(true) + _p8()" }, { "answer_id": 17070116, "author": "Anatoly Mironov", "author_id": 632117, "author_profile": "https://Stackoverflow.com/users/632117", "pm_score": 4, "selected": false, "text": "SP.Guid.newGuid var newGuid = function () {\n var result = '';\n var hexcodes = \"0123456789abcdef\".split(\"\");\n\n for (var index = 0; index < 32; index++) {\n var value = Math.floor(Math.random() * 16);\n\n switch (index) {\n case 8:\n result += '-';\n break;\n case 12:\n value = 4;\n result += '-';\n break;\n case 16:\n value = value & 3 | 8;\n result += '-';\n break;\n case 20:\n result += '-';\n break;\n }\n result += hexcodes[value];\n }\n return result;\n};\n" }, { "answer_id": 21963136, "author": "Jeff Ward", "author_id": 1026023, "author_profile": "https://Stackoverflow.com/users/1026023", "pm_score": 9, "selected": false, "text": "replace() toString() Math.random() generateQuickGUID guid generateQuickGuid Desktop Android\n broofa: 1617ms 12869ms\n e1: 636ms 5778ms\n e2: 606ms 4754ms\n e3: 364ms 3003ms\n e4: 329ms 2015ms\n e5: 147ms 1156ms\n e6: 146ms 1035ms\n e7: 105ms 726ms\n guid: 962ms 10762ms\ngenerateQuickGuid: 292ms 2961ms\n - Note: 500k iterations, results will vary by browser/CPU.\n function broofa() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);\n return v.toString(16);\n });\n}\n\nconsole.log(broofa()) x y 10 - 4 - 4 function e1() {\n var u='',i=0;\n while(i++<36) {\n var c='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'[i-1],r=Math.random()*16|0,v=c=='x'?r:(r&0x3|0x8);\n u+=(c=='-'||c=='4')?c:v.toString(16)\n }\n return u;\n}\n\nconsole.log(e1()) - 4 replace() function e2() {\n var u='',m='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',i=0,rb=Math.random()*0xffffffff|0;\n while(i++<36) {\n var c=m[i-1],r=rb&0xf,v=c=='x'?r:(r&0x3|0x8);\n u+=(c=='-'||c=='4')?c:v.toString(16);rb=i%8==0?Math.random()*0xffffffff|0:rb>>4\n }\n return u\n}\n\nconsole.log(e2()) function e3() {\n var h='0123456789abcdef';\n var k='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';\n /* same as e4() below */\n}\nfunction e4() {\n var h=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];\n var k=['x','x','x','x','x','x','x','x','-','x','x','x','x','-','4','x','x','x','-','y','x','x','x','-','x','x','x','x','x','x','x','x','x','x','x','x'];\n var u='',i=0,rb=Math.random()*0xffffffff|0;\n while(i++<36) {\n var c=k[i-1],r=rb&0xf,v=c=='x'?r:(r&0x3|0x8);\n u+=(c=='-'||c=='4')?c:h[v];rb=i%8==0?Math.random()*0xffffffff|0:rb>>4\n }\n return u\n}\n\nconsole.log(e4()) var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }\nfunction e5() {\n var k=['x','x','x','x','-','x','x','-','4','x','-','y','x','-','x','x','x','x','x','x'];\n var u='',i=0,rb=Math.random()*0xffffffff|0;\n while(i++<20) {\n var c=k[i-1],r=rb&0xff,v=c=='x'?r:(c=='y'?(r&0x3f|0x80):(r&0xf|0x40));\n u+=(c=='-')?c:lut[v];rb=i%4==0?Math.random()*0xffffffff|0:rb>>8\n }\n return u\n}\n\nconsole.log(e5()) r var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }\nfunction e7()\n{\n var d0 = Math.random()*0xffffffff|0;\n var d1 = Math.random()*0xffffffff|0;\n var d2 = Math.random()*0xffffffff|0;\n var d3 = Math.random()*0xffffffff|0;\n return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+\n lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+\n lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+\n lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];\n}\n\nconsole.log(e7()) UUID.generate()" }, { "answer_id": 22223296, "author": "ling", "author_id": 405042, "author_profile": "https://Stackoverflow.com/users/405042", "pm_score": 4, "selected": false, "text": "var getUniqueId = function (prefix) {\n var d = new Date().getTime();\n d += (parseInt(Math.random() * 100)).toString();\n if (undefined === prefix) {\n prefix = 'uid-';\n }\n d = prefix + d;\n return d;\n };\n" }, { "answer_id": 22856022, "author": "Giridhar", "author_id": 1379093, "author_profile": "https://Stackoverflow.com/users/1379093", "pm_score": 2, "selected": false, "text": "function NewGuid()\n{\n var sGuid = \"\";\n for (var i=0; i<32; i++)\n {\n sGuid += Math.floor(Math.random()*0xF).toString(0xF);\n }\n return sGuid;\n}\n" }, { "answer_id": 24891600, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 5, "selected": false, "text": " Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }\n Math.trueRandom = (function() {\n var crypt = window.crypto || window.msCrypto;\n\n if (crypt && crypt.getRandomValues) {\n // If we have a crypto library, use it\n var random = function(min, max) {\n var rval = 0;\n var range = max - min;\n if (range < 2) {\n return min;\n }\n\n var bits_needed = Math.ceil(Math.log2(range));\n if (bits_needed > 53) {\n throw new Exception(\"We cannot generate numbers larger than 53 bits.\");\n }\n var bytes_needed = Math.ceil(bits_needed / 8);\n var mask = Math.pow(2, bits_needed) - 1;\n // 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111\n\n // Create byte array and fill with N random numbers\n var byteArray = new Uint8Array(bytes_needed);\n crypt.getRandomValues(byteArray);\n\n var p = (bytes_needed - 1) * 8;\n for(var i = 0; i < bytes_needed; i++ ) {\n rval += byteArray[i] * Math.pow(2, p);\n p -= 8;\n }\n\n // Use & to apply the mask and reduce the number of recursive lookups\n rval = rval & mask;\n\n if (rval >= range) {\n // Integer out of acceptable range\n return random(min, max);\n }\n // Return an integer that falls within the range\n return min + rval;\n }\n return function() {\n var r = random(0, 1000000000) / 1000000000;\n return r;\n };\n } else {\n // From https://web.archive.org/web/20120502223108/http://baagoe.com/en/RandomMusings/javascript/\n // Johannes Baagøe <baagoe@baagoe.com>, 2010\n function Mash() {\n var n = 0xefc8249d;\n\n var mash = function(data) {\n data = data.toString();\n for (var i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n var h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n };\n\n mash.version = 'Mash 0.9';\n return mash;\n }\n\n // From http://baagoe.com/en/RandomMusings/javascript/\n function Alea() {\n return (function(args) {\n // Johannes Baagøe <baagoe@baagoe.com>, 2010\n var s0 = 0;\n var s1 = 0;\n var s2 = 0;\n var c = 1;\n\n if (args.length == 0) {\n args = [+new Date()];\n }\n var mash = Mash();\n s0 = mash(' ');\n s1 = mash(' ');\n s2 = mash(' ');\n\n for (var i = 0; i < args.length; i++) {\n s0 -= mash(args[i]);\n if (s0 < 0) {\n s0 += 1;\n }\n s1 -= mash(args[i]);\n if (s1 < 0) {\n s1 += 1;\n }\n s2 -= mash(args[i]);\n if (s2 < 0) {\n s2 += 1;\n }\n }\n mash = null;\n\n var random = function() {\n var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n s0 = s1;\n s1 = s2;\n return s2 = t - (c = t | 0);\n };\n random.uint32 = function() {\n return random() * 0x100000000; // 2^32\n };\n random.fract53 = function() {\n return random() +\n (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n };\n random.version = 'Alea 0.9';\n random.args = args;\n return random;\n\n }(Array.prototype.slice.call(arguments)));\n };\n return Alea();\n }\n}());\n\nMath.guid = function() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.trueRandom() * 16 | 0,\n v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n};\n" }, { "answer_id": 28921801, "author": "Andrew", "author_id": 492575, "author_profile": "https://Stackoverflow.com/users/492575", "pm_score": 4, "selected": false, "text": "var uuid = function () {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(\n /[xy]/g,\n function (match) {\n /*\n * Create a random nibble. The two clever bits of this code:\n *\n * - Bitwise operations will truncate floating point numbers\n * - For a bitwise OR of any x, x | 0 = x\n *\n * So:\n *\n * Math.random * 16\n *\n * creates a random floating point number\n * between 0 (inclusive) and 16 (exclusive) and\n *\n * | 0\n *\n * truncates the floating point number into an integer.\n */\n var randomNibble = Math.random() * 16 | 0;\n\n /*\n * Resolves the variant field. If the variant field (delineated\n * as y in the initial string) is matched, the nibble must\n * match the mask (where x is a do-not-care bit):\n *\n * 10xx\n *\n * This is achieved by performing the following operations in\n * sequence (where x is an intermediate result):\n *\n * - x & 0x3, which is equivalent to x % 3\n * - x | 0x8, which is equivalent to x + 8\n *\n * This results in a nibble between 8 inclusive and 11 exclusive,\n * (or 1000 and 1011 in binary), all of which satisfy the variant\n * field mask above.\n */\n var nibble = (match == 'y') ?\n (randomNibble & 0x3 | 0x8) :\n randomNibble;\n\n /*\n * Ensure the nibble integer is encoded as base 16 (hexadecimal).\n */\n return nibble.toString(16);\n }\n );\n};\n" }, { "answer_id": 30474286, "author": "mangalbhaskar", "author_id": 748469, "author_profile": "https://Stackoverflow.com/users/748469", "pm_score": 2, "selected": false, "text": "var createUUID = function() {\n return \"uuid-\" + ((new Date).getTime().toString(16) + Math.floor(1E7*Math.random()).toString(16));\n}\n" }, { "answer_id": 30609091, "author": "robocat", "author_id": 436776, "author_profile": "https://Stackoverflow.com/users/436776", "pm_score": 4, "selected": false, "text": "crypto.getRandomValues(a) Math.random() function uuid() {\n function randomDigit() {\n if (crypto && crypto.getRandomValues) {\n var rands = new Uint8Array(1);\n crypto.getRandomValues(rands);\n return (rands[0] % 16).toString(16);\n } else {\n return ((Math.random() * 16) | 0).toString(16);\n }\n }\n\n var crypto = window.crypto || window.msCrypto;\n return 'xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx'.replace(/x/g, randomDigit);\n}\n" }, { "answer_id": 32005477, "author": "Matthew Riches", "author_id": 780824, "author_profile": "https://Stackoverflow.com/users/780824", "pm_score": 1, "selected": false, "text": "function guid() {\n var chars = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\"];\n var str = \"\";\n for(var i=0; i<36; i++) {\n var str = str + ((i == 8 || i == 13 || i == 18 || i == 23) ? \"-\" : chars[Math.floor(Math.random()*chars.length)]);\n };\n return str;\n}\n" }, { "answer_id": 33092860, "author": "Kyros Koh", "author_id": 4292656, "author_profile": "https://Stackoverflow.com/users/4292656", "pm_score": 6, "selected": false, "text": "npm install uuid\n // Generate a v1 UUID (time-based)\nconst uuidV1 = require('uuid/v1');\nuuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'\n\n// Generate a v4 UUID (random)\nconst uuidV4 = require('uuid/v4');\nuuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'\n\n// Generate a v5 UUID (namespace)\nconst uuidV5 = require('uuid/v5');\n\n// ... using predefined DNS namespace (for domain names)\nuuidV5('hello.example.com', v5.DNS)); // -> 'fdda765f-fc57-5604-a269-52a7df8164ec'\n\n// ... using predefined URL namespace (for, well, URLs)\nuuidV5('http://example.com/hello', v5.URL); // -> '3bbcee75-cecc-5b56-8031-b6641c1ed1f1'\n\n// ... using a custom namespace\nconst MY_NAMESPACE = '(previously generated unique uuid string)';\nuuidV5('hello', MY_NAMESPACE); // -> '90123e1c-7512-523e-bb28-76fab9f2f73d'\n import uuid from 'uuid/v4';\nconst id = uuid();\n" }, { "answer_id": 33363081, "author": "andersh", "author_id": 1838058, "author_profile": "https://Stackoverflow.com/users/1838058", "pm_score": 3, "selected": false, "text": "Guid.raw();\n// -> '6fdf6ffc-ed77-94fa-407e-a7b86ed9e59d'\n const uuidv4 = require('uuid/v4');\nuuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a'\n" }, { "answer_id": 35135400, "author": "MaxPRafferty", "author_id": 1612869, "author_profile": "https://Stackoverflow.com/users/1612869", "pm_score": 2, "selected": false, "text": "function encode(lookup, number) {\n var loopCounter = 0;\n var done;\n\n var str = '';\n\n while (!done) {\n str = str + lookup( ( (number >> (4 * loopCounter)) & 0x0f ) | randomByte() );\n done = number < (Math.pow(16, loopCounter + 1 ) );\n loopCounter++;\n }\n return str;\n}\n\n/* Generates the short id */\nfunction generate() {\n\n var str = '';\n\n var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001);\n\n if (seconds === previousSeconds) {\n counter++;\n } else {\n counter = 0;\n previousSeconds = seconds;\n }\n\n str = str + encode(alphabet.lookup, version);\n str = str + encode(alphabet.lookup, clusterWorkerId);\n if (counter > 0) {\n str = str + encode(alphabet.lookup, counter);\n }\n str = str + encode(alphabet.lookup, seconds);\n\n return str;\n}\n" }, { "answer_id": 36147692, "author": "Ashish Yadav", "author_id": 5928459, "author_profile": "https://Stackoverflow.com/users/5928459", "pm_score": 2, "selected": false, "text": "function generateUUID() {\n var d = new Date();\n var k = d.getTime();\n var str = k.toString(16).slice(1)\n var UUID = 'xxxx-xxxx-4xxx-yxxx-xzx'.replace(/[xy]/g, function (c)\n {\n var r = Math.random() * 16 | 0;\n v = c == 'x' ? r : (r & 3 | 8);\n return v.toString(16);\n });\n\n var newString = UUID.replace(/[z]/, str)\n return newString;\n}\n\nvar x = generateUUID()\nconsole.log(x, x.length)\n" }, { "answer_id": 38903464, "author": "Dustin Poissant", "author_id": 2082141, "author_profile": "https://Stackoverflow.com/users/2082141", "pm_score": 2, "selected": false, "text": "var myGuid = GUID();\n" }, { "answer_id": 39254139, "author": "lugreen", "author_id": 4403281, "author_profile": "https://Stackoverflow.com/users/4403281", "pm_score": 0, "selected": false, "text": "var d = new Date().valueOf();\nvar n = d.toString();\nvar result = '';\nvar length = 32;\nvar p = 0;\nvar chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n\nfor (var i = length; i > 0; --i){\n result += ((i & 1) && n.charAt(p) ? '<b>' + n.charAt(p) + '</b>' : chars[Math.floor(Math.random() * chars.length)]);\n if(i & 1) p++;\n};\n" }, { "answer_id": 39365250, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function randomHex(length) {\n var random_string = '';\n if(!length){\n length = 1;\n }\n for(var i=0; i<length; i+=1){\n random_string += Math.floor(Math.random() * 15).toString(16);\n }\n return random_string;\n}\n\nfunction guid() {\n return randomHex(8);\n}\n" }, { "answer_id": 40066925, "author": "Pablo Pazos", "author_id": 1644320, "author_profile": "https://Stackoverflow.com/users/1644320", "pm_score": 2, "selected": false, "text": "function b(\n a // Placeholder\n){\n var cryptoObj = window.crypto || window.msCrypto; // For Internet Explorer 11\n return a // If the placeholder was passed, return\n ? ( // a random number from 0 to 15\n a ^ // unless b is 8,\n cryptoObj.getRandomValues(new Uint8Array(1))[0] // in which case\n % 16 // a random number from\n >> a/4 // 8 to 11\n ).toString(16) // in hexadecimal\n : ( // or otherwise a concatenated string:\n [1e7] + // 10000000 +\n -1e3 + // -1000 +\n -4e3 + // -4000 +\n -8e3 + // -80000000 +\n -1e11 // -100000000000,\n ).replace( // Replacing\n /[018]/g, // zeroes, ones, and eights with\n b // random hex digits\n )\n}\n" }, { "answer_id": 43901924, "author": "Jonathan Potter", "author_id": 589174, "author_profile": "https://Stackoverflow.com/users/589174", "pm_score": 4, "selected": false, "text": "function uuid() {\n return crypto.getRandomValues(new Uint32Array(4)).join('-');\n}\n 2350143528-4164020887-938913176-2513998651" }, { "answer_id": 44078785, "author": "Simon Rigét", "author_id": 3546836, "author_profile": "https://Stackoverflow.com/users/3546836", "pm_score": 8, "selected": false, "text": "let uniqueId = Date.now().toString(36) + Math.random().toString(36).substring(2);\n document.getElementById(\"unique\").innerHTML =\n Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36); <div id=\"unique\">\n</div> let u = Date.now().toString(16) + Math.random().toString(16) + '0'.repeat(16);\nlet guid = [u.substr(0,8), u.substr(8,4), '4000-8' + u.substr(13,3), u.substr(16,12)].join('-');\n let u = Date.now().toString(16)+Math.random().toString(16)+'0'.repeat(16);\nlet guid = [u.substr(0,8), u.substr(8,4), '4000-8' + u.substr(13,3), u.substr(16,12)].join('-');\ndocument.getElementById(\"unique\").innerHTML = guid; <div id=\"unique\">\n</div>" }, { "answer_id": 44996682, "author": "Behnam", "author_id": 3243488, "author_profile": "https://Stackoverflow.com/users/3243488", "pm_score": 4, "selected": false, "text": "const guid=()=> {\n const s4=()=> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); \n return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;\n}\n" }, { "answer_id": 47475081, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 4, "selected": false, "text": "function uuid4()\n{\n function hex (s, b)\n {\n return s +\n (b >>> 4 ).toString (16) + // high nibble\n (b & 0b1111).toString (16); // low nibble\n }\n\n let r = crypto.getRandomValues (new Uint8Array (16));\n\n r[6] = r[6] >>> 4 | 0b01000000; // Set type 4: 0100\n r[8] = r[8] >>> 3 | 0b10000000; // Set variant: 100\n\n return r.slice ( 0, 4).reduce (hex, '' ) +\n r.slice ( 4, 6).reduce (hex, '-') +\n r.slice ( 6, 8).reduce (hex, '-') +\n r.slice ( 8, 10).reduce (hex, '-') +\n r.slice (10, 16).reduce (hex, '-');\n}\n" }, { "answer_id": 48049791, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 2, "selected": false, "text": "Scriptlet.Typelib WScript.Echo((new ActiveXObject(\"Scriptlet.TypeLib\")).Guid)\n" }, { "answer_id": 53194038, "author": "nomadev", "author_id": 6803744, "author_profile": "https://Stackoverflow.com/users/6803744", "pm_score": 2, "selected": false, "text": "math.random() function uuidv4() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = parseFloat('0.' + Math.random().toString().replace('0.', '') + new Date().getTime()) * 16 | 0,\n v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n" }, { "answer_id": 53564402, "author": "Jacob Ochoa", "author_id": 7081569, "author_profile": "https://Stackoverflow.com/users/7081569", "pm_score": 0, "selected": false, "text": "class uuid extends Uint8Array {\n constructor() {\n super(16)\n /* Not v4, just some random bytes */\n window.crypto.getRandomValues(this)\n }\n toString() {\n let id = new String()\n for (let i = 0; i < this.length; i++) {\n /* Convert uint8 to hex string */\n let hex = this[i].toString(16).toUpperCase()\n\n /* Add zero padding */\n while (hex.length < 2) {\n hex = String(0).concat(hex)\n }\n id += hex\n\n /* Add dashes */\n if (i == 4 || i == 6 || i == 8 || i == 10 || i == 16) {\n id += '-'\n }\n }\n return id\n }\n}\n" }, { "answer_id": 53723395, "author": "Armen Michaeli", "author_id": 254343, "author_profile": "https://Stackoverflow.com/users/254343", "pm_score": 4, "selected": false, "text": "TypedArray DataView const uuid4 = () => {\n const ho = (n, p) => n.toString(16).padStart(p, 0); /// Return the hexadecimal text representation of number `n`, padded with zeroes to be of length `p`\n const data = crypto.getRandomValues(new Uint8Array(16)); /// Fill the buffer with random data\n data[6] = (data[6] & 0xf) | 0x40; /// Patch the 6th byte to reflect a version 4 UUID\n data[8] = (data[8] & 0x3f) | 0x80; /// Patch the 8th byte to reflect a variant 1 UUID (version 4 UUIDs are)\n const view = new DataView(data.buffer); /// Create a view backed by a 16-byte buffer\n return `${ho(view.getUint32(0), 8)}-${ho(view.getUint16(4), 4)}-${ho(view.getUint16(6), 4)}-${ho(view.getUint16(8), 4)}-${ho(view.getUint32(10), 8)}${ho(view.getUint16(14), 4)}`; /// Compile the canonical textual form from the array data\n};\n getRandomValues crypto randomBytes" }, { "answer_id": 54249313, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 3, "selected": false, "text": "yarn add uuid\n const uuidv1 = require('uuid/v1');\nuuidv1(); // ⇨ '45745c60-7b1a-11e8-9c9c-2d42b21b1a3e'\n const v1options = {\n node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],\n clockseq: 0x1234,\n msecs: new Date('2011-11-01').getTime(),\n nsecs: 5678\n};\nuuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'\n" }, { "answer_id": 55219682, "author": "user2226755", "author_id": 2226755, "author_profile": "https://Stackoverflow.com/users/2226755", "pm_score": 2, "selected": false, "text": "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx crypto.getRandomValues(new Uint8Array(1))[0] const uuidv4 = () =>\n ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n );\n\nconsole.log(uuidv4());\n function uuidv4() {\n let bytes = window.crypto.getRandomValues(new Uint8Array(32));\n const randomBytes = () => (bytes = bytes.slice(1)) && bytes[0];\n\n return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n (c ^ randomBytes() & 15 >> c / 4).toString(16)\n );\n}\n\n\nfor (var i = 0; i < 10; i++)\n console.log(uuidv4()); uuidv4() + \".\" + (+new Date())" }, { "answer_id": 58266401, "author": "li x", "author_id": 3342835, "author_profile": "https://Stackoverflow.com/users/3342835", "pm_score": 2, "selected": false, "text": "// We're not yet certain as to how the API will be accessed (whether it's in the global, or a\n// future built-in module), and this will be part of the investigative process as we continue\n// working on the proposal.\nuuid(); // \"52e6953d-edbe-4953-be2e-65ed3836b2f0\"\n const uuidv4 = require('uuid/v4');\nuuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'\n" }, { "answer_id": 61011303, "author": "dgellow", "author_id": 709884, "author_profile": "https://Stackoverflow.com/users/709884", "pm_score": 3, "selected": false, "text": "crypto function genUUID() {\n // Reference: https://stackoverflow.com/a/2117523/709884\n return (\"10000000-1000-4000-8000-100000000000\").replace(/[018]/g, s => {\n const c = Number.parseInt(s, 10)\n return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n })\n}\n + number[] number string number" }, { "answer_id": 61854245, "author": "Bennett Barouch", "author_id": 4139990, "author_profile": "https://Stackoverflow.com/users/4139990", "pm_score": 2, "selected": false, "text": "function random() {\n const\n fourBytesOn = 0xffffffff, // 4 bytes, all 32 bits on: 4294967295\n c = typeof crypto === \"object\"\n ? crypto // Node.js or most browsers\n : typeof msCrypto === \"object\" // Stinky non-standard Internet Explorer\n ? msCrypto // eslint-disable-line no-undef\n : null; // What old or bad environment are we running in?\n return c\n ? c.randomBytes\n ? parseInt(c.randomBytes(4).toString(\"hex\"), 16) / (fourBytesOn + 1) - Number.EPSILON // Node.js\n : c.getRandomValues(new Uint32Array(1))[0] / (fourBytesOn + 1) - Number.EPSILON // Browsers\n : Math.random();\n}\n\nfunction uuidV4() { // eslint-disable-line complexity\n // If possible, generate a single random value, 128 bits (16 bytes)\n // in length. In an environment where that is not possible, generate\n // and make use of four 32-bit (4-byte) random values.\n // Use crypto-grade randomness when available, else Math.random()\n const\n c = typeof crypto === \"object\"\n ? crypto // Node.js or most browsers\n : typeof msCrypto === \"object\" // Stinky non-standard Internet Explorer\n ? msCrypto // eslint-disable-line no-undef\n : null; // What old or bad environment are we running in?\n let\n byteArray = c\n ? c.randomBytes\n ? c.randomBytes(16) // Node.js\n : c.getRandomValues(new Uint8Array(16)) // Browsers\n : null,\n uuid = [ ];\n\n /* eslint-disable no-bitwise */\n if ( ! byteArray) { // No support for generating 16 random bytes\n // in one shot -- this will be slower\n const\n int = [\n random() * 0xffffffff | 0,\n random() * 0xffffffff | 0,\n random() * 0xffffffff | 0,\n random() * 0xffffffff | 0\n ];\n byteArray = [ ];\n for (let i = 0; i < 256; i++) {\n byteArray[i] = int[i < 4 ? 0 : i < 8 ? 1 : i < 12 ? 2 : 3] >> i % 4 * 8 & 0xff;\n }\n }\n byteArray[6] = byteArray[6] & 0x0f | 0x40; // Always 4, per RFC, indicating the version\n byteArray[8] = byteArray[8] & 0x3f | 0x80; // Constrained to [89ab], per RFC for version 4\n for (let i = 0; i < 16; ++i) {\n uuid[i] = (byteArray[i] < 16 ? \"0\" : \"\") + byteArray[i].toString(16);\n }\n uuid =\n uuid[ 0] + uuid[ 1] + uuid[ 2] + uuid[ 3] + \"-\" +\n uuid[ 4] + uuid[ 5] + \"-\" +\n uuid[ 6] + uuid[ 7] + \"-\" +\n uuid[ 8] + uuid[ 9] + \"-\" +\n uuid[10] + uuid[11] + uuid[12] + uuid[13] + uuid[14] + uuid[15];\n return uuid;\n /* eslint-enable no-bitwise */\n}\n" }, { "answer_id": 62166809, "author": "Mohan Ram", "author_id": 524723, "author_profile": "https://Stackoverflow.com/users/524723", "pm_score": 1, "selected": false, "text": "function uuidv4() {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n // tslint:disable-next-line: no-bitwise\n const r =\n (window.crypto.getRandomValues(new Uint32Array(1))[0] *\n Math.pow(2, -32) * 16) |\n 0;\n // tslint:disable-next-line: no-bitwise\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n" }, { "answer_id": 62359248, "author": "Aral Roca", "author_id": 4467741, "author_profile": "https://Stackoverflow.com/users/4467741", "pm_score": 4, "selected": false, "text": "URL.createObjectURL function uuid() {\n const url = URL.createObjectURL(new Blob())\n const [id] = url.toString().split('/').reverse()\n URL.revokeObjectURL(url)\n return id\n}\n" }, { "answer_id": 62840229, "author": "incureforce", "author_id": 3554861, "author_profile": "https://Stackoverflow.com/users/3554861", "pm_score": 2, "selected": false, "text": "let buffer = new Uint8Array(); crypto.getRandomValues let buffer = crypto.randomBytes(16) const hex = '0123456789ABCDEF'\n\nlet generateToken = function() {\n let buffer = new Uint8Array(16)\n\n crypto.getRandomValues(buffer)\n\n buffer[6] = 0x40 | (buffer[6] & 0xF)\n buffer[8] = 0x80 | (buffer[8] & 0xF)\n\n let segments = []\n\n for (let i = 0; i < 16; ++i) {\n segments.push(hex[(buffer[i] >> 4 & 0xF)])\n segments.push(hex[(buffer[i] >> 0 & 0xF)])\n\n if (i == 3 || i == 5 || i == 7 || i == 9) {\n segments.push('-')\n }\n }\n\n return segments.join('')\n}\n\nfor (let i = 0; i < 100; ++i) {\n console.log(generateToken())\n}" }, { "answer_id": 63313690, "author": "Yudner", "author_id": 8185493, "author_profile": "https://Stackoverflow.com/users/8185493", "pm_score": 0, "selected": false, "text": "var guid = createMyGuid();\n\nfunction createMyGuid() \n{ \n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { \n var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); \n return v.toString(16); \n }); \n}\n" }, { "answer_id": 63344366, "author": "tarkh", "author_id": 10917379, "author_profile": "https://Stackoverflow.com/users/10917379", "pm_score": 1, "selected": false, "text": "date.now() process.hrtime.bigint() 10000-90000 /*\n * uuid-timestamp (emitter)\n * UUID v4 based on timestamp\n *\n * Created by tarkh\n * tarkh.com (C) 2020\n */\nconst uuidEmit = () => {\n // Get now time\n const n = Date.now();\n // Generate random\n const r = Math.random();\n // Stringify now time and generate additional random number\n const s = String(n) + String(~~(r*9e4)+1e4);\n // Form UUID and return it\n return `${s.slice(0,8)}-${s.slice(8,12)}-4${s.slice(12,15)}-${[8,9,'a','b'][~~(r*3)]}${s.slice(15,18)}-${s.slice(s.length-12)}`;\n};\n\n// Generate 5 UUIDs\nconsole.log(`${uuidEmit()}\n${uuidEmit()}\n${uuidEmit()}\n${uuidEmit()}\n${uuidEmit()}`); /*\n * uuid-timestamp (parser)\n * UUID v4 based on timestamp\n *\n * Created by tarkh\n * tarkh.com (C) 2020\n */\nconst uuidParse = (uuid) => {\n // Get current timestamp string length\n let tl = String(Date.now()).length;\n // Strip out timestamp from UUID\n let ts = '';\n let i = -1;\n while(tl--) {\n i++;\n if(i===8||i===13||i===14||i===18||i===19||i===23) {\n tl++;\n continue;\n }\n ts += uuid[i];\n }\n return Number(ts);\n};\n\n// Get the timestamp when UUID was emitted\nconst time = uuidParse('15970688-7109-4530-8114-887109530114');\n\n// Covert timestamp to date and print it\nconsole.log(new Date(time).toUTCString()); nanoseconds process.hrtime.bigint()" }, { "answer_id": 63939316, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 1, "selected": false, "text": "function guid()\n{\n function s4()\n {\n return Math.floor(Math.random() * 65536).toString(16).padStart(4, '0')\n } // End Function s4\n\n return s4() + s4() + '-' + s4() + '-' + \"4\" + s4().substr(1) + '-' + s4() + '-' + s4() + s4() + s4();\n} // End Function guid\n function cryptGuid()\n{\n var array = new Uint16Array(8);\n (window.crypto || window.msCrypto).getRandomValues(array);\n var dataView = new DataView(array.buffer);\n\n var parts = [];\n\n for(var i = 0; i < array.length; ++i)\n {\n // 0&1,2,3,4,5-7 dataView.getUint16(0-7)\n if(i>1 && i<6) parts.push(\"-\");\n parts.push(dataView.getUint16(i).toString(16).padStart(4, '0'));\n }\n\n parts[5] = \"4\" + parts[5].substr(1);\n // console.log(parts);\n return parts.join('').toUpperCase();// .toLowerCase();\n}\n\ncryptGuid();\n" }, { "answer_id": 64976228, "author": "skalee", "author_id": 304175, "author_profile": "https://Stackoverflow.com/users/304175", "pm_score": 3, "selected": false, "text": "function uuid4() {\n let array = new Uint8Array(16)\n crypto.randomFillSync(array)\n\n // Manipulate the 9th byte\n array[8] &= 0b00111111 // Clear the first two bits\n array[8] |= 0b10000000 // Set the first two bits to 10\n\n // Manipulate the 7th byte\n array[6] &= 0b00001111 // Clear the first four bits\n array[6] |= 0b01000000 // Set the first four bits to 0100\n\n const pattern = \"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\"\n let idx = 0\n\n return pattern.replace(\n /XX/g,\n () => array[idx++].toString(16).padStart(2, \"0\"), // padStart ensures a leading zero, if needed\n )\n}\n function uuid4() {\n let array = new Uint8Array(16)\n crypto.getRandomValues(array)\n\n // Manipulate the 9th byte\n array[8] &= 0b00111111 // Clear the first two bits\n array[8] |= 0b10000000 // Set the first two bits to 10\n\n // Manipulate the 7th byte\n array[6] &= 0b00001111 // Clear the first four bits\n array[6] |= 0b01000000 // Set the first four bits to 0100\n\n const pattern = \"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\"\n let idx = 0\n\n return pattern.replace(\n /XX/g,\n () => array[idx++].toString(16).padStart(2, \"0\"), // padStart ensures a leading zero, if needed\n )\n}\n describe(\".uuid4()\", function() {\n it(\"returns a UUIDv4 string\", function() {\n const uuidPattern = \"XXXXXXXX-XXXX-4XXX-YXXX-XXXXXXXXXXXX\"\n const uuidPatternRx = new RegExp(uuidPattern.\n replaceAll(\"X\", \"[0-9a-f]\").\n replaceAll(\"Y\", \"[89ab]\"))\n\n for (let attempt = 0; attempt < 1000; attempt++) {\n let retval = uuid4()\n expect(retval.length).toEqual(36)\n expect(retval).toMatch(uuidPatternRx)\n }\n })\n})\n" }, { "answer_id": 65500983, "author": "smallscript", "author_id": 7859952, "author_profile": "https://Stackoverflow.com/users/7859952", "pm_score": 2, "selected": false, "text": "uuid BigInt uuid primaryKey code class Xuid class Xuid class Xuid uuid console.log(Xuid.v4New) {1eb4a659-8bdc-4ce0-c002-b1d505d38ea8} class Xuid {\n //@ edges.sm.st, ess.dev: MIT license Smallscript/David Simmons 2020\n //! Can't use `static const field = const` xbrowser (thus, const's duped)\n static get v4New() {\n const ns7Now = this.ns7Now, xnode48 = this.xnode48; let clock_seq13\n // monotonic `clock_seq` guarantee (13-bits/time-quantum)\n if(ns7Now <= this.ns7Now_prevSeq && this.ns7Now_prevSeq)\n clock_seq13 = ((this.ns7Now_prevSeq += 1n) - ns7Now) & 0b1_1111_1111_1111n\n else\n clock_seq13 = 0n, this.ns7Now_prevSeq = ns7Now\n const time60 = ((ns7Now << 4n) & 0xFFFF_FFFF_FFFF_0000n) |\n (ns7Now & 0x0000_0000_0000_0FFFn),\n v4 = 0x1_00000000_0000_0000_0000_000000000000n |\n (time60 << 64n) | (0x00000000_0000_4000_0000_000000000000n) | // M: V4\n (0b110n << 61n) | (clock_seq13 << 48n) | // N: Variant-2 time-seq collation\n xnode48, s = v4.toString(16)//.substr(1)\n return `{${s.substr(1,8)}-${s.substr(9,4)}-${s.substr(13,4)}-${\n s.substr(17,4)}-${s.substr(21,12)}}`\n }\n static get xnode48()/*:<BigInt#48>*/{\n if(this.xnode48_) return this.xnode48_\n let clockSeqNode; if(typeof URL !== 'undefined' && URL.createObjectURL) {\n const url = URL.createObjectURL(new Blob())\n const id = (url.toString().split('/').reverse()[0]).split('-')\n URL.revokeObjectURL(url)\n clockSeqNode = BigInt('0x'+id[3]+id[4])\n }\n else {\n const a4 = this.a4; this.getRandomValues(this.a4);\n clockSeqNode = (BigInt(a4[2]) << 32n) | BigInt(a4[3])\n }\n // simulate the 48-bit node-id and 13-bit clock-seq\n // to combine with 3-bit uuid-variant\n return this.xnode48_ = clockSeqNode & 0xFFFF_FFFF_FFFFn;\n }\n static get jdNow()/*:<double#ns7>*/{\n // return 2440587.5+Date.now()/864e5 // <- Date-quantum-ms form (7ns form below)\n return this.jdFromNs7(this.ns7Now)\n }\n static get ns7Now()/*:<BigInt#60>*/{\n if(typeof performance !== 'undefined' && performance.now)\n Reflect.defineProperty(this, 'ns7Now',\n Reflect.getOwnPropertyDescriptor(this,'ns7Now_performance'))\n else\n Reflect.defineProperty(this, 'ns7Now',\n Reflect.getOwnPropertyDescriptor(this, 'ns7Now_Date'))\n return this.ns7Now\n }\n static get ns7Now_Date()/*:<BigInt#60>*/{\n // const epoch1582Ns7_bias = 0x1b2_1dd2_1381_4000 // V1 1582 Oct 15\n // const epoch1601Ns7_bias = 0x19d_b1de_d53e_8000n // FILETIME base\n const epoch1970Ns7 = BigInt(Date.now() * 1000_0.0)\n return epoch1970Ns7 + 0x1b2_1dd2_1381_4000n\n }\n static get ns7Now_performance()/*:<BigInt#60>*/{\n const epochPgNs7 = BigInt(performance.now()*/*15*/1000_0.0|/*17*/0)\n if(!this.epoch1970PgNs7) // performance.timing.navigationStart\n this.epoch1970PgNs7 = this.ns7Now_Date - epochPgNs7\n return epochPgNs7 + this.epoch1970PgNs7\n }\n static dateFromJd(jd) {return new Date((jd - 2440587.5) * 864e5)}\n static dateFromNs7(ns7) {\n return new Date(Number(ns7 - 0x1b2_1dd2_1381_4000n) / 1000_0.0)}\n static jdFromNs7(ns7) { // atomic-clock leap-seconds (ignored)\n return 2440587.5 + (Number(ns7 - 0x1b2_1dd2_1381_4000n) / 864e9)\n }\n static ns7FromJd(jd) {\n return BigInt((jd - 2440587.5) * 864e9) + 0x1b2_1dd2_1381_4000n\n }\n static getRandomValues(va/*:<Uint32Array>*/) {\n if(typeof crypto !== 'undefined' && crypto.getRandomValues)\n crypto.getRandomValues(va)\n else for(let i = 0, n = va.length; i < n; i += 1)\n va[i] = Math.random() * 0x1_0000_0000 >>> 0\n }\n static get a4() {return this.a4_ || (this.a4_ = new Uint32Array(4))}\n static ntohl(v)/*:<BigInt>*/{\n let r = '0x', sign = 1n, s = BigInt(v).toString(16)\n if(s[0] == '-') s = s.substr(1), sign = -1n\n for(let i = s.length; i > 0; i -= 2)\n r += (i == 1) ? ('0' + s[i-1]) : s[i-2] + s[i-1]\n return sign*BigInt(r)\n }\n static ntohl32(v)/*:<Number>*/{return Number(this.ntohl(v))}\n}\n uuid uuid uuid uuid BigInt 80 loc class uuid time context time context uuid time JavaScript EdgeS ESS es6 class uuid time ntohl BigInt Xuid guid uuid uid git fossil SqLite FILETIME {1eb4a659-8bdc-4ce0-c002-b1d505d38ea8} object stores uuid primaryKey uuid time put efs service-worker cloud-server eswc efs sync replicate uuid const start = Xuid.ns7Now\nfor(let i = 100000; i; i -=1)\n Xuid.v4New\nconst end = Xuid.ns7Now\nconsole.log(`Delta 7ns: ${(end-start)/100000n}`)\n uuid" }, { "answer_id": 65893503, "author": "domaci_a_nas", "author_id": 1624339, "author_profile": "https://Stackoverflow.com/users/1624339", "pm_score": 2, "selected": false, "text": "currentNanoseconds = () => {\n return nodeMode ? process.hrtime.bigint() : BigInt(Date.now() * 1000000);\n}\n\nnodeFindMacAddress = () => {\n // Extract MAC address\n const interfaces = require('os').networkInterfaces();\n let result = null;\n for (index in interfaces) {\n let entry = interfaces[index];\n entry.forEach(item => {\n if (item.mac !== '00:00:00:00:00:00') {\n result = '-' + item.mac.replace(/:/g, '');\n }\n });\n }\n return result;\n}\n\nconst nodeMode = typeof(process) !== 'undefined';\nlet macAddress = nodeMode ? nodeFindMacAddress() : '-a52e99ef5efc';\nlet startTime = currentNanoseconds();\n\n\nlet uuids = []; // Array for storing generated UUIDs, useful for testing\nlet currentTime = null; // Holds the last value of Date.now(), used as a base for generating the UUID\nlet timePart = null; // Part of the UUID generated from Date.now()\nlet counter = 0; // Used for counting records created at certain millisecond\nlet lastTime = null; // Used for resetting the record counter\n\nconst limit = 1000000;\n\nfor (let testCounter = 0; testCounter < limit; testCounter++) {\n let uuid = testMe();\n\n if (nodeMode || testCounter <= 50) {\n uuids.push(uuid);\n }\n}\n\nconst timePassed = Number(currentNanoseconds() - startTime);\n\nif (nodeMode) {\n const fs = require('fs');\n fs.writeFileSync('temp.txt', JSON.stringify(uuids).replace(/,/g, ',\\n'));\n} else {\n console.log(uuids);\n}\n\nconsole.log({\n operationsPerSecond: (1000 * limit / timePassed).toString() + 'm',\n nanosecondsPerCycle: timePassed / limit,\n milliSecondsPassed: timePassed / 1000000,\n microSecondsPassed: timePassed / 1000,\n nanosecondsPassed: timePassed\n});\n\nfunction testMe() {\n currentTime = Date.now();\n let uuid = null; // Function result\n\n if (currentTime !== lastTime) {\n // Added a 9 before timestamp, so that the hex-encoded timestamp is 12 digits long. Currently, it is 11 digits long, and it will be until 2527-06-24\n // console.log(Date.parse(\"2527-06-24\").toString(16).length)\n // Code will stop working on 5138-11-17, because the timestamp will be 15 digits long, and the code only handles up to 14 digit timestamps\n // console.log((Date.parse(\"5138-11-17\")).toString().length)\n timePart = parseInt(('99999999999999' + currentTime).substr(-14)).toString(16);\n timePart = timePart.substr(0, 8) + '-' + timePart.substr(8, 4) + '-1';\n counter = 0;\n }\n\n randomPart = ('000000' + Math.floor(10 * (counter + Math.random()))).slice(-6);\n randomPart = randomPart.substr(0, 3) + '-a' + randomPart.substr(3, 3);\n uuid = timePart + randomPart + macAddress;\n\n counter++;\n\n lastTime = currentTime;\n\n return uuid;\n}" }, { "answer_id": 66085896, "author": "vanowm", "author_id": 2930038, "author_profile": "https://Stackoverflow.com/users/2930038", "pm_score": 2, "selected": false, "text": "function stringToUUID (str)\n{\n if (str === undefined || !str.length)\n str = \"\" + Math.random() * new Date().getTime() + Math.random();\n\n let c = 0,\n r = \"\";\n\n for (let i = 0; i < str.length; i++)\n c = (c + (str.charCodeAt(i) * (i + 1) - 1)) & 0xfffffffffffff;\n\n str = str.substr(str.length / 2) + c.toString(16) + str.substr(0, str.length / 2);\n for(let i = 0, p = c + str.length; i < 32; i++)\n {\n if (i == 8 || i == 12 || i == 16 || i == 20)\n r += \"-\";\n\n c = p = (str[(i ** i + p + 1) % str.length]).charCodeAt(0) + p + i;\n if (i == 12)\n c = (c % 5) + 1; //1-5\n else if (i == 16)\n c = (c % 4) + 8; //8-B\n else\n c %= 16; //0-F\n\n r += c.toString(16);\n }\n return r;\n}\n\nconsole.log(\"Random :\", stringToUUID());\nconsole.log(\"Static [1234]:\", stringToUUID(\"1234\")); //29c2c73b-52de-4344-9cf6-e6da61cb8656\nconsole.log(\"Static [test]:\", stringToUUID(\"test\")); //e39092c6-1dbb-3ce0-ad3a-2a41db98778c" }, { "answer_id": 66332305, "author": "Tikolu", "author_id": 3672036, "author_profile": "https://Stackoverflow.com/users/3672036", "pm_score": 5, "selected": false, "text": "window.URL.createObjectURL(new Blob([])).substring(31);\n URL.createObjectURL(new Blob([])).substr(-36);\n" }, { "answer_id": 66574022, "author": "Fernando Teles", "author_id": 1298007, "author_profile": "https://Stackoverflow.com/users/1298007", "pm_score": 3, "selected": false, "text": "function createGuid(){ \n let S4 = () => Math.floor((1+Math.random())*0x10000).toString(16).substring(1); \n let guid = `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;\n \n return guid.toLowerCase(); \n}\n" }, { "answer_id": 68004446, "author": "unsynchronized", "author_id": 830899, "author_profile": "https://Stackoverflow.com/users/830899", "pm_score": 2, "selected": false, "text": "function newId(base) {\nreturn[\n Math.random,\n function (){ return (newId.last ? windowId.last + Math.random() : Math.random() ) },\n Math.random,\n Date.now,\n Math.random\n].map(function(fn){\n return fn().toString(base||(16+(Math.random()*20))).substr(-8);\n}).join('-');\n}\n\nvar demo = function(base){\n document.getElementById('uuid').textContent = newId(base);\n}\ndemo(16); #uuid { font-family: monospace; font-size: 1.5em; } <p id=\"uuid\"></p>\n<button onclick=\"demo(16);\">Hex (base 16)</button>\n<button onclick=\"demo(36);\">Base 36</button>\n<button onclick=\"demo(10);\">Decimal (base 10)</button>\n<button onclick=\"demo();\">Random base</button>" }, { "answer_id": 68141099, "author": "blubberdiblub", "author_id": 794539, "author_profile": "https://Stackoverflow.com/users/794539", "pm_score": 3, "selected": false, "text": "crypto.getRandomValues function uuidv4() {\n const a = crypto.getRandomValues(new Uint16Array(8));\n let i = 0;\n return '00-0-4-1-000'.replace(/[^-]/g, \n s => (a[i++] + s * 0x10000 >> s).toString(16).padStart(4, '0')\n );\n}\n\nconsole.log(uuidv4()); Math.random function uuidv4() {\n return '00-0-4-1-000'.replace(/[^-]/g,\n s => ((Math.random() + ~~s) * 0x10000 >> s).toString(16).padStart(4, '0')\n );\n}\n\nconsole.log(uuidv4());" }, { "answer_id": 68990167, "author": "Explosion", "author_id": 14197829, "author_profile": "https://Stackoverflow.com/users/14197829", "pm_score": 2, "selected": false, "text": "function uuid(){\n var u = URL.createObjectURL(new Blob([\"\"]))\n URL.revokeObjectURL(u);\n return u.split(\"/\").slice(-1)[0]\n}\n" }, { "answer_id": 69237064, "author": "Pier-Luc Gendreau", "author_id": 1779688, "author_profile": "https://Stackoverflow.com/users/1779688", "pm_score": 4, "selected": false, "text": "import * as crypto from \"crypto\";\n\nconst uuid = crypto.randomUUID();\n crypto.randomUUID()" }, { "answer_id": 69307671, "author": "Armen Michaeli", "author_id": 254343, "author_profile": "https://Stackoverflow.com/users/254343", "pm_score": 1, "selected": false, "text": "URL.createObjectURL const uuid = url => url.substr(-36);\n createObjectURL createObjectURL new Blob() revokeObjectURL createObjectURL" }, { "answer_id": 69613170, "author": "Slava", "author_id": 10567223, "author_profile": "https://Stackoverflow.com/users/10567223", "pm_score": 1, "selected": false, "text": "export function makeId(length) {\n let result = '';\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n const charactersLength = characters.length;\n\n for (let i = 0; i < length; i++) {\n let letterPos = crypto.getRandomValues(new Uint8Array(1))[0] / 255 * charactersLength - 1\n result += characters[letterPos]\n }\n return result;\n}\n" }, { "answer_id": 70719021, "author": "Hashbrown", "author_id": 2518317, "author_profile": "https://Stackoverflow.com/users/2518317", "pm_score": -1, "selected": false, "text": "RFC4122 random.org crypto Math.random() async function UUID() {\n //get 31 random hex characters\n return (await (async () => {\n let output;\n try {\n //try from random.org\n output = (await (\n await fetch('https://www.random.org/integers/?num=31&min=0&max=15&col=31&base=16&format=plain&rnd=new')\n ).text())\n //get rid of whitespace\n .replace(/[^0-9a-fA-F]+/g, '')\n ;\n if (output.length != 31)\n throw '';\n }\n catch {\n output = '';\n try {\n //failing that, try getting 16 8-bit digits from crypto\n for (let num of crypto.getRandomValues(new Uint8Array(16)))\n //interpret as 32 4-bit hex numbers\n output += (num >> 4).toString(16) + (num & 15).toString(16);\n //we only want 31\n output = output.substr(1);\n }\n catch {\n //failing THAT, use Math.random\n while (output.length < 31)\n output += (0 | Math.random() * 16).toString(16);\n }\n }\n return output;\n })())\n //split into appropriate sections, and set the 15th character to 4\n .replace(/^(.{8})(.{4})(.{3})(.{4})/, '$1-$2-4$3-$4-')\n //force character 20 to the correct range\n .replace(/(?<=-)[^89abAB](?=[^-]+-[^-]+$)/, (num) => (\n (parseInt(num, 16) % 4 + 8).toString(16)\n ))\n ;\n}\n" }, { "answer_id": 71014981, "author": "Rambler", "author_id": 9136717, "author_profile": "https://Stackoverflow.com/users/9136717", "pm_score": 2, "selected": false, "text": "const { v4: uuidv4 } = require('uuid');\nuuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4926/" ]
105,075
<p>I'd like to run a long rsync command in Cygwin by double clicking on a .sh file in Windows. It must start in the file's containing directory (e.g. /cygdrive/c/scripts/) so that relative paths work. Anyone gotten this to work?</p> <p>Note: I've just found <a href="http://web.archive.org/web/20121204091631/http://blog.chavez.ws:80/2008/03/cygwin-command-here.html" rel="nofollow noreferrer">here</a>, a Cygwin package that manages Windows context menus (Bash Prompt Here). It might have some clues.</p>
[ { "answer_id": 105304, "author": "Vladimir", "author_id": 9641, "author_profile": "https://Stackoverflow.com/users/9641", "pm_score": 0, "selected": false, "text": ".bat go.sh @echo off\n\nC:\nchdir C:\\cygwin\\bin\n\nbash --login -i ./go.sh\n" }, { "answer_id": 105364, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 1, "selected": false, "text": "cd `dirname \"$0\"`\n" }, { "answer_id": 105395, "author": "David", "author_id": 7360, "author_profile": "https://Stackoverflow.com/users/7360", "pm_score": 2, "selected": false, "text": "$ cat test.bat\n@echo off\n\nset MYDIR=C:\\scripts\n\nC:\\cygwin\\bin\\bash --login -c \"cd $MYDIR && echo 'Now in' `pwd`; sleep 15\"\n" }, { "answer_id": 106069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "c:\\>assoc .jpg\n.jpg=jpegfile\n\nc:\\>ftype jpegfile\njpegfile=\"C:\\Program Files\\Common Files\\Microsoft Shared\\PhotoEd\\PHOTOED.EXE\" \"%1\"\n\nassoc .sh=bashscript\n\nftype bashscript=\"c:\\cygwin\\bin\\bash.exe\" \"%1\"\n ftype cygwin" }, { "answer_id": 620913, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "assoc .sh=bashscript\n\nftype bashscript=C:\\cygwin\\bin\\bash.exe --login -i -c 'cd \"$(dirname \"$(cygpath -u \"%1\")\")\"; bash \"$(cygpath -u \"%1\")\"'\n" }, { "answer_id": 2378545, "author": "HaveAGuess", "author_id": 57344, "author_profile": "https://Stackoverflow.com/users/57344", "pm_score": 1, "selected": false, "text": "C:\\Dev\\scripts\\cygbashrun.bat\n SET CYGWIN=nodosfilewarning\nC:\\Cygwin\\bin\\putty.exe -cygterm /bin/bash.exe %1\n" }, { "answer_id": 2735729, "author": "eomanis", "author_id": 328646, "author_profile": "https://Stackoverflow.com/users/328646", "pm_score": 3, "selected": false, "text": "echo Registering .sh and .bash files as \"bashscript\"...\nassoc .sh=bashscript\nassoc .bash=bashscript\necho.\necho Setting the run command for the file type \"bashscript\"...\nftype bashscript=C:\\cygwin\\bin\\bash.exe --login -i -c 'cd \"$(dirname \"$(cygpath -u \"%%1\")\")\"; bash \"$(cygpath -u \"%%1\")\" \"$(/argshandler.sh \"%%2\")\"'\necho.\necho Activating the drag^&drop capability for \"bashscript\" files (only 1 dropped item\necho will be passed to the script, multiple items are not supported yet)...\nreg add HKEY_CLASSES_ROOT\\bashscript\\shellex\\DropHandler /v \"\" /t REG_SZ /d \"{60254CA5-953B-11CF-8C96-00AA00B8708C}\" /f\n #!/bin/bash\nif [ ! \"$1\" == \"\" ]\nthen\n cygpath -u \"$1\"\nfi\n \"cygpathed-arg1\" \"cygpathed-arg2\" \"cygpathed-arg3\"\n ...; bash \"$(cygpath -u \"%%1\")\" $(/argshandler.sh \"%%2\" \"%%3\" ... \"%%9\")'\n" }, { "answer_id": 6609029, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 1, "selected": false, "text": " Windows Registry Editor Version 5.00\n ;File:ConfigureShToBeRunUnderExplorer.reg v:1.0 docs at the end\n [HKEY_CLASSES_ROOT\\Applications\\bash.exe] \n\n [HKEY_CLASSES_ROOT\\Applications\\bash.exe\\shell]\n\n [HKEY_CLASSES_ROOT\\Applications\\bash.exe\\shell\\open]\n\n [HKEY_CLASSES_ROOT\\Applications\\bash.exe\\shell\\open\\command]\n @=\"C:\\\\cygwin\\\\bin\\\\bash.exe -li \\\"%1\\\" %*\"\n\n ; This is a simple registry file to automate the execution of sh via cygwin on windows 7, might work on other Windows versions ... not tested \n ; you could add this setting by issueing the following command: reg import ConfigureShToBeRunUnderExplorer.reg \n ; Note the path of your bash.exe\n ; Note that you still have to add the .sh to your %PATHTEXT%\n ; usage: double - click the file or reg import file \n" }, { "answer_id": 24756123, "author": "Johnny Wong", "author_id": 1323552, "author_profile": "https://Stackoverflow.com/users/1323552", "pm_score": 0, "selected": false, "text": "@echo off\nREM Info: A script created by Johnny Wong. (last modified on 2014-7-15)\nREM It is used to pass a file argument to run a bash script file. The current directory is setting to the path of the script file for convenience.\nREM Could be copied to C:\\cygwin; and then you manually associate .cygwin file extension to open with this .bat file.\nset CYGWIN=nodosfilewarning\n\nC:\\cygwin\\bin\\bash --login -i -c 'cd \"`dirname \"%~1\"`\"; exec bash \"%~1\" %2 %3 %4 %5 %6 %7 %8 %9'\n\nREM finally pause the script (press any key to continue) to keep the window to see result\npause\n for %%a in (%p%) do set p=%%~a \"%~1\"" }, { "answer_id": 32011443, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "\"C:\\cygwin\\bin\\mintty.exe\" -w max -h always -t \"%1\" -e /bin/bash -li -c 'cd \"$(dirname \"$(cygpath -u \"%1\")\")\" && bash \"$(cygpath -u \"%1\")\"'\n \"C:\\cygwin\\bin\\mintty.exe\" -w max -h always -t \"%1\" -e /bin/bash -li -c 'printf \"\\033]0;$(cygpath -u \"%1\")\\007\" && cd \"$(dirname \"$(cygpath -u \"%1\")\")\" && bash \"$(cygpath -u \"%1\")\"'\n @echo off\nassoc .sh=shellscript\nftype shellscript=\"C:\\cygwin\\bin\\mintty.exe\" -w max -h always -t \"%%1\" -e /bin/bash -li -c 'cd \"$(dirname \"$(cygpath -u \"%%1\")\")\" ^&^& bash \"$(cygpath -u \"%%1\")\"'\npause\n @echo off\nassoc .sh=shellscript\nftype shellscript=\"C:\\cygwin\\bin\\mintty.exe\" -w max -h always -t \"%%1\" -e /bin/bash -li -c 'printf \"\\033]0;$(cygpath -u \"%%1\")\\007\" ^&^& cd \"$(dirname \"$(cygpath -u \"%%1\")\")\" ^&^& bash \"$(cygpath -u \"%%1\")\"'\npause\n" }, { "answer_id": 52270726, "author": "Light93", "author_id": 2049786, "author_profile": "https://Stackoverflow.com/users/2049786", "pm_score": 2, "selected": false, "text": "C:\\cygwin64\\bin\\mintty.exe [Computer\\HKEY_CLASSES_ROOT\\Applications\\mintty.exe\\shell\\open\\command]\n C:\\cygwin64\\bin\\mintty.exe -t \"%1\" /bin/bash -l -i -c \"v1=\\\"$(cygpath -u \\\"%0\\\" -a)\\\" && v2=\\\"$(dirname \\\"$v1\\\")\\\" && cd \\\"$v2\\\" ; exec bash \\\"%1\\\" %*\" \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1701/" ]
105,095
<p>If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?</p> <p>If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?</p> <p>sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines. </p> <p>same thing would apply to any other language implementation that has a GIL.</p>
[ { "answer_id": 105369, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 7, "selected": true, "text": "#!/usr/bin/env python\nimport threading\n\nshared_balance = 0\n\nclass Deposit(threading.Thread):\n def run(self):\n for _ in xrange(1000000):\n global shared_balance\n balance = shared_balance\n balance += 100\n shared_balance = balance\n\nclass Withdraw(threading.Thread):\n def run(self):\n for _ in xrange(1000000):\n global shared_balance\n balance = shared_balance\n balance -= 100\n shared_balance = balance\n\nthreads = [Deposit(), Withdraw()]\n\nfor thread in threads:\n thread.start()\n\nfor thread in threads:\n thread.join()\n\nprint shared_balance\n balance = shared_balance shared_balance = balance" }, { "answer_id": 385446, "author": "jimx", "author_id": 47606, "author_profile": "https://Stackoverflow.com/users/47606", "pm_score": 0, "selected": false, "text": "class Withdraw(threading.Thread): \ndef run(self): \n for _ in xrange(1000000): \n global shared_balance \n if shared_balance >= 100:\n balance = shared_balance\n balance -= 100 \n shared_balance = balance\n" }, { "answer_id": 385887, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "1 a += b\n2 a *= 3\n3 b = a\n b = 5\n" }, { "answer_id": 20408373, "author": "Akshar Raaj", "author_id": 839549, "author_profile": "https://Stackoverflow.com/users/839549", "pm_score": 2, "selected": false, "text": "#increment value\nglobal var\nread_var = var\nvar = read_var + 1\n read_var = var read_var = var read_var = var var = read_var+1 var = read_var+1 var" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ]
105,100
<p>What is the difference between display:block and display:inline</p>
[ { "answer_id": 105126, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 2, "selected": false, "text": "<p> * none - no display at all.\n* inline - An inline box.\n* block - A block box.\n* inline-block - effectively a block box inside an inline box. Not supported by Mozilla at time of writing. IE will only apply inline-block to elements that are traditionally inline such as span or a but not p or div. Loopy.\n* run-in - Either an inline or block box depending on the context. If a block box follows the run-in box, the run-in box becomes the first inline box of that block box, otherwise it becomes a block box itself. Crazy. Not supported by IE/Win or Mozilla at the time of writing.\n* list-item - the equivalent of the default styling of the HTML li element.\n* table - a block-level table - the equivalent of the default styling of the HTML table element. Not supported by IE.\n* inline-table - an inline-level table. Not supported by IE.\n* table-row-group - the equivalent of the default styling of the HTML tbody element. Not supported by IE.\n* table-header-group - the equivalent of the default styling of the HTML thead element. Not supported by IE.\n* table-footer-group - the equivalent of the default styling of the HTML tfoot element. Not supported by IE.\n* table-row - the equivalent of the default styling of the HTML tr element. Not supported by IE.\n* table-column-group - the equivalent of the default styling of the HTML colgroup element. Not supported by IE.\n* table-column - the equivalent of the default styling of the HTML col element. Not supported by IE.\n* table-cell - the equivalent of the default styling of the HTML td or th elements. Not supported by IE.\n* table-caption - the equivalent of the default styling of the HTML caption element. Not supported by IE.\n" }, { "answer_id": 105210, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "display: block display: inline display: table" }, { "answer_id": 105246, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 1, "selected": false, "text": "float float" }, { "answer_id": 35533479, "author": "Sim13", "author_id": 5957934, "author_profile": "https://Stackoverflow.com/users/5957934", "pm_score": 0, "selected": false, "text": "display: block\n display: inline-block\n display: inline-block" }, { "answer_id": 66956153, "author": "Bonny", "author_id": 11565236, "author_profile": "https://Stackoverflow.com/users/11565236", "pm_score": 0, "selected": false, "text": "h1{\n background-color:yellow;\n}\n\nspan{\n background-color:lightpink;\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <link rel=\"stylesheet\" href=\"style.css\">\n <title>Document</title>\n</head>\n<body>\n <h1>This is heading 1</h1>\n <h1> This is heading 2</h1>\n\n <span>Span1</span>\n <span>Span2</span>\n</body>\n</html> h1{\n background-color:yellow;\n display:inline;\n}\n\nspan{\n background-color:lightpink;\n display:block;\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <link rel=\"stylesheet\" href=\"style.css\">\n <title>Document</title>\n</head>\n<body>\n <h1>This is heading 1</h1>\n <h1> This is heading 2</h1>\n\n <span>Span1</span>\n <span>Span2</span>\n</body>\n</html>" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
105,113
<p>Most of us have already used the casual patterns such as <a href="https://stackoverflow.com/questions/26685/what-is-mvc-and-what-are-the-advantages-of-it">MVC</a>, <a href="https://stackoverflow.com/questions/91932?sort=votes#sort-top">strategy</a>, etc.</p> <p>But there must be some unusual solutions to unusual problems, and I'd like to hear about it.</p>
[ { "answer_id": 105188, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 3, "selected": false, "text": "char getNextChar(char previous) {\n\nswitch (previous)\ncase 'a': return b;\ncase 'b': return c;\n...\ncase 'z': return a;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
105,121
<p>Is there any way to capture the trace statements of your Flex app while not running in debug mode?</p> <p>Or is there any other way to output logging information when not running a debugger?</p> <p>Currently I'm trying to fix a bug that only presents itself in very specific deployment scenario, but I could see this being useful in some instances for customers to send logs to tech support when they are reporting bugs or other problems.</p>
[ { "answer_id": 105611, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 3, "selected": true, "text": "Log log() debug() error() trace() trace()" }, { "answer_id": 191534, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 2, "selected": false, "text": "import org.osflash.thunderbolt.Logger;\n\nvar myNumber: int = 5;\nvar myString: String = \"Lorem ipsum\";\nLogger.error (\"Logging two objects: A number typed as int and a string\", myNumber, myString);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
105,125
<p>Our project uses Cruise Control to both build and hot deploy a web application to a remote server (via FTP) running Tomcat in the form of a .war file. Unfortunately, "hot" deploys don't appear to work properly, causing us to reboot Tomcat in response to each deployment. We would really like to do this auto-magically, much like the build itself. Is there an easy way to do this?</p> <p>Side note: both machines are running Windows (XP or server, I think).</p> <p>Side note 2: Performance doesn't really matter. This is an integration box.</p>
[ { "answer_id": 105289, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 1, "selected": false, "text": "crontab -e\n 30 1 * * * ./path_to_tamcat/bin/catalina.sh stop\n 32 1 * * * ./path_to_tamcat/bin/catalina.sh start\n" }, { "answer_id": 2110708, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 0, "selected": false, "text": "/WEB-INF/lib mail.jar Context antiResourceLocking true /META-INF/context.xml <Context antiResourceLocking=\"true\">\n <!-- Your stuff here. -->\n</Context>\n" }, { "answer_id": 64460421, "author": "Sobhan", "author_id": 7189597, "author_profile": "https://Stackoverflow.com/users/7189597", "pm_score": 0, "selected": false, "text": "sudo crontab -e\n @reboot /`PATH_TO_WHERE_TOMCAT_INSTALLED`/bin/startup.sh\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7357/" ]
105,130
<p>What are the major reasons for using <a href="http://en.wikipedia.org/wiki/WinDbg" rel="noreferrer">WinDbg</a> vs the Visual Studio debugger?</p> <p>And is it commonly used as a complete replacement for the Visual Studio debugger, or more for when the need arises.</p>
[ { "answer_id": 119993, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 3, "selected": false, "text": ".loadby sos mscorwks\n !help\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19263/" ]
105,147
<p>Working on a new back end system for my company, and one of their requests is for a window to become locked down and for the user to be sent to the login screen if they leave it idle for to long.</p> <p>I figure I'd do this with JavaScript by attaching listeners to clicks, mouse moves and key-ups but I worry about messing with other scripts.</p> <p>Any suggestions? ­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 119993, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 3, "selected": false, "text": ".loadby sos mscorwks\n !help\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9176/" ]
105,198
<p>I'm still a little unclear and when to wrap a <em>lock</em> around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge:</p> <pre><code>class Foo { private static readonly string bar = "O_o"; private bool TrySomething() { string bar; lock(Foo.objectToLockOn) { bar = Foo.bar; } // Do something with bar } } </code></pre> <p>That just doesn't make sense to me--why would there by concurrency issues with READING a register?</p> <p>Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL...</p> <pre><code>class Foo { private static string joke = "yo momma"; private string GetJoke() { lock(Foo.objectToLockOn) { return Foo.joke; } } } </code></pre> <p>vs.</p> <pre><code>class Foo { private static string joke = "yo momma"; private string GetJoke() { string joke; lock(Foo.objectToLockOn) { joke = Foo.joke; } return joke; } } </code></pre>
[ { "answer_id": 105650, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 6, "selected": true, "text": "class Foo\n{\n private int count = 0;\n public void TrySomething() \n {\n count++;\n }\n}\n class Foo\n{\n private int count = 0;\n private readonly object sync = new object();\n public void TrySomething() \n {\n lock(sync)\n count++;\n }\n}\n class Foo\n{\n private int count = 0;\n public void TrySomething() \n {\n System.Threading.Interlocked.Increment(ref count);\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
105,212
<p>Suppose I have a directory <code>/dir</code> inside which there are 3 symlinks to other directories <code>/dir/dir11</code>, <code>/dir/dir12</code>, and <code>/dir/dir13</code>. I want to list all the files in <code>dir</code> including the ones in <code>dir11</code>, <code>dir12</code> and <code>dir13</code>.</p> <p>To be more generic, I want to list all files including the ones in the directories which are symlinks. <code>find .</code>, <code>ls -R</code>, etc stop at the symlink without navigating into them to list further.</p>
[ { "answer_id": 105249, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 9, "selected": true, "text": "-L ls ls -LR\n find -follow\n -follow find -L\n -follow" }, { "answer_id": 105251, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 4, "selected": false, "text": " ls -LR\n -L, --dereference\n when showing file information for a symbolic link, show informa‐\n tion for the file the link references rather than for the link\n itself\n find -L .\n -L Follow symbolic links.\n" }, { "answer_id": 105256, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 6, "selected": false, "text": "find /dir -type f -follow -print\n -type f -follow -print find /dir -type f -follow -print|xargs ls -l\n" }, { "answer_id": 105258, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 2, "selected": false, "text": "ls -R -L\n -L" }, { "answer_id": 105365, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 7, "selected": false, "text": "tree -l" }, { "answer_id": 11785629, "author": "Ashwin Muni", "author_id": 1092329, "author_profile": "https://Stackoverflow.com/users/1092329", "pm_score": 3, "selected": false, "text": "find -L /var/www/ -type l\n\n# man find\n -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the\n" }, { "answer_id": 25059432, "author": "divinedragon", "author_id": 979772, "author_profile": "https://Stackoverflow.com/users/979772", "pm_score": 3, "selected": false, "text": "tree find ./ | sed -e 's/[^-][^\\/]*\\//--/g;s/--/ |-/'\n" }, { "answer_id": 51562111, "author": "qrtLs", "author_id": 4933053, "author_profile": "https://Stackoverflow.com/users/4933053", "pm_score": -1, "selected": false, "text": "find . -type f -exec cat {} +" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18072/" ]
105,252
<p>How do I convert between big-endian and little-endian values in C++?</p> <p>For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.</p> <hr /> <p>Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.</p>
[ { "answer_id": 105319, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 4, "selected": false, "text": "// Specialization for 2-byte types.\ntemplate<>\ninline void endian_byte_swapper< 2 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n ushort* p_dest = reinterpret_cast< ushort* >(dest);\n ushort const* const p_src = reinterpret_cast< ushort const* >(src);\n *p_dest = (*p_src >> 8) | (*p_src << 8);\n}\n\n// Specialization for 4-byte types.\ntemplate<>\ninline void endian_byte_swapper< 4 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n uint* p_dest = reinterpret_cast< uint* >(dest);\n uint const* const p_src = reinterpret_cast< uint const* >(src);\n *p_dest = (*p_src >> 24) | ((*p_src & 0x00ff0000) >> 8) | ((*p_src & 0x0000ff00) << 8) | (*p_src << 24);\n}\n" }, { "answer_id": 105323, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 3, "selected": false, "text": "short big = 0xdead;\nshort little = (((big & 0xff)<<8) | ((big & 0xff00)>>8));\n" }, { "answer_id": 105339, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 9, "selected": true, "text": "unsigned short _byteswap_ushort(unsigned short value);\n unsigned long _byteswap_ulong(unsigned long value);\n unsigned __int64 _byteswap_uint64(unsigned __int64 value);\n uint32_t __builtin_bswap32 (uint32_t x)\nuint64_t __builtin_bswap64 (uint64_t x)\n" }, { "answer_id": 105342, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 4, "selected": false, "text": "void swapByteOrder(unsigned short& us)\n{\n us = (us >> 8) |\n (us << 8);\n}\n\nvoid swapByteOrder(unsigned int& ui)\n{\n ui = (ui >> 24) |\n ((ui<<8) & 0x00FF0000) |\n ((ui>>8) & 0x0000FF00) |\n (ui << 24);\n}\n\nvoid swapByteOrder(unsigned long long& ull)\n{\n ull = (ull >> 56) |\n ((ull<<40) & 0x00FF000000000000) |\n ((ull<<24) & 0x0000FF0000000000) |\n ((ull<<8) & 0x000000FF00000000) |\n ((ull>>8) & 0x00000000FF000000) |\n ((ull>>24) & 0x0000000000FF0000) |\n ((ull>>40) & 0x000000000000FF00) |\n (ull << 56);\n}\n" }, { "answer_id": 105354, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 3, "selected": false, "text": "unsigned int change_endian(unsigned int x)\n{\n unsigned char *ptr = (unsigned char *)&x;\n return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];\n}\n" }, { "answer_id": 105371, "author": "anon6439", "author_id": 15477, "author_profile": "https://Stackoverflow.com/users/15477", "pm_score": 4, "selected": false, "text": "_byteswap_ushort(), _byteswap_ulong(), and _byteswap_int64()" }, { "answer_id": 105410, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 6, "selected": false, "text": "ntohl() //Network to Host byte order (Long)\nhtonl() //Host to Network byte order (Long)\n\nntohs() //Network to Host byte order (Short)\nhtons() //Host to Network byte order (Short)\n" }, { "answer_id": 105632, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": " template<typename T>\n void ByteSwap(T * p)\n {\n for (int i = 0; i < sizeof(T)/2; ++i)\n std::swap(((char *)p)[i], ((char *)p)[sizeof(T)-1-i]);\n }\n" }, { "answer_id": 107099, "author": "Mathieu Pagé", "author_id": 5861, "author_profile": "https://Stackoverflow.com/users/5861", "pm_score": 2, "selected": false, "text": "// We define some constant for little, big and host endianess. Here I use \n// BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you\n// don't want to use boost you will have to modify this part a bit.\nenum EEndian\n{\n LITTLE_ENDIAN_ORDER,\n BIG_ENDIAN_ORDER,\n#if defined(BOOST_LITTLE_ENDIAN)\n HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER\n#elif defined(BOOST_BIG_ENDIAN)\n HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER\n#else\n#error \"Impossible de determiner l'indianness du systeme cible.\"\n#endif\n};\n\n// this function swap the bytes of values given it's size as a template\n// parameter (could sizeof be used?).\ntemplate <class T, unsigned int size>\ninline T SwapBytes(T value)\n{\n union\n {\n T value;\n char bytes[size];\n } in, out;\n\n in.value = value;\n\n for (unsigned int i = 0; i < size / 2; ++i)\n {\n out.bytes[i] = in.bytes[size - 1 - i];\n out.bytes[size - 1 - i] = in.bytes[i];\n }\n\n return out.value;\n}\n\n// Here is the function you will use. Again there is two compile-time assertion\n// that use the boost librarie. You could probably comment them out, but if you\n// do be cautious not to use this function for anything else than integers\n// types. This function need to be calles like this :\n//\n// int x = someValue;\n// int i = EndianSwapBytes<HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER>(x);\n//\ntemplate<EEndian from, EEndian to, class T>\ninline T EndianSwapBytes(T value)\n{\n // A : La donnée à swapper à une taille de 2, 4 ou 8 octets\n BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n\n // A : La donnée à swapper est d'un type arithmetic\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n // Si from et to sont du même type on ne swap pas.\n if (from == to)\n return value;\n\n return SwapBytes<T, sizeof(T)>(value);\n}\n" }, { "answer_id": 3522853, "author": "Steve Lorimer", "author_id": 955273, "author_profile": "https://Stackoverflow.com/users/955273", "pm_score": 5, "selected": false, "text": "#include <boost/type_traits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/detail/endian.hpp>\n#include <stdexcept>\n#include <cstdint>\n\nenum endianness\n{\n little_endian,\n big_endian,\n network_endian = big_endian,\n \n #if defined(BOOST_LITTLE_ENDIAN)\n host_endian = little_endian\n #elif defined(BOOST_BIG_ENDIAN)\n host_endian = big_endian\n #else\n #error \"unable to determine system endianness\"\n #endif\n};\n\nnamespace detail {\n\ntemplate<typename T, size_t sz>\nstruct swap_bytes\n{\n inline T operator()(T val)\n {\n throw std::out_of_range(\"data size\");\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 1>\n{\n inline T operator()(T val)\n {\n return val;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 2>\n{\n inline T operator()(T val)\n {\n return ((((val) >> 8) & 0xff) | (((val) & 0xff) << 8));\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 4>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff000000) >> 24) |\n (((val) & 0x00ff0000) >> 8) |\n (((val) & 0x0000ff00) << 8) |\n (((val) & 0x000000ff) << 24));\n }\n};\n\ntemplate<>\nstruct swap_bytes<float, 4>\n{\n inline float operator()(float val)\n {\n uint32_t mem =swap_bytes<uint32_t, sizeof(uint32_t)>()(*(uint32_t*)&val);\n return *(float*)&mem;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 8>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff00000000000000ull) >> 56) |\n (((val) & 0x00ff000000000000ull) >> 40) |\n (((val) & 0x0000ff0000000000ull) >> 24) |\n (((val) & 0x000000ff00000000ull) >> 8 ) |\n (((val) & 0x00000000ff000000ull) << 8 ) |\n (((val) & 0x0000000000ff0000ull) << 24) |\n (((val) & 0x000000000000ff00ull) << 40) |\n (((val) & 0x00000000000000ffull) << 56));\n }\n};\n\ntemplate<>\nstruct swap_bytes<double, 8>\n{\n inline double operator()(double val)\n {\n uint64_t mem =swap_bytes<uint64_t, sizeof(uint64_t)>()(*(uint64_t*)&val);\n return *(double*)&mem;\n }\n};\n\ntemplate<endianness from, endianness to, class T>\nstruct do_byte_swap\n{\n inline T operator()(T value)\n {\n return swap_bytes<T, sizeof(T)>()(value);\n }\n};\n// specialisations when attempting to swap to the same endianess\ntemplate<class T> struct do_byte_swap<little_endian, little_endian, T> { inline T operator()(T value) { return value; } };\ntemplate<class T> struct do_byte_swap<big_endian, big_endian, T> { inline T operator()(T value) { return value; } };\n\n} // namespace detail\n\ntemplate<endianness from, endianness to, class T>\ninline T byte_swap(T value)\n{\n // ensure the data is only 1, 2, 4 or 8 bytes\n BOOST_STATIC_ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n // ensure we're only swapping arithmetic types\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n return detail::do_byte_swap<from, to, T>()(value);\n}\n // swaps val from host-byte-order to network-byte-order\nauto swapped = byte_swap<host_endian, network_endian>(val);\n // swap a value received from the network into host-byte-order\nauto val = byte_swap<network_endian, host_endian>(val_from_network);\n" }, { "answer_id": 4956493, "author": "Alexandre C.", "author_id": 373025, "author_profile": "https://Stackoverflow.com/users/373025", "pm_score": 7, "selected": false, "text": "#include <climits>\n\ntemplate <typename T>\nT swap_endian(T u)\n{\n static_assert (CHAR_BIT == 8, \"CHAR_BIT != 8\");\n\n union\n {\n T u;\n unsigned char u8[sizeof(T)];\n } source, dest;\n\n source.u = u;\n\n for (size_t k = 0; k < sizeof(T); k++)\n dest.u8[k] = source.u8[sizeof(T) - k - 1];\n\n return dest.u;\n}\n swap_endian<uint32_t>(42)" }, { "answer_id": 4956807, "author": "Maxim Egorushkin", "author_id": 412080, "author_profile": "https://Stackoverflow.com/users/412080", "pm_score": 3, "selected": false, "text": "<endian.h> #include <iostream>\n\n#include <endian.h>\n\ntemplate<size_t N> struct SizeT {};\n\n#define BYTESWAPS(bits) \\\ntemplate<class T> inline T htobe(T t, SizeT<bits / 8>) { return htobe ## bits(t); } \\\ntemplate<class T> inline T htole(T t, SizeT<bits / 8>) { return htole ## bits(t); } \\\ntemplate<class T> inline T betoh(T t, SizeT<bits / 8>) { return be ## bits ## toh(t); } \\\ntemplate<class T> inline T letoh(T t, SizeT<bits / 8>) { return le ## bits ## toh(t); }\n\nBYTESWAPS(16)\nBYTESWAPS(32)\nBYTESWAPS(64)\n\n#undef BYTESWAPS\n\ntemplate<class T> inline T htobe(T t) { return htobe(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T htole(T t) { return htole(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T betoh(T t) { return betoh(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T letoh(T t) { return letoh(t, SizeT<sizeof t>()); }\n\nint main()\n{\n std::cout << std::hex;\n std::cout << htobe(static_cast<unsigned short>(0xfeca)) << '\\n';\n std::cout << htobe(0xafbeadde) << '\\n';\n\n // Use ULL suffix to specify integer constant as unsigned long long \n std::cout << htobe(0xfecaefbeafdeedfeULL) << '\\n';\n}\n cafe\ndeadbeaf\nfeeddeafbeefcafe\n" }, { "answer_id": 6487066, "author": "friedemann", "author_id": 815363, "author_profile": "https://Stackoverflow.com/users/815363", "pm_score": 2, "selected": false, "text": "long swap(long i) {\n char *c = (char *) &i;\n return * (long *) (char[]) {c[3], c[2], c[1], c[0] };\n}\n" }, { "answer_id": 10346064, "author": "Matthieu M.", "author_id": 147192, "author_profile": "https://Stackoverflow.com/users/147192", "pm_score": 6, "selected": false, "text": "i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | ((unsigned)data[3]<<24);\n i = (data[3]<<0) | (data[2]<<8) | (data[1]<<16) | ((unsigned)data[0]<<24);\n int unsigned int unsigned int" }, { "answer_id": 18333053, "author": "user2699548", "author_id": 2699548, "author_profile": "https://Stackoverflow.com/users/2699548", "pm_score": 3, "selected": false, "text": "#define htonl(x) _byteswap_ulong(x)\n" }, { "answer_id": 18334154, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": 2, "selected": false, "text": "x = ((x & 0x00000000ffffffff) << 32) ^ ((x >> 32) & 0x00000000ffffffff);\nx = ((x & 0x0000ffff0000ffff) << 16) ^ ((x >> 16) & 0x0000ffff0000ffff);\nx = ((x & 0x00ff00ff00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff00ff00ff);\n x = ( x << 32) ^ (x >> 32);\n uint64_t k = 0x00000000ffffffff; /* compiler should know a trick for this */\nx = ((x & k) << 32) ^ ((x >> 32) & k);\nk ^= k << 16;\nx = ((x & k) << 16) ^ ((x >> 16) & k);\nk ^= k << 8;\nx = ((x & k) << 8) ^ ((x >> 8) & k);\n int i = sizeof(x) * CHAR_BIT / 2;\nuintmax_t k = (1 << i) - 1;\nwhile (i >= 8)\n{\n x = ((x & k) << i) ^ ((x >> i) & k);\n i >>= 1;\n k ^= k << i;\n}\n x = ( x << 16) ^ (x >> 16);\nx = ((x & 0x00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff);\n" }, { "answer_id": 25177297, "author": "The Quantum Physicist", "author_id": 1317944, "author_profile": "https://Stackoverflow.com/users/1317944", "pm_score": 3, "selected": false, "text": "template <typename T>\nvoid SwapEnd(T& var)\n{\n static_assert(std::is_pod<T>::value, \"Type must be POD type for safety\");\n std::array<char, sizeof(T)> varArray;\n std::memcpy(varArray.data(), &var, sizeof(T));\n for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)\n std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);\n std::memcpy(&var, varArray.data(), sizeof(T));\n}\n uint64_t uint8_t reinterpret_cast reinterpret_cast double x = 5;\nSwapEnd(x);\n x" }, { "answer_id": 25704741, "author": "Adam Freeman", "author_id": 538458, "author_profile": "https://Stackoverflow.com/users/538458", "pm_score": 2, "selected": false, "text": "// can be used for short, unsigned short, word, unsigned word (2-byte types)\n#define BYTESWAP16(n) (((n&0xFF00)>>8)|((n&0x00FF)<<8))\n\n// can be used for int or unsigned int or float (4-byte types)\n#define BYTESWAP32(n) ((BYTESWAP16((n&0xFFFF0000)>>16))|((BYTESWAP16(n&0x0000FFFF))<<16))\n\n// can be used for unsigned long long or double (8-byte types)\n#define BYTESWAP64(n) ((BYTESWAP32((n&0xFFFFFFFF00000000)>>32))|((BYTESWAP32(n&0x00000000FFFFFFFF))<<32))\n" }, { "answer_id": 26007257, "author": "The Welder", "author_id": 2086872, "author_profile": "https://Stackoverflow.com/users/2086872", "pm_score": 0, "selected": false, "text": "__declspec(naked) uint32_t EndianSwap(uint32 value)\n{\n __asm\n {\n mov eax, dword ptr[esp + 4]\n bswap eax\n ret\n }\n}\n unsigned long _byteswap_ulong(unsigned long value);\n mov ebx, eax\nshr ebx, 16\nxchg al, ah\nxchg bl, bh\nshl eax, 16\nor eax, ebx\n" }, { "answer_id": 35092546, "author": "Joao", "author_id": 1604608, "author_profile": "https://Stackoverflow.com/users/1604608", "pm_score": 2, "selected": false, "text": "template<typename T> inline static T swapByteOrder(const T& val) {\n int totalBytes = sizeof(val);\n T swapped = (T) 0;\n for (int i = 0; i < totalBytes; ++i) {\n swapped |= (val >> (8*(totalBytes-i-1)) & 0xFF) << (8*i);\n }\n return swapped;\n}\n" }, { "answer_id": 37386513, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 0, "selected": false, "text": "uint32_t sw_get_uint32_1234(pu32)\nuint32_1234 *pu32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32_1234[0] = (*pu32)[BO32_0];\n bou32.u32_1234[1] = (*pu32)[BO32_1];\n bou32.u32_1234[2] = (*pu32)[BO32_2];\n bou32.u32_1234[3] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_1234(pu32, u32)\nuint32_1234 *pu32;\nuint32_t u32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_1234[0];\n (*pu32)[BO32_1] = bou32.u32_1234[1];\n (*pu32)[BO32_2] = bou32.u32_1234[2];\n (*pu32)[BO32_3] = bou32.u32_1234[3];\n}\n\n#if HAS_SW_INT64\nint64 sw_get_int64_12345678(pi64)\nint64_12345678 *pi64;\n{\n union {\n int64_12345678 i64_12345678;\n int64 i64;\n } boi64;\n boi64.i64_12345678[0] = (*pi64)[BO64_0];\n boi64.i64_12345678[1] = (*pi64)[BO64_1];\n boi64.i64_12345678[2] = (*pi64)[BO64_2];\n boi64.i64_12345678[3] = (*pi64)[BO64_3];\n boi64.i64_12345678[4] = (*pi64)[BO64_4];\n boi64.i64_12345678[5] = (*pi64)[BO64_5];\n boi64.i64_12345678[6] = (*pi64)[BO64_6];\n boi64.i64_12345678[7] = (*pi64)[BO64_7];\n return(boi64.i64);\n}\n#endif\n\nint32_t sw_get_int32_3412(pi32)\nint32_3412 *pi32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32_3412[2] = (*pi32)[BO32_0];\n boi32.i32_3412[3] = (*pi32)[BO32_1];\n boi32.i32_3412[0] = (*pi32)[BO32_2];\n boi32.i32_3412[1] = (*pi32)[BO32_3];\n return(boi32.i32);\n}\n\nvoid sw_set_int32_3412(pi32, i32)\nint32_3412 *pi32;\nint32_t i32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32 = i32;\n (*pi32)[BO32_0] = boi32.i32_3412[2];\n (*pi32)[BO32_1] = boi32.i32_3412[3];\n (*pi32)[BO32_2] = boi32.i32_3412[0];\n (*pi32)[BO32_3] = boi32.i32_3412[1];\n}\n\nuint32_t sw_get_uint32_3412(pu32)\nuint32_3412 *pu32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32_3412[2] = (*pu32)[BO32_0];\n bou32.u32_3412[3] = (*pu32)[BO32_1];\n bou32.u32_3412[0] = (*pu32)[BO32_2];\n bou32.u32_3412[1] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_3412(pu32, u32)\nuint32_3412 *pu32;\nuint32_t u32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_3412[2];\n (*pu32)[BO32_1] = bou32.u32_3412[3];\n (*pu32)[BO32_2] = bou32.u32_3412[0];\n (*pu32)[BO32_3] = bou32.u32_3412[1];\n}\n\nfloat sw_get_float_1234(pf)\nfloat_1234 *pf;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f_1234[0] = (*pf)[BO32_0];\n bof.f_1234[1] = (*pf)[BO32_1];\n bof.f_1234[2] = (*pf)[BO32_2];\n bof.f_1234[3] = (*pf)[BO32_3];\n return(bof.f);\n}\n\nvoid sw_set_float_1234(pf, f)\nfloat_1234 *pf;\nfloat f;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f = (float)f;\n (*pf)[BO32_0] = bof.f_1234[0];\n (*pf)[BO32_1] = bof.f_1234[1];\n (*pf)[BO32_2] = bof.f_1234[2];\n (*pf)[BO32_3] = bof.f_1234[3];\n}\n\ndouble sw_get_double_12345678(pd)\ndouble_12345678 *pd;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d_12345678[0] = (*pd)[BO64_0];\n bod.d_12345678[1] = (*pd)[BO64_1];\n bod.d_12345678[2] = (*pd)[BO64_2];\n bod.d_12345678[3] = (*pd)[BO64_3];\n bod.d_12345678[4] = (*pd)[BO64_4];\n bod.d_12345678[5] = (*pd)[BO64_5];\n bod.d_12345678[6] = (*pd)[BO64_6];\n bod.d_12345678[7] = (*pd)[BO64_7];\n return(bod.d);\n}\n\nvoid sw_set_double_12345678(pd, d)\ndouble_12345678 *pd;\ndouble d;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d = d;\n (*pd)[BO64_0] = bod.d_12345678[0];\n (*pd)[BO64_1] = bod.d_12345678[1];\n (*pd)[BO64_2] = bod.d_12345678[2];\n (*pd)[BO64_3] = bod.d_12345678[3];\n (*pd)[BO64_4] = bod.d_12345678[4];\n (*pd)[BO64_5] = bod.d_12345678[5];\n (*pd)[BO64_6] = bod.d_12345678[6];\n (*pd)[BO64_7] = bod.d_12345678[7];\n}\n typedef char int8_1[1], uint8_1[1];\n\ntypedef char int16_12[2], uint16_12[2]; /* little endian */\ntypedef char int16_21[2], uint16_21[2]; /* big endian */\n\ntypedef char int24_321[3], uint24_321[3]; /* Alpha Micro, PDP-11 */\n\ntypedef char int32_1234[4], uint32_1234[4]; /* little endian */\ntypedef char int32_3412[4], uint32_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char int32_4321[4], uint32_4321[4]; /* big endian */\n\ntypedef char int64_12345678[8], uint64_12345678[8]; /* little endian */\ntypedef char int64_34128756[8], uint64_34128756[8]; /* Alpha Micro, PDP-11 */\ntypedef char int64_87654321[8], uint64_87654321[8]; /* big endian */\n\ntypedef char float_1234[4]; /* little endian */\ntypedef char float_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char float_4321[4]; /* big endian */\n\ntypedef char double_12345678[8]; /* little endian */\ntypedef char double_78563412[8]; /* Alpha Micro? */\ntypedef char double_87654321[8]; /* big endian */\n" }, { "answer_id": 39548833, "author": "pz64_", "author_id": 6737471, "author_profile": "https://Stackoverflow.com/users/6737471", "pm_score": 2, "selected": false, "text": "#define uint32_t unsigned \n#define uint16_t unsigned short\n\n#define swap16(x) ((((uint16_t)(x) & 0x00ff)<<8)| \\\n(((uint16_t)(x) & 0xff00)>>8))\n\n#define swap32(x) ((((uint32_t)(x) & 0x000000ff)<<24)| \\\n(((uint32_t)(x) & 0x0000ff00)<<8)| \\\n(((uint32_t)(x) & 0x00ff0000)>>8)| \\\n(((uint32_t)(x) & 0xff000000)>>24))\n" }, { "answer_id": 41196306, "author": "Ryan Hilbert", "author_id": 2884225, "author_profile": "https://Stackoverflow.com/users/2884225", "pm_score": 1, "selected": false, "text": "#define REVERSE_BYTES(...) do for(size_t REVERSE_BYTES=0; REVERSE_BYTES<sizeof(__VA_ARGS__)>>1; ++REVERSE_BYTES)\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES];\\\nwhile(0)\n int main(){\n unsigned long long x = 0xABCDEF0123456789;\n printf(\"Before: %llX\\n\",x);\n REVERSE_BYTES(x);\n printf(\"After : %llX\\n\",x);\n\n char c[7]=\"nametag\";\n printf(\"Before: %c%c%c%c%c%c%c\\n\",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n REVERSE_BYTES(c);\n printf(\"After : %c%c%c%c%c%c%c\\n\",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n}\n Before: ABCDEF0123456789\nAfter : 8967452301EFCDAB\nBefore: nametag\nAfter : gateman\n do while(0) REVERSE_BYTES for for ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES]\n((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES]\n __VA_ARGS__ unsigned char [] {}" }, { "answer_id": 44123161, "author": "Malcolm McLean", "author_id": 3310281, "author_profile": "https://Stackoverflow.com/users/3310281", "pm_score": -1, "selected": false, "text": "/*\n* read a double from a stream in ieee754 format regardless of host\n* encoding.\n* fp - the stream\n* bigendian - set to if big bytes first, clear for little bytes\n* first\n*\n*/\ndouble freadieee754(FILE *fp, int bigendian)\n{\n unsigned char buff[8];\n int i;\n double fnorm = 0.0;\n unsigned char temp;\n int sign;\n int exponent;\n double bitval;\n int maski, mask;\n int expbits = 11;\n int significandbits = 52;\n int shift;\n double answer;\n\n /* read the data */\n for (i = 0; i < 8; i++)\n buff[i] = fgetc(fp);\n /* just reverse if not big-endian*/\n if (!bigendian)\n {\n for (i = 0; i < 4; i++)\n {\n temp = buff[i];\n buff[i] = buff[8 - i - 1];\n buff[8 - i - 1] = temp;\n }\n }\n sign = buff[0] & 0x80 ? -1 : 1;\n /* exponet in raw format*/\n exponent = ((buff[0] & 0x7F) << 4) | ((buff[1] & 0xF0) >> 4);\n\n /* read inthe mantissa. Top bit is 0.5, the successive bits half*/\n bitval = 0.5;\n maski = 1;\n mask = 0x08;\n for (i = 0; i < significandbits; i++)\n {\n if (buff[maski] & mask)\n fnorm += bitval;\n\n bitval /= 2.0;\n mask >>= 1;\n if (mask == 0)\n {\n mask = 0x80;\n maski++;\n }\n }\n /* handle zero specially */\n if (exponent == 0 && fnorm == 0)\n return 0.0;\n\n shift = exponent - ((1 << (expbits - 1)) - 1); /* exponent = shift + bias */\n /* nans have exp 1024 and non-zero mantissa */\n if (shift == 1024 && fnorm != 0)\n return sqrt(-1.0);\n /*infinity*/\n if (shift == 1024 && fnorm == 0)\n {\n\n#ifdef INFINITY\n return sign == 1 ? INFINITY : -INFINITY;\n#endif\n return (sign * 1.0) / 0.0;\n }\n if (shift > -1023)\n {\n answer = ldexp(fnorm + 1.0, shift);\n return answer * sign;\n }\n else\n {\n /* denormalised numbers */\n if (fnorm == 0.0)\n return 0.0;\n shift = -1022;\n while (fnorm < 1.0)\n {\n fnorm *= 2;\n shift--;\n }\n answer = ldexp(fnorm, shift);\n return answer * sign;\n }\n}\n" }, { "answer_id": 55634732, "author": "Quinn Carver", "author_id": 2953356, "author_profile": "https://Stackoverflow.com/users/2953356", "pm_score": 0, "selected": false, "text": "template<typename T>void swap(T &t){\n for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n *((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n }\n}\n" }, { "answer_id": 55756299, "author": "cycollins", "author_id": 8611540, "author_profile": "https://Stackoverflow.com/users/8611540", "pm_score": 0, "selected": false, "text": "std::vector<uint16_t> storage(n); // where n is the number to be converted\n\n// the following would do the trick\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n #if (__DARWIN_BYTE_ORDER != __DARWIN_BIG_ENDIAN)\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n#endif\n" }, { "answer_id": 61146679, "author": "Thinkal VB", "author_id": 7057208, "author_profile": "https://Stackoverflow.com/users/7057208", "pm_score": 1, "selected": false, "text": "#include <algorithm>\n template <typename T>\nvoid swapEndian(T& buffer)\n{\n static_assert(std::is_pod<T>::value, \"swapEndian support POD type only\");\n char* startIndex = static_cast<char*>((void*)buffer.data());\n char* endIndex = startIndex + sizeof(buffer);\n std::reverse(startIndex, endIndex);\n}\n swapEndian (stlContainer);\n" }, { "answer_id": 63106400, "author": "Mrocco", "author_id": 12178397, "author_profile": "https://Stackoverflow.com/users/12178397", "pm_score": 1, "selected": false, "text": "void endianness_swap(uint32_t& val) {\n uint8_t a, b, c;\n a = (val & 0xFF000000) >> 24;\n b = (val & 0x00FF0000) >> 16;\n c = (val & 0x0000FF00) >> 8;\n val=(val & 0x000000FF) << 24;\n val = val + (c << 16) + (b << 8) + (a);\n}\n" }, { "answer_id": 67458876, "author": "Sunny127", "author_id": 1925162, "author_profile": "https://Stackoverflow.com/users/1925162", "pm_score": -1, "selected": false, "text": "void writeLittleEndianToBigEndian(void* ptrLittleEndian, void* ptrBigEndian , size_t bufLen )\n{\n char *pchLittleEndian = (char*)ptrLittleEndian;\n\n char *pchBigEndian = (char*)ptrBigEndian;\n\n for ( size_t i = 0 ; i < bufLen ; i++ ) \n pchBigEndian[bufLen-1-i] = pchLittleEndian[i];\n}\n\nstd::uint32_t row = 0x12345678;\n\nchar buf[4]; \n\nwriteLittleEndianToBigEndian( &row, &buf, sizeof(row) );\n" }, { "answer_id": 67681004, "author": "natersoz", "author_id": 138264, "author_profile": "https://Stackoverflow.com/users/138264", "pm_score": 0, "selected": false, "text": "#include <cstdint>\n#include <type_traits>\n\n/**\n * Perform an endian swap of bytes against a templatized unsigned word.\n *\n * @tparam value_type The data type to perform the endian swap against.\n * @param value The data value to swap.\n *\n * @return value_type The resulting swapped word.\n */\ntemplate <typename value_type>\nconstexpr inline auto endian_swap(value_type value) -> value_type\n{\n using half_type = typename std::conditional<\n sizeof(value_type) == 8u,\n uint32_t,\n typename std::conditional<sizeof(value_type) == 4u, uint16_t, uint8_t>::\n type>::type;\n\n size_t const half_bits = sizeof(value_type) * 8u / 2u;\n half_type const upper_half = static_cast<half_type>(value >> half_bits);\n half_type const lower_half = static_cast<half_type>(value);\n\n if (sizeof(value_type) == 2u)\n {\n return (static_cast<value_type>(lower_half) << half_bits) | upper_half;\n }\n\n return ((static_cast<value_type>(endian_swap(lower_half)) << half_bits) |\n endian_swap(upper_half));\n}\n" }, { "answer_id": 69500743, "author": "Glenn Teitelbaum", "author_id": 2963099, "author_profile": "https://Stackoverflow.com/users/2963099", "pm_score": 0, "selected": false, "text": "#include <bit>\n#include <type_traits>\n#include <concepts>\n#include <array>\n#include <cstring>\n#include <iostream>\n#include <bitset>\n\ntemplate <int LEN, int OFF=LEN/2>\nclass do_swap\n{\n // FOR 8 bytes:\n // LEN=8 (LEN/2==4) <H><G><F><E><D><C><B><A>\n // OFF=4: FROM=0, TO=7 => [A]<G><F><E><D><C><B>[H]\n // OFF=3: FROM=1, TO=6 => [A][B]<F><E><D><C>[G][H]\n // OFF=2: FROM=2, TO=5 => [A][B][C]<E><D>[F][G][H]\n // OFF=1: FROM=3, TO=4 => [A][B][C][D][E][F][G][H]\n // OFF=0: FROM=4, TO=3 => DONE\npublic:\n enum consts {FROM=LEN/2-OFF, TO=(LEN-1)-FROM};\n using NXT=do_swap<LEN, OFF-1>;\n// flip the first and last for the current iteration's range\n static void flip(std::array<std::byte, LEN>& b)\n {\n std::byte tmp=b[FROM];\n b[FROM]=b[TO];\n b[TO]=tmp;\n NXT::flip(b);\n }\n};\ntemplate <int LEN>\nclass do_swap<LEN, 0> // STOP the template recursion\n{\npublic:\n static void flip(std::array<std::byte, LEN>&)\n {\n }\n};\n\ntemplate<std::integral T, std::endian TO, std::endian FROM=std::endian::native>\n requires ((TO==std::endian::big) || (TO==std::endian::little))\n && ((FROM==std::endian::big) || (FROM==std::endian::little))\nclass endian_swap\n{\npublic:\n enum consts {BYTE_COUNT=sizeof(T)};\n static T cvt(const T integral)\n {\n // if FROM and TO are the same -- nothing to do\n if (TO==FROM)\n {\n return integral;\n }\n\n // endian::big --> endian::little is the same as endian::little --> endian::big\n // the bytes have to be reversed\n // memcpy seems to be the most supported way to do byte swaps in a defined way\n std::array<std::byte, BYTE_COUNT> bytes;\n std::memcpy(&bytes, &integral, BYTE_COUNT);\n do_swap<BYTE_COUNT>::flip(bytes);\n T ret;\n std::memcpy(&ret, &bytes, BYTE_COUNT);\n return ret;\n }\n};\n\nstd::endian big()\n{\n return std::endian::big;\n}\n\nstd::endian little()\n{\n return std::endian::little;\n}\n\nstd::endian native()\n{\n return std::endian::native;\n}\n\nlong long swap_to_big(long long x)\n{\n return endian_swap<long long, std::endian::big>::cvt(x);\n}\n\nlong long swap_to_little(long long x)\n{\n return endian_swap<long long, std::endian::little>::cvt(x);\n}\n\nvoid show(std::string label, long long x)\n{\n std::cout << label << \"\\t: \" << std::bitset<64>(x) << \" (\" << x << \")\" << std::endl;\n}\n\nint main(int argv, char ** argc)\n{\n long long init=0xF8FCFEFF7F3F1F0;\n long long to_big=swap_to_big(init);\n long long to_little=swap_to_little(init);\n show(\"Init\", init);\n show(\">big\", to_big);\n show(\">little\", to_little);\n}\n" }, { "answer_id": 74330996, "author": "yano", "author_id": 3476780, "author_profile": "https://Stackoverflow.com/users/3476780", "pm_score": 0, "selected": false, "text": "boost::endian::endian_reverse #include <iostream>\n#include <iomanip>\n#include \"boost/endian/conversion.hpp\"\n\nint main()\n{\n uint32_t word = 0x01;\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word << std::endl;\n // outputs 00000001;\n\n uint32_t word2 = boost::endian::endian_reverse(word);\n // there's also a `void ::endian_reverse_inplace(...) function\n // that reverses the value passed to it in place and returns nothing\n\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word2 << std::endl;\n // outputs 01000000\n\n return 0;\n}\n std::byteswap" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19129/" ]
105,264
<p>I'm new to the WCSF and can't seem to find anything related to "building a custom template" for creating the views/presenters/code-behinds/etc with your own flavor ...</p> <p>Can anyone point me in the right direction?</p>
[ { "answer_id": 105319, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 4, "selected": false, "text": "// Specialization for 2-byte types.\ntemplate<>\ninline void endian_byte_swapper< 2 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n ushort* p_dest = reinterpret_cast< ushort* >(dest);\n ushort const* const p_src = reinterpret_cast< ushort const* >(src);\n *p_dest = (*p_src >> 8) | (*p_src << 8);\n}\n\n// Specialization for 4-byte types.\ntemplate<>\ninline void endian_byte_swapper< 4 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n uint* p_dest = reinterpret_cast< uint* >(dest);\n uint const* const p_src = reinterpret_cast< uint const* >(src);\n *p_dest = (*p_src >> 24) | ((*p_src & 0x00ff0000) >> 8) | ((*p_src & 0x0000ff00) << 8) | (*p_src << 24);\n}\n" }, { "answer_id": 105323, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 3, "selected": false, "text": "short big = 0xdead;\nshort little = (((big & 0xff)<<8) | ((big & 0xff00)>>8));\n" }, { "answer_id": 105339, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 9, "selected": true, "text": "unsigned short _byteswap_ushort(unsigned short value);\n unsigned long _byteswap_ulong(unsigned long value);\n unsigned __int64 _byteswap_uint64(unsigned __int64 value);\n uint32_t __builtin_bswap32 (uint32_t x)\nuint64_t __builtin_bswap64 (uint64_t x)\n" }, { "answer_id": 105342, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 4, "selected": false, "text": "void swapByteOrder(unsigned short& us)\n{\n us = (us >> 8) |\n (us << 8);\n}\n\nvoid swapByteOrder(unsigned int& ui)\n{\n ui = (ui >> 24) |\n ((ui<<8) & 0x00FF0000) |\n ((ui>>8) & 0x0000FF00) |\n (ui << 24);\n}\n\nvoid swapByteOrder(unsigned long long& ull)\n{\n ull = (ull >> 56) |\n ((ull<<40) & 0x00FF000000000000) |\n ((ull<<24) & 0x0000FF0000000000) |\n ((ull<<8) & 0x000000FF00000000) |\n ((ull>>8) & 0x00000000FF000000) |\n ((ull>>24) & 0x0000000000FF0000) |\n ((ull>>40) & 0x000000000000FF00) |\n (ull << 56);\n}\n" }, { "answer_id": 105354, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 3, "selected": false, "text": "unsigned int change_endian(unsigned int x)\n{\n unsigned char *ptr = (unsigned char *)&x;\n return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];\n}\n" }, { "answer_id": 105371, "author": "anon6439", "author_id": 15477, "author_profile": "https://Stackoverflow.com/users/15477", "pm_score": 4, "selected": false, "text": "_byteswap_ushort(), _byteswap_ulong(), and _byteswap_int64()" }, { "answer_id": 105410, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 6, "selected": false, "text": "ntohl() //Network to Host byte order (Long)\nhtonl() //Host to Network byte order (Long)\n\nntohs() //Network to Host byte order (Short)\nhtons() //Host to Network byte order (Short)\n" }, { "answer_id": 105632, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": " template<typename T>\n void ByteSwap(T * p)\n {\n for (int i = 0; i < sizeof(T)/2; ++i)\n std::swap(((char *)p)[i], ((char *)p)[sizeof(T)-1-i]);\n }\n" }, { "answer_id": 107099, "author": "Mathieu Pagé", "author_id": 5861, "author_profile": "https://Stackoverflow.com/users/5861", "pm_score": 2, "selected": false, "text": "// We define some constant for little, big and host endianess. Here I use \n// BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you\n// don't want to use boost you will have to modify this part a bit.\nenum EEndian\n{\n LITTLE_ENDIAN_ORDER,\n BIG_ENDIAN_ORDER,\n#if defined(BOOST_LITTLE_ENDIAN)\n HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER\n#elif defined(BOOST_BIG_ENDIAN)\n HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER\n#else\n#error \"Impossible de determiner l'indianness du systeme cible.\"\n#endif\n};\n\n// this function swap the bytes of values given it's size as a template\n// parameter (could sizeof be used?).\ntemplate <class T, unsigned int size>\ninline T SwapBytes(T value)\n{\n union\n {\n T value;\n char bytes[size];\n } in, out;\n\n in.value = value;\n\n for (unsigned int i = 0; i < size / 2; ++i)\n {\n out.bytes[i] = in.bytes[size - 1 - i];\n out.bytes[size - 1 - i] = in.bytes[i];\n }\n\n return out.value;\n}\n\n// Here is the function you will use. Again there is two compile-time assertion\n// that use the boost librarie. You could probably comment them out, but if you\n// do be cautious not to use this function for anything else than integers\n// types. This function need to be calles like this :\n//\n// int x = someValue;\n// int i = EndianSwapBytes<HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER>(x);\n//\ntemplate<EEndian from, EEndian to, class T>\ninline T EndianSwapBytes(T value)\n{\n // A : La donnée à swapper à une taille de 2, 4 ou 8 octets\n BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n\n // A : La donnée à swapper est d'un type arithmetic\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n // Si from et to sont du même type on ne swap pas.\n if (from == to)\n return value;\n\n return SwapBytes<T, sizeof(T)>(value);\n}\n" }, { "answer_id": 3522853, "author": "Steve Lorimer", "author_id": 955273, "author_profile": "https://Stackoverflow.com/users/955273", "pm_score": 5, "selected": false, "text": "#include <boost/type_traits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/detail/endian.hpp>\n#include <stdexcept>\n#include <cstdint>\n\nenum endianness\n{\n little_endian,\n big_endian,\n network_endian = big_endian,\n \n #if defined(BOOST_LITTLE_ENDIAN)\n host_endian = little_endian\n #elif defined(BOOST_BIG_ENDIAN)\n host_endian = big_endian\n #else\n #error \"unable to determine system endianness\"\n #endif\n};\n\nnamespace detail {\n\ntemplate<typename T, size_t sz>\nstruct swap_bytes\n{\n inline T operator()(T val)\n {\n throw std::out_of_range(\"data size\");\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 1>\n{\n inline T operator()(T val)\n {\n return val;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 2>\n{\n inline T operator()(T val)\n {\n return ((((val) >> 8) & 0xff) | (((val) & 0xff) << 8));\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 4>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff000000) >> 24) |\n (((val) & 0x00ff0000) >> 8) |\n (((val) & 0x0000ff00) << 8) |\n (((val) & 0x000000ff) << 24));\n }\n};\n\ntemplate<>\nstruct swap_bytes<float, 4>\n{\n inline float operator()(float val)\n {\n uint32_t mem =swap_bytes<uint32_t, sizeof(uint32_t)>()(*(uint32_t*)&val);\n return *(float*)&mem;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 8>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff00000000000000ull) >> 56) |\n (((val) & 0x00ff000000000000ull) >> 40) |\n (((val) & 0x0000ff0000000000ull) >> 24) |\n (((val) & 0x000000ff00000000ull) >> 8 ) |\n (((val) & 0x00000000ff000000ull) << 8 ) |\n (((val) & 0x0000000000ff0000ull) << 24) |\n (((val) & 0x000000000000ff00ull) << 40) |\n (((val) & 0x00000000000000ffull) << 56));\n }\n};\n\ntemplate<>\nstruct swap_bytes<double, 8>\n{\n inline double operator()(double val)\n {\n uint64_t mem =swap_bytes<uint64_t, sizeof(uint64_t)>()(*(uint64_t*)&val);\n return *(double*)&mem;\n }\n};\n\ntemplate<endianness from, endianness to, class T>\nstruct do_byte_swap\n{\n inline T operator()(T value)\n {\n return swap_bytes<T, sizeof(T)>()(value);\n }\n};\n// specialisations when attempting to swap to the same endianess\ntemplate<class T> struct do_byte_swap<little_endian, little_endian, T> { inline T operator()(T value) { return value; } };\ntemplate<class T> struct do_byte_swap<big_endian, big_endian, T> { inline T operator()(T value) { return value; } };\n\n} // namespace detail\n\ntemplate<endianness from, endianness to, class T>\ninline T byte_swap(T value)\n{\n // ensure the data is only 1, 2, 4 or 8 bytes\n BOOST_STATIC_ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n // ensure we're only swapping arithmetic types\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n return detail::do_byte_swap<from, to, T>()(value);\n}\n // swaps val from host-byte-order to network-byte-order\nauto swapped = byte_swap<host_endian, network_endian>(val);\n // swap a value received from the network into host-byte-order\nauto val = byte_swap<network_endian, host_endian>(val_from_network);\n" }, { "answer_id": 4956493, "author": "Alexandre C.", "author_id": 373025, "author_profile": "https://Stackoverflow.com/users/373025", "pm_score": 7, "selected": false, "text": "#include <climits>\n\ntemplate <typename T>\nT swap_endian(T u)\n{\n static_assert (CHAR_BIT == 8, \"CHAR_BIT != 8\");\n\n union\n {\n T u;\n unsigned char u8[sizeof(T)];\n } source, dest;\n\n source.u = u;\n\n for (size_t k = 0; k < sizeof(T); k++)\n dest.u8[k] = source.u8[sizeof(T) - k - 1];\n\n return dest.u;\n}\n swap_endian<uint32_t>(42)" }, { "answer_id": 4956807, "author": "Maxim Egorushkin", "author_id": 412080, "author_profile": "https://Stackoverflow.com/users/412080", "pm_score": 3, "selected": false, "text": "<endian.h> #include <iostream>\n\n#include <endian.h>\n\ntemplate<size_t N> struct SizeT {};\n\n#define BYTESWAPS(bits) \\\ntemplate<class T> inline T htobe(T t, SizeT<bits / 8>) { return htobe ## bits(t); } \\\ntemplate<class T> inline T htole(T t, SizeT<bits / 8>) { return htole ## bits(t); } \\\ntemplate<class T> inline T betoh(T t, SizeT<bits / 8>) { return be ## bits ## toh(t); } \\\ntemplate<class T> inline T letoh(T t, SizeT<bits / 8>) { return le ## bits ## toh(t); }\n\nBYTESWAPS(16)\nBYTESWAPS(32)\nBYTESWAPS(64)\n\n#undef BYTESWAPS\n\ntemplate<class T> inline T htobe(T t) { return htobe(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T htole(T t) { return htole(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T betoh(T t) { return betoh(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T letoh(T t) { return letoh(t, SizeT<sizeof t>()); }\n\nint main()\n{\n std::cout << std::hex;\n std::cout << htobe(static_cast<unsigned short>(0xfeca)) << '\\n';\n std::cout << htobe(0xafbeadde) << '\\n';\n\n // Use ULL suffix to specify integer constant as unsigned long long \n std::cout << htobe(0xfecaefbeafdeedfeULL) << '\\n';\n}\n cafe\ndeadbeaf\nfeeddeafbeefcafe\n" }, { "answer_id": 6487066, "author": "friedemann", "author_id": 815363, "author_profile": "https://Stackoverflow.com/users/815363", "pm_score": 2, "selected": false, "text": "long swap(long i) {\n char *c = (char *) &i;\n return * (long *) (char[]) {c[3], c[2], c[1], c[0] };\n}\n" }, { "answer_id": 10346064, "author": "Matthieu M.", "author_id": 147192, "author_profile": "https://Stackoverflow.com/users/147192", "pm_score": 6, "selected": false, "text": "i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | ((unsigned)data[3]<<24);\n i = (data[3]<<0) | (data[2]<<8) | (data[1]<<16) | ((unsigned)data[0]<<24);\n int unsigned int unsigned int" }, { "answer_id": 18333053, "author": "user2699548", "author_id": 2699548, "author_profile": "https://Stackoverflow.com/users/2699548", "pm_score": 3, "selected": false, "text": "#define htonl(x) _byteswap_ulong(x)\n" }, { "answer_id": 18334154, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": 2, "selected": false, "text": "x = ((x & 0x00000000ffffffff) << 32) ^ ((x >> 32) & 0x00000000ffffffff);\nx = ((x & 0x0000ffff0000ffff) << 16) ^ ((x >> 16) & 0x0000ffff0000ffff);\nx = ((x & 0x00ff00ff00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff00ff00ff);\n x = ( x << 32) ^ (x >> 32);\n uint64_t k = 0x00000000ffffffff; /* compiler should know a trick for this */\nx = ((x & k) << 32) ^ ((x >> 32) & k);\nk ^= k << 16;\nx = ((x & k) << 16) ^ ((x >> 16) & k);\nk ^= k << 8;\nx = ((x & k) << 8) ^ ((x >> 8) & k);\n int i = sizeof(x) * CHAR_BIT / 2;\nuintmax_t k = (1 << i) - 1;\nwhile (i >= 8)\n{\n x = ((x & k) << i) ^ ((x >> i) & k);\n i >>= 1;\n k ^= k << i;\n}\n x = ( x << 16) ^ (x >> 16);\nx = ((x & 0x00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff);\n" }, { "answer_id": 25177297, "author": "The Quantum Physicist", "author_id": 1317944, "author_profile": "https://Stackoverflow.com/users/1317944", "pm_score": 3, "selected": false, "text": "template <typename T>\nvoid SwapEnd(T& var)\n{\n static_assert(std::is_pod<T>::value, \"Type must be POD type for safety\");\n std::array<char, sizeof(T)> varArray;\n std::memcpy(varArray.data(), &var, sizeof(T));\n for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)\n std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);\n std::memcpy(&var, varArray.data(), sizeof(T));\n}\n uint64_t uint8_t reinterpret_cast reinterpret_cast double x = 5;\nSwapEnd(x);\n x" }, { "answer_id": 25704741, "author": "Adam Freeman", "author_id": 538458, "author_profile": "https://Stackoverflow.com/users/538458", "pm_score": 2, "selected": false, "text": "// can be used for short, unsigned short, word, unsigned word (2-byte types)\n#define BYTESWAP16(n) (((n&0xFF00)>>8)|((n&0x00FF)<<8))\n\n// can be used for int or unsigned int or float (4-byte types)\n#define BYTESWAP32(n) ((BYTESWAP16((n&0xFFFF0000)>>16))|((BYTESWAP16(n&0x0000FFFF))<<16))\n\n// can be used for unsigned long long or double (8-byte types)\n#define BYTESWAP64(n) ((BYTESWAP32((n&0xFFFFFFFF00000000)>>32))|((BYTESWAP32(n&0x00000000FFFFFFFF))<<32))\n" }, { "answer_id": 26007257, "author": "The Welder", "author_id": 2086872, "author_profile": "https://Stackoverflow.com/users/2086872", "pm_score": 0, "selected": false, "text": "__declspec(naked) uint32_t EndianSwap(uint32 value)\n{\n __asm\n {\n mov eax, dword ptr[esp + 4]\n bswap eax\n ret\n }\n}\n unsigned long _byteswap_ulong(unsigned long value);\n mov ebx, eax\nshr ebx, 16\nxchg al, ah\nxchg bl, bh\nshl eax, 16\nor eax, ebx\n" }, { "answer_id": 35092546, "author": "Joao", "author_id": 1604608, "author_profile": "https://Stackoverflow.com/users/1604608", "pm_score": 2, "selected": false, "text": "template<typename T> inline static T swapByteOrder(const T& val) {\n int totalBytes = sizeof(val);\n T swapped = (T) 0;\n for (int i = 0; i < totalBytes; ++i) {\n swapped |= (val >> (8*(totalBytes-i-1)) & 0xFF) << (8*i);\n }\n return swapped;\n}\n" }, { "answer_id": 37386513, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 0, "selected": false, "text": "uint32_t sw_get_uint32_1234(pu32)\nuint32_1234 *pu32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32_1234[0] = (*pu32)[BO32_0];\n bou32.u32_1234[1] = (*pu32)[BO32_1];\n bou32.u32_1234[2] = (*pu32)[BO32_2];\n bou32.u32_1234[3] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_1234(pu32, u32)\nuint32_1234 *pu32;\nuint32_t u32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_1234[0];\n (*pu32)[BO32_1] = bou32.u32_1234[1];\n (*pu32)[BO32_2] = bou32.u32_1234[2];\n (*pu32)[BO32_3] = bou32.u32_1234[3];\n}\n\n#if HAS_SW_INT64\nint64 sw_get_int64_12345678(pi64)\nint64_12345678 *pi64;\n{\n union {\n int64_12345678 i64_12345678;\n int64 i64;\n } boi64;\n boi64.i64_12345678[0] = (*pi64)[BO64_0];\n boi64.i64_12345678[1] = (*pi64)[BO64_1];\n boi64.i64_12345678[2] = (*pi64)[BO64_2];\n boi64.i64_12345678[3] = (*pi64)[BO64_3];\n boi64.i64_12345678[4] = (*pi64)[BO64_4];\n boi64.i64_12345678[5] = (*pi64)[BO64_5];\n boi64.i64_12345678[6] = (*pi64)[BO64_6];\n boi64.i64_12345678[7] = (*pi64)[BO64_7];\n return(boi64.i64);\n}\n#endif\n\nint32_t sw_get_int32_3412(pi32)\nint32_3412 *pi32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32_3412[2] = (*pi32)[BO32_0];\n boi32.i32_3412[3] = (*pi32)[BO32_1];\n boi32.i32_3412[0] = (*pi32)[BO32_2];\n boi32.i32_3412[1] = (*pi32)[BO32_3];\n return(boi32.i32);\n}\n\nvoid sw_set_int32_3412(pi32, i32)\nint32_3412 *pi32;\nint32_t i32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32 = i32;\n (*pi32)[BO32_0] = boi32.i32_3412[2];\n (*pi32)[BO32_1] = boi32.i32_3412[3];\n (*pi32)[BO32_2] = boi32.i32_3412[0];\n (*pi32)[BO32_3] = boi32.i32_3412[1];\n}\n\nuint32_t sw_get_uint32_3412(pu32)\nuint32_3412 *pu32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32_3412[2] = (*pu32)[BO32_0];\n bou32.u32_3412[3] = (*pu32)[BO32_1];\n bou32.u32_3412[0] = (*pu32)[BO32_2];\n bou32.u32_3412[1] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_3412(pu32, u32)\nuint32_3412 *pu32;\nuint32_t u32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_3412[2];\n (*pu32)[BO32_1] = bou32.u32_3412[3];\n (*pu32)[BO32_2] = bou32.u32_3412[0];\n (*pu32)[BO32_3] = bou32.u32_3412[1];\n}\n\nfloat sw_get_float_1234(pf)\nfloat_1234 *pf;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f_1234[0] = (*pf)[BO32_0];\n bof.f_1234[1] = (*pf)[BO32_1];\n bof.f_1234[2] = (*pf)[BO32_2];\n bof.f_1234[3] = (*pf)[BO32_3];\n return(bof.f);\n}\n\nvoid sw_set_float_1234(pf, f)\nfloat_1234 *pf;\nfloat f;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f = (float)f;\n (*pf)[BO32_0] = bof.f_1234[0];\n (*pf)[BO32_1] = bof.f_1234[1];\n (*pf)[BO32_2] = bof.f_1234[2];\n (*pf)[BO32_3] = bof.f_1234[3];\n}\n\ndouble sw_get_double_12345678(pd)\ndouble_12345678 *pd;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d_12345678[0] = (*pd)[BO64_0];\n bod.d_12345678[1] = (*pd)[BO64_1];\n bod.d_12345678[2] = (*pd)[BO64_2];\n bod.d_12345678[3] = (*pd)[BO64_3];\n bod.d_12345678[4] = (*pd)[BO64_4];\n bod.d_12345678[5] = (*pd)[BO64_5];\n bod.d_12345678[6] = (*pd)[BO64_6];\n bod.d_12345678[7] = (*pd)[BO64_7];\n return(bod.d);\n}\n\nvoid sw_set_double_12345678(pd, d)\ndouble_12345678 *pd;\ndouble d;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d = d;\n (*pd)[BO64_0] = bod.d_12345678[0];\n (*pd)[BO64_1] = bod.d_12345678[1];\n (*pd)[BO64_2] = bod.d_12345678[2];\n (*pd)[BO64_3] = bod.d_12345678[3];\n (*pd)[BO64_4] = bod.d_12345678[4];\n (*pd)[BO64_5] = bod.d_12345678[5];\n (*pd)[BO64_6] = bod.d_12345678[6];\n (*pd)[BO64_7] = bod.d_12345678[7];\n}\n typedef char int8_1[1], uint8_1[1];\n\ntypedef char int16_12[2], uint16_12[2]; /* little endian */\ntypedef char int16_21[2], uint16_21[2]; /* big endian */\n\ntypedef char int24_321[3], uint24_321[3]; /* Alpha Micro, PDP-11 */\n\ntypedef char int32_1234[4], uint32_1234[4]; /* little endian */\ntypedef char int32_3412[4], uint32_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char int32_4321[4], uint32_4321[4]; /* big endian */\n\ntypedef char int64_12345678[8], uint64_12345678[8]; /* little endian */\ntypedef char int64_34128756[8], uint64_34128756[8]; /* Alpha Micro, PDP-11 */\ntypedef char int64_87654321[8], uint64_87654321[8]; /* big endian */\n\ntypedef char float_1234[4]; /* little endian */\ntypedef char float_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char float_4321[4]; /* big endian */\n\ntypedef char double_12345678[8]; /* little endian */\ntypedef char double_78563412[8]; /* Alpha Micro? */\ntypedef char double_87654321[8]; /* big endian */\n" }, { "answer_id": 39548833, "author": "pz64_", "author_id": 6737471, "author_profile": "https://Stackoverflow.com/users/6737471", "pm_score": 2, "selected": false, "text": "#define uint32_t unsigned \n#define uint16_t unsigned short\n\n#define swap16(x) ((((uint16_t)(x) & 0x00ff)<<8)| \\\n(((uint16_t)(x) & 0xff00)>>8))\n\n#define swap32(x) ((((uint32_t)(x) & 0x000000ff)<<24)| \\\n(((uint32_t)(x) & 0x0000ff00)<<8)| \\\n(((uint32_t)(x) & 0x00ff0000)>>8)| \\\n(((uint32_t)(x) & 0xff000000)>>24))\n" }, { "answer_id": 41196306, "author": "Ryan Hilbert", "author_id": 2884225, "author_profile": "https://Stackoverflow.com/users/2884225", "pm_score": 1, "selected": false, "text": "#define REVERSE_BYTES(...) do for(size_t REVERSE_BYTES=0; REVERSE_BYTES<sizeof(__VA_ARGS__)>>1; ++REVERSE_BYTES)\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES];\\\nwhile(0)\n int main(){\n unsigned long long x = 0xABCDEF0123456789;\n printf(\"Before: %llX\\n\",x);\n REVERSE_BYTES(x);\n printf(\"After : %llX\\n\",x);\n\n char c[7]=\"nametag\";\n printf(\"Before: %c%c%c%c%c%c%c\\n\",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n REVERSE_BYTES(c);\n printf(\"After : %c%c%c%c%c%c%c\\n\",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n}\n Before: ABCDEF0123456789\nAfter : 8967452301EFCDAB\nBefore: nametag\nAfter : gateman\n do while(0) REVERSE_BYTES for for ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES]\n((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES]\n __VA_ARGS__ unsigned char [] {}" }, { "answer_id": 44123161, "author": "Malcolm McLean", "author_id": 3310281, "author_profile": "https://Stackoverflow.com/users/3310281", "pm_score": -1, "selected": false, "text": "/*\n* read a double from a stream in ieee754 format regardless of host\n* encoding.\n* fp - the stream\n* bigendian - set to if big bytes first, clear for little bytes\n* first\n*\n*/\ndouble freadieee754(FILE *fp, int bigendian)\n{\n unsigned char buff[8];\n int i;\n double fnorm = 0.0;\n unsigned char temp;\n int sign;\n int exponent;\n double bitval;\n int maski, mask;\n int expbits = 11;\n int significandbits = 52;\n int shift;\n double answer;\n\n /* read the data */\n for (i = 0; i < 8; i++)\n buff[i] = fgetc(fp);\n /* just reverse if not big-endian*/\n if (!bigendian)\n {\n for (i = 0; i < 4; i++)\n {\n temp = buff[i];\n buff[i] = buff[8 - i - 1];\n buff[8 - i - 1] = temp;\n }\n }\n sign = buff[0] & 0x80 ? -1 : 1;\n /* exponet in raw format*/\n exponent = ((buff[0] & 0x7F) << 4) | ((buff[1] & 0xF0) >> 4);\n\n /* read inthe mantissa. Top bit is 0.5, the successive bits half*/\n bitval = 0.5;\n maski = 1;\n mask = 0x08;\n for (i = 0; i < significandbits; i++)\n {\n if (buff[maski] & mask)\n fnorm += bitval;\n\n bitval /= 2.0;\n mask >>= 1;\n if (mask == 0)\n {\n mask = 0x80;\n maski++;\n }\n }\n /* handle zero specially */\n if (exponent == 0 && fnorm == 0)\n return 0.0;\n\n shift = exponent - ((1 << (expbits - 1)) - 1); /* exponent = shift + bias */\n /* nans have exp 1024 and non-zero mantissa */\n if (shift == 1024 && fnorm != 0)\n return sqrt(-1.0);\n /*infinity*/\n if (shift == 1024 && fnorm == 0)\n {\n\n#ifdef INFINITY\n return sign == 1 ? INFINITY : -INFINITY;\n#endif\n return (sign * 1.0) / 0.0;\n }\n if (shift > -1023)\n {\n answer = ldexp(fnorm + 1.0, shift);\n return answer * sign;\n }\n else\n {\n /* denormalised numbers */\n if (fnorm == 0.0)\n return 0.0;\n shift = -1022;\n while (fnorm < 1.0)\n {\n fnorm *= 2;\n shift--;\n }\n answer = ldexp(fnorm, shift);\n return answer * sign;\n }\n}\n" }, { "answer_id": 55634732, "author": "Quinn Carver", "author_id": 2953356, "author_profile": "https://Stackoverflow.com/users/2953356", "pm_score": 0, "selected": false, "text": "template<typename T>void swap(T &t){\n for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n *((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n }\n}\n" }, { "answer_id": 55756299, "author": "cycollins", "author_id": 8611540, "author_profile": "https://Stackoverflow.com/users/8611540", "pm_score": 0, "selected": false, "text": "std::vector<uint16_t> storage(n); // where n is the number to be converted\n\n// the following would do the trick\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n #if (__DARWIN_BYTE_ORDER != __DARWIN_BIG_ENDIAN)\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n#endif\n" }, { "answer_id": 61146679, "author": "Thinkal VB", "author_id": 7057208, "author_profile": "https://Stackoverflow.com/users/7057208", "pm_score": 1, "selected": false, "text": "#include <algorithm>\n template <typename T>\nvoid swapEndian(T& buffer)\n{\n static_assert(std::is_pod<T>::value, \"swapEndian support POD type only\");\n char* startIndex = static_cast<char*>((void*)buffer.data());\n char* endIndex = startIndex + sizeof(buffer);\n std::reverse(startIndex, endIndex);\n}\n swapEndian (stlContainer);\n" }, { "answer_id": 63106400, "author": "Mrocco", "author_id": 12178397, "author_profile": "https://Stackoverflow.com/users/12178397", "pm_score": 1, "selected": false, "text": "void endianness_swap(uint32_t& val) {\n uint8_t a, b, c;\n a = (val & 0xFF000000) >> 24;\n b = (val & 0x00FF0000) >> 16;\n c = (val & 0x0000FF00) >> 8;\n val=(val & 0x000000FF) << 24;\n val = val + (c << 16) + (b << 8) + (a);\n}\n" }, { "answer_id": 67458876, "author": "Sunny127", "author_id": 1925162, "author_profile": "https://Stackoverflow.com/users/1925162", "pm_score": -1, "selected": false, "text": "void writeLittleEndianToBigEndian(void* ptrLittleEndian, void* ptrBigEndian , size_t bufLen )\n{\n char *pchLittleEndian = (char*)ptrLittleEndian;\n\n char *pchBigEndian = (char*)ptrBigEndian;\n\n for ( size_t i = 0 ; i < bufLen ; i++ ) \n pchBigEndian[bufLen-1-i] = pchLittleEndian[i];\n}\n\nstd::uint32_t row = 0x12345678;\n\nchar buf[4]; \n\nwriteLittleEndianToBigEndian( &row, &buf, sizeof(row) );\n" }, { "answer_id": 67681004, "author": "natersoz", "author_id": 138264, "author_profile": "https://Stackoverflow.com/users/138264", "pm_score": 0, "selected": false, "text": "#include <cstdint>\n#include <type_traits>\n\n/**\n * Perform an endian swap of bytes against a templatized unsigned word.\n *\n * @tparam value_type The data type to perform the endian swap against.\n * @param value The data value to swap.\n *\n * @return value_type The resulting swapped word.\n */\ntemplate <typename value_type>\nconstexpr inline auto endian_swap(value_type value) -> value_type\n{\n using half_type = typename std::conditional<\n sizeof(value_type) == 8u,\n uint32_t,\n typename std::conditional<sizeof(value_type) == 4u, uint16_t, uint8_t>::\n type>::type;\n\n size_t const half_bits = sizeof(value_type) * 8u / 2u;\n half_type const upper_half = static_cast<half_type>(value >> half_bits);\n half_type const lower_half = static_cast<half_type>(value);\n\n if (sizeof(value_type) == 2u)\n {\n return (static_cast<value_type>(lower_half) << half_bits) | upper_half;\n }\n\n return ((static_cast<value_type>(endian_swap(lower_half)) << half_bits) |\n endian_swap(upper_half));\n}\n" }, { "answer_id": 69500743, "author": "Glenn Teitelbaum", "author_id": 2963099, "author_profile": "https://Stackoverflow.com/users/2963099", "pm_score": 0, "selected": false, "text": "#include <bit>\n#include <type_traits>\n#include <concepts>\n#include <array>\n#include <cstring>\n#include <iostream>\n#include <bitset>\n\ntemplate <int LEN, int OFF=LEN/2>\nclass do_swap\n{\n // FOR 8 bytes:\n // LEN=8 (LEN/2==4) <H><G><F><E><D><C><B><A>\n // OFF=4: FROM=0, TO=7 => [A]<G><F><E><D><C><B>[H]\n // OFF=3: FROM=1, TO=6 => [A][B]<F><E><D><C>[G][H]\n // OFF=2: FROM=2, TO=5 => [A][B][C]<E><D>[F][G][H]\n // OFF=1: FROM=3, TO=4 => [A][B][C][D][E][F][G][H]\n // OFF=0: FROM=4, TO=3 => DONE\npublic:\n enum consts {FROM=LEN/2-OFF, TO=(LEN-1)-FROM};\n using NXT=do_swap<LEN, OFF-1>;\n// flip the first and last for the current iteration's range\n static void flip(std::array<std::byte, LEN>& b)\n {\n std::byte tmp=b[FROM];\n b[FROM]=b[TO];\n b[TO]=tmp;\n NXT::flip(b);\n }\n};\ntemplate <int LEN>\nclass do_swap<LEN, 0> // STOP the template recursion\n{\npublic:\n static void flip(std::array<std::byte, LEN>&)\n {\n }\n};\n\ntemplate<std::integral T, std::endian TO, std::endian FROM=std::endian::native>\n requires ((TO==std::endian::big) || (TO==std::endian::little))\n && ((FROM==std::endian::big) || (FROM==std::endian::little))\nclass endian_swap\n{\npublic:\n enum consts {BYTE_COUNT=sizeof(T)};\n static T cvt(const T integral)\n {\n // if FROM and TO are the same -- nothing to do\n if (TO==FROM)\n {\n return integral;\n }\n\n // endian::big --> endian::little is the same as endian::little --> endian::big\n // the bytes have to be reversed\n // memcpy seems to be the most supported way to do byte swaps in a defined way\n std::array<std::byte, BYTE_COUNT> bytes;\n std::memcpy(&bytes, &integral, BYTE_COUNT);\n do_swap<BYTE_COUNT>::flip(bytes);\n T ret;\n std::memcpy(&ret, &bytes, BYTE_COUNT);\n return ret;\n }\n};\n\nstd::endian big()\n{\n return std::endian::big;\n}\n\nstd::endian little()\n{\n return std::endian::little;\n}\n\nstd::endian native()\n{\n return std::endian::native;\n}\n\nlong long swap_to_big(long long x)\n{\n return endian_swap<long long, std::endian::big>::cvt(x);\n}\n\nlong long swap_to_little(long long x)\n{\n return endian_swap<long long, std::endian::little>::cvt(x);\n}\n\nvoid show(std::string label, long long x)\n{\n std::cout << label << \"\\t: \" << std::bitset<64>(x) << \" (\" << x << \")\" << std::endl;\n}\n\nint main(int argv, char ** argc)\n{\n long long init=0xF8FCFEFF7F3F1F0;\n long long to_big=swap_to_big(init);\n long long to_little=swap_to_little(init);\n show(\"Init\", init);\n show(\">big\", to_big);\n show(\">little\", to_little);\n}\n" }, { "answer_id": 74330996, "author": "yano", "author_id": 3476780, "author_profile": "https://Stackoverflow.com/users/3476780", "pm_score": 0, "selected": false, "text": "boost::endian::endian_reverse #include <iostream>\n#include <iomanip>\n#include \"boost/endian/conversion.hpp\"\n\nint main()\n{\n uint32_t word = 0x01;\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word << std::endl;\n // outputs 00000001;\n\n uint32_t word2 = boost::endian::endian_reverse(word);\n // there's also a `void ::endian_reverse_inplace(...) function\n // that reverses the value passed to it in place and returns nothing\n\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word2 << std::endl;\n // outputs 01000000\n\n return 0;\n}\n std::byteswap" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ]
105,308
<p>I want to take the url: <a href="http://www.mydomain.com/signup-12345" rel="nofollow noreferrer">http://www.mydomain.com/signup-12345</a></p> <p>And actually give them: <a href="http://www.mydomain.com/signup/?aff=12345" rel="nofollow noreferrer">http://www.mydomain.com/signup/?aff=12345</a></p> <p>I have NO history with mod_rewrite, HELP!</p>
[ { "answer_id": 111010, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "RewriteCond %{query_string}& ^aff=((.+&)|&)$ \nRewriteRule ^/signup-old-script.asp$ /signup-new-script.php?affID=%2 [L,R]\n" }, { "answer_id": 5170559, "author": "Ship", "author_id": 641583, "author_profile": "https://Stackoverflow.com/users/641583", "pm_score": 1, "selected": false, "text": "IsapiRewrite" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13704/" ]
105,311
<p>What is a "table-driven method"?</p> <p>As mentioned by Bill Gates in the <a href="https://www.youtube.com/watch?v=nNOohFst9Lc" rel="nofollow noreferrer">second Windows Vista commercial</a> at 1:05.</p>
[ { "answer_id": 118492, "author": "David Medinets", "author_id": 219658, "author_profile": "https://Stackoverflow.com/users/219658", "pm_score": 2, "selected": false, "text": "hash[tv] = process_tv_records\nhash[cable] = process_cable_records\n" }, { "answer_id": 28268626, "author": "Drake Sobania", "author_id": 2788862, "author_profile": "https://Stackoverflow.com/users/2788862", "pm_score": 3, "selected": false, "text": "if table number == 1\n table has 4 seats\nelse if table number == 2\n table has 8 seats\n. . .\n tables [] = {4, 8, 2, 4, ...}\ntable seats = tables[table number]\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19272/" ]
105,330
<p>I have a dev, that will get around our code coverage by writing tests that never fail.</p> <p>The code is just atrocious, but the tests never catch it because they assert(true).</p> <p>I code review, but I can't do everyones work for them, all the time. How do you get people like this motivated to make good software?</p> <p>Is there a build plugin for detecting tests that can't fail?</p> <p>C#, mbUnit tests.</p>
[ { "answer_id": 105351, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 0, "selected": false, "text": "assert(true) grep" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
105,349
<p>I am using bash in os X Terminal app, and my custom $PS1 breaks when I scroll through my history.</p> <pre><code>PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\n\[${red}\$${NC}\]" </code></pre> <p>also tried PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\r\n[${red}\$${NC}]" </p> <p>The problem seems to be in the newline. I have used this bash prompt on Slackware no prob.</p>
[ { "answer_id": 105658, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 0, "selected": false, "text": "\\[ \\] PS1=\"${BLUE}\\u${CYAN}@${RED}\\h${BLUE}\\w\\n${red}\\$${NC}\"\n \\[ \\]" }, { "answer_id": 105922, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 0, "selected": false, "text": "PS1=\"${BLUE}\\u${CYAN}@${RED}\\h${BLUE}\\w${RED}\\r\\n\\$\\[${blue}\\]\"\n" }, { "answer_id": 1911711, "author": "Hedgehog", "author_id": 152860, "author_profile": "https://Stackoverflow.com/users/152860", "pm_score": 2, "selected": false, "text": "function _my_prompt ()\n{ \n # magic goes here\n my_prmpt=.... \n}\nPROMPT_COMMAND='_my_prompt'\nPS1=\"[\\$my_prmpt] \\$\"\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
105,372
<p>How can you enumerate an <code>enum</code> in C#?</p> <p>E.g. the following code does not compile:</p> <pre class="lang-cs prettyprint-override"><code>public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } </code></pre> <p>And it gives the following compile-time error:</p> <blockquote> <p>'Suit' is a 'type' but is used like a 'variable'</p> </blockquote> <p>It fails on the <code>Suit</code> keyword, the second one.</p>
[ { "answer_id": 105401, "author": "Tom Carr", "author_id": 14954, "author_profile": "https://Stackoverflow.com/users/14954", "pm_score": 6, "selected": false, "text": "Enum.GetNames(Suit)\n" }, { "answer_id": 105402, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 13, "selected": true, "text": "foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))\n{\n}\n (Suit[])" }, { "answer_id": 105421, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 10, "selected": false, "text": "Enum.GetNames() public enum Suits\n{\n Spades,\n Hearts,\n Clubs,\n Diamonds,\n NumSuits\n}\n\npublic void PrintAllSuits()\n{\n foreach (string name in Enum.GetNames(typeof(Suits)))\n {\n System.Console.WriteLine(name);\n }\n}\n Enum.GetValues(typeof(Suit)) public enum Suits\n{\n Spades,\n Hearts,\n Clubs,\n Diamonds,\n NumSuits\n}\n\npublic void PrintAllSuits()\n{\n foreach (var suit in Enum.GetValues(typeof(Suits)))\n {\n System.Console.WriteLine(suit.ToString());\n }\n}\n" }, { "answer_id": 105617, "author": "Joshua Drake", "author_id": 19308, "author_profile": "https://Stackoverflow.com/users/19308", "pm_score": 6, "selected": false, "text": "public void PrintAllSuits()\n{\n foreach(string suit in Enum.GetNames(typeof(Suits)))\n {\n Console.WriteLine(suit);\n }\n}\n" }, { "answer_id": 944352, "author": "bob", "author_id": 23805, "author_profile": "https://Stackoverflow.com/users/23805", "pm_score": 9, "selected": false, "text": "public static class EnumExtensions\n{\n /// <summary>\n /// Gets all items for an enum value.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n public static IEnumerable<T> GetAllItems<T>(this Enum value)\n {\n foreach (object item in Enum.GetValues(typeof(T)))\n {\n yield return (T)item;\n }\n }\n\n /// <summary>\n /// Gets all items for an enum type.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n public static IEnumerable<T> GetAllItems<T>() where T : struct\n {\n foreach (object item in Enum.GetValues(typeof(T)))\n {\n yield return (T)item;\n }\n }\n\n /// <summary>\n /// Gets all combined items from an enum value.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n /// <example>\n /// Displays ValueA and ValueB.\n /// <code>\n /// EnumExample dummy = EnumExample.Combi;\n /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())\n /// {\n /// Console.WriteLine(item);\n /// }\n /// </code>\n /// </example>\n public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)\n {\n int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);\n\n foreach (object item in Enum.GetValues(typeof(T)))\n {\n int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);\n\n if (itemAsInt == (valueAsInt & itemAsInt))\n {\n yield return (T)item;\n }\n }\n }\n\n /// <summary>\n /// Determines whether the enum value contains a specific value.\n /// </summary>\n /// <param name=\"value\">The value.</param>\n /// <param name=\"request\">The request.</param>\n /// <returns>\n /// <c>true</c> if value contains the specified value; otherwise, <c>false</c>.\n /// </returns>\n /// <example>\n /// <code>\n /// EnumExample dummy = EnumExample.Combi;\n /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))\n /// {\n /// Console.WriteLine(\"dummy contains EnumExample.ValueA\");\n /// }\n /// </code>\n /// </example>\n public static bool Contains<T>(this Enum value, T request)\n {\n int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);\n int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);\n\n if (requestAsInt == (valueAsInt & requestAsInt))\n {\n return true;\n }\n\n return false;\n }\n}\n [Flags]\npublic enum EnumExample\n{\n ValueA = 1,\n ValueB = 2,\n ValueC = 4,\n ValueD = 8,\n Combi = ValueA | ValueB\n}\n" }, { "answer_id": 1375234, "author": "Ekevoo", "author_id": 98029, "author_profile": "https://Stackoverflow.com/users/98029", "pm_score": 8, "selected": false, "text": "Enum.GetValues public Enum[] GetValues(Enum enumeration)\n{\n FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);\n Enum[] enumerations = new Enum[fields.Length];\n\n for (var i = 0; i < fields.Length; i++)\n enumerations[i] = (Enum) fields[i].GetValue(enumeration);\n\n return enumerations;\n}\n" }, { "answer_id": 1743591, "author": "lmat - Reinstate Monica", "author_id": 200985, "author_profile": "https://Stackoverflow.com/users/200985", "pm_score": 6, "selected": false, "text": "foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }\n Array enums = Enum.GetValues(typeof(Suit));\nforeach (Suit suitEnum in enums) \n{\n DoSomething(suitEnum);\n}\n" }, { "answer_id": 3195229, "author": "Mallox", "author_id": 81112, "author_profile": "https://Stackoverflow.com/users/81112", "pm_score": 6, "selected": false, "text": "public static List<T> GetEnumValues<T>() where T : new() {\n T valueType = new T();\n return typeof(T).GetFields()\n .Select(fieldInfo => (T)fieldInfo.GetValue(valueType))\n .Distinct()\n .ToList();\n}\n\npublic static List<String> GetEnumNames<T>() {\n return typeof (T).GetFields()\n .Select(info => info.Name)\n .Distinct()\n .ToList();\n}\n T valueType = new T() List<MyEnum> result = Utils.GetEnumValues<MyEnum>();\n" }, { "answer_id": 4200724, "author": "Aubrey Taylor", "author_id": 510266, "author_profile": "https://Stackoverflow.com/users/510266", "pm_score": 6, "selected": false, "text": "Enum.GetValues() public class EnumHelper\n{\n public static T[] GetValues<T>()\n {\n Type enumType = typeof(T);\n\n if (!enumType.IsEnum)\n {\n throw new ArgumentException(\"Type '\" + enumType.Name + \"' is not an enum\");\n }\n\n List<T> values = new List<T>();\n\n var fields = from field in enumType.GetFields()\n where field.IsLiteral\n select field;\n\n foreach (FieldInfo field in fields)\n {\n object value = field.GetValue(enumType);\n values.Add((T)value);\n }\n\n return values.ToArray();\n }\n\n public static object[] GetValues(Type enumType)\n {\n if (!enumType.IsEnum)\n {\n throw new ArgumentException(\"Type '\" + enumType.Name + \"' is not an enum\");\n }\n\n List<object> values = new List<object>();\n\n var fields = from field in enumType.GetFields()\n where field.IsLiteral\n select field;\n\n foreach (FieldInfo field in fields)\n {\n object value = field.GetValue(enumType);\n values.Add(value);\n }\n\n return values.ToArray();\n }\n}\n" }, { "answer_id": 9113274, "author": "James", "author_id": 1185191, "author_profile": "https://Stackoverflow.com/users/1185191", "pm_score": 7, "selected": false, "text": "GetValues() Suit enum EnumLoop<Suit>.ForEach((suit) => {\n DoSomethingWith(suit);\n});\n EnumLoop class EnumLoop<Key> where Key : struct, IConvertible {\n static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));\n static internal void ForEach(Action<Key> act) {\n for (int i = 0; i < arr.Length; i++) {\n act(arr[i]);\n }\n }\n}\n" }, { "answer_id": 11666195, "author": "Mickey Perlstein", "author_id": 1125913, "author_profile": "https://Stackoverflow.com/users/1125913", "pm_score": 5, "selected": false, "text": "[Flags]\npublic enum ABC {\n a = 1,\n b = 2,\n c = 4\n};\n\npublic IEnumerable<ABC> Getselected (ABC flags)\n{\n var values = flags.ToString().Split(',');\n var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));\n return enums;\n}\n\nABC temp= ABC.a | ABC.b;\nvar list = getSelected (temp);\nforeach (var item in list)\n{\n Console.WriteLine(item.ToString() + \" ID=\" + (int)item);\n}\n" }, { "answer_id": 13077473, "author": "jhilden", "author_id": 1173800, "author_profile": "https://Stackoverflow.com/users/1173800", "pm_score": 4, "selected": false, "text": "var resman = ViewModelResources.TimeFrame.ResourceManager;\n\nViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame\n in Enum.GetValues(typeof(MapOverlayTimeFrames))\n select new SelectListItem\n {\n Value = timeFrame.ToString(),\n Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()\n };\n" }, { "answer_id": 14513140, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 4, "selected": false, "text": "public void EnumerateEnum<T>()\n{\n int length = Enum.GetValues(typeof(T)).Length;\n for (var i = 0; i < length; i++)\n {\n var @enum = (T)(object)i;\n }\n}\n public void EnumerateEnum()\n{\n for (var i = Suit.Spade; i <= Suit.Diamond; i++)\n {\n var @enum = i;\n }\n}\n" }, { "answer_id": 15457453, "author": "sircodesalot", "author_id": 2043536, "author_profile": "https://Stackoverflow.com/users/2043536", "pm_score": 7, "selected": false, "text": "Cast<T> var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();\n IEnumerable<Suit>" }, { "answer_id": 17121612, "author": "Darkside", "author_id": 606847, "author_profile": "https://Stackoverflow.com/users/606847", "pm_score": 5, "selected": false, "text": "public static class EnumExtensions\n{\n /// <summary>\n /// Gets all items for an enum value.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum\n {\n return (T[])Enum.GetValues(typeof (T));\n }\n}\n" }, { "answer_id": 18191073, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 5, "selected": false, "text": "Enum.GetValues(type) type.GetEnumValues() type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null)) GetEnumValues Enum<T> public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible\n{\n public static IEnumerable<T> GetValues()\n {\n return (T[])Enum.GetValues(typeof(T));\n }\n\n public static IEnumerable<string> GetNames()\n {\n return Enum.GetNames(typeof(T));\n }\n}\n Enum<Suit>.GetValues();\n\n// Or\nEnum.GetValues(typeof(Suit)); // Pretty consistent style\n public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible\n{\n // Lazily loaded\n static T[] values;\n static string[] names;\n\n public static IEnumerable<T> GetValues()\n {\n return values ?? (values = (T[])Enum.GetValues(typeof(T)));\n }\n\n public static IEnumerable<string> GetNames()\n {\n return names ?? (names = Enum.GetNames(typeof(T)));\n }\n}\n" }, { "answer_id": 20009790, "author": "dmihailescu", "author_id": 376495, "author_profile": "https://Stackoverflow.com/users/376495", "pm_score": 4, "selected": false, "text": "public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible\n{\n if (typeof(T).BaseType != typeof(Enum))\n {\n throw new ArgumentException(string.Format(\"{0} is not of type System.Enum\", typeof(T)));\n }\n return Enum.GetValues(typeof(T)) as T[];\n}\n static readonly YourEnum[] _values = GetEnumValues<YourEnum>();\n IEnumerable<T>" }, { "answer_id": 21231697, "author": "matt burns", "author_id": 276093, "author_profile": "https://Stackoverflow.com/users/276093", "pm_score": 4, "selected": false, "text": "foreach (Suit suit in Enum.GetValues(typeof(Suit)))\n{\n}\n" }, { "answer_id": 22941865, "author": "anar khalilov", "author_id": 437979, "author_profile": "https://Stackoverflow.com/users/437979", "pm_score": 4, "selected": false, "text": "((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));\n" }, { "answer_id": 25814247, "author": "Gabriel", "author_id": 632986, "author_profile": "https://Stackoverflow.com/users/632986", "pm_score": 4, "selected": false, "text": "public static Dictionary<int, string> ToList<T>() where T : struct\n{\n return ((IEnumerable<T>)Enum\n .GetValues(typeof(T)))\n .ToDictionary(\n item => Convert.ToInt32(item),\n item => item.ToString());\n}\n var enums = EnumHelper.ToList<MyEnum>();\n" }, { "answer_id": 31096712, "author": "Ross Gatih", "author_id": 1747521, "author_profile": "https://Stackoverflow.com/users/1747521", "pm_score": 4, "selected": false, "text": "class Pack\n{\n public const int NumSuits = 4;\n public const int CardsPerSuit = 13;\n private PlayingCard[,] cardPack;\n\n public Pack()\n {\n this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];\n for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)\n {\n for (Value value = Value.Two; value <= Value.Ace; value++)\n {\n cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);\n }\n }\n }\n}\n Suit Value enum Suit { Clubs, Diamonds, Hearts, Spades }\nenum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}\n PlayingCard Suit Value class PlayingCard\n{\n private readonly Suit suit;\n private readonly Value value;\n\n public PlayingCard(Suit s, Value v)\n {\n this.suit = s;\n this.value = v;\n }\n}\n" }, { "answer_id": 32884992, "author": "Slappywag", "author_id": 4218542, "author_profile": "https://Stackoverflow.com/users/4218542", "pm_score": 3, "selected": false, "text": "enum public class EnumHelper\n{\n public static IEnumerable<T> GetValues<T>()\n {\n return Enum.GetValues(typeof(T)).Cast<T>();\n }\n\n public static IEnumerable getListOfEnum(Type type)\n {\n MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod(\"GetValues\").MakeGenericMethod(type);\n return (IEnumerable)getValuesMethod.Invoke(null, null);\n }\n}\n getListOfEnum IEnumerable Type myType = someEnumValue.GetType();\n\nIEnumerable resultEnumerable = getListOfEnum(myType);\n\nforeach (var item in resultEnumerable)\n{\n Console.WriteLine(String.Format(\"Item: {0} Value: {1}\",item.ToString(),(int)item));\n}\n" }, { "answer_id": 34953875, "author": "Kylo Ren", "author_id": 4576125, "author_profile": "https://Stackoverflow.com/users/4576125", "pm_score": 5, "selected": false, "text": "Enum 1. var values = Enum.GetValues(typeof(myenum))\n2. var values = Enum.GetNames(typeof(myenum))\n object String foreach foreach(var value in values)\n{\n // Do operations here\n}\n" }, { "answer_id": 41558833, "author": "Termininja", "author_id": 3618581, "author_profile": "https://Stackoverflow.com/users/3618581", "pm_score": 2, "selected": false, "text": "typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)\n .ToList().ForEach(x => DoSomething(x.Name));\n" }, { "answer_id": 43134553, "author": "MUT", "author_id": 5863303, "author_profile": "https://Stackoverflow.com/users/5863303", "pm_score": 4, "selected": false, "text": "public static IEnumerable<T> GetValues<T>() public static IEnumerable<T> GetValues<T>()\n{\n return Enum.GetValues(typeof(T)).Cast<T>();\n}\n foreach public static void EnumerateAllSuitsDemoMethod()\n {\n // Custom method\n var foos = GetValues<Suit>();\n foreach (var foo in foos)\n {\n // Do something\n }\n }\n" }, { "answer_id": 46680065, "author": "Emily Chen", "author_id": 4549031, "author_profile": "https://Stackoverflow.com/users/4549031", "pm_score": 3, "selected": false, "text": "enum" }, { "answer_id": 58249447, "author": "R.Akhlaghi", "author_id": 2830315, "author_profile": "https://Stackoverflow.com/users/2830315", "pm_score": 3, "selected": false, "text": "List<int> listEnumValues = new List<int>();\nYourEnumType[] myEnumMembers = (YourEnumType[])Enum.GetValues(typeof(YourEnumType));\nforeach ( YourEnumType enumMember in myEnumMembers)\n{\n listEnumValues.Add(enumMember.GetHashCode());\n}\n" }, { "answer_id": 58974242, "author": "rlv-dan", "author_id": 1087811, "author_profile": "https://Stackoverflow.com/users/1087811", "pm_score": 1, "selected": false, "text": "enum Suit\n{\n Spades,\n Hearts,\n Clubs,\n Diamonds\n}\n foreach (var e in Enum.GetValues(typeof(Suit)))\n{\n Console.WriteLine(e.ToString() + \" = \" + (int)e);\n}\n Spades = 0\nHearts = 1\nClubs = 2\nDiamonds = 3\n" }, { "answer_id": 58975533, "author": "Erçin Dedeoğlu", "author_id": 2426367, "author_profile": "https://Stackoverflow.com/users/2426367", "pm_score": 0, "selected": false, "text": " public static Dictionary<int, string> ToList<T>() where T : struct =>\n ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());\n var enums = ToList<Enum>();\n" }, { "answer_id": 65103244, "author": "Arad", "author_id": 7734384, "author_profile": "https://Stackoverflow.com/users/7734384", "pm_score": 7, "selected": false, "text": "GetValues Suit[] suitValues = Enum.GetValues<Suit>();\n foreach (Suit suit in Enum.GetValues<Suit>())\n{\n\n}\n GetNames string[] suitNames = Enum.GetNames<Suit>();\n" }, { "answer_id": 66007982, "author": "Inam Abbas", "author_id": 7258037, "author_profile": "https://Stackoverflow.com/users/7258037", "pm_score": 0, "selected": false, "text": "public class Program\n{\n\n public static List<T> GetEnamList<T>()\n {\n var enums = Enum.GetValues(typeof(T)).Cast<T>().Select(v => v).ToList();\n return enums;\n }\n private void LoadEnumList()\n {\n List<DayofWeek> dayofweeks = GetEnamList<DayofWeek>();\n\n foreach (var item in dayofweeks)\n {\n dayofweeks.Add(item);\n }\n }\n}\n\n public enum DayofWeek\n {\n Monday,\n Tuesday,\n Wensday,\n Thursday,\n Friday,\n Sturday,\n Sunday\n }\n" }, { "answer_id": 66110060, "author": "marsh-wiggle", "author_id": 1574221, "author_profile": "https://Stackoverflow.com/users/1574221", "pm_score": 2, "selected": false, "text": "enum DemoFlags\n{\n DemoFlag = 1,\n OtherFlag = 2,\n TestFlag = 4,\n LastFlag = 8,\n}\n DemoFlags demoFlags = DemoFlags.DemoFlag | DemoFlags.TestFlag;\n \"DemoFlag | TestFlag\"\n public static string ConvertToEnumString<T>(T enumToConvert, string separator = \" | \") where T : Enum\n{\n StringBuilder convertedEnums = new StringBuilder();\n\n foreach (T enumValue in Enum.GetValues(typeof(T)))\n {\n if (enumToConvert.HasFlag(enumValue)) convertedEnums.Append($\"{ enumValue }{separator}\");\n }\n\n if (convertedEnums.Length > 0) convertedEnums.Length -= separator.Length;\n\n return convertedEnums.ToString();\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
105,400
<p>I am maintaining a pretty sizable application and database and am noticing some poor database performance in a few of our stored procedures.</p> <p>I always hear that "adding an index" can be done to help performance. I am certainly no DBA, and I do not understand what indexes are, why they help, and how to create them.</p> <p>I basically need an indexes 101. </p> <p>Can anyone give me resources so that I can learn?</p>
[ { "answer_id": 105503, "author": "TrevorD", "author_id": 12492, "author_profile": "https://Stackoverflow.com/users/12492", "pm_score": 0, "selected": false, "text": "create index <indexname> on <tablename>(<column1>[,<column2>...])\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
105,418
<p>I want to be able to figure out what port a particular program is using. Are there any programs available online or that come with windows that will tell me which processes are using which ports on my computer?</p> <p>PS - before you downmod this for not being a programming question, I'm looking for the program to test some networking code.</p>
[ { "answer_id": 105447, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "netstat" }, { "answer_id": 105448, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 8, "selected": true, "text": "netstat -b -a -n -b" }, { "answer_id": 106478, "author": "Jim Olsen", "author_id": 15603, "author_profile": "https://Stackoverflow.com/users/15603", "pm_score": 5, "selected": false, "text": "C:\\>netstat -ano\n\nActive Connections\n\n Proto Local Address Foreign Address State PID\n ...\n TCP [::]:49335 [::]:0 LISTENING 1056\n ...\n\nC:\\>tasklist /fi \"pid eq 1056\"\n\nImage Name PID Session Name Session# Mem Usage\n========================= ======== ================ =========== ============\nsqlservr.exe 1056 Services 0 66,192 K\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021/" ]
105,477
<p>I think I've got it down to the most basic case:</p> <pre><code>int main(int argc, char ** argv) { int * arr; foo(arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1; } void foo(int * arr) { arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69; } </code></pre> <p>The output is this:</p> <pre class="lang-none prettyprint-override"><code>&gt; ./a.out car[3]=-1869558540 a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer being freed *** set a breakpoint in malloc_error_break to debug &gt; </code></pre> <p>If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.</p>
[ { "answer_id": 105507, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 3, "selected": false, "text": "void foo( int ** arr) {\n *arr = (int *)malloc( sizeof(int) * 25 );\n (*arr)[3] = 69;\n}\n" }, { "answer_id": 105508, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 7, "selected": true, "text": "int main(int argc, char ** argv) {\n int * arr;\n\n foo(arr);\n printf(\"car[3]=%d\\n\",arr[3]);\n free (arr);\n return 1;\n}\n\nvoid foo(int * &arr ) {\n arr = (int*) malloc( sizeof(int)*25 );\n arr[3] = 69;\n}\n int main(int argc, char ** argv) {\n int * arr;\n\n arr = foo();\n printf(\"car[3]=%d\\n\",arr[3]);\n free (arr);\n return 1;\n}\n\nint * foo(void ) {\n int * arr;\n arr = (int*) malloc( sizeof(int)*25 );\n arr[3] = 69;\n return arr;\n}\n int main(int argc, char ** argv) {\n int * arr;\n\n foo(&arr);\n printf(\"car[3]=%d\\n\",arr[3]);\n free (arr);\n return 1;\n}\n\nvoid foo(int ** arr ) {\n (*arr) = (int*) malloc( sizeof(int)*25 );\n (*arr)[3] = 69;\n}\n" }, { "answer_id": 105539, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 2, "selected": false, "text": "int * foo() {\n return (int*) malloc( sizeof(int)*25 );\n}\n\nint main() {\n int* arr = foo();\n}\n void foo(int ** arr) {\n *arr = malloc(...);\n}\n\nint main() {\n foo(&arr);\n}\n void foo(int * & arr)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
105,479
<p>We want to maintain 3 webservices for the different steps of deployment, but how do we define in our application which service to use? Do we just maintain 3 web references and ifdef the uses of them somehow?</p>
[ { "answer_id": 107077, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "msbuild /t:deploy $(SERVER) $(USERNAME) msbuild /t:deploy /p:server=test msbuild /t:deploy /p:server=live /p:secret=foo" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17176/" ]
105,499
<p>I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy. </p> <p>If I use the web service, then it is possible to set proxy. </p>
[ { "answer_id": 108530, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 1, "selected": false, "text": " Dim client As ProductServiceClient = New ProductServiceClient(\"wsHttpProductService\")\n client.ClientCredentials.UserName.UserName = \"username\"\n client.ClientCredentials.UserName.Password = \"password\"\n Dim ProductList As List(Of Product) = client.GetProducts()\n mView.Products = ProductList\n client.Close()\n" }, { "answer_id": 108532, "author": "Pawel Pabich", "author_id": 3323, "author_profile": "https://Stackoverflow.com/users/3323", "pm_score": 3, "selected": true, "text": " MyClient client = new MyClient();\n client.ClientCredentials.UserName.UserName = \"u\";\n client.ClientCredentials.UserName.Password = \"p\";\n" }, { "answer_id": 6354185, "author": "Diganta Kumar", "author_id": 798727, "author_profile": "https://Stackoverflow.com/users/798727", "pm_score": 2, "selected": false, "text": " // username token credentials\n var clientCredentials = new ClientCredentials();\n clientCredentials.UserName.UserName = ConfigurationManager.AppSettings[\"Client.Mpgs.Username\"];\n clientCredentials.UserName.Password = ConfigurationManager.AppSettings[\"Client.Mpgs.Password\"];\n proxy.ChannelFactory.Endpoint.Behaviors.Remove(typeof(ClientCredentials));\n proxy.ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);\n\n // proxy credentials \n //http://kennyw.com/indigo/143\n //http://blogs.msdn.com/b/stcheng/archive/2008/12/03/wcf-how-to-supply-dedicated-credentials-for-webproxy-authentication.aspx\n proxy.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential\n (\n ConfigurationManager.AppSettings[\"Client.ProxyServer.Username\"]\n , ConfigurationManager.AppSettings[\"Client.ProxyServer.Password\"]\n , ConfigurationManager.AppSettings[\"Client.ProxyServer.DomainName\"]\n );\n <system.net>\n <defaultProxy useDefaultCredentials=\"true\">\n <proxy usesystemdefault=\"True\" proxyaddress=\"http://proxyServer:8080/\" bypassonlocal=\"False\" autoDetect=\"False\" /> </defaultProxy>\n</system.net>\n<system.serviceModel>\n <bindings>\n <wsHttpBinding>\n <binding name=\"WSHttpBinding_ITest\" closeTimeout=\"00:01:00\" openTimeout=\"00:01:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:01:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"65536\" messageEncoding=\"Text\" textEncoding=\"utf-8\" useDefaultWebProxy=\"true\" allowCookies=\"false\">\n <readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\"/>\n <reliableSession ordered=\"true\" inactivityTimeout=\"00:10:00\" enabled=\"false\"/>\n <security mode=\"TransportWithMessageCredential\">\n <transport clientCredentialType=\"None\" proxyCredentialType=\"None\" realm=\"\"/>\n <message clientCredentialType=\"UserName\" negotiateServiceCredential=\"true\" algorithmSuite=\"Default\"/>\n </security>\n </binding>\n </wsHttpBinding>\n </bindings>\n <client>\n <endpoint address=\"https://wcfservice.organisation.com/test/test.svc\" binding=\"wsHttpBinding\" bindingConfiguration=\"WSHttpBinding_ITest\" contract=\"Test.Test\" name=\"WSHttpBinding_ITest\"/>\n </client>\n</system.serviceModel>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19146/" ]
105,504
<p>When retrieving a lookup code value from a table, some folks do this...</p> <pre><code>Dim dtLookupCode As New LookupCodeDataTable() Dim taLookupCode AS New LookupCodeTableAdapter() Dim strDescription As String dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL") strDescription = dtLookupCode.Item(0).Meaning </code></pre> <p>...however, I've also seen things done "chained" like this...</p> <pre><code>strDescription = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL").Item(0).Meaning </code></pre> <p>...which bypasses having a lookup code data table in the first place since the table adapter knows what the structure of its result set looks like.</p> <p>Does using the "chained" method save the overhead of creating the data table object, or does it effectively get created anyway in order to properly handle the .Item(0).Meaning statement?</p>
[ { "answer_id": 105548, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 2, "selected": false, "text": "if (ConfigurationManager.AppSettings(\"ConnectionString\") == null)\n{\n throw new MissingConfigSettingException(\"ConnectionString\");\n}\n\nstring connectionString = ConfigurationManager.AppSettings(\"ConnectionString\");\n string connectionString = ConfigurationManager.AppSettings(\"ConnectionString\")\n\nif (connectionString == null)\n{\n throw new MissingConfigSettingException(\"ConnectionString\");\n}\n // Disassembled AppSettings member of ConfigurationManager \n\npublic static NameValueCollection AppSettings\n{\n get\n {\n object section = GetSection(\"appSettings\");\n\n if ((section == null) || !(section is NameValueCollection))\n {\n throw new\n ConfigurationErrorsException(SR.GetString(\"Config_appsettings_declaration_invalid\"));\n }\n\n return (NameValueCollection) section;\n }\n}\n" }, { "answer_id": 105573, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": true, "text": "Dim dtLookupCode As New LookupCodeDataTable()\nDim taLookupCode AS New LookupCodeTableAdapter()\n dtLookupCode = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\n dtLookupCode Dim taLookupCode AS New LookupCodeTableAdapter\nDim dtLookupCode As LookupCodeDataTable\nDim strDescription As String\n\ndtLookupCode = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\nstrDescription = dtLookupCode.Item(0).Meaning\n Dim taLookupCode AS New LookupCodeTableAdapter\nDim dtLookupCode As LookupCodeDataTable = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\nDim strDescription As String = dtLookupCode.Item(0).Meaning\n" }, { "answer_id": 105574, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 0, "selected": false, "text": "dtLookupCode = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\nstrDescription = dtLookupCode.Item(0).Meaning\n strDescription = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\").Item(0).Meaning\n Dim dtLookupCode As New LookupCodeDataTable()\n LookupCodeDataTable Dim dtLookupCode As LookupCodeDataTable\n" }, { "answer_id": 105795, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 1, "selected": false, "text": "function getMeaning( lookupCode as LookupCodeDataTable)\n getMeaning=lookupCode.Item(0).Meaning\nend function\n strDescription=getMeaning(taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\"))\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
105,522
<p>OK, so things have progressed significantly with my DSL since I asked <a href="https://stackoverflow.com/questions/82776/how-do-i-reference-a-diagram-in-a-dsl-t4-template">this question</a> a few days ago.</p> <p>As soon as I've refactored my code, I'll post my own answer to that one, but for now, I'm having another problem.</p> <p>I'm dynamically generating sub-diagrams from a DSL-created model, saving those diagrams as images and then generating a Word document with those images embedded. So far, so good.</p> <p> But where my shapes have compartments (for examples, Operations on a Service Contract - can you guess what it is, yet?), the compartment header is displayed but <b>none of the items</b>.</p> <p>If I examine my shape object, it has a single nested child - an ElementListCompartment which in turn, has a number of items that I'm expecting to be displayed. The ElementListCompartment.IsExpanded property is set to true (and the compartment header has a little 'collapse' icon on it) but where, oh where, are my items?</p> <p>The shape was added to the diagram using</p> <pre><code>parentShape.FixupChildShapes(modelElement); </code></pre> <p>So, can anyone guide me on my merry way?</p>
[ { "answer_id": 1068424, "author": "Eugene Burmako", "author_id": 131615, "author_profile": "https://Stackoverflow.com/users/131615", "pm_score": 3, "selected": true, "text": "private Store LoadStore()\n{\n var store = new Store();\n store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));\n return store;\n}\n\nprivate void LoadDiagram(Store store)\n{\n using (var tx = store.TransactionManager.BeginTransaction(\"tx\", true))\n {\n var validator = new ValidationController();\n var deserializer = ActiveWriterSerializationHelper.Instance;\n deserializer.LoadModelAndDiagram(store,\n @\"..\\..\\ActiveWriter1.actiw\", @\"..\\..\\ActiveWriter1.actiw.diagram\", null, validator);\n tx.Commit();\n }\n}\n\nprivate DiagramView CreateDiagramView()\n{\n var store = LoadStore();\n LoadDiagram(store);\n\n using (var tx = store.TransactionManager.BeginTransaction(\"tx2\", true))\n {\n var dir = store.DefaultPartition.ElementDirectory;\n var diag = dir.FindElements<ActiveRecordMapping>().SingleOrDefault();\n var view = new DiagramView(){Diagram = diag};\n diag.Associate(view);\n tx.Commit();\n\n view.Dock = DockStyle.Fill;\n return view;\n }\n}\n\nprotected override void OnLoad(EventArgs e)\n{\n var view = CreateDiagramView();\n this.Controls.Add(view);\n}\n private Store LoadStore()\n{\n var store = new Store();\n store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));\n ActiveWriterDomainModel.EnableDiagramRules(store);\n return store;\n}\n\n/// <summary>\n/// Enables rules in this domain model related to diagram fixup for the given store.\n/// If diagram data will be loaded into the store, this method should be called first to ensure\n/// that the diagram behaves properly.\n/// </summary>\npublic static void EnableDiagramRules(DslModeling::Store store)\n{\n if(store == null) throw new global::System.ArgumentNullException(\"store\");\n\n DslModeling::RuleManager ruleManager = store.RuleManager;\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.FixUpDiagram));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.ConnectorRolePlayerChanged));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemAddRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemDeleteRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerChangeRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerPositionChangeRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemChangeRule));\n}\n Diagram.FixUpDiagram(parentElement, childElement) childElement parentElement EnsureCompartments" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5806/" ]
105,535
<p>I have a VmWare virtual machine that is coming dangerously close to it's primarry HDD's limit and I need to extend it. How do I do this? I'm working with VmWare Workstation 6.0.5</p>
[ { "answer_id": 105547, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": true, "text": "vmware-vdiskmanager -x 12GB path\\to\\disk.vmdk\n" }, { "answer_id": 105571, "author": "Paul Mrozowski", "author_id": 3656, "author_profile": "https://Stackoverflow.com/users/3656", "pm_score": 0, "selected": false, "text": "vmware-vdiskmanager.exe -x 50Gb NameOfDisk.vmdk\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980/" ]
105,556
<p>We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents?</p>
[ { "answer_id": 105591, "author": "Cyberherbalist", "author_id": 16964, "author_profile": "https://Stackoverflow.com/users/16964", "pm_score": 2, "selected": true, "text": "I:\\>xsd\nMicrosoft (R) Xml Schemas/DataTypes support utility\n[Microsoft (R) .NET Framework, Version 1.0.3705.0]\nCopyright (C) Microsoft Corporation 1998-2001. All rights reserved.\n\n\nxsd.exe -\n Utility to generate schema or class files from given source.\n\nxsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/uri:]\nxsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]\nxsd.exe <instance>.xml [/outputdir:]\nxsd.exe <schema>.xdr [/outputdir:]\n" }, { "answer_id": 325715, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 1, "selected": false, "text": "<xs:element name=\"foo\" type=\"footype\" minOccurs=\"0\" maxOccurs=\"unbounded\" /> \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
105,564
<p>The original query looks like this (MySQL):</p> <pre><code>SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date </code></pre> <p>Would it be possible to rewrite it (without unions or procedures), so that result will look like this:</p> <ul> <li>list of books where title matches query ordered by date, followed by:</li> <li>list of books where description matches query ordered by date</li> </ul> <p>So basically just give a higher priority to matching titles over descriptions.</p>
[ { "answer_id": 105580, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": -1, "selected": false, "text": "SELECT *, 1 as order from books where title like '%text%'\nunion\nSELECT *, 2 as order from books where description like '%text%'\nORDER BY order, date\n" }, { "answer_id": 105588, "author": "Rory", "author_id": 8479, "author_profile": "https://Stackoverflow.com/users/8479", "pm_score": 5, "selected": true, "text": "select * from books \nwhere title like '%text%' or description like '%text%'\norder by case when title like '%text%' then 1 else 2 end, date\n" }, { "answer_id": 105589, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 2, "selected": false, "text": "select * from books \nwhere title like \"%text%\" or description like \"%text%\" \norder by date, case when title like \"%text%\" then 0 else 1 end\n" }, { "answer_id": 105622, "author": "K Richard", "author_id": 16771, "author_profile": "https://Stackoverflow.com/users/16771", "pm_score": 0, "selected": false, "text": "order by case when title like '%text%' then 0 else 1 end\n" }, { "answer_id": 105629, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select * \nfrom books \nwhere title like \"%text%\" \nor description like \"%text%\" \norder by case when title like \"%text%\" then 1 else 0 end desc, date\n" }, { "answer_id": 108825, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 0, "selected": false, "text": "DECLARE @Books TABLE\n(\n [ID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,\n [Title] NVARCHAR(MAX) NOT NULL,\n [Description] NVARCHAR(MAX) NOT NULL,\n [Date] DATETIME NOT NULL\n)\n\nINSERT INTO @Books\nSELECT 'War and Peace','A Russian Epic','2008-01-01' UNION\nSELECT 'Dogs of War','Mercenary Stories','2006-01-01' UNION\nSELECT 'World At Arms','A Story of World War Two','2007-01-01' UNION\nSELECT 'The B Team','Street Wars','2005-01-01' \n\nSELECT * FROM\n(\n SELECT *, CASE WHEN [Title] LIKE '%war%' THEN 1 WHEN [Description] LIKE '%war%' THEN 2 END AS Ord\n FROM @Books\n WHERE [Title] LIKE '%war%' OR [Description] LIKE '%war%'\n) AS Derived\nORDER BY Ord ASC, [Date] ASC\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
105,572
<p>Is there a <code>SQL</code> or <code>PHP</code> script that I can run that will change the default collation in all tables and fields in a database?</p> <p>I can write one myself, but I think that this should be something that readily available at a site like this. If I can come up with one myself before somebody posts one, I will post it myself.</p>
[ { "answer_id": 105614, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 4, "selected": false, "text": "<?php\n// your connection\nmysql_connect(\"localhost\",\"root\",\"***\");\nmysql_select_db(\"db1\");\n\n// convert code\n$res = mysql_query(\"SHOW TABLES\");\nwhile ($row = mysql_fetch_array($res))\n{\n foreach ($row as $key => $table)\n {\n mysql_query(\"ALTER TABLE \" . $table . \" CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci\");\n echo $key . \" =&gt; \" . $table . \" CONVERTED<br />\";\n }\n}\n?> \n" }, { "answer_id": 106272, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<?php\n\nfunction MysqlError()\n{\n if (mysql_errno())\n {\n echo \"<b>Mysql Error: \" . mysql_error() . \"</b>\\n\";\n }\n}\n\n$username = \"root\";\n$password = \"\";\n$db = \"database\";\n$host = \"localhost\";\n\n$target_charset = \"utf8\";\n$target_collate = \"utf8_general_ci\";\n\necho \"<pre>\";\n\n$conn = mysql_connect($host, $username, $password);\nmysql_select_db($db, $conn);\n\n$tabs = array();\n$res = mysql_query(\"SHOW TABLES\");\nMysqlError();\nwhile (($row = mysql_fetch_row($res)) != null)\n{\n $tabs[] = $row[0];\n}\n\n// now, fix tables\nforeach ($tabs as $tab)\n{\n $res = mysql_query(\"show index from {$tab}\");\n MysqlError();\n $indicies = array();\n\n while (($row = mysql_fetch_array($res)) != null)\n {\n if ($row[2] != \"PRIMARY\")\n {\n $indicies[] = array(\"name\" => $row[2], \"unique\" => !($row[1] == \"1\"), \"col\" => $row[4]);\n mysql_query(\"ALTER TABLE {$tab} DROP INDEX {$row[2]}\");\n MysqlError();\n echo \"Dropped index {$row[2]}. Unique: {$row[1]}\\n\";\n }\n }\n\n $res = mysql_query(\"DESCRIBE {$tab}\");\n MysqlError();\n while (($row = mysql_fetch_array($res)) != null)\n {\n $name = $row[0];\n $type = $row[1];\n $set = false;\n if (preg_match(\"/^varchar\\((\\d+)\\)$/i\", $type, $mat))\n {\n $size = $mat[1];\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} VARBINARY({$size})\");\n MysqlError();\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} VARCHAR({$size}) CHARACTER SET {$target_charset}\");\n MysqlError();\n $set = true;\n\n echo \"Altered field {$name} on {$tab} from type {$type}\\n\";\n }\n else if (!strcasecmp($type, \"CHAR\"))\n {\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} BINARY(1)\");\n MysqlError();\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} VARCHAR(1) CHARACTER SET {$target_charset}\");\n MysqlError();\n $set = true;\n\n echo \"Altered field {$name} on {$tab} from type {$type}\\n\";\n }\n else if (!strcasecmp($type, \"TINYTEXT\"))\n {\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} TINYBLOB\");\n MysqlError();\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} TINYTEXT CHARACTER SET {$target_charset}\");\n MysqlError();\n $set = true;\n\n echo \"Altered field {$name} on {$tab} from type {$type}\\n\";\n }\n else if (!strcasecmp($type, \"MEDIUMTEXT\"))\n {\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} MEDIUMBLOB\");\n MysqlError();\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} MEDIUMTEXT CHARACTER SET {$target_charset}\");\n MysqlError();\n $set = true;\n\n echo \"Altered field {$name} on {$tab} from type {$type}\\n\";\n }\n else if (!strcasecmp($type, \"LONGTEXT\"))\n {\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} LONGBLOB\");\n MysqlError();\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} LONGTEXT CHARACTER SET {$target_charset}\");\n MysqlError();\n $set = true;\n\n echo \"Altered field {$name} on {$tab} from type {$type}\\n\";\n }\n else if (!strcasecmp($type, \"TEXT\"))\n {\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} BLOB\");\n MysqlError();\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} TEXT CHARACTER SET {$target_charset}\");\n MysqlError();\n $set = true;\n\n echo \"Altered field {$name} on {$tab} from type {$type}\\n\";\n }\n\n if ($set)\n mysql_query(\"ALTER TABLE {$tab} MODIFY {$name} COLLATE {$target_collate}\");\n }\n\n // re-build indicies..\n foreach ($indicies as $index)\n {\n if ($index[\"unique\"])\n {\n mysql_query(\"CREATE UNIQUE INDEX {$index[\"name\"]} ON {$tab} ({$index[\"col\"]})\");\n MysqlError();\n }\n else\n {\n mysql_query(\"CREATE INDEX {$index[\"name\"]} ON {$tab} ({$index[\"col\"]})\");\n MysqlError();\n }\n\n echo \"Created index {$index[\"name\"]} on {$tab}. Unique: {$index[\"unique\"]}\\n\";\n }\n\n // set default collate\n mysql_query(\"ALTER TABLE {$tab} DEFAULT CHARACTER SET {$target_charset} COLLATE {$target_collate}\");\n}\n\n// set database charset\nmysql_query(\"ALTER DATABASE {$db} DEFAULT CHARACTER SET {$target_charset} COLLATE {$target_collate}\");\n\nmysql_close($conn);\necho \"</pre>\";\n\n?>\n" }, { "answer_id": 669746, "author": "DavidWinterbottom", "author_id": 25517, "author_profile": "https://Stackoverflow.com/users/25517", "pm_score": 6, "selected": false, "text": "mysql --database=dbname -B -N -e \"SHOW TABLES\" \\\n| awk '{print \"SET foreign_key_checks = 0; ALTER TABLE\", $1, \"CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; \"}' \\\n| mysql --database=dbname &\n --user --password mysql SET foreign_key_checks = 0; SET foreign_key_checks = 1;" }, { "answer_id": 3090459, "author": "Ivan", "author_id": 372802, "author_profile": "https://Stackoverflow.com/users/372802", "pm_score": 5, "selected": false, "text": "SELECT CONCAT('ALTER TABLE `', t.`TABLE_SCHEMA`, '`.`', t.`TABLE_NAME`,\n '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') as stmt \nFROM `information_schema`.`TABLES` t\nWHERE 1\nAND t.`TABLE_SCHEMA` = 'database_name'\nORDER BY 1\n" }, { "answer_id": 10872664, "author": "Alexander I.Grafov", "author_id": 830979, "author_profile": "https://Stackoverflow.com/users/830979", "pm_score": 1, "selected": false, "text": "SHOW TABLES SELECT table_name\n , table_collation \nFROM information_schema.tables\n" }, { "answer_id": 16079203, "author": "RameshVel", "author_id": 97572, "author_profile": "https://Stackoverflow.com/users/97572", "pm_score": 2, "selected": false, "text": "awk for t in $(mysql --user=root --password=admin --database=DBNAME -e \"show tables\";);do echo \"Altering\" $t;mysql --user=root --password=admin --database=DBNAME -e \"ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;\";done\n for t in $(mysql --user=root --password=admin --database=DBNAME -e \"show tables\";);\n do \n echo \"Altering\" $t;\n mysql --user=root --password=admin --database=DBNAME -e \"ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;\";\n done\n" }, { "answer_id": 19312653, "author": "Abdennour TOUMI", "author_id": 747579, "author_profile": "https://Stackoverflow.com/users/747579", "pm_score": 0, "selected": false, "text": "collatedb <username> <password> <database> <collation>\n collatedb root 0000 myDatabase utf8_bin\n" }, { "answer_id": 24254872, "author": "dtbaker", "author_id": 457850, "author_profile": "https://Stackoverflow.com/users/457850", "pm_score": 0, "selected": false, "text": "latin1_swedish_ci utf8_general_ci latin1_swedish_ci utf8_general_ci // list the names of your wordpress plugin database tables (without db prefix)\n$tables_to_check = array(\n 'social_message',\n 'social_facebook',\n 'social_facebook_message',\n 'social_facebook_page',\n 'social_google',\n 'social_google_mesage',\n 'social_twitter',\n 'social_twitter_message',\n);\n// choose the collate to search for and replace:\n$convert_fields_collate_from = 'latin1_swedish_ci';\n$convert_fields_collate_to = 'utf8_general_ci';\n$convert_tables_character_set_to = 'utf8';\n$show_debug_messages = false;\nglobal $wpdb;\n$wpdb->show_errors();\nforeach($tables_to_check as $table) {\n $table = $wpdb->prefix . $table;\n $indicies = $wpdb->get_results( \"SHOW INDEX FROM `$table`\", ARRAY_A );\n $results = $wpdb->get_results( \"SHOW FULL COLUMNS FROM `$table`\" , ARRAY_A );\n foreach($results as $result){\n if($show_debug_messages)echo \"Checking field \".$result['Field'] .\" with collat: \".$result['Collation'].\"\\n\";\n if(isset($result['Field']) && $result['Field'] && isset($result['Collation']) && $result['Collation'] == $convert_fields_collate_from){\n if($show_debug_messages)echo \"Table: $table - Converting field \" .$result['Field'] .\" - \" .$result['Type'].\" - from $convert_fields_collate_from to $convert_fields_collate_to \\n\";\n // found a field to convert. check if there's an index on this field.\n // we have to remove index before converting field to binary.\n $is_there_an_index = false;\n foreach($indicies as $index){\n if ( isset($index['Column_name']) && $index['Column_name'] == $result['Field']){\n // there's an index on this column! store it for adding later on.\n $is_there_an_index = $index;\n $wpdb->query( $wpdb->prepare( \"ALTER TABLE `%s` DROP INDEX %s\", $table, $index['Key_name']) );\n if($show_debug_messages)echo \"Dropped index \".$index['Key_name'].\" before converting field.. \\n\";\n break;\n }\n }\n $set = false;\n\n if ( preg_match( \"/^varchar\\((\\d+)\\)$/i\", $result['Type'], $mat ) ) {\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARBINARY({$mat[1]})\" );\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARCHAR({$mat[1]}) CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}\" );\n $set = true;\n } else if ( !strcasecmp( $result['Type'], \"CHAR\" ) ) {\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` BINARY(1)\" );\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARCHAR(1) CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}\" );\n $set = true;\n } else if ( !strcasecmp( $result['Type'], \"TINYTEXT\" ) ) {\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TINYBLOB\" );\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TINYTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}\" );\n $set = true;\n } else if ( !strcasecmp( $result['Type'], \"MEDIUMTEXT\" ) ) {\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` MEDIUMBLOB\" );\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` MEDIUMTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}\" );\n $set = true;\n } else if ( !strcasecmp( $result['Type'], \"LONGTEXT\" ) ) {\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` LONGBLOB\" );\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` LONGTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}\" );\n $set = true;\n } else if ( !strcasecmp( $result['Type'], \"TEXT\" ) ) {\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` BLOB\" );\n $wpdb->query( \"ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}\" );\n $set = true;\n }else{\n if($show_debug_messages)echo \"Failed to change field - unsupported type: \".$result['Type'].\"\\n\";\n }\n if($set){\n if($show_debug_messages)echo \"Altered field success! \\n\";\n $wpdb->query( \"ALTER TABLE `$table` MODIFY {$result['Field']} COLLATE $convert_fields_collate_to\" );\n }\n if($is_there_an_index !== false){\n // add the index back.\n if ( !$is_there_an_index[\"Non_unique\"] ) {\n $wpdb->query( \"CREATE UNIQUE INDEX `{$is_there_an_index['Key_name']}` ON `{$table}` ({$is_there_an_index['Column_name']})\", $is_there_an_index['Key_name'], $table, $is_there_an_index['Column_name'] );\n } else {\n $wpdb->query( \"CREATE UNIQUE INDEX `{$is_there_an_index['Key_name']}` ON `{$table}` ({$is_there_an_index['Column_name']})\", $is_there_an_index['Key_name'], $table, $is_there_an_index['Column_name'] );\n }\n }\n }\n }\n // set default collate\n $wpdb->query( \"ALTER TABLE `{$table}` DEFAULT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}\" );\n if($show_debug_messages)echo \"Finished with table $table \\n\";\n}\n$wpdb->hide_errors();\n" }, { "answer_id": 33494889, "author": "Luca Camillo", "author_id": 1964225, "author_profile": "https://Stackoverflow.com/users/1964225", "pm_score": 0, "selected": false, "text": "var elems = $('dfn'); var lastID = elems.length - 1;\nelems.each(function(i) {\n if ($(this).html() != 'utf8_general_ci') { \n $('input:checkbox', $('td', $(this).parent().parent()).first()).attr('checked','checked');\n } \n\n if (i == lastID) {\n $(\"button[name='submit_mult'][value='change']\").click();\n }\n});\n $(\"select[name*='field_collation']\" ).val('utf8_general_ci');\n" }, { "answer_id": 42545503, "author": "davewy", "author_id": 4451284, "author_profile": "https://Stackoverflow.com/users/4451284", "pm_score": 0, "selected": false, "text": "latin1_bin <?php\n\n/////////// BEGIN CONFIG ////////////////////\n\n$username = \"\";\n$password = \"\";\n$db = \"\";\n$host = \"\";\n\n$target_charset = \"utf8\";\n$target_collation = \"utf8_unicode_ci\";\n$target_bin_collation = \"utf8_bin\";\n\n/////////// END CONFIG ////////////////////\n\nfunction MySQLSafeQuery($conn, $query) {\n $res = mysqli_query($conn, $query);\n if (mysqli_errno($conn)) {\n echo \"<b>Mysql Error: \" . mysqli_error($conn) . \"</b>\\n\";\n echo \"<span>This query caused the above error: <i>\" . $query . \"</i></span>\\n\";\n }\n return $res;\n}\n\nfunction binary_typename($type) {\n $mysql_type_to_binary_type_map = array(\n \"VARCHAR\" => \"VARBINARY\",\n \"CHAR\" => \"BINARY(1)\",\n \"TINYTEXT\" => \"TINYBLOB\",\n \"MEDIUMTEXT\" => \"MEDIUMBLOB\",\n \"LONGTEXT\" => \"LONGBLOB\",\n \"TEXT\" => \"BLOB\"\n );\n\n $typename = \"\";\n if (preg_match(\"/^varchar\\((\\d+)\\)$/i\", $type, $mat))\n $typename = $mysql_type_to_binary_type_map[\"VARCHAR\"] . \"(\" . (2*$mat[1]) . \")\";\n else if (!strcasecmp($type, \"CHAR\"))\n $typename = $mysql_type_to_binary_type_map[\"CHAR\"] . \"(1)\";\n else if (array_key_exists(strtoupper($type), $mysql_type_to_binary_type_map))\n $typename = $mysql_type_to_binary_type_map[strtoupper($type)];\n return $typename;\n}\n\necho \"<pre>\";\n\n// Connect to database\n$conn = mysqli_connect($host, $username, $password);\nmysqli_select_db($conn, $db);\n\n// Get list of tables\n$tabs = array();\n$query = \"SHOW TABLES\";\n$res = MySQLSafeQuery($conn, $query);\nwhile (($row = mysqli_fetch_row($res)) != null)\n $tabs[] = $row[0];\n\n// Now fix tables\nforeach ($tabs as $tab) {\n $res = MySQLSafeQuery($conn, \"SHOW INDEX FROM `{$tab}`\");\n $indicies = array();\n\n while (($row = mysqli_fetch_array($res)) != null) {\n if ($row[2] != \"PRIMARY\") {\n $append = true;\n foreach ($indicies as $index) {\n if ($index[\"name\"] == $row[2]) {\n $index[\"col\"][] = $row[4];\n $append = false;\n }\n }\n if($append)\n $indicies[] = array(\"name\" => $row[2], \"unique\" => !($row[1] == \"1\"), \"col\" => array($row[4]));\n }\n }\n\n foreach ($indicies as $index) {\n MySQLSafeQuery($conn, \"ALTER TABLE `{$tab}` DROP INDEX `{$index[\"name\"]}`\");\n echo \"Dropped index {$index[\"name\"]}. Unique: {$index[\"unique\"]}\\n\";\n }\n\n $res = MySQLSafeQuery($conn, \"SHOW FULL COLUMNS FROM `{$tab}`\");\n while (($row = mysqli_fetch_array($res)) != null) {\n $name = $row[0];\n $type = $row[1];\n $current_collation = $row[2];\n $target_collation_bak = $target_collation;\n if(!strcasecmp($current_collation, \"latin1_bin\"))\n $target_collation = $target_bin_collation;\n $set = false;\n $binary_typename = binary_typename($type);\n if ($binary_typename != \"\") {\n MySQLSafeQuery($conn, \"ALTER TABLE `{$tab}` MODIFY `{$name}` {$binary_typename}\");\n MySQLSafeQuery($conn, \"ALTER TABLE `{$tab}` MODIFY `{$name}` {$type} CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'\");\n $set = true;\n echo \"Altered field {$name} on {$tab} from type {$type}\\n\";\n }\n $target_collation = $target_collation_bak;\n }\n\n // Rebuild indicies\n foreach ($indicies as $index) {\n // Handle multi-column indices\n $joined_col_str = \"\";\n foreach ($index[\"col\"] as $col)\n $joined_col_str = $joined_col_str . \", `\" . $col . \"`\";\n $joined_col_str = substr($joined_col_str, 2);\n\n $query = \"\";\n if ($index[\"unique\"])\n $query = \"CREATE UNIQUE INDEX `{$index[\"name\"]}` ON `{$tab}` ({$joined_col_str})\";\n else\n $query = \"CREATE INDEX `{$index[\"name\"]}` ON `{$tab}` ({$joined_col_str})\";\n MySQLSafeQuery($conn, $query);\n\n echo \"Created index {$index[\"name\"]} on {$tab}. Unique: {$index[\"unique\"]}\\n\";\n }\n\n // Set default character set and collation for table\n MySQLSafeQuery($conn, \"ALTER TABLE `{$tab}` DEFAULT CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'\");\n}\n\n// Set default character set and collation for database\nMySQLSafeQuery($conn, \"ALTER DATABASE `{$db}` DEFAULT CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'\");\n\nmysqli_close($conn);\necho \"</pre>\";\n\n?>\n" }, { "answer_id": 43817316, "author": "Lost Koder", "author_id": 2851483, "author_profile": "https://Stackoverflow.com/users/2851483", "pm_score": 0, "selected": false, "text": "mysql.exe --database=[database] -u [user] -p[password] -B -N -e \"SHOW TABLES\" \\\n| awk.exe '{print \"SET foreign_key_checks = 0; ALTER TABLE\", $1, \"CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; \"}' \\\n| mysql.exe -u [user] -p[password] --database=[database] &\n" }, { "answer_id": 70567152, "author": "Khaled Lela", "author_id": 1283715, "author_profile": "https://Stackoverflow.com/users/1283715", "pm_score": 0, "selected": false, "text": "php artisan make:migration update_character_set_utf8_m4 $DBNAME = config('database.connections.mysql.database');\n$CHARACTER = 'utf8mb4';\n$COLLATE = 'utf8mb4_unicode_ci';\n\necho \"Altering DB $DBNAME\\n\";\nDB::unprepared(\"ALTER DATABASE $DBNAME CHARACTER SET $CHARACTER COLLATE $COLLATE;\");\n\n$tables = DB::select(\"SELECT table_name FROM information_schema.tables WHERE table_schema = '{$DBNAME}'\");\nforeach ($tables as $table) {\n echo \"Altering $table->table_name\\n\";\n DB::unprepared(\"ALTER TABLE $table->table_name CONVERT TO CHARACTER SET $CHARACTER COLLATE $COLLATE;\");\n}\n php artisan migrate" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
105,602
<p>I have inherited a monster.</p> <p>It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.</p> <p>To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.</p> <p>This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.</p> <p>My question is, what methods would you suggest to refactor or restructure such a thing?</p> <p>I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.</p> <p>Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.</p> <p>Thanks for any and all ideas.</p>
[ { "answer_id": 106482, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 4, "selected": false, "text": "if else if (someCondition)\n{\n 100+ lines of code\n {\n ...\n }\n}\nelse\n{\n simple statement here\n}\n if" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19304/" ]
105,604
<p>I've just installed MediaWiki on a web server. Obviously it needs lots of privileges during installation to set up its database correctly. Now that it's installed can I safely revoke some privileges (e.g. create table, drop table?) Or might it need to create more tables later (when they are first needed?) If not then I would prefer to grant it as few privileges as possible.</p>
[ { "answer_id": 105952, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 3, "selected": true, "text": "grant select,lock tables,insert on media_wiki_db.* to 'wiki'@'localhost' identified by 'password';\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12048/" ]
105,607
<p>I love BlogEngine. But from what I can se it does not collect the standard information about the visitors I would like to see (referrer, browser-type and so on). </p> <p>When I log in as Admin I have a menu item named "Referrer". I can choose a weekday and then I'll be presented with 1 or 2 rows with </p> <p>"google.com 4 hits, "itmaskinen.se 6 hits" and so on, But that's not what I want to se, I want to se where my visitors come from, country, IP if possible, how many visitors and so on. </p> <p>If someone of you are familiar with Blogengine.Net and can point me in the right direction to where I would put my own log-code or if you know any visitor-statistic-extension that can do it for me, I would be really happy to know. I prefer an extension, because if I make changes myself to BlogEngine it may break later updates I install. </p> <p>Blogengine.Net is a blog software made in .Net found here: <a href="http://www.dotnetblogengine.net/" rel="noreferrer">http://www.dotnetblogengine.net/</a> </p> <p>And yes, I prefer to take this question here rather then in the Blogengine.Net forum, you know why. ;) </p> <p>(Anyone, feel free to edit my (bad) english in this post and after that delete this sentence) </p>
[ { "answer_id": 224194, "author": "Rafe", "author_id": 27497, "author_profile": "https://Stackoverflow.com/users/27497", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\n var pageTracker = _gat._getTracker(\"UA-129049-25\");\n var userDefinedValue = '<%= System.Web.Security.Membership.GetUser() != null ? System.Web.Security.Membership.GetUser().UserName : \"\" %>';\n pageTracker._setVar(userDefinedValue);\n pageTracker._trackPageview();\n</script>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19307/" ]
105,609
<p>I have an enum that looks as follows:</p> <pre><code>public enum TransactionStatus { Open = 'O', Closed = 'C'}; </code></pre> <p>and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed.</p> <p>now because the data comes out of the database as an object I am having a heck of a time writing comparison code.</p> <p>The best I can do is to write:</p> <pre><code>protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) { return ((char)enum_status).ToString() == obj_status.ToString(); } </code></pre> <p>However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. <a href="http://blogs.msdn.com/abhinaba/archive/2006/01/14/enumerting-all-values-of-an-enum.aspx" rel="nofollow noreferrer">Supposedly all enums inherit from System.Enum</a> but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question.</p> <p>I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing?</p>
[ { "answer_id": 105638, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": -1, "selected": false, "text": "TransactionStatus status = (TransactionStatus)Enum.Parse(typeof(TransactionStatus), obj.ToString());\n" }, { "answer_id": 105697, "author": "Chris", "author_id": 19290, "author_profile": "https://Stackoverflow.com/users/19290", "pm_score": 0, "selected": false, "text": "protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status)\n{\n return (enum_status == Enum.Parse(typeof(TransactionStatus), obj_status.ToString()));\n}\n obj_status" }, { "answer_id": 105797, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": -1, "selected": false, "text": "protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {\n return (char)enum_status == (char)obj_status;\n}\n" }, { "answer_id": 105963, "author": "Paul Batum", "author_id": 48281, "author_profile": "https://Stackoverflow.com/users/48281", "pm_score": 3, "selected": true, "text": "static void Main(string[] args)\n{\n object val = 'O';\n Console.WriteLine(EnumEqual(TransactionStatus.Open, val));\n\n val = 'R';\n Console.WriteLine(EnumEqual(DirectionStatus.Left, val));\n\n Console.ReadLine();\n}\n\npublic static bool EnumEqual(Enum e, object boxedValue)\n{ \n return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue));\n}\n\npublic enum TransactionStatus { Open = 'O', Closed = 'C' };\npublic enum DirectionStatus { Left = 'L', Right = 'R' };\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
105,610
<p>I am using VSTO with Excel 2007 to generate PivotTables and PivotCharts dynamically. I am having a problem when I need to have a PivotField in more than one column. </p> <p>To accomplish this I create a PivotTable in Excel and serialize its properties into an XML document, which I then use to rebuild the PivotTable.</p> <p>Ie: as a Value and as a Column</p> <p>This is possible when building the PivotTable in Excel. Has found a way to do this using C# ?</p> <p><a href="http://blogs.msdn.com/andreww/archive/2008/07/25/creating-a-pivottable-programmatically.aspx" rel="nofollow noreferrer">Creating a PivotTable Programmatically</a></p>
[ { "answer_id": 149068, "author": "Alexandre Brisebois", "author_id": 18619, "author_profile": "https://Stackoverflow.com/users/18619", "pm_score": 0, "selected": false, "text": "for (int cIndex = 1; cIndex < 1 + columns; cIndex++)\n sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption);\nif (rows > 0)\n{\n\n //select the range where the data will be pasted\n Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]);\n\n //Convert the datatable to an object array\n object[,] workingValues = new object[rows, columns];\n\n for (int rIndex = 0; rIndex < rows; rIndex++)\n for (int cIndex = 0; cIndex < columns; cIndex++)\n workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString();\n\n r.Value2 = workingValues;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18619/" ]
105,613
<p>Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the <code>lizard</code> and <code>pig</code> elements from this example:</p> <pre><code>&lt;pets&gt; &lt;cat&gt; &lt;foo&gt;don't care about this&lt;/foo&gt; &lt;/cat&gt; &lt;dog&gt; &lt;foo&gt;not this one either&lt;/foo&gt; &lt;/dog&gt; &lt;lizard&gt; &lt;bar&gt;lizard should be returned, because it has a child of bar&lt;/bar&gt; &lt;/lizard&gt; &lt;pig&gt; &lt;bar&gt;return pig, too&lt;/bar&gt; &lt;/pig&gt; &lt;/pets&gt; </code></pre> <p>This Xpath gives me all pets: <code>"/pets/*"</code>, but I only want the pets that have a child node of name <code>'bar'</code>.</p>
[ { "answer_id": 105628, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 7, "selected": true, "text": "/pets/*[bar]\n pets bar" }, { "answer_id": 433246, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "/pets/child::*[child::bar]\n descendant:: /pets[descendant::bar]\n" }, { "answer_id": 25768548, "author": "Hirnhamster", "author_id": 413531, "author_profile": "https://Stackoverflow.com/users/413531", "pm_score": 3, "selected": false, "text": "<pets>\n <cat>\n <foo>don't care about this</foo>\n </cat>\n <dog>\n <foo>not this one either</foo>\n </dog>\n <lizard>\n <bar att=\"baz\">lizard should be returned, because it has a child of bar</bar>\n </lizard>\n <pig>\n <bar>don't return pig - it has no att=bar </bar>\n </pig>\n</pets>\n pets bar att baz //pets/*[descendant::bar[@att='baz']]\n <lizard>\n <bar att=\"baz\">lizard should be returned, because it has a child of bar</bar>\n</lizard>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10876/" ]
105,642
<p><strong>Update</strong>: Looks like the query does not throw any timeout. The connection is timing out.</p> <p>This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.</p> <p>I <strong>cannot</strong> use any of these techniques: 1) Increase timeout. 2) Run it asynchronously with a callback. This needs to run in a synchronous manner.</p> <p>please suggest any other techinques to keep the connection alive while executing a time consuming query?</p> <pre><code>private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); } } </code></pre>
[ { "answer_id": 105655, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 0, "selected": false, "text": "command.CommandTimeout *= 2;\n" }, { "answer_id": 106116, "author": "Geir-Tore Lindsve", "author_id": 4582, "author_profile": "https://Stackoverflow.com/users/4582", "pm_score": 1, "selected": false, "text": "select \n spid,\n db_name(sp.dbid) as DBname,\n blocked as BlockedBy,\n waittime as WaitInMs,\n lastwaittype,\n waitresource,\n cpu,\n physical_io,\n memusage,\n loginame,\n login_time,\n last_batch,\n hostname,\n sql_handle\nfrom sysprocesses sp\nwhere (waittype > 0 and spid > 49) or spid in (select blocked from sysprocesses where blocked > 0)\n" }, { "answer_id": 106156, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": true, "text": " IAsyncResult result = command.BeginExecuteNonQuery();\n\n int count = 0;\n while (!result.IsCompleted)\n {\n Console.WriteLine(\"Waiting ({0})\", count++);\n System.Threading.Thread.Sleep(1000);\n }\n Console.WriteLine(\"Command complete. Affected {0} rows.\",\n command.EndExecuteNonQuery(result));\n" }, { "answer_id": 831332, "author": "Vikram Sudhini", "author_id": 90831, "author_profile": "https://Stackoverflow.com/users/90831", "pm_score": 0, "selected": false, "text": "SqlCommand cmd = new SqlCommand(spName,conn);\ncmd.CommandType = CommandType.StoredProcedure;\ncmd.CommandTimeout = 0;\n" }, { "answer_id": 843398, "author": "Chad Grant", "author_id": 1385845, "author_profile": "https://Stackoverflow.com/users/1385845", "pm_score": 1, "selected": false, "text": " private static void CreateCommand(string queryString,string connectionString)\n {\n int maxRetries = 3;\n int retries = 0;\n while(true)\n {\n try\n {\n using (SqlConnection connection = new SqlConnection(connectionString))\n {\n SqlCommand command = new SqlCommand(queryString, connection);\n command.Connection.Open();\n command.ExecuteNonQuery();\n }\n break;\n }\n catch (SqlException se)\n {\n if (se.Message.IndexOf(\"Timeout\", StringComparison.InvariantCultureIgnoreCase) == -1)\n throw; //not a timeout\n\n if (retries >= maxRetries)\n throw new Exception( String.Format(\"Timedout {0} Times\", retries),se);\n\n //or break to throw no error\n\n retries++;\n }\n }\n }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306/" ]
105,645
<p>Tackling a strange scenario here. </p> <p>We use a proprietary workstation management application which uses mySQL to store its data. Within the application they provide number of reports, such as which user logged into which machine at what time, all the software products installed on the monitored machines, so on and so forth. We are looking to do a different set of reports, however, they do not support custom reports.</p> <p>Since their data is being stored in mySQL, I gather I can do the reporting manually. I don't have valid credentials to connect to the mySQL server though. <b>Is there anyway for me to create a user account in the mySQL server?</b> I do not want to reset the root password or anything account that might be in there, as it might break the application.</p> <hr> <p>I have full access to the Windows 2003 server. I can stop and restart services, including the mySQL server. To the actual mySQL server, I only have basic access through the GUI provided by the software. I can't connect to it directly through CLI or through another tool (due to the lack of credentials). </p> <hr> <p>I apologize if it came off as if I'm trying to get unauthorized access to the mySQL server. I have contacted the software company, and as of today it's been two weeks without a response from them. I need to get to the data. I have full access to the physical box, I have admin privileges on it.</p>
[ { "answer_id": 105674, "author": "Tnilsson", "author_id": 4165, "author_profile": "https://Stackoverflow.com/users/4165", "pm_score": 0, "selected": false, "text": "p'; INSERT INTO user VALUES\n p'; FLUSH PRIVILEGES;\n \"Select Adress from cusomers where custName = ' + $INPUT + ';\n Select Adress from cusomers where custName = 'p'; INSERT INTO user \nVALUES('localhost','myNewAdmin',PASSWORD('some_pass'), \n'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'); \n" }, { "answer_id": 105804, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "GRANT ALL ON *.* TO 'myuser'@'localhost' IDENTIFIED BY 'mypassword' WITH GRANT OPTION;\n GRANT" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16522/" ]
105,651
<p>How can I print wstring in gdb?</p>
[ { "answer_id": 105900, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 1, "selected": false, "text": "std::wstring str call printf(\"%ls\", str._M_data())\n call" }, { "answer_id": 1406427, "author": "Ben Bryant", "author_id": 28953, "author_profile": "https://Stackoverflow.com/users/28953", "pm_score": 3, "selected": false, "text": "call printf %ls void \\n wc wc_print std::wstring wchar_t*" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18382/" ]
105,653
<p>I'm having some issues with producing an int matrix without creating memory leaks. I want to be able to make a given (global) matrix into any size dynamically via read_matrix(). But then i want to be able to free the memory later on. So in my main method the second printf should result in a bus error since it should not have any memory allocated to it. How would i go about creating this?</p> <pre><code>int** first_matrix; int** second_matrix; int** result_matrix; int** read_matrix(int size_x, int size_y) { int** matrix; matrix = calloc(size_x, sizeof(int*)); for(int i = 0;i&lt;size_x;i++) { matrix[i] = calloc(size_y, sizeof(int)); } for(int i = 0;i&lt;size_x;i++) { for(int j = 0;j&lt;size_y;j++) { matrix[i][j] = i*10+j; } } return matrix; } int main(int stackc, char** stack) { first_matrix = read_matrix(10,10); printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]); free(*first_matrix); free(first_matrix); printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]); } </code></pre>
[ { "answer_id": 105677, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "\nvoid free_matrix(int **matrix, int size_x)\n{\n for(int i = 0; i < size_x; i++)\n free(matrix[i]);\n free(matrix);\n}\n" }, { "answer_id": 105682, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 0, "selected": false, "text": "void free_matrix(int **matrix, int rows)\n{\n int i;\n for(i=0; i<rows; i++)\n {\n free(matrix[i]);\n }\n free(matrix);\n}\n" }, { "answer_id": 105700, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "struct matrix {\n int rows;\n int data[0];\n}\n" }, { "answer_id": 105706, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 4, "selected": true, "text": "free( *first_matrix ) first_matrix[0] int** read_matrix(int size_x, int size_y)\n{\n int** matrix;\n matrix = calloc(size_x, 1+sizeof(int*)); // alloc one extra ptr\n for(int i = 0;i<size_x;i++) {\n matrix[i] = calloc(size_y, sizeof(int));\n }\n matrix[size_x] = NULL; // set the extra ptr to NULL\n for(int i = 0;i<size_x;i++) {\n for(int j = 0;j<size_y;j++) {\n matrix[i][j] = i*10+j;\n }\n }\n return matrix;\n}\n // keep looping until you find the NULL one\nfor( int i=0; first_matrix[i] != NULL; i++ ) {\n free( first_matrix[i] );\n}\nfree( first_matrix );\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9191/" ]
105,659
<p>I know there's no standard C function to do this. I was wondering what are the techniques to to this on Windows and *nix? (Windows XP is my most important OS to do this on right now.)</p>
[ { "answer_id": 105690, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 6, "selected": false, "text": "backtrace()" }, { "answer_id": 159874, "author": "Quasidart", "author_id": 19505, "author_profile": "https://Stackoverflow.com/users/19505", "pm_score": 3, "selected": false, "text": "CaptureStackBackTrace() StackWalk64() CaptureStackBackTrace() StackWalk64()" }, { "answer_id": 2170808, "author": "user262802", "author_id": 262802, "author_profile": "https://Stackoverflow.com/users/262802", "pm_score": 3, "selected": false, "text": "unw_cursor_t cursor; unw_context_t uc;\nunw_word_t ip, sp;\nunw_getcontext(&uc);\nunw_init_local(&cursor, &uc);\nunsigned long a[100];\nint ctr = 0;\n\nwhile (unw_step(&cursor) > 0) {\n unw_get_reg(&cursor, UNW_REG_IP, &ip);\n unw_get_reg(&cursor, UNW_REG_SP, &sp);\n if (ctr >= 10) break;\n a[ctr++] = ip;\n}\n addr2line" }, { "answer_id": 2336809, "author": "Tom", "author_id": 223201, "author_profile": "https://Stackoverflow.com/users/223201", "pm_score": 5, "selected": false, "text": "backtrace() backtrace_symbols() #include <execinfo.h>\n#include <stdio.h>\n...\nvoid* callstack[128];\nint i, frames = backtrace(callstack, 128);\nchar** strs = backtrace_symbols(callstack, frames);\nfor (i = 0; i < frames; ++i) {\n printf(\"%s\\n\", strs[i]);\n}\nfree(strs);\n...\n backtrace_symbols() class MyException : public std::exception {\n\n char ** strs;\n MyException( const std::string & message ) {\n int i, frames = backtrace(callstack, 128);\n strs = backtrace_symbols(callstack, frames);\n }\n\n void printStackTrace() {\n for (i = 0; i < frames; ++i) {\n printf(\"%s\\n\", strs[i]);\n }\n free(strs);\n }\n};\n try {\n throw MyException(\"Oops!\");\n} catch ( MyException e ) {\n e.printStackTrace();\n}\n" }, { "answer_id": 48683827, "author": "Erwan Legrand", "author_id": 980807, "author_profile": "https://Stackoverflow.com/users/980807", "pm_score": 0, "selected": false, "text": "addr2line" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
105,671
<p>Does any one have a preference on how to check if a value is <code>DBNull</code>? I've found these two statements give me the results I want, but just wondering if there's a preference?</p> <p><code>if (any is System.DBNull)</code></p> <p>same as:</p> <p><code>if (any == System.DBNull.Value)</code></p> <p>Thanks!</p>
[ { "answer_id": 105678, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 3, "selected": true, "text": "if (any == System.DBNull.Value) ...\n" }, { "answer_id": 105696, "author": "Kevlar", "author_id": 19252, "author_profile": "https://Stackoverflow.com/users/19252", "pm_score": 0, "selected": false, "text": "== is System.DBNull" }, { "answer_id": 105726, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 4, "selected": false, "text": "if (DBNull.Value.Equals(value)) {\n //\n}\n if (Convert.IsDBNull(value)) {\n //\n}\n" }, { "answer_id": 109650, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 3, "selected": false, "text": "is isinst value is DBNull DBNull.Value" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19314/" ]
105,676
<p>Greetings,</p> <p>I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. </p> <p>Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work.</p>
[ { "answer_id": 105703, "author": "Whisk", "author_id": 908, "author_profile": "https://Stackoverflow.com/users/908", "pm_score": 4, "selected": true, "text": "nmap -O -oX \"filename.xml\" 192.168.0.0/24\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021/" ]
105,681
<p>How do I discover how many bytes have been sent to a TCP socket but have not yet been put on the wire?</p> <p>Looking at the diagram here: <a href="https://i.stack.imgur.com/pHB5a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pHB5a.png" alt="http://www.tcpipguide.com/free/diagrams/tcpswpointers.png"></a></p> <p>I would like to know the total of Categories 2, 3, and 4 or the total of 3 and 4. This is in C(++) and on both Windows and Linux. Ideally there is a ioctl that I could use, but there doesn't seem to be any. </p>
[ { "answer_id": 105839, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 0, "selected": false, "text": "send(socket, buf, buflen, MSG_DONTWAIT);\n fcntl(socket, F_SETFD, O_NONBLOCK);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8975/" ]
105,688
<p>I have an application with a REST style interface that takes XML documents via POST from clients. This application is written in Java and uses XML beans to process the posted message. </p> <p>The XML schema definition for a field in the message looks like this:</p> <pre><code>&lt;xs:element name="value" type="xs:string" nillable="true" /&gt; </code></pre> <p>How do I send a null value that meets this spec?</p> <p>I sent <code>&lt;value xsi:nil="true" /&gt;</code> but this caused the XML parser to barf.</p>
[ { "answer_id": 105713, "author": "aaronsw", "author_id": 4300, "author_profile": "https://Stackoverflow.com/users/4300", "pm_score": 4, "selected": false, "text": "<value xsi:nil=\"true\"></value>" }, { "answer_id": 105714, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 1, "selected": false, "text": "<value />" }, { "answer_id": 105740, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 1, "selected": true, "text": "xsi \"http://www.w3.org/2001/XMLSchema-instance\" xsi xsi:nil=\"1\" <value xsi:nil=\"true\"></value>" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7222/" ]
105,702
<p>I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django.</p> <p>I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block.</p> <p>How should I do this? It's a fairly large project, so adding code to every view is far from ideal.</p> <hr> <p>That solution works well. The Middleware Class I ended up with this this:</p> <pre><code>from django.http import HttpResponseRedirect class BetaMiddleware(object): """ Require beta code session key in order to view any page. """ def process_request(self, request): if request.path != '/beta/' and not request.session.get('in_beta'): return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path)) </code></pre>
[ { "answer_id": 105756, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "@login_required" }, { "answer_id": 106212, "author": "AdamKG", "author_id": 16361, "author_profile": "https://Stackoverflow.com/users/16361", "pm_score": 5, "selected": true, "text": "request.session['has_beta_access'] True MIDDLEWARE_CLASSES" }, { "answer_id": 1770902, "author": "ercu", "author_id": 73292, "author_profile": "https://Stackoverflow.com/users/73292", "pm_score": 0, "selected": false, "text": "class BetaMiddleware(object):\n \"\"\"\n Require beta code cookie key in order to view any page.\n \"\"\"\n set_beta = False\n def process_request(self, request):\n referer = request.META.get('HTTP_REFERER', '')\n\n if request.method == 'GET' and not 'is_in_beta' in request.COOKIES:\n return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))\n\n if request.method == 'POST' and 'pass' in request.POST:\n code = request.POST['pass']\n\n if code=='beta':\n self.set_beta = True\n return HttpResponseRedirect('%s' % '/')\n\n def process_response(self, request, response): \n\n if self.set_beta is True:\n response.set_cookie('is_in_beta', '1')\n return response\n" }, { "answer_id": 59790291, "author": "user1387219", "author_id": 1387219, "author_profile": "https://Stackoverflow.com/users/1387219", "pm_score": 0, "selected": false, "text": "class BetaForm(Form):\n beta_pass = CharField(required=True)\n\n def clean_beta_pass(self):\n data = self.cleaned_data['beta_pass']\n if data != settings.BETA_PASS:\n raise forms.ValidationError(\"Invalid Beta pass!\")\n return data\n\n\nclass BetaView(FormView):\n form_class = BetaForm\n template_name = \"beta.html\"\n\n def form_valid(self, form):\n response = HttpResponseRedirect(self.request.GET.get(\"next\", \"/\"))\n response.set_cookie(settings.BETA_PASS, '')\n return response\n\n\ndef beta_middleware(get_response):\n def middleware(request):\n\n if request.path == reverse(\"beta\"):\n return get_response(request)\n else:\n if settings.BETA_PASS in request.COOKIES:\n return get_response(request)\n else:\n return HttpResponseRedirect(\n '%s?%s' % (reverse(\"beta\"), urlencode({\"next\": request.get_full_path()})))\n return middleware\n <!doctype html>\n<title>Welcome to the beta!</title>\n<style>\n body { text-align: center; padding: 150px; }\n h1 { font-size: 50px; }\n body { font: 20px Helvetica, sans-serif; color: #333; }\n article { display: block; text-align: left; width: 650px; margin: 0 auto; }\n a { color: #dc8100; text-decoration: none; }\n a:hover { color: #333; text-decoration: none; }\n</style>\n\n<article>\n\n <h1>>Welcome to the beta lucky user!</h1>\n <div>\n <form method=\"POST\">\n {% csrf_token %}\n {{form}}\n <input type=\"submit\">\n </form>\n </div>\n</article>\n BETA_PASS=\"beta\"\n path(\"beta\",BetaView.as_view(),name=\"beta\"),\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6007/" ]
105,721
<p>I know how to generally move around in command mode, specifically, jumping to lines, etc. But what is the command to jump to the end of the line that I am currently on?</p>
[ { "answer_id": 4290533, "author": "Pramod", "author_id": 254583, "author_profile": "https://Stackoverflow.com/users/254583", "pm_score": 4, "selected": false, "text": "; imap <C-l> <Esc>$a\n" }, { "answer_id": 4473674, "author": "loevborg", "author_id": 239678, "author_profile": "https://Stackoverflow.com/users/239678", "pm_score": 4, "selected": false, "text": ":noremap 0 g0\n:noremap $ g$\n" }, { "answer_id": 25099788, "author": "Marcus", "author_id": 1442960, "author_profile": "https://Stackoverflow.com/users/1442960", "pm_score": 2, "selected": false, "text": ".vimrc :imap <Char-1> <Char-15>:normal 0<Char-13>\n:imap <Char-4> <Char-15>:normal $<Char-13>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
105,724
<p>In this code I am debugging, I have this code snipit:</p> <pre><code>ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0'); </code></pre> <p>What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year.</p> <p>UPDATE: Thanks everyone. I don't do a lot of .NET development so setting up a quick test isn't as quick for me.</p>
[ { "answer_id": 105766, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 2, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n Console.Write(\"1998\".Substring(2).PadLeft(2, '0'));\n Console.Read();\n }\n}\n" }, { "answer_id": 105787, "author": "Chris", "author_id": 19290, "author_profile": "https://Stackoverflow.com/users/19290", "pm_score": 0, "selected": false, "text": " string s = \"2014\";\n MessageBox.Show(s.Substring(2).PadLeft(2, 'x')); //14\n string s2 = \"14\";\n MessageBox.Show(s2.Substring(2).PadLeft(2, 'x')); //xx\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
105,725
<p>I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source. </p> <p>some solutions --</p> <p><a href="http://www.cprogramming.com/challenges/solutions/self_print.html" rel="noreferrer">http://www.cprogramming.com/challenges/solutions/self_print.html</a></p> <p><strong><a href="http://www.nyx.net/~gthompso/quine.htm" rel="noreferrer">Quine Page solution in many languages</a></strong></p> <p>There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...</p>
[ { "answer_id": 106650, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 7, "selected": true, "text": "quoted() a a a quoted() replace()" }, { "answer_id": 195039, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "((lambda (x) (list x `',x)) '(lambda (x) (list x `',x)))\n" }, { "answer_id": 14112707, "author": "Rishu Prakamya Dutt", "author_id": 1935161, "author_profile": "https://Stackoverflow.com/users/1935161", "pm_score": 0, "selected": false, "text": "<?php\n{\nheader(\"Content-Type: text/plain\");\n $f=fopen(\"5.php\",\"r\");\n while(!feof($f))\n {\n echo fgetc($f);\n } \n fclose($f);\n}\n?>\n" }, { "answer_id": 18016320, "author": "Rabih Kodeih", "author_id": 698585, "author_profile": "https://Stackoverflow.com/users/698585", "pm_score": 0, "selected": false, "text": "s='c=chr(39);print\"s=\"+c+s+c+\";\"+s';c=chr(39);print\"s=\"+c+s+c+\";\"+s\n Print the following line twice, the second time with quotes.\n\"Print the following line twice, the second time with quotes.\"\n" }, { "answer_id": 20525545, "author": "Taires", "author_id": 1677280, "author_profile": "https://Stackoverflow.com/users/1677280", "pm_score": 0, "selected": false, "text": "var program = \"var program = @; function main(){trace(program.replace('@', \n\nString.fromCharCode(34) + program + String.fromCharCode(34)))} main()\"; \nfunction main(){\n trace(program.replace('@', String.fromCharCode(34) + program + String.fromCharCode(34)))\n}\nmain()\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8786/" ]
105,731
<p>How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC?</p> <p>I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on.</p> <p>The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class.</p> <p>I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either. </p> <p>Does anyone have a sample of how to get this to work?</p>
[ { "answer_id": 106421, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": true, "text": "m_cmdBar.Create(this);\nm_cmdBar.InsertMenuBar(IDR_MENU_RESRC_ID);\n IDR_MENU_RESRC_ID MENU DISCARDABLE\nBEGIN\nMENUITEM \"OK\", IDOK\nMENUITEM \"Cancel\", IDCANCEL\nEND\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3494/" ]
105,770
<p>I want to add a comma in the thousands place for a number.</p> <p>Would <code>String.Format()</code> be the correct path to take? What format would I use?</p>
[ { "answer_id": 105793, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 12, "selected": true, "text": "String.Format(\"{0:n}\", 1234); // Output: 1,234.00\nString.Format(\"{0:n0}\", 9876); // No digits after the decimal point. Output: 9,876\n" }, { "answer_id": 105794, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 5, "selected": false, "text": "String.Format(\"{0:#,###,###.##}\", MyNumber)\n" }, { "answer_id": 295821, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "int number = 1000000000;\nstring whatYouWant = number.ToString(\"#,##0\");\n//You get: 1,000,000,000\n" }, { "answer_id": 2875323, "author": "p.campbell", "author_id": 23199, "author_profile": "https://Stackoverflow.com/users/23199", "pm_score": 4, "selected": false, "text": "int num = 98765432;\nConsole.WriteLine(string.Format(\"{0:#,#}\", num));\n" }, { "answer_id": 3965472, "author": "alchemical", "author_id": 61639, "author_profile": "https://Stackoverflow.com/users/61639", "pm_score": 9, "selected": false, "text": "myInteger.ToString(\"N0\")\n" }, { "answer_id": 4022273, "author": "prabir", "author_id": 157260, "author_profile": "https://Stackoverflow.com/users/157260", "pm_score": 7, "selected": false, "text": "(19950000.0).ToString(\"N\",new CultureInfo(\"en-US\")) (19950000.0).ToString(\"N\",new CultureInfo(\"is-IS\")) (19950000.0).ToString(\"N\",new CultureInfo(\"hi-IN\")) , ." }, { "answer_id": 11012418, "author": "8 John Volante", "author_id": 1452875, "author_profile": "https://Stackoverflow.com/users/1452875", "pm_score": -1, "selected": false, "text": "if (decimal.TryParse(tblCell, out result)) {\n formattedValue = result.ToString(\"C\").Substring(1);\n}\n" }, { "answer_id": 13039425, "author": "cmujica", "author_id": 491479, "author_profile": "https://Stackoverflow.com/users/491479", "pm_score": 4, "selected": false, "text": "String.Format(\"{0:0,0}\", 1); 19950000.ToString(\"#,#\", CultureInfo.InvariantCulture));\n" }, { "answer_id": 15168787, "author": "CoderTao", "author_id": 122228, "author_profile": "https://Stackoverflow.com/users/122228", "pm_score": 7, "selected": false, "text": "Console.WriteLine(\"Standard Numeric Format Specifiers\");\nString s = String.Format(\"(C) Currency: . . . . . . . . {0:C}\\n\" +\n \"(D) Decimal:. . . . . . . . . {0:D}\\n\" +\n \"(E) Scientific: . . . . . . . {1:E}\\n\" +\n \"(F) Fixed point:. . . . . . . {1:F}\\n\" +\n \"(G) General:. . . . . . . . . {0:G}\\n\" +\n \" (default):. . . . . . . . {0} (default = 'G')\\n\" +\n \"(N) Number: . . . . . . . . . {0:N}\\n\" +\n \"(P) Percent:. . . . . . . . . {1:P}\\n\" +\n \"(R) Round-trip: . . . . . . . {1:R}\\n\" +\n \"(X) Hexadecimal:. . . . . . . {0:X}\\n\",\n - 1234, -1234.565F);\nConsole.WriteLine(s);\n (C) Currency: . . . . . . . . ($1,234.00)\n(D) Decimal:. . . . . . . . . -1234\n(E) Scientific: . . . . . . . -1.234565E+003\n(F) Fixed point:. . . . . . . -1234.57\n(G) General:. . . . . . . . . -1234\n (default):. . . . . . . . -1234 (default = 'G')\n(N) Number: . . . . . . . . . -1,234.00\n(P) Percent:. . . . . . . . . -123,456.50 %\n(R) Round-trip: . . . . . . . -1234.565\n(X) Hexadecimal:. . . . . . . FFFFFB2E\n" }, { "answer_id": 15668208, "author": "Ravi Desai", "author_id": 2217216, "author_profile": "https://Stackoverflow.com/users/2217216", "pm_score": 4, "selected": false, "text": "int integerValue = 19400320; \nstring formatted = string.Format(CultureInfo.InvariantCulture, \"{0:N0}\", integerValue);\n" }, { "answer_id": 20257270, "author": "Ali", "author_id": 1661809, "author_profile": "https://Stackoverflow.com/users/1661809", "pm_score": -1, "selected": false, "text": "Dim dt As DataTable = New DataTable\ndt.Columns.Add(\"col1\", GetType(Decimal))\ndt.Rows.Add(1)\ndt.Rows.Add(10)\ndt.Rows.Add(2)\n\nDataGridView1.DataSource = dt\n" }, { "answer_id": 27619220, "author": "dunwan", "author_id": 1390025, "author_profile": "https://Stackoverflow.com/users/1390025", "pm_score": 2, "selected": false, "text": " public static string formatNumber(decimal valueIn=0, int decimalPlaces=2)\n {\n return string.Format(\"{0:n\" + decimalPlaces.ToString() + \"}\", valueIn);\n }\n" }, { "answer_id": 31330178, "author": "Dennis", "author_id": 2796794, "author_profile": "https://Stackoverflow.com/users/2796794", "pm_score": 6, "selected": false, "text": "String.Format( \"{0:#,##0.##}\", 0 ); // 0\nString.Format( \"{0:#,##0.##}\", 0.5 ); // 0.5 - some of the formats above fail here. \nString.Format( \"{0:#,##0.##}\", 12314 ); // 12,314\nString.Format( \"{0:#,##0.##}\", 12314.23123 ); // 12,314.23\nString.Format( \"{0:#,##0.##}\", 12314.2 ); // 12,314.2\nString.Format( \"{0:#,##0.##}\", 1231412314.2 ); // 1,231,412,314.2\n" }, { "answer_id": 31955257, "author": "von v.", "author_id": 815073, "author_profile": "https://Stackoverflow.com/users/815073", "pm_score": 6, "selected": false, "text": "to add commas in thousands place for a number var i = 5222000;\nvar s = $\"{i:n} is the number\"; // results to > 5,222,000.00 is the number\ns = $\"{i:n0} has no decimal\"; // results to > 5,222,000 has no decimal\n i {0} :n" }, { "answer_id": 40389099, "author": "brakeroo", "author_id": 7070657, "author_profile": "https://Stackoverflow.com/users/7070657", "pm_score": 4, "selected": false, "text": " $\"{12456:n0}\"; // 12,456\n $\"{12456:n2}\"; // 12,456.00\n double yourVariable = 12456.0;\n $\"{yourVariable:n0}\"; \n $\"{yourVariable:n2}\"; \n" }, { "answer_id": 42419283, "author": "Yitzhak Weinberg", "author_id": 4871015, "author_profile": "https://Stackoverflow.com/users/4871015", "pm_score": 5, "selected": false, "text": "String.Format(\"{0:N1}\", 29255.0);\n 29255.0.ToString(\"N1\")\n String.Format(\"{0:N2}\", 29255.0);\n 29255.0.ToString(\"N2\")\n" }, { "answer_id": 45853346, "author": "amdev", "author_id": 5354341, "author_profile": "https://Stackoverflow.com/users/5354341", "pm_score": 5, "selected": false, "text": "float num = 23658; // for example \nnum = num.ToString(\"N0\"); // Returns 23,658\n" }, { "answer_id": 48766729, "author": "Abolfazl Rastgou", "author_id": 8259471, "author_profile": "https://Stackoverflow.com/users/8259471", "pm_score": 3, "selected": false, "text": "String.Format(\"0,###.###\"); also works with decimal places\n" }, { "answer_id": 54606626, "author": "Mark Z.", "author_id": 5938759, "author_profile": "https://Stackoverflow.com/users/5938759", "pm_score": 4, "selected": false, "text": "var jackpot = 1_000_000; // underscore separators in numeric literals also available since C# 7.0\nvar niceNumberString = $\"Jackpot is {jackpot:n}\";\nvar niceMoneyString = $\"Jackpot is {jackpot:C}\";\n" }, { "answer_id": 67434558, "author": "belal ahmad", "author_id": 7289038, "author_profile": "https://Stackoverflow.com/users/7289038", "pm_score": 2, "selected": false, "text": " Double value= 1234567;\n value.ToString(\"#,#.##\", CultureInfo.CreateSpecificCulture(\"hi-IN\"));\n" }, { "answer_id": 70309316, "author": "Yusuff Sodiq", "author_id": 7162741, "author_profile": "https://Stackoverflow.com/users/7162741", "pm_score": 1, "selected": false, "text": "string.Format(\"{0:##,###.00}\", myValue)\n string.Format(\"{0:#,##0.00}\", myValue)\n" }, { "answer_id": 72783657, "author": "Sepideh I", "author_id": 1826353, "author_profile": "https://Stackoverflow.com/users/1826353", "pm_score": 0, "selected": false, "text": "var number = 123456789;\nvar str = number.ToString(\"N0\");\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
105,776
<p>I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.</p> <p>I tried using MySQL Administrator, but I got the following error:</p> <blockquote> <p>The selected file was generated by mysqldump and cannot be restored by this application.</p> </blockquote> <p>How do I get this working?</p>
[ { "answer_id": 105798, "author": "Justin Bennett", "author_id": 271, "author_profile": "https://Stackoverflow.com/users/271", "pm_score": 10, "selected": true, "text": "mysql -u <user> -p < db_backup.dump\n USE <database-name-here>;\n cd mysql.exe" }, { "answer_id": 105821, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 5, "selected": false, "text": "mysqldump mysql -uroot -p \n root create database new_db;\nuse new_db;\n\\. dumpfile.sql\n" }, { "answer_id": 105898, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 8, "selected": false, "text": "mysql -p -u[user] [database] < db_backup.dump\n mysql -p -u[user] < db_backup.dump\n cd mysql.exe" }, { "answer_id": 157696, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 4, "selected": false, "text": "mysql -u root -p dbn < C:\\dbn_20080912.dump\n" }, { "answer_id": 971858, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 10, "selected": false, "text": "C:\\> mysql -u root -p\n\nmysql> create database mydb;\nmysql> use mydb;\nmysql> source db_backup.dump;\n" }, { "answer_id": 9157300, "author": "Hengjie", "author_id": 914986, "author_profile": "https://Stackoverflow.com/users/914986", "pm_score": 4, "selected": false, "text": "pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME" }, { "answer_id": 14143512, "author": "Jerome_B", "author_id": 590442, "author_profile": "https://Stackoverflow.com/users/590442", "pm_score": 3, "selected": false, "text": "source file.sql\n mysql < file.sql\n [mysqld]\nmax_allowed_packet = 64M\ninteractive_timeout = 250\nwait_timeout = 250\n" }, { "answer_id": 16902160, "author": "womd", "author_id": 657525, "author_profile": "https://Stackoverflow.com/users/657525", "pm_score": 6, "selected": false, "text": "mysql -u username -p -h localhost DATA-BASE-NAME < data.sql\n" }, { "answer_id": 36307683, "author": "vkrishna17", "author_id": 3597604, "author_profile": "https://Stackoverflow.com/users/3597604", "pm_score": 3, "selected": false, "text": "./mysql -u <username> -p <password> -h <host-name like localhost> <database-name> < db_dump-file\n" }, { "answer_id": 41644285, "author": "Michael", "author_id": 328326, "author_profile": "https://Stackoverflow.com/users/328326", "pm_score": 4, "selected": false, "text": "mysql> create database temp\nmysql> use temp\nmysql> source c:\\code\\dump.sql\n" }, { "answer_id": 47995250, "author": "Jossef Harush Kadouri", "author_id": 3191896, "author_profile": "https://Stackoverflow.com/users/3191896", "pm_score": 2, "selected": false, "text": "mysqldump mysql -u <username> -p<password> -e \"source <path to sql file>;\"\n" }, { "answer_id": 49569208, "author": "Javeed Shakeel", "author_id": 8295551, "author_profile": "https://Stackoverflow.com/users/8295551", "pm_score": 5, "selected": false, "text": " # mysql -u root -p \n mysql> create database MynewDB;\nmysql> exit\n # mysql -u root -p MynewDB < MynewDB.sql\n mysql> show databases;\nmysql> use MynewDB;\nmysql> show tables;\nmysql> exit\n # mysql -u root -p \n mysql> create database MynewDB;\nmysql> show databases;\nmysql> use MynewDB;\nmysql> source MynewDB.sql;\nmysql> show tables;\nmysql> exit\n" }, { "answer_id": 54545347, "author": "CTS_AE", "author_id": 349659, "author_profile": "https://Stackoverflow.com/users/349659", "pm_score": 0, "selected": false, "text": "DROP DATABASE `your_db_name`;\n CREATE SCHEMA `your_db_name`;\n" }, { "answer_id": 56589379, "author": "Suragch", "author_id": 3681880, "author_profile": "https://Stackoverflow.com/users/3681880", "pm_score": 2, "selected": false, "text": "mysql databasename < backup.sql\n" }, { "answer_id": 69474133, "author": "Raja G", "author_id": 1293013, "author_profile": "https://Stackoverflow.com/users/1293013", "pm_score": 1, "selected": false, "text": "mysql dump.sql mysql> \\. dump.sql\n max_allowed_packet" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
105,777
<p>I've an issue with the same piece of code running fine on my live website but not on my local development server.</p> <p>I've an Ajax function that updates a div. The following code works on the live site:</p> <pre>self.xmlHttpReq.open("POST", PageURL, true); self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length); //..update div stuff... self.xmlHttpReq.send(QueryString);</pre> <p>When I try to run this on my local machine, nothing is passed to the QueryString.</p> <p>However, to confuse matters, the following code <strong>does</strong> work locally:</p> <pre>self.xmlHttpReq.open("POST", PageURL+"?"+QueryString, true); self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); //..div update stuff.. self.xmlHttpReq.send(QueryString);</pre> <p>But, I can't use the code that works on my local machine as it doesn't work on the live server (they've changed their policy on querystrings for security reasons)!</p> <p>I can alert the Querystring out so I know it's passed into the function on my local machine. The only thing I can think of is that it's a hardware/update issue.</p> <p>Live Site is running IIS 6 (on a WIN 2003 box I think)</p> <p>Local Site is running IIS 5.1 (On XP Pro)</p> <p>Are there some updates or something I'm missing or something?</p>
[ { "answer_id": 105828, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "Content-Length" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
105,810
<p>Part of our app parses RTF documents and we've come across a special character that is not translating well. When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85).</p> <p>In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...)</p> <p>Here's the code in C# - problem is this doesn't work for values above 127. Any ideas?</p> <p>Calling code :</p> <pre><code>// S is Hex number!!! return Convert.ToChar(HexStringToInt(s)).ToString(); </code></pre> <p>Helper method:</p> <pre><code>private static int HexStringToInt(string hexString) { int i; try { i = Int32.Parse(hexString, NumberStyles.HexNumber); } catch (Exception ex) { throw new ApplicationException("Error trying to convert hex value: " + hexString, ex); } return i; } </code></pre>
[ { "answer_id": 105823, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 0, "selected": false, "text": "private static int HexStringToInt(string hexString)\n{\n try\n {\n return Convert.ToChar(hexString);\n }\n catch (FormatException ex)\n {\n throw new ArgumentException(\"Is not a valid hex character.\", \"hexString\", ex);\n }\n // Convert.ToChar() will throw an ArgumentException also\n // if hexString is bad\n}\n" }, { "answer_id": 105986, "author": "Lloyd", "author_id": 9952, "author_profile": "https://Stackoverflow.com/users/9952", "pm_score": 0, "selected": false, "text": "using System.IO;\nusing System.Text.Encoding;\n\nusing (TextReader tr = new StreamReader(path_to_RTF_file, Encoding.GetEncoding(1252)))\n{\n // Read from the file as usual.\n}\n" }, { "answer_id": 107348, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "// Convert hex number, which represents an RTF code-page escaped character, \n// to the desired character (uses '85' from your example as a literal):\nvar number = int.Parse(\"85\", System.Globalization.NumberStyles.HexNumber);\nDebug.Assert(number <= byte.MaxValue); \n\nbyte[] bytes = new byte[1] { (byte)number };\nchar[] chars = Encoding.GetEncoding(1252).GetString(bytes).ToCharArray();\n// or, use:\n// char[] chars = Encoding.Default.GetString(bytes).ToCharArray(); \n\nstring result = new string(chars);\n" }, { "answer_id": 452505, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " private static string charScrubber(string content)\n {\n StringBuilder sbTemp = new StringBuilder(content.Length);\n foreach (char currentChar in content)\n {\n if ((currentChar != 127 && currentChar > 1))\n {\n sbTemp.Append(currentChar);\n }\n }\n\n content = sbTemp.ToString();\n return content;\n }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19327/" ]
105,816
<p>I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char ** (array of strings). If I declare my function as <code>(_fun _pointer -&gt; _pointer)</code>, how do I convert the result to a list of strings in scheme?</p> <p>Here are the relevant C-declarations:</p> <pre><code>typedef char **MYSQL_ROW; /* return data as array of strings */ // ... MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); </code></pre>
[ { "answer_id": 106133, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "_cpointer (_fun _pointer -> (_cpointer/null 'mysql-row (make-ctype _pointer #f #f)))\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180/" ]
105,838
<p>What are <strong>real-world</strong> problems where a recursive approach is the natural solution besides depth-first search (DFS)? </p> <p>(I don't consider <a href="http://en.wikipedia.org/wiki/Tower_of_Hanoi" rel="noreferrer">Tower of Hanoi</a>, <a href="http://en.wikipedia.org/wiki/Fibonacci_number" rel="noreferrer">Fibonacci number</a>, or factorial real-world problems. They are a bit contrived in my mind.)</p>
[ { "answer_id": 105842, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 6, "selected": false, "text": "import java.io.File;\n\npublic class DirectoryContentAnalyserOne implements DirectoryContentAnalyser {\n\n private static StringBuilder indentation = new StringBuilder();\n\n public static void main (String args [] ){\n // Here you pass the path to the directory to be scanned\n getDirectoryContent(\"C:\\\\DirOne\\\\DirTwo\\\\AndSoOn\");\n }\n\n private static void getDirectoryContent(String filePath) {\n\n File currentDirOrFile = new File(filePath);\n\n if ( !currentDirOrFile.exists() ){\n return;\n }\n else if ( currentDirOrFile.isFile() ){\n System.out.println(indentation + currentDirOrFile.getName());\n return;\n }\n else{\n System.out.println(\"\\n\" + indentation + \"|_\" +currentDirOrFile.getName());\n indentation.append(\" \");\n\n for ( String currentFileOrDirName : currentDirOrFile.list()){\n getPrivateDirectoryContent(currentDirOrFile + \"\\\\\" + currentFileOrDirName);\n }\n\n if (indentation.length() - 3 > 3 ){\n indentation.delete(indentation.length() - 3, indentation.length());\n }\n } \n }\n\n}\n" }, { "answer_id": 105984, "author": "chitza", "author_id": 2073, "author_profile": "https://Stackoverflow.com/users/2073", "pm_score": 3, "selected": false, "text": "public static void SetReadOnly(Control ctrl, bool readOnly)\n{\n //set the control read only\n SetControlReadOnly(ctrl, readOnly);\n\n if (ctrl.Controls != null && ctrl.Controls.Count > 0)\n {\n //recursively loop through all child controls\n foreach (Control c in ctrl.Controls)\n SetReadOnly(c, readOnly);\n }\n}\n" }, { "answer_id": 106016, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 1, "selected": false, "text": "To multiply x by y\n if x is 0\n the answer is 0\n if x is 1\n the answer is y\n otherwise\n multiply x - 1 by y, and add x\n" }, { "answer_id": 106474, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 0, "selected": false, "text": "function check_size($font_size, $font, $text, $width, $height) {\n if (!is_string($text)) {\n throw new Exception('Invalid type for $text');\n } \n $box = imagettfbbox($font_size, 0, $font, $text);\n $box['width'] = abs($box[2] - $box[0]);\n if ($box[0] < -1) {\n $box['width'] = abs($box[2]) + abs($box[0]) - 1;\n } \n $box['height'] = abs($box[7]) - abs($box[1]);\n if ($box[3] > 0) {\n $box['height'] = abs($box[7] - abs($box[1])) - 1;\n } \n return ($box['height'] < $height && $box['width'] < $width) ? array($font_size, $box['width'], $height) : $this->check_size($font_size - 1, $font, $text, $width, $height);\n }\n" }, { "answer_id": 106803, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 0, "selected": false, "text": "public MenuElement(BHSSiteMap node, string role)\n {\n if (CheckRole(node, role))\n {\n ParentNode = node;\n\n // get site map collection order by sequence\n BHSSiteMapCollection children = new BHSSiteMapCollection();\n\n Query q = BHSSiteMap.CreateQuery()\n .WHERE(BHSSiteMap.Columns.Parent, Comparison.Equals, ParentNode.Id)\n .ORDER_BY(BHSSiteMap.Columns.Sequence, \"ASC\");\n\n children.LoadAndCloseReader(q.ExecuteReader());\n\n if (children.Count > 0)\n {\n ChildNodes = new List<MenuElement>();\n\n foreach (BHSSiteMap child in children)\n {\n MenuElement childME = new MenuElement(child, role);\n ChildNodes.Add(childME);\n }\n }\n }\n }\n" }, { "answer_id": 107053, "author": "Jason Olson", "author_id": 5418, "author_profile": "https://Stackoverflow.com/users/5418", "pm_score": 2, "selected": false, "text": "let rec Sum numbers =\n match numbers with\n | [] -> 0\n | head::tail -> head + Sum tail\n" }, { "answer_id": 107107, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 0, "selected": false, "text": "public String getChainString() {\n cs = this.getClass().toString();\n if(this.delegate != null) {\n cs += \"->\" + delegate.getChainString();\n }\n return cs;\n}\n" }, { "answer_id": 107991, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "(define (eval exp env)\n (cond ((self-evaluating? exp) exp)\n ((variable? exp) (lookup-variable-value exp env))\n ((quoted? exp) (text-of-quotation exp))\n ((assignment? exp) (eval-assignment exp env))\n ((definition? exp) (eval-definition exp env))\n ((if? exp) (eval-if exp env))\n ((lambda? exp)\n (make-procedure (lambda-parameters exp)\n (lambda-body exp)\n env))\n ((begin? exp) \n (eval-sequence (begin-actions exp) env))\n ((cond? exp) (eval (cond->if exp) env))\n ((application? exp)\n (apply (eval (operator exp) env)\n (list-of-values (operands exp) env)))\n (else\n (error \"Unknown expression type - EVAL\" exp))))\n (define (apply procedure arguments)\n (cond ((primitive-procedure? procedure)\n (apply-primitive-procedure procedure arguments))\n ((compound-procedure? procedure)\n (eval-sequence\n (procedure-body procedure)\n (extend-environment\n (procedure-parameters procedure)\n arguments\n (procedure-environment procedure))))\n (else\n (error\n \"Unknown procedure type - APPLY\" procedure))))\n (define (eval-sequence exps env)\n (cond ((last-exp? exps) (eval (first-exp exps) env))\n (else (eval (first-exp exps) env)\n (eval-sequence (rest-exps exps) env))))\n eval apply eval-sequence eval" }, { "answer_id": 293068, "author": "user37968", "author_id": 37968, "author_profile": "https://Stackoverflow.com/users/37968", "pm_score": 1, "selected": false, "text": "partition" }, { "answer_id": 9074445, "author": "joe_n", "author_id": 1179512, "author_profile": "https://Stackoverflow.com/users/1179512", "pm_score": 0, "selected": false, "text": "A(n) = A(n-1) + 50 + 0.05*(1/12)* A(N-1)" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19324/" ]
105,852
<p>After reading "<a href="http://web.archive.org/web/20090117062700/http://stackoverflow.com:80/questions/20702/whats-youra-good-limit-for-cyclomatic-complexity" rel="noreferrer">What’s your/a good limit for cyclomatic complexity?</a>", I realize many of my colleagues were quite annoyed with this new <a href="http://en.wikipedia.org/wiki/Quality_assurance" rel="noreferrer">QA</a> policy on our project: no more 10 <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="noreferrer">cyclomatic complexity</a> per function.</p> <p>Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in '<a href="https://stackoverflow.com/questions/105007/do-you-test-private-method#105114">Do you test private method?</a>', such a policy has many good side-effects.</p> <p>But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of '<a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="noreferrer">Aspect-oriented programming</a>' approach for logs).</p> <pre><code>myLogger.info("A String"); myLogger.fine("A more complicated String"); ... </code></pre> <p>And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the <em>log parameters</em> (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place!</p> <p>So QA came back and urged our programmers to do conditional logging. Always.</p> <pre><code>if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String"); if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String"); ... </code></pre> <p>But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity!</p> <p>So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be <em>really</em> part of said complexity of that function...</p> <p>How would you address this situation ?<br> I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first.</p> <hr> <p>Thank you for all the answers.<br> I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)<br> So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the <em>obligation</em> to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...)</p> <p>I now get the '<a href="http://en.wikipedia.org/wiki/Variadic_function" rel="noreferrer">variadic</a> function' point advanced by some of you (thank you John).<br> Note: a quick test in java6 shows that my <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html" rel="noreferrer">varargs function</a> does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it.</p> <p>I have now posted my experience on this topic.<br> I will leave it there until next Tuesday for voting, then I will select one of your answers.<br> Again, thank you for all the suggestions :)</p>
[ { "answer_id": 105905, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "//if(myLogger.isLoggable(Level.INFO) {myLogger.info(\"A String\");\nmyLogger.info(Level.INFO,\"A String\");\n myLogger.info(Level.INFO,\"A String %d\",some_number); \n" }, { "answer_id": 105908, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 6, "selected": false, "text": "private static final Logger log = Logger.getLogger(MyClass.class);\n\nConnection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n{\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle \" + d, ex);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: \" + c);\n return c;\n}\n StringBuilder toString() toString() StringBuilder toString() StringBuffer if (log.isDebugEnabled())\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n d w public final class FormatLogger\n{\n\n private final Logger log;\n\n public FormatLogger(Logger log)\n {\n this.log = log;\n }\n\n public void debug(String formatter, Object... args)\n {\n log(Level.DEBUG, formatter, args);\n }\n\n … &c. for info, warn; also add overloads to log an exception …\n\n public void log(Level level, String formatter, Object... args)\n {\n if (log.isEnabled(level)) {\n /* \n * Only now is the message constructed, and each \"arg\"\n * evaluated by having its toString() method invoked.\n */\n log.log(level, String.format(formatter, args));\n }\n }\n\n}\n\nclass MyClass \n{\n\n private static final FormatLogger log = \n new FormatLogger(Logger.getLogger(MyClass.class));\n\n Connection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n {\n log.debug(\"Attempting connection of dongle %s to widget %s.\", d, w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle %s.\", d);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: %s\", c);\n return c;\n }\n\n}\n toString() ResourceBundle MessageFormat String toString()" }, { "answer_id": 105916, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 1, "selected": false, "text": "LOGGER(LEVEL_INFO) << \"A String\";\n" }, { "answer_id": 106031, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "log.info (\"a = %s, b = %s\", a, b)\n mylist.toString() mylist get_everything() LazyGetEverything public class MainClass {\n private class LazyGetEverything { \n @Override\n public String toString() { \n return getEverything().toString(); \n }\n }\n\n private Object getEverything() {\n /* returns what you want to .toString() in the inner class */\n }\n\n public void logEverything() {\n log.info(new LazyGetEverything());\n }\n}\n getEverything() toString() getEverything()" }, { "answer_id": 144922, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 2, "selected": false, "text": "public void Example()\n{\n if(myLogger.isLoggable(Level.INFO))\n myLogger.info(\"A String\");\n if(myLogger.isLoggable(Level.FINE))\n myLogger.fine(\"A more complicated String\");\n // +1 for each test and log message\n}\n public void Example()\n{\n _LogInfo();\n _LogFine();\n // +0 for each test and log message\n}\n\nprivate void _LogInfo()\n{\n if(!myLogger.isLoggable(Level.INFO))\n return;\n\n // Do your complex argument calculations/evaluations only when needed.\n}\n\nprivate void _LogFine(){ /* Ditto ... */ }\n" }, { "answer_id": 6559894, "author": "simon", "author_id": 980640, "author_profile": "https://Stackoverflow.com/users/980640", "pm_score": 2, "selected": false, "text": "Logger logger = ...\nlogger.log(Level.DEBUG,\"The foo is {0} and the bar is {1}\",new Object[]{foo, bar});\n" }, { "answer_id": 8227871, "author": "johnlon", "author_id": 1059904, "author_profile": "https://Stackoverflow.com/users/1059904", "pm_score": 1, "selected": false, "text": "void debugUtil(String s, Object… args) {\n if (LOG.isDebugEnabled())\n LOG.debug(s, args);\n }\n);\n debugUtil(“We got a %s”, new Object() {\n @Override String toString() { \n // only evaluated if the debug statement is executed\n return expensiveCallToGetSomeValue().toString;\n }\n }\n);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
105,884
<p>I have an .Net MVC application which runs fine if I use the build in Visual Studio Webserver. If I use the projects property pages to switch to IIS as the webserver and create a virtual directory for my project, any request I send to the server results in a "Directory listing denied" failure.</p> <p>Does anyone know a solution for this?</p>
[ { "answer_id": 105905, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "//if(myLogger.isLoggable(Level.INFO) {myLogger.info(\"A String\");\nmyLogger.info(Level.INFO,\"A String\");\n myLogger.info(Level.INFO,\"A String %d\",some_number); \n" }, { "answer_id": 105908, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 6, "selected": false, "text": "private static final Logger log = Logger.getLogger(MyClass.class);\n\nConnection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n{\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle \" + d, ex);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: \" + c);\n return c;\n}\n StringBuilder toString() toString() StringBuilder toString() StringBuffer if (log.isDebugEnabled())\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n d w public final class FormatLogger\n{\n\n private final Logger log;\n\n public FormatLogger(Logger log)\n {\n this.log = log;\n }\n\n public void debug(String formatter, Object... args)\n {\n log(Level.DEBUG, formatter, args);\n }\n\n … &c. for info, warn; also add overloads to log an exception …\n\n public void log(Level level, String formatter, Object... args)\n {\n if (log.isEnabled(level)) {\n /* \n * Only now is the message constructed, and each \"arg\"\n * evaluated by having its toString() method invoked.\n */\n log.log(level, String.format(formatter, args));\n }\n }\n\n}\n\nclass MyClass \n{\n\n private static final FormatLogger log = \n new FormatLogger(Logger.getLogger(MyClass.class));\n\n Connection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n {\n log.debug(\"Attempting connection of dongle %s to widget %s.\", d, w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle %s.\", d);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: %s\", c);\n return c;\n }\n\n}\n toString() ResourceBundle MessageFormat String toString()" }, { "answer_id": 105916, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 1, "selected": false, "text": "LOGGER(LEVEL_INFO) << \"A String\";\n" }, { "answer_id": 106031, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "log.info (\"a = %s, b = %s\", a, b)\n mylist.toString() mylist get_everything() LazyGetEverything public class MainClass {\n private class LazyGetEverything { \n @Override\n public String toString() { \n return getEverything().toString(); \n }\n }\n\n private Object getEverything() {\n /* returns what you want to .toString() in the inner class */\n }\n\n public void logEverything() {\n log.info(new LazyGetEverything());\n }\n}\n getEverything() toString() getEverything()" }, { "answer_id": 144922, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 2, "selected": false, "text": "public void Example()\n{\n if(myLogger.isLoggable(Level.INFO))\n myLogger.info(\"A String\");\n if(myLogger.isLoggable(Level.FINE))\n myLogger.fine(\"A more complicated String\");\n // +1 for each test and log message\n}\n public void Example()\n{\n _LogInfo();\n _LogFine();\n // +0 for each test and log message\n}\n\nprivate void _LogInfo()\n{\n if(!myLogger.isLoggable(Level.INFO))\n return;\n\n // Do your complex argument calculations/evaluations only when needed.\n}\n\nprivate void _LogFine(){ /* Ditto ... */ }\n" }, { "answer_id": 6559894, "author": "simon", "author_id": 980640, "author_profile": "https://Stackoverflow.com/users/980640", "pm_score": 2, "selected": false, "text": "Logger logger = ...\nlogger.log(Level.DEBUG,\"The foo is {0} and the bar is {1}\",new Object[]{foo, bar});\n" }, { "answer_id": 8227871, "author": "johnlon", "author_id": 1059904, "author_profile": "https://Stackoverflow.com/users/1059904", "pm_score": 1, "selected": false, "text": "void debugUtil(String s, Object… args) {\n if (LOG.isDebugEnabled())\n LOG.debug(s, args);\n }\n);\n debugUtil(“We got a %s”, new Object() {\n @Override String toString() { \n // only evaluated if the debug statement is executed\n return expensiveCallToGetSomeValue().toString;\n }\n }\n);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
105,932
<p>It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:</p> <ul> <li>Window position same as it was <ul> <li>Unless the screen has resized and the old position is now off screen.</li> </ul></li> <li>Splitters should retain their position</li> <li>Tab containers should retain their selection</li> <li>Some dropdowns should retain their selection</li> <li>Window state (maximize, minimize, normal) is the same as it was. <ul> <li>Maybe you should never start minimized, I haven't decided.</li> </ul></li> </ul> <p>I'll add my current solutions as an answer along with the limitations.</p>
[ { "answer_id": 106010, "author": "Don Kirkby", "author_id": 4794, "author_profile": "https://Stackoverflow.com/users/4794", "pm_score": 5, "selected": true, "text": " private void MyForm_FormClosing(object sender, FormClosingEventArgs e)\n {\n Settings.Default.CustomWindowSettings = WindowSettings.Record(\n Settings.Default.CustomWindowSettings,\n this, \n splitContainer1);\n }\n\n private void MyForm_Load(object sender, EventArgs e)\n {\n WindowSettings.Restore(\n Settings.Default.CustomWindowSettings, \n this, \n splitContainer1);\n }\n" }, { "answer_id": 106012, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 2, "selected": false, "text": "Properties.Settings.Default.Save();\n" }, { "answer_id": 106020, "author": "Geir-Tore Lindsve", "author_id": 4582, "author_profile": "https://Stackoverflow.com/users/4582", "pm_score": 2, "selected": false, "text": "Size size;\nint x;\nint y;\nif (WindowState.Equals(FormWindowState.Normal))\n{\n size = Size;\n if (Location.X + size.Width > Screen.PrimaryScreen.Bounds.Width)\n x = Screen.PrimaryScreen.Bounds.Width - size.Width;\n else\n x = Location.X;\n if (Location.Y + Size.Height > Screen.PrimaryScreen.Bounds.Height)\n y = Screen.PrimaryScreen.Bounds.Height - size.Height;\n else\n y = Location.Y;\n}\nelse\n{\nsize = RestoreBounds.Size;\nx = (Screen.PrimaryScreen.Bounds.Width - size.Width)/2;\ny = (Screen.PrimaryScreen.Bounds.Height - size.Height)/2;\n}\nProperties.Settings.Position.AsPoint = new Point(x, y); // Property setting is type of Point\nProperties.Settings.Size.AsSize = size; // Property setting is type of Size\nProperties.Settings.SplitterDistance.Value = splitContainer1.SplitterDistance; // Property setting is type of int\nProperties.Settings.IsMaximized = WindowState == FormWindowState.Maximized; // Property setting is type of bool\nProperties.Settings.DropDownSelection = DropDown1.SelectedValue;\nProperties.Settings.Save();\n" }, { "answer_id": 106598, "author": "Wonko", "author_id": 14842, "author_profile": "https://Stackoverflow.com/users/14842", "pm_score": 3, "selected": false, "text": "private void MainForm_Load(object sender, EventArgs e) {\n RestoreState();\n}\n\nprivate void MainForm_FormClosing(object sender, FormClosingEventArgs e) {\n SaveState();\n}\n\nprivate void SaveState() {\n if (WindowState == FormWindowState.Normal) {\n Properties.Settings.Default.MainFormLocation = Location;\n Properties.Settings.Default.MainFormSize = Size;\n } else {\n Properties.Settings.Default.MainFormLocation = RestoreBounds.Location;\n Properties.Settings.Default.MainFormSize = RestoreBounds.Size;\n }\n Properties.Settings.Default.MainFormState = WindowState;\n Properties.Settings.Default.SplitterDistance = splitContainer1.SplitterDistance;\n Properties.Settings.Default.Save();\n}\n\nprivate void RestoreState() {\n if (Properties.Settings.Default.MainFormSize == new Size(0, 0)) {\n return; // state has never been saved\n }\n StartPosition = FormStartPosition.Manual;\n Location = Properties.Settings.Default.MainFormLocation;\n Size = Properties.Settings.Default.MainFormSize;\n // I don't like an app to be restored minimized, even if I closed it that way\n WindowState = Properties.Settings.Default.MainFormState == \n FormWindowState.Minimized ? FormWindowState.Normal : Properties.Settings.Default.MainFormState;\n splitContainer1.SplitterDistance = Properties.Settings.Default.SplitterDistance;\n}\n" }, { "answer_id": 108217, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "private void FitToScreen()\n{\n if (this.Width > Screen.PrimaryScreen.WorkingArea.Width)\n {\n this.Width = Screen.PrimaryScreen.WorkingArea.Width;\n }\n if (this.Height > Screen.PrimaryScreen.WorkingArea.Height)\n {\n this.Height = Screen.PrimaryScreen.WorkingArea.Height;\n }\n} \nprivate void LoadPreferences()\n{\n // Called from Form.OnLoad\n\n // Remember the initial window state and set it to Normal before sizing the form\n FormWindowState initialWindowState = this.WindowState;\n this.WindowState = FormWindowState.Normal;\n this.Size = UserPreferencesManager.LoadSetting(\"_Size\", this.Size);\n _currentFormSize = Size;\n // Fit to the current screen size in case the screen resolution\n // has changed since the size was last persisted.\n FitToScreen();\n bool isMaximized = UserPreferencesManager.LoadSetting(\"_Max\", initialWindowState == FormWindowState.Maximized);\n WindowState = isMaximized ? FormWindowState.Maximized : FormWindowState.Normal;\n}\nprivate void SavePreferences()\n{\n // Called from Form.OnClosed\n UserPreferencesManager.SaveSetting(\"_Size\", _currentFormSize);\n UserPreferencesManager.SaveSetting(\"_Max\", this.WindowState == FormWindowState.Maximized);\n ... save other settings\n}\n" }, { "answer_id": 5577540, "author": "takrl", "author_id": 520044, "author_profile": "https://Stackoverflow.com/users/520044", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Configuration;\nusing System.Reflection;\nusing System.Windows.Forms;\n\nnamespace CustomForm\n{\n public class MyCustomForm : Form\n {\n private ApplicationSettingsBase _appSettings = null;\n private string _settingName = \"\";\n\n public Form() : base() { }\n\n public Form(ApplicationSettingsBase settings, string settingName)\n : base()\n {\n _appSettings = settings;\n _settingName = settingName;\n\n this.Load += new EventHandler(Form_Load);\n this.FormClosing += new FormClosingEventHandler(Form_FormClosing);\n }\n\n private void Form_Load(object sender, EventArgs e)\n {\n if (_appSettings == null) return;\n\n PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);\n if (settingProperty == null) return;\n\n WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;\n if (previousSettings == null) return;\n\n previousSettings.Restore(this);\n }\n\n private void Form_FormClosing(object sender, FormClosingEventArgs e)\n {\n if (_appSettings == null) return;\n\n PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);\n if (settingProperty == null) return;\n\n WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;\n if (previousSettings == null)\n previousSettings = new WindowSettings();\n\n previousSettings.Record(this);\n\n settingProperty.SetValue(_appSettings, previousSettings, null);\n\n _appSettings.Save();\n }\n }\n}\n CustomForm.MyCustomForm f = new CustomForm.MyCustomForm(Properties.Settings.Default, \"formSettings\");\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
105,935
<p>This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.</p>
[ { "answer_id": 106125, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 1, "selected": false, "text": "For i = 1 To TheComboBoxControl.ListCount\n if TheComboBoxControl.ItemData(i) = \"Item to search for\" Then do_something()\nNext i\n" }, { "answer_id": 106157, "author": "Rikalous", "author_id": 4271, "author_profile": "https://Stackoverflow.com/users/4271", "pm_score": 1, "selected": false, "text": "Private Declare Function SendMessage Lib \"user32\" Alias \"SendMessageA\" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long \nPrivate Const LB_FINDSTRINGEXACT = &H1A2\n\nDim index as Integer\nDim searchString as String\nsearchString = \"Target\" & Chr(0)\n\nindex = SendMessage(ListBox1.hWnd, LB_FINDSTRINGEXACT , -1, searchString)\n" }, { "answer_id": 106322, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": true, "text": "Function CheckForItem(strItem, ListB As ListBox) As Boolean\nDim rs As DAO.Recordset\nDim db As Database\nDim tdf As TableDef\n\n Set db = CurrentDb\n\n CheckForItem = False\n\n Select Case ListB.RowSourceType\n Case \"Value List\"\n CheckForItem = InStr(ListB.RowSource, strItem) > 0\n\n Case \"Table/Query\"\n Set rs = db.OpenRecordset(ListB.RowSource)\n\n For i = 0 To rs.Fields.Count - 1\n strList = strList & \" & \"\",\"\" & \" & rs.Fields(i).Name\n Next\n\n rs.FindFirst \"Instr(\" & Mid(strList, 10) & \",'\" & strItem & \"')>0\"\n\n If Not rs.EOF Then CheckForItem = True\n\n Case \"Field List\"\n\n Set tdf = db.TableDefs(ListB.RowSource)\n\n For Each itm In tdf.Fields\n If itm.Name = strItem Then CheckForItem = True\n Next\n\n End Select\n\nEnd Function\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
105,950
<p>I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.</p>
[ { "answer_id": 105965, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 5, "selected": true, "text": "sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database'\n" }, { "answer_id": 106015, "author": "Tim", "author_id": 10363, "author_profile": "https://Stackoverflow.com/users/10363", "pm_score": 5, "selected": false, "text": "ALTER LOGIN ALTER LOGIN <login_name> WITH DEFAULT_DATABASE = <default_database>\n sp_defaultdb" }, { "answer_id": 106017, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 2, "selected": false, "text": "@loginname YourDomain\\YourLogin sp_defaultdb @loginame='YourDomain\\YourLogin', @defdb='YourDatabase'\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320/" ]
105,971
<p>I am working on a bash script where I need to conditionally execute some things if a particular file exists. This is happening multiple times, so I abstracted the following function:</p> <pre><code>function conditional-do { if [ -f $1 ] then echo "Doing stuff" $2 else echo "File doesn't exist!" end } </code></pre> <p>Now, when I want to execute this, I do something like:</p> <pre><code>function exec-stuff { echo "do some command" echo "do another command" } conditional-do /path/to/file exec-stuff </code></pre> <p>The problem is, I am bothered that I am defining 2 things: the function of a group of commands to execute, and then invoking my first function.</p> <p>I would like to pass this block of commands (often 2 or more) directly to "conditional-do" in a clean manner, but I have no idea how this is doable (or if it is even possible)... does anyone have any ideas?</p> <p>Note, I need it to be a readable solution... otherwise I would rather stick with what I have.</p>
[ { "answer_id": 105999, "author": "Ludvig A. Norin", "author_id": 16909, "author_profile": "https://Stackoverflow.com/users/16909", "pm_score": 4, "selected": true, "text": "function file_exists {\n if ( [ -e $1 ] ) then \n echo \"Doing stuff\"\n else\n echo \"File $1 doesn't exist\" \n false\n fi\n}\n\nfile_exists filename && (\n echo \"Do your stuff...\"\n)\n file_exists filename && echo \"Do your stuff...\"\n function file_exists {\n if ( [ -e $1 ] ) then \n echo \"Doing stuff\"\n shift\n $*\n else\n echo \"File $1 doesn't exist\" \n false\n fi\n}\n\nfile_exists filename echo \"Do your stuff...\"\n" }, { "answer_id": 110919, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "[ -f $filename ] && echo \"it has worked!\"\n function file-exists {\n [ \"$1\" ] && [ -f $1 ]\n}\n\nfile-exists $filename && echo \"It has worked\"\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
105,996
<ul> <li>I want to obtain maximum performance out of a process with many variables, many of which cannot be controlled. </li> <li>I cannot run thousands of experiments, so it'd be nice if I could run hundreds of experiments and <ul> <li>vary many controllable parameters</li> <li>collect data on many parameters indicating performance</li> <li>'correct,' as much as possible, for those parameters I couldn't control</li> <li>Tease out the 'best' values for those things I can control, and start all over again</li> </ul></li> </ul> <p>It feels like this would be called data mining, where you're going through tons of data which doesn't immediately appear to relate, but does show correlation after some effort.</p> <p>So... Where do I start looking at algorithms, concepts, theory of this sort of thing? Even related terms for purposes of search would be useful.</p> <p>Background: I like to do ultra-marathon cycling, and keep logs of each ride. I'd like to keep more data, and after hundreds of rides be able to pull out information about how I perform.</p> <p>However, everything varies - routes, environment (temp, pres., hum., sun load, wind, precip., etc), fuel, attitude, weight, water load, etc, etc, etc. I can control a few things, but running the same route 20 times to test out a new fuel regime would just be depressing, and take years to perform all the experiments that I'd like to do. I can, however, record all these things and more(telemetry on bicycle FTW).</p>
[ { "answer_id": 106013, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 3, "selected": true, "text": "speed = x*weight + y*wind + z*climb + constant\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
105,998
<p>According to what I have found so far, I can use the following code:</p> <pre> LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean)super.getApplicationContext().getBean("&sessionFactory"); System.out.println(sessionFactory.getConfiguration().buildSettings().getJdbcBatchSize()); </pre> <p>but then I get a Hibernate Exception:</p> <blockquote> <p>org.hibernate.HibernateException: No local DataSource found for configuration - dataSource property must be set on LocalSessionFactoryBean</p> </blockquote> <p>Can somebody shed some light?</p>
[ { "answer_id": 106165, "author": "Matt Solnit", "author_id": 6198, "author_profile": "https://Stackoverflow.com/users/6198", "pm_score": 3, "selected": true, "text": "System.out.println(sessionFactory.getConfiguration().getProperty(\"hibernate.jdbc.batch_size\"))\n" }, { "answer_id": 107359, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 2, "selected": false, "text": "((SessionFactoryImplementor)sessionFactory).getSettings().getJdbcBatchSize()\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/105998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14068/" ]
106,000
<p>I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list?</p> <p>I have been searching for awhile but I cannot seem to find a comprehensive list.</p> <p>Thanks :)</p>
[ { "answer_id": 106165, "author": "Matt Solnit", "author_id": 6198, "author_profile": "https://Stackoverflow.com/users/6198", "pm_score": 3, "selected": true, "text": "System.out.println(sessionFactory.getConfiguration().getProperty(\"hibernate.jdbc.batch_size\"))\n" }, { "answer_id": 107359, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 2, "selected": false, "text": "((SessionFactoryImplementor)sessionFactory).getSettings().getJdbcBatchSize()\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14281/" ]
106,001
<p>I have some code which utilizes parameterized queries to prevent against injection, but I also need to be able to dynamically construct the query regardless of the structure of the table. What is the proper way to do this?</p> <p>Here's an example, say I have a table with columns Name, Address, Telephone. I have a web page where I run <b>Show Columns</b> and populate a select drop-down with them as options.</p> <p>Next, I have a textbox called <b>Search</b>. This textbox is used as the parameter.</p> <p>Currently my code looks something like this:</p> <pre> result = pquery('SELECT * FROM contacts WHERE `' + escape(column) + '`=?', search); </pre> <p>I get an icky feeling from it though. The reason I'm using parameterized queries is to avoid using <b>escape</b>. Also, <b>escape</b> is likely not designed for escaping column names.</p> <p>How can I make sure this works the way I intend?</p> <p><b>Edit:</b> The reason I require dynamic queries is that the schema is user-configurable, and I will not be around to fix anything hard-coded.</p>
[ { "answer_id": 106014, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 4, "selected": true, "text": "@columns = qw/Name Address Telephone/;\nif ($columns[$param]) {\n $query = \"select * from contacts where $columns[$param] = ?\";\n} else {\n die \"Invalid column!\";\n}\n\nrun_sql($query, $search);\n" }, { "answer_id": 106089, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "SELECT * FROM \"SomeTable\" WHERE \"SomeColumn\" = ?\n" }, { "answer_id": 106090, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 0, "selected": false, "text": "if ( $column !~ /^\\w+$/ ) {\n die \"Bad column name [$column]\";\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ]
106,033
<p>Suppose I am writing an application in C++ and C#. I want to write the low level parts in C++ and write the high level logic in C#. How can I load a .NET assembly from my C++ program and start calling methods and accessing the properties of my C# classes?</p>
[ { "answer_id": 106101, "author": "Francis B.", "author_id": 17067, "author_profile": "https://Stackoverflow.com/users/17067", "pm_score": 5, "selected": true, "text": "[Guid(\"123565C4-C5FA-4512-A560-1D47F9FDFA20\")]\npublic interface IConfig\n{\n [DispId(1)]\n string Destination{ get; }\n\n [DispId(2)]\n void Unserialize();\n\n [DispId(3)]\n void Serialize();\n}\n\n[ComVisible(true)]\n[Guid(\"12AC8095-BD27-4de8-A30B-991940666927\")]\n[ClassInterface(ClassInterfaceType.None)]\npublic sealed class Config : IConfig\n{\n public Config()\n {\n }\n\n public string Destination\n {\n get { return \"\"; }\n }\n\n public void Serialize()\n {\n }\n\n public void Unserialize()\n {\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4828/" ]
106,036
<p>I have a WinForms app written in C# with .NET 3.5. It runs a lengthy batch process. I want the app to update status of what the batch process is doing. What is the best way to update the UI?</p>
[ { "answer_id": 106063, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 3, "selected": false, "text": "Application.DoEvents()" }, { "answer_id": 106408, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 1, "selected": false, "text": "Control.Invoke Control.Invoke .BeginInvoke() .BeginInvoke()" }, { "answer_id": 8219852, "author": "frediano", "author_id": 874840, "author_profile": "https://Stackoverflow.com/users/874840", "pm_score": 2, "selected": false, "text": "Backgroundworker ProgressChanged ProgressBar WorkerReportsProgress=true ReportProgress" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
106,053
<p>I already know the obvious answer to this question: "just download &lt;insert favorite windows grep or grep-like tool here&gt;". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep":</p> <pre> perl -n -e "print $_ if (m![expression]!);" [filename] </pre> <p>How do I write a batch script that I can do something like, for example:</p> <pre> dir | grep.bat mypattern grep.bat mypattern myfile.txt </pre> <p><strong>EDIT</strong>: Even though I marked another "answer", I wanted to give kudos to <a href="https://stackoverflow.com/questions/106053/how-to-make-a-batch-file-to-act-like-a-simple-grep-using-perl#106099">Ray Hayes answer</a>, as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted.</p>
[ { "answer_id": 106099, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 5, "selected": false, "text": "c:\\>FindStr /? \nSearches for strings in files.\n\nFINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]\n [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]\n strings [[drive:][path]filename[ ...]]\n\n /B Matches pattern if at the beginning of a line.\n /E Matches pattern if at the end of a line.\n /L Uses search strings literally.\n /R Uses search strings as regular expressions.\n /S Searches for matching files in the current directory and all\n subdirectories.\n /I Specifies that the search is not to be case-sensitive.\n /X Prints lines that match exactly.\n /V Prints only lines that do not contain a match.\n /N Prints the line number before each line that matches.\n /M Prints only the filename if a file contains a match.\n /O Prints character offset before each matching line.\n /P Skip files with non-printable characters.\n /OFF[LINE] Do not skip files with offline attribute set.\n /A:attr Specifies color attribute with two hex digits. See \"color /?\"\n /F:file Reads file list from the specified file(/ stands for console).\n /C:string Uses specified string as a literal search string.\n /G:file Gets search strings from the specified file(/ stands for console).\n /D:dir Search a semicolon delimited list of directories\n strings Text to be searched for.\n [drive:][path]filename\n Specifies a file or files to search.\n\nUse spaces to separate multiple search strings unless the argument is prefixed\nwith /C. For example, 'FINDSTR \"hello there\" x.y' searches for \"hello\" or\n\"there\" in file x.y. 'FINDSTR /C:\"hello there\" x.y' searches for\n\"hello there\" in file x.y.\n\nRegular expression quick reference:\n . Wildcard: any character\n * Repeat: zero or more occurances of previous character or class\n ^ Line position: beginning of line\n $ Line position: end of line\n [class] Character class: any one character in set\n [^class] Inverse class: any one character not in set\n [x-y] Range: any characters within the specified range\n \\x Escape: literal use of metacharacter x\n \\<xyz Word position: beginning of word\n xyz\\> Word position: end of word\n" }, { "answer_id": 106102, "author": "ian93", "author_id": 93438, "author_profile": "https://Stackoverflow.com/users/93438", "pm_score": 1, "selected": false, "text": "@echo off\nperl -x -S script.pl %1\n" }, { "answer_id": 106140, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 4, "selected": true, "text": "@rem = '--*-Perl-*--\n@echo off\nperl -x -S %0 %*\ngoto endofperl\n\n\n@rem -- BEGIN PERL -- ';\n#!d:/Perl/bin/perl.exe -w\n#line 10\nuse strict; \n#use Test::Setup;\nuse Getopt::Long;\n\nGetopt::Long::Configure (\"bundling\");\n\nmy $ignore_case = 0;\nmy $number_line = 0;\nmy $invert_results = 0;\nmy $verbose = 0;\n\nmy $result = GetOptions( \n 'i|ignore_case' => \\$ignore_case, \n 'n|number' => \\$number_line,\n 'v|invert' => \\$invert_results,\n 'verbose' => \\$verbose,\n);\nmy $regex = shift;\n\nif ( $ignore_case ) { \n $regex = \"(?i:$regex)\";\n}\n$regex = qr/$regex/;\nprint \"\\$regex=$regex\\n\";\nif ( $verbose ) { \n print \"Verbose: Ignoring case.\\n\" if $ignore_case;\n print \"Verbose: Printing file name and line number.\\n\" if $number_line;\n print \"Verbose: Inverting result set.\\n\" if $invert_results;\n print \"\\n\";\n}\n\n@ARGV = map { glob \"$_\" } @ARGV;\n\nwhile ( <> ) { \n my $matches = m/$regex/;\n next unless $matches ^ $invert_results;\n print \"$ARGV\\:$.:\" if $number_line;\n print;\n}\n\n__END__\n:endofperl\n" }, { "answer_id": 106187, "author": "Jim Olsen", "author_id": 15603, "author_profile": "https://Stackoverflow.com/users/15603", "pm_score": 1, "selected": false, "text": "@echo off\n\nfor /f \"usebackq delims==\" %%f in (`dir /w /b %2`) do (\n perl -n -e \"print $_ if (m!%1!);\" \"%%f\"\n REM or something like: myperlscript.pl %1 \"%%f\"\n)\n" }, { "answer_id": 106326, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "use strict;\nuse warnings;\n\nmy $pattern = shift or die \"Usage: $0 <pattern> [files|-]\\n\";\nwhile (<>) { print if /$pattern/ }\n pl2bat mygrep.pl\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ]
106,058
<p>Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some.</p> <p>Is there a <em>practical</em> code example of Lisp's power?<br/>(Preferably alongside equivalent logic coded in a regular language.)</p>
[ { "answer_id": 107544, "author": "Mikael Jansson", "author_id": 18753, "author_profile": "https://Stackoverflow.com/users/18753", "pm_score": 6, "selected": false, "text": "(defun ldap-users ()\n (let ((people (make-hash-table :test 'equal)))\n (ldap:dosearch (ent (ldap:search *ldap* \"(&(telephonenumber=*) (cn=*))\"))\n (let ((mail (car (ldap:attr-value ent 'mail)))\n (uid (car (ldap:attr-value ent 'uid)))\n (name (car (ldap:attr-value ent 'cn)))\n (phonenumber (car (ldap:attr-value ent 'telephonenumber))))\n (setf (gethash uid people)\n (list mail name phonenumber))))\n people))\n (defun ldap-users ()\n (let ((people (make-hash-table :test 'equal))) ; equal so strings compare equal!\n (ldap:dosearch (ent (ldap:search *ldap* \"(&(telephonenumber=*) (cn=*))\"))\n (with-ldap-attrs (mail uid name phonenumber) ent\n (setf (gethash uid people)\n (list mail name phonenumber))))\n people))\n #define (defun ldap-attr (entity attr)\n `(,attr (car (ldap:attr-value ,entity ',attr))))\n attr car first ldap:attr-value (defmacro with-ldap-attrs (attrs ent &rest body)\n `(let ,(loop for attr in attrs\n collecting `,(ldap-attr ent attr))\n ,@body)) \n ,@ macroexpand-1 (macroexpand-1 '(with-ldap-attrs (mail phonenumber) ent\n (format t \"~a with ~a\" mail phonenumber)))\n (let ((mail (car (trivial-ldap:attr-value ent 'mail)))\n (phonenumber (car (trivial-ldap:attr-value ent 'phonenumber))))\n (format t \"~a with ~a\" mail phonenumber))\n when (defmacro my-when (test &rest body)\n `(if ,test \n (progn ,@body)))\n if progn ;; one form\n(if (numberp 1)\n (print \"yay, a number\"))\n\n;; two forms\n(if (numberp 1)\n (progn\n (assert-world-is-sane t)\n (print \"phew!\"))))\n my-when progn (my-when (numberp 1)\n (assert-world-is-sane t)\n (print \"phew!\"))\n my-when Lisp> (macroexpand-1 '(my-when (numberp 1)\n (print \"yay!\")))\n\n(if (numberp 1)\n (progn (print \"yay!\")))\n macroexpand-1" }, { "answer_id": 108068, "author": "Mikael Jansson", "author_id": 18753, "author_profile": "https://Stackoverflow.com/users/18753", "pm_score": 4, "selected": false, "text": "class PeelingTool:\n \"\"\"I'm used to peel things. Mostly fruit, but anything peelable goes.\"\"\"\n def peel(self, veggie):\n veggie.get_peeled(self)\n\nclass Veggie:\n \"\"\"I'm a defenseless Veggie. I obey the get_peeled protocol\n used by the PeelingTool\"\"\"\n def get_peeled(self, tool):\n pass\n\nclass FingerTool(PeelingTool):\n ...\n\nclass KnifeTool(PeelingTool):\n ...\n\nclass Banana(Veggie):\n def get_peeled(self, tool):\n if type(tool) == FingerTool:\n self.hold_and_peel(tool)\n elif type(tool) == KnifeTool:\n self.cut_in_half(tool)\n peel (defclass peeling-tool () ())\n(defclass knife-tool (peeling-tool) ())\n(defclass finger-tool (peeling-tool) ())\n\n(defclass veggie () ())\n(defclass banana (veggie) ())\n\n(defgeneric peel (veggie tool)\n (:documentation \"I peel veggies, or actually anything that wants to be peeled\"))\n\n;; It might be possible to peel any object using any tool,\n;; but I have no idea how. Left as an exercise for the reader\n(defmethod peel (veggie tool)\n ...)\n\n;; Bananas are easy to peel with our fingers!\n(defmethod peel ((veggie banana) (tool finger-tool))\n (with-hands (left-hand right-hand) *me*\n (hold-object left-hand banana)\n (peel-with-fingers right-hand tool banana)))\n\n;; Slightly different using a knife\n(defmethod peel ((veggie banana) (tool knife-tool))\n (with-hands (left-hand right-hand) *me*\n (hold-object left-hand banana)\n (cut-in-half tool banana)))\n" }, { "answer_id": 108102, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 3, "selected": false, "text": "C-M-x (html\n (head\n (title \"The Title\"))\n (body\n (h1 \"The Headline\" :class \"headline\")\n (p \"Some text here\" :id \"content\")))\n <html>\n <head>\n <title>The title</title>\n </head>\n <body>\n <h1 class=\"headline\">The Headline</h1>\n <p id=\"contents\">Some text here</p>\n </body>\n</html>\n" }, { "answer_id": 109131, "author": "Attila Lendvai", "author_id": 14464, "author_profile": "https://Stackoverflow.com/users/14464", "pm_score": 3, "selected": false, "text": "(babel:octets-to-string\n (with-output-to-sequence (*html-stream*)\n <div (constantAttribute 42\n someJavaScript `js-inline(print (+ 40 2))\n runtimeAttribute ,(concatenate 'string \"&foo\" \"&bar\"))\n <someRandomElement\n <someOther>>>))\n\n =>\n\n \"<div constantAttribute=\\\"42\\\"\n someJavaScript=\\\"javascript: print((40 + 2))\\\"\n runtimeAttribute=\\\"&amp;foo&amp;bar\\\">\n <someRandomElement>\n <someOther/>\n </someRandomElement>\n </div>\"\n , (progn\n (write-sequence\n #(60 100 105 118 32 99 111 110 115 116 97 110 116 65 116 116 114 105 98\n 117 116 101 61 34 52 50 34 32 115 111 109 101 74 97 118 97 83 99 114\n 105 112 116 61 34 106 97 118 97 115 99 114 105 112 116 58 32 112 114\n 105 110 116 40 40 52 48 32 43 32 50 41 41 34 32 114 117 110 116 105\n 109 101 65 116 116 114 105 98 117 116 101 61 34)\n *html-stream*)\n (write-quasi-quoted-binary\n (let ((*transformation*\n #<quasi-quoted-string-to-quasi-quoted-binary {1006321441}>))\n (transform-quasi-quoted-string-to-quasi-quoted-binary\n (let ((*transformation*\n #<quasi-quoted-xml-to-quasi-quoted-string {1006326E51}>))\n (locally\n (declare (sb-ext:muffle-conditions sb-ext:compiler-note))\n (let ((it (concatenate 'string \"runtime calculated: \" \"&foo\" \"&bar\")))\n (if it\n (transform-quasi-quoted-xml-to-quasi-quoted-string/attribute-value it)\n nil))))))\n *html-stream*)\n (write-sequence\n #(34 62 10 32 32 60 115 111 109 101 82 97 110 100 111 109 69 108 101 109\n 101 110 116 62 10 32 32 32 32 60 115 111 109 101 79 116 104 101 114 47\n 62 10 32 32 60 47 115 111 109 101 82 97 110 100 111 109 69 108 101 109\n 101 110 116 62 10 60 47 100 105 118 62 10)\n *html-stream*)\n +void+)\n \"<div constantAttribute=\\\"42\\\"\n someJavaScript=\\\"javascript: print((40 + 2))\\\"\n runtimeAttribute=\\\"\"\n \"\\\">\n <someRandomElement>\n <someOther/>\n </someRandomElement>\n</div>\"\n" }, { "answer_id": 118924, "author": "Nowhere man", "author_id": 400277, "author_profile": "https://Stackoverflow.com/users/400277", "pm_score": 4, "selected": false, "text": "(defmacro while (condition &body body)\n `(if ,condition\n (progn\n ,@body\n (do nil ((not ,condition))\n ,@body))))\n (let ((foo 5))\n (while (not (zerop (decf foo)))\n (format t \"still not zero: ~a~%\" foo)))\n still not zero: 4\nstill not zero: 3\nstill not zero: 2\nstill not zero: 1\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ]
106,067
<p>In java, which regular expression can be used to replace these, for example:</p> <p>before: aaabbb after: ab</p> <p>before: 14442345 after: 142345</p> <p>thanks!</p>
[ { "answer_id": 106096, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 6, "selected": true, "text": "s/(.)\\1+/$1/g;\n s {\n (.) # match any charater ( and capture it )\n \\1 # if it is followed by itself \n + # One or more times\n}{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences)\n original.replaceAll(\"(.)\\\\1+\", \"$1\");\n" }, { "answer_id": 106107, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": "String a = \"aaabbb\";\nString b = a.replaceAll(\"(.)\\\\1+\", \"$1\");\nSystem.out.println(\"'\" + a + \"' -> '\" + b + \"'\");\n" }, { "answer_id": 106109, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 2, "selected": false, "text": "\"14442345\".replaceAll(\"(.)\\\\1+\", \"$1\");\n" }, { "answer_id": 106110, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 2, "selected": false, "text": "originalString.replaceAll( \"(.)\\\\1+\", \"$1\" );\n" }, { "answer_id": 106145, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 1, "selected": false, "text": "(.)\\\\1+\n (.)\\1+ \n $1\n" }, { "answer_id": 111796, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "tr/a-z0-9//s;\n $ perl -E'@a = (aaabbb, 14442345); for(@a) { tr/a-z0-9//s; say }'\nab\n142345 \n tr s/(.)\\1+/$1/sg; \n#NOTE: `s` modifier. It takes into account consecutive newlines.\n $ perl -E'@a = (aaabbb, 14442345); for(@a) { s/(.)\\1+/$1/sg; say }'\nab\n142345 \n" }, { "answer_id": 24529905, "author": "kunwar.sangram", "author_id": 2280300, "author_profile": "https://Stackoverflow.com/users/2280300", "pm_score": 0, "selected": false, "text": "static String cleanDuplicates(@NonNull final String val) { \n assert val != null;\n return val.replaceAll(\"(?<dup>.)\\\\k<dup>+\",\"${dup}\");\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
106,095
<p>Using ASP.NET 2.0, I have a web app where I am trying to use JavaScript to make one tab in a tab-container the active tab.</p> <p>The recommendations have been based on:</p> <pre><code>var mX=document.getElementById('&lt;%= tc1.ClientID%&gt;') $find('&lt;%= tc1.ClientID%&gt;').set_activeTabIndex(1); </code></pre> <p>Which both produce the error:</p> <pre><code>The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). </code></pre> <p>I've tried moving the code out of the head tag and into the body tag; same error.</p> <p>I've also tried the alternative <code>&lt;%# tc1.ClientID%&gt;</code>, as in:</p> <pre><code>var mX = document.getElementById('&lt;%# tc1.ClientID %&gt;') mX.ActiveTabIndex="2"; </code></pre> <p>Generates a null error - code above is rendered in the html as: </p> <pre><code>var mX = document.getElementById('') mX.ActiveTabIndex="2"; </code></pre> <p>Can anyone explain in plain(er) language what this means and what the solution is?</p>
[ { "answer_id": 106297, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 0, "selected": false, "text": "<div runat=\"server\" id=\"rawr\">\n <span id=\"myspan\">HI</span>\n</div>\n</form>\n\n<script type=\"text/javascript\">\n var obj = '<%= DateTime.Now.ToShortDateString() %>';\n var ele = document.getElementById(\"myspan\");\n ele.innerHTML = obj;\n</script>\n" }, { "answer_id": 106355, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 2, "selected": false, "text": "<asp:Panel id=\"whatever\" runat=\"server\">\n <script type=\"text/javascript\">\n var mX=document.getElementById('<%= tc1.ClientID%>');\n //and so on...\n </script>\n</asp:Panel>\n <asp:Panel id=\"whatever\" runat=\"server\">\n <asp:PlaceHolder id=\"dontCare\" runat=\"server\">\n <script type=\"text/javascript\">\n var mX=document.getElementById('<%= tc1.ClientID%>');\n //and so on...\n </script>\n </asp:PlaceHolder>\n</asp:Panel>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
106,117
<p>Please bear with me, I'm just learning C++. </p> <p>I'm trying to write my header file (for class) and I'm running into an odd error.</p> <pre><code>cards.h:21: error: expected unqualified-id before ')' token cards.h:22: error: expected `)' before "str" cards.h:23: error: expected `)' before "r" </code></pre> <p>What does "expected unqualified-id before ')' token" mean? And what am I doing wrong? </p> <p>Edit: Sorry, I didn't post the entire code.</p> <pre><code>/* Card header file [Author] */ // NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/ #define Card #define Hand #define AppError #include &lt;string&gt; using namespace std; // TODO: Docs here class Card { // line 17 public: enum Suit {Club, Diamond, Spade, Heart}; enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}; Card(); // line 22 Card(string str); Card(Rank r, Suit s); </code></pre> <p>Edit: I'm just trying to compile the header file by itself using "g++ file.h". </p> <p>Edit: Closed question. My code is working now. Thanks everyone! Edit: Reopened question after reading <a href="https://stackoverflow.com/questions/34456/etiquette-closing-your-posts">Etiquette: Closing your posts</a></p>
[ { "answer_id": 106127, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "#define #ifndef CARD_H\n#define CARD_H\n\nclass Card ...\n...\n\n#endif\n string std::string" }, { "answer_id": 106170, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 5, "selected": true, "text": "#define #define Card Card #define Token #define Token Replace 1 #define Card 1(); ();" }, { "answer_id": 107858, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "#define Card\n#define Hand\n#define AppError\n class Card ;\nclass Hand ;\nclass AppError ;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ]
106,134
<p>Does anyone know of any tools capable of defining a declarative mapping from T-Box structures from one ontology to another, which when executed can effect translation of A-Box instance data from one ontology's form to another's? </p> <p>I have recently written such a tool to meet my needs, but I was wondering if I reinvented the wheel.</p>
[ { "answer_id": 106127, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "#define #ifndef CARD_H\n#define CARD_H\n\nclass Card ...\n...\n\n#endif\n string std::string" }, { "answer_id": 106170, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 5, "selected": true, "text": "#define #define Card Card #define Token #define Token Replace 1 #define Card 1(); ();" }, { "answer_id": 107858, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "#define Card\n#define Hand\n#define AppError\n class Card ;\nclass Hand ;\nclass AppError ;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19269/" ]
106,137
<p>When you want to add whitespace between HTML elements (using CSS), to which element do you attach it?</p> <p>I'm regularly in situations along these lines:</p> <pre><code>&lt;body&gt; &lt;h1&gt;This is the heading&lt;/h1&gt; &lt;p&gt;This is a paragraph&lt;/p&gt; &lt;h1&gt;Here's another heading&lt;/h1&gt; &lt;div&gt;This is a footer&lt;/div&gt; &lt;/body&gt; </code></pre> <p>Now, say I wanted 1em of space between each of these elements, but none above the first h1 or below the last div. To which elements would I attach it?</p> <p>Obviously, there's no real <strong>technical</strong> difference between this:</p> <pre><code>h1, p { margin-bottom: 1em; } </code></pre> <p>...and this...</p> <pre><code>div { margin-top: 1em; } p { margin-top: 1em; margin-bottom: 1em } </code></pre> <p>What I'm interested is secondary factors: </p> <ol> <li>Consistency</li> <li>Applicability to all situations</li> <li>Ease / Simplicity</li> <li>Ease of making changes</li> </ol> <p>For example: in this particular scenario, I'd say that the first solution is better than the second, as it's simpler; you're only attaching a margin-bottom to two elements in a single property definition. However, I'm looking for a more general-purpose solution. Every time I do CSS work, I get the feeling that there's a good rule of thumb to apply... but I'm not sure what it is. Does anyone have a good argument?</p>
[ { "answer_id": 106153, "author": "Pavling", "author_id": 18197, "author_profile": "https://Stackoverflow.com/users/18197", "pm_score": 4, "selected": true, "text": "<body>\n <h1>This is the heading</h1>\n <p>This is a paragraph</p>\n <h1>Here's another heading</h1>\n <div class=\"last\">This is a footer</div>\n</body>\n div { margin-bottom: 1em; }\np { margin-bottom: 1em; }\nh1 { margin-bottom: 1em; }\n.last {margin-bottom: 0; }\n" }, { "answer_id": 106286, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<h1> <p> h1, p { margin: 1em; }\n\n<h1>...</h1>\n<p>...</p>\n" }, { "answer_id": 110329, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": false, "text": "<body>\n <div id=\"header\"></div>\n <h1>This is the heading</h1>\n <p>This is a paragraph</p>\n <h1>Here's another heading</h1>\n <div id=\"footer\">This is a footer</div>\n</body>\n #header {\n margin-bottom: 1em;\n}\n\n#footer {\n margin-top: 1em;\n}\n\nh1, p {\n margin: 1em 0;\n}\n" }, { "answer_id": 111524, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "last h1 {\n margin: 0 0 1em;\n}\n\ndiv, p, p + h1, div + h1 {\n margin: 1em 0 0;\n}\n h1 h1" }, { "answer_id": 33955089, "author": "JDavies", "author_id": 1256637, "author_profile": "https://Stackoverflow.com/users/1256637", "pm_score": 0, "selected": false, "text": "h1{\n margin-top:10px;\n margin-bottom:10px;\n}\nh1:first-child{\n margin-top:0px;\n}\np{\n margin:10px;\n}\np:first-child{\n margin-top:0px;\n}\np:last-child{\n margin-bottom:0px;\n}\n" }, { "answer_id": 34799717, "author": "tao", "author_id": 1891677, "author_profile": "https://Stackoverflow.com/users/1891677", "pm_score": 1, "selected": false, "text": "body > * {\n margin-bottom: 1em;\n}\nbody > *:last-child {\n margin-bottom: 0;\n}\n margin-bottom:0;" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
106,175
<p><a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="nofollow noreferrer">VB.NET</a> has a very handy "with" statement, but it also lets you use it on an unnamed variable, like this:</p> <pre><code>With New FancyClass() .Level = "SuperSpiffy" .Style = Slimming .Execute() End With </code></pre> <p>Is there a way to get at the "hidden" instance, so I can view its properties in the Immediate window? I doubt I'll get it in the watch windows, so immediate is fine.</p> <p>If you try to access the instance the same way (say, when <code>.Execute()</code> throws an exception) from the Immediate window, you get an error:</p> <pre><code>? .Style 'With' contexts and statements are not valid in debug windows. </code></pre> <p>Is there any trick that can be used to get this, or do I have to convert the code to another style? If <code>With</code> functioned more like a <code>Using</code> statement, (e.g. "With v = New FancyClass()") this wouldn't pose a problem.</p> <p>I know how <code>With</code> is working, what alternatives exist, what the compiler does, etc. I just want to know if this is possible.</p>
[ { "answer_id": 106284, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "Dim x = new SomethingOrOther()\nWith x\n .DoSomething()\nEnd With\nx = Nothing ' for the memory conscious\n" }, { "answer_id": 121635, "author": "MikeScott8", "author_id": 1889, "author_profile": "https://Stackoverflow.com/users/1889", "pm_score": 2, "selected": true, "text": "Using fc as new FancyClass()\n With fc \n .Level = \"SuperSpiffy\" \n .Style = Slimming \n .Execute()\n End With\nEnd Using\n fc=nothing \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15127/" ]
106,179
<p>Does anyone have a regular expression handy that will match any legal DNS hostname or IP address?</p> <p>It's easy to write one that works 95% of the time, but I'm hoping to get something that's well tested to exactly match the latest RFC specs for DNS hostnames.</p>
[ { "answer_id": 106223, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 10, "selected": true, "text": "ValidIpAddressRegex = \"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$\";\n\nValidHostnameRegex = \"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$\";\n Valid952HostnameRegex = \"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$\";\n" }, { "answer_id": 2296904, "author": "Bill Stephens", "author_id": 277020, "author_profile": "https://Stackoverflow.com/users/277020", "pm_score": 0, "selected": false, "text": "^.*-Dhttp\\.proxyHost=(\\w{1,}\\.\\w{1,}\\.\\w{1,}\\.*\\w{0,})\\s.*$\n" }, { "answer_id": 2375080, "author": "Alex Volkov", "author_id": 86294, "author_profile": "https://Stackoverflow.com/users/86294", "pm_score": 3, "selected": false, "text": "egrep '([[:digit:]]{1,3}\\.){3}[[:digit:]]{1,3}'\n tld=$(curl -s http://data.iana.org/TLD/tlds-alpha-by-domain.txt | sed 1d | cut -f1 -d'-' | tr '\\n' '|' | sed 's/\\(.*\\)./\\1/')\necho \"($tld)\"\n (([a-z0-9]+|([a-z0-9]+[-]+[a-z0-9]+))[.])+\n $pattern = '/^(([a-z0-9]+|([a-z0-9]+[-]+[a-z0-9]+))[.])+(AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN|XN|XN|XN|XN|XN|XN|XN|XN|XN|XN|YE|YT|YU|ZA|ZM|ZW)[.]?$/i';\n\n if (preg_match, $pattern, $matching_string){\n ... do stuff\n }\n" }, { "answer_id": 6342447, "author": "PythonDev", "author_id": 736327, "author_profile": "https://Stackoverflow.com/users/736327", "pm_score": 2, "selected": false, "text": "def isValidHostname(hostname):\n\n if len(hostname) > 255:\n return False\n if hostname[-1:] == \".\":\n hostname = hostname[:-1] # strip exactly one dot from the right,\n # if present\n allowed = re.compile(\"(?!-)[A-Z\\d-]{1,63}(?<!-)$\", re.IGNORECASE)\n return all(allowed.match(x) for x in hostname.split(\".\"))\n" }, { "answer_id": 8818278, "author": "Thangaraj", "author_id": 1143035, "author_profile": "https://Stackoverflow.com/users/1143035", "pm_score": -1, "selected": false, "text": "[a-z\\d+].*?\\\\.\\w{2,4}$\n" }, { "answer_id": 9250864, "author": "Prakash Thapa", "author_id": 854054, "author_profile": "https://Stackoverflow.com/users/854054", "pm_score": 2, "selected": false, "text": "^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$\n" }, { "answer_id": 14453696, "author": "Alban", "author_id": 1911082, "author_profile": "https://Stackoverflow.com/users/1911082", "pm_score": 5, "selected": false, "text": "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\n ([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}\n OR 10.48.0.200\n" }, { "answer_id": 15887225, "author": "Saikrishna Rao", "author_id": 1128212, "author_profile": "https://Stackoverflow.com/users/1128212", "pm_score": -1, "selected": false, "text": "([0-9]{1,3}\\.){3}[0-9]{1,3}\n" }, { "answer_id": 16134774, "author": "user2240578", "author_id": 2240578, "author_profile": "https://Stackoverflow.com/users/2240578", "pm_score": 1, "selected": false, "text": "/^(?:[a-zA-Z0-9]+|[a-zA-Z0-9][-a-zA-Z0-9]+[a-zA-Z0-9])(?:\\.[a-zA-Z0-9]+|[a-zA-Z0-9][-a-zA-Z0-9]+[a-zA-Z0-9])?$/\n" }, { "answer_id": 22137739, "author": "zangw", "author_id": 3011380, "author_profile": "https://Stackoverflow.com/users/3011380", "pm_score": 1, "selected": false, "text": "\"^((\\\\d{1,2}|1\\\\d{2}|2[0-4]\\\\d|25[0-5])\\.){3}(\\\\d{1,2}|1\\\\d{2}|2[0-4]\\\\d|25[0-5])$\"\n" }, { "answer_id": 24402376, "author": "ayu for u", "author_id": 2971220, "author_profile": "https://Stackoverflow.com/users/2971220", "pm_score": 0, "selected": false, "text": "AddressRegex = \"^(ftp|http|https):\\/\\/([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}:[0-9]{1,5})$\";\n\nHostnameRegex = /^(ftp|http|https):\\/\\/([a-z0-9]+\\.)?[a-z0-9][a-z0-9-]*((\\.[a-z]{2,6})|(\\.[a-z]{2,6})(\\.[a-z]{2,6}))$/i\n" }, { "answer_id": 28230259, "author": "aliasav", "author_id": 3725732, "author_profile": "https://Stackoverflow.com/users/3725732", "pm_score": 1, "selected": false, "text": "regex = '^([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])$'\n" }, { "answer_id": 30472389, "author": "seraphim", "author_id": 962682, "author_profile": "https://Stackoverflow.com/users/962682", "pm_score": 0, "selected": false, "text": "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\n" }, { "answer_id": 31600964, "author": "Thom Anderson", "author_id": 3821279, "author_profile": "https://Stackoverflow.com/users/3821279", "pm_score": 0, "selected": false, "text": "grep -E '(^|[^[:alnum:]+)(([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\.){3}([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])([^[:alnum:]]|$)' \n -P grep grep -P '(?<![\\d\\w\\.])(?<o>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\\.\\g<o>){3}(?![\\d\\w\\.])'\n grep -P '(?<![\\d\\w\\.])(?<x>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\\.\\g<x>){3}(?!([\\d\\w]|\\.\\d))'\n" }, { "answer_id": 34721398, "author": "sirjay", "author_id": 1802225, "author_profile": "https://Stackoverflow.com/users/1802225", "pm_score": -1, "selected": false, "text": "filter_var(gethostbyname($dns), FILTER_VALIDATE_IP) == true ? 'ip' : 'not ip'" }, { "answer_id": 36564531, "author": "Mohammad Shahid Siddiqui", "author_id": 1591700, "author_profile": "https://Stackoverflow.com/users/1591700", "pm_score": 1, "selected": false, "text": ">>> my_hostname = \"testhostn.ame\"\n>>> print bool(re.match(\"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$\", my_hostname))\nTrue\n>>> my_hostname = \"testhostn....ame\"\n>>> print bool(re.match(\"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$\", my_hostname))\nFalse\n>>> my_hostname = \"testhostn.A.ame\"\n>>> print bool(re.match(\"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$\", my_hostname))\nTrue\n" }, { "answer_id": 50192885, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 2, "selected": false, "text": "#include <arpa/inet.h>\n#include <stdio.h>\n\nint main(int argc, char *argv[]) {\n for (int i=1; i!=argc; ++i) {\n struct in_addr addr = {0};\n printf(\"%s: \", argv[i]);\n if (inet_pton(AF_INET, argv[i], &addr) != 1)\n printf(\"invalid\\n\");\n else\n printf(\"%u\\n\", addr.s_addr);\n }\n return 0;\n}\n >>> import ipaddress\n>>> import re\n>>> msg = \"My address is 192.168.0.42; 192.168.0.420 is not an address\"\n>>> for maybeip in re.findall(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}', msg):\n... try:\n... print(ipaddress.ip_address(maybeip))\n... except ValueError:\n... pass\n" }, { "answer_id": 54954504, "author": "Darrell Root", "author_id": 9722622, "author_profile": "https://Stackoverflow.com/users/9722622", "pm_score": 1, "selected": false, "text": "import Network\nlet tests = [\"192.168.4.4\",\"fkjhwojfw\",\"192.168.4.4.4\",\"2620:3\",\"2620::33\"]\n\nfor test in tests {\n if let _ = IPv4Address(test) {\n debugPrint(\"\\(test) is valid ipv4 address\")\n } else if let _ = IPv6Address(test) {\n debugPrint(\"\\(test) is valid ipv6 address\")\n } else {\n debugPrint(\"\\(test) is not a valid IP address\")\n }\n}\n\noutput:\n\"192.168.4.4 is valid ipv4 address\"\n\"fkjhwojfw is not a valid IP address\"\n\"192.168.4.4.4 is not a valid IP address\"\n\"2620:3 is not a valid IP address\"\n\"2620::33 is valid ipv6 address\"\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10452/" ]
106,201
<p>In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here. </p> <p><strong>Problem</strong></p> <p>I have:</p> <p>An application that has to be installed on on Redhat or SuSE enterprise. </p> <p>It has huge system requirements and requires OpenGL.</p> <p>It is part of a suite of tools that need to operate together on one machine.</p> <p>This application is used for a time intensive task in terms of man hours.</p> <p>I don't want to sit in the server room working on this application.</p> <p>So, the question came up... how do I run this application from a remote windows machine?</p> <p>I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme.</p>
[ { "answer_id": 106218, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 5, "selected": true, "text": "Connection->Seconds Between Keepalives: 30\nConnection->Enable TCP Keepalives: Yes\n\nConnection->SSH->X11->Enable X11 forwarding: Yes\nConnection->SSH->X11->X display location: localhost:0:0\n" }, { "answer_id": 61294376, "author": "Rafael Duarte", "author_id": 5395184, "author_profile": "https://Stackoverflow.com/users/5395184", "pm_score": 0, "selected": false, "text": "sudo vi /etc/ssh/ssh_config\n sudo vi ~/.bashrc\n d:\\cygwin64\\bin\\run.exe --quote /usr/bin/bash.exe -l -c \"cd; /usr/bin/xinit /etc/X11/xinit/startxwinrc -- /usr/bin/XWin :0 -ac -multiwindow -listen tcp\"\n d:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico -e /usr/bin/ssh -Y user_name@ip_from_server\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
106,206
<p>I'm writing an import utility that is using phone numbers as a unique key within the import.</p> <p>I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is <strong>slow</strong> and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index.</p> <p>I tried using the script from this post:<br> <a href="https://stackoverflow.com/questions/52315/t-sql-trim-nbsp-and-other-non-alphanumeric-characters">T-SQL trim &amp;nbsp (and other non-alphanumeric characters)</a></p> <p>But that didn't speed it up any.</p> <p>Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared.</p> <p>Whatever is done needs to perform <strong>fast</strong>.</p> <p><strong>Update</strong><br> Given what people responded with, I think I'm going to have to clean the fields before I run the import utility. </p> <p>To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records). </p> <p>Could comparing BIGINT to BIGINT be slowing things down?</p> <p>I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.</p>
[ { "answer_id": 106226, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 5, "selected": true, "text": "using System; \nusing System.Data; \nusing System.Text.RegularExpressions; \nusing System.Data.SqlClient; \nusing System.Data.SqlTypes; \nusing Microsoft.SqlServer.Server; \n\npublic partial class UserDefinedFunctions \n{ \n [Microsoft.SqlServer.Server.SqlFunction] \n public static SqlString StripNonNumeric(SqlString input) \n { \n Regex regEx = new Regex(@\"\\D\"); \n return regEx.Replace(input.Value, \"\"); \n } \n}; \n UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber)\n" }, { "answer_id": 106448, "author": "Mike L", "author_id": 4796, "author_profile": "https://Stackoverflow.com/users/4796", "pm_score": 1, "selected": false, "text": "UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber) \nWHERE phonenumber like '%[^0-9]%'\n" }, { "answer_id": 2596080, "author": "Dennis Allen", "author_id": 214691, "author_profile": "https://Stackoverflow.com/users/214691", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION String.ComparablePhone( @string nvarchar(32) ) RETURNS bigint AS\nBEGIN\n DECLARE @out bigint;\n\n-- 1. table of unique characters to be kept\n DECLARE @keepers table ( chr nchar(1) not null primary key );\n INSERT INTO @keepers ( chr ) VALUES (N'0'),(N'1'),(N'2'),(N'3'),(N'4'),(N'5'),(N'6'),(N'7'),(N'8'),(N'9');\n\n-- 2. Identify the characters in the string to remove\n WITH found ( id, position ) AS\n (\n SELECT \n ROW_NUMBER() OVER (ORDER BY (n1+n10) DESC), -- since we are using stuff, for the position to continue to be accurate, start from the greatest position and work towards the smallest\n (n1+n10)\n FROM \n (SELECT 0 AS n1 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS d1,\n (SELECT 0 AS n10 UNION SELECT 10 UNION SELECT 20 UNION SELECT 30) AS d10\n WHERE\n (n1+n10) BETWEEN 1 AND len(@string)\n AND substring(@string, (n1+n10), 1) NOT IN (SELECT chr FROM @keepers)\n )\n-- 3. Use stuff to snuff out the identified characters\n SELECT \n @string = stuff( @string, position, 1, '' )\n FROM \n found\n ORDER BY\n id ASC; -- important to process the removals in order, see ROW_NUMBER() above\n\n-- 4. Try and convert the results to a bigint \n IF len(@string) = 0\n RETURN NULL; -- an empty string converts to 0\n\n RETURN convert(bigint,@string); \nEND\n INSERT INTO Contacts ( phone, first_name, last_name )\nSELECT i.phone, i.first_name, i.last_name\nFROM Imported AS i\nLEFT JOIN Contacts AS c ON String.ComparablePhone(c.phone) = String.ComparablePhone(i.phone)\nWHERE c.phone IS NULL -- Exclude those that already exist\n" }, { "answer_id": 4087219, "author": "Debayan Samaddar", "author_id": 495923, "author_profile": "https://Stackoverflow.com/users/495923", "pm_score": 3, "selected": false, "text": "create function dbo.RemoveNonNumericChar(@str varchar(500)) \nreturns varchar(500) \nbegin \ndeclare @startingIndex int \nset @startingIndex=0 \nwhile 1=1 \nbegin \n set @startingIndex= patindex('%[^0-9]%',@str) \n if @startingIndex <> 0 \n begin \n set @str = replace(@str,substring(@str,@startingIndex,1),'') \n end \n else break; \nend \nreturn @str \nend\n\ngo \n\nselect dbo.RemoveNonNumericChar('aisdfhoiqwei352345234@#$%^$@345345%^@#$^') \n" }, { "answer_id": 6267337, "author": "Tim", "author_id": 787723, "author_profile": "https://Stackoverflow.com/users/787723", "pm_score": 0, "selected": false, "text": "SUBSTRING([Phone], CHARINDEX('(', [Phone], 1)+1, 3)\n + SUBSTRING([Phone], CHARINDEX(')', [Phone], 1)+1, 3)\n + SUBSTRING([Phone], CHARINDEX('-', [Phone], 1)+1, 4) AS Phone\n" }, { "answer_id": 6529463, "author": "David Coster", "author_id": 1022942, "author_profile": "https://Stackoverflow.com/users/1022942", "pm_score": 7, "selected": false, "text": "CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))\nRETURNS VARCHAR(1000)\nAS\nBEGIN\n WHILE PATINDEX('%[^0-9]%', @strText) > 0\n BEGIN\n SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')\n END\n RETURN @strText\nEND\n" }, { "answer_id": 7033123, "author": "Tom", "author_id": 780032, "author_profile": "https://Stackoverflow.com/users/780032", "pm_score": 4, "selected": false, "text": "set @Phone = REPLACE(REPLACE(REPLACE(REPLACE(@Phone,'(',''),' ',''),'-',''),')','')\n" }, { "answer_id": 17950550, "author": "Brainwater", "author_id": 2634647, "author_profile": "https://Stackoverflow.com/users/2634647", "pm_score": 5, "selected": false, "text": "replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string" }, { "answer_id": 22532045, "author": "AdamE", "author_id": 3441873, "author_profile": "https://Stackoverflow.com/users/3441873", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION [dbo].[RemoveAlphaCharacters](@InputString VARCHAR(1000))\nRETURNS VARCHAR(1000)\nAS\nBEGIN\n WHILE PATINDEX('%[^0-9]%',@InputString)>0\n SET @InputString = STUFF(@InputString,PATINDEX('%[^0-9]%',@InputString),1,'') \n RETURN @InputString\nEND\n\nGO\n" }, { "answer_id": 40070177, "author": "hkravitz", "author_id": 2919045, "author_profile": "https://Stackoverflow.com/users/2919045", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION [dbo].[UDF_RemoveNumericStringsFromString]\n (\n @str varchar(100)\n )\n RETURNS TABLE AS RETURN\n WITH Tally (n) as \n (\n -- 100 rows\n SELECT TOP (Len(@Str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))\n FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)\n CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)\n )\n\n SELECT OutStr = STUFF(\n (SELECT SUBSTRING(@Str, n,1) st\n FROM Tally\n WHERE ISNUMERIC(SUBSTRING(@Str, n,1)) = 1\n FOR XML PATH(''),type).value('.', 'varchar(100)'),1,0,'')\n GO\n\n /*Use it*/\n SELECT OutStr\n FROM dbo.UDF_RemoveNumericStringsFromString('fjkfhk759734977fwe9794t23')\n /*Result set\n 759734977979423 */\n" }, { "answer_id": 74276585, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 1, "selected": false, "text": "TRANSLATE REPLACE DECLARE @BadCharacters VARCHAR(256) = 'abcdefghijklmnopqrstuvwxyz';\n \nSELECT REPLACE(\n TRANSLATE(YourColumn, \n @BadCharacters, \n REPLICATE(LEFT(@BadCharacters,1),LEN(@BadCharacters))),\n LEFT(@BadCharacters,1),\n '')\nFROM @YourTable\n TRANSLATE DECLARE @CharactersToKeep VARCHAR(30) = '0123456789', \n @ExampleBadCharacter CHAR(1) = CHAR(26); \n \nSELECT REPLACE(TRANSLATE(YourColumn, bad_chars, REPLICATE(@ExampleBadCharacter, LEN(bad_chars + 'X') - 1)), @ExampleBadCharacter, '')\nFROM @YourTable\n CROSS APPLY (SELECT REPLACE(\n TRANSLATE(YourColumn, \n @CharactersToKeep, \n REPLICATE(LEFT(@CharactersToKeep, 1), LEN(@CharactersToKeep))), \n LEFT(@CharactersToKeep, 1), \n '')) ca(bad_chars)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
106,222
<p>I've read on Wikipedia and other sites about <a href="https://en.wikipedia.org/wiki/OSGi" rel="noreferrer">OSGi</a>, but I don't really see the big picture. It says that it's a component-based platform, and that you can reload modules at runtime. Also the "practical example" given everywhere is the Eclipse Plugin Framework.</p> <p>My questions are:</p> <ol> <li><p>What is the clear and simple definition of OSGi?</p></li> <li><p>What common problems does it solve?</p></li> </ol> <p>By "common problems" I mean problems we face everyday, like "What can OSGi do for making our jobs more efficient/fun/simple?"</p>
[ { "answer_id": 44545984, "author": "Martin Vysny", "author_id": 377320, "author_profile": "https://Stackoverflow.com/users/377320", "pm_score": 3, "selected": false, "text": "NoClassDefFoundError ClassNotFoundException com.example.Foo com.example.Foo" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
106,234
<p>lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.</p> <p>What are some of the most common and useful ways of using lsof, and which command-line switches are used for that? </p>
[ { "answer_id": 106249, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "lsof -i -n" }, { "answer_id": 106255, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 4, "selected": false, "text": "lsof -p pid\n" }, { "answer_id": 106259, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 5, "selected": false, "text": "lsof -i :port \n" }, { "answer_id": 319997, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "port lsof -iTCP -i :port\nlsof -i :22\n @host lsof -i@192.168.1.5\n @host:port grep LISTEN lsof -i| grep LISTEN\n -u lsof -u daniel\n -c lsof -c syslog-ng\n -p lsof -p 10075\n -t PID lsof -t -c Mail\n -t -c HUP kill -HUP $(lsof -t -c sshd)\n -t -u kill -9 $(lsof -t -u daniel)\n" }, { "answer_id": 1084508, "author": "mas", "author_id": 19007, "author_profile": "https://Stackoverflow.com/users/19007", "pm_score": 3, "selected": false, "text": "lsof +f -- /mountpoint\n" }, { "answer_id": 11494954, "author": "siesta", "author_id": 1366793, "author_profile": "https://Stackoverflow.com/users/1366793", "pm_score": 4, "selected": false, "text": "lsof +D /some/directory\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
106,237
<p>I have an application where a Hilbert R-Tree <a href="http://en.wikipedia.org/wiki/Hilbert_R-tree" rel="noreferrer">(wikipedia)</a> <a href="http://citeseer.comp.nus.edu.sg/84580.html" rel="noreferrer">(citeseer)</a> would seem to be an appropriate data structure. Specifically, it requires reasonably fast spatial queries over a data set that will experience a lot of updates.</p> <p>However, as far as I can see, none of the descriptions of the algorithms for this data structure even <em>mention</em> how to actually calculate the requisite <strong>Hilbert Value</strong>; which is the distance along a <a href="http://en.wikipedia.org/wiki/Hilbert_curve" rel="noreferrer">Hilbert Curve</a> to the point.</p> <p>So any suggestions for how to go about calculating this?</p>
[ { "answer_id": 313964, "author": "michael", "author_id": 40246, "author_profile": "https://Stackoverflow.com/users/40246", "pm_score": 3, "selected": false, "text": "/**\n * Find the Hilbert order (=vertex index) for the given grid cell \n * coordinates.\n * @param x cell column (from 0)\n * @param y cell row (from 0)\n * @param r resolution of Hilbert curve (grid will have Math.pow(2,r) \n * rows and cols)\n * @return Hilbert order \n */\npublic static int encode(int x, int y, int r) {\n\n int mask = (1 << r) - 1;\n int hodd = 0;\n int heven = x ^ y;\n int notx = ~x & mask;\n int noty = ~y & mask;\n int temp = notx ^ y;\n\n int v0 = 0, v1 = 0;\n for (int k = 1; k < r; k++) {\n v1 = ((v1 & heven) | ((v0 ^ noty) & temp)) >> 1;\n v0 = ((v0 & (v1 ^ notx)) | (~v0 & (v1 ^ noty))) >> 1;\n }\n hodd = (~v0 & (v1 ^ x)) | (v0 & (v1 ^ noty));\n\n return interleaveBits(hodd, heven);\n}\n\n/**\n * Interleave the bits from two input integer values\n * @param odd integer holding bit values for odd bit positions\n * @param even integer holding bit values for even bit positions\n * @return the integer that results from interleaving the input bits\n *\n * @todo: I'm sure there's a more elegant way of doing this !\n */\nprivate static int interleaveBits(int odd, int even) {\n int val = 0;\n // Replaced this line with the improved code provided by Tuska\n // int n = Math.max(Integer.highestOneBit(odd), Integer.highestOneBit(even));\n int max = Math.max(odd, even);\n int n = 0;\n while (max > 0) {\n n++;\n max >>= 1;\n }\n\n for (int i = 0; i < n; i++) {\n int bitMask = 1 << i;\n int a = (even & bitMask) > 0 ? (1 << (2*i)) : 0;\n int b = (odd & bitMask) > 0 ? (1 << (2*i+1)) : 0;\n val += a + b;\n }\n\n return val;\n}\n" }, { "answer_id": 1567226, "author": "user189964", "author_id": 189964, "author_profile": "https://Stackoverflow.com/users/189964", "pm_score": 2, "selected": false, "text": "public static long spreadBits32(int y) {\n long[] B = new long[] {\n 0x5555555555555555L, \n 0x3333333333333333L,\n 0x0f0f0f0f0f0f0f0fL,\n 0x00ff00ff00ff00ffL,\n 0x0000ffff0000ffffL,\n 0x00000000ffffffffL\n };\n\n int[] S = new int[] { 1, 2, 4, 8, 16, 32 };\n long x = y;\n\n x = (x | (x << S[5])) & B[5];\n x = (x | (x << S[4])) & B[4];\n x = (x | (x << S[3])) & B[3];\n x = (x | (x << S[2])) & B[2];\n x = (x | (x << S[1])) & B[1];\n x = (x | (x << S[0])) & B[0];\n return x;\n}\n\npublic static long interleave64(int x, int y) {\n return spreadBits32(x) | (spreadBits32(y) << 1);\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
106,251
<p>In my model I have:</p> <pre><code>validate :my_custom_validation def my_custom_validation errors.add_to_base("error message") if condition.exists? end </code></pre> <p>I would like to add some parameters to mycustomer vaildation like so:</p> <pre><code>validate :my_custom_validation, :parameter1 =&gt; x, :parameter2 =&gt; y </code></pre> <p>How do I write the mycustomvalidation function to account for parameters? </p>
[ { "answer_id": 106267, "author": "Bill Turner", "author_id": 17773, "author_profile": "https://Stackoverflow.com/users/17773", "pm_score": 1, "selected": false, "text": "def validate\n errors.add('That particular field', 'can not be the value you presented') if !self.field_to_check.blank? && self.field_to_check == 'I AM COOL'\nend\n" }, { "answer_id": 106294, "author": "paradoja", "author_id": 18396, "author_profile": "https://Stackoverflow.com/users/18396", "pm_score": 4, "selected": true, "text": ":my_custom_validation, parameter1: x, parameter2: y\n { parameter1: x, parameter2: y}\n def my_custom_validation(*attr)\n options = attr.pop if attr.last.is_a? Hash\n # do something with options\n errors.add_to_base(\"error message\") if condition.exists?\n\nend\n" }, { "answer_id": 72746111, "author": "Matt M", "author_id": 4848156, "author_profile": "https://Stackoverflow.com/users/4848156", "pm_score": 0, "selected": false, "text": "validate -> { my_custom_validation(parameter1: x, parameter2: y) }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396/" ]
106,275
<p>If I have a table field named 'description', what would be the SQL (using MS SQL) to get a list of records of all distinct words used in this field.</p> <p>For example:</p> <p>If the table contains the following for the 'description' field:</p> <pre><code>Record1 "The dog jumped over the fence." Record2 "The giant tripped on the fence." ... </code></pre> <p>The SQL record output would be:</p> <pre><code>"The","giant","dog","jumped","tripped","on","over","fence" </code></pre>
[ { "answer_id": 106282, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "CREATE TABLE test\n(\n id int identity(1, 1) not null,\n description varchar(50) not null\n)\n\nINSERT INTO test VALUES('The dog jumped over the fence')\nINSERT INTO test VALUES('The giant tripped on the fence')\n\nCREATE FUNCTION dbo.Split\n(\n @RowData nvarchar(2000),\n @SplitOn nvarchar(5)\n) \nRETURNS @RtnValue table \n(\n Id int identity(1,1),\n Data nvarchar(100)\n) \nAS \nBEGIN \n Declare @Cnt int\n Set @Cnt = 1\n\n While (Charindex(@SplitOn,@RowData)>0)\n Begin\n Insert Into @RtnValue (data)\n Select \n Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))\n\n Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))\n Set @Cnt = @Cnt + 1\n End\n\n Insert Into @RtnValue (data)\n Select Data = ltrim(rtrim(@RowData))\n\n Return\nEND\n\nCREATE FUNCTION dbo.SplitAll(@SplitOn nvarchar(5))\nRETURNS @RtnValue table\n(\n Id int identity(1,1),\n Data nvarchar(100)\n)\nAS\nBEGIN\nDECLARE My_Cursor CURSOR FOR SELECT Description FROM dbo.test\nDECLARE @description varchar(50)\n\nOPEN My_Cursor\nFETCH NEXT FROM My_Cursor INTO @description\nWHILE @@FETCH_STATUS = 0\nBEGIN\n INSERT INTO @RtnValue\n SELECT Data FROM dbo.Split(@description, @SplitOn)\n FETCH NEXT FROM My_Cursor INTO @description\nEND\nCLOSE My_Cursor\nDEALLOCATE My_Cursor\n\nRETURN\n\nEND\n\nSELECT DISTINCT Data FROM dbo.SplitAll(N' ')\n" }, { "answer_id": 746546, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic partial class UserDefinedFunctions\n{\n private class SplitStrings : IEnumerable\n {\n private List<string> splits;\n\n public SplitStrings(string toSplit, string splitOn)\n {\n splits = new List<string>();\n\n // nothing, return empty list\n if (string.IsNullOrEmpty(toSplit))\n {\n return;\n }\n\n // return one word\n if (string.IsNullOrEmpty(splitOn))\n {\n splits.Add(toSplit);\n\n return;\n }\n\n splits.AddRange(\n toSplit.Split(new string[] { splitOn }, StringSplitOptions.RemoveEmptyEntries)\n );\n }\n\n #region IEnumerable Members\n\n public IEnumerator GetEnumerator()\n {\n return splits.GetEnumerator();\n }\n\n #endregion\n }\n\n [Microsoft.SqlServer.Server.SqlFunction(FillRowMethodName = \"readRow\", TableDefinition = \"word nvarchar(255)\")]\n public static IEnumerable fnc_clr_split_string(string toSplit, string splitOn)\n {\n return new SplitStrings(toSplit, splitOn);\n }\n\n public static void readRow(object inWord, out SqlString word)\n {\n string w = (string)inWord;\n\n if (string.IsNullOrEmpty(w))\n {\n word = string.Empty;\n return;\n }\n\n if (w.Length > 255)\n {\n w = w.Substring(0, 254);\n }\n\n word = w;\n }\n};\n" }, { "answer_id": 15111948, "author": "user2115248", "author_id": 2115248, "author_profile": "https://Stackoverflow.com/users/2115248", "pm_score": 2, "selected": false, "text": "declare @tmp table(descr varchar(400))\n\ninsert into @tmp\nselect 'The dog jumped over the fence.'\nunion select 'The giant tripped on the fence.'\n\n/* the actual doing starts here */\nupdate @tmp\nset descr = replace(descr, '.', '') --get rid of dots in the ends of sentences.\n\ndeclare @xml xml\nset @xml = '<c>' + replace(\n (select ' ' + descr\n from @tmp\n for xml path('')\n), ' ', '</c><c>') + '</c>'\n\n;with \nallWords as (\n select section.Cols.value('.', 'varchar(250)') words\n from @xml.nodes('/c') section(Cols)\n )\nselect words\nfrom allWords\nwhere ltrim(rtrim(words)) <> ''\ngroup by words\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
106,298
<p>You may think that this is a coincidence that the topic of my question is similar to the name of the forum but I actually got here by googling the term "stack overflow".</p> <p>I use the OPNET network simulator in which I program using C. I think I am having a problem with big array sizes. It seems that I am hitting some sort of memory allocation limitation. It may have to do with OPNET, Windows, my laptop memory or most likely C language. The problem is caused when I try to use nested arrays with a total number of elements coming to several thousand integers. I think I am exceeding an overall memory allocation limit and I am wondering if there is a way to increase this cap. Here's the exact problem description:</p> <p>I basically have a routing table. Let's call it routing_tbl[n], meaning I am supporting 30 nodes (routers). Now, for each node in this table, I keep info. about many (hundreds) available paths, in an array called paths[p]. Again, for each path in this array, I keep the list of nodes that belong to it in an array called hops[h]. So, I am using at least nph integers worth of memory but this table contains other information as well. In the same function, I am also using another nested array that consumes almost 40,000 integers as well. As soon as I run my simulation, it quits complaining about stack overflow. It works when I reduce the total size of the routing table. What do you think causes the problem and how can it be solved? Much appreciated Ali</p>
[ { "answer_id": 106306, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 3, "selected": false, "text": "int recurse(int number) {\n\n return (recurse(number));\n}\n void hugeStack (void) {\n\n unsigned long long reallyBig[100000000][1000000000];\n\n ...\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
106,310
<p>We have a web application that was implemented using GWT. What it presents is fetched from a Jboss/Seam server using the remoting mechanism, and this works fine. However, the application is now extended to support sessions and users. The Seam GWT service doesn't seem to provide a way to let me log in such that Seam can return restricted data back to the GWT application, and so it looks to me that I will have to wrap the GWT application in facelets.</p> <p>It is not obvious to me that a login using the Seam session mechanism will help me get correct data into the GWT application however, so my question is whether I will be lucky and it will just work, or if I need to do some client side magic, server side magic or if my perception of missing login functionality in the Seam GWT service actually is wrong.</p> <p>Bonus points to anyone that can provide me with a complete example showing something similar.</p>
[ { "answer_id": 120356, "author": "larsivi", "author_id": 14047, "author_profile": "https://Stackoverflow.com/users/14047", "pm_score": 3, "selected": true, "text": "Identity.instance().getUsername(); @Restrict" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14047/" ]
106,323
<p>Anyone have a good set of sqlplus configuration directives to help transform a given sql query into nicely tab separated output for pulling into a spreadsheet or further processing?</p>
[ { "answer_id": 106398, "author": "Eddie Awad", "author_id": 17273, "author_profile": "https://Stackoverflow.com/users/17273", "pm_score": -1, "selected": true, "text": "select chr(9) from dual;\n" }, { "answer_id": 7066859, "author": "user158017", "author_id": 158017, "author_profile": "https://Stackoverflow.com/users/158017", "pm_score": 3, "selected": false, "text": "set colsep set colsep Chr(9) set colsep ' ' col TAB# new_value TAB NOPRINT\nselect chr(9) TAB# from dual;\nset colsep \"&TAB\"\n\nselect * from table;\n" }, { "answer_id": 27654468, "author": "Marvin W", "author_id": 2341528, "author_profile": "https://Stackoverflow.com/users/2341528", "pm_score": 1, "selected": false, "text": "SELECT column1 || CHR(9) || column2 || CHR(9) || column3 ... ...\nFROM table\n" }, { "answer_id": 57429359, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "set serveroutput on\nSET NEWPAGE NONE\nset feedback off\nset echo off\nset feedback off\nset heading off\nset colsep \nset pagesize 0 \nSET UNDERLINE OFF\nset pagesize 50000\nset linesize 32767\nconnect use/password\n set colsep \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19387/" ]
106,324
<p>With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.</p> <p>Any place where we still have to use delegates and lambda expressions won't work?</p>
[ { "answer_id": 106348, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": false, "text": " delegate(int i) { Console.WriteLine(i.ToString()) }\n f => Console.WriteLine(f.ToString())\n" }, { "answer_id": 106374, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 2, "selected": false, "text": "s.Find(a =>\n{\n if (a.StartsWith(\"H\"))\n return a.Equals(\"HI\");\n else\n return !a.Equals(\"FOO\");\n});\n" }, { "answer_id": 106480, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 5, "selected": false, "text": "public static void Invoke(Delegate d)\n{\n d.DynamicInvoke();\n}\n\nstatic void Main(string[] args)\n{\n // fails\n Invoke(() => Console.WriteLine(\"Test\"));\n\n // works\n Invoke(new Action(() => Console.WriteLine(\"Test\")));\n\n Console.ReadKey();\n}\n" }, { "answer_id": 144638, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "delegate delegate" }, { "answer_id": 149319, "author": "Dandikas", "author_id": 23436, "author_profile": "https://Stackoverflow.com/users/23436", "pm_score": 3, "selected": false, "text": "List<string> names = GetNames();\nnames.ForEach(Console.WriteLine);\n" }, { "answer_id": 24552532, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 3, "selected": false, "text": "delegate Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS\n Action<int> a = => { }; //omitted parameter, doesnt compile.\n button.onClicked += delegate { Console.WriteLine(\"clicked\"); };\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306/" ]
106,329
<p>I've recently inherited C# console application that is in need of some pruning and clean up. Long story short, the app consists of a single class containing over 110,000 lines of code. Yup, over 110,000 lines in a single class. And, of course, the app is core to our business, running 'round the clock updating data used on a dynamic website. Although I'm told my predecessor was "a really good programmer", it obvious he was not at all into OOP (or version control).</p> <p>Anyway... while familiarizing myself with the code I've found plenty of methods that are declared, but never referenced. It looks as if copy/paste was used to version the code, for example say I have a method called getSomethingImportant(), chances are there is another method called getSomethingImortant_July2007() (the pattern is functionName_[datestamp] in most cases). It looks like when the programmer was asked to make a change to getSomethingImportant() he would copy/paste then rename to getSomethingImortant_Date, make changes to getSomethingImortant_Date, then change any method calls in the code to the new method name, leaving the old method in the code but never referenced.</p> <p>I'd like to write a simple console app that crawls through the one huge class and returns a list of all methods with the number of times each method was referenced. By my estimates there are well over 1000 methods, so doing this by hand would take a while.</p> <p>Are there classes within the .NET framework that I can use to examine this code? Or any other usefull tools that may help identify methods that are declared but never referenced?</p> <p>(Side question: Has anyone else ever seen a C# app like this, one reeeealy big class? It's more or less one huge procedural process, I know this is the first I've seen, at least of this size.)</p>
[ { "answer_id": 106532, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": -1, "selected": false, "text": " .string \"w+\"\n .text\n .type create_secure_tmpfile, @function\ncreate_secure_tmpfile:\n pushl %ebp\n movl %esp, %ebp\n subl $24, %esp\n movl $-1, -8(%ebp)\n subl $4, %esp\n subl $12, %esp\n pushl 24(%ebp)\n call create_secure_tmpfile\n addl $16, %esp\n movl 20(%ebp), %edx\n movl %eax, (%edx)\n" }, { "answer_id": 238311, "author": "Patrick from NDepend team", "author_id": 27194, "author_profile": "https://Stackoverflow.com/users/27194", "pm_score": 3, "selected": false, "text": "from m in Application.Methods\nselect new { m, m.MethodsCalled, m.MethodsCallingMe }\n from m in Methods \nlet depth0 = m.DepthOfIsUsing(\"NUnit.Framework.Constraints.ConstraintExpression.Property(String)\")\nwhere depth0 >= 0 orderby depth0\nselect new { m, depth0 }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19389/" ]
106,336
<p>I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds? </p> <p>FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.</p>
[ { "answer_id": 106350, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 2, "selected": false, "text": ".getClass() Object map()" }, { "answer_id": 106351, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 8, "selected": true, "text": "ArrayList list = ...;\n// List<object> list = ...;\nforeach (object o in list) {\n if (o is int) {\n HandleInt((int)o);\n }\n else if (o is string) {\n HandleString((string)o);\n }\n ...\n}\n ArrayList<Object> list = ...;\nfor (Object o : list) {\n if (o instanceof Integer)) {\n handleInt((Integer o).intValue());\n }\n else if (o instanceof String)) {\n handleString((String)o);\n }\n ...\n}\n" }, { "answer_id": 106360, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 6, "selected": false, "text": "for (Object object : list) {\n System.out.println(object.getClass().getName());\n}\n" }, { "answer_id": 106381, "author": "faran", "author_id": 19350, "author_profile": "https://Stackoverflow.com/users/19350", "pm_score": 6, "selected": false, "text": "getClass() for (Object obj : list) {\n if (obj instanceof String) {\n ...\n }\n}\n for (Object obj : list) {\n if (obj.getClass().equals(String.class)) {\n ...\n }\n}\n C A C c = new C();\nassert c instanceof A;\n C c = new C();\nassert !c.getClass().equals(A.class)\n" }, { "answer_id": 109840, "author": "Heath Borders", "author_id": 9636, "author_profile": "https://Stackoverflow.com/users/9636", "pm_score": 4, "selected": false, "text": "Object o = ...\nif (o.getClass().equals(Foo.class)) {\n ...\n}\n Object o = ...\nif (Foo.class.isAssignableFrom(o)) {\n ...\n}\n" }, { "answer_id": 359623, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "for (Object o:list) {\n Double.parseDouble(o.toString);\n}\n" }, { "answer_id": 7755802, "author": "Reid Mac", "author_id": 888059, "author_profile": "https://Stackoverflow.com/users/888059", "pm_score": 3, "selected": false, "text": "ArrayList<Object> listOfObjects = new ArrayList<Object>();\nfor(Object obj: listOfObjects){\n if(obj instanceof String){\n }else if(obj instanceof Integer){\n }etc...\n}\n" }, { "answer_id": 14897094, "author": "potter", "author_id": 2075930, "author_profile": "https://Stackoverflow.com/users/2075930", "pm_score": 3, "selected": false, "text": "import java.util.ArrayList;\n\n/**\n * @author potter\n *\n */\npublic class storeAny {\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n\n ArrayList<Object> anyTy=new ArrayList<Object>();\n anyTy.add(new Integer(1));\n anyTy.add(new String(\"Jesus\"));\n anyTy.add(new Double(12.88));\n anyTy.add(new Double(12.89));\n anyTy.add(new Double(12.84));\n anyTy.add(new Double(12.82));\n\n for (Object o : anyTy) {\n if(o instanceof String){\n System.out.println(o.toString());\n } else if(o instanceof Integer) {\n System.out.println(o.toString()); \n } else if(o instanceof Double) {\n System.out.println(o.toString());\n }\n }\n }\n}\n" }, { "answer_id": 28350991, "author": "Sufiyan Ghori", "author_id": 1149423, "author_profile": "https://Stackoverflow.com/users/1149423", "pm_score": 2, "selected": false, "text": "object.getClass().getName() object.getClass().getSimpleName() Object[] intArray = { 1 }; \n\nfor (Object object : intArray) { \n System.out.println(object.getClass().getName());\n System.out.println(object.getClass().getSimpleName());\n}\n java.lang.Integer\nInteger\n" }, { "answer_id": 30150716, "author": "Andrew", "author_id": 2079831, "author_profile": "https://Stackoverflow.com/users/2079831", "pm_score": 2, "selected": false, "text": "\n mixedArrayList.forEach((o) -> {\n String type = o.getClass().getSimpleName();\n switch (type) {\n case \"String\":\n // treat as a String\n break;\n case \"Integer\":\n // treat as an int\n break;\n case \"Double\":\n // treat as a double\n break;\n ...\n default:\n // whatever\n }\n });\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13491/" ]
106,378
<p>I'm trying to figure out a way to make user controls run in their own UI threads. Is this possible? I'm trying to prevent a module-based application from crashing due to a single module.</p> <p>Any thoughts?</p>
[ { "answer_id": 106467, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public void Button1_Click(object sender, EventArgs args)\n{\n while(true) {}\n}\n" }, { "answer_id": 107000, "author": "asponge", "author_id": 19449, "author_profile": "https://Stackoverflow.com/users/19449", "pm_score": 1, "selected": false, "text": "DateTime startTime = DateTime.Now;\nwhile(DateTime.Now.Subtract(startTime).TotalSeconds < 30)\n{\n //do something\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
106,383
<p>Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.</p> <p>e.g.</p> <pre><code>public DerivedClass : BaseClass {} </code></pre> <p>Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?</p>
[ { "answer_id": 106407, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "class BaseClass\n{\n public void A()\n {\n Console.WriteLine(\"BaseClass.A\");\n }\n\n public void B()\n {\n Console.WriteLine(\"BaseClass.B\");\n }\n}\n\nclass DerivedClass : BaseClass\n{\n new public void A()\n {\n throw new NotSupportedException();\n }\n\n new public void B()\n {\n throw new NotSupportedException();\n }\n\n public void C()\n {\n base.A();\n base.B();\n }\n}\n DerivedClass d = new DerivedClass();\n d.A();\n" }, { "answer_id": 106469, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "interface I\n{\n void C();\n}\n\nclass BaseClass\n{\n public void A() { MessageBox.Show(\"A\"); }\n public void B() { MessageBox.Show(\"B\"); }\n}\n\nclass Derived : I\n{\n public void C()\n {\n b.A();\n b.B();\n }\n\n private BaseClass b;\n}\n" }, { "answer_id": 107215, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "class Plane\n{\n public Fly() { .. }\n public string GetPilot() {...}\n}\n" }, { "answer_id": 3156791, "author": "nono", "author_id": 380968, "author_profile": "https://Stackoverflow.com/users/380968", "pm_score": 5, "selected": false, "text": "List<object> Add(object _ob) // the only way to hide\n[Obsolete(\"This is not supported in this class.\", true)]\npublic new void Add(object _ob)\n{\n throw NotImplementedException(\"Don't use!!\");\n}\n" }, { "answer_id": 49006898, "author": "James Wilkins", "author_id": 1236397, "author_profile": "https://Stackoverflow.com/users/1236397", "pm_score": 0, "selected": false, "text": "[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n new => throw new NotSupportedException(); IList<T> List<T> public class GoodForNothing: IDisposable\n{\n void IDisposable.Dispose() { ... }\n}\n var obj = new GoodForNothing() Dispose() obj obj IDisposable public class MyList<T> : IList<T>\n{\n List<T> _Items = new List<T>();\n public T this[int index] => _Items[index];\n public int Count => _Items.Count;\n public void Add(T item) => _Items.Add(item);\n [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n void ICollection<T>.Clear() => throw new InvalidOperationException(\"No you may not!\"); // (hidden)\n /*...etc...*/\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16866/" ]
106,387
<p>I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct binary?</p> <p>This will be for Ubuntu machines.</p>
[ { "answer_id": 106399, "author": "shoover", "author_id": 18356, "author_profile": "https://Stackoverflow.com/users/18356", "pm_score": 7, "selected": true, "text": "uname -a\n uname -m\n" }, { "answer_id": 106411, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 2, "selected": false, "text": "if $(uname -a | grep 'x86_64'); then\n echo \"I'm 64-bit\"\nelse\n echo \"I'm 32-bit\"\nfi\n" }, { "answer_id": 106416, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 6, "selected": false, "text": "MACHINE_TYPE=`uname -m`\nif [ ${MACHINE_TYPE} == 'x86_64' ]; then\n # 64-bit stuff here\nelse\n # 32-bit stuff here\nfi\n" }, { "answer_id": 106440, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 3, "selected": false, "text": "slot8(msd):/opt # uname -a\nLinux slot8a 2.6.21_mvlcge500-electra #1 SMP PREEMPT Wed Jun 18 16:29:33 \\\nEDT 2008 ppc64 GNU/Linux\n" }, { "answer_id": 7308155, "author": "Victor Zamanian", "author_id": 243089, "author_profile": "https://Stackoverflow.com/users/243089", "pm_score": 6, "selected": false, "text": "getconf LONG_BIT if [ `getconf LONG_BIT` = \"64\" ]\nthen\n echo \"I'm 64-bit\"\nelse\n echo \"I'm 32-bit\"\nfi\n" }, { "answer_id": 7813672, "author": "inukaze", "author_id": 983309, "author_profile": "https://Stackoverflow.com/users/983309", "pm_score": 3, "selected": false, "text": "archs=`uname -m`\ncase \"$archs\" in\n i?86) archs=i386 ;;\n x86_64) archs=\"x86_64 i386\" ;;\n ppc64) archs=\"ppc64 ppc\" ;;\nesac\n\nfor arch in $archs; do\n test -x ./ioquake3.$arch || continue\n exec ./ioquake3.$arch \"$@\"\ndone\n # First Obtain \"kernel\" name\nKERNEL=$(uname -s)\n\nif [ $KERNEL = \"Darwin\" ]; then\n KERNEL=mac\nelif [ $Nucleo = \"Linux\" ]; then\n KERNEL=linux\nelif [ $Nucleo = \"FreeBSD\" ]; then\n KERNEL=linux\nelse\n echo \"Unsupported OS\"\nfi\n\n# Second get the right Arquitecture\nARCH=$(uname -m)\n\nif [ $ARCH = \"i386\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"i486\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"i586\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$Nucleo/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"i686\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"x86_64\" ]; then\n export WINESERVER=\"$PWD/wine/$KERNEL/x86_64/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86_64/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"64 Bits\"\n else\n echo \"Unsoportted Architecture\"\nfi\n # Get the Kernel Name\nKernel=$(uname -s)\ncase \"$Kernel\" in\n Linux) Kernel=\"linux\" ;;\n Darwin) Kernel=\"mac\" ;;\n FreeBSD) Kernel=\"freebsd\" ;;\n* ) echo \"Your Operating System -> ITS NOT SUPPORTED\" ;;\nesac\n\necho\necho \"Operating System Kernel : $Kernel\"\necho\n# Get the machine Architecture\nArchitecture=$(uname -m)\ncase \"$Architecture\" in\n x86) Architecture=\"x86\" ;;\n ia64) Architecture=\"ia64\" ;;\n i?86) Architecture=\"x86\" ;;\n amd64) Architecture=\"amd64\" ;;\n x86_64) Architecture=\"x86_64\" ;;\n sparc64) Architecture=\"sparc64\" ;;\n* ) echo \"Your Architecture '$Architecture' -> ITS NOT SUPPORTED.\" ;;\nesac\n\necho\necho \"Operating System Architecture : $Architecture\"\necho\n" }, { "answer_id": 8475731, "author": "lolesque", "author_id": 787216, "author_profile": "https://Stackoverflow.com/users/787216", "pm_score": 4, "selected": false, "text": "chroot getconf LONG_BIT file /bin/cp" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
106,400
<p>I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary?</p> <p>Thanks!</p>
[ { "answer_id": 106424, "author": "Mariano", "author_id": 2542, "author_profile": "https://Stackoverflow.com/users/2542", "pm_score": 2, "selected": false, "text": "select * from users order by max(rank) desc limit 0, 49 \nunion \nselect * from users where user = x\n" }, { "answer_id": 106638, "author": "igelkott", "author_id": 2052165, "author_profile": "https://Stackoverflow.com/users/2052165", "pm_score": 1, "selected": false, "text": "select user from users where id = \"fred\"; \nselect user from users where id != \"fred\" order by rank limit 49;\n" }, { "answer_id": 106658, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "declare @topUsers table(\n userId int primary key,\n username varchar(25)\n)\ninsert into @topUsers\nselect top 50 \n userId, \n userName\nfrom Users\norder by rank desc\n\ninsert into @topUsers\nselect\n userID,\n userName\nfrom Users\nwhere userID = 1234 --userID of special user\n\nselect * from @topUsers\n" }, { "answer_id": 106735, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "select distinct <columnlist>\nfrom (select * from users order by max(rank) desc limit 0, 49 \n union \n select * from users where user = x)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
106,401
<p>The built-in <code>PHP</code> extension for <code>SOAP</code> doesn't validate everything in the incoming <code>SOAP</code> request against the <code>XML Schema</code> in the <code>WSDL</code>. It does check for the existence of basic entities, but when you have something complicated like <code>simpleType</code> restrictions the extension pretty much ignores their existence.</p> <p>What is the best way to validate the <code>SOAP</code> request against <code>XML Schema</code> contained in the <code>WSDL</code>?</p>
[ { "answer_id": 8532467, "author": "CodeKid", "author_id": 1101681, "author_profile": "https://Stackoverflow.com/users/1101681", "pm_score": 3, "selected": true, "text": "<xsd:element name=\"SomeParameter\" type=\"xsd:boolean\" />\n <get:SomeParameter>dfgdfg</get:SomeParameter>\n nusoap_xmlschema: processing typed element SomeParameter of type http://www.w3.org/2001/XMLSchema:boolean\n" }, { "answer_id": 70744983, "author": "celsowm", "author_id": 284932, "author_profile": "https://Stackoverflow.com/users/284932", "pm_score": 2, "selected": false, "text": "function validate(string $xmlEnvelope, string $wsdl) : ?array{\n \n libxml_use_internal_errors(true);\n \n //extracting schema from WSDL\n $xml = new DOMDocument();\n $wsdl_string = file_get_contents($wsdl);\n\n //extracting namespaces from WSDL\n $outer = new SimpleXMLElement($wsdl_string);\n $wsdl_namespaces = $outer->getDocNamespaces();\n \n //extracting the schema tag inside WSDL\n $xml->loadXML($wsdl_string);\n $xpath = new DOMXPath($xml);\n $xpath->registerNamespace('xsd', 'http://www.w3.org/2001/XMLSchema');\n $schemaNode = $xpath->evaluate('//xsd:schema');\n\n $schemaXML = \"\";\n foreach ($schemaNode as $node) {\n \n //add namespaces from WSDL to schema\n foreach($wsdl_namespaces as $prefix => $ns){\n $node->setAttribute(\"xmlns:$prefix\", $ns);\n }\n $schemaXML .= simplexml_import_dom($node)\n ->asXML();\n }\n \n //capturing de XML envelope\n $xml = new DOMDocument();\n $xml->loadXML($xmlEnvelope);\n \n //extracting namespaces from soap Envelope\n $outer = new SimpleXMLElement($xmlEnvelope);\n $envelope_namespaces = $outer->getDocNamespaces();\n \n $xpath = new DOMXPath($xml);\n $xpath->registerNamespace('soapEnv', 'http://schemas.xmlsoap.org/soap/envelope/');\n $envelopeBody = $xpath->evaluate('//soapEnv:Body/*[1]');\n $envelopeBodyXML = \"\";\n foreach ($envelopeBody as $node) {\n \n //add namespaces from envelope to the body content\n foreach($envelope_namespaces as $prefix => $ns){\n $node->setAttribute(\"xmlns:$prefix\", $ns);\n }\n $envelopeBodyXML .= simplexml_import_dom($node)\n ->asXML();\n }\n \n $doc = new DOMDocument();\n $doc->loadXML($envelopeBodyXML); // load xml\n $is_valid_xml = $doc->schemaValidateSource($schemaXML); // path to xsd file\n\n return libxml_get_errors(); \n \n}\n function myFunction($param) {\n\n $xmlEnvelope = file_get_contents(\"php://input\");\n $errors = validate($xmlEnvelope, $wsdl);\n\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5726/" ]
106,405
<p>We maintain a RPM based software distribution at work so that we have a common set of software across all the platforms that we support. As a result we have to build a lot of third party software, and frequently find situations where we need to run autoconf/automake/libtoolize/etc to get it to build on Solaris or another platform. </p> <p>I've had very mixed results with this. It seems that these tools are fairly brittle and frequently the files only work with the version of autoconf/automake/etc that they were originally written for. </p> <p>Ideally I'd like to only have to support one version of the GNU autotools, but I get the impression that I'm really going to end up having to have a copy of every version lying around. </p> <p>Is this unusual, or do other people have the same problems? Is there a subset of the versions of autotools that will cover all cases?</p>
[ { "answer_id": 108745, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 3, "selected": false, "text": "configure; make; make install" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19235/" ]
106,412
<p>In general, I occasionally have a chain of nested macros with a few preprocessor conditional elements in their definitions. These can be painful to debug since it's hard to directly see the actual code being executed.</p> <p>A while ago I vaguely remember finding a compiler (gcc) flag to expand them, but I had trouble getting this to work in practice.</p>
[ { "answer_id": 107350, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "gcc -E foo.cpp\n CC -E foo.cpp\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3561/" ]
106,425
<p>How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.</p>
[ { "answer_id": 106438, "author": "Miguel Ventura", "author_id": 19401, "author_profile": "https://Stackoverflow.com/users/19401", "pm_score": 8, "selected": true, "text": "javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();\n" }, { "answer_id": 15943140, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 2, "selected": false, "text": "javascript:\nvar q = document.createElement('script');\nq.src = 'http://svnpenn.github.io/bm/yt.js';\ndocument.body.appendChild(q);\nvoid 0;\n" }, { "answer_id": 47242413, "author": "naviram", "author_id": 1265306, "author_profile": "https://Stackoverflow.com/users/1265306", "pm_score": -1, "selected": false, "text": "loadjs=function(){function e(e,n){var t,r,i,c=[],o=(e=e.push?e:[e]).length,f=o;for(t=function(e,t){t.length&&c.push(e),--f||n(c)};o--;)r=e[o],(i=s[r])?t(r,i):(u[r]=u[r]||[]).push(t)}function n(e,n){if(e){var t=u[e];if(s[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function t(e,n,r,i){var o,s,u=document,f=r.async,a=(r.numRetries||0)+1,h=r.before||c;i=i||0,/(^css!|\\.css$)/.test(e)?(o=!0,(s=u.createElement(\"link\")).rel=\"stylesheet\",s.href=e.replace(/^css!/,\"\")):((s=u.createElement(\"script\")).src=e,s.async=void 0===f||f),s.onload=s.onerror=s.onbeforeload=function(c){var u=c.type[0];if(o&&\"hideFocus\"in s)try{s.sheet.cssText.length||(u=\"e\")}catch(e){u=\"e\"}if(\"e\"==u&&(i+=1)<a)return t(e,n,r,i);n(e,u,c.defaultPrevented)},!1!==h(e,s)&&u.head.appendChild(s)}function r(e,n,r){var i,c,o=(e=e.push?e:[e]).length,s=o,u=[];for(i=function(e,t,r){if(\"e\"==t&&u.push(e),\"b\"==t){if(!r)return;u.push(e)}--o||n(u)},c=0;c<s;c++)t(e[c],i,r)}function i(e,t,i){var s,u;if(t&&t.trim&&(s=t),u=(s?i:t)||{},s){if(s in o)throw\"LoadJS\";o[s]=!0}r(e,function(e){e.length?(u.error||c)(e):(u.success||c)(),n(s,e)},u)}var c=function(){},o={},s={},u={};return i.ready=function(n,t){return e(n,function(e){e.length?(t.error||c)(e):(t.success||c)()}),i},i.done=function(e){n(e,[])},i.reset=function(){o={},s={},u={}},i.isDefined=function(e){return e in o},i}();\nloadjs('//path/external/js', {\n success: function () {\n console.log('something to run after the script was loaded');\n });\n" }, { "answer_id": 57921981, "author": "Tom", "author_id": 5480147, "author_profile": "https://Stackoverflow.com/users/5480147", "pm_score": 1, "selected": false, "text": "javascript:var r = new XMLHttpRequest();\n r.open(\"GET\", \"https://...my.js\", true);\n r.onloadend = function (oEvent) {\n new Function(r.responseText)();\n /* now you can use your code */\n };\n r.send();\n undefined\n" }, { "answer_id": 73669489, "author": "xbtsw", "author_id": 493978, "author_profile": "https://Stackoverflow.com/users/493978", "pm_score": 0, "selected": false, "text": "(() => {\n const main = () => {\n // write your code here\n alert($('body')[0].innerHTML)\n }\n const scriptEle = document.createElement('script')\n scriptEle.onload = main\n scriptEle.src = 'https://cdn.jsdelivr.net/npm/jquery@3.6.1/dist/jquery.min.js'\n document.body.appendChild(scriptEle)\n})();\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401774/" ]
106,437
<p>I have a stateless bean something like:</p> <pre><code>@Stateless public class MyStatelessBean implements MyStatelessLocal, MyStatelessRemote { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.SUPPORTED) public void processObjects(List&lt;Object&gt; objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.process(obj); } } @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); } } </code></pre> <p>The typically usage then is the client would call processObjects(...), which doesn't actually interact with the entity manager. It does what it needs to do and calls process(...) individually for each object to process. The duration of process(...) is relatively short, but processObjects(...) could take a very long time to run through everything. Therefore I don't want it to maintain an open transaction. I <em>do</em> need the individual process(...) operations to operate within their own transaction. This should be a new transaction for every call. Lastly I'd like to keep the option open for the client to call process(...) directly.</p> <p>I've tried a number of different transaction types: never, not supported, supported (on processObjects) and required, requires new (on process) but I get TransactionRequiredException every time merge() is called.</p> <p>I've been able to make it work by splitting up the methods into two different beans:</p> <pre><code>@Stateless @TransationAttribute(TransactionAttributeType.NOT_SUPPORTED) public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 { @EJB private MyStatelessBean2 myBean2; public void processObjects(List&lt;Object&gt; objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.myBean2.process(obj); } } } @Stateless public class MyStatelessBean2 implements MyStatelessLocal2, MyStatelessRemote2 { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); } } </code></pre> <p>but I'm still curious if it's possible to accomplish this in one class. It looks to me like the transaction manager only operates at the bean level, even when individual methods are given more specific annotations. So if I mark one method in a way to prevent the transaction from starting calling other methods within that same instance will also not create a transaction, no matter how they're marked?</p> <p>I'm using JBoss Application Server 4.2.1.GA, but non-specific answers are welcome / preferred.</p>
[ { "answer_id": 511912, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "@EJB // supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1\n@Stateless\n@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)\npublic class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {\n @EJB\n private MyStatelessLocal1 myBean2;\n\n public void processObjects(List<Object> objs) {\n // this method just processes the data; no need for a transaction\n for(Object obj : objs) {\n this.myBean2.process(obj);\n }\n }\n\n\n @TransationAttribute(TransactionAttributeType.REQUIRES_NEW)\n public void process(Object obj) {\n // do some work with obj that must be in the scope of a transaction\n\n this.mgr.merge(obj);\n // ...\n this.mgr.merge(obj);\n // ...\n this.mgr.flush();\n }\n}\n process() @TransactionAttribute" }, { "answer_id": 2660238, "author": "bluecarbon", "author_id": 149895, "author_profile": "https://Stackoverflow.com/users/149895", "pm_score": 2, "selected": false, "text": "// supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1\n@Stateless\n@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)\npublic class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {\n\n @Resource\n private SessionContext ctx;\n\n @EJB\n private MyStatelessLocal1 myBean2;\n\n public void processObjects(List<Object> objs) {\n // this method just processes the data; no need for a transaction\n for(Object obj : objs) {\n this.myBean2.process(obj);\n }\n }\n\n\n public void process(Object obj) {\n\n UserTransaction tx = ctx.getUserTransaction();\n\n tx.begin();\n\n // do some work with obj that must be in the scope of a transaction\n\n this.mgr.merge(obj);\n // ...\n this.mgr.merge(obj);\n // ...\n this.mgr.flush();\n\n tx.commit();\n }\n}\n" }, { "answer_id": 10109028, "author": "tizzo", "author_id": 1326940, "author_profile": "https://Stackoverflow.com/users/1326940", "pm_score": 1, "selected": false, "text": "@EJB SessionContext.getBusinessObject()" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458/" ]
106,446
<p><strong>Before you answer: Yes I have read the jtable tutorial over at Sun</strong>. No, it did not help me. Yes, I am a dolt. <strong>Please don't answer with a reference to that document</strong>. What I am specifically interested in is how to dynamically add rows and columns to my Jtable via the Netbeans IDE. I already have an object that contains a hashmap with my data. I can't figure out where or what object I should be passing that object to. Thanks for your time! </p> <p>I have a vector that contains a series (of length l) of objects (each one corresponding to a row). How do I get that vector object to display on the JTable?</p>
[ { "answer_id": 106462, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "JTable TableModel TableModel DefaultTableModel" }, { "answer_id": 106493, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "ArrayList<Row> Row HashMap<String, Object>" }, { "answer_id": 106661, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 1, "selected": false, "text": "DefaultTableModel HashMap Vector HashMap DefaultTableModel TableModel JTable import java.util.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class JTableExample extends JFrame\n{\n private void makeGUI()\n {\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n // HashMap with some data.\n HashMap<String, String> map = new HashMap<String, String>();\n map.put(\"key1\", \"value1\");\n map.put(\"key2\", \"value2\");\n\n // Create a DefaultTableModel, which will be used as the\n // model for the JTable.\n DefaultTableModel model = new DefaultTableModel();\n\n // Populate the model with data from HashMap.\n model.setColumnIdentifiers(new String[] {\"key\", \"value\"});\n\n for (String key : map.keySet())\n model.addRow(new Object[] {key, map.get(key)});\n\n // Make a JTable, using the DefaultTableModel we just made\n // as its model.\n JTable table = new JTable(model);\n\n this.getContentPane().add(table);\n this.setSize(200,200);\n this.setLocation(200,200);\n this.validate();\n this.setVisible(true);\n }\n\n public static void main(String[] args)\n {\n new JTableExample().makeGUI();\n }\n}\n Vector JTable import java.util.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class JTableExample extends JFrame\n{\n private void makeGUI()\n {\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n // Vector with data.\n Vector<String> v = new Vector<String>();\n v.add(\"first\");\n v.add(\"second\");\n\n // Create a DefaultTableModel, which will be used as the\n // model for the JTable.\n DefaultTableModel model = new DefaultTableModel();\n\n // Add a column of data from Vector into the model.\n model.addColumn(\"data\", v);\n\n // Make a JTable, using the DefaultTableModel we just made\n // as its model.\n JTable table = new JTable(model);\n\n this.getContentPane().add(table);\n this.setSize(200,200);\n this.setLocation(200,200);\n this.validate();\n this.setVisible(true);\n }\n\n public static void main(String[] args)\n {\n new JTableExample().makeGUI();\n }\n}\n DefaultTableModel setDataVector" }, { "answer_id": 225302, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "import java.util.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class JTableExample extends JFrame\n{\n private void makeGUI()\n {\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n // HashMap with some data.\n HashMap<String, String> map = new HashMap<String, String>();\n map.put(\"key1\", \"value1\");\n map.put(\"key2\", \"value2\");\n\n // Create a DefaultTableModel, which will be used as the\n // model for the JTable.\n DefaultTableModel model = new DefaultTableModel();\n\n // Populate the model with data from HashMap.\n model.setColumnIdentifiers(new String[] {\"key\", \"value\"});\n\n for (String key : map.keySet())\n model.addRow(new Object[] {key, map.get(key)});\n\n // Make a JTable, using the DefaultTableModel we just made\n // as its model.\n JTable table = new JTable(model);\n\n this.getContentPane().add(new JScrollPane(table));\n this.setSize(200,200);\n this.setLocation(200,200);\n this.validate();\n this.setVisible(true);\n }\n\n public static void main(String[] args)\n {\n new JTableExample().makeGUI();\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19398/" ]
106,453
<p>I've been working on an embedded C/C++ project recently using the shell in Tornado 2 as a way of debugging what's going on in our kit. The only problem with this approach is that it's a complicated system and as a result, has a fair bit of output. Tornado 'helpfully' scrolls the window every time some new information arrives which means that if you spot an error, it disappears out of site too quickly to see. Each time you scroll up to look, the system adds more information, so the only way to view it is to disconnect the hardware.</p> <p>I'd love to know if anyone has a way of redirecting the output from Tornado?</p> <p>I was hoping there might be a way to log it all from a small python app so that I can apply filters to the incoming information. I've tried connecting into the Tornado process, but the window with the information isn't a standard CEditCtrl so extracting the text that way was a dead end.</p> <p>Any ideas anyone?</p> <p><strong>[Edit]</strong> I should have mentioned that we're only running Tornado 2.1.0 and upgrading to a more recent version is beyond my control.</p> <p><strong>[Edit2]</strong> The window in question in Tornado is an 'AfxFrameOrView42' according to WinID.</p>
[ { "answer_id": 106626, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "\n-> ?shConfig\n...\nRECORD = off\nRECORD_FILE = C:/test.txt\nRECORD_TYPE = output\n...\n\n-> ?shConfig RECORD_TYPE all\n-> ?shConfig RECORD_FILE myData.txt\n-> ?shConfig RECORD on\nStarted recording commands in 'myData.txt'.\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/106453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]