qid
int64
4
22.2M
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" }, { "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" } ]
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" }, { "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" }, { "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" }, { "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" }, { "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\");" }, { "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" }, { "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" }, { "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" }, { "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_*" }, { "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" } ]
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" }, { "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" }, { "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++;" }, { "answer_id": 598946, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 1, "selected": false, "text": "short" } ]
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" }, { "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" }, { "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" } ]
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" }, { "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" } ]
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" }, { "answer_id": 208910, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 4, "selected": false, "text": "\"abcd\".StartsWith(\"\")" }, { "answer_id": 390801, "author": "jason", "author_id": 45914, "author_profile": "https://Stackoverflow.com/users/45914", "pm_score": 4, "selected": false, "text": "A" }, { "answer_id": 484398, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 2, "selected": false, "text": "String.StartsWith()" }, { "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" }, { "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" } ]
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" }, { "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" } ]
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" } ]
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" } ]
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)" } ]
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" } ]
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" } ]
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" }, { "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" } ]
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" }, { "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" } ]
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" } ]
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" }, { "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(...)" } ]
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" } ]
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" }, { "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" }, { "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" } ]
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" }, { "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" }, { "answer_id": 146074, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "if" } ]
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" } ]
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" }, { "answer_id": 7414495, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "inline" }, { "answer_id": 7418299, "author": "Emilio Garavaglia", "author_id": 924727, "author_profile": "https://Stackoverflow.com/users/924727", "pm_score": 6, "selected": false, "text": "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" }, { "answer_id": 145881, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "file_get_contents" } ]
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" }, { "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" }, { "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" }, { "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[]" }, { "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" }, { "answer_id": 68885656, "author": "Jay Lieske", "author_id": 656176, "author_profile": "https://Stackoverflow.com/users/656176", "pm_score": 0, "selected": false, "text": "OCAMLRUNPARAM=b" } ]
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" }, { "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" }, { "answer_id": 25845284, "author": "GP89", "author_id": 659346, "author_profile": "https://Stackoverflow.com/users/659346", "pm_score": 1, "selected": false, "text": "wx.TaskBarIcon" } ]
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" } ]
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" } ]
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" }, { "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" }, { "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" }, { "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" } ]
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" } ]
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" } ]
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" }, { "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" } ]
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" } ]
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" } ]
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" }, { "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" }, { "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" }, { "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" }, { "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\">" } ]
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" }, { "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" }, { "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" }, { "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" }, { "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" }, { "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" }, { "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" }, { "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()" }, { "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" }, { "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" }, { "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" }, { "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" } ]
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" } ]
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" }, { "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" } ]
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" }, { "answer_id": 146651, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 4, "selected": false, "text": "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>>" }, { "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>>" }, { "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>>" }, { "answer_id": 12000452, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "Tuple" }, { "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" }, { "answer_id": 36466344, "author": "ChristopheD", "author_id": 81179, "author_profile": "https://Stackoverflow.com/users/81179", "pm_score": 3, "selected": false, "text": "IDictionary<T>" }, { "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" }, { "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" }, { "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" }, { "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" } ]
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" }, { "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" } ]
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)" }, { "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" } ]
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" }, { "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" }, { "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" } ]
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" }, { "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" }, { "answer_id": 146760, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 8, "selected": false, "text": ".m" }, { "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" }, { "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" }, { "answer_id": 359068, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": false, "text": "#pragma mark" }, { "answer_id": 489639, "author": "Dan", "author_id": 49663, "author_profile": "https://Stackoverflow.com/users/49663", "pm_score": 3, "selected": false, "text": "#pragma 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" }, { "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" }, { "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" }, { "answer_id": 1250637, "author": "Johan Kool", "author_id": 60488, "author_profile": "https://Stackoverflow.com/users/60488", "pm_score": 3, "selected": false, "text": "fi" }, { "answer_id": 1377441, "author": "fbrereto", "author_id": 153535, "author_profile": "https://Stackoverflow.com/users/153535", "pm_score": 3, "selected": false, "text": "TODO:" }, { "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": "[" }, { "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" }, { "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" }, { "answer_id": 4145853, "author": "Juan Arzola", "author_id": 405267, "author_profile": "https://Stackoverflow.com/users/405267", "pm_score": 2, "selected": false, "text": "<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" } ]
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" } ]
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" }, { "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" } ]
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" }, { "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" }, { "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" }, { "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" } ]
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" }, { "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" }, { "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" }, { "answer_id": 146546, "author": "ironfroggy", "author_id": 19687, "author_profile": "https://Stackoverflow.com/users/19687", "pm_score": 4, "selected": false, "text": "g()" }, { "answer_id": 150546, "author": "Krzysiek Goj", "author_id": 23018, "author_profile": "https://Stackoverflow.com/users/23018", "pm_score": 3, "selected": false, "text": "" } ]
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" } ]
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" } ]
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" }, { "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": "" } ]
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" } ]
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=" }, { "answer_id": 146482, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "sort" }, { "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" }, { "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" }, { "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" }, { "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" }, { "answer_id": 28001423, "author": "whoan", "author_id": 4095830, "author_profile": "https://Stackoverflow.com/users/4095830", "pm_score": 2, "selected": false, "text": "sponge" }, { "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" }, { "answer_id": 146464, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 5, "selected": false, "text": "int" }, { "answer_id": 146589, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 9, "selected": false, "text": "int" }, { "answer_id": 20447009, "author": "набиячлэвэли", "author_id": 2851815, "author_profile": "https://Stackoverflow.com/users/2851815", "pm_score": 4, "selected": false, "text": "std::is_pod" }, { "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" } ]
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" } ]
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" } ]
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" }, { "answer_id": 146601, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": true, "text": "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" } ]
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" }, { "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" }, { "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);" } ]
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" }, { "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" }, { "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" } ]
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" }, { "answer_id": 146633, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 3, "selected": false, "text": ".webloc" }, { "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" }, { "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" }, { "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" }, { "answer_id": 5841473, "author": "Abhishek", "author_id": 732351, "author_profile": "https://Stackoverflow.com/users/732351", "pm_score": 2, "selected": false, "text": "public" }, { "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()" }, { "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" }, { "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[])" }, { "answer_id": 11491829, "author": "A.H.", "author_id": 947357, "author_profile": "https://Stackoverflow.com/users/947357", "pm_score": 5, "selected": false, "text": "static" }, { "answer_id": 11643561, "author": "gnat", "author_id": 839601, "author_profile": "https://Stackoverflow.com/users/839601", "pm_score": 2, "selected": false, "text": "Application" }, { "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[])" }, { "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();" }, { "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" }, { "answer_id": 42364080, "author": "Basheer AL-MOMANI", "author_id": 4251431, "author_profile": "https://Stackoverflow.com/users/4251431", "pm_score": 3, "selected": false, "text": "java" } ]
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" } ]
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\"" }, { "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" }, { "answer_id": 146683, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "sub" } ]
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" }, { "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" }, { "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": "" }, { "answer_id": 64030820, "author": "oakaigh", "author_id": 11934495, "author_profile": "https://Stackoverflow.com/users/11934495", "pm_score": 0, "selected": false, "text": "#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" }, { "answer_id": 904738, "author": "Keith Bentrup", "author_id": 109826, "author_profile": "https://Stackoverflow.com/users/109826", "pm_score": 2, "selected": false, "text": "!important" }, { "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" }, { "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]))" }, { "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" }, { "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\"" } ]
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" }, { "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]))" }, { "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" }, { "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\"" } ]
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\")" }, { "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\")" }, { "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" }, { "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" }, { "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" }, { "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" }, { "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" } ]
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" } ]
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" }, { "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" } ]
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" }, { "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" } ]
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" }, { "answer_id": 1412194, "author": "statenjason", "author_id": 88340, "author_profile": "https://Stackoverflow.com/users/88340", "pm_score": 4, "selected": true, "text": "DependencyProperty.Register" }, { "answer_id": 4262967, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 0, "selected": false, "text": "Selector" }, { "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/" ]