qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
145,312
<p>What is the maximum number of threads you can create in a C# application? And what happens when you reach this limit? Is an exception of some kind thrown?</p>
[ { "answer_id": 145412, "author": "mastermind", "author_id": 168864, "author_profile": "https://Stackoverflow.com/users/168864", "pm_score": 5, "selected": false, "text": " static void DummyCall()\n {\n Thread.Sleep(1000000000);\n }\n\n static void Main(string[] args)\n {\n int count = 0;\n var threadList = new List<Thread>();\n try\n {\n while (true)\n {\n Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);\n newThread.Start();\n threadList.Add(newThread);\n count++;\n }\n }\n catch (Exception ex)\n {\n }\n }\n static void DummyCall()\n {\n Thread.Sleep(1000000000);\n }\n\n static void Main(string[] args)\n {\n int count = 0;\n var threadList = new List<Thread>();\n try\n {\n while (true)\n {\n Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);\n threadList.Add(newThread);\n count++;\n }\n }\n catch (Exception ex)\n {\n }\n }\n" }, { "answer_id": 59001963, "author": "Yousha Aleayoub", "author_id": 1429432, "author_profile": "https://Stackoverflow.com/users/1429432", "pm_score": 0, "selected": false, "text": "private static void Main(string[] args)\n{\n int threadCount = 0;\n try\n {\n for (int i = 0; i < int.MaxValue; i ++)\n {\n new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();\n threadCount ++;\n }\n }\n catch\n {\n Console.WriteLine(threadCount);\n Console.ReadKey(true);\n }\n}\n" }, { "answer_id": 59499772, "author": "ivke", "author_id": 6533764, "author_profile": "https://Stackoverflow.com/users/6533764", "pm_score": 4, "selected": false, "text": "ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
145,321
<p>For some reason after I installed Boot Camp, my os x terminal started to point to the Boot Camp drive instead of my os x home directory by default! Once in the terminal I know how to switch back an forth and am able to do that, but I was wondering how to make my terminal default back to my os x home folder?</p> <p>I've checked my Home Directory under System Preferences->Accounts->Control-click on my account and it is pointing to the right place. I've also tried unmounting it with no luck.</p>
[ { "answer_id": 145339, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 4, "selected": false, "text": "cd <directory>\n\nin /Users/<yourUserName>/.profile\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
145,335
<p>I know how to lighten the colors for certain commands, however I'd like to lighten the standard ansi colors across all commands.</p>
[ { "answer_id": 145444, "author": "quackingduck", "author_id": 3624, "author_profile": "https://Stackoverflow.com/users/3624", "pm_score": 4, "selected": true, "text": "rxvt*background: #000000\nrxvt*foreground: #7f7f7f\nrxvt*color0: #000000\nrxvt*color1: #9e1828\nrxvt*color2: #aece92\nrxvt*color3: #968a38\nrxvt*color4: #414171\nrxvt*color5: #963c59\nrxvt*color6: #418179\nrxvt*color7: #bebebe\nrxvt*color8: #666666\nrxvt*color9: #cf6171\nrxvt*color10: #c5f779\nrxvt*color11: #fff796\nrxvt*color12: #4186be\nrxvt*color13: #cf9ebe\nrxvt*color14: #71bebe\nrxvt*color15: #ffffff\n ~/.Xdefaults" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3624/" ]
145,337
<ol> <li>What is the most efficient way to check if an array is <strong>a flat array of primitive values</strong> or if it is a <strong>multidimensional array</strong>?</li> <li>Is there any way to do this without actually looping through an array and running <code>is_array()</code> on each of its elements?</li> </ol>
[ { "answer_id": 145342, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "is_array()" }, { "answer_id": 145343, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function countdim($array)\n{\n if (is_array(reset($array))) \n $return = countdim(reset($array)) + 1;\n else\n $return = 1;\n \n return $return;\n}\n" }, { "answer_id": 145348, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "is_array($arr[0]);\n $ more multi.php\n<?php\n\n$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));\n$b = array(1 => 'a',2 => 'b');\n$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));\n\nfunction is_multi($a) {\n $rv = array_filter($a,'is_array');\n if(count($rv)>0) return true;\n return false;\n}\n\nfunction is_multi2($a) {\n foreach ($a as $v) {\n if (is_array($v)) return true;\n }\n return false;\n}\n\nfunction is_multi3($a) {\n $c = count($a);\n for ($i=0;$i<$c;$i++) {\n if (is_array($a[$i])) return true;\n }\n return false;\n}\n$iters = 500000;\n$time = microtime(true);\nfor ($i = 0; $i < $iters; $i++) {\n is_multi($a);\n is_multi($b);\n is_multi($c);\n}\n$end = microtime(true);\necho \"is_multi took \".($end-$time).\" seconds in $iters times\\n\";\n\n$time = microtime(true);\nfor ($i = 0; $i < $iters; $i++) {\n is_multi2($a);\n is_multi2($b);\n is_multi2($c);\n}\n$end = microtime(true);\necho \"is_multi2 took \".($end-$time).\" seconds in $iters times\\n\";\n$time = microtime(true);\nfor ($i = 0; $i < $iters; $i++) {\n is_multi3($a);\n is_multi3($b);\n is_multi3($c);\n}\n$end = microtime(true);\necho \"is_multi3 took \".($end-$time).\" seconds in $iters times\\n\";\n?>\n\n$ php multi.php\nis_multi took 7.53565130424 seconds in 500000 times\nis_multi2 took 4.56964588165 seconds in 500000 times\nis_multi3 took 9.01706600189 seconds in 500000 times\n $ more multi.php\n<?php\n\n$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));\n$b = array(1 => 'a',2 => 'b');\n\nfunction is_multi($a) {\n $rv = array_filter($a,'is_array');\n if(count($rv)>0) return true;\n return false;\n}\n\nvar_dump(is_multi($a));\nvar_dump(is_multi($b));\n?>\n\n$ php multi.php\nbool(true)\nbool(false)\n" }, { "answer_id": 150647, "author": "scronide", "author_id": 22844, "author_profile": "https://Stackoverflow.com/users/22844", "pm_score": 5, "selected": false, "text": "function is_multi($array) {\n return (count($array) != count($array, 1));\n}\n" }, { "answer_id": 994599, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "if (count($array) == count($array, COUNT_RECURSIVE)) \n{\n echo 'array is not multidimensional';\n}\nelse\n{\n echo 'array is multidimensional';\n}\n mode array(array())" }, { "answer_id": 6305810, "author": "RoboTamer", "author_id": 296559, "author_profile": "https://Stackoverflow.com/users/296559", "pm_score": 2, "selected": false, "text": "function isMultiArray($a){\n foreach($a as $v) if(is_array($v)) return TRUE;\n return FALSE;\n}\n $a = array(1 => 'a',2 => 'b',3 => array(1,2,3));\n$b = array(1 => 'a',2 => 'b');\n\necho isMultiArray($a) ? 'is multi':'is not multi';\necho '<br />';\necho isMultiArray($b) ? 'is multi':'is not multi';\n" }, { "answer_id": 16207297, "author": "Prashant", "author_id": 2301367, "author_profile": "https://Stackoverflow.com/users/2301367", "pm_score": 0, "selected": false, "text": "$array = array('yo'=>'dream', 'mydear'=> array('anotherYo'=>'dream'));\n$array1 = array('yo'=>'dream', 'mydear'=> 'not_array');\n\nfunction is_multi_dimensional($array){\n $flag = 0;\n while(list($k,$value)=each($array)){\n if(is_array($value))\n $flag = 1;\n }\n return $flag;\n}\necho is_multi_dimensional($array); // returns 1\necho is_multi_dimensional($array1); // returns 0\n" }, { "answer_id": 22581046, "author": "Pian0_M4n", "author_id": 2156913, "author_profile": "https://Stackoverflow.com/users/2156913", "pm_score": 3, "selected": false, "text": "if (count($myarray) !== count($myarray, COUNT_RECURSIVE)) return true;\nelse return false;\n COUNT_RECURSIVE" }, { "answer_id": 26416082, "author": "Alfonso Fernandez-Ocampo", "author_id": 903645, "author_profile": "https://Stackoverflow.com/users/903645", "pm_score": -1, "selected": false, "text": "static public function isMulti($array)\n{\n $result = array_unique(array_map(\"gettype\",$array));\n\n return count($result) == 1 && array_shift($result) == \"array\";\n}\n" }, { "answer_id": 36364362, "author": "Arshid KV", "author_id": 2513873, "author_profile": "https://Stackoverflow.com/users/2513873", "pm_score": -1, "selected": false, "text": "if (count($arrayList) != count($arrayList, COUNT_RECURSIVE)) \n{\n echo 'arrayList is multidimensional';\n\n}else{\n\n echo 'arrayList is no multidimensional';\n}\n" }, { "answer_id": 37146075, "author": "Andreas", "author_id": 6191314, "author_profile": "https://Stackoverflow.com/users/6191314", "pm_score": 4, "selected": false, "text": "function is_multidimensional(array $array) {\n return count($array) !== count($array, COUNT_RECURSIVE);\n}\n" }, { "answer_id": 43393402, "author": "Priyank", "author_id": 3046689, "author_profile": "https://Stackoverflow.com/users/3046689", "pm_score": 1, "selected": false, "text": "is_array(current($array));\n" }, { "answer_id": 48975528, "author": "hendra1", "author_id": 2636545, "author_profile": "https://Stackoverflow.com/users/2636545", "pm_score": 2, "selected": false, "text": "function is_multi_array( $arr ) {\nrsort( $arr );\nreturn isset( $arr[0] ) && is_array( $arr[0] );\n}\n//Usage\nvar_dump( is_multi_array( $some_array ) );\n" }, { "answer_id": 49510766, "author": "Darkcoder", "author_id": 7439186, "author_profile": "https://Stackoverflow.com/users/7439186", "pm_score": 0, "selected": false, "text": "array(\"data\"=> \"name\"); array(\"data\"=> array(\"name\"=>\"username\",\"fname\"=>\"fname\")); data function is_multi($a) {\n foreach ($a as $v) {\n if (is_array($v)) \n {\n return \"has array\";\n break;\n }\n break;\n }\n return 'only value';\n }\n" }, { "answer_id": 54403044, "author": "Mohd Abdul Mujib", "author_id": 807104, "author_profile": "https://Stackoverflow.com/users/807104", "pm_score": -1, "selected": false, "text": "$isMulti = !empty(array_filter($array, function($e) {\n return is_array($e);\n }));\n" }, { "answer_id": 59891437, "author": "Dorpo", "author_id": 12773519, "author_profile": "https://Stackoverflow.com/users/12773519", "pm_score": -1, "selected": false, "text": "$is_multi_array = array_reduce(array_keys($arr), function ($carry, $key) use ($arr) { return $carry && is_array($arr[$key]); }, true);\n" }, { "answer_id": 61155543, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public function is_multi(array $array):bool\n{\n return is_array($array[array_key_first($array)]);\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
145,354
<p>After searching online, the best solution I've found so far is to just make a symbolic link in either "/Library/logs/" or "~/Library/logs/" to get it to show up in the Console application.</p> <p>I'm wondering if it would be possible to add a new directory or log file to the "root" level directly under the "LOG FILES" section in the console.</p> <p>Here's a quick screenshot:</p> <p><img src="https://i.stack.imgur.com/0QsJz.png" alt="OS X Console"></p>
[ { "answer_id": 523000, "author": "Tao Zhyn", "author_id": 873, "author_profile": "https://Stackoverflow.com/users/873", "pm_score": 5, "selected": false, "text": "~/Library/Logs /opt/local/apache2/logs # cd ~/Library/Logs\n# ln -s /opt/local/apache2/logs/ apache2 \n" }, { "answer_id": 4964251, "author": "Tobias", "author_id": 545129, "author_profile": "https://Stackoverflow.com/users/545129", "pm_score": -1, "selected": false, "text": "sudo mkdir -p /usr/local/var/log/apache2\nsudo mv /private/var/log/apache2 /usr/local/var/log/apache2/apache2-old\nsudo ln -s /usr/local/var/log/apache2 /private/var/log/apache2\n sudo mkdir -p /usr/local/var/log/apache2\nsudo ln -s /private/var/log/apache2/apache2 /usr/local/var/log/apache2\nsudo mv /private/var/log/apache2 /usr/local/var/log/apache2/apache2-old\nsudo ln -s /usr/local/var/log/apache2 /private/var/log/apache2\n" }, { "answer_id": 33146932, "author": "2Steaks", "author_id": 3747342, "author_profile": "https://Stackoverflow.com/users/3747342", "pm_score": 1, "selected": false, "text": "cd /Library/Logs\nsudo mkdir log_files\nsudo ln -s /Users/USERNAME/Sites/website/logs/* log_files\n" }, { "answer_id": 38224434, "author": "user6556252", "author_id": 6556252, "author_profile": "https://Stackoverflow.com/users/6556252", "pm_score": 1, "selected": false, "text": "ln -s /opt/local/apache2/logs/error_log ~/Library/Logs/Apache2/error_log\n" }, { "answer_id": 42397332, "author": "Dierk", "author_id": 1603406, "author_profile": "https://Stackoverflow.com/users/1603406", "pm_score": 3, "selected": false, "text": "~/Library/Logs hln /usr/local/var/log /Users/dierk/Library/Logs/_usr_local_var_log brew install hardlink-osx hln [source] [destination]" }, { "answer_id": 47178140, "author": "Jacob Kjeldahl", "author_id": 5836028, "author_profile": "https://Stackoverflow.com/users/5836028", "pm_score": 0, "selected": false, "text": "ln /usr/local/var/logs/postgres.log ~/Library/logs\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
145,376
<p>Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?</p> <p>I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class.</p>
[ { "answer_id": 145428, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 4, "selected": true, "text": "gettype($FakeArray) == 'array' \nis_array($FakeArray)\n" }, { "answer_id": 145606, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 2, "selected": false, "text": "array_* array_merge array_shift" }, { "answer_id": 148509, "author": "rewbs", "author_id": 6095, "author_profile": "https://Stackoverflow.com/users/6095", "pm_score": 2, "selected": false, "text": "<?php\nfunction f(array $a) { /*...*/ }\n\n$ao = new ArrayObject();\nf($ao); //error\n?>\n Catchable fatal error: Argument 1 passed to f() must be an array, object given \n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
145,389
<p>As I am using for-loops on large multi-dim arrays, any saving on the for-loop mechanism itself is meaningful.</p> <p>Accordingly, I am looking for any tips on how to reduce this overhead.</p> <p>e.g. : counting down using uint instead of int and != 0 as stop instead of >0 allows the CPU to do less work (heard it once, not sure it is always true)</p>
[ { "answer_id": 145392, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "for row = 0 to 999\n for col = 0 to 999\n cell[row*1000+col] = row * 7 + col\n for row = 0 to 999\n x = row * 1000\n y = row * 7\n for col = 0 to 999\n cell[x+col] = y + col\n" }, { "answer_id": 145394, "author": "SteinNorheim", "author_id": 19220, "author_profile": "https://Stackoverflow.com/users/19220", "pm_score": 3, "selected": false, "text": "for (i=0; i<N; i++) {\n a[i]=...;\n}\n for (i=0; i<N; i+=4) {\n a[i]=...;\n a[i+1]=...;\n a[i+2]=...;\n a[i+3]=...;\n}\n" }, { "answer_id": 145399, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "for (int i = 0; i < 10; i++) { /* ... */ }\n\nint i = 0;\nwhile (i < 10) {\n // ...\n i++;\n}\n" }, { "answer_id": 145415, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 3, "selected": false, "text": "for (int i = 0; i < m; i++) \n for (j = 0; j < n; j++) \n s += arr[j][i];\n" }, { "answer_id": 145437, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 2, "selected": false, "text": "i++; int postincrement( int &i )\n{\n int itmp = i;\n i = i + 1;\n return itmp;\n} ++i; int preincrement( int &i )\n{\n i = i + 1;\n return i;\n}" }, { "answer_id": 598946, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 1, "selected": false, "text": "short int" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195/" ]
145,400
<p>How do I dictate the destination folder of a clickOnce application?</p>
[ { "answer_id": 145422, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 5, "selected": true, "text": "Apps" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23149/" ]
145,440
<p>I have an application written using VS2005 in C# targeting the Compact Framework 2.0 SP2. As part of the solution, I have CAB deploy project which deploys to the device without a problem. What I can't do is create a shortcut to my application on the devices desktop.</p> <p>I have spent several hours reading various bits of documentation (why is the search at the MSDN site so bad?), followed the instructions but no joy. </p> <p>What I've done is:</p> <ul> <li>Add the "Windows Folder" node to the File System</li> <li>Created a folder underneath that named "Desktop"</li> <li>Created a shortcut to the Applications Primary Output and placed that in the "Desktop" folder</li> </ul> <p>What am I missing?</p>
[ { "answer_id": 377749, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SHORTCUT = XX#\"\\Program Path...\"?\\Icon File Path...,-Icon Number\n Ex: 86#\"\\Storage Card\\Logical Sky CEdit\\cedit.exe\"?\\Storage Card\\Logical Sky CEdit\\cedit.exe,-101\n" }, { "answer_id": 3457264, "author": "Steve", "author_id": 417088, "author_profile": "https://Stackoverflow.com/users/417088", "pm_score": 3, "selected": false, "text": "[Shortcuts]\n\"ShortCutName\",0,\"MyApp.exe\",\"%CE3%\"\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16076/" ]
145,443
<p>If I use multiple repositories, all located under a single root folder, how can I set it up so that they will use a single master <code>svnconf</code>/<code>passwd</code> file for setup but still allow me to customize each if the need arises?</p> <p>This is on Windows, but I guess the process would be similar on other systems.</p> <p><strong>Update:</strong> I am using svnserve as a service.</p>
[ { "answer_id": 145453, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "conf/svnserve.conf password-db [general]" }, { "answer_id": 145463, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 3, "selected": true, "text": "svnserve" }, { "answer_id": 145466, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 1, "selected": false, "text": "svnserve svnserve.conf c:\\svn\\passwd\nc:\\svn\\project1\\conf\\svnserve.conf\nc:\\svn\\project2\\conf\\svnserve.conf\n svnserve.conf [general]\npassword-db = c:\\svn\\passwd\n authz <Location /project1>\n DAV svn\n SVNPath C:/Repositories/project1\n\n AuthType Basic\n AuthName \"Subversion Project1 repository\"\n AuthUserFile c:/etc/svn-auth-file\n\n Require valid-user\n\n AuthzSVNAccessFile c:/etc/svn-acl\n</Location>\n<Location /project2>\n DAV svn\n SVNPath C:/Repositories/project2\n\n AuthType Basic\n AuthName \"Subversion Project2 repository\"\n AuthUserFile c:/etc/svn-auth-file\n\n Require valid-user\n\n AuthzSVNAccessFile c:/etc/svn-acl\n</Location>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
145,449
<p>Notice in the bottom right hand corner of this page it has the SVN revision id? I'm assuming that's dynamic.</p> <p>I'd love to add that to some of my sites, just as a comment in the source to make sure code pushes are going through.</p> <p>NOTE: You can also assume that the working directory of the site in question is an svn checkout of the repo in question.</p> <p><b>Edit:</b> I'm looking for the global revision number, not the revision number of the file I'm looking at.</p>
[ { "answer_id": 145470, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": true, "text": "svnversion svnversion" }, { "answer_id": 145475, "author": "Brian Sadler", "author_id": 6912, "author_profile": "https://Stackoverflow.com/users/6912", "pm_score": 3, "selected": false, "text": " <svn username=\"${svn.username}\" password=\"${svn.password}\" javaHL=\"${svn.javahl}\"> \n <status path=\"${dir.build}\" revisionProperty=\"svn.status.revision\" />\n </svn>\n\n <replace dir=\"${dir.build}\" token=\"%revision%\" value=\"${svn.status.revision}\">\n <include name=\"**/*.php\" />\n </replace>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10680/" ]
145,508
<p>If you think it shouldn't, explain why.</p> <p>If yes, how deep should the guidelines be in your opinion? For example, indentation of code should be included?</p>
[ { "answer_id": 185085, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 2, "selected": false, "text": "for( int n = 0; n < 42; ++42 ) {\n // blah\n}\n for(int n = 0; n < 42; ++42 )\n{\n // blah\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23034/" ]
145,509
<p>Title is the entire question. Can someone give me a reason why this happens?</p>
[ { "answer_id": 145516, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "y.Length x.Substring(0, y.Length).Equals(y)" }, { "answer_id": 208910, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 4, "selected": false, "text": "\"abcd\".StartsWith(\"\") (\"abcd\".Substring(0,0) == \"\")\n" }, { "answer_id": 390801, "author": "jason", "author_id": 45914, "author_profile": "https://Stackoverflow.com/users/45914", "pm_score": 4, "selected": false, "text": "A B A B A B A B B B B B B B B B s t string s t s.Length >= t.Length t.Length t s s.Length >= t.Length Int32 index 0 <= index < t.Length s[index] == t[index] s t s.Length < t.Length s.Length >= t.Length Int32 index 0 <= index < t.Length s[index] != t[index] s t t s s s s s s.Length < String.Empty.Length s.Length >= String.Empty.Length Int32 index 0 <= index < String.Empty.Length s.Length >= 0 String.Empty.Length s.Length < String.Empty.Length is equal to zero, there is no satisfying s.Length < String.Empty.Length s.Length >= String.Empty.Length Int32 index 0 <= index < String.Empty.Length s s string public static bool DoStartsWith(this string s, string t) {\n if (s.Length >= t.Length) {\n for (int index = 0; index < t.Length; index++) {\n if (s[index] != t[index]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n" }, { "answer_id": 484398, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 2, "selected": false, "text": "String.StartsWith() System.Globalization.CultureInfo.IsPrefix() if (prefix.Length == 0)\n{\n return true;\n}\n" }, { "answer_id": 6433062, "author": "user804965", "author_id": 804965, "author_profile": "https://Stackoverflow.com/users/804965", "pm_score": 3, "selected": false, "text": " \"\".startsWith(\"\") == false \n \"\".equals(\"\") == true\n\n but yet\n\n \"a\".startsWith(\"a\") == true\n \"a\".equals(\"a\") == true\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ]
145,552
<p>I basically want to do this:</p> <pre><code>grep 'example.com' www_log &gt; example.com.YYYY-MM-DD-H:i:S.log </code></pre> <p>...with of course the filename being <b>example.com.2008-09-27-11:21:30.log</b></p> <p>I'd then put this in crontab to run daily.</p>
[ { "answer_id": 145554, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 4, "selected": true, "text": "grep 'example.com' www_log > `date +example.com.%Y-%m-%d-%H:%M:%S.log`\n grep 'example.com' www_log > `date +example.com.%F-%T.log`\n" }, { "answer_id": 145556, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 3, "selected": false, "text": "grep 'example.com' www_log > example.com.$(date +%F-%T).log\n" }, { "answer_id": 145568, "author": "Tao Zhyn", "author_id": 873, "author_profile": "https://Stackoverflow.com/users/873", "pm_score": 2, "selected": false, "text": "grep 'example.com' www_log > example.com.`date +%F-%T`.log\n $(command)\n `command`\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
145,563
<p>Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.</p> <p>example:</p> <pre><code>int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2} </code></pre> <p>the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs.</p>
[ { "answer_id": 145579, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "//split string into array firts\nstrsplit(numbers) //PHP function name to split a string into it's components\ni=0\nwhile( i < count(array))\n {\n if(isset(list[array[i]]))\n {\n list[array[i]]['count'] = list + 1\n }\n else\n {\n list[i]['count'] = 1\n list[i]['number']\n }\n i=i+1\n }\nusort(list) //usort is a php function that sorts an array by its value not its key, Im assuming that you have something in c++ that does this\nprint list[0]['number'] //Should contain the most used number\n" }, { "answer_id": 145646, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <algorithm>\n#include <map>\n\n// functor\nstruct maxoccur\n{\n int _M_val;\n int _M_rep;\n\n maxoccur()\n : _M_val(0),\n _M_rep(0)\n {}\n\n void operator()(const std::pair<int,int> &e)\n {\n std::cout << \"pair: \" << e.first << \" \" << e.second << std::endl;\n if ( _M_rep < e.second ) {\n _M_val = e.first;\n _M_rep = e.second;\n }\n }\n};\n\nint\nmain(int argc, char *argv[])\n{\n int a[] = {2,456,34,3456,2,435,2,456,2};\n std::map<int,int> m; \n\n // load the map\n for(unsigned int i=0; i< sizeof(a)/sizeof(a[0]); i++) \n m [a[i]]++;\n\n // find the max occurence...\n maxoccur ret = std::for_each(m.begin(), m.end(), maxoccur());\n std::cout << \"value:\" << ret._M_val << \" max repetition:\" << ret._M_rep << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 297914, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 0, "selected": false, "text": "std::tr1::unordered_map unordered_map partial_sort_copy #include <unordered_map>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\nnamespace {\n// Only used in most_frequent but can't be a local class because of the member template\nstruct second_greater {\n // Need to compare two (slightly) different types of pairs\n template <typename PairA, typename PairB>\n bool operator() (const PairA& a, const PairB& b) const\n { return a.second > b.second; }\n};\n}\n\ntemplate <typename Iter>\nstd::pair<typename std::iterator_traits<Iter>::value_type, unsigned int>\nmost_frequent(Iter begin, Iter end)\n{\n typedef typename std::iterator_traits<Iter>::value_type value_type;\n typedef std::pair<value_type, unsigned int> result_type;\n\n std::tr1::unordered_map<value_type, unsigned int> counts;\n\n for(; begin != end; ++begin)\n // This is safe because new entries in the map are defined to be initialized to 0 for\n // built-in numeric types - no need to initialize them first\n ++ counts[*begin];\n\n // Only need the top one at this point (could easily expand to top-n)\n std::vector<result_type> top(1);\n\n std::partial_sort_copy(counts.begin(), counts.end(),\n top.begin(), top.end(), second_greater());\n\n return top.front();\n}\n\nint main(int argc, char* argv[])\n{\n int a[] = { 2, 456, 34, 3456, 2, 435, 2, 456, 2 };\n\n std::pair<int, unsigned int> m = most_frequent(a, a + (sizeof(a) / sizeof(a[0])));\n\n std::cout << \"most common = \" << m.first << \" (\" << m.second << \" instances)\" << std::endl;\n assert(m.first == 2);\n assert(m.second == 4);\n\n return 0;\n}\n" }, { "answer_id": 74655267, "author": "A M", "author_id": 9666018, "author_profile": "https://Stackoverflow.com/users/9666018", "pm_score": 0, "selected": false, "text": "std::unordered_map using std::ranges #include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n\nnamespace rng = std::ranges;\n\nint main() {\n // Demo data\n std::vector data{ 2, 456, 34, 3456, 2, 435, 2, 456, 2 };\n\n // Count values\n using Counter = std::unordered_map<decltype (data)::value_type, std::size_t> ;\n\n Counter counter{}; for (const auto& d : data) counter[d]++;\n\n // Get max\n const auto& [value, count] = *rng::max_element(counter, {}, &Counter::value_type::second);\n\n // Show output\n std::cout << '\\n' << value << \" found \" << count << \" times\\n\";\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8786/" ]
145,570
<p>The following have been proposed for an upcoming C++ project.</p> <ul> <li>C++ Coding Standards, by Sutter and Alexandrescu</li> <li>JSF Air Vehicle C++ coding standards</li> <li>The Elements of C++ Style</li> <li>Effective C++ 3rd Edition, by Scott Meyers</li> </ul> <p>Are there other choices? Or is the list above what be should used on a C++ project?</p> <p>Some related links</p> <ul> <li><a href="https://stackoverflow.com/questions/145508/do-you-think-a-software-company-should-impose-developers-a-coding-style">Do you think a software company should impose developers a coding-style?</a></li> <li><a href="https://stackoverflow.com/questions/66268/what-is-the-best-cc-coding-style-closed">https://stackoverflow.com/questions/66268/what-is-the-best-cc-coding-style-closed</a></li> </ul>
[ { "answer_id": 145604, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 4, "selected": true, "text": "m_" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22807/" ]
145,573
<p>I have three related questions. </p> <p>I want to create a word file with a name from C++. I want to be able to sent the printing command to this file, so that the file is being printed without the user having to open the document and do it manually and I want to be able to open the document. Opening the document should just open word which then opens the file.</p>
[ { "answer_id": 8332989, "author": "ctype.h", "author_id": 1224599, "author_profile": "https://Stackoverflow.com/users/1224599", "pm_score": 0, "selected": false, "text": "start /min winword <filename> /q /n /f /mFilePrint /mFileExit\n <filename> file.rtf \"A File.docx\" system(\"start /min winword <filename> /q /n /f /mFilePrint /mFileExit\");\n /*winword.h\n *Includes functions to print Word files more easily\n */\n\n#ifndef WINWORD_H_\n#define WINWORD_H_\n\n#include <string.h>\n#include <stdlib.h>\n\n//Opens Word minimized, shows the user a dialog box to allow them to\n//select the printer, number of copies, etc., and then closes Word\nvoid wordprint(char* filename){\n char* command = new char[64 + strlen(filename)];\n strcpy(command, \"start /min winword \\\"\");\n strcat(command, filename);\n strcat(command, \"\\\" /q /n /f /mFilePrint /mFileExit\");\n system(command);\n delete command;\n}\n\n//Opens the document in Word\nvoid wordopen(char* filename){\n char* command = new char[64 + strlen(filename)];\n strcpy(command, \"start /max winword \\\"\");\n strcat(command, filename);\n strcat(command, \"\\\" /q /n\");\n system(command);\n delete command;\n}\n\n//Opens a copy of the document in Word so the user can save a copy\n//without seeing or modifying the original\nvoid wordduplicate(char* filename){\n char* command = new char[64 + strlen(filename)];\n strcpy(command, \"start /max winword \\\"\");\n strcat(command, filename);\n strcat(command, \"\\\" /q /n /f\");\n system(command);\n delete command;\n}\n\n#endif\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23163/" ]
145,607
<p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p> <p>The implementation can be in c# or python.</p> <p>Thanks.</p>
[ { "answer_id": 146957, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": true, "text": "difflib def text_compare(text1, text2, isjunk=None):\n return difflib.SequenceMatcher(isjunk, text1, text2).ratio()\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
145,617
<p>The case goes as following: You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming:</p> <pre><code> private bool FullScreenEnabled { get; set; } // Check if FullScreenEnabled is false and return; private void Case1() { if (FullScreenEnabled == false) { return; } // code to be executed goes here! } // Surround the code by an if statement. private void Case2() { if (FullScreenEnabled) { // code to be executed goes here! } } </code></pre>
[ { "answer_id": 145625, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": 5, "selected": true, "text": "private void MyMethod(bool arg){\n if(arg)\n return;\n //do stuff\n};\n" }, { "answer_id": 145627, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": -1, "selected": false, "text": "private void MyMethod(bool arg){\n if(!arg){\n //do stuff\n }\n}\n" }, { "answer_id": 145665, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 0, "selected": false, "text": "if (!FullScreenEnabled)\n throw new InvalidOperationException(\"Must be in fullscreen mode to do foo.\");\n" }, { "answer_id": 145671, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "if (!FullScreenEnabled) return;" }, { "answer_id": 145743, "author": "Lior Friedman", "author_id": 23176, "author_profile": "https://Stackoverflow.com/users/23176", "pm_score": 0, "selected": false, "text": "if (FullScreenEnabled == false) if (FullScreenEnabled) return" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/113670/" ]
145,657
<p>I need to compare large count of PDF files for it optical content. Because the PDF files was created on different platforms and with different versions of the software there are structural differences. For example:</p> <ul> <li>the chunking of text can be different</li> <li>the write order can be different</li> <li>the position can be differ some pixels</li> </ul> <p>It should compare the content like a human people and not the internal structure. I want test for regressions between different versions of the PDF generator that we used. </p>
[ { "answer_id": 2235509, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 4, "selected": false, "text": "$ convert -density 150x150 -fill red -opaque black +antialias 1.pdf back%02d.png\n$ convert -density 150x150 -transparent white +antialias 2.pdf front%02d.png\n$ composite front01.png back01.png result01.png # do this for all pairs of images\n" }, { "answer_id": 2235553, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 3, "selected": false, "text": "-layout #!/bin/sh\nRED=$'\\e'\"[1;31m\"\nGREEN=$'\\e'\"[1;32m\"\nRESET=$'\\e'\"[0m\"\nwdiff -w$RED -x$RESET -y$GREEN -z$RESET -n $1 $2\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631/" ]
145,689
<p>Design patterns are usually related to object oriented design.<br> <strong>Are there <a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)" rel="noreferrer">design patterns</a> for creating and programming <a href="http://en.wikipedia.org/wiki/Relational_database" rel="noreferrer">relational databases</a>?</strong><br> Many problems surely must have reusable solutions.</p> <p>Examples would include patterns for table design, stored procedures, triggers, etc...</p> <p>Is there an online repository of such patterns, similar to <a href="http://martinfowler.com" rel="noreferrer">martinfowler.com</a>?</p> <hr> <p>Examples of problems that patterns could solve:</p> <ul> <li>Storing hierarchical data (e.g. single table with type vs multiple tables with 1:1 key and differences...)</li> <li>Storing data with variable structure (e.g. generic columns vs xml vs delimited column...)</li> <li>Denormalize data (how to do it with minimal impact, etc...)</li> </ul>
[ { "answer_id": 145756, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 1, "selected": false, "text": "UPSERT MERGE UPDATE INSERT" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
145,699
<p>At the moment I use PHP for almost everything I develop for the Web but its linguistic limitations are starting to annoy me. However, as I developed some practices and maintain some PHP libraries that help me a lot, I don't feel I'd be ready to just switch to LISP throwing away all my PHP output. It could even be impossible on the servers where all I have access to is a regular LAMP hosting account.</p> <p>Ergo, my questions are: Could LISP code be just combined with PHP one? Are there solutions for side-by-side LISP/PHP, interface for their interoperability or perphaps just an implementation of one for the other? Or is it a mutually exclusive choice?</p>
[ { "answer_id": 145754, "author": "Mikael Jansson", "author_id": 18753, "author_profile": "https://Stackoverflow.com/users/18753", "pm_score": 3, "selected": false, "text": "defmacro.org" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22827/" ]
145,701
<p>Could anyone show me a sample about how to use these two commands in Windbg please? I read the document in debugger.chm, but confused. I did search in Google and MSDN, but not find an easy to learn sample.</p>
[ { "answer_id": 145782, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": " 1 x = 0\n 2 y = 0\n 3 call 8\n 4 x = 5\n 5 y = 7\n 6 call 8\n 7 halt\n\n 8 print x\n 9 print y\n10 call 12\n11 return\n\n12 print x + y\n13 print x * y\n14 return\n gu call 8 pc gu" }, { "answer_id": 177816, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "77ef2aa0 cc int 3\n0:000> bp main\n0:000> g\nBreakpoint 0 hit\nTestDebug1!main:\n00000001 400010aa c7442424c8000000 mov dword ptr [rsp+24h],0C8h ss:00000000 return b;\n return a;\n int* b = &a;\n\nfoo();\n\na = 400;\n\ngoo();\n\nreturn 0;\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
145,752
<p>For the most part, you just take whatever Visual Studio sets it for you as a default... I'm referring to the <a href="https://learn.microsoft.com/en-us/visualstudio/ide/build-actions?view=vs-2019" rel="noreferrer">BuildAction</a> property for each file selected in Solution Explorer. There are a number of options and it's difficult to know what each one of them will do.</p>
[ { "answer_id": 145769, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 10, "selected": false, "text": "xaml baml baml Resource SplashScreen" }, { "answer_id": 702249, "author": "James Moore", "author_id": 73046, "author_profile": "https://Stackoverflow.com/users/73046", "pm_score": 3, "selected": false, "text": "Window (System.Windows..::.Window).\n\nPage (System.Windows.Controls..::.Page).\n\nPageFunction (System.Windows.Navigation..::.PageFunction<(Of <(T>)>)).\n\nResourceDictionary (System.Windows..::.ResourceDictionary).\n\nFlowDocument (System.Windows.Documents..::.FlowDocument).\n\nUserControl (System.Windows.Controls..::.UserControl).\n" }, { "answer_id": 67512873, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 3, "selected": false, "text": "Compile MyClass.cs .csproj <ItemGroup>\n <Compile>MyClass.cs</Compile>\n</ItemGroup>\n Compile Content None .editorconfig EditorConfigFiles AdditionalFiles AvailableItemName <ItemGroup>\n <AvailableItemName Include=\"Foo\" />\n</ItemGroup>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
145,753
<p>I've got a project that was written in BASIC. I'm not sure of the exact reason, but the app will not function except when being run from a FAT-16 file system.</p> <p>I'd rather try to set up an environment that will support this app in a modern OS (Vista/XP) instead of rewriting it.</p> <p>Does anyone know how to get an app like this running in XP/Vista through some kind of code change (to the BASIC code) or FAT-16 &quot;emulator&quot; (if such a thing exists)?</p>
[ { "answer_id": 145776, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 3, "selected": false, "text": "CALL PEEK POKE IN OUT OPEN \"file\" FOR whatever AS #1" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
145,770
<p>There is a webpage loaded in the firefox sidebar and another webpage loaded in the main document. Now, how do I ask access the main document object through the Firefox sidebar? An example to do this through Javascript code in the firefox sidebar document to access the main document would be helpful.</p> <p>Thanks for the answers. I have to refine my question however. The main window has some webpage loaded and the sidebar has a webpage. I want the sidebar window to know what text the user has selected on the main window when a link on the sidebar window is clicked. I know how to get the selected text from a window. Only that the sidebar element adds complexity to the problem that I am not able to surpass.</p> <p>@PConory:</p> <p>I like your answer, but when I try it there is an error:</p> <blockquote> <p>Error: Permission denied to create wrapper for object of class UnnamedClass.</p> </blockquote> <p>Thanks.</p>
[ { "answer_id": 145791, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 1, "selected": false, "text": "#document\n window main-window\n ...\n browser\n #document\n window sidebarWindow\n mainWindow var mWin = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)\n .getInterface(Components.interfaces.nsIWebNavigation)\n .QueryInterface(Components.interfaces.nsIDocShellTreeItem)\n .rootTreeItem\n .QueryInterface(Components.interfaces.nsIInterfaceRequestor)\n .getInterface(Components.interfaces.nsIDOMWindow); \n" }, { "answer_id": 145824, "author": "Morgan ARR Allen", "author_id": 22474, "author_profile": "https://Stackoverflow.com/users/22474", "pm_score": 2, "selected": false, "text": "var newwin = window.open('http://otherpage')\nnewwin.onload = function()\n{\n newwin.postMessage('Hey newwin', 'http://sidebar');\n};\n\nmainpage.js\nwindow.addEventListener('message',function(e)\n{\n if(message.origin == 'http://sidebar')\n alert('message from sidebar');\n},false);\n" }, { "answer_id": 146137, "author": "treat your mods well", "author_id": 20772, "author_profile": "https://Stackoverflow.com/users/20772", "pm_score": 1, "selected": false, "text": "var child = window.open(...) window.opener" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6488/" ]
145,771
<p>I have tried to find how to create DLL-s on linux using google, but got very confusing information.</p> <p>Is it possible to write dynamic link libraries on linux? If not, are there other means by which I can call code in another module from several running programs?</p>
[ { "answer_id": 145794, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": false, "text": ".so .so -shared \ngcc -shared -o libfoo.so foo.c\n -l \nld -o a.out -lfoo someobject.o \n .so .dll" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ]
145,803
<p>I have a little dilemma on how to set up my visual studio builds for multi-targeting.</p> <p>Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project. Right now, the platform target is set to x86 so it can be run on Windows x64.</p> <p>The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.</p> <p>This raises some questions which I haven't got the answers to yet. I want to have the exact same code base. I must build with references to either the 32bit set of DLL's or 64bit DLL's. (Both 3rd party and SQL Server Compact)</p> <p>Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?</p> <p>Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?</p> <p>Any ideas and/or recommendations would be welcomed.</p>
[ { "answer_id": 145903, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 7, "selected": true, "text": "<Reference Include=\"Filename, ..., processorArchitecture=x86\">\n <HintPath>C:\\path\\to\\x86\\DLL</HintPath>\n</Reference>\n <ItemGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x86' \">\n <Reference ...>....</Reference>\n</ItemGroup>\n <ItemGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x64' \">\n <Reference Include=\"Filename, ..., processorArchitecture=AMD64\">\n <HintPath>C:\\path\\to\\x64\\DLL</HintPath>\n </Reference>\n</ItemGroup>\n <ItemGroup Condition=\"'$(Platform)' == 'x86'\">\n <Reference Include=\"System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86\" />\n</ItemGroup>\n<ItemGroup Condition=\"'$(Platform)' == 'x64'\">\n <Reference Include=\"System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64\" />\n</ItemGroup>\n" }, { "answer_id": 145970, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 5, "selected": false, "text": "C:\\whatever\\x86\\whatever.dll\nC:\\whatever\\x64\\whatever.dll\n <HintPath>C:\\whatever\\x86\\whatever.dll</HintPath>\n <HintPath>C:\\whatever\\$(Platform)\\whatever.dll</HintPath>\n" }, { "answer_id": 18743834, "author": "Yochai Timmer", "author_id": 536086, "author_profile": "https://Stackoverflow.com/users/536086", "pm_score": 1, "selected": false, "text": " <ItemGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|x86' \">\n <Reference Include=\"DLLName\">\n <HintPath>..\\DLLName.dll</HintPath>\n </Reference>\n <ProjectReference Include=\"..\\MyOtherProject.vcxproj\">\n <Project>{AAAAAA-000000-BBBB-CCCC-TTTTTTTTTT}</Project>\n <Name>MyOtherProject</Name>\n </ProjectReference>\n </ItemGroup>\n" }, { "answer_id": 51670076, "author": "Felix Keil", "author_id": 3703372, "author_profile": "https://Stackoverflow.com/users/3703372", "pm_score": 1, "selected": false, "text": "<ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>\n xcopy /E /H /R /Y /I /D $(SolutionDir)\\YourPathToX86Dlls $(TargetDir)\\x86\nxcopy /E /H /R /Y /I /D $(SolutionDir)\\YourPathToX64Dlls $(TargetDir)\\x64 AppDomain.CurrentDomain.AssemblyResolve += TryResolveArchitectureDependency;\n /// <summary>\n/// Event Handler for AppDomain.CurrentDomain.AssemblyResolve\n/// </summary>\n/// <param name=\"sender\">The app domain</param>\n/// <param name=\"resolveEventArgs\">The resolve event args</param>\n/// <returns>The architecture dependent assembly</returns>\npublic static Assembly TryResolveArchitectureDependency(object sender, ResolveEventArgs resolveEventArgs)\n{\n var dllName = resolveEventArgs.Name.Substring(0, resolveEventArgs.Name.IndexOf(\",\"));\n\n var anyCpuAssemblyPath = $\".\\\\{dllName}.dll\";\n\n var architectureName = System.Environment.Is64BitProcess ? \"x64\" : \"x86\";\n\n var assemblyPath = $\".\\\\{architectureName}\\\\{dllName}.dll\";\n\n if (File.Exists(assemblyPath))\n {\n return Assembly.LoadFrom(assemblyPath);\n }\n\n return null;\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3584/" ]
145,814
<p>Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:</p> <pre><code>template&lt;class T, template &lt;class&gt; class Manager = DefaultManager&gt; class Data { private: T *data_; public: void Dispatch() { if(SUPERSUBCLASS(Container, T)) { data_-&gt;IKnowThisIsHere(); } else { Manager&lt;T&gt;::SomeGenericFunction(data_); } } } </code></pre> <p>Where SUPERSUBCLASS is a compile-time macro to determine object inheritance. Of course, this fails in all cases where T does to inherit from Container (or T is an intrinsic type etc etc) because the compiler rightly complains that IKnowThisIsHere() is not a data member, even though this code path will never be followed, as shown here after preprocessing with T = int:</p> <pre><code>private: int *data_; public: void Dispatch() { if(false) { data_-&gt;IKnowThisIsHere(); </code></pre> <p>Compiler clearly complains at this code, even though it will never get executed. A suggestion of using a dynamic_cast also does not work, as again a type conversion is attempted at compile time that is not possible (for example with T=double, std::string):</p> <pre><code>void Dispatch() { if(false) { dynamic_cast&lt;Container*&gt;(data_)-&gt;IKnowThisIsHere(); error: cannot dynamic_cast '((const Data&lt;double, DefaultManager&gt;*)this)-&gt;Data&lt;double, DefaultManager&gt;::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class) error: cannot dynamic_cast '((const Data&lt;std::string, DefaultManager&gt;*)this)-&gt;Da&lt;sttad::string, DefaultManager&gt;::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic) </code></pre> <p>I really need to emulate (or indeed persuade!) having the compiler emit one set of code if T does inherit from Container, and another if it does not.</p> <p>Any suggestions?</p>
[ { "answer_id": 145859, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": 0, "selected": false, "text": "error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, RawManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)\n error: cannot dynamic_cast '((const Data<std::string, DefaultRawManager>*)this)->Data<std::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)\n" }, { "answer_id": 145944, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 3, "selected": true, "text": "template <bool n>\nstruct int2type\n{ enum { value = n}; };\n #include <iostream>\n\n#define MACRO() true // <- macro used to dispatch \n\ntemplate <bool n>\nstruct int2type\n{ enum { value = n }; };\n\nvoid method(int2type<false>)\n{ std::cout << __PRETTY_FUNCTION__ << std::endl; }\n\nvoid method(int2type<true>)\n{ std::cout << __PRETTY_FUNCTION__ << std::endl; }\n\nint\nmain(int argc, char *argv[])\n{\n // MACRO() determines which function to call\n //\n\n method( int2type<MACRO()>()); \n\n return 0;\n}\n" }, { "answer_id": 146074, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "if true if is_base_of if void Dispatch()\n{\n myfunc(data_);\n}\n\nprivate:\n\n// EDIT: disabled the default case where the specialisation matched\ntemplate <typename U>\ntypename enable_if_c<is_base_of<Container, U>::value, U>::type myfunc(U& data_) {\n data_->IKnowThisIsHere();\n}\n\ntemplate <typename U>\ntypename disable_if_c<is_base_of<Container, U>::value, U>::type myfunc(U& data_) { // default case\n Manager<U>::SomeGenericFunction(data_);\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23167/" ]
145,828
<p>I have a project I'm working on (for school) that I'm digging into the Boost libraries for the solutions. I need some way to distribute the required Boost source code with my application so that it can be compiled without the libraries being installed on the system doing the compiling. (School computers lack just about anything you can mention. The school just installed CVS last year. But they do have VS2005)</p> <p>Note: I'm using Visual Studio 2005 on Vista. I have Boost 1.34.1 on my system I used the <a href="http://www.boostpro.com/products/free" rel="nofollow noreferrer">automatic installer</a>. The documentation I've come across says something about using BCP command but that command doesn't seem to copy anything. (I'm using absolute path to call BCP so I don't end up calling the wrong command.)</p> <p>Edit: I am trying to use the RegEx libraries.</p> <p>Edit: The command I'm using for BCP is: <code>"c:\Program Files\boost\boost_1_34_1\bin\bcp.exe" boost/regex.hpp regex\</code></p> <p>And it returns: <code>no errors detected</code></p>
[ { "answer_id": 148195, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 2, "selected": false, "text": "\"c:\\Program Files\\boost\\boost_1_34_1\\bin\\bcp.exe\" --boost=\"c:\\Program Files\\boost\\boost_1_34_1\" regex regex\n --boost regex libs\\regex\\build\\" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ]
145,838
<p>What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980&lt; where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?</p>
[ { "answer_id": 145841, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 8, "selected": true, "text": "inline int aplusb_pow2(int a, int b) {\n return (a + b)*(a + b) ;\n}\n\nfor(int a = 0; a < 900000; ++a)\n for(int b = 0; b < 900000; ++b)\n aplusb_pow2(a, b);\n" }, { "answer_id": 145952, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": false, "text": "return 42 ;" }, { "answer_id": 146144, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": -1, "selected": false, "text": "__inline __inline __inline" }, { "answer_id": 7414495, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "inline #include" }, { "answer_id": 7418299, "author": "Emilio Garavaglia", "author_id": 924727, "author_profile": "https://Stackoverflow.com/users/924727", "pm_score": 6, "selected": false, "text": "inline register inline inline //fileA.h\ninline void afunc()\n{ std::cout << \"this is afunc\" << std::endl; }\n\n//file1.cpp\n#include \"fileA.h\"\nvoid acall()\n{ afunc(); }\n\n//main.cpp\n#include \"fileA.h\"\nvoid acall();\n\nint main()\n{ \n afunc(); \n acall();\n}\n\n//output\nthis is afunc\nthis is afunc\n afunc() inline" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22040/" ]
145,842
<p>I'm interested in finding out what people would consider the most useful data structures to know in programming. What data structure do you find yourself using all the time? </p> <p>Answers to this post should help new programmers interested in finding a useful data structure for their problem. Answers should probably include the data structure, information about it or a relevant link, the situation it is being used in and why it is a good choice for this problem (e.g ideal computation complexities, simplicity and understanding etc.)</p> <p>Each answer should be about one data structure only.</p> <p>Thanks for any pearls of wisdom and experience people can share.</p>
[ { "answer_id": 146042, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "Dictionary<keytype, valuetype>" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20388/" ]
145,855
<p>All,</p> <p>As part of an application I'm writing I need to have a HTTP PUT webservice which accepts incoming imagedata, which will by analyzed, validated, and added to a local file store.</p> <p>My issue arises after the size validation as the </p> <blockquote> <p><code>$_SERVER['CONTENT_LENGTH']</code></p> </blockquote> <p>has a > 0 value, and this value is identical to the test file size, so I can assume that all is going well up to this point <em>but</em> when I try to read the incoming stream data using </p> <blockquote> <p><code>file_get_contents('php://stdin');</code></p> </blockquote> <p>I get an empty string. I've also tried using </p> <blockquote> <p><code>file_get_contents('php://input');</code></p> </blockquote> <p>And this give me the same result of an empty string.</p> <p>Any help, suggestions or direction will be appreciated.</p> <p>NB: I'm using </p> <ul> <li>PHP 5.2.6</li> <li>Apache 2.0</li> </ul>
[ { "answer_id": 145874, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 0, "selected": false, "text": "r file_get_contents a/r/w/a+/r+/w+ fopen file_get_contents('php://input');\n" }, { "answer_id": 145881, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "file_get_contents string file_get_contents ( string $filename [, int $flags...)\n $flag FILE_USE_INCLUDE_PATH, FILE_TEXT, FILE_BINARY file_get_contents file_get_contents('php://input') file, fopen+fread multipart/form-data strlen" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11000/" ]
145,856
<p>I have an array of integers:</p> <pre><code>int[] number = new int[] { 2,3,6,7 }; </code></pre> <p>What is the easiest way of converting these into a single string where the numbers are separated by a character (like: <code>&quot;2,3,6,7&quot;</code>)?</p> <p>I'm using C# and .NET 3.5.</p>
[ { "answer_id": 145864, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 8, "selected": true, "text": "var ints = new int[] {1, 2, 3, 4, 5};\nvar result = string.Join(\",\", ints.Select(x => x.ToString()).ToArray());\nConsole.WriteLine(result); // prints \"1,2,3,4,5\"\n var result = string.Join(\",\", ints.Select(x => x.ToString()).ToArray());\n var result = string.Join(\",\", ints);\n // length computed from length of items in input array and length of separator\nstring str = FastAllocateString(length);\nfixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here\n{\n UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);\n buffer.AppendString(value[startIndex]);\n for (int j = startIndex + 1; j <= num2; j++)\n {\n buffer.AppendString(separator);\n buffer.AppendString(value[j]);\n }\n}\n" }, { "answer_id": 145868, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 3, "selected": false, "text": "String.Join(\";\", number.Select(item => item.ToString()).ToArray());\n String Select map String.Join ToArray() String.Join IEnumerable<String> Join" }, { "answer_id": 145937, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "StringBuilder builder = new StringBuilder();\nchar separator = ',';\nforeach(int value in integerArray)\n{\n if (builder.Length > 0) builder.Append(separator);\n builder.Append(value);\n}\nstring result = builder.ToString();\n" }, { "answer_id": 145967, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic static class Extensions\n{\n public static string JoinStrings<T>(this IEnumerable<T> source, \n Func<T, string> projection, string separator)\n {\n StringBuilder builder = new StringBuilder();\n bool first = true;\n foreach (T element in source)\n {\n if (first)\n {\n first = false;\n }\n else\n {\n builder.Append(separator);\n }\n builder.Append(projection(element));\n }\n return builder.ToString();\n }\n\n public static string JoinStrings<T>(this IEnumerable<T> source, string separator)\n {\n return JoinStrings(source, t => t.ToString(), separator);\n }\n}\n\nclass Test\n{\n\n public static void Main()\n {\n int[] x = {1, 2, 3, 4, 5, 10, 11};\n\n Console.WriteLine(x.JoinStrings(\";\"));\n Console.WriteLine(x.JoinStrings(i => i.ToString(\"X\"), \",\"));\n }\n}\n" }, { "answer_id": 146132, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 2, "selected": false, "text": "int[] number = new int[] { 1, 2, 3, 4, 5 };\nstring[] strings = new string[number.Length];\nfor (int i = 0; i < number.Length; i++)\n strings[i] = number[i].ToString();\nstring result = string.Join(\",\", strings);\n" }, { "answer_id": 225134, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "ints.ToString(\",\")\nints.ToString(\"|\")\nints.ToString(\":\")\n" }, { "answer_id": 225175, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 5, "selected": false, "text": "string.Join(\",\", Array.ConvertAll<int, String>(ints, Convert.ToString));\n string.Join(\",\", Array.ConvertAll(ints, item => item.ToString()))\n" }, { "answer_id": 2196447, "author": "void", "author_id": 265787, "author_profile": "https://Stackoverflow.com/users/265787", "pm_score": 2, "selected": false, "text": "ints.Aggregate(\"\", ( str, n ) => str +\",\"+ n ).Substring(1);\n" }, { "answer_id": 8304311, "author": "WebMasterP", "author_id": 60445, "author_profile": "https://Stackoverflow.com/users/60445", "pm_score": 3, "selected": false, "text": "int[] numbers = new int[] { 2,3,6,7 };\nstring number_string = string.Join(\",\", numbers);\n// do whatever you want with your exciting new number string\n" }, { "answer_id": 31986299, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "params object[] int[] ids = new int[] { 1, 2, 3 };\nstring.Join(\",\", ids);\n int[] ids = new int[] { 1, 2, 3 };\nSystem.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand(\"SELECT * FROM some_table WHERE id_column IN (@bla)\");\ncmd.CommandText = cmd.CommandText.Replace(\"@bla\", string.Join(\",\", ids));\n public static string JoinArray<T>(string separator, T[] inputTypeArray)\n{\n string strRetValue = null;\n System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();\n\n for (int i = 0; i < inputTypeArray.Length; ++i)\n {\n string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);\n\n if (!string.IsNullOrEmpty(str))\n {\n // SQL-Escape\n // if (typeof(T) == typeof(string))\n // str = str.Replace(\"'\", \"''\");\n\n ls.Add(str);\n } // End if (!string.IsNullOrEmpty(str))\n\n } // Next i\n\n strRetValue= string.Join(separator, ls.ToArray());\n ls.Clear();\n ls = null;\n\n return strRetValue;\n}\n public static class ArrayEx\n{\n\n public static string JoinArray<T>(this T[] inputTypeArray, string separator)\n {\n string strRetValue = null;\n System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();\n\n for (int i = 0; i < inputTypeArray.Length; ++i)\n {\n string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);\n\n if (!string.IsNullOrEmpty(str))\n {\n // SQL-Escape\n // if (typeof(T) == typeof(string))\n // str = str.Replace(\"'\", \"''\");\n\n ls.Add(str);\n } // End if (!string.IsNullOrEmpty(str))\n\n } // Next i\n\n strRetValue= string.Join(separator, ls.ToArray());\n ls.Clear();\n ls = null;\n\n return strRetValue;\n }\n\n}\n int[] ids = new int[] { 1, 2, 3 };\nstring strIdList = ids.JoinArray(\",\");\n // you need this once (only), and it must be in this namespace\nnamespace System.Runtime.CompilerServices\n{\n [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]\n public sealed class ExtensionAttribute : Attribute {}\n}\n" }, { "answer_id": 63710888, "author": "UkrGuru", "author_id": 12116884, "author_profile": "https://Stackoverflow.com/users/12116884", "pm_score": 1, "selected": false, "text": "var result = string.Join(\",\", ints);\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298/" ]
145,880
<p>The Objective Caml language will only produce stack traces if you ask for them just right - what are the requirements for both bytecode and native code?</p>
[ { "answer_id": 17256766, "author": "Marc Weber", "author_id": 674804, "author_profile": "https://Stackoverflow.com/users/674804", "pm_score": 3, "selected": false, "text": "export OCAMLRUNPARAM=b\n# compile with -g\n\nflush_all(); let r = Unix.fork() in if r == 0 then raise Exit\n" }, { "answer_id": 45396045, "author": "typesanitizer", "author_id": 2682729, "author_profile": "https://Stackoverflow.com/users/2682729", "pm_score": 2, "selected": false, "text": "debug foo.ml bar _tags <foo.ml>: package(bar), debug\n -g export OCAMLRUNPARAM=b" }, { "answer_id": 68885656, "author": "Jay Lieske", "author_id": 656176, "author_profile": "https://Stackoverflow.com/users/656176", "pm_score": 0, "selected": false, "text": "OCAMLRUNPARAM=b _tags ocamldebug ocamlprof .d.byte .p.native foo.ml export OCAMLRUNPARAM=b\n\nocamlbuild -no-links foo.d.byte && _build/foo.d.byte\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12874/" ]
145,887
<p>I want to display a thumbnail image in a <code>cell</code> of <code>tableViewController</code>, this thumbnail image is located at some remote place (URL of address is in XML file) so which format of image is cost effective?</p>
[ { "answer_id": 145898, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": true, "text": "optipng jpegtran" }, { "answer_id": 146211, "author": "catlan", "author_id": 23028, "author_profile": "https://Stackoverflow.com/users/23028", "pm_score": 0, "selected": false, "text": "UITableView" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
145,894
<p>I could not find any pointers on how to create a menubar icon on OSX using wx. I originally thought that the wxTaskBarIcon class would do, but it actually creates an icon on the Dock. On Windows, wxTaskBarIcon creates a Systray icon and associated menu, and I would think that on mac osx it would create a menubar icon, I guess not.</p>
[ { "answer_id": 145918, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": true, "text": "wxTaskBarIconType STATUSITEM DOCK NSStatusBar NSStatusItem" }, { "answer_id": 25845284, "author": "GP89", "author_id": 659346, "author_profile": "https://Stackoverflow.com/users/659346", "pm_score": 1, "selected": false, "text": "wx.TaskBarIcon SetIcon" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21943/" ]
145,900
<p>I have an install that upgrades a previous version of an app if it exits. I'd like to skip certain actions when the install is upgrade mode. How can I determine if the install is running in upgrade mode vs. first time install mode?</p> <p>I'm using Wise Installer, but I don't think that matters. I'm assuming that Windows Installer has a property that is set when the installer is in upgrade mode. I just can't seem to find it. If the property exists, I'm assuming I could use it in a conditional statement.</p>
[ { "answer_id": 146063, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 2, "selected": false, "text": " <!-- Property definitions -->\n <?define SkuName = \"MyCoolApp\"?>\n <?define ProductName=\"My Cool Application\"?>\n <?define Manufacturer=\"Acme Inc.\"?>\n <?define Copyright=\"Copyright © Acme Inc. All rights reserved.\"?>\n <?define ProductVersion=\"1.1.0.0\"?>\n <?define RTMProductVersion=\"1.0.0.0\" ?>\n <?define UpgradeCode=\"{EF9D543D-9BDA-47F9-A6B4-D1845A2EBD49}\"?>\n <?define ProductCode=\"{27EA5747-9CE3-3F83-96C3-B2F5212CD1A6}\"?>\n <?define Language=\"1033\"?>\n <?define CodePage=\"1252\"?>\n <?define InstallerVersion=\"200\"?>\n <Upgrade Id=\"$(var.UpgradeCode)\">\n <UpgradeVersion Minimum=\"$(var.ProductVersion)\"\n IncludeMinimum=\"no\"\n OnlyDetect=\"yes\"\n Language=\"$(var.Language)\"\n Property=\"NEWPRODUCTFOUND\" />\n\n <UpgradeVersion Minimum=\"$(var.RTMProductVersion)\"\n IncludeMinimum=\"yes\"\n Maximum=\"$(var.ProductVersion)\"\n IgnoreRemoveFailure=\"no\"\n IncludeMaximum=\"no\"\n Language=\"$(var.Language)\"\n Property=\"OLDIEFOUND\" />\n\n</Upgrade>\n OLDIEFOUND NEWPRODUCTFOUND <!-- Define custom actions -->\n<CustomAction Id=\"ActivateProduct\" \n Directory='MyCoolAppFolder' \n ExeCommand='\"[MyCoolAppFolder]activateme.exe\"' \n Return='asyncNoWait' \n Execute='deferred'/>\n\n<CustomAction Id=\"NoUpgrade4U\" \n Error=\"A newer version of MyCoolApp is already installed.\"/>\n InstallExcecuteSequence <InstallExecuteSequence>\n <Custom Action=\"NoUpgrade4U\" \n After=\"FindRelatedProducts\">NEWPRODUCTFOUND</Custom>\n <Custom Action=\"ActivateProduct\" \n OnExit='success'>NOT OLDIEFOUND</Custom>\n</InstallExecuteSequence>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22984/" ]
145,922
<p>I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError).</p> <p>What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping references to objects which should be able to be garbage collected.</p>
[ { "answer_id": 145945, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 6, "selected": true, "text": "jmap -dump:format=b,file=heap.bin <pid>\n jmap -histo <pid>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849/" ]
145,969
<p>I've got a sections table, and an items table.</p> <p>The problem is each item may be in one or more sections, so a simple 'section_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section_ids"...</p> <p>I've considered storing the list of ids as a comma separated string, the problem is I see no way to then check if an item is in a given section from the sql query. The only option I see here is to select the entire table, and parse the strings in php. Needless to say that with 1000's of items this isn't a good idea.</p> <p>Is there a better way to 'link' an item with multiple sections, and be able to easily select all items for a given section id?</p>
[ { "answer_id": 145985, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 0, "selected": false, "text": "Items - ItemsPerSection - Secion\nitemid <-> itemid\n sectionid <-> sectionid\n" }, { "answer_id": 146001, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": true, "text": "CREATE TABLE item_in_section (item_id int, section_id int)\n SELECT item.* from item, item_in_section WHERE item_in_section.item_id = item.item_id AND item_in_section.section_id = X GROUP BY item_id\n SELECT section.* from section, item_in_section WHERE item_in_section.section_id = section.section_id AND item_in_section.item_id = Y GROUP BY section_id\n" }, { "answer_id": 146002, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "items\nsections\nitemsections\n" }, { "answer_id": 146006, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "CREATE TABLE item_sections (\n ID datatype\n ITEM_ID datatype,\n SECTION_ID datatype);\n SELECT items.*\nFROM items, item_sections\nWHERE items.id = item_sections.item_id\nand item_sections.section_id = the-id-of the-section-you-want\n" }, { "answer_id": 146007, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "CREATE TABLE foos (\n id INTEGER,\n name VARCHAR\n)\n\nCREATE TABLE foo_sections (\n foo_id INTEGER,\n section_name VARCHAR,\n)\n\n-- Add some 'foos'\nINSERT INTO foos (1, 'Something');\nINSERT INTO foos (2, 'Something Else');\n\n-- Add some sections for each 'foo'\nINSERT INTO foo_sections (1, 'Section One');\nINSERT INTO foo_sections (1, 'Section Two');\nINSERT INTO foo_sections (2, 'Section One');\n\n-- To get all the section names for a specific 'foo' record:\nSELECT section_name FROM foo_sections WHERE foo_id = 1\n> Section One\n> Section Two\n" }, { "answer_id": 146010, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": -1, "selected": false, "text": "SELECT * FROM items WHERE FIND_IN_SET(5, section_id);\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
145,972
<p>I need to setup LookAndFeel Files in JDK 1.6. I have two files:</p> <ol> <li><p>napkinlaf-swingset2.jar</p></li> <li><p>napkinlaf.jar</p></li> </ol> <p>How can I set this up and use it?</p> <p>I would like a GTK look and feel OR Qt look and feel, Are they available?</p>
[ { "answer_id": 145996, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 3, "selected": false, "text": "java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp\n UIManager.setLookAndFeel(\"javax.swing.plaf.metal.MetalLookAndFeel\");\n com.sun.java.swing.plaf.gtk.GTKLookAndFeel\ncom.sun.java.swing.plaf.motif.MotifLookAndFeel\ncom.sun.java.swing.plaf.windows.WindowsLookAndFeel\n" }, { "answer_id": 146208, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": true, "text": "net.sourceforge.napkinlaf.NapkinLookAndFeel napkinlaf.jar lib/ext lib/swing.properties" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/145972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ]
146,020
<p>I'm doing some Android development, and I much prefer Visual Studio, but I'll have to use <em>Eclipse</em> for this.</p> <p>Has anyone made a tool which can make <em>Eclipse</em> look and behave more like visual studio? I mainly can't stand its <strong>clippyesqe</strong> suggestions on how I should program (Yes, I know I have not yet used that private field! Thanks Eclipse!), or its incredibly lousy <strong>intellisense</strong>.</p> <p>For example, in eclipse, if I don't type <code>this</code> first, its <strong>intellisense</strong> won't realise I want to look for locally scoped members. Also, the TAB to complete VS convention is drilled into my head, and <em>Eclipse</em> is ENTER to complete, I could switch everything by hand but that would take hours, and I was hoping someone had some sort of theme or something that has already done it.</p>
[ { "answer_id": 373079, "author": "jcollum", "author_id": 30946, "author_profile": "https://Stackoverflow.com/users/30946", "pm_score": 2, "selected": false, "text": "this.myString myString myString myString" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
146,038
<p>From time to time I browse the web and look for interesting algorithms and datastructures to put into my bag of tricks. A year ago I came across the <a href="http://en.wikipedia.org/wiki/Soft_heap" rel="noreferrer">Soft Heap</a> data-structure and learned about near sorting.</p> <p>The idea behind this is that it's possible to break the O(n log n) barrier of compare based sorts if you can live with the fact that the sort algorithm cheats a bit. You get a almost sorted list but you have to live with some errors as well.</p> <p>I played around with the algorithms in a test environement but never found a use for them. </p> <p>So the question: Has anyone ever used near sorting in practice? If so in which kind of applications? Can you think up a use-case where near sorting is the right thing to do? </p>
[ { "answer_id": 5814917, "author": "Ryan C. Thompson", "author_id": 125921, "author_profile": "https://Stackoverflow.com/users/125921", "pm_score": -1, "selected": false, "text": "sort nearsort" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
146,081
<p>I'm writing an interactive function that I'd like to have remember the last argument the user supplied and use it as the default. </p> <pre><code>(defun run-rake (param) (interactive "sTask: ") (shell-command (format "rake %s" task))) </code></pre> <p>The first time the function is invoked I want it to remember the argument the user supplied so that the next time they invoke the function they can just press enter and it will use the value they supplied the previous time.</p> <p>I can't seem to find this in the documentation - how do you do this in elisp?</p>
[ { "answer_id": 146139, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 0, "selected": false, "text": "(defvar *editconf-ruby-run-rake-last-rake-task* nil)\n\n(defun editconf-ruby-run-rake-last-rake-task (&optional new-val)\n (when new-val\n (setf *editconf-ruby-run-rake-last-rake-task* new-val))\n *editconf-ruby-run-rake-last-rake-task*)\n\n(defun editconf-ruby-run-rake (task-name)\n \"Execute rake `task-name'. See \n`krb-ruby-get-rakefile-path-for-current-buffer' for how the \nRakefile is located..\"\n (interactive\n (let* ((rakefile (krb-ruby-get-rakefile-path-for-current-buffer))\n (rake-tasks (krb-ruby-get-rake-tasks rakefile))\n (default-task (or (editconf-ruby-run-rake-last-rake-task)\n (editconf-ruby-run-rake-last-rake-task (car rake-tasks)))))\n (list\n (read-string (format \"Task [%s|%s]: \"\n rake-tasks\n default-task)\n nil nil default-task))))\n (editconf-ruby-run-rake-last-rake-task task-name)\n (let ((cmd (format \"cd %s; rake %s\"\n (krb-lisp-strip-path-suffix rakefile 1)\n task-name)))\n (message \"editconf-ruby-run-rake: cmd='%s'\" cmd)\n (shell-command cmd)))\n" }, { "answer_id": 146191, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 4, "selected": true, "text": "compile C-h f compile RETURN compile compile-command (let ((compile-command \"gcc -o foo foo.c frobnicate.c\"))\n ...\n (compile)\n ...)\n compile run-rake" }, { "answer_id": 150360, "author": "Trey Jackson", "author_id": 6148, "author_profile": "https://Stackoverflow.com/users/6148", "pm_score": 3, "selected": false, "text": "read-from-minibuffer\n (defvar run-rake-history nil \"History for run-rake\")\n(defun run-rake (cmd)\n(interactive (list (read-from-minibuffer \"Task: \" (car run-rake-history) nil nil 'run-rake-history)))\n (shell-command (format \"rake %s \" cmd)))\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ]
146,093
<p>I have several types of entities, each with their own fields, which are stored in separate tables.<br> Each record in such a table may be connected to zero or more records in a different table, i.e., linked to records from different entity types.<br> If I go with lookup tables, I get (m(m-1))/2=O(m^2) separate lookup tables that need to be initialized.<br> While still feasible for 6 or 7 different entity types, would it still be relevant for 50+ such types?<br> In particular, a given record would need to have links to most other entity types so theoretically speaking I would be dealing with a nearly-complete, non-directed, n-sided graph.<br> Can anyone shed some light on how to store this structure in a relational DBMS?<br> (I'm using Postgresql if it matters, but any solutions for other DBMS's would be equally helpful).<br> Thank you for your time!</p> <p>Yuval </p>
[ { "answer_id": 146165, "author": "Henning", "author_id": 7034, "author_profile": "https://Stackoverflow.com/users/7034", "pm_score": 2, "selected": false, "text": "CREATE TABLE base (\n id int(10) unsigned NOT NULL auto_increment,\n type enum('type1','type2') NOT NULL,\n PRIMARY KEY (id)\n);\n\nCREATE TABLE type1 (\n id int(10) unsigned NOT NULL,\n PRIMARY KEY (id),\n CONSTRAINT FK_type1_1 FOREIGN KEY (id) REFERENCES base (id)\n);\n\nCREATE TABLE type2 (\n id int(10) unsigned NOT NULL,\n PRIMARY KEY (id),\n CONSTRAINT FK_type2_1 FOREIGN KEY (id) REFERENCES base (id)\n);\n\n\nCREATE TABLE x_relations (\n from_id int(10) unsigned NOT NULL,\n to_id int(10) unsigned NOT NULL,\n PRIMARY KEY (from_id,to_id),\n KEY FK_x_relations_2 (to_id),\n CONSTRAINT FK_x_relations_1 FOREIGN KEY (from_id) REFERENCES base (id),\n CONSTRAINT FK_x_relations_2 FOREIGN KEY (to_id) REFERENCES base (id) \n ON DELETE CASCADE ON UPDATE CASCADE\n);\n type type1 type2" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23202/" ]
146,097
<p>Is there a prebuilt tool that would integrate with BEA/Oracle Weblogic 10.0 and trace on a database table each call to a web service exposed by the server?</p> <p>UPDATE: the goal is <strong>not</strong> to debug the web services (they are working well). The objective is to <strong>trace each call</strong> on a table, using an existing add-on.</p>
[ { "answer_id": 146165, "author": "Henning", "author_id": 7034, "author_profile": "https://Stackoverflow.com/users/7034", "pm_score": 2, "selected": false, "text": "CREATE TABLE base (\n id int(10) unsigned NOT NULL auto_increment,\n type enum('type1','type2') NOT NULL,\n PRIMARY KEY (id)\n);\n\nCREATE TABLE type1 (\n id int(10) unsigned NOT NULL,\n PRIMARY KEY (id),\n CONSTRAINT FK_type1_1 FOREIGN KEY (id) REFERENCES base (id)\n);\n\nCREATE TABLE type2 (\n id int(10) unsigned NOT NULL,\n PRIMARY KEY (id),\n CONSTRAINT FK_type2_1 FOREIGN KEY (id) REFERENCES base (id)\n);\n\n\nCREATE TABLE x_relations (\n from_id int(10) unsigned NOT NULL,\n to_id int(10) unsigned NOT NULL,\n PRIMARY KEY (from_id,to_id),\n KEY FK_x_relations_2 (to_id),\n CONSTRAINT FK_x_relations_1 FOREIGN KEY (from_id) REFERENCES base (id),\n CONSTRAINT FK_x_relations_2 FOREIGN KEY (to_id) REFERENCES base (id) \n ON DELETE CASCADE ON UPDATE CASCADE\n);\n type type1 type2" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23034/" ]
146,106
<p>This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.</p> <p>Does anyone have advice for how to organize the directives?</p> <ul> <li>Should I try to organize top-down, mimicking the DOM?</li> <li>Should I organize functionally, putting directives for elements that support the same parts of the UI together?</li> <li>Should I just sort everything alphabetically by selector?</li> <li>Some combination of these approaches?</li> </ul> <p>Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place?</p> <p>Related Question: <a href="http://web.archive.org/web/20170119044450/http://stackoverflow.com:80/questions/72911/whats-the-best-way-to-organize-css-rules" rel="noreferrer">What's the best way to organize CSS rules?</a></p>
[ { "answer_id": 146115, "author": "Nick Sergeant", "author_id": 22468, "author_profile": "https://Stackoverflow.com/users/22468", "pm_score": 2, "selected": false, "text": ".class {border: 1px solid #000; padding: 0; margin: 0;}\n" }, { "answer_id": 146122, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "* { /* css */ }\nbody { /* css */ }\n#wrapper { /* css */ }\n#innerwrapper { /* css */ }\n\n#content { /* css */ }\n#content div { /* css */ }\n#content span { /* css */ }\n#content etc { /* css */ }\n\n#header { /* css */ }\n#header etc { /* css */ }\n\n#footer { /* css */ }\n#footer etc { /* css */ }\n\n.class1 { /* css */ }\n.class2 { /* css */ }\n.class3 { /* css */ }\n.classn { /* css */ }\n" }, { "answer_id": 146339, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "reset.css design.css text.css ul li\n{\n margin-left: 10px;\n padding: 0;\n}\n rule { property: value; property: value; }\n\nrule { property: value; property: value; }\n" }, { "answer_id": 146497, "author": "allesklar", "author_id": 19893, "author_profile": "https://Stackoverflow.com/users/19893", "pm_score": 1, "selected": false, "text": "@import url(\"stylesheet-name/complete-reset.css\");\n@import url(\"stylesheet-name/colors.css\");\n@import url(\"stylesheet-name/structure.css\");\n@import url(\"stylesheet-name/html-tags.css\");\n@import url(\"stylesheet-name/menu-items.css\");\n@import url(\"stylesheet-name/portfolio.css\");\n@import url(\"stylesheet-name/error-messages.css\");\n <div/> <body/> <h1/> <p/>" }, { "answer_id": 146695, "author": "mercator", "author_id": 23263, "author_profile": "https://Stackoverflow.com/users/23263", "pm_score": 7, "selected": true, "text": "#content {\n /* css */\n}\n #content div {\n /* css */\n }\n #content span {\n /* css */\n }\n #content etc {\n /* css */\n }\n\n#header {\n /* css */\n}\n #header etc {\n /* css */\n }\n reset.css layout.css nav.css forms.css colors.css type.css/fonts.css base.css" }, { "answer_id": 15900770, "author": "Chris Spittles", "author_id": 493762, "author_profile": "https://Stackoverflow.com/users/493762", "pm_score": 3, "selected": false, "text": "header, container, menu, checkbox, input\n menu item, list item, checkbox caption, header title\n disabled, highlighted, checked, fixed, size big, color yellow\n /* Base */\n\n/* Layout */\n\n/* Modules */\n\n/* State */\n\n/* Theme */\n" }, { "answer_id": 46469290, "author": "htmlstrap", "author_id": 8620010, "author_profile": "https://Stackoverflow.com/users/8620010", "pm_score": -1, "selected": false, "text": "<link rel=\"stylesheet\" href=\"css/style.css\"> @import url(colors.css);\n@import url(grid.css);\n@import url(custom.css); + some more files (if needed)\n colors.css @import @import url(root/variable.css);\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ]
146,134
<p>I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?</p> <pre><code>using System; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string illegal = "\"M&lt;&gt;\"\\a/ry/ h**ad:&gt;&gt; a\\/:*?\"&lt;&gt;| li*tt|le|| la\"mb.?"; illegal = illegal.Trim(Path.GetInvalidFileNameChars()); illegal = illegal.Trim(Path.GetInvalidPathChars()); Console.WriteLine(illegal); Console.ReadLine(); } } } </code></pre>
[ { "answer_id": 146162, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 10, "selected": true, "text": "string illegal = \"\\\"M\\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\\"| li*tt|le|| la\\\"mb.?\";\nstring invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\n\nforeach (char c in invalid)\n{\n illegal = illegal.Replace(c.ToString(), \"\"); \n}\n string illegal = \"\\\"M\\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\\"| li*tt|le|| la\\\"mb.?\";\nstring regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\nRegex r = new Regex(string.Format(\"[{0}]\", Regex.Escape(regexSearch)));\nillegal = r.Replace(illegal, \"\");\n" }, { "answer_id": 146472, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 4, "selected": false, "text": "string regex = string.Format(\n \"[{0}]\",\n Regex.Escape(new string(Path.GetInvalidFileNameChars())));\nRegex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);\n" }, { "answer_id": 639368, "author": "mirezus", "author_id": 35286, "author_profile": "https://Stackoverflow.com/users/35286", "pm_score": 3, "selected": false, "text": "if ( fileName.IndexOfAny(Path.GetInvalidFileNameChars()) > -1 )\n {\n throw new ArgumentException();\n }\n" }, { "answer_id": 3970561, "author": "James", "author_id": 480739, "author_profile": "https://Stackoverflow.com/users/480739", "pm_score": 4, "selected": false, "text": "using System.IO;\nusing System.Text.RegularExpressions;\n\npublic static class PathValidation\n{\n private static string pathValidatorExpression = \"^[^\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + \"]+$\";\n private static Regex pathValidator = new Regex(pathValidatorExpression, RegexOptions.Compiled);\n\n private static string fileNameValidatorExpression = \"^[^\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + \"]+$\";\n private static Regex fileNameValidator = new Regex(fileNameValidatorExpression, RegexOptions.Compiled);\n\n private static string pathCleanerExpression = \"[\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + \"]\";\n private static Regex pathCleaner = new Regex(pathCleanerExpression, RegexOptions.Compiled);\n\n private static string fileNameCleanerExpression = \"[\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + \"]\";\n private static Regex fileNameCleaner = new Regex(fileNameCleanerExpression, RegexOptions.Compiled);\n\n public static bool ValidatePath(string path)\n {\n return pathValidator.IsMatch(path);\n }\n\n public static bool ValidateFileName(string fileName)\n {\n return fileNameValidator.IsMatch(fileName);\n }\n\n public static string CleanPath(string path)\n {\n return pathCleaner.Replace(path, \"\");\n }\n\n public static string CleanFileName(string fileName)\n {\n return fileNameCleaner.Replace(fileName, \"\");\n }\n}\n" }, { "answer_id": 4270832, "author": "Gregor Slavec", "author_id": 355257, "author_profile": "https://Stackoverflow.com/users/355257", "pm_score": 7, "selected": false, "text": "var invalidChars = Path.GetInvalidFileNameChars();\n\nvar invalidCharsRemoved = stringWithInvalidChars\n.Where(x => !invalidChars.Contains(x))\n.ToArray();\n var invalidChars = Path.GetInvalidFileNameChars();\n\nstring invalidCharsRemoved = new string(stringWithInvalidChars\n .Where(x => !invalidChars.Contains(x))\n .ToArray());\n" }, { "answer_id": 5004799, "author": "Jan", "author_id": 489772, "author_profile": "https://Stackoverflow.com/users/489772", "pm_score": 4, "selected": false, "text": "string regex = String.Format(\"[{0}]\", Regex.Escape(new string(Path.GetInvalidFileNameChars())));\nRegex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);\n" }, { "answer_id": 7393722, "author": "Michael Minton", "author_id": 1488979, "author_profile": "https://Stackoverflow.com/users/1488979", "pm_score": 8, "selected": false, "text": "private static string CleanFileName(string fileName)\n{\n return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));\n}\n" }, { "answer_id": 8152352, "author": "René", "author_id": 280392, "author_profile": "https://Stackoverflow.com/users/280392", "pm_score": 5, "selected": false, "text": "Path.GetInvalidFileNameChars Path.GetInvalidFileNameChars Path.GetInvalidPathChars" }, { "answer_id": 19064110, "author": "anomepani", "author_id": 2000410, "author_profile": "https://Stackoverflow.com/users/2000410", "pm_score": 4, "selected": false, "text": "public string RemoveSpecialCharacters(string str)\n{\n return Regex.Replace(str, \"[^a-zA-Z0-9_]+\", \"_\", RegexOptions.Compiled);\n}\n <asp:RegularExpressionValidator ID=\"regxFolderName\" \n runat=\"server\" \n ErrorMessage=\"Enter folder name with a-z A-Z0-9_\" \n ControlToValidate=\"txtFolderName\" \n Display=\"Dynamic\" \n ValidationExpression=\"^[a-zA-Z0-9_]*$\" \n ForeColor=\"Red\">\n" }, { "answer_id": 20049013, "author": "mbdavis", "author_id": 2310450, "author_profile": "https://Stackoverflow.com/users/2310450", "pm_score": 1, "selected": false, "text": "public static bool IsValidFilename(string testName)\n{\n return !new Regex(\"[\" + Regex.Escape(new String(System.IO.Path.GetInvalidFileNameChars())) + \"]\").IsMatch(testName);\n}\n" }, { "answer_id": 20441844, "author": "Johan Larsson", "author_id": 1069200, "author_profile": "https://Stackoverflow.com/users/1069200", "pm_score": 2, "selected": false, "text": "public static class FileUtility\n{\n private const char PrefixChar = '%';\n private static readonly int MaxLength;\n private static readonly Dictionary<char,char[]> Illegals;\n static FileUtility()\n {\n List<char> illegal = new List<char> { PrefixChar };\n illegal.AddRange(Path.GetInvalidFileNameChars());\n MaxLength = illegal.Select(x => ((int)x).ToString().Length).Max();\n Illegals = illegal.ToDictionary(x => x, x => ((int)x).ToString(\"D\" + MaxLength).ToCharArray());\n }\n\n public static string FilenameEncode(string s)\n {\n var builder = new StringBuilder();\n char[] replacement;\n using (var reader = new StringReader(s))\n {\n while (true)\n {\n int read = reader.Read();\n if (read == -1)\n break;\n char c = (char)read;\n if(Illegals.TryGetValue(c,out replacement))\n {\n builder.Append(PrefixChar);\n builder.Append(replacement);\n }\n else\n {\n builder.Append(c);\n }\n }\n }\n return builder.ToString();\n }\n\n public static string FilenameDecode(string s)\n {\n var builder = new StringBuilder();\n char[] buffer = new char[MaxLength];\n using (var reader = new StringReader(s))\n {\n while (true)\n {\n int read = reader.Read();\n if (read == -1)\n break;\n char c = (char)read;\n if (c == PrefixChar)\n {\n reader.Read(buffer, 0, MaxLength);\n var encoded =(char) ParseCharArray(buffer);\n builder.Append(encoded);\n }\n else\n {\n builder.Append(c);\n }\n }\n }\n return builder.ToString();\n }\n\n public static int ParseCharArray(char[] buffer)\n {\n int result = 0;\n foreach (char t in buffer)\n {\n int digit = t - '0';\n if ((digit < 0) || (digit > 9))\n {\n throw new ArgumentException(\"Input string was not in the correct format\");\n }\n result *= 10;\n result += digit;\n }\n return result;\n }\n}\n" }, { "answer_id": 21148541, "author": "Danny Fallas", "author_id": 2030347, "author_profile": "https://Stackoverflow.com/users/2030347", "pm_score": -1, "selected": false, "text": "[YOUR STRING].Replace('\\\\', ' ').Replace('/', ' ').Replace('\"', ' ').Replace('*', ' ').Replace(':', ' ').Replace('?', ' ').Replace('<', ' ').Replace('>', ' ').Replace('|', ' ').Trim();\n" }, { "answer_id": 21691953, "author": "Lily Finley", "author_id": 2453778, "author_profile": "https://Stackoverflow.com/users/2453778", "pm_score": 5, "selected": false, "text": "var cleanFileName = string.Join(\"\", fileName.Split(Path.GetInvalidFileNameChars()));\n var cleanPath = string.Join(\"\", path.Split(Path.GetInvalidPathChars()));\n" }, { "answer_id": 23182807, "author": "Shehab Fawzy", "author_id": 1093516, "author_profile": "https://Stackoverflow.com/users/1093516", "pm_score": 9, "selected": false, "text": "public string RemoveInvalidChars(string filename)\n{\n return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));\n}\n public string ReplaceInvalidChars(string filename)\n{\n return string.Join(\"_\", filename.Split(Path.GetInvalidFileNameChars())); \n}\n" }, { "answer_id": 25936980, "author": "mcintyre321", "author_id": 2086, "author_profile": "https://Stackoverflow.com/users/2086", "pm_score": 0, "selected": false, "text": " static string SanitiseFilename(string key)\n {\n var invalidChars = Path.GetInvalidFileNameChars();\n var sb = new StringBuilder();\n foreach (var c in key)\n {\n var invalidCharIndex = -1;\n for (var i = 0; i < invalidChars.Length; i++)\n {\n if (c == invalidChars[i])\n {\n invalidCharIndex = i;\n }\n }\n if (invalidCharIndex > -1)\n {\n sb.Append(\"_\").Append(invalidCharIndex);\n continue;\n }\n\n if (c == '_')\n {\n sb.Append(\"__\");\n continue;\n }\n\n sb.Append(c);\n }\n return sb.ToString();\n\n }\n" }, { "answer_id": 26148296, "author": "Maxence", "author_id": 200443, "author_profile": "https://Stackoverflow.com/users/200443", "pm_score": 3, "selected": false, "text": "<abc -> abc\n>abc -> abc\n public static string ReplaceInvalidFileNameChars(string s)\n{\n char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();\n foreach (char c in invalidFileNameChars)\n s = s.Replace(c.ToString(), \"[\" + Array.IndexOf(invalidFileNameChars, c) + \"]\");\n return s;\n}\n <abc -> [1]abc\n >abc -> [2]abc\n" }, { "answer_id": 28419584, "author": "Alexey F", "author_id": 410547, "author_profile": "https://Stackoverflow.com/users/410547", "pm_score": 3, "selected": false, "text": " private static readonly HashSet<char> invalidFileNameChars = new HashSet<char>(Path.GetInvalidFileNameChars());\n\n public static string RemoveInvalidFileNameChars(string name)\n {\n if (!name.Any(c => invalidFileNameChars.Contains(c))) {\n return name;\n }\n\n return new string(name.Where(c => !invalidFileNameChars.Contains(c)).ToArray());\n }\n" }, { "answer_id": 31264965, "author": "Suplanus", "author_id": 3559353, "author_profile": "https://Stackoverflow.com/users/3559353", "pm_score": 0, "selected": false, "text": "private static string CleanPath(string path)\n{\n string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\n Regex r = new Regex(string.Format(\"[{0}]\", Regex.Escape(regexSearch)));\n List<string> split = path.Split('\\\\').ToList();\n string returnValue = split.Aggregate(string.Empty, (current, s) => current + (r.Replace(s, \"\") + @\"\\\"));\n returnValue = returnValue.TrimEnd('\\\\');\n return returnValue;\n}\n" }, { "answer_id": 46106819, "author": "Daniel Scott", "author_id": 949129, "author_profile": "https://Stackoverflow.com/users/949129", "pm_score": 2, "selected": false, "text": "public static class PathExtensions\n{\n private static HashSet<char> _invalidFilenameChars;\n private static HashSet<char> InvalidFilenameChars\n {\n get { return _invalidFilenameChars ?? (_invalidFilenameChars = new HashSet<char>(Path.GetInvalidFileNameChars())); }\n }\n\n\n /// <summary>Replaces characters in <c>text</c> that are not allowed in file names with the \n /// specified replacement character.</summary>\n /// <param name=\"text\">Text to make into a valid filename. The same string is returned if \n /// it is valid already.</param>\n /// <param name=\"replacement\">Replacement character, or NULL to remove bad characters.</param>\n /// <param name=\"fancyReplacements\">TRUE to replace quotes and slashes with the non-ASCII characters ” and ⁄.</param>\n /// <returns>A string that can be used as a filename. If the output string would otherwise be empty, \"_\" is returned.</returns>\n public static string ToValidFilename(this string text, char? replacement = '_', bool fancyReplacements = false)\n {\n StringBuilder sb = new StringBuilder(text.Length);\n HashSet<char> invalids = InvalidFilenameChars;\n bool changed = false;\n\n for (int i = 0; i < text.Length; i++)\n {\n char c = text[i];\n if (invalids.Contains(c))\n {\n changed = true;\n char repl = replacement ?? '\\0';\n if (fancyReplacements)\n {\n if (c == '\"') repl = '”'; // U+201D right double quotation mark\n else if (c == '\\'') repl = '’'; // U+2019 right single quotation mark\n else if (c == '/') repl = '⁄'; // U+2044 fraction slash\n }\n if (repl != '\\0')\n sb.Append(repl);\n }\n else\n sb.Append(c);\n }\n\n if (sb.Length == 0)\n return \"_\";\n\n return changed ? sb.ToString() : text;\n }\n\n\n /// <summary>\n /// Returns TRUE if the specified path is a valid, local filesystem path.\n /// </summary>\n /// <param name=\"pathString\"></param>\n /// <returns></returns>\n public static bool IsValidLocalPath(this string pathString)\n {\n // From solution at https://stackoverflow.com/a/11636052/949129\n Uri pathUri;\n Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri);\n return isValidUri && pathUri != null && pathUri.IsLoopback;\n }\n}\n" }, { "answer_id": 48926264, "author": "aemre", "author_id": 4582867, "author_profile": "https://Stackoverflow.com/users/4582867", "pm_score": 2, "selected": false, "text": "public static class StringExtensions\n {\n public static string RemoveUnnecessary(this string source)\n {\n string result = string.Empty;\n string regex = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\n Regex reg = new Regex(string.Format(\"[{0}]\", Regex.Escape(regex)));\n result = reg.Replace(source, \"\");\n return result;\n }\n }\n" }, { "answer_id": 50851598, "author": "schoetbi", "author_id": 108238, "author_profile": "https://Stackoverflow.com/users/108238", "pm_score": 0, "selected": false, "text": "public static class FileNameCorrector\n{\n private static HashSet<char> invalid = new HashSet<char>(Path.GetInvalidFileNameChars());\n\n public static string ToValidFileName(this string name, char replacement = '\\0')\n {\n var builder = new StringBuilder();\n foreach (var cur in name)\n {\n if (cur > 31 && cur < 128 && !invalid.Contains(cur))\n {\n builder.Append(cur);\n }\n else if (replacement != '\\0')\n {\n builder.Append(replacement);\n }\n }\n\n return builder.ToString();\n }\n}\n" }, { "answer_id": 51518619, "author": "Backs", "author_id": 2910943, "author_profile": "https://Stackoverflow.com/users/2910943", "pm_score": 3, "selected": false, "text": "Path.GetInvalidPathChars() + # public static class FileNameExtensions\n{\n private static readonly Lazy<string[]> InvalidFileNameChars =\n new Lazy<string[]>(() => Path.GetInvalidPathChars()\n .Union(Path.GetInvalidFileNameChars()\n .Union(new[] { '+', '#' })).Select(c => c.ToString(CultureInfo.InvariantCulture)).ToArray());\n\n\n private static readonly HashSet<string> ProhibitedNames = new HashSet<string>\n {\n @\"aux\",\n @\"con\",\n @\"clock$\",\n @\"nul\",\n @\"prn\",\n\n @\"com1\",\n @\"com2\",\n @\"com3\",\n @\"com4\",\n @\"com5\",\n @\"com6\",\n @\"com7\",\n @\"com8\",\n @\"com9\",\n\n @\"lpt1\",\n @\"lpt2\",\n @\"lpt3\",\n @\"lpt4\",\n @\"lpt5\",\n @\"lpt6\",\n @\"lpt7\",\n @\"lpt8\",\n @\"lpt9\"\n };\n\n public static bool IsValidFileName(string fileName)\n {\n return !string.IsNullOrWhiteSpace(fileName)\n && fileName.All(o => !IsInvalidFileNameChar(o))\n && !IsProhibitedName(fileName);\n }\n\n public static bool IsProhibitedName(string fileName)\n {\n return ProhibitedNames.Contains(fileName.ToLower(CultureInfo.InvariantCulture));\n }\n\n private static string ReplaceInvalidFileNameSymbols([CanBeNull] this string value, string replacementValue)\n {\n if (value == null)\n {\n return null;\n }\n\n return InvalidFileNameChars.Value.Aggregate(new StringBuilder(value),\n (sb, currentChar) => sb.Replace(currentChar, replacementValue)).ToString();\n }\n\n public static bool IsInvalidFileNameChar(char value)\n {\n return InvalidFileNameChars.Value.Contains(value.ToString(CultureInfo.InvariantCulture));\n }\n\n public static string GetValidFileName([NotNull] this string value)\n {\n return GetValidFileName(value, @\"_\");\n }\n\n public static string GetValidFileName([NotNull] this string value, string replacementValue)\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(@\"value should be non empty\", nameof(value));\n }\n\n if (IsProhibitedName(value))\n {\n return (string.IsNullOrWhiteSpace(replacementValue) ? @\"_\" : replacementValue) + value; \n }\n\n return ReplaceInvalidFileNameSymbols(value, replacementValue);\n }\n\n public static string GetFileNameError(string fileName)\n {\n if (string.IsNullOrWhiteSpace(fileName))\n {\n return CommonResources.SelectReportNameError;\n }\n\n if (IsProhibitedName(fileName))\n {\n return CommonResources.FileNameIsProhibited;\n }\n\n var invalidChars = fileName.Where(IsInvalidFileNameChar).Distinct().ToArray();\n\n if(invalidChars.Length > 0)\n {\n return string.Format(CultureInfo.CurrentCulture,\n invalidChars.Length == 1 ? CommonResources.InvalidCharacter : CommonResources.InvalidCharacters,\n StringExtensions.JoinQuoted(@\",\", @\"'\", invalidChars.Select(c => c.ToString(CultureInfo.CurrentCulture))));\n }\n\n return string.Empty;\n }\n}\n GetValidFileName _" }, { "answer_id": 53576636, "author": "Zananok", "author_id": 1612470, "author_profile": "https://Stackoverflow.com/users/1612470", "pm_score": 2, "selected": false, "text": "public static string CleanIllegalName(string p_testName) => new Regex(string.Format(\"[{0}]\", Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars())))).Replace(p_testName, \"\");\n" }, { "answer_id": 61797980, "author": "Hans-Peter Kalb", "author_id": 13095025, "author_profile": "https://Stackoverflow.com/users/13095025", "pm_score": 0, "selected": false, "text": "public static string ReplaceIllegalFileChars(string FileNameWithoutPath, char ReplacementChar)\n{\n const string IllegalFileChars = \"*?/\\\\:<>|\\\"\";\n StringBuilder sb = new StringBuilder(FileNameWithoutPath.Length);\n char c;\n\n for (int i = 0; i < FileNameWithoutPath.Length; i++)\n {\n c = FileNameWithoutPath[i];\n if (IllegalFileChars.IndexOf(c) >= 0)\n {\n c = ReplacementChar;\n }\n sb.Append(c);\n }\n return (sb.ToString());\n}\n NewFileName = ReplaceIllegalFileChars(FileName, '_');\n" }, { "answer_id": 64121323, "author": "c-chavez", "author_id": 1042409, "author_profile": "https://Stackoverflow.com/users/1042409", "pm_score": 2, "selected": false, "text": "private static HashSet<char> _invalidCharsHash;\nprivate static HashSet<char> InvalidCharsHash\n{\n get { return _invalidCharsHash ?? (_invalidCharsHash = new HashSet<char>(Path.GetInvalidFileNameChars())); }\n}\n\nprivate static string ReplaceInvalidChars(string fileName, string newValue)\n{\n char newChar = newValue[0];\n\n char[] chars = fileName.ToCharArray();\n for (int i = 0; i < chars.Length; i++)\n {\n char c = chars[i];\n if (InvalidCharsHash.Contains(c))\n chars[i] = newChar;\n }\n\n return new string(chars);\n}\n string illegal = \"\\\"M<>\\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\\"<>| li*tt|le|| la\\\"mb.?\";\nstring legal = ReplaceInvalidChars(illegal);\n _M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n private static string RemoveInvalidChars(string fileName, string newValue)\n{\n char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];\n bool remove = newChar == char.MinValue;\n\n char[] chars = fileName.ToCharArray();\n char[] newChars = new char[chars.Length];\n int i2 = 0;\n for (int i = 0; i < chars.Length; i++)\n {\n char c = chars[i];\n if (InvalidCharsHash.Contains(c))\n {\n if (!remove)\n newChars[i2++] = newChar;\n }\n else\n newChars[i2++] = c;\n\n }\n\n return new string(newChars, 0, i2);\n}\n Test1 Test2 replacing with '_', 1000000 iterations ============Test1===============\nElapsed=00:00:01.6665595\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test2===============\nElapsed=00:00:01.7526835\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test3===============\nElapsed=00:00:05.2306227\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test4===============\nElapsed=00:00:14.8203696\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test5===============\nElapsed=00:00:01.8273760\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test6===============\nElapsed=00:00:05.4249985\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test7===============\nElapsed=00:00:07.5653833\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test8===============\nElapsed=00:12:23.1410106\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test9===============\nElapsed=00:00:02.1016708\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test10===============\nElapsed=00:00:05.0987225\nResult=M ary had a little lamb.\n\n============Test11===============\nElapsed=00:00:06.8004289\nResult=M ary had a little lamb.\n removing invalid chars, 1000000 iterations ============Test1===============\nElapsed=00:00:01.6945352\nResult= M a ry h ad a li tt le la mb.\n\n============Test2===============\nElapsed=00:00:01.4798049\nResult=M ary had a little lamb.\n\n============Test3===============\nElapsed=00:00:04.0415688\nResult=M ary had a little lamb.\n\n============Test4===============\nElapsed=00:00:14.3397960\nResult=M ary had a little lamb.\n\n============Test5===============\nElapsed=00:00:01.6782505\nResult=M ary had a little lamb.\n\n============Test6===============\nElapsed=00:00:04.9251707\nResult=M ary had a little lamb.\n\n============Test7===============\nElapsed=00:00:07.9562379\nResult=M ary had a little lamb.\n\n============Test8===============\nElapsed=00:12:16.2918943\nResult=M ary had a little lamb.\n\n============Test9===============\nElapsed=00:00:02.0770277\nResult=M ary had a little lamb.\n\n============Test10===============\nElapsed=00:00:05.2721232\nResult=M ary had a little lamb.\n\n============Test11===============\nElapsed=00:00:05.2802903\nResult=M ary had a little lamb.\n Test1 Test2 Test5 Test8 private static HashSet<char> _invalidCharsHash;\nprivate static HashSet<char> InvalidCharsHash\n{\n get { return _invalidCharsHash ?? (_invalidCharsHash = new HashSet<char>(Path.GetInvalidFileNameChars())); }\n}\n\nprivate static string _invalidCharsValue;\nprivate static string InvalidCharsValue\n{\n get { return _invalidCharsValue ?? (_invalidCharsValue = new string(Path.GetInvalidFileNameChars())); }\n}\n\nprivate static char[] _invalidChars;\nprivate static char[] InvalidChars\n{\n get { return _invalidChars ?? (_invalidChars = Path.GetInvalidFileNameChars()); }\n}\n\nstatic void Main(string[] args)\n{\n string testPath = \"\\\"M <>\\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\\"<>| li*tt|le|| la\\\"mb.?\";\n\n int max = 1000000;\n string newValue = \"\";\n\n TimeBenchmark(max, Test1, testPath, newValue);\n TimeBenchmark(max, Test2, testPath, newValue);\n TimeBenchmark(max, Test3, testPath, newValue);\n TimeBenchmark(max, Test4, testPath, newValue);\n TimeBenchmark(max, Test5, testPath, newValue);\n TimeBenchmark(max, Test6, testPath, newValue);\n TimeBenchmark(max, Test7, testPath, newValue);\n TimeBenchmark(max, Test8, testPath, newValue);\n TimeBenchmark(max, Test9, testPath, newValue);\n TimeBenchmark(max, Test10, testPath, newValue);\n TimeBenchmark(max, Test11, testPath, newValue);\n\n Console.Read();\n}\n\nprivate static void TimeBenchmark(int maxLoop, Func<string, string, string> func, string testString, string newValue)\n{\n var sw = new Stopwatch();\n sw.Start();\n string result = string.Empty;\n\n for (int i = 0; i < maxLoop; i++)\n result = func?.Invoke(testString, newValue);\n\n sw.Stop();\n\n Console.WriteLine($\"============{func.Method.Name}===============\");\n Console.WriteLine(\"Elapsed={0}\", sw.Elapsed);\n Console.WriteLine(\"Result={0}\", result);\n Console.WriteLine(\"\");\n}\n\nprivate static string Test1(string fileName, string newValue)\n{\n char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];\n\n char[] chars = fileName.ToCharArray();\n for (int i = 0; i < chars.Length; i++)\n {\n if (InvalidCharsHash.Contains(chars[i]))\n chars[i] = newChar;\n }\n\n return new string(chars);\n}\n\nprivate static string Test2(string fileName, string newValue)\n{\n char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];\n bool remove = newChar == char.MinValue;\n\n char[] chars = fileName.ToCharArray();\n char[] newChars = new char[chars.Length];\n int i2 = 0;\n for (int i = 0; i < chars.Length; i++)\n {\n char c = chars[i];\n if (InvalidCharsHash.Contains(c))\n {\n if (!remove)\n newChars[i2++] = newChar;\n }\n else\n newChars[i2++] = c;\n\n }\n\n return new string(newChars, 0, i2);\n}\n\nprivate static string Test3(string filename, string newValue)\n{\n foreach (char c in InvalidCharsValue)\n {\n filename = filename.Replace(c.ToString(), newValue);\n }\n\n return filename;\n}\n\nprivate static string Test4(string filename, string newValue)\n{\n Regex r = new Regex(string.Format(\"[{0}]\", Regex.Escape(InvalidCharsValue)));\n filename = r.Replace(filename, newValue);\n return filename;\n}\n\nprivate static string Test5(string filename, string newValue)\n{\n return string.Join(newValue, filename.Split(InvalidChars));\n}\n\nprivate static string Test6(string fileName, string newValue)\n{\n return InvalidChars.Aggregate(fileName, (current, c) => current.Replace(c.ToString(), newValue));\n}\n\nprivate static string Test7(string fileName, string newValue)\n{\n string regex = string.Format(\"[{0}]\", Regex.Escape(InvalidCharsValue));\n return Regex.Replace(fileName, regex, newValue, RegexOptions.Compiled);\n}\n\nprivate static string Test8(string fileName, string newValue)\n{\n string regex = string.Format(\"[{0}]\", Regex.Escape(InvalidCharsValue));\n Regex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);\n return removeInvalidChars.Replace(fileName, newValue);\n}\n\nprivate static string Test9(string fileName, string newValue)\n{\n StringBuilder sb = new StringBuilder(fileName.Length);\n bool changed = false;\n\n for (int i = 0; i < fileName.Length; i++)\n {\n char c = fileName[i];\n if (InvalidCharsHash.Contains(c))\n {\n changed = true;\n sb.Append(newValue);\n }\n else\n sb.Append(c);\n }\n\n if (sb.Length == 0)\n return newValue;\n\n return changed ? sb.ToString() : fileName;\n}\n\nprivate static string Test10(string fileName, string newValue)\n{\n if (!fileName.Any(c => InvalidChars.Contains(c)))\n {\n return fileName;\n }\n\n return new string(fileName.Where(c => !InvalidChars.Contains(c)).ToArray());\n}\n\nprivate static string Test11(string fileName, string newValue)\n{\n string invalidCharsRemoved = new string(fileName\n .Where(x => !InvalidChars.Contains(x))\n .ToArray());\n\n return invalidCharsRemoved;\n}\n" }, { "answer_id": 64495739, "author": "Fabske", "author_id": 667449, "author_profile": "https://Stackoverflow.com/users/667449", "pm_score": 2, "selected": false, "text": "StringHelper.RemoveInvalidCharacters 1: 451 ms \nStringHelper.RemoveInvalidCharacters 2: 7139 ms \nStringHelper.RemoveInvalidCharacters 3: 2447 ms \nStringHelper.RemoveInvalidCharacters 4: 3733 ms \nStringHelper.RemoveInvalidCharacters 5: 11689 ms (==> Regex!)\n public static string RemoveInvalidCharacters(string content, char replace = '_', bool doNotReplaceBackslashes = false)\n{\n if (string.IsNullOrEmpty(content))\n return content;\n\n var idx = content.IndexOfAny(InvalidCharacters);\n if (idx >= 0)\n {\n var sb = new StringBuilder(content);\n while (idx >= 0)\n {\n if (sb[idx] != '\\\\' || !doNotReplaceBackslashes)\n sb[idx] = replace;\n idx = content.IndexOfAny(InvalidCharacters, idx+1);\n }\n return sb.ToString();\n }\n return content;\n}\n InvalidCharacters" }, { "answer_id": 66053014, "author": "Simant", "author_id": 649384, "author_profile": "https://Stackoverflow.com/users/649384", "pm_score": 2, "selected": false, "text": " public static class StringExtension\n {\n public static string RemoveInvalidChars(this string originalString)\n { \n string finalString=string.Empty;\n if (!string.IsNullOrEmpty(originalString))\n {\n return string.Concat(originalString.Split(Path.GetInvalidFileNameChars()));\n }\n return finalString; \n }\n }\n string illegal = \"\\\"M<>\\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\\"<>| li*tt|le|| la\\\"mb.?\";\nstring afterIllegalChars = illegal.RemoveInvalidChars();\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
146,140
<p>I have an OpenGL RGBA texture and I blit another RGBA texture onto it using a framebuffer object. The problem is that if I use the usual blend functions with <code>glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),</code> the resulting blit causes the destination texture alpha to change, making it slightly transparent for places where alpha previously was 1. I would like the destination surface alpha never to change, but otherwise the effect on RGB values should be exactly like with <code>GL_SRC_ALPHA</code> and <code>GL_ONE_MINUS_SRC_ALPHA</code>. So the blend factor functions should be (As,As,As,0) and (1-As,1-As,1-As,1). How can I achieve that?</p>
[ { "answer_id": 146161, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 4, "selected": true, "text": "void glBlendFuncSeparate(\n GLenum srcRGB, \n GLenum dstRGB, \n GLenum srcAlpha, \n GLenum dstAlpha);\n glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);\n void glColorMask( GLboolean red,\n GLboolean green,\n GLboolean blue,\n GLboolean alpha )\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
146,153
<p>I need to randomly fade my background images in and out.</p> <p>It will be a timed function, like once every 5 seconds.<br> I need to do it with ASP.NET, Javascript, CSS or all three.</p> <p>Please help me out here guys. Thank you.</p>
[ { "answer_id": 146181, "author": "SpoiledTechie.com", "author_id": 7644, "author_profile": "https://Stackoverflow.com/users/7644", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n<!--\nThis file retrieved from the JS-Examples archives\nhttp://www.js-examples.com\n1000s of free ready to use scripts, tutorials, forums.\nAuthor: Steve S - http://jsmadeeasy.com/ \n-->\n\n<style>\nbody\n{\n/*Remove below line to make bgimage NOT fixed*/\nbackground-attachment:fixed;\nbackground-repeat: no-repeat;\n/*Use center center in place of 300 200 to center bg image*/\nbackground-position: 300 200;\n}\n</style>\n\n<script language=\"JavaScript1.2\">\n/* you must supply your own immages */\nvar bgimages=new Array()\nbgimages[0]=\"http://js-examples.com/images/blue_ball0.gif\"\nbgimages[1]=\"http://js-examples.com/images/red_ball0.gif\"\nbgimages[2]=\"http://js-examples.com/images/green_ball0.gif\"\n\n//preload images\nvar pathToImg=new Array()\nfor (i=0;i<bgimages.length;i++)\n{\n pathToImg[i]=new Image()\n pathToImg[i].src=bgimages[i]\n}\n\nvar inc=-1\n\nfunction bgSlide()\n{\n if (inc<bgimages.length-1)\n inc++\n else\n inc=0\n document.body.background=pathToImg[inc].src\n}\n\nif (document.all||document.getElementById)\n window.onload=new Function('setInterval(\"bgSlide()\",3000)')\n</script>\n\n</head>\n<body>\n<BR><center><a href='http://www.js-examples.com'>JS-Examples.com</a></center> \n</body>\n</html>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
146,159
<p>From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have.</p> <p>If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious.</p>
[ { "answer_id": 146186, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 10, "selected": true, "text": "void transform (float *output, float const * input, float const * matrix, int *n)\n{\n int i;\n for (i=0; i<*n; i++)\n {\n float x = input[i*2+0];\n float y = input[i*2+1];\n output[i*2+0] = matrix[0] * x + matrix[1] * y;\n output[i*2+1] = matrix[2] * x + matrix[3] * y;\n }\n}\n int restrict double* int* char* void* restrict CALL TRANSFORM(A(1, 30), A(2, 31), A(3, 32), 30)" }, { "answer_id": 146197, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 3, "selected": false, "text": "strcpy(char *d, const char* s)\n{\n while(*d++ = *s++);\n}\n" }, { "answer_id": 146221, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 5, "selected": false, "text": "struct { double re; double im; };" }, { "answer_id": 397151, "author": "user49734", "author_id": 49734, "author_profile": "https://Stackoverflow.com/users/49734", "pm_score": 6, "selected": false, "text": "matmul(a,b)\n sqrt(sum(x**2))\n FORALL PURE ELEMENTAL" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18687/" ]
146,204
<p>Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like:</p> <pre><code>Dictionary&lt;string, List&lt;object&gt;&gt; </code></pre> <p>But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET.</p>
[ { "answer_id": 146213, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 4, "selected": false, "text": "List<KeyValuePair<object, object>>" }, { "answer_id": 146227, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "Lookup Lookup Enumerable.ToLookup" }, { "answer_id": 146651, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 4, "selected": false, "text": "Lookup(TKey, TElement) ToLookup IEnumerable(T) Lookup(TKey, TElement) Lookup(TKey, TElement) Lookup(TKey, TElement)" }, { "answer_id": 841778, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();\n\n// add some values to the collection here\n\nfor (int i = 0; i < list.Count; i++)\n{\n Print(list[i].Key, list[i].Value);\n}\n" }, { "answer_id": 2929123, "author": "Dan", "author_id": 352915, "author_profile": "https://Stackoverflow.com/users/352915", "pm_score": 2, "selected": false, "text": "Dictionary<string, List<object>> MultiMap Code Project" }, { "answer_id": 6099928, "author": "Sintrinsic", "author_id": 766343, "author_profile": "https://Stackoverflow.com/users/766343", "pm_score": 1, "selected": false, "text": " class DKD {\n List<Dictionary<string, string>> dictionaries;\n public DKD(){\n dictionaries = new List<Dictionary<string, string>>();}\n public object this[string key]{\n get{\n string temp;\n List<string> valueList = new List<string>();\n for (int i = 0; i < dictionaries.Count; i++){\n dictionaries[i].TryGetValue(key, out temp);\n if (temp == key){\n valueList.Add(temp);}}\n return valueList;}\n set{\n for (int i = 0; i < dictionaries.Count; i++){\n if (dictionaries[i].ContainsKey(key)){\n continue;}\n else{\n dictionaries[i].Add(key,(string) value);\n return;}}\n dictionaries.Add(new Dictionary<string, string>());\n dictionaries.Last()[key] =(string)value;\n }\n }\n }\n" }, { "answer_id": 6749925, "author": "Greg", "author_id": 852342, "author_profile": "https://Stackoverflow.com/users/852342", "pm_score": 2, "selected": false, "text": "List<KeyValuePair<string, object>> List<KeyValuePair<string, object>> myList = new List<KeyValuePair<string, object>>();\n//fill it here\nvar q = from a in myList Where a.Key.Equals(\"somevalue\") Select a.Value\nif(q.Count() > 0){ //you've got your value }\n" }, { "answer_id": 9844443, "author": "Hector Correa", "author_id": 446681, "author_profile": "https://Stackoverflow.com/users/446681", "pm_score": 6, "selected": false, "text": "public class ListWithDuplicates : List<KeyValuePair<string, string>>\n{\n public void Add(string key, string value)\n {\n var element = new KeyValuePair<string, string>(key, value);\n this.Add(element);\n }\n}\n\nvar list = new ListWithDuplicates();\nlist.Add(\"k1\", \"v1\");\nlist.Add(\"k1\", \"v2\");\nlist.Add(\"k1\", \"v3\");\n\nforeach(var item in list)\n{\n string x = string.format(\"{0}={1}, \", item.Key, item.Value);\n}\n" }, { "answer_id": 10056923, "author": "Stefan Mielke", "author_id": 1319421, "author_profile": "https://Stackoverflow.com/users/1319421", "pm_score": 2, "selected": false, "text": "Dictionary<string, List<string>> List<string> value = new List<string>();\nif (dictionary.Contains(key)) {\n value = dictionary[key];\n}\nvalue.Add(newValue);\n" }, { "answer_id": 12000452, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "Tuple // declaration\nvar list = new List<Tuple<string, List<object>>>();\n\n// to add an item to the list\nvar item = Tuple<string, List<object>>(\"key\", new List<object>);\nlist.Add(item);\n\n// to iterate\nforeach(var i in list)\n{\n Console.WriteLine(i.Item1.ToString());\n}\n" }, { "answer_id": 29736005, "author": "shan", "author_id": 4808087, "author_profile": "https://Stackoverflow.com/users/4808087", "pm_score": -1, "selected": false, "text": "Dictionary<string, string[]> previousAnswers = null;\n" }, { "answer_id": 30438792, "author": "Alireza Esrari", "author_id": 4182361, "author_profile": "https://Stackoverflow.com/users/4182361", "pm_score": -1, "selected": false, "text": "private string keyBuilder(int key1, int key2)\n{\n return string.Format(\"{0}/{1}\", key1, key2);\n}\n myDict.ContainsKey(keyBuilder(key1, key2))\n" }, { "answer_id": 36466344, "author": "ChristopheD", "author_id": 81179, "author_profile": "https://Stackoverflow.com/users/81179", "pm_score": 3, "selected": false, "text": "IDictionary<T> public class MultiMap<TKey,TValue>\n{\n private readonly Dictionary<TKey,IList<TValue>> storage;\n\n public MultiMap()\n {\n storage = new Dictionary<TKey,IList<TValue>>();\n }\n\n public void Add(TKey key, TValue value)\n {\n if (!storage.ContainsKey(key)) storage.Add(key, new List<TValue>());\n storage[key].Add(value);\n }\n\n public IEnumerable<TKey> Keys\n {\n get { return storage.Keys; }\n }\n\n public bool ContainsKey(TKey key)\n {\n return storage.ContainsKey(key);\n }\n\n public IList<TValue> this[TKey key]\n {\n get\n {\n if (!storage.ContainsKey(key))\n throw new KeyNotFoundException(\n string.Format(\n \"The given key {0} was not found in the collection.\", key));\n return storage[key];\n }\n }\n}\n const string key = \"supported_encodings\";\nvar map = new MultiMap<string,Encoding>();\nmap.Add(key, Encoding.ASCII);\nmap.Add(key, Encoding.UTF8);\nmap.Add(key, Encoding.Unicode);\n\nforeach (var existingKey in map.Keys)\n{\n var values = map[existingKey];\n Console.WriteLine(string.Join(\",\", values));\n}\n" }, { "answer_id": 47529046, "author": "Ali Yousefi", "author_id": 948236, "author_profile": "https://Stackoverflow.com/users/948236", "pm_score": 0, "selected": false, "text": "public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable\n{\n private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();\n private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();\n\n public ICollection<T1> Keys\n {\n get\n {\n return _keyValue.Keys;\n }\n }\n\n public ICollection<T2> Values\n {\n get\n {\n return _valueKey.Keys;\n }\n }\n\n public int Count\n {\n get\n {\n return _keyValue.Count;\n }\n }\n\n public bool IsReadOnly\n {\n get\n {\n return false;\n }\n }\n\n public List<T2> this[T1 index]\n {\n get { return _keyValue[index]; }\n set { _keyValue[index] = value; }\n }\n\n public List<T1> this[T2 index]\n {\n get { return _valueKey[index]; }\n set { _valueKey[index] = value; }\n }\n\n public void Add(T1 key, T2 value)\n {\n lock (this)\n {\n if (!_keyValue.TryGetValue(key, out List<T2> result))\n _keyValue.TryAdd(key, new List<T2>() { value });\n else if (!result.Contains(value))\n result.Add(value);\n\n if (!_valueKey.TryGetValue(value, out List<T1> result2))\n _valueKey.TryAdd(value, new List<T1>() { key });\n else if (!result2.Contains(key))\n result2.Add(key);\n }\n }\n\n public bool TryGetValues(T1 key, out List<T2> value)\n {\n return _keyValue.TryGetValue(key, out value);\n }\n\n public bool TryGetKeys(T2 value, out List<T1> key)\n {\n return _valueKey.TryGetValue(value, out key);\n }\n\n public bool ContainsKey(T1 key)\n {\n return _keyValue.ContainsKey(key);\n }\n\n public bool ContainsValue(T2 value)\n {\n return _valueKey.ContainsKey(value);\n }\n\n public void Remove(T1 key)\n {\n lock (this)\n {\n if (_keyValue.TryRemove(key, out List<T2> values))\n {\n foreach (var item in values)\n {\n var remove2 = _valueKey.TryRemove(item, out List<T1> keys);\n }\n }\n }\n }\n\n public void Remove(T2 value)\n {\n lock (this)\n {\n if (_valueKey.TryRemove(value, out List<T1> keys))\n {\n foreach (var item in keys)\n {\n var remove2 = _keyValue.TryRemove(item, out List<T2> values);\n }\n }\n }\n }\n\n public void Clear()\n {\n _keyValue.Clear();\n _valueKey.Clear();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return _keyValue.GetEnumerator();\n }\n}\n public class TestA\n{\n public int MyProperty { get; set; }\n}\n\npublic class TestB\n{\n public int MyProperty { get; set; }\n}\n\n HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();\n\n var a = new TestA() { MyProperty = 9999 };\n var b = new TestB() { MyProperty = 60 };\n var b2 = new TestB() { MyProperty = 5 };\n hashMapDictionary.Add(a, b);\n hashMapDictionary.Add(a, b2);\n hashMapDictionary.TryGetValues(a, out List<TestB> result);\n foreach (var item in result)\n {\n //do something\n }\n" }, { "answer_id": 50105713, "author": "Slate", "author_id": 2983132, "author_profile": "https://Stackoverflow.com/users/2983132", "pm_score": 1, "selected": false, "text": " public static class ListWithDuplicateExtensions\n {\n public static void Add<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)\n {\n var element = new KeyValuePair<TKey, TValue>(key, value);\n collection.Add(element);\n }\n\n public static int TryGetValue<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, out IEnumerable<TValue> values)\n {\n values = collection.Where(pair => pair.Key.Equals(key)).Select(pair => pair.Value);\n return values.Count();\n }\n }\n" }, { "answer_id": 56185457, "author": "John", "author_id": 1197590, "author_profile": "https://Stackoverflow.com/users/1197590", "pm_score": 0, "selected": false, "text": "public class ListMap<T,V> : List<KeyValuePair<T, V>>\n{\n public void Add(T key, V value) {\n Add(new KeyValuePair<T, V>(key, value));\n }\n\n public List<V> Get(T key) {\n return FindAll(p => p.Key.Equals(key)).ConvertAll(p=> p.Value);\n }\n}\n var fruits = new ListMap<int, string>();\nfruits.Add(1, \"apple\");\nfruits.Add(1, \"orange\");\nvar c = fruits.Get(1).Count; //c = 2;\n" }, { "answer_id": 58571875, "author": "Alexander Tolstikov", "author_id": 5050824, "author_profile": "https://Stackoverflow.com/users/5050824", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Dictionary which supports duplicates and null entries\n/// </summary>\n/// <typeparam name=\"TKey\">Type of key</typeparam>\n/// <typeparam name=\"TValue\">Type of items</typeparam>\npublic class OpenDictionary<TKey, TValue>\n{\n private readonly Lazy<List<TValue>> _nullStorage = new Lazy<List<TValue>>(\n () => new List<TValue>());\n\n private readonly Dictionary<TKey, List<TValue>> _innerDictionary =\n new Dictionary<TKey, List<TValue>>();\n\n /// <summary>\n /// Get all entries\n /// </summary>\n public IEnumerable<TValue> Values =>\n _innerDictionary.Values\n .SelectMany(x => x)\n .Concat(_nullStorage.Value);\n\n /// <summary>\n /// Add an item\n /// </summary>\n public OpenDictionary<TKey, TValue> Add(TKey key, TValue item)\n {\n if (ReferenceEquals(key, null))\n _nullStorage.Value.Add(item);\n else\n {\n if (!_innerDictionary.ContainsKey(key))\n _innerDictionary.Add(key, new List<TValue>());\n\n _innerDictionary[key].Add(item);\n }\n\n return this;\n }\n\n /// <summary>\n /// Remove an entry by key\n /// </summary>\n public OpenDictionary<TKey, TValue> RemoveEntryByKey(TKey key, TValue entry)\n {\n if (ReferenceEquals(key, null))\n {\n int targetIdx = _nullStorage.Value.FindIndex(x => x.Equals(entry));\n if (targetIdx < 0)\n return this;\n\n _nullStorage.Value.RemoveAt(targetIdx);\n }\n else\n {\n if (!_innerDictionary.ContainsKey(key))\n return this;\n\n List<TValue> targetChain = _innerDictionary[key];\n if (targetChain.Count == 0)\n return this;\n\n int targetIdx = targetChain.FindIndex(x => x.Equals(entry));\n if (targetIdx < 0)\n return this;\n\n targetChain.RemoveAt(targetIdx);\n }\n\n return this;\n }\n\n /// <summary>\n /// Remove all entries by key\n /// </summary>\n public OpenDictionary<TKey, TValue> RemoveAllEntriesByKey(TKey key)\n {\n if (ReferenceEquals(key, null))\n {\n if (_nullStorage.IsValueCreated)\n _nullStorage.Value.Clear();\n } \n else\n {\n if (_innerDictionary.ContainsKey(key))\n _innerDictionary[key].Clear();\n }\n\n return this;\n }\n\n /// <summary>\n /// Try get entries by key\n /// </summary>\n public bool TryGetEntries(TKey key, out IReadOnlyList<TValue> entries)\n {\n entries = null;\n\n if (ReferenceEquals(key, null))\n {\n if (_nullStorage.IsValueCreated)\n {\n entries = _nullStorage.Value;\n return true;\n }\n else return false;\n }\n else\n {\n if (_innerDictionary.ContainsKey(key))\n {\n entries = _innerDictionary[key];\n return true;\n }\n else return false;\n }\n }\n}\n var dictionary = new OpenDictionary<string, int>();\ndictionary.Add(\"1\", 1); \n// The next line won't throw an exception; \ndictionary.Add(\"1\", 2);\n\ndictionary.TryGetEntries(\"1\", out List<int> result); \n// result is { 1, 2 }\n\ndictionary.Add(null, 42);\ndictionary.Add(null, 24);\ndictionary.TryGetEntries(null, out List<int> result); \n// result is { 42, 24 }\n" }, { "answer_id": 59055761, "author": "reniasa", "author_id": 6938051, "author_profile": "https://Stackoverflow.com/users/6938051", "pm_score": 4, "selected": false, "text": "var duplicatedDictionaryExample = new List<(string Key, string Value)> { (\"\", \"\") ... }\n foreach(var entry in duplicatedDictionaryExample)\n{ \n // do something with the values\n entry.Key;\n entry.Value;\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
146,212
<p>I have a table of "items", and a table of "itemkeywords". When a user searches for a keyword, I want to give him one page of results plus the total number of results.</p> <p>What I'm doing currently is (for a user that searches "a b c": </p> <pre><code>SELECT DISTINCT {fields I want} FROM itemkeywords JOIN items WHERE (keyword = 'a' or keyword='b' or keyword='c' ORDER BY "my magic criteria" LIMIT 20.10 </code></pre> <p>and then I do the same query with a count</p> <pre><code>SELECT COUNT(*) FROM itemkeywords JOIN items WHERE (keyword = 'a' or keyword='b' or keyword='c' </code></pre> <p>This may get to get a fairly large table, and I consider this solution suck enormously...<br> But I can't think of anything much better.</p> <p>The obvious alternative to avoid hitting MySQL twice , which is doing the first query only, without the LIMIT clause, and then navigating to the correct record to show the corresponding page, and then to the end of the recordset in order to count the result seems even worse...</p> <p>Any ideas?</p> <p>NOTE: I'm using ASP.Net and MySQL, not PHP</p>
[ { "answer_id": 146229, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": true, "text": "mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name\n -> WHERE id > 100 LIMIT 10;\nmysql> SELECT FOUND_ROWS();\n" }, { "answer_id": 146233, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT {fields I want}, count(*) as results \n FROM itemkeywords JOIN items \n WHERE (keyword = 'a' or keyword='b' or keyword='c'\n ORDER BY \"my magic criteria\"\n LIMIT 20.10\n DESCRIBE" }, { "answer_id": 146234, "author": "dajobe", "author_id": 11177, "author_profile": "https://Stackoverflow.com/users/11177", "pm_score": 0, "selected": false, "text": "SQL_CALC_FOUND_ROWS SELECT FOUND_ROWS()" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
146,230
<p>In Nant, I would like to be able to extract the last name of the directory in a path.<br> For example, we have the path 'c:\my_proj\source\test.my_dll\'</p> <p>I would like to pass in that path and extract 'test.my_dll'</p> <p>Is there a way to easily do this?</p>
[ { "answer_id": 14837268, "author": "Paul'OS", "author_id": 2065512, "author_profile": "https://Stackoverflow.com/users/2065512", "pm_score": 2, "selected": false, "text": "<property name=\"some.dir\" value=\"c:\\my_proj\\source\\test.my_dll\" />\n<property name=\"some.dir.parent\" value=\"${directory::get-parent-directory(some.dir)}\" />\n<property name=\"directory\" value=\"${string::replace(some.dir, some.dir.parent + '\\', '') }\" />\n" }, { "answer_id": 24349114, "author": "Nikhil Gupta", "author_id": 2279816, "author_profile": "https://Stackoverflow.com/users/2279816", "pm_score": 1, "selected": false, "text": "directory::get-name(path) path" }, { "answer_id": 26300485, "author": "yoroto", "author_id": 1691568, "author_profile": "https://Stackoverflow.com/users/1691568", "pm_score": 3, "selected": false, "text": "${string::substring(path, string::last-index-of(path, '\\') + 1, string::get-length(path) - string::last-index-of(path, '\\') - 1)}\n" }, { "answer_id": 35912245, "author": "Frank Rem", "author_id": 450467, "author_profile": "https://Stackoverflow.com/users/450467", "pm_score": 0, "selected": false, "text": "<script language=\"C#\" prefix=\"path\" >\n <code>\n <![CDATA[\n [Function(\"get-dir-name\")]\n public static string GetDirName(string path) {\n return System.IO.Path.GetFileName(path);\n }\n ]]>\n </code>\n </script>\n\n<target name=\"build\">\n <foreach item=\"Folder\" in=\".\" property=\"path\">\n <echo message=\"${path::get-dir-name(path)}\" />\n </foreach>\n</target>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
146,250
<p>Should I push keypresses to vehicles when they're pressed, or should vehicles pull keys pressed from the engine?</p> <p>I have a vehicle object, which has location, velocity and accelleration members (among other things) and an update method, during which it updates its location based on its velocity, and its vevlocity based on its accelleration.</p> <p>I have a game object which contains the game loop, which calls the update method on the vehicle.</p> <p>If the player controls the vehicle with the arrow keys, should a keypress set the accelleration (push) and a key-release clear the velocity, or should the vehicle ask the game-engine if the accellerate key is pressed (pull)? I think a push would mean that the keyboard control module would need to know about vehicles, whereas pull would mean a vehicle needs to know specific keyboard controls.</p> <p>I think a related question would be something like: should all objects know about all other objects, or should there be a strict hierarchy, so objects can ask things / tell things to other objects up the tree, but not down (or vice-versa)?</p>
[ { "answer_id": 146264, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 1, "selected": false, "text": "def handle_key_event(name_of_key):" }, { "answer_id": 161132, "author": "Jeff", "author_id": 16639, "author_profile": "https://Stackoverflow.com/users/16639", "pm_score": 1, "selected": false, "text": "void UpdateVehicleFromInput()\n{\n if (InputSystem()->IsKeyDown(key))\n DoSomething();\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16676/" ]
146,269
<p>I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).</p> <p>I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas.</p>
[ { "answer_id": 146423, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 9, "selected": true, "text": "<Window.Resources>\n\n<DataTemplate x:Key=\"ItemTemplate\">\n <TextBlock Text=\"{Binding}\" Foreground=\"Red\" />\n</DataTemplate>\n\n<DataTemplate x:Key=\"SelectedTemplate\">\n <TextBlock Text=\"{Binding}\" Foreground=\"White\" />\n</DataTemplate>\n\n<Style TargetType=\"{x:Type ListBoxItem}\" x:Key=\"ContainerStyle\">\n <Setter Property=\"ContentTemplate\" Value=\"{StaticResource ItemTemplate}\" />\n <Style.Triggers>\n <Trigger Property=\"IsSelected\" Value=\"True\">\n <Setter Property=\"ContentTemplate\" Value=\"{StaticResource SelectedTemplate}\" />\n </Trigger>\n </Style.Triggers>\n</Style>\n\n</Window.Resources>\n<ListBox x:Name=\"lstItems\" ItemContainerStyle=\"{StaticResource ContainerStyle}\" />\n" }, { "answer_id": 27614229, "author": "Darien Pardinas", "author_id": 1416294, "author_profile": "https://Stackoverflow.com/users/1416294", "pm_score": 4, "selected": false, "text": "ListBoxItem <DataTemplate> IsSelected TextBlock Foreground <DataTemplate x:Key=\"SimpleDataTemplate\">\n <TextBlock Text=\"{Binding}\">\n <TextBlock.Style>\n <Style>\n <Setter Property=\"TextBlock.Foreground\" Value=\"Green\"/>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding Path=IsSelected, RelativeSource={\n RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem }}}\"\n Value=\"True\">\n <Setter Property=\"TextBlock.Foreground\" Value=\"Red\"/>\n </DataTrigger>\n <DataTrigger Binding=\"{Binding Path=IsMouseOver, RelativeSource={\n RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem }}}\"\n Value=\"True\">\n <Setter Property=\"TextBlock.Foreground\" Value=\"Yellow\"/>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n </TextBlock>\n</DataTemplate>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23222/" ]
146,271
<p><strong>EDIT: This question is more about language engineering than C++ itself. I used C++ as an example to show what I wanted, mostly because I use it daily. I didn't want to know how it works on C++ but open a discussion on how it <em>could</em> be done.</strong></p> <p>That's not the way it works right now, that's the way I <em>wish</em> it could be done, and that would break C compability for sure, but that's what I think extern "C" is all about.</p> <p>I mean, in every function or method that you declare right now you have to explicit write that the object will be sent by reference prefixing the reference operator on it. I wish that every non-POD type would be automatically sent by reference, because I use that a lot, actually for every object that is more than 32 bits in size, and that's almost every class of mine.</p> <p>Let's exemplify how it's right now, assume <em>a</em>, <em>b</em> and <em>c</em> to be classes:</p> <pre> class example { public: int just_use_a(const a &object); int use_and_mess_with_b(b &object); void do_nothing_on_c(c object); }; </pre> <p>Now what I wish:</p> <pre> class example { public: int just_use_a(const a object); int use_and_mess_with_b(b object); extern "C" void do_nothing_on_c(c object); }; </pre> <p>Now, do_nothing_on_c() could behave just like it is today.</p> <p>That would be interesting at least for me, feels much more clear, and also if you <em>know</em> every non-POD parameter is coming by reference I believe the mistakes would be the same that if you had to explicit declare it.</p> <p>Another point of view for this change, from someone coming from C, the reference operator seems to me a way to get the variable <em>address</em>, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too?</p>
[ { "answer_id": 146285, "author": "user7545", "author_id": 7545, "author_profile": "https://Stackoverflow.com/users/7545", "pm_score": 1, "selected": false, "text": "void myFunct(int cantChangeMyValue)\n void myFunct(int* cantChangeMyAddress) {\n *cantChangeMyAddress = 10;\n}\n void myFunct(int & hereBeMagic) {\n hereBeMagic = 10; // same as 2, without the dereference\n}\n" }, { "answer_id": 146315, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 1, "selected": false, "text": "const" }, { "answer_id": 146330, "author": "Michael Labbé", "author_id": 22244, "author_profile": "https://Stackoverflow.com/users/22244", "pm_score": 1, "selected": false, "text": "void Foo::PrintStats( void ) const {\n /* Cannot modify Foo member variables */\n}\n\nvoid Foo::ChangeStats( void ) {\n /* Can modify foo member variables */\n}\n void ManipulateFoo( const Foo &foo )\n{\n foo.PrintStats(); // Works\n foo.ChangeStats(); // Oops; compile error\n}\n" }, { "answer_id": 146451, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 0, "selected": false, "text": "class B{/*something...*/};\nint b(B& param);\n" }, { "answer_id": 146462, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": true, "text": "typedef struct { int value ; } P ;\n\n/* p is a pointer to P */\nvoid doSomethingElse(P * p)\n{\n p->value = 32 ;\n p = malloc(sizeof(P)) ; /* Don't bother with the leak */\n p->value = 45 ;\n}\n\nvoid doSomething()\n{\n P * p = malloc(sizeof(P)) ;\n p->value = 25 ;\n\n doSomethingElse(p) ;\n\n int i = p->value ;\n /* Value of p ? 25 ? 32 ? 42 ? */\n}\n struct P { int value ; } ;\n\n// p is a reference to a pointer to P\nvoid doSomethingElse(P * & p)\n{\n p->value = 32 ;\n p = (P *) malloc(sizeof(P)) ; // Don't bother with the leak\n p->value = 45 ;\n}\n\nvoid doSomething()\n{\n P * p = (P *) malloc(sizeof(P)) ;\n p->value = 25 ;\n\n doSomethingElse(p) ;\n\n int i = p->value ;\n // Value of p ? 25 ? 32 ? 42 ?\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18623/" ]
146,275
<p>I have a templated class defined (in part) as</p> <pre><code>template &lt;class T&gt; MyClass { public: void DoSomething(){} }; </code></pre> <p>If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.</p> <p>My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.</p> <p>Has anyone any suggestions?</p>
[ { "answer_id": 146309, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": true, "text": "class Base { \npublic:\n virtual ~Base(){}\n virtual void DoSomething() = 0;\n}\n\ntemplate <class T> class MyClass : public Base {\npublic:\n void DoSomething(){}\n};\n\nstd::vector<Base *> objects;\nobjects.push_back(new MyClass<int>);\nobjects.push_back(new MyClass<char>);\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23167/" ]
146,291
<p>I have a problem with <strong>scandir()</strong>: The manpage contains this as prototype:</p> <pre><code>int scandir(const char *dir, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **)); </code></pre> <p>Therefore I have this:</p> <pre><code>static inline int RubyCompare(const struct dirent **a, const struct dirent **b) { return(strcmp((*a)-&gt;d_name, (*b)-&gt;d_name)); } </code></pre> <p>And here's the call:</p> <pre><code>num = scandir(buf, &amp;entries, NULL, RubyCompare); </code></pre> <p>Finally the compiler says this:</p> <pre><code>warning: passing argument 4 of ‘scandir’ from incompatible pointer type </code></pre> <p>Compiler is <strong>gcc-4.3.2</strong>, my CFLAGS are following: </p> <pre><code>-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99 </code></pre> <p>What is the meaning of this warning? The declaration of RubyCompare looks correct for me and besides the warning the code works completely.</p>
[ { "answer_id": 146352, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 4, "selected": true, "text": "static inline int RubyCompare(const void *a, const void *b)\n{\n return(strcmp((*(struct dirent **)a)->d_name, \n (*(struct dirent **)b)->d_name));\n}\n num = scandir(buf, &entries, NULL, alphasort);\n" }, { "answer_id": 1424093, "author": "Mark Borgerding", "author_id": 3343, "author_profile": "https://Stackoverflow.com/users/3343", "pm_score": 2, "selected": false, "text": "#define USE_SCANDIR_VOIDPTR \n#if defined( __GLIBC_PREREQ )\n# if __GLIBC_PREREQ(2,10)\n# undef USE_SCANDIR_VOIDPTR\n# endif\n#endif\n\n#ifdef USE_SCANDIR_VOIDPTR\n static int RubyCompare(const void *a, const void *b)\n#else \n static int RubyCompare(const struct dirent **a, const struct dirent **b)\n#endif\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18179/" ]
146,297
<p>With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared.</p> <p>What are yours? </p>
[ { "answer_id": 146304, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 7, "selected": false, "text": "Double-Click on a symbol Double-Click on a symbol View Layout Show Favorites Bar" }, { "answer_id": 146760, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 8, "selected": false, "text": ".m .h" }, { "answer_id": 156626, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 5, "selected": false, "text": "p i m control-period #import \"file\" file" }, { "answer_id": 200023, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "// TODO: Some task that needs to be done.\n" }, { "answer_id": 215769, "author": "Steve Streza", "author_id": 29314, "author_profile": "https://Stackoverflow.com/users/29314", "pm_score": 6, "selected": false, "text": "#pragma mark Foo\n Foo #pragma mark -\n" }, { "answer_id": 359068, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": false, "text": "#pragma mark #!/bin/sh\n echo -n \"//================....================\n #pragma mark \"\n" }, { "answer_id": 489639, "author": "Dan", "author_id": 49663, "author_profile": "https://Stackoverflow.com/users/49663", "pm_score": 3, "selected": false, "text": "#pragma mark #MARK: Foo #MARK: -" }, { "answer_id": 847146, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 3, "selected": false, "text": "#pragma mark === Initialization ===\n" }, { "answer_id": 934152, "author": "Jon Hess", "author_id": 104008, "author_profile": "https://Stackoverflow.com/users/104008", "pm_score": 6, "selected": false, "text": "objc_exception_throw NSZombieEnabled = YES;\nNSDeallocateZombies = NO;\n Double-click Click" }, { "answer_id": 938384, "author": "nevan king", "author_id": 74118, "author_profile": "https://Stackoverflow.com/users/74118", "pm_score": 7, "selected": false, "text": "defaults write com.apple.Xcode XCShowUndoPastSaveWarning NO\n defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{\"ORGANIZATIONNAME\" = \"Microsoft\";}'\n com.yourcompanyname /Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates/Application com.yourcompany info.plist log NSLog NSMu NSMutableArray NSArray NS" }, { "answer_id": 962289, "author": "Nikolai Ruhe", "author_id": 104790, "author_profile": "https://Stackoverflow.com/users/104790", "pm_score": 5, "selected": false, "text": "> xed -x # open a new untitled document\n> xed -xc foo.txt # create foo.txt and open it\n> xed -l 2000 foo.txt # open foo.txt and go to line 2000\n\n# set Xcode to be your EDITOR for command line tools\n# e.g. for subversion commit\n> echo 'export EDITOR=\"xed -wcx\"' >> ~/.profile\n\n> man xed # there's a man page, too\n" }, { "answer_id": 976786, "author": "TimM", "author_id": 105387, "author_profile": "https://Stackoverflow.com/users/105387", "pm_score": 3, "selected": false, "text": ".h .m" }, { "answer_id": 1250637, "author": "Johan Kool", "author_id": 60488, "author_profile": "https://Stackoverflow.com/users/60488", "pm_score": 3, "selected": false, "text": "fi if" }, { "answer_id": 1377441, "author": "fbrereto", "author_id": 153535, "author_profile": "https://Stackoverflow.com/users/153535", "pm_score": 3, "selected": false, "text": "TODO: int* p(0); // TODO: initialize me!\n" }, { "answer_id": 1610134, "author": "geowar", "author_id": 445215, "author_profile": "https://Stackoverflow.com/users/445215", "pm_score": 3, "selected": false, "text": "defaults write com.apple.Xcode PBXBuildSuccessSound ~/Library/Sounds/metal\\ stamp.wav\ndefaults write com.apple.Xcode PBXBuildFailureSound ~/Library/Sounds/Elephant\n" }, { "answer_id": 2495952, "author": "Senseful", "author_id": 35690, "author_profile": "https://Stackoverflow.com/users/35690", "pm_score": 4, "selected": false, "text": "[ [ [ myObject testMethod [myObject testMethod]\n ] myObject [myObject ]\n ] myObject" }, { "answer_id": 2499740, "author": "billo", "author_id": 299872, "author_profile": "https://Stackoverflow.com/users/299872", "pm_score": 2, "selected": false, "text": "cd project_directory\nxcodebuild -configuration Release -alltargets clean\nxcodebuild -configuration Release -alltargets\n" }, { "answer_id": 2713424, "author": "LK.", "author_id": 56380, "author_profile": "https://Stackoverflow.com/users/56380", "pm_score": 2, "selected": false, "text": "NSObject UIView UIViewController NSObject //=====================================================\n// Private Interface\n//=====================================================\n\n@interface test (private)\n@end\n\n//=====================================================\n// Public Implementation\n//=====================================================\n\n@implementation test\n\n- (void)dealloc {\n NSLog(@\">>> Dealloc: test [0x%X]\", self);\n [super dealloc];\n NSLog(@\"<<< Dealloc: test\");\n}\n\n- (id) init\n{\n self = [super init];\n if(self) {\n NSLog(@\">>> Alloc: test [0x%X]\", self);\n }\n return self;\n}\n\n@end\n\n//=====================================================\n// Private Implementation\n//=====================================================\n\n@implementation test (private)\n@end\n" }, { "answer_id": 2851299, "author": "Nikolai Ruhe", "author_id": 104790, "author_profile": "https://Stackoverflow.com/users/104790", "pm_score": 3, "selected": false, "text": "<filename>:<linenumber>: error | warn | note : <message>\\n" }, { "answer_id": 3456939, "author": "Ole Begemann", "author_id": 116862, "author_profile": "https://Stackoverflow.com/users/116862", "pm_score": 3, "selected": false, "text": "defaults write com.apple.Xcode XCCodeSenseAutoSuggestionStyle List\n" }, { "answer_id": 3456990, "author": "gnuchu", "author_id": 143613, "author_profile": "https://Stackoverflow.com/users/143613", "pm_score": 3, "selected": false, "text": "Command + '/' \n" }, { "answer_id": 3508907, "author": "nicktmro", "author_id": 108622, "author_profile": "https://Stackoverflow.com/users/108622", "pm_score": 4, "selected": false, "text": "- ta\n - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath\n" }, { "answer_id": 4145853, "author": "Juan Arzola", "author_id": 405267, "author_profile": "https://Stackoverflow.com/users/405267", "pm_score": 2, "selected": false, "text": "<filename:lineNumber> #ifdef DEBUG\n#define DLog(fmt, ...) NSLog((@\"%s <%@:%d> \" fmt), __PRETTY_FUNCTION__, [[NSString stringWithFormat:@\"%s\", __FILE__ ] lastPathComponent] ,__LINE__, ##__VA_ARGS__)\n#else\n#define DLog(format, ...)\n#endif\n <filename:lineNumber>" }, { "answer_id": 4799706, "author": "monsterkodi", "author_id": 1769504, "author_profile": "https://Stackoverflow.com/users/1769504", "pm_score": 3, "selected": false, "text": "if (cond) {\n code;\n}\n if (cond)\n{\n code;\n}\n defaults write com.apple.Xcode XCCodeSenseFormattingOptions -dict-add BlockSeparator \"\\n\"\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23113/" ]
146,305
<p>Are there some principles of organizing classes into namespaces?</p> <p>For example is it OK if classes from namespace N depends on classes from N.X? And if classes from N.X depends on classes from N?</p>
[ { "answer_id": 146312, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 2, "selected": false, "text": "N.X N N N.X" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23223/" ]
146,311
<p>It says in <a href="http://www.ibm.com/developerworks/java/library/j-jtp04223.html" rel="nofollow noreferrer">this article</a> that: </p> <blockquote> <p>Making a class final because it is immutable is a good reason to do so.</p> </blockquote> <p>I'm a bit puzzled by this... I understand that immutability is a good thing from the POV of thread-safety and simplicity, but it seems that these concerns are somewhat orthogonal to extensibility. So, why is immutability a good reason for making a class final?</p>
[ { "answer_id": 146374, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "void checkUrl(MyUrlClass testurl) throws SecurityException {\n if (illegalDomains.contains(testurl.getDomain())) throw new SecurityException();\n}\n securitymanager.checkUrl(urltoconnect);\nSocket sckt = opensocket(urltoconnect);\nsendrequest(sckt);\ngetresponse(sckt);\n" }, { "answer_id": 12600683, "author": "Vinoth Kumar C M", "author_id": 571718, "author_profile": "https://Stackoverflow.com/users/571718", "pm_score": 4, "selected": false, "text": "BigDecimal BigInteger BigInteger BigDecimal public static BigInteger safeInstance(BigInteger val) {\n\n if (val.getClass() != BigInteger.class)\n\n return new BigInteger(val.toByteArray());\n\n\n return val;\n\n }\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
146,316
<p>What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number of classes.</p>
[ { "answer_id": 148481, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 6, "selected": true, "text": "# IronPython\nimport System\nexported_types = [\n (t.Namespace, t.Name)\n for t in System.Int32().GetType().Assembly.GetExportedTypes()]\n\nimport itertools\nget_ns = lambda (ns, typename): ns\nsorted_exported_types = sorted(exported_types, key=get_ns)\ncounts_per_ns = dict(\n (ns, len(list(typenames)))\n for ns, typenames\n in itertools.groupby(sorted_exported_types, get_ns))\ncounts = sorted(counts_per_ns.values())\n\nprint 'Min:', counts[0]\nprint 'Max:', counts[-1]\nprint 'Avg:', sum(counts) / len(counts)\nprint 'Med:',\nif len(counts) % 2:\n print counts[len(counts) / 2]\nelse: # ignoring len == 1 case\n print (counts[len(counts) / 2 - 1] + counts[len(counts) / 2]) / 2\n C:\\tools\\nspop>ipy nspop.py\nMin: 1\nMax: 173\nAvg: 27\nMed: 15\n" }, { "answer_id": 686782, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 0, "selected": false, "text": "using" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15497/" ]
146,320
<p>First, I'd like to establish the acceptable end-to-end latency for a real-time system in the financial world is less than 200ms. Okay, here's what I'm after. In the design of real-time systems, there are "design patterns" (or techniques) that will increase the performance (i.e. reduce processing time, improve scalability, etc).</p> <p>An example of what I'm after is, the use of GUIDs instead of sequential numbers for allocation of primary keys. Rationale for GUIDs is that handlers have their own primary key generators without "consulting" each other. This allows for parallel processing to occur and permits scaling.</p> <p>Here're some more. I'll try and add to the list when able to.</p> <ul> <li>The use of <a href="http://en.wikipedia.org/wiki/Event_Driven_Architecture" rel="nofollow noreferrer">event driven architecture (EDA)</a>.</li> <li>Use of messaging queues to support EDA.</li> </ul> <p>I bow to the collective wisdom of the community. Thanks heaps!</p>
[ { "answer_id": 146510, "author": "Caerbanog", "author_id": 23190, "author_profile": "https://Stackoverflow.com/users/23190", "pm_score": 1, "selected": false, "text": "for(int i=0;i< x/2; i++)\n //do something\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428965/" ]
146,354
<p>I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.</p> <p>So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?</p> <pre><code>$database = 'live'; if (some staging environment variable is true) { $database = 'testing'; // and not live } </code></pre> <p>If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile</p> <p>Hope this makes sense</p> <p>many thanks</p> <p>Ian</p>
[ { "answer_id": 146380, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 6, "selected": false, "text": "SetEnv DATABASE_NAME testing\n $database = $_SERVER[\"DATABASE_NAME\"];\n $database = getenv(\"DATABASE_NAME\");\n" }, { "answer_id": 146382, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 4, "selected": false, "text": "SetEnv database testing\n if (getenv('database') == 'testing') {\n if ($_SERVER['database'] == 'testing') {\n" }, { "answer_id": 146446, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 5, "selected": true, "text": "php_value name value\n" }, { "answer_id": 43287890, "author": "S.Donovan", "author_id": 7564507, "author_profile": "https://Stackoverflow.com/users/7564507", "pm_score": 0, "selected": false, "text": "SetEnv KeyName DataValue KeyName, DataValue $var = $_SERVER[\"KeyName\"]; DataValue" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
146,358
<p>I'm using .NET 3.5. I have two string arrays, which may share one or more values:</p> <pre><code>string[] list1 = new string[] { "apple", "orange", "banana" }; string[] list2 = new string[] { "banana", "pear", "grape" }; </code></pre> <p>I'd like a way to merge them into one array with no duplicate values:</p> <pre><code>{ "apple", "orange", "banana", "pear", "grape" } </code></pre> <p>I can do this with LINQ:</p> <pre><code>string[] result = list1.Concat(list2).Distinct().ToArray(); </code></pre> <p>but I imagine that's not very efficient for large arrays.</p> <p>Is there a better way?</p>
[ { "answer_id": 146393, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "private static IEnumerable<T> Merge<T>(IEnumerable<T> source1,\n IEnumerable<T> source2)\n{\n return Merge(source1, source2, Comparer<T>.Default);\n}\n\nprivate static IEnumerable<T> Merge<T>(IEnumerable<T> source1,\n IEnumerable<T> source2, IComparer<T> comparer)\n{\n #region Parameter Validation\n\n if (Object.ReferenceEquals(null, source1))\n throw new ArgumentNullException(\"source1\");\n if (Object.ReferenceEquals(null, source2))\n throw new ArgumentNullException(\"source2\");\n if (Object.ReferenceEquals(null, comparer))\n throw new ArgumentNullException(\"comparer\");\n\n #endregion\n\n using (IEnumerator<T>\n enumerator1 = source1.GetEnumerator(),\n enumerator2 = source2.GetEnumerator())\n {\n Boolean more1 = enumerator1.MoveNext();\n Boolean more2 = enumerator2.MoveNext();\n\n while (more1 && more2)\n {\n Int32 comparisonResult = comparer.Compare(\n enumerator1.Current,\n enumerator2.Current);\n if (comparisonResult < 0)\n {\n // enumerator 1 has the \"lowest\" item\n yield return enumerator1.Current;\n more1 = enumerator1.MoveNext();\n }\n else if (comparisonResult > 0)\n {\n // enumerator 2 has the \"lowest\" item\n yield return enumerator2.Current;\n more2 = enumerator2.MoveNext();\n }\n else\n {\n // they're considered equivalent, only yield it once\n yield return enumerator1.Current;\n more1 = enumerator1.MoveNext();\n more2 = enumerator2.MoveNext();\n }\n }\n\n // Yield rest of values from non-exhausted source\n while (more1)\n {\n yield return enumerator1.Current;\n more1 = enumerator1.MoveNext();\n }\n while (more2)\n {\n yield return enumerator2.Current;\n more2 = enumerator2.MoveNext();\n }\n }\n}\n private static IEnumerable<T> CheapDistinct<T>(IEnumerable<T> source)\n{\n return CheapDistinct<T>(source, Comparer<T>.Default);\n}\n\nprivate static IEnumerable<T> CheapDistinct<T>(IEnumerable<T> source,\n IComparer<T> comparer)\n{\n #region Parameter Validation\n\n if (Object.ReferenceEquals(null, source))\n throw new ArgumentNullException(\"source\");\n if (Object.ReferenceEquals(null, comparer))\n throw new ArgumentNullException(\"comparer\");\n\n #endregion\n\n using (IEnumerator<T> enumerator = source.GetEnumerator())\n {\n if (enumerator.MoveNext())\n {\n T item = enumerator.Current;\n\n // scan until different item found, then produce\n // the previous distinct item\n while (enumerator.MoveNext())\n {\n if (comparer.Compare(item, enumerator.Current) != 0)\n {\n yield return item;\n item = enumerator.Current;\n }\n }\n\n // produce last item that is left over from above loop\n yield return item;\n }\n }\n}\n String[] list_1 = { \"apple\", \"orange\", \"apple\", \"banana\" };\nString[] list_2 = { \"banana\", \"pear\", \"grape\" };\n\nArray.Sort(list_1);\nArray.Sort(list_2);\n\nIEnumerable<String> items = Merge(\n CheapDistinct(list_1),\n CheapDistinct(list_2));\nforeach (String item in items)\n Console.Out.WriteLine(item);\n" }, { "answer_id": 146416, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 2, "selected": false, "text": "IEnumerable<string> mergedDistinctList = new HashSet<string>(list1).Union(list2);\n Setting up arrays of 3000000 strings overlapping by 300000\nStarting Hashset...\nHashSet: 00:00:02.8237616\nStarting Concat/Distinct...\nConcat/Distinct: 00:00:02.5629681\n int num = 3000000;\n int num10Pct = (int)(num / 10);\n\n Console.WriteLine(String.Format(\"Setting up arrays of {0} strings overlapping by {1}\", num, num10Pct));\n string[] list1 = Enumerable.Range(1, num).Select((a) => a.ToString()).ToArray();\n string[] list2 = Enumerable.Range(num - num10Pct, num + num10Pct).Select((a) => a.ToString()).ToArray();\n\n Console.WriteLine(\"Starting Hashset...\");\n Stopwatch sw = new Stopwatch();\n sw.Start();\n string[] merged = new HashSet<string>(list1).Union(list2).ToArray();\n sw.Stop();\n Console.WriteLine(\"HashSet: \" + sw.Elapsed);\n\n Console.WriteLine(\"Starting Concat/Distinct...\");\n sw.Reset();\n sw.Start();\n string[] merged2 = list1.Concat(list2).Distinct().ToArray();\n sw.Stop();\n Console.WriteLine(\"Concat/Distinct: \" + sw.Elapsed);\n" }, { "answer_id": 146428, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "public static IEnumerable<T> DistinctConcat<T>(IEnumerable<T> first, IEnumerable<T> second)\n{\n HashSet<T> returned = new HashSet<T>();\n foreach (T element in first)\n {\n if (returned.Add(element))\n {\n yield return element;\n }\n }\n foreach (T element in second)\n {\n if (returned.Add(element))\n {\n yield return element;\n }\n }\n}\n" }, { "answer_id": 147149, "author": "Wonko", "author_id": 14842, "author_profile": "https://Stackoverflow.com/users/14842", "pm_score": 8, "selected": true, "text": "string[] result = list1.Union(list2).ToArray();\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5142/" ]
146,359
<p>I am trying to figure out this:</p> <pre><code>c = 1 def f(n): print c + n def g(n): c = c + n f(1) # =&gt; 2 g(1) # =&gt; UnboundLocalError: local variable 'c' referenced before assignment </code></pre> <p>Thanks!</p>
[ { "answer_id": 146365, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": true, "text": "global def g(n):\n global c\n c = c + n\n" }, { "answer_id": 146546, "author": "ironfroggy", "author_id": 19687, "author_profile": "https://Stackoverflow.com/users/19687", "pm_score": 4, "selected": false, "text": "g() f() g() c class A:\n c = 1\n def f(self, n):\n print self.c + n\n def g(self, n):\n self.c += n\n\na = A()\na.f(1)\na.g(1)\na.f(1)\n 2\n3\n" }, { "answer_id": 150546, "author": "Krzysiek Goj", "author_id": 23018, "author_profile": "https://Stackoverflow.com/users/23018", "pm_score": 3, "selected": false, "text": " x = 1\ndef explode():\n print x # raises UnboundLocalError here\n x = 2\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462204/" ]
146,381
<p>I keep reading about C99 and C++11 and all these totally sweet things that are getting added to the language standard that might be nice to use someday. However, we currently languish in the land of writing C++ in Visual Studio.</p> <p>Will any of the new stuff in the standard ever get added to visual studio, or is Microsoft more interested in adding new C# variants to do that?</p> <p>Edit: In addition to the accepted answer, I found the Visual C++ team blog:</p> <p><a href="http://blogs.msdn.com/vcblog/" rel="nofollow noreferrer">http://blogs.msdn.com/vcblog/</a></p> <p>And specifically, this post in it:</p> <p><a href="https://web.archive.org/web/20190109064523/https://blogs.msdn.microsoft.com/vcblog/2008/02/22/tr1-slide-decks/" rel="nofollow noreferrer">https://web.archive.org/web/20190109064523/https://blogs.msdn.microsoft.com/vcblog/2008/02/22/tr1-slide-decks/</a></p> <p>Very useful. Thanks!</p>
[ { "answer_id": 146419, "author": "jakobengblom2", "author_id": 23054, "author_profile": "https://Stackoverflow.com/users/23054", "pm_score": 8, "selected": true, "text": "long long __pragma __FUNCTION__ __restrict long long" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13500/" ]
146,385
<p>I am trying to call a webservice using ssl. How do i get the relevant server cert so that i can import it into my truststore? I know about the use of property com.ibm.ssl.enableSignerExchangePrompt from a main method but i would add the server cert to my truststore manually.</p> <p>I dont want this property set in any of my servlets</p> <p>Any help is greatly appreciated Thanks Damien</p>
[ { "answer_id": 146565, "author": "el_eduardo", "author_id": 13469, "author_profile": "https://Stackoverflow.com/users/13469", "pm_score": 3, "selected": true, "text": "\npublic class dummyTrustManager implements X509TrustManager {\n\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n //do nothing\n }\n\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n // do nothing\n }\n\n public X509Certificate[] getAcceptedIssuers() {\n //just return an empty issuer\n return new X509Certificate[0];\n }\n }\n \nSSLContext context = SSLContext.getInstance(\"SSL\");\ncontext.init(null, new TrustManager[] { new dummyTrustManager() },\n new java.security.SecureRandom());\n\nSSLSocketFactory factory = context.getSocketFactory();\nInetAddress addr = InetAddress.getByName(host_);\nSSLSocket sock = (SSLSocket)factory.createSocket(addr, port_);\n \nSSLSession session = sock.getSession();\nCertificate[] certchain = session.getPeerCertificates();\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11612/" ]
146,387
<p>I'd like to get <strong>uniform distribution</strong> in range [0.0, 1.0)</p> <p>If possible, please let the implementation make use of random bytes from <strong>/dev/urandom.</strong></p> <p>It would also be nice if your solution was <strong>thread-safe</strong>. If you're not sure, please indicate that.</p> <p>See <a href="https://stackoverflow.com/questions/146387#149814">some solution</a> I thought about after reading other answers.</p>
[ { "answer_id": 146410, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#include <stdlib.h>\nprintf(\"%f\\n\", drand48());\n double c;\nfd = open(\"/dev/random\", O_RDONLY);\nunsigned int a, b;\nread(fd, &a, sizeof(a));\nread(fd, &b, sizeof(b));\nif (a > b)\n c = fabs((double)b / (double)a);\nelse\n c = fabs((double)a / (double)b);\n" }, { "answer_id": 146413, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 1, "selected": false, "text": "#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n...\nFILE* f = fopen(\"/dev/urandom\", \"r\");\nuint32_t i;\nfread(&i, sizeof(i), 1, f); // check return value in real world code!!\nfclose(f);\ndouble theRandomValue = i / (double) (UINT32_MAX);\n" }, { "answer_id": 149814, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 3, "selected": true, "text": " unsigned short int r1, r2, r3;\n// let r1, r2 and r3 hold random values\ndouble result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
146,390
<p>In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string. For example:</p> <pre><code>&gt;&gt;&gt; a = (1,"Hello",7.2) &gt;&gt;&gt; print "these are the values %d, %s, %f" % a these are the values 1, Hello, 7.200000 </code></pre> <p>Is there some way to use any array or collection in a java printf statement in a similar way?</p> <p>I've looked at the <a href="http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax" rel="nofollow noreferrer">documentation</a> and it appears to have built in support for some types like Calendar, but I don't see anything for collections. </p> <p>If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)?</p>
[ { "answer_id": 146408, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 5, "selected": true, "text": "public PrintString printf(String format, Object... args);\n [] ... out.printf(\"%s:%s\", a, b);\n out.printf(\"%s:%s\", new Object[] { a, b });\n out.printf(\"%s:%s\", things);\n out.printf(\"%s:%s\", things.toArray());\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4138/" ]
146,391
<p>I can't figure out a use case for being able to annotate interfaces in Java. </p> <p>Maybe someone could give me an example?</p>
[ { "answer_id": 7962199, "author": "Phyxx", "author_id": 157605, "author_profile": "https://Stackoverflow.com/users/157605", "pm_score": 0, "selected": false, "text": "final RESTInterfaceV1 client = ProxyFactory.create(RESTInterfaceV1.class, \"http://localhost:8080/rest\");\n" }, { "answer_id": 25694022, "author": "raspacorp", "author_id": 2487263, "author_profile": "https://Stackoverflow.com/users/2487263", "pm_score": 3, "selected": false, "text": "public interface IUser {\n @NotNull Long getUserId();\n ...\n}\n\npublic class WebUser implements IUser {\n private Long userId;\n\n @Override\n public Long getUserId(){\n return userId;\n }\n ...\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
146,435
<p>I have a file temp.txt, that I want to sort with the <code>sort</code> command in bash.</p> <p>I want the sorted results to replace the original file.</p> <p>This doesn't work for example (I get an empty file):</p> <pre><code>sortx temp.txt &gt; temp.txt </code></pre> <p>Can this be done in one line without resorting to copying to temporary files?</p> <hr> <p>EDIT: The <code>-o</code> option is very cool for <code>sort</code>. I used <code>sort</code> in my question as an example. I run into the same problem with other commands:</p> <pre><code>uniq temp.txt &gt; temp.txt. </code></pre> <p>Is there a better general solution?</p>
[ { "answer_id": 146441, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 2, "selected": false, "text": "ex" }, { "answer_id": 146445, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 3, "selected": false, "text": "sort temp.txt > temp.txt.sort && mv temp.txt.sort temp.txt\n" }, { "answer_id": 146473, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 8, "selected": true, "text": "sort temp.txt -o temp.txt\n" }, { "answer_id": 146481, "author": "sammyo", "author_id": 10826, "author_profile": "https://Stackoverflow.com/users/10826", "pm_score": 1, "selected": false, "text": "--output= -o sort temp.txt -otemp.txt\n" }, { "answer_id": 146482, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "sort sort sort temp.txt -o temp.txt" }, { "answer_id": 146603, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 2, "selected": false, "text": " -o output-file\n Write output to output-file instead of to the standard output.\n If output-file is one of the input files, sort copies it to a\n temporary file before sorting and writing the output to output-\n file.\n" }, { "answer_id": 147826, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 5, "selected": false, "text": "sort sort sort temp.txt -o temp.txt\n sort sort -o F F cat F | sort -o F sort --merge -m cat F | sort -m -o F - G F cat sort uniq perl uniq temp.txt | perl -e 'undef $/; $_ = <>; open(OUT,\">temp.txt\"); print OUT;'\n uniq $_" }, { "answer_id": 148680, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 2, "selected": false, "text": "uniq temp.txt | awk '{line[i++] = $0}END{for(j=0;j<i;j++){print line[j]}}' > temp.txt\n" }, { "answer_id": 2463200, "author": "jasper", "author_id": 295743, "author_profile": "https://Stackoverflow.com/users/295743", "pm_score": 1, "selected": false, "text": "uniq sort inputfile | uniq | sort -o inputfile\n" }, { "answer_id": 4413942, "author": "wor", "author_id": 538470, "author_profile": "https://Stackoverflow.com/users/538470", "pm_score": 4, "selected": false, "text": "{ rm file && uniq > file; } < file\n" }, { "answer_id": 17491611, "author": "Sean", "author_id": 1175459, "author_profile": "https://Stackoverflow.com/users/1175459", "pm_score": 4, "selected": false, "text": "% sed \"s/root/toor/\" /etc/passwd | grep -v joey | sponge /etc/passwd\n sponge sponge $ mistyped_command my-important-file | sponge my-important-file\nmistyped-command: command not found\n my-important-file" }, { "answer_id": 17603766, "author": "johnnyB", "author_id": 1923994, "author_profile": "https://Stackoverflow.com/users/1923994", "pm_score": 3, "selected": false, "text": "sort file -o file $ sort file -o !#^\n $ sort -u -o file !#$\n" }, { "answer_id": 28001423, "author": "whoan", "author_id": 4095830, "author_profile": "https://Stackoverflow.com/users/4095830", "pm_score": 2, "selected": false, "text": "sponge sed sed -ni r<(command file) file\n sort uniq tac sed -i command file sed -n sed r bash <(command file) ip_cmd() { # in place command\n CMD=${1:?You must specify a command}\n FILE=${2:?You must specify a file}\n sed -ni r<(\"$CMD\" \"$FILE\") \"$FILE\"\n}\n $ cat file\nd\nb\nc\nb\na\n\n$ ip_cmd sort file\n$ cat file\na\nb\nb\nc\nd\n\n$ ip_cmd uniq file\n$ cat file\na\nb\nc\nd\n\n$ ip_cmd tac file\n$ cat file\nd\nc\nb\na\n\n$ ip_cmd\nbash: 1: You must specify a command\n$ ip_cmd uniq\nbash: 2: You must specify a file\n" }, { "answer_id": 38610841, "author": "Antonio Lebrón", "author_id": 5624788, "author_profile": "https://Stackoverflow.com/users/5624788", "pm_score": 0, "selected": false, "text": "uniq file 1<> file\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
146,439
<p>Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met. </p> <p>Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel. Is this possible with C#?</p> <p>Main thing I am looking for is how to catch a program starting up, rest should be easy.</p>
[ { "answer_id": 146474, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 4, "selected": true, "text": "Process[] processes = Process.GetProcessesByName(processName);\nforeach(Process process in processes)\n{\n process.Kill();\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21691/" ]
146,452
<p>I've come across this term POD-type a few times.<br> What does it mean? </p>
[ { "answer_id": 146454, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 11, "selected": true, "text": "struct class" }, { "answer_id": 146464, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 5, "selected": false, "text": "int char float long unsigned char double" }, { "answer_id": 146589, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 9, "selected": false, "text": "int char wchar_t bool float double long/short signed/unsigned enums const volatile class struct union public" }, { "answer_id": 20447009, "author": "набиячлэвэли", "author_id": 2851815, "author_profile": "https://Stackoverflow.com/users/2851815", "pm_score": 4, "selected": false, "text": "std::is_pod namespace std {\n// Could use is_standard_layout && is_trivial instead of the builtin.\ntemplate<typename _Tp>\n struct is_pod\n : public integral_constant<bool, __is_pod(_Tp)>\n { };\n}\n" }, { "answer_id": 48435532, "author": "ThomasMcLeod", "author_id": 540815, "author_profile": "https://Stackoverflow.com/users/540815", "pm_score": 3, "selected": false, "text": "std::is_pod" }, { "answer_id": 52989731, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 4, "selected": false, "text": "static_assert std::is_pod std::is_pod #include <type_traits>\n#include <array>\n#include <vector>\n\nint main() {\n#if __cplusplus >= 201103L\n // # Not POD\n //\n // Non-POD examples. Let's just walk all non-recursive non-POD branches of cppreference.\n {\n // Non-trivial implies non-POD.\n // https://en.cppreference.com/w/cpp/named_req/TrivialType\n {\n // Has one or more default constructors, all of which are either\n // trivial or deleted, and at least one of which is not deleted.\n {\n // Not trivial because we removed the default constructor\n // by using our own custom non-default constructor.\n {\n struct C {\n C(int) {}\n };\n static_assert(std::is_trivially_copyable<C>(), \"\");\n static_assert(!std::is_trivial<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n\n // No, this is not a default trivial constructor either:\n // https://en.cppreference.com/w/cpp/language/default_constructor\n //\n // The constructor is not user-provided (i.e., is implicitly-defined or\n // defaulted on its first declaration)\n {\n struct C {\n C() {}\n };\n static_assert(std::is_trivially_copyable<C>(), \"\");\n static_assert(!std::is_trivial<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n }\n\n // Not trivial because not trivially copyable.\n {\n struct C {\n C(C&) {}\n };\n static_assert(!std::is_trivially_copyable<C>(), \"\");\n static_assert(!std::is_trivial<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n }\n\n // Non-standard layout implies non-POD.\n // https://en.cppreference.com/w/cpp/named_req/StandardLayoutType\n {\n // Non static members with different access control.\n {\n // i is public and j is private.\n {\n struct C {\n public:\n int i;\n private:\n int j;\n };\n static_assert(!std::is_standard_layout<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n\n // These have the same access control.\n {\n struct C {\n private:\n int i;\n int j;\n };\n static_assert(std::is_standard_layout<C>(), \"\");\n static_assert(std::is_pod<C>(), \"\");\n\n struct D {\n public:\n int i;\n int j;\n };\n static_assert(std::is_standard_layout<D>(), \"\");\n static_assert(std::is_pod<D>(), \"\");\n }\n }\n\n // Virtual function.\n {\n struct C {\n virtual void f() = 0;\n };\n static_assert(!std::is_standard_layout<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n\n // Non-static member that is reference.\n {\n struct C {\n int &i;\n };\n static_assert(!std::is_standard_layout<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n\n // Neither:\n //\n // - has no base classes with non-static data members, or\n // - has no non-static data members in the most derived class\n // and at most one base class with non-static data members\n {\n // Non POD because has two base classes with non-static data members.\n {\n struct Base1 {\n int i;\n };\n struct Base2 {\n int j;\n };\n struct C : Base1, Base2 {};\n static_assert(!std::is_standard_layout<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n\n // POD: has just one base class with non-static member.\n {\n struct Base1 {\n int i;\n };\n struct C : Base1 {};\n static_assert(std::is_standard_layout<C>(), \"\");\n static_assert(std::is_pod<C>(), \"\");\n }\n\n // Just one base class with non-static member: Base1, Base2 has none.\n {\n struct Base1 {\n int i;\n };\n struct Base2 {};\n struct C : Base1, Base2 {};\n static_assert(std::is_standard_layout<C>(), \"\");\n static_assert(std::is_pod<C>(), \"\");\n }\n }\n\n // Base classes of the same type as the first non-static data member.\n // TODO failing on GCC 8.1 -std=c++11, 14 and 17.\n {\n struct C {};\n struct D : C {\n C c;\n };\n //static_assert(!std::is_standard_layout<C>(), \"\");\n //static_assert(!std::is_pod<C>(), \"\");\n };\n\n // C++14 standard layout new rules, yay!\n {\n // Has two (possibly indirect) base class subobjects of the same type.\n // Here C has two base classes which are indirectly \"Base\".\n //\n // TODO failing on GCC 8.1 -std=c++11, 14 and 17.\n // even though the example was copy pasted from cppreference.\n {\n struct Q {};\n struct S : Q { };\n struct T : Q { };\n struct U : S, T { }; // not a standard-layout class: two base class subobjects of type Q\n //static_assert(!std::is_standard_layout<U>(), \"\");\n //static_assert(!std::is_pod<U>(), \"\");\n }\n\n // Has all non-static data members and bit-fields declared in the same class\n // (either all in the derived or all in some base).\n {\n struct Base { int i; };\n struct Middle : Base {};\n struct C : Middle { int j; };\n static_assert(!std::is_standard_layout<C>(), \"\");\n static_assert(!std::is_pod<C>(), \"\");\n }\n\n // None of the base class subobjects has the same type as\n // for non-union types, as the first non-static data member\n //\n // TODO: similar to the C++11 for which we could not make a proper example,\n // but with recursivity added.\n\n // TODO come up with an example that is POD in C++14 but not in C++11.\n }\n }\n }\n\n // # POD\n //\n // POD examples. Everything that does not fall neatly in the non-POD examples.\n {\n // Can't get more POD than this.\n {\n struct C {};\n static_assert(std::is_pod<C>(), \"\");\n static_assert(std::is_pod<int>(), \"\");\n }\n\n // Array of POD is POD.\n {\n struct C {};\n static_assert(std::is_pod<C>(), \"\");\n static_assert(std::is_pod<C[]>(), \"\");\n }\n\n // Private member: became POD in C++11\n // https://stackoverflow.com/questions/4762788/can-a-class-with-all-private-members-be-a-pod-class/4762944#4762944\n {\n struct C {\n private:\n int i;\n };\n#if __cplusplus >= 201103L\n static_assert(std::is_pod<C>(), \"\");\n#else\n static_assert(!std::is_pod<C>(), \"\");\n#endif\n }\n\n // Most standard library containers are not POD because they are not trivial,\n // which can be seen directly from their interface definition in the standard.\n // https://stackoverflow.com/questions/27165436/pod-implications-for-a-struct-which-holds-an-standard-library-container\n {\n static_assert(!std::is_pod<std::vector<int>>(), \"\");\n static_assert(!std::is_trivially_copyable<std::vector<int>>(), \"\");\n // Some might be though:\n // https://stackoverflow.com/questions/3674247/is-stdarrayt-s-guaranteed-to-be-pod-if-t-is-pod\n static_assert(std::is_pod<std::array<int, 1>>(), \"\");\n }\n }\n\n // # POD effects\n //\n // Now let's verify what effects does PODness have.\n //\n // Note that this is not easy to do automatically, since many of the\n // failures are undefined behaviour.\n //\n // A good initial list can be found at:\n // https://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special/4178176#4178176\n {\n struct Pod {\n uint32_t i;\n uint64_t j;\n };\n static_assert(std::is_pod<Pod>(), \"\");\n\n struct NotPod {\n NotPod(uint32_t i, uint64_t j) : i(i), j(j) {}\n uint32_t i;\n uint64_t j;\n };\n static_assert(!std::is_pod<NotPod>(), \"\");\n\n // __attribute__((packed)) only works for POD, and is ignored for non-POD, and emits a warning\n // https://stackoverflow.com/questions/35152877/ignoring-packed-attribute-because-of-unpacked-non-pod-field/52986680#52986680\n {\n struct C {\n int i;\n };\n\n struct D : C {\n int j;\n };\n\n struct E {\n D d;\n } /*__attribute__((packed))*/;\n\n static_assert(std::is_pod<C>(), \"\");\n static_assert(!std::is_pod<D>(), \"\");\n static_assert(!std::is_pod<E>(), \"\");\n }\n }\n#endif\n}\n for std in 11 14 17; do echo $std; g++-8 -Wall -Werror -Wextra -pedantic -std=c++$std pod.cpp; done\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
146,484
<p>Can some one specify the windows API, one need to use in order to be able to change programmatically the screen refresh rate?</p>
[ { "answer_id": 146512, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": false, "text": "i := 0;\nwhile EnumDisplaySettings(nil, i, dm) do begin\n Memo1.Lines.Add(Format('Color Depth: %d', [dm.dmBitsPerPel]));\n Memo1.Lines.Add(Format('Resolution: %d, %d', [dm.dmPelsWidth, dm.dmPelsHeight]));\n Memo1.Lines.Add(Format('Display mode: %d', [dm.dmDisplayFlags]));\n Memo1.Lines.Add(Format('Frequency: %d', [dm.dmDisplayFrequency]));\n Inc(i);\nend;\n // In this case i is an index in the list of valid display modes.\nif EnumDisplaySettings(nil, i, dm) then begin\n // Sanity check!\n if ChangeDisplaySettings(dm, CDS_TEST) = 0) then\n ChangeDisplaySettings(dm, 0); // Use CDS_UPDATEREGISTRY if this is the new default mode.\nend;\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11659/" ]
146,498
<p>I am trying to make a <code>JTable</code> that has column spans available. Specifically, I am looking to nest a <code>JTable</code> inside another <code>JTable</code>, and when the user clicks to view the nested table, it should expand to push down the rows below and fill the empty space. This is similar to what you see in MS Access where you can nest tables, and clicking the expand button on a row will show you the corresponding entries in the nested table. </p> <p>If someone knows of a way to perform a column span with <code>JTable</code>, can you please point me in the right direction? Or if you know of an alternative way to do this, I am open to suggestions. The application is being built with Swing. Elements in the table, both high level and low level, have to be editable in any solution. Using nested <code>JTable</code>s this won't be a problem, and any other solution would have to take this into consideration as well.</p>
[ { "answer_id": 5065700, "author": "Synox", "author_id": 79461, "author_profile": "https://Stackoverflow.com/users/79461", "pm_score": 0, "selected": false, "text": "/*\n * (swing1.1beta3)\n * \n * |-----------------------------------------------------|\n * | 1st | 2nd | 3rd |\n * |-----------------------------------------------------|\n * | | | | | | |\n */\n//package jp.gr.java_conf.tame.swing.examples;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\nimport jp.gr.java_conf.tame.swing.table.*;\n\n/**\n * @version 1.0 11/09/98\n */\npublic class MultiWidthHeaderExample extends JFrame {\n\n MultiWidthHeaderExample() {\n super( \"Multi-Width Header Example\" );\n\n DefaultTableModel dm = new DefaultTableModel();\n dm.setDataVector(new Object[][]{\n {\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"},\n {\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"}},\n new Object[]{\"1 st\",\"\",\"\",\"\",\"\",\"\"});\n\n JTable table = new JTable( dm ) {\n protected JTableHeader createDefaultTableHeader() {\n return new GroupableTableHeader(columnModel);\n }\n };\n TableColumnModel cm = table.getColumnModel();\n ColumnGroup g_2nd = new ColumnGroup(\"2 nd\");\n g_2nd.add(cm.getColumn(1));\n g_2nd.add(cm.getColumn(2));\n ColumnGroup g_3rd = new ColumnGroup(\"3 rd\");\n g_3rd.add(cm.getColumn(3));\n g_3rd.add(cm.getColumn(4));\n g_3rd.add(cm.getColumn(5));\n GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();\n header.addColumnGroup(g_2nd);\n header.addColumnGroup(g_3rd);\n JScrollPane scroll = new JScrollPane( table );\n getContentPane().add( scroll );\n setSize( 400, 100 ); \n header.revalidate(); \n }\n\n public static void main(String[] args) {\n MultiWidthHeaderExample frame = new MultiWidthHeaderExample();\n frame.addWindowListener( new WindowAdapter() {\n public void windowClosing( WindowEvent e ) {\n System.exit(0);\n }\n });\n frame.setVisible(true);\n }\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
146,522
<p>I’ve got a brand new Django project. I’ve added one minimal view function to <code>views.py</code>, and one URL pattern to <code>urls.py</code>, passing the view by function reference instead of a string:</p> <pre><code># urls.py # ------- # coding=utf-8 from django.conf.urls.defaults import * from myapp import views urlpatterns = patterns('', url(r'^myview/$', views.myview), ) # views.py ---------- # coding=utf-8 from django.http import HttpResponse def myview(request): return HttpResponse('MYVIEW LOL', content_type="text/plain") </code></pre> <p>I’m trying to use <code>reverse()</code> to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern:</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; import urls &gt;&gt;&gt; from myapp import views &gt;&gt;&gt; urls.urlpatterns[0].callback is views.myview True &gt;&gt;&gt; reverse(views.myview) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse *args, **kwargs))) File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse "arguments '%s' not found." % (lookup_view, args, kwargs)) NoReverseMatch: Reverse for '&lt;function myview at 0x6fe6b0&gt;' with arguments '()' and keyword arguments '{}' not found. </code></pre> <p>As far as I can tell from the documentation, function references should be fine in both the URL pattern and <code>reverse()</code>.</p> <ul> <li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings" rel="noreferrer">URL patterns with function references</a></li> <li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse" rel="noreferrer"><code>reverse</code> with function references</a></li> </ul> <p>I’m using the Django trunk, revision 9092.</p>
[ { "answer_id": 146524, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "myproject.myapp.views myapp.views settings.py ROOT_URLCONF = `myproject.urls`\n >>> from django.core.urlresolvers import reverse\n>>> from myproject.myapp import views\n>>> reverse(views.myview)\n'/myview/'\n >>> from django.core import urlresolvers\n>>> from myapp import myview\n>>> urlresolvers.get_resolver (None).reverse_dict\n{None: ([(u'myview/', [])], 'myview/$'), <function myview at 0x845d17c>: ([(u'myview/', [])], 'myview/$')}\n>>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]\n>>> reverse(v1)\n'/myview/'\n>>> v1 is myview\nFalse\n>>> v1.__module__\n'testproject.myapp.views'\n>>> myview.__module__\n'myapp.views'\n r'^myview/$' reverse ('myapp.myview') urls.py myapp myproject/myapp/urls.py myproject/urls.py from django.conf.urls.defaults import patterns\nurlpatterns = patterns ('',\n (r'^/', 'myapp.urls'),\n)\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20578/" ]
146,528
<p>Say I'm writing some ruby code and I want to use the standard Date type to get the current date. Instead of using a search engine, is there a faster way to find the documentation for this class? I know I can get the methods for Date by typing <code>Date.methods</code>, but as far as I know this doesn't provide details about argument types or return value.</p> <p>Editor-specific answers are welcomed. My editor of choice is Emacs.</p>
[ { "answer_id": 146536, "author": "scable", "author_id": 8942, "author_profile": "https://Stackoverflow.com/users/8942", "pm_score": 2, "selected": false, "text": "ri Date\n ri Date#yourMethod\n" }, { "answer_id": 146601, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": true, "text": "ri ri ri" }, { "answer_id": 29442474, "author": "Manav", "author_id": 141220, "author_profile": "https://Stackoverflow.com/users/141220", "pm_score": 0, "selected": false, "text": "$ cd ~/.rvm/src\n$ rvm docs generate-ri\n ri $ irb\nirb(main):001:0> help 'String#chomp'\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22423/" ]
146,531
<p>I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories?</p>
[ { "answer_id": 146535, "author": "Davide Vosti", "author_id": 1812, "author_profile": "https://Stackoverflow.com/users/1812", "pm_score": 3, "selected": false, "text": "delete from table where id not in (\n select id from table \n order by id desc \n limit 50\n)\n" }, { "answer_id": 146540, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": -1, "selected": false, "text": "DELETE FROM _table_ \nWHERE _date_ NOT IN (SELECT _date_ FROM _table_ ORDER BY _date_ DESC LIMIT 50)\n" }, { "answer_id": 146541, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": -1, "selected": false, "text": "SELECT timestampcol FROM table ORDER BY timestampcol DESC LIMIT 49,1;\n DELETE FROM table WHERE timestampcol < ( SELECT timestampcol FROM table ORDER BY timestampcol DSEC LIMIT 49,1 )\n IN" }, { "answer_id": 146621, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 2, "selected": false, "text": "select count(*) from table;\n delete from table order by timestamp limit result - 50;\n" }, { "answer_id": 146629, "author": "Gilean", "author_id": 6305, "author_profile": "https://Stackoverflow.com/users/6305", "pm_score": 4, "selected": true, "text": "SELECT unixTime FROM entries ORDER BY unixTime DESC LIMIT 49, 1;\nDELETE FROM entries WHERE unixTime < $sqlResult;\n" }, { "answer_id": 64186858, "author": "Paul Brownsea", "author_id": 974736, "author_profile": "https://Stackoverflow.com/users/974736", "pm_score": 0, "selected": false, "text": "DELETE FROM `table` WHERE `datetime` < (SELECT `datetime` FROM `table` ORDER BY `datetime` DESC LIMIT 49,1); table datetime" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ]
146,557
<p>I was reading a question about the Python <em>global</em> statement ( <a href="https://stackoverflow.com/questions/146359/python-scope">"Python scope"</a> ) and I was remembering about how often I used this statement when I was a Python beginner (I used <em>global</em> a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".<br></p> <p>Do you use this statement in Python ? Has your usage of it changed with time ?</p>
[ { "answer_id": 146673, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 3, "selected": false, "text": "global global" }, { "answer_id": 146985, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 6, "selected": false, "text": "_cached_result = None\ndef myComputationallyExpensiveFunction():\n global _cached_result\n if _cached_result:\n return _cached_result\n\n # ... figure out result\n\n _cached_result = result\n return result\n def myComputationallyExpensiveFunction():\n if myComputationallyExpensiveFunction.cache:\n return myComputationallyExpensiveFunction.cache\n\n # ... figure out result\n\n myComputationallyExpensiveFunction.cache = result\n return result\nmyComputationallyExpensiveFunction.cache = None\n" }, { "answer_id": 6523333, "author": "Adam Rossmiller", "author_id": 821450, "author_profile": "https://Stackoverflow.com/users/821450", "pm_score": 3, "selected": false, "text": "discretes = 0\ndef use_discretes():\n #this global statement is a message to the parser to refer \n #to the globally defined identifier \"discretes\"\n global discretes\n if using_real_hardware():\n discretes = 1\n...\n file1.py:\n def setup():\n global DISP1, DISP2, DISP3\n DISP1 = grab_handle('display_1')\n DISP2 = grab_handle('display_2')\n DISP3 = grab_handle('display_3')\n ...\n\nfile2.py:\n import file1\n\n file1.setup()\n #file1.DISP1 DOES NOT EXIST until after setup() is called.\n file1.DISP1.resolution = 1024, 768\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20037/" ]
146,575
<p>I'm writing a program (for Mac OS X, using Objective-C) and I need to create a bunch of .webloc files programmatically.</p> <p>The .webloc file is simply file which is created after you drag-n-drop an URL from Safari's location bar to some folder.</p> <p>Generally speaking, I need an approach to create items in a filesystem which point to some location in the Web. As I understand .webloc files should be used for this on Mac OS X.</p> <p>So, is it possible to craft a .webloc file having a valid url and some title for it?</p>
[ { "answer_id": 146630, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 3, "selected": false, "text": ".webloc .webloc % DeRez \"Desktop/Crafting .webloc file - Stack Overflow.webloc\"\ndata 'drag' (128, \"Crafting .webloc file -#1701953\") {\n $\"0000 0001 0000 0000 0000 0000 0000 0003\" /* ................ */\n $\"5445 5854 0000 0100 0000 0000 0000 0000\" /* TEXT............ */\n $\"7572 6C20 0000 0100 0000 0000 0000 0000\" /* url ............ */\n $\"7572 6C6E 0000 0100 0000 0000 0000 0000\" /* urln............ */\n};\n\ndata 'url ' (256, \"Crafting .webloc file -#1701953\") {\n $\"6874 7470 3A2F 2F73 7461 636B 6F76 6572\" /* http://stackover */\n $\"666C 6F77 2E63 6F6D 2F71 7565 7374 696F\" /* flow.com/questio */\n $\"6E73 2F31 3436 3537 352F 6372 6166 7469\" /* ns/146575/crafti */\n $\"6E67 2D77 6562 6C6F 632D 6669 6C65\" /* ng-webloc-file */\n};\n\ndata 'TEXT' (256, \"Crafting .webloc file -#1701953\") {\n $\"6874 7470 3A2F 2F73 7461 636B 6F76 6572\" /* http://stackover */\n $\"666C 6F77 2E63 6F6D 2F71 7565 7374 696F\" /* flow.com/questio */\n $\"6E73 2F31 3436 3537 352F 6372 6166 7469\" /* ns/146575/crafti */\n $\"6E67 2D77 6562 6C6F 632D 6669 6C65\" /* ng-webloc-file */\n};\n\ndata 'urln' (256, \"Crafting .webloc file -#1701953\") {\n $\"4372 6166 7469 6E67 202E 7765 626C 6F63\" /* Crafting .webloc */\n $\"2066 696C 6520 2D20 5374 6163 6B20 4F76\" /* file - Stack Ov */\n $\"6572 666C 6F77\" /* erflow */\n};\n 'url ' 'TEXT' 'urln' 'drag'" }, { "answer_id": 146633, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 3, "selected": false, "text": ".webloc 'url ' 'TEXT' 'drag' 'urln'" }, { "answer_id": 146964, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 6, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>URL</key>\n <string>http://apple.com</string>\n</dict>\n</plist>\n" }, { "answer_id": 147927, "author": "Yurii Soldak", "author_id": 20294, "author_profile": "https://Stackoverflow.com/users/20294", "pm_score": 3, "selected": false, "text": ".url [InternetShortcut]\nURL=http://www.apple.com/\n" }, { "answer_id": 12278748, "author": "Nick Moore", "author_id": 220847, "author_profile": "https://Stackoverflow.com/users/220847", "pm_score": 0, "selected": false, "text": "// data for 'drag' resource (it's always the same)\n#define DRAG_DATA_LENGTH 64\nstatic const unsigned char _dragData[DRAG_DATA_LENGTH]={\n 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,\n 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x75, 0x72, 0x6C, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x75, 0x72, 0x6C, 0x6E, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};\n\nstatic void _addData(NSData *data, ResType type, short resId, ResFileRefNum refNum)\n{\n Handle handle;\n if (PtrToHand([data bytes], &handle, [data length])==noErr) {\n ResFileRefNum previousRefNum=CurResFile();\n UseResFile(refNum);\n\n HLock(handle);\n AddResource(handle, type, resId, \"\\p\");\n HUnlock(handle);\n\n UseResFile(previousRefNum);\n }\n}\n\nvoid WeblocCreateFile(NSString *location, NSString *name, NSURL *fileUrl)\n{\n NSString *contents=[NSString stringWithFormat:\n @\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n @\"<!DOCTYPE plist PUBLIC \\\"-//Apple//DTD PLIST 1.0//EN\\\" \\\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\\\">\\n\"\n @\"<plist version=\\\"1.0\\\">\\n\"\n @\"<dict>\\n\"\n @\"<key>URL</key>\\n\"\n @\"<string>%@</string>\\n\"\n @\"</dict>\\n\"\n @\"</plist>\\n\", location];\n\n if ([[contents dataUsingEncoding:NSUTF8StringEncoding] writeToURL:fileUrl options:NSDataWritingAtomic error:nil])\n { \n // split into parent and filename parts\n NSString *parentPath=[[fileUrl URLByDeletingLastPathComponent] path];\n NSString *fileName=[fileUrl lastPathComponent];\n\n FSRef parentRef;\n if(FSPathMakeRef((const UInt8 *)[parentPath fileSystemRepresentation], &parentRef, NULL)==noErr)\n {\n unichar fileNameBuffer[[fileName length]];\n [fileName getCharacters:fileNameBuffer];\n\n FSCreateResFile(&parentRef, [fileName length], fileNameBuffer, 0, NULL, NULL, NULL);\n if (ResError()==noErr)\n {\n FSRef fileRef;\n if(FSPathMakeRef((const UInt8 *)[[fileUrl path] fileSystemRepresentation], &fileRef, NULL)==noErr)\n {\n ResFileRefNum resFileReference = FSOpenResFile(&fileRef, fsWrPerm);\n if (resFileReference>0 && ResError()==noErr)\n {\n _addData([NSData dataWithBytes:_dragData length:DRAG_DATA_LENGTH], 'drag', 128, resFileReference);\n _addData([location dataUsingEncoding:NSUTF8StringEncoding], 'url ', 256, resFileReference);\n _addData([location dataUsingEncoding:NSUTF8StringEncoding], 'TEXT', 256, resFileReference);\n _addData([name dataUsingEncoding:NSUTF8StringEncoding], 'urln', 256, resFileReference);\n CloseResFile(resFileReference);\n }\n }\n }\n }\n }\n}\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20294/" ]
146,576
<p>The method signature of a Java <code>main</code>method is:</p> <pre><code>public static void main(String[] args) { ... } </code></pre> <p><strong>Is there a reason why this method must be static?</strong></p>
[ { "answer_id": 146583, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 8, "selected": false, "text": "main main" }, { "answer_id": 146662, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 9, "selected": true, "text": "public class JavaClass{\n protected JavaClass(int x){}\n public void main(String[] args){\n }\n}\n new JavaClass(int) x JavaClass main main public" }, { "answer_id": 5841473, "author": "Abhishek", "author_id": 732351, "author_profile": "https://Stackoverflow.com/users/732351", "pm_score": 2, "selected": false, "text": "public public public private main() public static main() main() void main()" }, { "answer_id": 11423098, "author": "Sam Harwell", "author_id": 138304, "author_profile": "https://Stackoverflow.com/users/138304", "pm_score": 2, "selected": false, "text": "static void main() void main() Program new Program() static void main() main() void main() new ClassName() main() new ClassName() new ClassName() main() main() static void main() main() main()" }, { "answer_id": 11444861, "author": "yorkw", "author_id": 873875, "author_profile": "https://Stackoverflow.com/users/873875", "pm_score": 5, "selected": false, "text": "public static void main(String[] args)\n public static void main(String... args)\n ../launcher/java.c java [-options] class [args...] /*\n * Get the application's main class.\n * ... ...\n */\nif (jarfile != 0) {\n mainClassName = GetMainClassName(env, jarfile);\n\n... ...\n\n mainClass = LoadClass(env, classname);\n if(mainClass == NULL) { /* exception occured */\n\n... ...\n\n/* Get the application's main method */\nmainID = (*env)->GetStaticMethodID(env, mainClass, \"main\",\n \"([Ljava/lang/String;)V\");\n\n... ...\n\n{ /* Make sure the main method is public */\n jint mods;\n jmethodID mid;\n jobject obj = (*env)->ToReflectedMethod(env, mainClass,\n mainID, JNI_TRUE);\n\n... ...\n\n/* Build argument array */\nmainArgs = NewPlatformStringArray(env, argv, argc);\nif (mainArgs == NULL) {\n ReportExceptionDescription(env);\n goto leave;\n}\n\n/* Invoke main method. */\n(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);\n\n... ...\n" }, { "answer_id": 11473329, "author": "alain.janinm", "author_id": 1140748, "author_profile": "https://Stackoverflow.com/users/1140748", "pm_score": 2, "selected": false, "text": "public static void main(String[]) <clinit> <init>" }, { "answer_id": 11491829, "author": "A.H.", "author_id": 947357, "author_profile": "https://Stackoverflow.com/users/947357", "pm_score": 5, "selected": false, "text": "static class MyApplication {\n public MyApplication(){\n // Some init code here\n }\n public void main(String[] args){\n // real application code here\n }\n}\n main main abstract static main abstract" }, { "answer_id": 11643561, "author": "gnat", "author_id": 839601, "author_profile": "https://Stackoverflow.com/users/839601", "pm_score": 2, "selected": false, "text": "Application public static void main(String[] args)" }, { "answer_id": 17517621, "author": "Isabella Engineer", "author_id": 2558244, "author_profile": "https://Stackoverflow.com/users/2558244", "pm_score": 3, "selected": false, "text": "public static void main(String args[]) public static main() main() class demo { \n private int length;\n private static int breadth;\n void output(){\n length=5;\n System.out.println(length);\n }\n\n static void staticOutput(){\n breadth=10; \n System.out.println(breadth);\n }\n\n public static void main(String args[]){\n demo d1=new demo();\n d1.output(); // Note here output() function is not static so here\n // we need to create object\n staticOutput(); // Note here staticOutput() function is static so here\n // we needn't to create object Similar is the case with main\n /* Although:\n demo.staticOutput(); Works fine\n d1.staticOutput(); Works fine */\n }\n}\n void main() String[] args main() args String" }, { "answer_id": 28099497, "author": "Sourav Saha", "author_id": 3475143, "author_profile": "https://Stackoverflow.com/users/3475143", "pm_score": 0, "selected": false, "text": "Class_name.method_name(); static main() Class_name.method_name();\n main() String main(String args[])" }, { "answer_id": 30140527, "author": "Lordferrous ", "author_id": 4786435, "author_profile": "https://Stackoverflow.com/users/4786435", "pm_score": 4, "selected": false, "text": "public static void main(String args[])\n main() public static main() void main()" }, { "answer_id": 42364080, "author": "Basheer AL-MOMANI", "author_id": 4251431, "author_profile": "https://Stackoverflow.com/users/4251431", "pm_score": 3, "selected": false, "text": "java java ClassName argument1 argument2 ...\n main allows invoke without instance ClassName command-line argument list of Strings String[] args" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2937/" ]
146,602
<p>Has anyone had any recent requirements for programming automated DOS Batch style tasks on a Windows box?</p> <p>I've got some automation to do and I'd rather not sit and write a pile of .BAT files in Notepad if there is a better way of automating these tasks: mainly moving of files under certain date and time conditions, as well as triggering Windows applications before and after moving the files.</p> <p>I am thinking along the lines of an IDE that has all the DOS commands 'available' to the editor with the correct parameter syntax checking. Is there anything like this out there, or should I be solving this problem with something other than .BAT files?</p>
[ { "answer_id": 146619, "author": "Bullines", "author_id": 27870, "author_profile": "https://Stackoverflow.com/users/27870", "pm_score": 3, "selected": false, "text": "Dim objFSO\n\nSet objFSO = CreateObject (\"Scripting.FileSystemObject\")\nIf objFSO.FileExists(\"C:\\source\\your_file.txt\") Then\n objFSO.CopyFile \"C:\\source\\your_file.txt\", \"C:\\destination\\your_file.txt\"\nEndIf\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22376/" ]
146,604
<p>I have a new object with a collection of new objects within it on some property as an IList. I see through sql profiler two insert queries being executed.. one for the parent, which has the new guid id, and one for the child, however, the foreign-key on the child that references the parent, is an empty guid. Here is my mapping on the parent: </p> <pre><code>&lt;id name="BackerId"&gt; &lt;generator class="guid" /&gt; &lt;/id&gt; &lt;property name="Name" /&gt; &lt;property name="PostCardSizeId" /&gt; &lt;property name="ItemNumber" /&gt; &lt;bag name="BackerEntries" table="BackerEntry" cascade="all" lazy="false" order-by="Priority"&gt; &lt;key column="BackerId" /&gt; &lt;one-to-many class="BackerEntry" /&gt; &lt;/bag&gt; </code></pre> <p>On the Backer.cs class, I defined BackerEntries property as </p> <pre><code>IList&lt;BackerEntry&gt; </code></pre> <p>When I try to SaveOrUpdate the passed in entity I get the following results in sql profiler:</p> <p>exec sp_executesql N'INSERT INTO Backer (Name, PostCardSizeId, ItemNumber, BackerId) VALUES (@p0, @p1, @p2, @p3)',N'@p0 nvarchar(3),@p1 uniqueidentifier,@p2 nvarchar(3),@p3 uniqueidentifier',@p0=N'qaa',@p1='BC95E7EB-5EE8-44B2-82FF30F5176684D',@p2=N'qaa',@p3='18FBF8CE-FD22-4D08-A3B1-63D6DFF426E5'</p> <p>exec sp_executesql N'INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7)',N'@p0 uniqueidentifier,@p1 uniqueidentifier,@p2 nvarchar(5),@p3 nvarchar(5),@p4 int,@p5 bit,@p6 int,@p7 uniqueidentifier',@p0='00000000-0000-0000-0000-000000000000',@p1='2C5BDD33-5DD3-42EC-AA0E-F1E548A5F6E4',@p2=N'qaadf',@p3=N'wasdf',@p4=0,@p5=1,@p6=0,@p7='FE9C4A35-6211-4E17-A75A-60CCB526F1CA'</p> <p>As you can see, its not resetting the empty guid for BackerId on the child to the new real guid of the parent.</p> <p>Finally, the exception throw is: </p> <pre><code>"NHibernate.Exceptions.GenericADOException: could not insert: [CB.ThePostcardCompany.MiddleTier.BackerEntry][SQL: INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)] ---\u003e System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint </code></pre> <p>EDIT: SOLVED! The first answer below pointed me into the correct direction. I needed to add that back reference on the child mapping and class. This allowed it to work in a purely .net way - however, when accepting json, there was a disconnect so I had to come up with some quirky code to 're-attach' the children.</p>
[ { "answer_id": 146640, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 4, "selected": true, "text": "<bag name=\"BackerEntries\" table=\"BackerEntry\" cascade=\"all\" lazy=\"false\" order-by=\"Priority\">\n <key column=\"BackerId\" not-null=\"true\"/>\n <one-to-many class=\"BackerEntry\" />\n</bag>\n <many-to-one name=\"parent\" column=\"PARENT_ID\" not-null=\"true\"/>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
146,607
<p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p> <p>This input:</p> <blockquote> The Web </blockquote> <p>Should produce this output:</p> <blockquote> <p>The Web This Is A Test Variable</p> </blockquote> <p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p> <p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p> <pre><code>def stripMatchedQuotes(item): MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE) MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE) item = MatchedSingleQuotes.sub(r'\1', item, 1) item = MatchedDoubleQuotes.sub(r'\1', item, 1) return item def processVariables(item): VariableDefinition = re.compile(r'&lt;%(.*?)=(.*?)%&gt;', re.LOCALE) VariableUse = re.compile(r'&lt;%(.*?)%&gt;', re.LOCALE) Variables={} while VariableDefinition.search(item): VarName, VarDef = VariableDefinition.search(item).groups() VarName = stripMatchedQuotes(VarName).upper().strip() VarDef = stripMatchedQuotes(VarDef.strip()) Variables[VarName] = VarDef item = VariableDefinition.sub('', item, 1) while VariableUse.search(item): VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip() item = VariableUse.sub(Variables[VarName], item, 1) return item </code></pre>
[ { "answer_id": 146639, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 1, "selected": false, "text": "r\"(\\\"|')(.*?)\\1\" \\1" }, { "answer_id": 146671, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 5, "selected": true, "text": "MatchedQuotes = re.compile(r\"(['\\\"])(.*)\\1\", re.LOCALE)\nitem = MatchedQuotes.sub(r'\\2', item, 1)\n VariableDefinition = re.compile(r'<%([\"\\']?)(.*?)\\1=([\"\\']?)(.*?)\\3%>', re.LOCALE)\nVarRepl = re.compile(r'<%([\"\\']?)(.*?)\\1%>', re.LOCALE)\n\ndef processVariables(item):\n vars = {}\n def findVars(m):\n vars[m.group(2).upper()] = m.group(4)\n return \"\"\n\n item = VariableDefinition.sub(findVars, item)\n return VarRepl.sub(lambda m: vars[m.group(2).upper()], item)\n\nprint processVariables('<%\"TITLE\"=\"This Is A Test Variable\"%>The Web <%\"TITLE\"%>')\n Original : 13.637\nGlobal regexes : 12.771\nSingle regex : 9.095\nFinal version : 1.846\n" }, { "answer_id": 146683, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "sub >>> import re\n>>> var_matcher = re.compile(r'<%(.*?)%>', re.LOCALE)\n>>> string = '<%\"TITLE\"%> <%\"SHMITLE\"%>'\n>>> values = {'\"TITLE\"': \"I am a title.\", '\"SHMITLE\"': \"And I am a shmitle.\"}\n>>> var_matcher.sub(lambda m: vars[m.group(1)], string)\n'I am a title. And I am a shmitle.\n \"\"" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19207/" ]
146,622
<p>I'm in the process of learning Erlang. As an exercise I picked up the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">Sieve of Eratosthenes</a> algorithm of generating prime numbers. Here is my code:</p> <pre><code>-module(seed2). -export([get/1]). get(N) -&gt; WorkList = lists:duplicate(N, empty), get(2, N, WorkList, []). get(thats_the_end, _N, _WorkList, ResultList) -&gt; lists:reverse(ResultList); get(CurrentPrime, N, WorkList, ResultList) -&gt; ModWorkList = markAsPrime(CurrentPrime, N, WorkList), NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList), get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]). markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =&lt; N -&gt; WorkListMod = replace(CurrentPrime, WorkList, prime), markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod). markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark &gt; N -&gt; WorkList; markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -&gt; WorkListMod = replace(TheCurrentMark, WorkList, marked), markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod). findNextPrime(Iterator, N, _WorkList) when Iterator &gt; N -&gt; thats_the_end; findNextPrime(Iterator, N, WorkList) -&gt; I = lists:nth(Iterator, WorkList), if I =:= empty -&gt; Iterator; true -&gt; findNextPrime(Iterator + 1, N, WorkList) end. replace(N, L, New)-&gt; {L1, [_H|L2]} = lists:split(N - 1, L), lists:append(L1, [New|L2]). </code></pre> <p>This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation. </p> <p>My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"</p> <p>EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? </p>
[ { "answer_id": 172611, "author": "Andreas", "author_id": 25328, "author_profile": "https://Stackoverflow.com/users/25328", "pm_score": 5, "selected": true, "text": "-module(primes).\n-export([sieve/1]).\n-include_lib(\"eunit/include/eunit.hrl\").\n\nsieve([]) ->\n [];\nsieve([H|T]) -> \n List = lists:filter(fun(N) -> N rem H /= 0 end, T),\n [H|sieve(List)];\nsieve(N) ->\n sieve(lists:seq(2,N)).\n" }, { "answer_id": 203110, "author": "Roskoto", "author_id": 13635, "author_profile": "https://Stackoverflow.com/users/13635", "pm_score": -1, "selected": false, "text": "-module(seed4).\n-export([get/1]).\n\nget(N) -> WorkList = array:new([{size, N}, {default, empty}]),\n get(2, N, WorkList, []).\n\nget(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);\nget(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),\n NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),\n get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).\n\n\nmarkAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),\n markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).\n\nmarkAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;\nmarkAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),\n markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).\n\nfindNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;\nfindNextPrime(Iterator, N, WorkList) -> I = array:get(Iterator - 1, WorkList),\n if\n I =:= empty -> Iterator;\n true -> findNextPrime(Iterator + 1, N, WorkList)\n end.\n\nreplace(N, L, New) -> array:set(N - 1, New, L).\n" }, { "answer_id": 290718, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Sum of all primes below Max. Will use sieve of Eratosthenes \nsum_primes(Max) ->\n LastCheck = round(math:sqrt(Max)),\n All = lists:seq(3, Max, 2), %note are creating odd-only array\n Primes = sieve(All, Max, LastCheck),\n %io:format(\"Primes: ~p~n\", [Primes]),\n lists:sum(Primes) + 2. %adding back the number 2 to the list\n\n%sieve of Eratosthenes\nsieve(All, Max, LastCheck) ->\n sieve([], All, Max, LastCheck).\n\nsieve(Primes, All, Max, LastCheck) ->\n %swap the first element of All onto Primes \n [Cur|All2] = All,\n Primes2 = [Cur|Primes],\n case Cur > LastCheck of \n true ->\n lists:append(Primes2, All2); %all known primes and all remaining from list (not sieved) are prime\n false -> \n All3 = lists:filter(fun(X) -> X rem Cur =/= 0 end, All2),\n sieve(Primes2, All3, Max, LastCheck)\n\n end.\n" }, { "answer_id": 382698, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "\n-module(test).\n\n%%-export([sum_primes/1]).\n-compile(export_all).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%Sum of all primes below Max. Will use sieve of Eratosthenes \nsum_primes(Max) ->\n LastCheck = round(math:sqrt(Max)),\n All = lists:seq(3, Max, 2), %note are creating odd-only array\n %%Primes = sieve(noref,All, LastCheck),\n Primes = spawn_sieve(All, LastCheck),\n lists:sum(Primes) + 2. %adding back the number 2 to the list\n\n\n%%sieve of Eratosthenes\nsieve(Ref,All, LastCheck) ->\n sieve(Ref,[], All, LastCheck).\n\nsieve(noref,Primes, All = [Cur|_], LastCheck) when Cur > LastCheck ->\n lists:reverse(Primes, All); %all known primes and all remaining from list (not sieved) are prime \nsieve({Pid,Ref},Primes, All=[Cur|_], LastCheck) when Cur > LastCheck ->\n Pid ! {Ref,lists:reverse(Primes, All)}; \nsieve(Ref,Primes, [Cur|All2], LastCheck) ->\n %%All3 = lists:filter(fun(X) -> X rem Cur =/= 0 end, All2),\n All3 = lists_filter(Cur,All2),\n sieve(Ref,[Cur|Primes], All3, LastCheck).\n\n\nlists_filter(Cur,All2) ->\n lists_filter(Cur,All2,[]).\n\nlists_filter(V,[H|T],L) ->\n case H rem V of\n 0 ->\n lists_filter(V,T,L);\n _ ->\n lists_filter(V,T,[H|L])\n end;\nlists_filter(_,[],L) ->\n lists:reverse(L).\n\n\n%% This is a sloppy implementation ;)\nspawn_sieve(All,Last) ->\n %% split the job\n {L1,L2} = lists:split(round(length(All)/2),All),\n Filters = filters(All,Last),\n L3 = lists:append(Filters,L2),\n Pid = self(),\n Ref1=make_ref(),\n Ref2=make_ref(),\n erlang:spawn(?MODULE,sieve,[{Pid,Ref1},L1,Last]),\n erlang:spawn(?MODULE,sieve,[{Pid,Ref2},L3,Last]),\n Res1=receive\n {Ref1,R1} ->\n {1,R1};\n {Ref2,R1} ->\n {2,R1}\n end,\n Res2= receive\n {Ref1,R2} ->\n {1,R2};\n {Ref2,R2} ->\n {2,R2}\n end,\n apnd(Filters,Res1,Res2).\n\n\nfilters([H|T],Last) when H \n [H|filters(T,Last)];\nfilters([H|_],_) ->\n [H];\nfilters(_,_) ->\n [].\n\n\napnd(Filters,{1,N1},{2,N2}) ->\n lists:append(N1,subtract(N2,Filters));\napnd(Filters,{2,N2},{1,N1}) ->\n lists:append(N1,subtract(N2,Filters)).\n\n\n\nsubtract([H|L],[H|T]) ->\n subtract(L,T);\nsubtract(L=[A|_],[B|_]) when A > B ->\n L;\nsubtract(L,[_|T]) ->\n subtract(L,T);\nsubtract(L,[]) ->\n L.\n" }, { "answer_id": 599002, "author": "matt_h", "author_id": 72346, "author_profile": "https://Stackoverflow.com/users/72346", "pm_score": 3, "selected": false, "text": "primes(Prime, Max, Primes,Integers) when Prime > Max ->\n lists:reverse([Prime|Primes]) ++ Integers;\nprimes(Prime, Max, Primes, Integers) ->\n [NewPrime|NewIntegers] = [ X || X <- Integers, X rem Prime =/= 0 ],\n primes(NewPrime, Max, [Prime|Primes], NewIntegers).\n\nprimes(N) ->\n primes(2, round(math:sqrt(N)), [], lists:seq(3,N,2)). % skip odds\n" }, { "answer_id": 955210, "author": "G B", "author_id": 113644, "author_profile": "https://Stackoverflow.com/users/113644", "pm_score": 1, "selected": false, "text": "-module(primes).\n-export([primes/1, primes/2]).\n\nprimes(X) -> sieve(range(2, X)).\nprimes(X, Y) -> remove(primes(X), primes(Y)).\n\nrange(X, X) -> [X];\nrange(X, Y) -> [X | range(X + 1, Y)].\n\nsieve([X]) -> [X];\nsieve([H | T]) -> [H | sieve(remove([H * X || X <-[H | T]], T))].\n\nremove(_, []) -> [];\nremove([H | X], [H | Y]) -> remove(X, Y);\nremove(X, [H | Y]) -> [H | remove(X, Y)].\n" }, { "answer_id": 15122408, "author": "George Payne", "author_id": 2102985, "author_profile": "https://Stackoverflow.com/users/2102985", "pm_score": 0, "selected": false, "text": " -module(sieve).\n -export([find/2,mark/2,primes/1]).\n\n primes(N) -> [2|lists:reverse(primes(lists:seq(2,N),2,[]))].\n\n primes(_,0,[_|T]) -> T;\n primes(L,P,Primes) -> NewList = mark(L,P),\n NewP = find(NewList,P),\n primes(NewList,NewP,[NewP|Primes]).\n\n find([],_) -> 0;\n find([H|_],P) when H > P -> H;\n find([_|T],P) -> find(T,P). \n\n\n mark(L,P) -> lists:reverse(mark(L,P,2,[])).\n\n mark([],_,_,NewList) -> NewList;\n mark([_|T],P,Counter,NewList) when Counter rem P =:= 0 -> mark(T,P,Counter+1,[P|NewList]);\n mark([H|T],P,Counter,NewList) -> mark(T,P,Counter+1,[H|NewList]). \n" }, { "answer_id": 21490400, "author": "Namdak Tönpa", "author_id": 1791822, "author_profile": "https://Stackoverflow.com/users/1791822", "pm_score": 0, "selected": false, "text": "S = lists:seq(2,100),\nlists:foldl(fun(A,X) -> X--[A] end,S,[Y||X<-S,Y<-S,X<math:sqrt(Y)+1,Y rem X==0]).\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13635/" ]
146,657
<p>I have a couple of header files, which boil down to:</p> <p>tree.h:</p> <pre><code>#include "element.h" typedef struct tree_ { struct *tree_ first_child; struct *tree_ next_sibling; int tag; element *obj; .... } tree; </code></pre> <p>and element.h:</p> <pre><code>#include "tree.h" typedef struct element_ { tree *tree_parent; char *name; ... } element; </code></pre> <p>The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.</p> <p>This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.</p> <p>How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)?</p>
[ { "answer_id": 146669, "author": "Michael Labbé", "author_id": 22244, "author_profile": "https://Stackoverflow.com/users/22244", "pm_score": 2, "selected": false, "text": "/* begin foo.h */\n#ifndef _FOO_H\n#define _FOO_H\n\n// Your code here\n\n#endif\n/* end foo.h */\n struct tree; /* element.h */\nstruct element; /* tree.h */\n" }, { "answer_id": 146691, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "#include \"element.h\"\n typedef struct element_ element;\n" }, { "answer_id": 146693, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 2, "selected": false, "text": "\n// tree.h:\n#ifndef TREE_H\n#define TREE_H\nstruct element;\nstruct tree\n{\n struct element *obj;\n ....\n};\n\n#endif\n\n// element.h:\n#ifndef ELEMENT_H\n#define ELEMENT_H\nstruct tree;\nstruct element\n{\n struct tree *tree_parent;\n ...\n};\n#endif\n" }, { "answer_id": 146694, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 6, "selected": true, "text": "// tell the compiler that element is a structure typedef:\ntypedef struct element_ element;\n\ntypedef struct tree_ tree;\nstruct tree_\n{\n tree *first_child;\n tree *next_sibling;\n int tag;\n\n // now you can declare pointers to the structure.\n element *obj;\n};\n" }, { "answer_id": 146697, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "struct element_;\ntypedef struct element_ element;\n" }, { "answer_id": 146707, "author": "dmeister", "author_id": 4194, "author_profile": "https://Stackoverflow.com/users/4194", "pm_score": 0, "selected": false, "text": " element.h:\nstruct tree_;\nstruct element_\n {\n struct tree_ *tree_parent;\n char *name;\n };\n\ntree.h:\nstruct element_;\nstruct tree_\n {\n struct tree_* first_child;\n struct tree_* next_sibling;\n int tag;\n struct element_ *obj;\n };\n" }, { "answer_id": 64030820, "author": "oakaigh", "author_id": 11934495, "author_profile": "https://Stackoverflow.com/users/11934495", "pm_score": 0, "selected": false, "text": "#include typedef /* a.h - dependency of b.h */\n#ifndef _A_H\n#define _A_H\n\n#include \"b.h\"\n\ntypedef struct a_p {\n b_t *b;\n} a_t;\n\n#endif // _A_H\n /* b.h - dependency of a.h */\n#ifndef _B_H\n#define _B_H\n\ntypedef struct b_p b_t;\n\n/** \n * !!!\n * to avoid recursion, only include \"a.h\" \n * when \"a.h\" isn't included before\n */\n#ifndef _A_H\n #include \"a.h\"\n typedef struct b_p {\n a_t a;\n } b_t;\n#endif\n\n#endif // _B_H\n include a.h #include \"a.h\"\n\nint main() {\n a_t aigh;\n\n return 0;\n}\n include" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19214/" ]
146,659
<p>I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is positioned with Javascript. The implementation I have right now is not particular elegant even with the Javascript, so my questions are:</p> <ol> <li>Is there a way to do this without Javascript?</li> <li>If I have to use Javascript, are there any "nice" solutions to this floating footer problem? By "nice" I mean something that will work across browsers, doesn't overload the browser's resources (since it will have to recalculate often), and is elegant/easy to use (i.e. it would be nice to write something like <code>new FloatingFooter("floatingDiv")</code>).</li> </ol> <p>I'm going to guess there is no super easy solution that has everything above, but something I can build off of would be great.</p> <p>Finally, just a more general question. I know this problem is a big pain to solve, so what are other UI alternatives rather than having footer content at the bottom of every page? On my particular site, I use it to show transitions between steps. Are there other ways I could do this?</p>
[ { "answer_id": 146689, "author": "Mattias", "author_id": 261, "author_profile": "https://Stackoverflow.com/users/261", "pm_score": 2, "selected": false, "text": ".footer {\n position: absolute;\n top: expression((document.body.clientHeight - myFooterheight) + \"px\");\n}\n" }, { "answer_id": 146718, "author": "qbeuek", "author_id": 5348, "author_profile": "https://Stackoverflow.com/users/5348", "pm_score": -1, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html>\n <head>\n <style>\n .content\n {\n position : absolute;\n top : 0;\n left : 0;\n right : 0;\n bottom : 50px; /* that's the height of the footer */\n overflow : auto;\n background-color : blue;\n }\n .footer\n {\n position : absolute;\n left : 0;\n right : 0;\n bottom : 0px; /* that's the height of the footer */\n height : 50px;\n overflow : hidden;\n background-color : green;\n }\n </style>\n </head>\n <body>\n <div class=\"content\">\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n </div>\n <div class=\"footer\">\n the footer\n </div>\n </body>\n</html>\n" }, { "answer_id": 147152, "author": "Taptronic", "author_id": 14728, "author_profile": "https://Stackoverflow.com/users/14728", "pm_score": 5, "selected": true, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<title>Liquid Footer</title>\n <style type=\"text/css\">\n .footer {\nbackground-color: #cdcdcd;\nheight: 180px;\ntext-align: center;\nfont-size:10px;\ncolor:#CC0000;\nfont-family:Verdana;\npadding-top: 10px;\nwidth: 100%;\nposition:fixed;\nleft: 0px;\nbottom: 0px;\n}\n </style>\n <!--[if lte IE 6]>\n <style type=\"text/css\">\n body {height:100%; overflow-y:auto;}\n html {overflow-x:auto; overflow-y:hidden;}\n * html .footer {position:absolute;}\n </style>\n <![endif]-->\n</head>\n\n<body>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n <div class=\"footer\">-- This is your liquid footer --</div>\n</body>\n</html>\n" }, { "answer_id": 150890, "author": "Morgan ARR Allen", "author_id": 22474, "author_profile": "https://Stackoverflow.com/users/22474", "pm_score": 0, "selected": false, "text": "height 100% overflow: auto <html/> <body/> <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html>\n <head>\n <style>\n html, body\n {\n height: 100%;\n overflow: auto;\n }\n\n .fixed\n {\n position: absolute;\n bottom: 0px;\n height: 40px;\n background: blue;\n width: 100%;\n }\n </style>\n </head>\n <body>\n <div class=\"fixed\"></div>\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br /><!-- ... -->\n </body>\n</html>\n" }, { "answer_id": 904738, "author": "Keith Bentrup", "author_id": 109826, "author_profile": "https://Stackoverflow.com/users/109826", "pm_score": 2, "selected": false, "text": "!important <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html>\n <head>\n <style>\n html {\n overflow-x: auto;\n overflow-y: scroll !important;\n overflow-y: hidden; /* ie6 value b/c !important ignored */\n }\n\n body {\n padding:0;\n margin:0;\n height: 100%;\n overflow-y: hidden !important;\n overflow-y: scroll; /* ie6 value b/c !important ignored */\n }\n\n #bottom {\n background-color:#ddd;\n position: fixed !important;\n position: absolute; /* ie6 value b/c !important ignored */\n width: 100%;\n bottom: 0px;\n z-index: 5;\n height:100px;\n }\n #content {\n font-size: 50px;\n }\n </style>\n </head> \n <body>\n <div id=\"bottom\">\n keep this text in the viewport at all times\n </div>\n <div id=\"content\">\n Let's create enough content to force scroll bar to appear.\n Then we can ensure this works when content overflows.\n One quick way to do this is to give this text a large font\n and throw on some extra line breaks.\n <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>\n <br/><br/><br/><br/><br/><br/><br/><br/> \n </div> \n </body> \n</html>\n" }, { "answer_id": 7950811, "author": "Greg", "author_id": 1021527, "author_profile": "https://Stackoverflow.com/users/1021527", "pm_score": 1, "selected": false, "text": "$(function(){\n positionFooter(); \n function positionFooter(){\n if($(document).height() < $(window).height()){//Without the body height conditional the footer will always stick to the bottom of the window, regardless of the body height, $(document).height() - could be main container/wrapper like $(\"#main\").height() it depend on your code\n $(\"#footer\").css({position: \"absolute\",top:($(window).scrollTop()+$(window).height()-$(\"#footer\").height())+\"px\"})\n } \n }\n\n $(window).scroll(positionFooter);\n $(window).resize(positionFooter);\n});\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
146,661
<p>Has anyone successfully built an Adobe Air application with Maven? If so, what are the steps to get it working?</p> <p>I have been trying to use <a href="http://code.google.com/p/flex-mojos/" rel="noreferrer">flex-mojos</a> to build an Air applications. When I set the packaging type to "aswf", as suggested in the <a href="http://code.google.com/p/flex-mojos/wiki/DashboardSamplePom" rel="noreferrer">DashboardSamplePom</a>, Maven complains that aswf is an unknown packaging type. I also found their <a href="http://svn.sonatype.org/flexmojos/repository/info/flex-mojos/air-super-pom/2.0-alpha4/air-super-pom-2.0-alpha4.pom" rel="noreferrer">air-super-pom</a>, but could not figure out how to reference it as the parent of my POM.</p>
[ { "answer_id": 146690, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 2, "selected": false, "text": "<plugin>\n <groupId>...</groupId>\n <artifactId>...</artifactId>\n <extensions>true</extensions>\n...\n</plugin>\n" }, { "answer_id": 684170, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 1, "selected": false, "text": "<parent>\n <groupId>org.sonatype.flexmojos</groupId>\n <artifactId>flexmojos-air-super-pom</artifactId>\n <version>3.1-SNAPSHOT</version>\n</parent>\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767/" ]
146,668
<p>In ruby I am parsing a date in the following format: 24092008. I want to convert each section (year, month, date) into a number.</p> <p>I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.</p> <pre><code> date =~ /^([\d]{2})([\d]{2})([\d]{4})/ year = Integer($3) month = Integer($2) day = Integer($1) </code></pre> <p>When it hits the month line it crashes as follows:</p> <pre><code>`Integer': invalid value for Integer: "09" (ArgumentError) </code></pre> <p>It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").</p> <p>Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?</p> <p>Thanks.</p>
[ { "answer_id": 146679, "author": "Atiaxi", "author_id": 2555346, "author_profile": "https://Stackoverflow.com/users/2555346", "pm_score": 5, "selected": true, "text": "irb(main):003:0> Integer(\"04\")\n=> 4\nirb(main):004:0> Integer(\"09\")\nArgumentError: invalid value for Integer: \"09\"\n from (irb):4:in `Integer'\n from (irb):4\n from :0\n irb(main):005:0> \"04\".to_i\n=> 4\nirb(main):006:0> \"09\".to_i\n=> 9\n" }, { "answer_id": 146717, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 1, "selected": false, "text": "(0([\\d])|([1-9][\\d])) ([\\d]{2}) (?:...) (?:0([\\d])|([1-9][\\d]))" }, { "answer_id": 31566372, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": false, "text": "Integer(\"09\", 10) # => 9\n .to_i \"123abc\".to_i # => 123\nInteger(\"123abc\", 10) # => ArgumentError\n irb method(:Integer) #<Method: Object(Kernel)#Integer> Kernel" }, { "answer_id": 71045978, "author": "Abhi", "author_id": 2968762, "author_profile": "https://Stackoverflow.com/users/2968762", "pm_score": 0, "selected": false, "text": "Integer(\"08016\") #=> ArgumentError: invalid value for Integer(): \"08016\" def is_numeric(data)\n _is_numeric = true if Integer(data) rescue false\n\n # To deal with Integers with leading 0\n if !_is_numeric\n _is_numeric = data.split(\"\").all?{|q| Integer(q.to_i).to_s == q }\n end\n\n _is_numeric\nend\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151/" ]
146,704
<p>Puzzled by the Lua 5.0 documentation references to things like <code>_LOADED</code>, <code>LUA_PATH</code>, <code>_ALERT</code> and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is <code>_VERSION</code>?</p>
[ { "answer_id": 146679, "author": "Atiaxi", "author_id": 2555346, "author_profile": "https://Stackoverflow.com/users/2555346", "pm_score": 5, "selected": true, "text": "irb(main):003:0> Integer(\"04\")\n=> 4\nirb(main):004:0> Integer(\"09\")\nArgumentError: invalid value for Integer: \"09\"\n from (irb):4:in `Integer'\n from (irb):4\n from :0\n irb(main):005:0> \"04\".to_i\n=> 4\nirb(main):006:0> \"09\".to_i\n=> 9\n" }, { "answer_id": 146717, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 1, "selected": false, "text": "(0([\\d])|([1-9][\\d])) ([\\d]{2}) (?:...) (?:0([\\d])|([1-9][\\d]))" }, { "answer_id": 31566372, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": false, "text": "Integer(\"09\", 10) # => 9\n .to_i \"123abc\".to_i # => 123\nInteger(\"123abc\", 10) # => ArgumentError\n irb method(:Integer) #<Method: Object(Kernel)#Integer> Kernel" }, { "answer_id": 71045978, "author": "Abhi", "author_id": 2968762, "author_profile": "https://Stackoverflow.com/users/2968762", "pm_score": 0, "selected": false, "text": "Integer(\"08016\") #=> ArgumentError: invalid value for Integer(): \"08016\" def is_numeric(data)\n _is_numeric = true if Integer(data) rescue false\n\n # To deal with Integers with leading 0\n if !_is_numeric\n _is_numeric = data.split(\"\").all?{|q| Integer(q.to_i).to_s == q }\n end\n\n _is_numeric\nend\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12291/" ]
146,715
<p>I want to create a class that, for example, extends HttpServlet? My compiler warns me that my class should have a serialVersionUID. If I know that this object will never be serialized, should I define it or add an annotation to suppress those warnings?</p> <p>What would you do and why?</p>
[ { "answer_id": 2831663, "author": "Mike", "author_id": 332658, "author_profile": "https://Stackoverflow.com/users/332658", "pm_score": 4, "selected": false, "text": "@SuppressWarnings(\"serial\") private void writeObject(ObjectOutputStream oos) throws IOException {\n throw new IOException(\"This class is NOT serializable.\");\n}\n" }, { "answer_id": 34287502, "author": "VasiliNovikov", "author_id": 1091436, "author_profile": "https://Stackoverflow.com/users/1091436", "pm_score": 1, "selected": false, "text": "javac -Xlint -Xlint:-serial *******" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11450/" ]
146,730
<p>Lifehacker had a post a couple days ago asking people about <a href="http://lifehacker.com/5054519/" rel="nofollow noreferrer">the best mouse you've ever had</a> and it appears some people have traded their mouse for a tablet.</p> <p>I'm curious if anyone here has traded their mouse in for a tablet? Does it work well for development? Looking for pros and cons from people who have tried it or are using it.</p> <p>Thanks.</p>
[ { "answer_id": 2831663, "author": "Mike", "author_id": 332658, "author_profile": "https://Stackoverflow.com/users/332658", "pm_score": 4, "selected": false, "text": "@SuppressWarnings(\"serial\") private void writeObject(ObjectOutputStream oos) throws IOException {\n throw new IOException(\"This class is NOT serializable.\");\n}\n" }, { "answer_id": 34287502, "author": "VasiliNovikov", "author_id": 1091436, "author_profile": "https://Stackoverflow.com/users/1091436", "pm_score": 1, "selected": false, "text": "javac -Xlint -Xlint:-serial *******" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519/" ]
146,737
<p>So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?</p>
[ { "answer_id": 146775, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 4, "selected": false, "text": "hash_method multiply square config_parser() do_hash_method() config_parser() do_hash_method() config_parser() function config_parser()\n{\n // Do some code here\n // $hash_method is in config_parser() local scope\n $hash_method = 'multiply';\n\n if ($hashing_enabled)\n {\n function do_hash_method($var)\n {\n // $hash_method is from the parent's local scope\n if ($hash_method == 'multiply')\n return $var * $var;\n else\n return $var ^ $var;\n }\n }\n}\n\n\nfunction hashme($val)\n{\n // do_hash_method still knows about $hash_method\n // even though it's not in the local scope anymore\n $val = do_hash_method($val)\n}\n" }, { "answer_id": 147115, "author": "grossvogel", "author_id": 14957, "author_profile": "https://Stackoverflow.com/users/14957", "pm_score": 3, "selected": false, "text": "class ConfigurableEncoder{\n private $algorithm = 'multiply'; //default is multiply\n\n public function encode($x){\n return call_user_func(array($this,$this->algorithm),$x);\n }\n\n public function multiply($x){\n return $x * 5;\n }\n\n public function add($x){\n return $x + 5;\n }\n\n public function setAlgorithm($algName){\n switch(strtolower($algName)){\n case 'add':\n $this->algorithm = 'add';\n break;\n case 'multiply': //fall through\n default: //default is multiply\n $this->algorithm = 'multiply';\n break;\n }\n }\n}\n\n$raw = 5;\n$encoder = new ConfigurableEncoder(); // set to multiply\necho \"raw: $raw\\n\"; // 5\necho \"multiply: \" . $encoder->encode($raw) . \"\\n\"; // 25\n$encoder->setAlgorithm('add');\necho \"add: \" . $encoder->encode($raw) . \"\\n\"; // 10\n" }, { "answer_id": 153361, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 7, "selected": true, "text": "function replace_spaces ($text) {\n $replacement = function ($matches) {\n return str_replace ($matches[1], ' ', '&nbsp;').' ';\n };\n return preg_replace_callback ('/( +) /', $replacement, $text);\n}\n replacement replace_spaces() $replacement" }, { "answer_id": 45921531, "author": "Hisham Dalal", "author_id": 2269902, "author_profile": "https://Stackoverflow.com/users/2269902", "pm_score": 1, "selected": false, "text": "// Author: HishamDalal@gamil.com\n// Publish on: 2017-08-28\n\nclass users\n{\n private $users = null;\n private $i = 5;\n\n function __construct(){\n // Get users from database\n $this->users = array('a', 'b', 'c', 'd', 'e', 'f');\n }\n\n function displayUsers($callback){\n for($n=0; $n<=$this->i; $n++){\n echo $callback($this->users[$n], $n);\n }\n }\n\n function showUsers($callback){\n return $callback($this->users);\n\n }\n\n function getUserByID($id, $callback){\n $user = isset($this->users[$id]) ? $this->users[$id] : null;\n return $callback($user);\n }\n\n}\n\n$u = new users();\n\n$u->displayUsers(function($username, $userID){\n echo \"$userID -> $username<br>\";\n});\n\n$u->showUsers(function($users){\n foreach($users as $user){\n echo strtoupper($user).' ';\n }\n\n});\n\n$x = $u->getUserByID(2, function($user){\n\n return \"<h1>$user</h1>\";\n});\n\necho ($x);\n 0 -> a\n1 -> b\n2 -> c\n3 -> d\n4 -> e\n5 -> f\n\nA B C D E F \n\nc\n" }, { "answer_id": 54981674, "author": "Harsh Gehlot", "author_id": 8684908, "author_profile": "https://Stackoverflow.com/users/8684908", "pm_score": 1, "selected": false, "text": " <?php\n $param='ironman';\n function sayhello(){\n $param='captain';\n $func=function () use ($param){\n $param='spiderman';\n };\n $func();\n echo $param;\n }\n sayhello();\n?>\n\n//output captain\n\n//and if we pass variable as a reference as(&$param) then output would be spider man;\n" }, { "answer_id": 65252274, "author": "Willem van der Veen", "author_id": 8059459, "author_profile": "https://Stackoverflow.com/users/8059459", "pm_score": 1, "selected": false, "text": "$arr = [1,2,3,3];\n$outersScopeNr = 2;\n\n// The second arg in array_filter is a closure\n// It would be inconvenient to have this function in global namespace\n// The use keyword lets us access a variable in an outer scope\n$newArr = array_filter($arr, function ($el) use ($outersScopeNr) {\n return $el === 3 || $el === $outersScopeNr;\n});\n\nvar_dump($newArr);\n// array (size=3)\n// 1 => int 2\n// 2 => int 3\n// 3 => int 3\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11252/" ]
146,743
<p>I need to store a list of key value pairs of (integer, boolean) in .NET</p> <p>When I use a dictionary it re-orders them. Is there a built in collection that will handle this.</p>
[ { "answer_id": 146751, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": " List<KeyValuePair<int, bool>> l = \n new List<KeyValuePair<int, bool>>();\n l.Add(new KeyValuePair<int, bool>(1, false));\n" }, { "answer_id": 146756, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 0, "selected": false, "text": "var myList = new List<KeyValuePair<int, bool>>();\n" }, { "answer_id": 146771, "author": "Caerbanog", "author_id": 23190, "author_profile": "https://Stackoverflow.com/users/23190", "pm_score": -1, "selected": false, "text": "SortedDictionary<Tkey, Tvalue>\n a < b\n" }, { "answer_id": 146856, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 0, "selected": false, "text": "KeyValuePair<int, bool>[] pairs\n List<KeyValuePair<int, bool>> \n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4998/" ]
146,750
<p>I'm setting up a new development server and want to install the latest version of SQL Server 2008 Express.</p> <p>Will our existing sql2005 databases work with 2008 without modification? If so is there any reason to install both versions on the same server?</p>
[ { "answer_id": 146776, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 3, "selected": true, "text": "with move restore database RESTORE DATABASE mydb FROM disk = 'c:\\backupfile.bak'\n WITH MOVE 'maindatafile' to 'c:\\newdatalocation.mdf',\n MOVE 'mainlogfile' to 'c:\\newloglocation.ldf'" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
146,777
<p>Specifically, when you create an interface/implementor pair, and there is no overriding organizational concern (such as the interface should go in a different assembly ie, as recommended by the s# architecture) do you have a default way of organizing them in your namespace/naming scheme?</p> <p>This is obviously a more opinion based question but I think some people have thought about this more and we can all benefit from their conclusions.</p>
[ { "answer_id": 146783, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 3, "selected": false, "text": "Interfaces\n|--IAnimal\n|--IVegetable\n|--IMineral\nMineralImplementor\nOrganisms\n|--AnimalImplementor\n|--VegetableImplementor\n" }, { "answer_id": 146785, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "Animals\n|\n| - IAnimal\n| - Dog\n| - Cat\nPlants\n|\n| - IPlant\n| - Cactus\n" }, { "answer_id": 12240130, "author": "Akli", "author_id": 1445483, "author_profile": "https://Stackoverflow.com/users/1445483", "pm_score": -1, "selected": false, "text": "namespace A;\n\n Interface IMyInterface\n {\n void MyMethod();\n }\n\nnamespace A;\n\n Interface MyDependentClass\n {\n private IMyInterface inject;\n\n public MyDependentClass(IMyInterface inject)\n {\n this.inject = inject;\n }\n\n public void DoJob()\n {\n //Bla bla\n inject.MyMethod();\n }\n }\n namespace B;\n\n Interface MyImplementing : IMyInterface\n {\n public void MyMethod()\n {\n Console.WriteLine(\"hello world\");\n }\n }\n namespace A;\n\n Interface IMyInterface\n {\n void MyMethod();\n }\n\nnamespace A;\n\n Interface MyImplementing : IMyInterface\n {\n public void MyMethod()\n {\n Console.WriteLine(\"hello world\");\n }\n }\n" }, { "answer_id": 72917378, "author": "Erik Philips", "author_id": 209259, "author_profile": "https://Stackoverflow.com/users/209259", "pm_score": 0, "selected": false, "text": "System.Collections.Generic.IEnumerable<T>\n System.Collections.Generic.List<T>\nSystem.Collections.Generic.Queue<T>\nSystem.Collections.Generic.Stack<T>\n// etc\n System.Data.Entity.IDbSet<T>\n System.Data.Entity.DbSet<T>\n Microsoft.Extensions.Logging.ILogger<T>\n- Microsoft.Extensions.Logging.Logger<T>\nMicrosoft.Extensions.Options.IOptions<T>\n- Microsoft.Extensions.Options.OptionsManager<T>\n- Microsoft.Extensions.Options.OptionsWrapper<T>\n- Microsoft.Extensions.Caching.Memory.MemoryCacheOptions\n- Microsoft.Extensions.Caching.SqlServer.SqlServerCacheOptions\n- Microsoft.Extensions.Caching.Redis.RedisCacheOptions\n Caching RedisCacheOptions Memory -> MemoryCacheOptions\nSqlServer -> SqlServerCatchOptions\nRedis -> RedisCacheOptions\n CarDealership.Entities.IPerson\nCarDealership.Entities.IVehicle\nCarDealership.Entities.Person\nCarDealership.Entities.Vehicle\n CarDealership.Entities.EntityFramework.Person\nCarDealership.Entities.EntityFramework.Vehicle\nCarDealership.Entities.EntityFramework.SalesPerson\nCarDealership.Entities.EntityFramework.FinancePerson\nCarDealership.Entities.EntityFramework.LotVehicle\nCarDealership.Entities.EntityFramework.ShuttleVehicle\nCarDealership.Entities.EntityFramework.BorrowVehicle\n CarDealership.Entities.Dapper.Person\nCarDealership.Entities.Dapper.Vehicle\n//etc\n MyNamespace.Interfaces\nMyNamespace.Enums\nMyNameSpace.Classes\nMyNamespace.Structs\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
146,789
<p>This question is related to (but perhaps not quite the same as):</p> <p><a href="https://stackoverflow.com/questions/61451/does-django-have-html-helpers">Does Django have HTML helpers?</a></p> <p>My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:</p> <p>I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective <strong>models.py</strong>)</p> <pre><code>class Person(models.Model): ... class Address(models.Model): contact = models.ForeignKey(Person) </code></pre> <p>Now, whenever I look at a Person, I want to see all their Addresses. So suppose <strong>Persons/views.py</strong> has something likeso:</p> <pre><code>def detail(request, person_id): person = get_object_or_404( Person, pk=person_id ) return render_to_response('persons/details.html', { 'title' : unicode(person), 'addresses': person.address_set.all() } ) </code></pre> <p>And, I have a template, <strong>persons/details.html</strong>, with code, for example, like-so:</p> <pre><code>{% extends "base.html" %} {% for address in addresses %} &lt;b&gt;{{ address.name }}&lt;/b&gt; {{ address.type }} &lt;br&gt; {{ address.street_1 }}&lt;br&gt; {{ address.street_2 }}&lt;br&gt; {{ address.city }} {{ address.stateprov }} {{ address.postalcode }}&lt;br&gt; {{ address.country }} &lt;hr&gt; {{ endfor }} </code></pre> <p>I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then &lt; br > must be substituted by &lt; /td >&lt; td >. Other times, I don't want a street_2 to display (or the &lt; br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!</p> <p>What I want is a <strong>persons/details.html</strong> with, for example, the following: </p> <pre><code>{% extends "base.html" %} {% for address in addresses %} {% address.as_html4 %} {% endfor %} </code></pre> <p>And if I want inline table, something likeso (I guess!):</p> <pre><code>{% extends "base.html" %} &lt;table&gt;&lt;tr&gt; {% for address in addresses %} &lt;tr&gt;&lt;td&gt; {% address.as_html4 &lt;/td&gt;&lt;td&gt; %} &lt;/td&gt;&lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>The question is, then: Where is the best place to put the formatting? The logic?</p> <p>Django seem to have the following (plausible) options:</p> <ol> <li><p>Put the formatting in models.py</p></li> <li><p>Put the logic/formatting in views.py</p></li> <li><p>Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)</p></li> <li><p>Create custom tags</p></li> </ol> <p>Help / insight much appreciated!</p>
[ { "answer_id": 146833, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": true, "text": "@register.inclusion_tag('person/address.html')\ndef display_address(address):\n return {'address': address}\n {% load %} {% display_address address %}\n" }, { "answer_id": 153012, "author": "carefulweb", "author_id": 12683, "author_profile": "https://Stackoverflow.com/users/12683", "pm_score": 1, "selected": false, "text": "{{ value|linebreaks }} # standard django filter\n If value is Joel\\nis a slug, the output will be <p>Joel<br>is a slug</p>.\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
146,794
<p>I'm running into an unusual problem in my unit tests. The class I'm testing creates a dependency property dynamically at runtime and the type of that dependency property can vary depending on the circumstances. While writing my unit tests, I need to create the dependency property with different types and that leads to errors because you can't redefine an existing dependency property.</p> <p>So is there any way to either un-register a dependency property or to change the type of an existing dependency property?</p> <p>Thanks!</p> <hr> <p>OverrideMetadata() only lets you change a very few things like default value so it isn't helpful. The AppDomain approach is a good idea and might work but seems more complicated than I really wanted to delve into for the sake of unit testing.</p> <p>I never did find a way to unregister a dependency property so I punted and carefully reorganized my unit tests to avoid the issue. I'm getting a bit less test coverage, but since this problem would never occur in a real application and only during unit testing I can live with it.</p> <p>Thanks for the help!</p>
[ { "answer_id": 146830, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 1, "selected": false, "text": "MyDependencyProperty.OverrideMetadata(typeof(MyNewType), \n new PropertyMetadata());\n" }, { "answer_id": 993561, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Label myLabel = new Label();\nthis.RegisterName(myLabel.Name, myLabel);\n this.UnregisterName(myLabel.Name);\n" }, { "answer_id": 1412194, "author": "statenjason", "author_id": 88340, "author_profile": "https://Stackoverflow.com/users/88340", "pm_score": 4, "selected": true, "text": "DependencyProperty.Register DependencyProperty.RegisterCommon FromNameKey key = new FromNameKey(name, ownerType);\nlock (Synchronized)\n{\n if (PropertyFromName.Contains(key))\n {\n throw new ArgumentException(SR.Get(\"PropertyAlreadyRegistered\", \n new object[] { name, ownerType.Name }));\n }\n}\n DependencyProperty dp = \n new DependencyProperty(name, propertyType, ownerType, \n defaultMetadata, validateValueCallback);\n\ndefaultMetadata.Seal(dp, null);\n//...Yada yada...\nlock (Synchronized)\n{\n PropertyFromName[key] = dp;\n}\n DependencyProperty.PropertyFromName DependencyProperty.RegisteredPropertyList ItemStructList<DependencyProperty> private void RemoveDependency(DependencyProperty prop)\n{\n var registeredPropertyField = typeof(DependencyProperty).\n GetField(\"RegisteredPropertyList\", BindingFlags.NonPublic | BindingFlags.Static);\n object list = registeredPropertyField.GetValue(null);\n var genericMeth = list.GetType().GetMethod(\"Remove\");\n try\n {\n genericMeth.Invoke(list, new[] { prop });\n }\n catch (TargetInvocationException)\n {\n Console.WriteLine(\"Does not exist in list\");\n }\n\n var propertyFromNameField = typeof(DependencyProperty).\n GetField(\"PropertyFromName\", BindingFlags.NonPublic | BindingFlags.Static);\n var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);\n\n object keyToRemove = null;\n foreach (DictionaryEntry item in propertyFromName)\n {\n if (item.Value == prop)\n keyToRemove = item.Key;\n }\n if (keyToRemove != null)\n propertyFromName.Remove(keyToRemove);\n}\n" }, { "answer_id": 4262967, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 0, "selected": false, "text": "Selector HorizontalItemsSource VerticalItemsSource ItemsSourceProperty ItemsSource Private Shadows private new MyControlType.ItemsSourceProperty foreach DictionaryEntry Dim dpType = GetType(DependencyProperty)\nDim bFlags = BindingFlags.NonPublic Or BindingFlags.Static\n\nDim FromName = \n Function(name As String, ownerType As Type) DirectCast(dpType.GetMethod(\"FromName\",\n bFlags).Invoke(Nothing, {name, ownerType}), DependencyProperty)\n\nDim PropertyFromName = DirectCast(dpType.GetField(\"PropertyFromName\", bFlags).\n GetValue(Nothing), Hashtable)\n\nDim dp = FromName.Invoke(\"ItemsSource\", GetType(DimensionalGrid))\nDim entries(PropertyFromName.Count - 1) As DictionaryEntry\nPropertyFromName.CopyTo(entries, 0)\nDim entry = entries.Single(Function(e) e.Value Is dp)\nPropertyFromName.Remove(entry.Key)\n ItemsSource" }, { "answer_id": 48708748, "author": "Davy", "author_id": 1790588, "author_profile": "https://Stackoverflow.com/users/1790588", "pm_score": 0, "selected": false, "text": "BindingOperations.ClearAllBindings(this);\nDispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new DispatcherOperationCallback(delegate { return null; }), null);\n" } ]
2008/09/28
[ "https://Stackoverflow.com/questions/146794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9045/" ]