qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
6,110
<p>I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations.</p> <p>For example, here are some records that describe the same customer:</p> <p><strong>Location Table</strong></p> <pre><code> ID Location_Name 1 TownShop#1 2 Town Shop - Loc 2 3 The Town Shop 4 TTS - Someplace 5 Town Shop,the 3 6 Toen Shop4 </code></pre> <p>My goal is to make it look like:</p> <p><strong>Location Table</strong></p> <pre><code> ID Company_ID Location_Name 1 1 Town Shop#1 2 1 Town Shop - Loc 2 3 1 The Town Shop 4 1 TTS - Someplace 5 1 Town Shop,the 3 6 1 Toen Shop4 </code></pre> <p><strong>Company Table</strong></p> <pre><code> Company_ID Company_Name 1 The Town Shop </code></pre> <p>There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations.</p> <p>Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand.</p> <p>Any suggestions on how I can approach this is appreciated.</p> <p><strong>@Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row.</strong></p> <p><strong>@yukondude, Your step 4 is the heart of my question.</strong></p>
[ { "answer_id": 6119, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "SELECT count(*) AS repcount, \"Location Name\" FROM mytable\n WHERE \"Company Name\" IS NULL\n GROUP BY \"Location Name\"\n ORDER BY repcount DESC\n LIMIT 5;\n" }, { "answer_id": 6428, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 0, "selected": false, "text": "UPDATE Location\nSET Company_ID = 1\nWHERE (LOWER(Location_Name) LIKE '%to_n shop%'\nOR LOWER(Location_Name) LIKE '%tts%')\nAND Company_ID IS NULL;\n IS NULL SELECT CONCAT('UPDATE Location SET Company_ID = ',\n Company_ID, ' WHERE LOWER(Location_Name) LIKE ',\n LOWER(REPLACE(Company_Name), ' ', '%'), ' AND Company_ID IS NULL;')\nFROM Company;\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754/" ]
6,113
<p>The application my team is currently developing has a DLL that is used to perform all database access. The application can not use a trusted connection because the database is behind a firewall and the domain server is not. So it appears that the connection string needs to have a DB username and password. The DLL currently has the database connection string hard coded, but I don't want to do this when we launch as the assembly can be disassembled and the username and password would be right there in the open.</p> <p>One of the requirements is that the password needs to be changed once every few months, so we would need to roll that out to our internal user base.</p> <p>Is there a way to store the password encrypted in such a way we can easily distribute to the entire user base without storing it in the assembly?</p> <p>UPDATE: Thanks to everyone who's answered. I'll try to answer some of the questions back to me... The data DLL is used by both ASP.NET WebForms and VB.NET WinForms. I understand that Applications can have their own config files, but I haven't seen anything on config files for DLLs. Unfortunately, I can't get to the Jon Galloway post at work so I can't judge if that will work. From a development standpoint, we don't want to use web services inhouse, but may be providing them to third parties sometime next year. I don't think impersonation will work because we can't authenticate the user through the firewall. As a user (or former user) can be an attacker, we're keeping it from everyone!</p>
[ { "answer_id": 6123, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "web.config" }, { "answer_id": 6176, "author": "Brian Childress", "author_id": 721, "author_profile": "https://Stackoverflow.com/users/721", "pm_score": 0, "selected": false, "text": "<section name=\"enterpriseLibrary.ConfigurationSource\" type=\"Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n<enterpriseLibrary.ConfigurationSource selectedSource=\"Common\">\n<sources>\n <add name=\"Common\" type=\"Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n filePath=\"Config\\Exception.config\" />\n</sources>\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/702/" ]
6,126
<p>It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life.</p> <p>Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem?</p> <p>Example, all on one line:</p> <pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true &amp;&amp; var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true) { </code></pre> <p>Example, multi-line:</p> <pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true &amp;&amp; var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true) { </code></pre> <p>Example-nested:</p> <pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true) { if (var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true) { </code></pre>
[ { "answer_id": 6131, "author": "abyx", "author_id": 573, "author_profile": "https://Stackoverflow.com/users/573", "pm_score": 3, "selected": false, "text": "== true" }, { "answer_id": 6132, "author": "TimM", "author_id": 32, "author_profile": "https://Stackoverflow.com/users/32", "pm_score": 1, "selected": false, "text": "Bool cond1 == (var1 && var2);\nBool cond2 == (var3 && var4);\n\nif ( cond1 && cond2 ) {}\n" }, { "answer_id": 6133, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 2, "selected": false, "text": "if (var1 == true\n && var2 == true\n && var3 == true\n ) {\n /* do something.. */\n}\n if (var1 == true\n && var2 == true\n && var3 == true) {\n /* do something.. */\n}\n" }, { "answer_id": 6135, "author": "Mike Powell", "author_id": 205, "author_profile": "https://Stackoverflow.com/users/205", "pm_score": 3, "selected": false, "text": "bool orderValid = orderDate < DateTime.Now && orderStatus != Status.Canceled;\nbool custValid = customerBalance == 0 && customerName != \"Mike\";\nif (orderValid && custValid)\n{\n...\n" }, { "answer_id": 6140, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 7, "selected": true, "text": "bool isOpaque = object.Alpha == 1.0f;\nbool isDrawable = object.CanDraw && object.Layer == currentLayer;\nbool isHidden = hideList.Find(object);\n\nbool isVisible = isOpaque && isDrawable && ! isHidden;\n\nif(isVisible)\n{\n // ...\n}\n public bool IsVisible {\n get\n {\n bool isOpaque = object.Alpha == 1.0f;\n bool isDrawable = object.CanDraw && object.Layer == currentLayer;\n bool isHidden = hideList.Find(object);\n\n return isOpaque && isDrawable && ! isHidden;\n }\n}\n\nvoid Draw()\n{\n if(IsVisible)\n {\n // ...\n }\n}\n" }, { "answer_id": 6148, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 0, "selected": false, "text": "if (var1 = true\n && var2 = true\n && var2 = true\n && var3 = true\n && var4 = true\n && var5 = true\n && var6 = true){\n if ((var1 = true && var2 = true)\n && ((var2 = true && var3 = true)\n && (var4 = true && var5 = true))\n && (var6 = true)){\n" }, { "answer_id": 6152, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "public void doSomething() {\n if (condition1 && condition2 && condition3 && condition4) {\n // do something\n }\n}\n public void doSomething() {\n if (!condition1) {\n return;\n }\n\n if (!condition2) {\n return;\n }\n\n if (!condition3) {\n return;\n }\n\n if (!condition4) {\n return;\n }\n\n // do something\n}\n" }, { "answer_id": 6158, "author": "Simon Gillbee", "author_id": 756, "author_profile": "https://Stackoverflow.com/users/756", "pm_score": 3, "selected": false, "text": "if (var1 == true && // Explanation of the check\n var2 == true && // Explanation of the check\n var3 == true && // Explanation of the check\n var4 == true && // Explanation of the check\n var5 == true && // Explanation of the check\n var6 == true) // Explanation of the check\n { }\n if (var1 && // Explanation of the check\n var2 && // Explanation of the check\n var3 && // Explanation of the check\n var4 && // Explanation of the check\n var5 && // Explanation of the check\n var6) // Explanation of the check\n { }\n /// <Summary>\n/// Tests whether all the conditions are appropriately met\n/// </Summary>\nprivate bool AreAllConditionsMet (\n bool var1,\n bool var2,\n bool var3,\n bool var4,\n bool var5,\n bool var6)\n{\n return (\n var1 && // Explanation of the check\n var2 && // Explanation of the check\n var3 && // Explanation of the check\n var4 && // Explanation of the check\n var5 && // Explanation of the check\n var6); // Explanation of the check\n}\n\nprivate void SomeMethod()\n{\n // Do some stuff (including declare the required variables)\n if (AreAllConditionsMet (var1, var2, var3, var4, var5, var6))\n {\n // Do something\n }\n}\n" }, { "answer_id": 6159, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 0, "selected": false, "text": "all() >>> L = [True, True, True, False, True]\n>>> all(L) # True, only if all elements of L are True.\nFalse\n>>> any(L) # True, if any elements of L are True.\nTrue\n" }, { "answer_id": 6163, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": -1, "selected": false, "text": "if (var1 == true) {\n if (var2 == true) {\n if (var3 == true) {\n ...\n }\n }\n}\n" }, { "answer_id": 6193, "author": "fastcall", "author_id": 328, "author_profile": "https://Stackoverflow.com/users/328", "pm_score": 0, "selected": false, "text": "do {\n if (!cond1)\n break;\n if (!cond2)\n break;\n if (!cond3)\n break;\n ...\n DoSomething();\n} while (false);\n" }, { "answer_id": 14148, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 2, "selected": false, "text": "import org.apache.commons.collections.ClosureUtils;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.collections.functors.NOPClosure;\n\nMap predicateMap = new HashMap();\n\npredicateMap.put( isHonorRoll, addToHonorRoll );\npredicateMap.put( isProblem, flagForAttention );\npredicateMap.put( null, ClosureUtils.nopClosure() );\n\nClosure processStudents = \n ClosureUtils.switchClosure( predicateMap );\n\nCollectionUtils.forAllDo( allStudents, processStudents );\n import org.apache.commons.collections.Closure;\nimport org.apache.commons.collections.Predicate;\n\n// Anonymous Predicate that decides if a student \n// has made the honor roll.\nPredicate isHonorRoll = new Predicate() {\n public boolean evaluate(Object object) {\n Student s = (Student) object;\n\n return( ( s.getGrade().equals( \"A\" ) ) ||\n ( s.getGrade().equals( \"B\" ) && \n s.getAttendance() == PERFECT ) );\n }\n};\n\n// Anonymous Predicate that decides if a student\n// has a problem.\nPredicate isProblem = new Predicate() {\n public boolean evaluate(Object object) {\n Student s = (Student) object;\n\n return ( ( s.getGrade().equals( \"D\" ) || \n s.getGrade().equals( \"F\" ) ) ||\n s.getStatus() == SUSPENDED );\n }\n};\n\n// Anonymous Closure that adds a student to the \n// honor roll\nClosure addToHonorRoll = new Closure() {\n public void execute(Object object) {\n Student s = (Student) object;\n\n // Add an award to student record\n s.addAward( \"honor roll\", 2005 );\n Database.saveStudent( s );\n }\n};\n\n// Anonymous Closure flags a student for attention\nClosure flagForAttention = new Closure() {\n public void execute(Object object) {\n Student s = (Student) object;\n\n // Flag student for special attention\n s.addNote( \"talk to student\", 2005 );\n s.addNote( \"meeting with parents\", 2005 );\n Database.saveStudent( s );\n }\n};\n" }, { "answer_id": 14167, "author": "wusher", "author_id": 1632, "author_profile": "https://Stackoverflow.com/users/1632", "pm_score": 0, "selected": false, "text": "bool isVar1Valid, isVar2Valid, isVar3Valid, isVar4Valid;\nisVar1Valid = ( var1 == 1 )\nisVar2Valid = ( var2.Count >= 2 )\nisVar3Valid = ( var3 != null )\nisVar4Valid = ( var4 != null && var4.IsEmpty() == false )\nif ( isVar1Valid && isVar2Valid && isVar3Valid && isVar4Valid ) {\n //do code\n}\n" }, { "answer_id": 202845, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "{\n last unless $var1;\n last unless $var2;\n last unless $var3;\n last unless $var4;\n last unless $var5;\n last unless $var6;\n\n ... # Place Code Here\n}\n last return" }, { "answer_id": 2797562, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 1, "selected": false, "text": "$vars = array('var1', 'var2', ... etc.);\nforeach ($vars as $v)\n if ($$v == true) {\n // do something\n break;\n }\n" }, { "answer_id": 43766233, "author": "Sean", "author_id": 7892369, "author_profile": "https://Stackoverflow.com/users/7892369", "pm_score": 0, "selected": false, "text": " if ( (condition_A)\n && (condition_B)\n && (condition_C)\n && (condition_D)\n && (condition_E)\n && (condition_F)\n )\n {\n ...\n }\n if (condition_A) {\n if (condition_B) {\n if (condition_C) {\n if (condition_D) {\n if (condition_E) {\n if (condition_F) {\n ...\n }\n }\n }\n }\n }\n }\n if ( ( (condition_A)\n && (condition_B)\n )\n || ( (condition_C)\n && (condition_D)\n )\n || ( (condition_E)\n && (condition_F)\n )\n )\n {\n do_this_same_thing();\n }\n if (condition_A && condition_B) {\n do_this_same_thing();\n }\n if (condition_C && (condition_D) {\n do_this_same_thing();\n }\n if (condition_E && condition_F) {\n do_this_same_thing();\n }\n if (expr_A & expr_B || expr_C | expr_D & expr_E || expr_E && expr_F & expr_G || expr_H {\n }\n if ( ( (expr_A)\n & (expr_B)\n )\n || ( (expr_C)\n | ( (expr_D)\n & (expr_E)\n )\n )\n || ( (expr_E)\n && ( (expr_F)\n & (expr_G)\n )\n )\n || (expr_H)\n )\n {\n }\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
6,130
<p>I'm using subclipse in Flex Builder 3, and recently received this error when trying to commit:</p> <p><code>svn: Checksum mismatch for '/Users/redacted/Documents/Flex Builder 3/path/to/my/file.mxml'; expected: 'f8cb275de72776657406154dd3c10348', actual: 'null'</code></p> <p>I worked around it by:</p> <ol> <li>Committing all the other changed files, omitting the troublesome one.</li> <li>Copying the contents of the trouble file to a TextMate window</li> <li>Deleting my project in FlexBuilder/Eclipse</li> <li>Checking my project out fresh from SVN</li> <li>Copying the text of the trouble file back in from the TextMate Window</li> <li>Committing the changes.</li> </ol> <p>It worked, but I can't help but think there's a better way. What's actaully happening to cause the svn:checksum error, and what's the best fix.</p> <p>Maybe more important -- is this a symptom of a greater problem?</p>
[ { "answer_id": 6509, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 3, "selected": false, "text": "svn update\n" }, { "answer_id": 1771570, "author": "jsh", "author_id": 132408, "author_profile": "https://Stackoverflow.com/users/132408", "pm_score": 2, "selected": false, "text": "svn delete -m \"deleting corrupted file XXXX\" \nsvn+ssh://username@svnserver/path/to/XXXX\n" }, { "answer_id": 5912499, "author": "Denis Barmenkov", "author_id": 116373, "author_profile": "https://Stackoverflow.com/users/116373", "pm_score": 2, "selected": false, "text": "- go to work directory where recorder/expected checksum issue occured\n- call \"svn diff\" and make sure that there isnt any local modifications\n- cd ..\n- remove trouble file's directory with \"rm -rf\"\n- issue \"svn up\" command, svn client will restore new fresh files copies\n" }, { "answer_id": 10291990, "author": "Mike", "author_id": 448078, "author_profile": "https://Stackoverflow.com/users/448078", "pm_score": 0, "selected": false, "text": ".svn\\text-base\\<problematic file>.svn-base .svn\\entries" }, { "answer_id": 14261173, "author": "Jeroen", "author_id": 271204, "author_profile": "https://Stackoverflow.com/users/271204", "pm_score": 0, "selected": false, "text": "<scm>...</scm>" }, { "answer_id": 16141964, "author": "harsh", "author_id": 878732, "author_profile": "https://Stackoverflow.com/users/878732", "pm_score": 0, "selected": false, "text": " svn: Checksum mismatch for 'path-to-folder\\WEB-INF\\web.xml':\n expected: d60cb051162e4a6790a3ea0c9ddfb434\n actual: 16885ded2cbc1adc250e4cbbc1427546\n" }, { "answer_id": 17944947, "author": "Dolen Oinam", "author_id": 2633734, "author_profile": "https://Stackoverflow.com/users/2633734", "pm_score": 0, "selected": false, "text": "svn update --set-depth empty" }, { "answer_id": 24737533, "author": "Torben Lajer", "author_id": 2550568, "author_profile": "https://Stackoverflow.com/users/2550568", "pm_score": 0, "selected": false, "text": "find . -name .svn -exec rm -rf {} \\;" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/763/" ]
6,134
<p>I have a problem with some zombie-like processes on a certain server that need to be killed every now and then. How can I best identify the ones that have run for longer than an hour or so?</p>
[ { "answer_id": 6145, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": false, "text": "ps aux\n USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND\nroot 1 0.0 0.0 7200 308 ? Ss Jun22 0:02 init [5]\nroot 2 0.0 0.0 0 0 ? S Jun22 0:02 [migration/0]\nroot 3 0.0 0.0 0 0 ? SN Jun22 0:18 [ksoftirqd/0]\nroot 4 0.0 0.0 0 0 ? S Jun22 0:00 [watchdog/0]\n stat /proc/<pid>\n ohm ~$ stat /proc/1\n File: `/proc/1'\n Size: 0 Blocks: 0 IO Block: 4096 directory\nDevice: 3h/3d Inode: 65538 Links: 5\nAccess: (0555/dr-xr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root)\nAccess: 2008-06-22 15:37:44.347627750 -0700\nModify: 2008-06-22 15:37:44.347627750 -0700\nChange: 2008-06-22 15:37:44.347627750 -0700\n" }, { "answer_id": 6150, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 5, "selected": false, "text": "ps -eo uid,pid,etime | egrep '^ *user-id' | egrep ' ([0-9]+-)?([0-9]{2}:?){3}' | awk '{print $2}' | xargs -I{} kill {}\n" }, { "answer_id": 1616779, "author": "Maniraj Patri", "author_id": 195723, "author_profile": "https://Stackoverflow.com/users/195723", "pm_score": 2, "selected": false, "text": "ps -aef date" }, { "answer_id": 3474710, "author": "Peter V. Mørch", "author_id": 345716, "author_profile": "https://Stackoverflow.com/users/345716", "pm_score": 3, "selected": false, "text": "sudo apt-get install libproc-processtable-perl perl -MProc::ProcessTable -Mstrict -w -e 'my $anHourAgo = time-60*60; my $t = new Proc::ProcessTable;foreach my $p ( @{$t->table} ) { if ($p->start() < $anHourAgo) { print $p->pid, \"\\n\" } }'\n #!/usr/bin/perl -w\nuse strict;\nuse Proc::ProcessTable;\nmy $anHourAgo = time-60*60;\nmy $t = new Proc::ProcessTable;\nforeach my $p ( @{$t->table} ) {\n if ($p->start() < $anHourAgo) {\n print $p->pid, \"\\n\";\n }\n}\n perl process.pl" }, { "answer_id": 7020431, "author": "Rodney Amato", "author_id": 4342, "author_profile": "https://Stackoverflow.com/users/4342", "pm_score": 1, "selected": false, "text": "kill $(ps -o pid,bsdtime -p $(pgrep bad_process) | awk '{ if ($RN > 1 && $2 > 100) { print $1; }}')\n" }, { "answer_id": 9316199, "author": "mob", "author_id": 168657, "author_profile": "https://Stackoverflow.com/users/168657", "pm_score": 1, "selected": false, "text": "stat -t /proc/<pid> | awk '{print $14}' date +%s" }, { "answer_id": 9973593, "author": "David Jeske", "author_id": 519568, "author_profile": "https://Stackoverflow.com/users/519568", "pm_score": 0, "selected": false, "text": "#include <proc/readproc.h>\n#include <proc/sysinfo.h>\n\nfloat\npid_age(pid_t pid)\n{\n proc_t proc_info;\n int seconds_since_boot = uptime(0,0);\n if (!get_proc_stats(pid, &proc_info)) {\n return 0.0;\n }\n\n // readproc.h comment lies about what proc_t.start_time is. It's\n // actually expressed in Hertz ticks since boot\n\n int seconds_since_1970 = time(NULL);\n int time_of_boot = seconds_since_1970 - seconds_since_boot;\n long t = seconds_since_boot - (unsigned long)(proc_info.start_time / Hertz);\n\n int delta = t;\n float days = ((float) delta / (float)(60*60*24));\n return days;\n}\n" }, { "answer_id": 10525736, "author": "Jodie C", "author_id": 812270, "author_profile": "https://Stackoverflow.com/users/812270", "pm_score": 6, "selected": true, "text": "if [[ \"$(uname)\" = \"Linux\" ]];then killall --older-than 1h someprocessname;fi\n if [[ \"$(uname)\" = \"Linux\" ]];then killall -i --older-than 1h someprocessname;fi\n -i" }, { "answer_id": 11042931, "author": "Rafael S. Calsaverini", "author_id": 114388, "author_profile": "https://Stackoverflow.com/users/114388", "pm_score": 2, "selected": false, "text": "bc echo `date +%s` - `stat -t /proc/<pid> | awk '{print $14}'` | bc\n #file: sincetime\n#!/bin/bash\ninit=`stat -t /proc/$1 | awk '{print $14}'`\ncurr=`date +%s`\nseconds=`echo $curr - $init| bc`\nname=`cat /proc/$1/cmdline`\necho $name $seconds\n #file: greptime\n#!/bin/bash\npidlist=`ps ax | grep -i -E $1 | grep -v grep | awk '{print $1}' | grep -v PID | xargs echo`\nfor pid in $pidlist; do\n sincetime $pid\ndone\n greptime <pattern>\n" }, { "answer_id": 16547667, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "killall -i pgrep -f /proc #!/bin/sh \n\nmax_age=120 # (seconds) \nnaughty=\"$(pgrep -f offlineimap)\" \nif [[ -n \"$naughty\" ]]; then # naughty is running \n age_in_seconds=$(echo \"$(date +%s) - $(stat -c %X /proc/$naughty)\" | bc) \n if [[ \"$age_in_seconds\" -ge \"$max_age\" ]]; then # naughty is too old! \n kill -s 9 \"$naughty\" \n fi \nfi \n max_age /usr/bin/python2 offlineimap killall" }, { "answer_id": 24594339, "author": "user3743785", "author_id": 3743785, "author_profile": "https://Stackoverflow.com/users/3743785", "pm_score": 0, "selected": false, "text": "* * * * * ps -lf | grep \"user\" | perl -ane '($h,$m,$s) = split /:/,$F\n+[13]; kill 9, $F[3] if ($h > 1);'\n #!/bin/sh\n# longprockill.sh\nps -lf | grep \"user\" | perl -ane '($h,$m,$s) = split /:/,$F[13]; kill\n+ 9, $F[3] if ($h > 1);'\n * * * * * longprockill.sh\n" }, { "answer_id": 52023199, "author": "Phil Hudson", "author_id": 6375702, "author_profile": "https://Stackoverflow.com/users/6375702", "pm_score": 0, "selected": false, "text": "sincetime #!/bin/bash\nps --no-headers -o etimes,args \"$1\"\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ]
6,155
<p>What kinds of hook scripts are people using for Subversion? Just general ideas but code would be great too!</p>
[ { "answer_id": 68850, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 6, "selected": false, "text": "pre-revprop-change pre-revprop-change.bat post-revprop-change.cmd snv:log FIND.EXE /b exit /b @ECHO OFF\n\nset repos=%1\nset rev=%2\nset user=%3\nset propname=%4\nset action=%5\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow changes to svn:log. The author, date and other revision\n:: properties cannot be changed\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%propname%'=='svn:log' goto ERROR_PROPNAME\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow modifications to svn:log (no addition/overwrite or deletion)\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%action%'=='M' goto ERROR_ACTION\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Make sure that the new svn:log message contains some text.\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset bIsEmpty=true\nfor /f \"tokens=*\" %%g in ('find /V \"\"') do (\n set bIsEmpty=false\n)\nif '%bIsEmpty%'=='true' goto ERROR_EMPTY\n\ngoto :eof\n\n\n\n:ERROR_EMPTY\necho Empty svn:log properties are not allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_PROPNAME\necho Only changes to svn:log revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_ACTION\necho Only modifications to svn:log revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\nexit /b 1 \n" }, { "answer_id": 3630318, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 0, "selected": false, "text": "@ECHO OFF\nsetlocal\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Get subversion arguments\nset repos=%~1\nset txn=%2\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Set some variables\nset svnlookparam=\"%repos%\" -t %txn%\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Make sure that the new svn:log message contains some text.\nset bIsEmpty=true\nfor /f \"tokens=* usebackq\" %%g in (`svnlook log %svnlookparam%`) do (\n set bIsEmpty=false\n)\nif '%bIsEmpty%'=='true' goto ERROR_EMPTY\n\necho Allowed. >&2\n\ngoto :END\n\n\n:ERROR_EMPTY\necho Empty log messages are not allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\n:: You may require to remove the /b below if your hook is called directly by subversion\nexit /b 1\n\n:END\nendlocal\n" }, { "answer_id": 3630534, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 1, "selected": false, "text": "[email protected],[email protected],[email protected]\n @ECHO OFF\nsetlocal\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Get subversion arguments\nset repos=%~1\nset rev=%2\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Set some variables\nset tos=%repos%\\hooks\\%~n0.tos.txt\nset reposname=%~nx1\nset svnlookparam=\"%repos%\" --revision %rev%\n\nif not exist \"%tos%\" goto :END\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Prepare sendmail email file\nset author=\nfor /f \"tokens=* usebackq\" %%g in (`svnlook author %svnlookparam%`) do (\n set author=%%g\n)\n\nfor /f \"tokens=* usebackq delims=\" %%g in (\"%tos%\") do (\n set EmailNotificationTo=%%g\n)\nset SendMailFile=%~n0_%reposname%_%rev%.sm\n\necho To: %EmailNotificationTo% >> \"%SendMailFile%\"\necho From: %reposname%[email protected] >> \"%SendMailFile%\"\necho Subject: [%reposname%] Revision %rev% - Subversion Commit Notification >> \"%SendMailFile%\"\n\necho --- log [%author%] --- >> \"%SendMailFile%\"\nsvnlook log %svnlookparam% >> \"%SendMailFile%\" 2>&1\necho --- changed --- >> \"%SendMailFile%\"\nsvnlook changed %svnlookparam% --copy-info >> \"%SendMailFile%\" 2>&1\n\necho .>> \"%SendMailFile%\"\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Send email\ntype \"%SendMailFile%\" | \"%~dp0sendmail.exe\" -t\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Clean-up\nif exist \"%SendMailFile%\" del \"%SendMailFile%\"\n\n\n:END\nendlocal\n" }, { "answer_id": 7303568, "author": "JohnUlmer", "author_id": 928175, "author_profile": "https://Stackoverflow.com/users/928175", "pm_score": 0, "selected": false, "text": "svnadmin setlog <filesystem path to my repository> --bypass-hooks -r 117 junk svn setlog help" }, { "answer_id": 9010360, "author": "nicobo", "author_id": 579827, "author_profile": "https://Stackoverflow.com/users/579827", "pm_score": 2, "selected": false, "text": "@ECHO OFF\n\nset user=%3\n\nif /I '%user%'=='syncuser' goto ERROR_REV\n\nexit 0\n\n:ERROR_REV echo \"Only the syncuser user may change revision properties\" >&2\nexit 1\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ]
6,173
<p>I'm looking for a .NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link. </p> <p>And a side question:</p> <p>Is there <strong>one regex to rule them all</strong>? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability)</p>
[ { "answer_id": 6179, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 0, "selected": false, "text": "%href=\"(.[\"]*)\"%" }, { "answer_id": 6181, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "<a[^>]+href=\"([^\"]+)\"[^>]*>\n" }, { "answer_id": 6182, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 1, "selected": false, "text": "(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\0\n....*SNIP*....\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)\n" }, { "answer_id": 6183, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 5, "selected": true, "text": "((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)\n" }, { "answer_id": 6202, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 2, "selected": false, "text": "([\"'])(mailto:|http:).*?\\1\n #Matches things in single or double quotes, but not the quotes themselves\n(?<=([\"']))((?<=href=['\"])|(?<=src=['\"])).*?(?=\\1)\n\n#Maches thing in either double or single quotes, including the quotes.\n([\"'])((?<=href=\")|(?<=src=\")).*?\\1\n" }, { "answer_id": 13446, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 2, "selected": false, "text": "HtmlDocument doc = new HtmlDocument();\ndoc.Load(\"file.htm\");\nforeach(HtmlNode link in doc.DocumentElement.SelectNodes(\"//a@href\")\n{\nResponse.Write(link[\"href\"].Value);\n}\ndoc.Save(\"file.htm\");\n" }, { "answer_id": 13488, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 3, "selected": false, "text": "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]" }, { "answer_id": 12285635, "author": "dvcama", "author_id": 1649650, "author_profile": "https://Stackoverflow.com/users/1649650", "pm_score": 0, "selected": false, "text": "(http\\\\://[:/?#\\\\[\\\\]@!%$&'()*+,;=a-zA-Z0-9._\\\\-~]+)\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322/" ]
6,184
<p>When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread.</p> <p>The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.</p>
[ { "answer_id": 6189, "author": "Simon Gillbee", "author_id": 756, "author_profile": "https://Stackoverflow.com/users/756", "pm_score": 4, "selected": false, "text": "private delegate void EventArgsDelegate(object sender, EventArgs ea);\n\nvoid SomethingHappened(object sender, EventArgs ea)\n{\n //\n // Make sure this callback is on the correct thread\n //\n if (this.InvokeRequired)\n {\n this.Invoke(new EventArgsDelegate(SomethingHappened), new object[] { sender, ea });\n return;\n }\n\n //\n // Do something with the event such as update a control\n //\n textBox1.Text = \"Something happened\";\n}\n" }, { "answer_id": 6211, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": 6, "selected": true, "text": "void SomethingHappened(object sender, EventArgs ea)\n{\n if (InvokeRequired)\n {\n Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea);\n return;\n }\n\n textBox1.Text = \"Something happened\";\n}\n" }, { "answer_id": 37136, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 3, "selected": false, "text": "void SomethingHappened(object sender, EventArgs ea)\n{\n MethodInvoker del = delegate{ textBox1.Text = \"Something happened\"; }; \n InvokeRequired ? Invoke( del ) : del(); \n}\n" }, { "answer_id": 341879, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "using System;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public class MainForm : Form\n {\n private TypeWithAsync _type;\n\n [STAThread()]\n public static void Main()\n {\n Application.EnableVisualStyles();\n Application.Run(new MainForm());\n }\n\n public MainForm()\n {\n _type = new TypeWithAsync();\n _type.DoSomethingCompleted += DoSomethingCompleted;\n\n var panel = new FlowLayoutPanel() { Dock = DockStyle.Fill };\n\n var btn = new Button() { Text = \"Synchronous\" };\n btn.Click += SyncClick;\n panel.Controls.Add(btn);\n\n btn = new Button { Text = \"Asynchronous\" };\n btn.Click += AsyncClick;\n panel.Controls.Add(btn);\n\n Controls.Add(panel);\n }\n\n private void SyncClick(object sender, EventArgs e)\n {\n int value = _type.DoSomething();\n MessageBox.Show(string.Format(\"DoSomething() returned {0}.\", value));\n }\n\n private void AsyncClick(object sender, EventArgs e)\n {\n _type.DoSomethingAsync();\n }\n\n private void DoSomethingCompleted(object sender, DoSomethingCompletedEventArgs e)\n {\n MessageBox.Show(string.Format(\"DoSomethingAsync() returned {0}.\", e.Value));\n }\n }\n\n class TypeWithAsync\n {\n private AsyncOperation _operation;\n\n // synchronous version of method\n public int DoSomething()\n {\n Thread.Sleep(5000);\n return 27;\n }\n\n // async version of method\n public void DoSomethingAsync()\n {\n if (_operation != null)\n {\n throw new InvalidOperationException(\"An async operation is already running.\");\n }\n\n _operation = AsyncOperationManager.CreateOperation(null);\n ThreadPool.QueueUserWorkItem(DoSomethingAsyncCore);\n }\n\n // wrapper used by async method to call sync version of method, matches WaitCallback so it\n // can be queued by the thread pool\n private void DoSomethingAsyncCore(object state)\n {\n int returnValue = DoSomething();\n var e = new DoSomethingCompletedEventArgs(returnValue);\n _operation.PostOperationCompleted(RaiseDoSomethingCompleted, e);\n }\n\n // wrapper used so async method can raise the event; matches SendOrPostCallback\n private void RaiseDoSomethingCompleted(object args)\n {\n OnDoSomethingCompleted((DoSomethingCompletedEventArgs)args);\n }\n\n private void OnDoSomethingCompleted(DoSomethingCompletedEventArgs e)\n {\n var handler = DoSomethingCompleted;\n\n if (handler != null) { handler(this, e); }\n }\n\n public EventHandler<DoSomethingCompletedEventArgs> DoSomethingCompleted;\n }\n\n public class DoSomethingCompletedEventArgs : EventArgs\n {\n private int _value;\n\n public DoSomethingCompletedEventArgs(int value)\n : base()\n {\n _value = value;\n }\n\n public int Value\n {\n get { return _value; }\n }\n }\n}\n" }, { "answer_id": 10824842, "author": "Chase", "author_id": 1234970, "author_profile": "https://Stackoverflow.com/users/1234970", "pm_score": 2, "selected": false, "text": "lazy programmer private void DoInvoke(MethodInvoker del) {\n if (InvokeRequired) {\n Invoke(del);\n } else {\n del();\n }\n}\n//example of how to call it\nprivate void tUpdateLabel(ToolStripStatusLabel lbl, String val) {\n DoInvoke(delegate { lbl.Text = val; });\n}\n private void directPass() {\n DoInvoke(this.directInvoke);\n}\nprivate void directInvoke() {\n textLabel.Text = \"Directly passed.\";\n}\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/756/" ]
6,209
<p>Given a string like this:</p> <blockquote> <p>a,"string, with",various,"values, and some",quoted</p> </blockquote> <p>What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections?</p> <p>The output should be an array:</p> <blockquote> <p>[ "a", "string, with", "various", "values, and some", "quoted" ]</p> </blockquote>
[ { "answer_id": 6215, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "Loop on the string letter by letter.\n If current_letter == quote : \n toggle inside_quote variable.\n Else if (current_letter ==comma and not inside_quote) : \n push current_word into array and clear current_word.\n Else \n append the current_letter to current_word\nWhen the loop is done push the current_word into array \n" }, { "answer_id": 6237, "author": "mauriciopastrana", "author_id": 547, "author_profile": "https://Stackoverflow.com/users/547", "pm_score": 0, "selected": false, "text": "function getstringbetween($string, $start, $end){\n $string = \" \".$string;\n $ini = strpos($string,$start);\n if ($ini == 0) return \"\";\n $ini += strlen($start); \n $len = strpos($string,$end,$ini) - $ini;\n return substr($string,$ini,$len);\n}\n\n$fullstring = \"this is my [tag]dog[/tag]\";\n$parsed = getstringbetween($fullstring, \"[tag]\", \"[/tag]\");\n\necho $parsed; // (result = dog) \n" }, { "answer_id": 6243, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 0, "selected": false, "text": "'\"' '\"' #COMMA# '\"' ',' #COMMA# ',' def parse_input(input):\n\n quote_mod = int(not input.startswith('\"'))\n\n input = input.split('\"')\n for item in input:\n if item == '':\n input.remove(item)\n for i in range(len(input)):\n if i % 2 == quoted_mod:\n input[i] = input[i].replace(\",\", \"#COMMA#\")\n\n input = \"\".join(input).split(\",\")\n for item in input:\n if item == '':\n input.remove(item)\n for i in range(len(input)):\n input[i] = input[i].replace(\"#COMMA#\", \",\")\n return input\n\n# parse_input('a,\"string, with\",various,\"values, and some\",quoted')\n# -> ['a,string', ' with,various,values', ' and some,quoted']\n# parse_input('\"a,b\",c,\"d,e,f,h\",\"i,j,k\"')\n# -> ['a,b', 'c', 'd,e,f,h', 'i,j,k']\n" }, { "answer_id": 6278, "author": "Brian Jorgensen", "author_id": 229, "author_profile": "https://Stackoverflow.com/users/229", "pm_score": 0, "selected": false, "text": "def parsecsv(instr):\n i = 0\n j = 0\n\n outstrs = []\n\n # i is fixed until a match occurs, then it advances\n # up to j. j inches forward each time through:\n\n while i < len(instr):\n\n if j < len(instr) and instr[j] == '\"':\n # skip the opening quote...\n j += 1\n # then iterate until we find a closing quote.\n while instr[j] != '\"':\n j += 1\n if j == len(instr):\n raise Exception(\"Unmatched double quote at end of input.\")\n\n if j == len(instr) or instr[j] == ',':\n s = instr[i:j] # get the substring we've found\n s = s.strip() # remove extra whitespace\n\n # remove surrounding quotes if they're there\n if len(s) > 2 and s[0] == '\"' and s[-1] == '\"':\n s = s[1:-1]\n\n # add it to the result\n outstrs.append(s)\n\n # skip over the comma, move i up (to where\n # j will be at the end of the iteration)\n i = j+1\n\n j = j+1\n\n return outstrs\n\ndef testcase(instr, expected):\n outstr = parsecsv(instr)\n print outstr\n assert expected == outstr\n\n# Doesn't handle things like '1, 2, \"a, b, c\" d, 2' or\n# escaped quotes, but those can be added pretty easily.\n\ntestcase('a, b, \"1, 2, 3\", c', ['a', 'b', '1, 2, 3', 'c'])\ntestcase('a,b,\"1, 2, 3\" , c', ['a', 'b', '1, 2, 3', 'c'])\n\n# odd number of quotes gives a \"unmatched quote\" exception\n#testcase('a,b,\"1, 2, 3\" , \"c', ['a', 'b', '1, 2, 3', 'c'])\n" }, { "answer_id": 6322, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 0, "selected": false, "text": "arr = [i.replace(\"|\", \",\") for i in re.sub('\"([^\"]*)\\,([^\"]*)\"',\"\\g<1>|\\g<2>\", str_to_test).split(\",\")]\n" }, { "answer_id": 6386, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 3, "selected": false, "text": "import csv\nreader = csv.reader(open(\"some.csv\"))\nfor row in reader:\n print row\n" }, { "answer_id": 3861098, "author": "Greg Bayer", "author_id": 466482, "author_profile": "https://Stackoverflow.com/users/466482", "pm_score": 1, "selected": false, "text": "def splitIgnoringSingleQuote(string, split_char, remove_quotes=False):\n string_split = []\n current_word = \"\"\n inside_quote = False\n for letter in string:\n if letter == \"'\":\n if not remove_quotes:\n current_word += letter\n if inside_quote:\n inside_quote = False\n else:\n inside_quote = True\n elif letter == split_char and not inside_quote:\n string_split.append(current_word)\n current_word = \"\"\n else:\n current_word += letter\n string_split.append(current_word)\n return string_split\n" }, { "answer_id": 52808987, "author": "Goodword", "author_id": 3999494, "author_profile": "https://Stackoverflow.com/users/3999494", "pm_score": 0, "selected": false, "text": "def find_character_indices(s, ch):\n return [i for i, ltr in enumerate(s) if ltr == ch]\n\n\ndef split_text_preserving_quotes(content, include_quotes=False):\n quote_indices = find_character_indices(content, '\"')\n\n output = content[:quote_indices[0]].split()\n\n for i in range(1, len(quote_indices)):\n if i % 2 == 1: # end of quoted sequence\n start = quote_indices[i - 1]\n end = quote_indices[i] + 1\n output.extend([content[start:end]])\n\n else:\n start = quote_indices[i - 1] + 1\n end = quote_indices[i]\n split_section = content[start:end].split()\n output.extend(split_section)\n\n output += content[quote_indices[-1] + 1:].split() \n\n return output\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
6,301
<p>Why is <code>Array.Length</code> an int, and not a <code>uint</code>. This bothers me (just a bit) because a length value can never be negative. </p> <p>This also forced me to use an int for a length-property on my own class, because when you specify an int-value, this needs to be cast explicitly...</p> <p>So the ultimate question is: is there any use for an unsigned int (<code>uint</code>)? Even Microsoft seems not to use them.</p>
[ { "answer_id": 6320, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 7, "selected": true, "text": "UInt" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
6,326
<p>I have the following html.erb code that I'm looking to move to Haml:</p> <pre><code>&lt;span class="&lt;%= item.dashboardstatus.cssclass %&gt;" &gt;&lt;%= item.dashboardstatus.status %&gt;&lt;/span&gt; </code></pre> <p>What it does is associate the CSS class of the currently assigned status to the span.</p> <p>How is this done in Haml? I'm sure I'm missing something really simple.</p>
[ { "answer_id": 6355, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 5, "selected": true, "text": "%span{:class => item.dashboardstatus.cssclass }= item.dashboardstatus.status\n" }, { "answer_id": 46319782, "author": "joeyk16", "author_id": 4574914, "author_profile": "https://Stackoverflow.com/users/4574914", "pm_score": 0, "selected": false, "text": " %div{\"data-turbolinks\" => \"false\"}\n = link_to 'Send payment', new_payments_manager_path(sender_id: current_user.id, receiver_id: @collaboration.with(current_user).id, collaboration_id: params[:id]), class: 'button'\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722/" ]
6,340
<p>I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly :p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas?</p> <pre><code>CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; </code></pre> <p><em>Edited to remove double primary key definition...</em></p> <hr> <p>Yeah, unfortunately that didn't fix it though. Now I'm getting:</p> <blockquote> <p>Can't create table './<em>REMOVED MY DB NAME</em>/SHIPPING_GRID.frm' (errno: 150)</p> </blockquote> <p>Doing a phpinfo() tells me this for mysql:</p> <blockquote> <p>Client API version 5.0.45</p> </blockquote> <p>Yes, the VENDOR.no is type int(6).</p>
[ { "answer_id": 6349, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 5, "selected": true, "text": "CREATE TABLE SHIPPING_GRID( \n id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', \n shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', \n start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', \n end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', \n shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', \n price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', \n is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', \n INDEX (shipping_vendor_no), \n INDEX (start_vendor_no), \n INDEX (end_vendor_no), \n FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), \n FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), \n FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) \n) TYPE = INNODB;\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
6,369
<p>So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause:</p> <pre><code>CREATE PROCEDURE getSomething @keyList varchar(4096) AS SELECT * FROM mytbl WHERE name IN (@keyList) </code></pre> <p>How do I call my stored proc with more than 1 value in the list? So far I've tried </p> <pre><code>exec getSomething 'John' -- works but only 1 value exec getSomething 'John','Tom' -- doesn't work - expects two variables exec getSomething "'John','Tom'" -- doesn't work - doesn't find anything exec getSomething '"John","Tom"' -- doesn't work - doesn't find anything exec getSomething '\'John\',\'Tom\'' -- doesn't work - syntax error </code></pre> <p><strong>EDIT:</strong> I actually found this <a href="http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm" rel="noreferrer">page</a> that has a great reference of the various ways to pas an array to a sproc</p>
[ { "answer_id": 6377, "author": "Brian Childress", "author_id": 721, "author_profile": "https://Stackoverflow.com/users/721", "pm_score": 0, "selected": false, "text": "DECLARE @idoc int\nDECLARE @doc varchar(1000)\nSET @doc ='\n<ROOT>\n<Customer CustomerID=\"VINET\" ContactName=\"Paul Henriot\">\n <Order CustomerID=\"VINET\" EmployeeID=\"5\" OrderDate=\"1996-07-04T00:00:00\">\n <OrderDetail OrderID=\"10248\" ProductID=\"11\" Quantity=\"12\"/>\n <OrderDetail OrderID=\"10248\" ProductID=\"42\" Quantity=\"10\"/>\n </Order>\n</Customer>\n<Customer CustomerID=\"LILAS\" ContactName=\"Carlos Gonzlez\">\n <Order CustomerID=\"LILAS\" EmployeeID=\"3\" OrderDate=\"1996-08-16T00:00:00\">\n <OrderDetail OrderID=\"10283\" ProductID=\"72\" Quantity=\"3\"/>\n </Order>\n</Customer>\n</ROOT>'\n--Create an internal representation of the XML document.\nEXEC sp_xml_preparedocument @idoc OUTPUT, @doc\n-- Execute a SELECT statement that uses the OPENXML rowset provider.\nSELECT *\nFROM OPENXML (@idoc, '/ROOT/Customer',1)\n WITH (CustomerID varchar(10),\n ContactName varchar(20))\n" }, { "answer_id": 6384, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\nSELECT * FROM mytbl WHERE name IN (fn_GetKeyList(@keyList))\n exec getSomething 'John,Tom,Foo,Bar'\n" }, { "answer_id": 48422, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select * \nfrom mytbl \nwhere \",\" + ltrim(rtrim(@keylist)) + \",\" like \"%,\" + ltrim(rtrim(name)) + \",%\"\n" }, { "answer_id": 123686, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\ndeclare @sql varchar(4096)\nselect @sql = \"SELECT * FROM mytbl WHERE name IN (\" + @keyList +\")\"\nexec(@sql)\n" }, { "answer_id": 251136, "author": "Abel Gaxiola", "author_id": 31191, "author_profile": "https://Stackoverflow.com/users/31191", "pm_score": 0, "selected": false, "text": "GetSomething DECLARE @NameArray XML = NULL\n SELECT * FROM MyTbl WHERE name IN (SELECT ParamValues.ID.value('.','VARCHAR(10)')\nFROM @NameArray.nodes('id') AS ParamValues(ID))\n DECLARE @NameArray XML\n\nSET @NameArray = '<id><</id>id>Name_1<<id>/id></id><id><</id>id>Name_2<<id>/id></id><id><</id>id>Name_3<<id>/id></id><id><</id>id>Name_4<<id>/id></id>'\n EXEC GetSomething @NameArray\n DECLARE @IdArray XML\n\nSET @IdArray = '<id><</id>id>Name_1<<id>/id></id><id><</id>id>Name_2<<id>/id></id><id><</id>id>Name_3<<id>/id></id><id><</id>id>Name_4<<id>/id></id>'\n\nSELECT ParamValues.ID.value('.','VARCHAR(10)')\nFROM @IdArray.nodes('id') AS ParamValues(ID)\n" }, { "answer_id": 7892156, "author": "Ben", "author_id": 982820, "author_profile": "https://Stackoverflow.com/users/982820", "pm_score": 2, "selected": false, "text": "exec getSomething \"\"\"John\"\",\"\"Tom\"\",\"\"Bob\"\",\"\"Harry\"\"\"\n CREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\nSELECT * FROM mytbl WHERE @keyList LIKE '%'+name+'%' \n" }, { "answer_id": 37604460, "author": "DeFlanko", "author_id": 4006015, "author_profile": "https://Stackoverflow.com/users/4006015", "pm_score": 0, "selected": false, "text": "DECLARE @ICD_VALUE_RPT VARCHAR(MAX) SET @ICD_VALUE_RPT = 'Value1, Value2'\nDECLARE @ICD_VALUE_ARRAY XML SET @ICD_VALUE_ARRAY = CONCAT('<id>', REPLACE(REPLACE(@ICD_VALUE_RPT, ',', '</id>,<id>'),' ',''), '</id>')\n WHERE (PATS_WITH_PL_DIAGS.ICD10_CODE IN (SELECT ParamValues.ID.value('.','VARCHAR(MAX)') FROM @ICD_VALUE_ARRAY.nodes('id') AS ParamValues(ID))\nOR PATS_WITH_PL_DIAGS.ICD9_CODE IN (SELECT ParamValues.ID.value('.','VARCHAR(MAX)') FROM @ICD_VALUE_ARRAY.nodes('id') AS ParamValues(ID))\n)\n" }, { "answer_id": 46092262, "author": "user3732708", "author_id": 3732708, "author_profile": "https://Stackoverflow.com/users/3732708", "pm_score": 0, "selected": false, "text": "@itemIds varchar(max)\n\nCREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\nSELECT * FROM mytbl WHERE name IN (SELECT Value FROM [Global_Split] (@itemIds,','))\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779/" ]
6,371
<p>I've had a hard time trying to find good examples of how to manage database schemas and data between development, test, and production servers.</p> <p>Here's our setup. Each developer has a virtual machine running our app and the MySQL database. It is their personal sandbox to do whatever they want. Currently, developers will make a change to the SQL schema and do a dump of the database to a text file that they commit into SVN.</p> <p>We're wanting to deploy a continuous integration development server that will always be running the latest committed code. If we do that now, it will reload the database from SVN for each build.</p> <p>We have a test (virtual) server that runs "release candidates." Deploying to the test server is currently a very manual process, and usually involves me loading the latest SQL from SVN and tweaking it. Also, the data on the test server is inconsistent. You end up with whatever test data the last developer to commit had on his sandbox server.</p> <p>Where everything breaks down is the deployment to production. Since we can't overwrite the live data with test data, this involves manually re-creating all the schema changes. If there were a large number of schema changes or conversion scripts to manipulate the data, this can get really hairy.</p> <p>If the problem was just the schema, It'd be an easier problem, but there is "base" data in the database that is updated during development as well, such as meta-data in security and permissions tables.</p> <p>This is the biggest barrier I see in moving toward continuous integration and one-step-builds. How do <strong><em>you</em></strong> solve it?</p> <hr> <p>A follow-up question: how do you track database versions so you know which scripts to run to upgrade a given database instance? Is a version table like Lance mentions below the standard procedure?</p> <hr> <p>Thanks for the reference to Tarantino. I'm not in a .NET environment, but I found their <a href="http://code.google.com/p/tarantino/wiki/DatabaseChangeManagement" rel="noreferrer">DataBaseChangeMangement wiki page</a> to be very helpful. Especially this <a href="http://tarantino.googlecode.com/svn/docs/Database-Change-Management.ppt" rel="noreferrer">Powerpoint Presentation (.ppt)</a></p> <p>I'm going to write a Python script that checks the names of <code>*.sql</code> scripts in a given directory against a table in the database and runs the ones that aren't there in order based on a integer that forms the first part of the filename. If it is a pretty simple solution, as I suspect it will be, then I'll post it here.</p> <hr> <p>I've got a working script for this. It handles initializing the DB if it doesn't exist and running upgrade scripts as necessary. There are also switches for wiping an existing database and importing test data from a file. It's about 200 lines, so I won't post it (though I might put it on pastebin if there's interest).</p>
[ { "answer_id": 775948, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 3, "selected": false, "text": "dev_<<db>> , tst_<<db>> , stg_<<db>> , prd_<<db>>" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/763/" ]
6,373
<p>There are two popular closure styles in javascript. The first I call <em>anonymous constructor</em>:</p> <pre><code>new function() { var code... } </code></pre> <p>and the <em>inline executed function</em>:</p> <pre><code>(function() { var code... })(); </code></pre> <p>are there differences in behaviour between those two? Is one "better" over the other?</p>
[ { "answer_id": 6387, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 3, "selected": false, "text": "function Blah() {\n alert('blah');\n}\nnew Bla();\n" }, { "answer_id": 6424, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 5, "selected": true, "text": "new expression\n var tempObject = {};\nvar result = expression.call(tempObject);\nif (result is not an object)\n result = tempObject;\n tempObject expression expression.call tempObject.__proto__ = expression.prototype" }, { "answer_id": 6436, "author": "Lance Fisher", "author_id": 571, "author_profile": "https://Stackoverflow.com/users/571", "pm_score": 0, "selected": false, "text": "<html>\n<body>\n<script type=\"text/javascript\">\nvar a = new function() { \n alert(\"method 1\");\n\n return \"test\";\n};\n\nvar b = (function() {\n alert(\"method 2\");\n\n return \"test\";\n})();\n\nalert(a); //a is a function\nalert(b); //b is a string containing \"test\"\n\n</script>\n</body>\n</html>\n" }, { "answer_id": 6489, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": -1, "selected": false, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n\nnew function() { \na = \"Hello\";\nalert(a + \" Inside Function\");\n};\n\nalert(a + \" Outside Function\");\n\n(function() { \nvar b = \"World\";\nalert(b + \" Inside Function\");\n})();\n\nalert(b + \" Outside Function\");\n</script>\n</body>\n</html>\n" }, { "answer_id": 6542, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 2, "selected": false, "text": "(function(){ })();" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
6,392
<p>I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to:</p> <pre><code>sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] </code></pre> <p>Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's <a href="http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getDisplayName()" rel="noreferrer">display name</a>, and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon.</p> <p>Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration.</p> <hr> <p>Ok, here's an update. A coworker suggested I update JAVA_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden).</p> <p>However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround.</p> <hr> <p>I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution.</p>
[ { "answer_id": 6496, "author": "Jason Day", "author_id": 737, "author_profile": "https://Stackoverflow.com/users/737", "pm_score": 6, "selected": true, "text": "# sudo cp /etc/localtime /etc/localtime.dist\n# sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime\n" }, { "answer_id": 6502, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 0, "selected": false, "text": "/usr/bin/zdump -v /etc/localtime | less\n /etc/localtime Sun Mar 31 01:00:00 2080 UTC = Sun Mar 31 02:00:00 2080 BST isdst=1 gmtoff=3600\n" }, { "answer_id": 182437, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 2, "selected": false, "text": "-Duser.timezone=Australia/Sydney JAVA_OPTS Australia/Sydney Pacific/Numea" }, { "answer_id": 3912695, "author": "Liu Zehua", "author_id": 473064, "author_profile": "https://Stackoverflow.com/users/473064", "pm_score": 5, "selected": false, "text": "$ sudo cp /etc/timezone /etc/timezone.dist\n$ echo \"Australia/Adelaide\" | sudo tee /etc/timezone\nAustralia/Adelaide\n$ sudo dpkg-reconfigure --frontend noninteractive tzdata\n\nCurrent default time zone: 'Australia/Adelaide'\nLocal time is now: Sat May 8 21:19:24 CST 2010.\nUniversal Time is now: Sat May 8 11:49:24 UTC 2010.\n" }, { "answer_id": 66403246, "author": "Sleem", "author_id": 238813, "author_profile": "https://Stackoverflow.com/users/238813", "pm_score": 0, "selected": false, "text": "timedatectl sudo timedatectl set-timezone UTC\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
6,406
<p>Is it possible to access an element on a Master page from the page loaded within the <code>ContentPlaceHolder</code> for the master?</p> <p>I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The <code>ListView</code> currently does not update it's values until the cache is reloaded. We have found that just re-running the <code>ListView.DataBind()</code> will update a listview's contents. We have not been able to run the <code>ListView.DataBind()</code> on a page that uses the Master page. </p> <p>Below is a sample of what I wanted to do but a compiler error says </p> <blockquote> <p>"PeopleListView does not exist in the current context"</p> </blockquote> <p>GIS.master - Where ListView resides</p> <pre><code>...&lt;asp:ListView ID="PeopleListView"... </code></pre> <p>GISInput_People.aspx - Uses GIS.master as it's master page</p> <p>GISInput_People.aspx.cs</p> <pre><code>AddNewPerson() { // Add person to table .... // Update Person List PeopleListView.DataBind(); ... } </code></pre> <p>What would be the best way to resolve an issue like this in C# .Net?</p>
[ { "answer_id": 6411, "author": "Brandon Wood", "author_id": 423, "author_profile": "https://Stackoverflow.com/users/423", "pm_score": -1, "selected": false, "text": "(Master as MyMaster).PeopleListView.DataBind();\n" }, { "answer_id": 6413, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "ListView peopleListView = (ListView)this.Master.FindControl(\"PeopleListView\");\npeopleListView.DataSource = [whatever];\npeopleListView.DataBind();\n" }, { "answer_id": 23871, "author": "Adam Carr", "author_id": 1405, "author_profile": "https://Stackoverflow.com/users/1405", "pm_score": 1, "selected": false, "text": "<%@ MasterType attribute=\"value\" [attribute=\"value\"...] %>\n" }, { "answer_id": 10945605, "author": "BrainCoder", "author_id": 1245631, "author_profile": "https://Stackoverflow.com/users/1245631", "pm_score": 2, "selected": false, "text": "public TextBox PropMasterTextBox1\n{\n get { return txtMasterBox1; }\n set { txtMasterBox1 = value; }\n}\n Master.PropMasterTextBox1.Text=\"SomeString\";\n public string SetMasterTextBox1Text\n{ \n get { return txtMasterBox1.Text; }\n set { txtMasterBox1.Text = value; }\n}\n Master.SetMasterTextBox1Text=\"someText\";\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ]
6,414
<p>In a C# (feel free to answer for other languages) loop, what's the difference between <code>break</code> and <code>continue</code> as a means to leave the structure of the loop, and go to the next iteration?</p> <p>Example:</p> <pre><code>foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference between this and continue ? //continue; } } </code></pre>
[ { "answer_id": 6415, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 5, "selected": false, "text": "break foreach continue DataRow" }, { "answer_id": 6417, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 12, "selected": true, "text": "break continue for (int i = 0; i < 10; i++) {\n if (i == 0) {\n break;\n }\n\n DoSomeThingWith(i);\n}\n DoSomeThingWith for (int i = 0; i < 10; i++) {\n if(i == 0) {\n continue;\n }\n\n DoSomeThingWith(i);\n}\n DoSomeThingWith i = 0 DoSomeThingWith i = 1 i = 9" }, { "answer_id": 6442, "author": "JeremiahClark", "author_id": 581, "author_profile": "https://Stackoverflow.com/users/581", "pm_score": 9, "selected": false, "text": "break continue" }, { "answer_id": 6446, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 4, "selected": false, "text": "break continue do-while do-until break continue break Ask a question\nWhile the answer is invalid:\n Ask the question\n While True:\n Ask a question\n If the answer is valid:\n break\n do-until Do:\n Ask a question\n Until the answer is valid\n break" }, { "answer_id": 6555, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "a = 5\nwhile a < 10\n a + 1\nend\n a = 5\nb = while a < 10\n a + 1\nend # b is now 10\n 10.times do |x|\n puts x\nend\n def timesten\n 10.times{ |t| puts yield t }\nend\n\n\ntimesten do |x|\n x * 2\nend\n# will print\n2\n4\n6\n8 ... and so on\n\n\ntimesten do |x|\n break\n x * 2\nend\n# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped\n\ntimesten do |x|\n break 5\n x * 2\nend\n# This is the same as above. it's \"returning\" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5\n\ntimesten do |x|\n next 5\n x * 2\nend \n# this would print\n5\n5\n5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.\n" }, { "answer_id": 16866, "author": "SemiColon", "author_id": 1994, "author_profile": "https://Stackoverflow.com/users/1994", "pm_score": 7, "selected": false, "text": "for(i = 0; i < 10; i++)\n{\n if(i == 2)\n break;\n}\n for(i = 0; i < 10; i++)\n{\n if(i == 2)\n goto BREAK;\n}\nBREAK:;\n for(i = 0; i < 10; i++)\n{\n if(i == 2)\n continue;\n\n printf(\"%d\", i);\n}\n for(i = 0; i < 10; i++)\n{\n if(i == 2)\n goto CONTINUE;\n\n printf(\"%d\", i);\n\n CONTINUE:;\n}\n" }, { "answer_id": 4497072, "author": "Pritom Nandy", "author_id": 548420, "author_profile": "https://Stackoverflow.com/users/548420", "pm_score": 4, "selected": false, "text": "// break statement\nfor (int i = 0; i < 5; i++) {\n if (i == 3) {\n break; // It will force to come out from the loop\n }\n\n lblDisplay.Text = lblDisplay.Text + i + \"[Printed] \";\n}\n //continue statement\nfor (int i = 0; i < 5; i++) {\n if (i == 3) {\n continue; // It will take the control to start point of loop\n }\n\n lblDisplay.Text = lblDisplay.Text + i + \"[Printed] \";\n}\n" }, { "answer_id": 19300205, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "foreach(var i in Enumerable.Range(1,3))\n{\n Console.WriteLine(i);\n}\n foreach(var i in Enumerable.Range(1,3))\n{\n if (i == 2)\n break;\n\n Console.WriteLine(i);\n}\n foreach(var i in Enumerable.Range(1,3))\n{\n if (i == 2)\n continue;\n\n Console.WriteLine(i);\n}\n break continue" }, { "answer_id": 35169830, "author": "Umair Khalid", "author_id": 4732930, "author_profile": "https://Stackoverflow.com/users/4732930", "pm_score": 2, "selected": false, "text": "for(int i = 0; i < list.Count; i++){\n if(i == 5)\n i = list.Count; //it will make \"i<list.Count\" false and loop will exit\n}\n" }, { "answer_id": 48887451, "author": "dba", "author_id": 2408978, "author_profile": "https://Stackoverflow.com/users/2408978", "pm_score": 0, "selected": false, "text": " 'VB\n For i=0 To 10\n If i=5 then Exit For '= break in C#;\n 'Do Something for i<5\n next\n \n For i=0 To 10\n If i=5 then Continue For '= continue in C#\n 'Do Something for i<>5...\n Next\n" }, { "answer_id": 69146895, "author": "Mostafa Ghorbani", "author_id": 12094348, "author_profile": "https://Stackoverflow.com/users/12094348", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n {\n var numbers = new List<int>();\n\n\n while (numbers.Count < 5)\n { \n \n Console.WriteLine(\"Enter 5 uniqe numbers:\");\n var number = Convert.ToInt32(Console.ReadLine());\n\n\n\n if (numbers.Contains(number))\n {\n Console.WriteLine(\"You have already entered\" + number);\n continue;\n }\n\n\n\n numbers.Add(number);\n }\n\n\n numbers.Sort();\n\n\n foreach(var number in numbers)\n {\n Console.WriteLine(number);\n }\n\n\n }\n 1,2,3,4,5\n 1,2,2,2,3,4\n {\n var sum = 0;\n while (true)\n {\n Console.Write(\"Enter a number (or 'ok' to exit): \");\n var input = Console.ReadLine();\n\n if (input.ToLower() == \"ok\")\n break;\n\n sum += Convert.ToInt32(input);\n }\n Console.WriteLine(\"Sum of all numbers is: \" + sum);\n }\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
6,430
<p>I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an <code>ArrayList</code> of business objects bound to a Windows Forms <code>DataGrid</code>. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the <code>DataGrid</code> to find any changes, and save them to the database. But I can't find a way to access the <code>DataGrid</code> rows. </p> <p>I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an <code>ArrayList</code> as the <code>DataSource</code>?) But as for iterating the <code>DataGrid</code>, I'm quite surprised it doesn't seem possible.</p> <p>Must I really stuff my business objects data into datatables in order to use the datagrid? </p>
[ { "answer_id": 6435, "author": "NotMyself", "author_id": 303, "author_profile": "https://Stackoverflow.com/users/303", "pm_score": 4, "selected": true, "text": "foreach(var row in DataGrid1.Rows)\n{\n DoStuff(row);\n}\n//Or --------------------------------------------- \nforeach(DataGridRow row in DataGrid1.Rows)\n{\n DoStuff(row);\n}\n//Or ---------------------------------------------\nfor(int i = 0; i< DataGrid1.Rows.Count - 1; i++)\n{\n DoStuff(DataGrid1.Rows[i]);\n}\n" }, { "answer_id": 6541, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "List<DataRow>" }, { "answer_id": 7491, "author": "Mike", "author_id": 785, "author_profile": "https://Stackoverflow.com/users/785", "pm_score": 1, "selected": false, "text": "object cell = myDataGrid[row, col];\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/785/" ]
6,441
<p>The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is <em>supposed</em> to disable radio buttons if you select the &quot;Disable 2 radio buttons&quot; option. It should enable the radio buttons if you select the &quot;Enable both radio buttons&quot; option. These both work...</p> <p>However, if you don't use your mouse to move between the 2 options (&quot;Enable...&quot; and &quot;Disable...&quot;) then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves).</p> <p>If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function SetLocationOptions() { var frmTemp = document.frm; var selTemp = frmTemp.user; if (selTemp.selectedIndex &gt;= 0) { var myOpt = selTemp.options[selTemp.selectedIndex]; if (myOpt.attributes[0].nodeValue == '1') { frmTemp.transfer_to[0].disabled = true; frmTemp.transfer_to[1].disabled = true; frmTemp.transfer_to[2].checked = true; } else { frmTemp.transfer_to[0].disabled = false; frmTemp.transfer_to[1].disabled = false; } } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form name="frm" action="coopfunds_transfer_request.asp" method="post"&gt; &lt;select name="user" onchange="javascript: SetLocationOptions()"&gt; &lt;option value="" /&gt;Choose One &lt;option value="58" user_is_tsm="0" /&gt;Enable both radio buttons &lt;option value="157" user_is_tsm="1" /&gt;Disable 2 radio buttons &lt;/select&gt; &lt;br /&gt;&lt;br /&gt; &lt;input type="radio" name="transfer_to" value="fund_amount1" /&gt;Premium&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input type="radio" name="transfer_to" value="fund_amount2" /&gt;Other&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input type="radio" name="transfer_to" value="both" CHECKED /&gt;Both &lt;br /&gt;&lt;br /&gt; &lt;input type="button" class="buttonStyle" value="Submit Request" /&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 6456, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 2, "selected": false, "text": "document.getElementById('whatever') Line 27: <form name=\"frm\" id=\"f\" ...\n\nLine 6: var frmTemp = document.getElementById('f');\n" }, { "answer_id": 6868, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 4, "selected": true, "text": "<select name=\"user\" id=\"selUser\" onchange=\"javascript:SetLocationOptions()\" onkeyup=\"javascript:SetLocationOptions()\">\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
6,467
<p>I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. </p> <p>I'm using a function to increment a day and another to decrement: </p> <pre><code>IncrementaDia(){ echo $1 | awk ' BEGIN { diasDelMes[1] = 31 diasDelMes[2] = 28 diasDelMes[3] = 31 diasDelMes[4] = 30 diasDelMes[5] = 31 diasDelMes[6] = 30 diasDelMes[7] = 31 diasDelMes[8] = 31 diasDelMes[9] = 30 diasDelMes[10] = 31 diasDelMes[11] = 30 diasDelMes[12] = 31 } { anio=substr($1,1,4) mes=substr($1,5,2) dia=substr($1,7,2) if((anio % 4 == 0 &amp;&amp; anio % 100 != 0) || anio % 400 == 0) { diasDelMes[2] = 29; } if( dia == diasDelMes[int(mes)] ) { if( int(mes) == 12 ) { anio = anio + 1 mes = 1 dia = 1 } else { mes = mes + 1 dia = 1 } } else { dia = dia + 1 } } END { printf("%04d%02d%02d", anio, mes, dia) } ' } if [ $# -eq 1 ]; then tomorrow=$1 else today=$(date +"%Y%m%d") tomorrow=$(IncrementaDia $hoy) fi </code></pre> <p>but now I need to do more complex arithmetic. </p> <p>What it's the best and more compatible way to do this?</p>
[ { "answer_id": 6468, "author": "abyx", "author_id": 573, "author_profile": "https://Stackoverflow.com/users/573", "pm_score": 6, "selected": false, "text": "date --date='1 days ago' '+%a'\n" }, { "answer_id": 6471, "author": "ggasp", "author_id": 527, "author_profile": "https://Stackoverflow.com/users/527", "pm_score": 3, "selected": false, "text": "date --date='1 days ago' '+%a'\n date --date='1 days ago' '+%Y%m%d'\n20080807\n" }, { "answer_id": 6746, "author": "abyx", "author_id": 573, "author_profile": "https://Stackoverflow.com/users/573", "pm_score": 2, "selected": false, "text": "$ date -j 0802301535\nSat Mar 1 15:35:00 EST 2008\n" }, { "answer_id": 21642, "author": "caerwyn", "author_id": 2406, "author_profile": "https://Stackoverflow.com/users/2406", "pm_score": 3, "selected": false, "text": "% date -n\n1219371462\n% date 1219371462\nThu Aug 21 22:17:42 EDT 2008\n% \n date(1)" }, { "answer_id": 70745, "author": "Jonathan Bourke", "author_id": 8361, "author_profile": "https://Stackoverflow.com/users/8361", "pm_score": 2, "selected": false, "text": "#!/usr/local/bin/perl\n\n$today = time();\n\n$user = $ARGV[0];\n\n$command=\"awk -F: '/$user/ {print \\$6}' /etc/passwd\";\n\nchomp ($user_dir = `$command`);\n\nif ( -f \"$user_dir/.sh_history\" ) {\n @file_dates = stat(\"$user_dir/.sh_history\");\n $sh_file_date = $file_dates[8];\n} else {\n $sh_file_date = 0;\n}\nif ( -f \"$user_dir/.bash_history\" ) {\n @file_dates = stat(\"$user_dir/.bash_history\");\n $bash_file_date = $file_dates[8];\n} else {\n $bash_file_date = 0;\n}\nif ( $sh_file_date > $bash_file_date ) {\n $file_date = $sh_file_date;\n} else {\n $file_date = $bash_file_date;\n}\n$difference = $today - $file_date;\n\nif ( $difference >= 3888000 ) {\n print \"User needs to be disabled, 45 days old or older!\\n\";\n exit (1);\n} else {\n print \"OK\\n\";\n exit (0);\n}\n" }, { "answer_id": 71794, "author": "Joe Watkins", "author_id": 11928, "author_profile": "https://Stackoverflow.com/users/11928", "pm_score": 2, "selected": false, "text": "\nBEGIN { dateinit }\n { newdate=daysadd(OldDate,DaysToAdd)}\n\n # daynum: convert DD-MON-YYYY to day count\n #-----------------------------------------\nfunction daynum(date, d,m,y,i,n)\n{\n y=substr(date,8,4)\n m=gmonths[toupper(substr(date,4,3))]\n d=substr(date,1,2)\n return mktime(y\" \"m\" \"d\" 12 00 00\")\n}\n\n #numday: convert day count to DD-MON-YYYY\n #-------------------------------------------\nfunction numday(n, y,m,d)\n{\n m=toupper(substr(strftime(\"%B\",n),1,3))\n return strftime(\"%d-\"m\"-%Y\",n)\n}\n\n # daysadd: add (or subtract) days from date (DD-MON-YYYY), return new date (DD-MON-YYYY)\n #------------------------------------------\nfunction daysadd(date, days)\n{\n return numday(daynum(date)+(days*86400))\n}\n\n #init variables for date calcs\n #-----------------------------------------\nfunction dateinit( x,y,z)\n{\n # Stuff for date calcs\n split(\"JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12\", z)\n for (x in z)\n {\n split(z[x],y,\":\")\n gmonths[y[1]]=y[2]\n }\n}\n" }, { "answer_id": 3125174, "author": "Larry Morell", "author_id": 376990, "author_profile": "https://Stackoverflow.com/users/376990", "pm_score": 5, "selected": true, "text": "$ ComputeDate 'yesterday': 03/19/2010\n$ ComputeDate 'yes': 03/19/2010\n$ ComputeDate 'today': 03/20/2010\n$ ComputeDate 'tod': 03/20/2010\n$ ComputeDate 'now': 03/20/2010\n$ ComputeDate 'tomorrow': 03/21/2010\n$ ComputeDate 'tom': 03/21/2010\n$ ComputeDate '10/29/32': 10/29/2032\n$ ComputeDate 'October 29': 10/1/2029\n$ ComputeDate 'October 29, 2010': 10/29/2010\n$ ComputeDate 'this monday': 'this monday' has passed. Did you mean 'next monday?'\n$ ComputeDate 'a week after today': 03/27/2010\n$ ComputeDate 'this satu': 03/20/2010\n$ ComputeDate 'next monday': 03/22/2010\n$ ComputeDate 'next thur': 03/25/2010\n$ ComputeDate 'mon in 2 weeks': 03/28/2010\n$ ComputeDate 'the last day of the month': 03/31/2010\n$ ComputeDate 'the last day of feb': 2/28/2010\n$ ComputeDate 'the last day of feb 2000': 2/29/2000\n$ ComputeDate '1 week from yesterday': 03/26/2010\n$ ComputeDate '1 week from today': 03/27/2010\n$ ComputeDate '1 week from tomorrow': 03/28/2010\n$ ComputeDate '2 weeks from yesterday': 4/2/2010\n$ ComputeDate '2 weeks from today': 4/3/2010\n$ ComputeDate '2 weeks from tomorrow': 4/4/2010\n$ ComputeDate '1 week after the last day of march': 4/7/2010\n$ ComputeDate '1 week after next Thursday': 4/1/2010\n$ ComputeDate '2 weeks after the last day of march': 4/14/2010\n$ ComputeDate '2 weeks after 1 day after the last day of march': 4/15/2010\n$ ComputeDate '1 day after the last day of march': 4/1/2010\n$ ComputeDate '1 day after 1 day after 1 day after 1 day after today': 03/24/2010\n #! /bin/bash\n# ConvertDate -- convert a human-readable date to a MM/DD/YY date\n#\n# Date ::= Month/Day/Year\n# | Month/Day\n# | DayOfWeek\n# | [this|next] DayOfWeek\n# | DayofWeek [of|in] [Number|next] weeks[s]\n# | Number [day|week][s] from Date\n# | the last day of the month\n# | the last day of Month\n#\n# Month ::= January | February | March | April | May | ... | December\n# January ::= jan | january | 1\n# February ::= feb | january | 2\n# ...\n# December ::= dec | december | 12\n# Day ::= 1 | 2 | ... | 31\n# DayOfWeek ::= today | Sunday | Monday | Tuesday | ... | Saturday\n# Sunday ::= sun*\n# ...\n# Saturday ::= sat*\n#\n# Number ::= Day | a\n#\n# Author: Larry Morell\n\nif [ $# = 0 ]; then\n printdirections $0\n exit\nfi\n\n\n\n# Request the value of a variable\nGetVar () {\n Var=$1\n echo -n \"$Var= [${!Var}]: \"\n local X\n read X\n if [ ! -z $X ]; then\n eval $Var=\"$X\"\n fi\n}\n\nIsLeapYear () {\n local Year=$1\n if [ $[20$Year % 4] -eq 0 ]; then\n echo yes\n else\n echo no\n fi\n}\n\n# AddToDate -- compute another date within the same year\n\nDayNames=(mon tue wed thu fri sat sun ) # To correspond with 'date' output\n\nDay2Int () {\n ErrorFlag=\n case $1 in\n -e )\n ErrorFlag=-e; shift\n ;;\n esac\n local dow=$1\n n=0\n while [ $n -lt 7 -a $dow != \"${DayNames[n]}\" ]; do\n let n++\n done\n if [ -z \"$ErrorFlag\" -a $n -eq 7 ]; then\n echo Cannot convert $dow to a numeric day of wee\n exit\n fi\n echo $[n+1]\n\n}\n\nMonths=(31 28 31 30 31 30 31 31 30 31 30 31)\nMonthNames=(jan feb mar apr may jun jul aug sep oct nov dec)\n# Returns the month (1-12) from a date, or a month name\nMonth2Int () {\n ErrorFlag=\n case $1 in\n -e )\n ErrorFlag=-e; shift\n ;;\n esac\n M=$1\n Month=${M%%/*} # Remove /...\n case $Month in\n [a-z]* )\n Month=${Month:0:3}\n M=0\n while [ $M -lt 12 -a ${MonthNames[M]} != $Month ]; do\n let M++\n done\n let M++\n esac\n if [ -z \"$ErrorFlag\" -a $M -gt 12 ]; then\n echo \"'$Month' Is not a valid month.\"\n exit\n fi\n echo $M\n}\n\n# Retrieve month,day,year from a legal date\nGetMonth() {\n echo ${1%%/*}\n}\n\nGetDay() {\n echo $1 | col / 2\n}\n\nGetYear() {\n echo ${1##*/}\n}\n\n\nAddToDate() {\n\n local Date=$1\n local days=$2\n local Month=`GetMonth $Date`\n local Day=`echo $Date | col / 2` # Day of Date\n local Year=`echo $Date | col / 3` # Year of Date\n local LeapYear=`IsLeapYear $Year`\n\n if [ $LeapYear = \"yes\" ]; then\n let Months[1]++\n fi\n Day=$[Day+days]\n while [ $Day -gt ${Months[$Month-1]} ]; do\n Day=$[Day - ${Months[$Month-1]}]\n let Month++\n done\n echo \"$Month/$Day/$Year\"\n}\n\n# Convert a date to normal form\nNormalizeDate () {\n Date=`echo \"$*\" | sed 'sX *X/Xg'`\n local Day=`date +%d`\n local Month=`date +%m`\n local Year=`date +%Y`\n #echo Normalizing Date=$Date > /dev/tty\n case $Date in\n */*/* )\n Month=`echo $Date | col / 1 `\n Month=`Month2Int $Month`\n Day=`echo $Date | col / 2`\n Year=`echo $Date | col / 3`\n ;;\n */* )\n Month=`echo $Date | col / 1 `\n Month=`Month2Int $Month`\n Day=1\n Year=`echo $Date | col / 2 `\n ;;\n [a-z]* ) # Better be a month or day of week\n Exp=${Date:0:3}\n case $Exp in\n jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )\n Month=$Exp\n Month=`Month2Int $Month`\n Day=1\n #Year stays the same\n ;;\n mon|tue|wed|thu|fri|sat|sun )\n # Compute the next such day\n local DayOfWeek=`date +%u`\n D=`Day2Int $Exp`\n if [ $DayOfWeek -le $D ]; then\n Date=`AddToDate $Month/$Day/$Year $[D-DayOfWeek]`\n else\n Date=`AddToDate $Month/$Day/$Year $[7+D-DayOfWeek]`\n fi\n\n # Reset Month/Day/Year\n Month=`echo $Date | col / 1 `\n Day=`echo $Date | col / 2`\n Year=`echo $Date | col / 3`\n ;;\n * ) echo \"$Exp is not a valid month or day\"\n exit\n ;;\n esac\n ;;\n * ) echo \"$Date is not a valid date\"\n exit\n ;;\n esac\n case $Day in\n [0-9]* );; # Day must be numeric\n * ) echo \"$Date is not a valid date\"\n exit\n ;;\n esac\n [0-9][0-9][0-9][0-9] );; # Year must be 4 digits\n [0-9][0-9] )\n Year=20$Year\n ;;\n esac\n Date=$Month/$Day/$Year\n echo $Date\n}\n# NormalizeDate jan\n# NormalizeDate january\n# NormalizeDate jan 2009\n# NormalizeDate jan 22 1983\n# NormalizeDate 1/22\n# NormalizeDate 1 22\n# NormalizeDate sat\n# NormalizeDate sun\n# NormalizeDate mon\n\nComputeExtension () {\n\n local Date=$1; shift\n local Month=`GetMonth $Date`\n local Day=`echo $Date | col / 2`\n local Year=`echo $Date | col / 3`\n local ExtensionExp=\"$*\"\n case $ExtensionExp in\n *w*d* ) # like 5 weeks 3 days or even 5w2d\n ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`\n weeks=`echo $ExtensionExp | col 1`\n days=`echo $ExtensionExp | col 2`\n days=$[7*weeks+days]\n Due=`AddToDate $Month/$Day/$Year $days`\n ;;\n *d ) # Like 5 days or 5d\n ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`\n days=$ExtensionExp\n Due=`AddToDate $Month/$Day/$Year $days`\n ;;\n * )\n Due=$ExtensionExp\n ;;\n esac\n echo $Due\n\n}\n\n\n# Pop -- remove the first element from an array and shift left\nPop () {\n Var=$1\n eval \"unset $Var[0]\"\n eval \"$Var=(\\${$Var[*]})\"\n}\n\nComputeDate () {\n local Date=`NormalizeDate $1`; shift\n local Expression=`echo $* | sed 's/^ *a /1 /;s/,/ /' | tr A-Z a-z `\n local Exp=(`echo $Expression `)\n local Token=$Exp # first one\n local Ans=\n #echo \"Computing date for ${Exp[*]}\" > /dev/tty\n case $Token in\n */* ) # Regular date\n M=`GetMonth $Token`\n D=`GetDay $Token`\n Y=`GetYear $Token`\n if [ -z \"$Y\" ]; then\n Y=$Year\n elif [ ${#Y} -eq 2 ]; then\n Y=20$Y\n fi\n Ans=\"$M/$D/$Y\"\n ;;\n yes* )\n Ans=`AddToDate $Date -1`\n ;;\n tod*|now )\n Ans=$Date\n ;;\n tom* )\n Ans=`AddToDate $Date 1`\n ;;\n the )\n case $Expression in\n *day*after* ) #the day after Date\n Pop Exp; # Skip the\n Pop Exp; # Skip day\n Pop Exp; # Skip after\n #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty\n Date=`ComputeDate $Date ${Exp[*]}` #Recursive call\n #echo \"New date is \" $Date > /dev/tty\n Ans=`AddToDate $Date 1`\n ;;\n *last*day*of*th*month|*end*of*th*month )\n M=`date +%m`\n Day=${Months[M-1]}\n if [ $M -eq 2 -a `IsLeapYear $Year` = yes ]; then\n let Day++\n fi\n Ans=$Month/$Day/$Year\n ;;\n *last*day*of* )\n D=${Expression##*of }\n D=`NormalizeDate $D`\n M=`GetMonth $D`\n Y=`GetYear $D`\n # echo M is $M > /dev/tty\n Day=${Months[M-1]}\n if [ $M -eq 2 -a `IsLeapYear $Y` = yes ]; then\n let Day++\n fi\n Ans=$[M]/$Day/$Y\n ;;\n * )\n echo \"Unknown expression: \" $Expression\n exit\n ;;\n esac\n ;;\n next* ) # next DayOfWeek\n Pop Exp\n dow=`Day2Int $DayOfWeek` # First 3 chars\n tdow=`Day2Int ${Exp:0:3}` # First 3 chars\n n=$[7-dow+tdow]\n Ans=`AddToDate $Date $n`\n ;;\n this* )\n Pop Exp\n dow=`Day2Int $DayOfWeek`\n tdow=`Day2Int ${Exp:0:3}` # First 3 chars\n if [ $dow -gt $tdow ]; then\n echo \"'this $Exp' has passed. Did you mean 'next $Exp?'\"\n exit\n fi\n n=$[tdow-dow]\n Ans=`AddToDate $Date $n`\n ;;\n [a-z]* ) # DayOfWeek ...\n\n M=${Exp:0:3}\n case $M in\n jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )\n ND=`NormalizeDate ${Exp[*]}`\n Ans=$ND\n ;;\n mon|tue|wed|thu|fri|sat|sun )\n dow=`Day2Int $DayOfWeek`\n Ans=`NormalizeDate $Exp`\n\n if [ ${#Exp[*]} -gt 1 ]; then # Just a DayOfWeek\n #tdow=`GetDay $Exp` # First 3 chars\n #if [ $dow -gt $tdow ]; then\n #echo \"'this $Exp' has passed. Did you mean 'next $Exp'?\"\n #exit\n #fi\n #n=$[tdow-dow]\n #else # DayOfWeek in a future week\n Pop Exp # toss monday\n Pop Exp # toss in/off\n if [ $Exp = next ]; then\n Exp=2\n fi\n n=$[7*(Exp-1)] # number of weeks\n n=$[n+7-dow+tdow]\n Ans=`AddToDate $Date $n`\n fi\n ;;\n esac\n ;;\n [0-9]* ) # Number weeks [from|after] Date\n n=$Exp\n Pop Exp;\n case $Exp in\n w* ) let n=7*n;;\n esac\n\n Pop Exp; Pop Exp\n #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty\n Date=`ComputeDate $Date ${Exp[*]}` #Recursive call\n #echo \"New date is \" $Date > /dev/tty\n Ans=`AddToDate $Date $n`\n ;;\n esac\n echo $Ans\n}\n\nYear=`date +%Y`\nMonth=`date +%m`\nDay=`date +%d`\nDayOfWeek=`date +%a |tr A-Z a-z`\n\nDate=\"$Month/$Day/$Year\"\nComputeDate $Date $*\n $ echo a b c d e | col 5 3 2\n e c b\n #!/bin/sh\n# col -- extract columns from a file\n# Usage:\n# col [-r] [c] col-1 col-2 ...\n# where [c] if supplied defines the field separator\n# where each col-i represents a column interpreted according to the presence of -r as follows:\n# -r present : counting starts from the right end of the line\n# -r absent : counting starts from the left side of the line\nSeparator=\" \"\nReverse=false\ncase \"$1\" in\n -r ) Reverse=true; shift;\n ;;\n [0-9]* )\n ;;\n * )Separator=\"$1\"; shift;\n ;;\nesac\n\ncase \"$1\" in\n -r ) Reverse=true; shift;\n ;;\n [0-9]* )\n ;;\n * )Separator=\"$1\"; shift;\n ;;\nesac\n\n# Replace each col-i with $i\nCols=\"\"\nfor f in $*\ndo\n if [ $Reverse = true ]; then\n Cols=\"$Cols \\$(NF-$f+1),\"\n else\n Cols=\"$Cols \\$$f,\"\n fi\n\ndone\n\nCols=`echo \"$Cols\" | sed 's/,$//'`\n#echo \"Using column specifications of $Cols\"\nawk -F \"$Separator\" \"{print $Cols}\"\n #!/bin/sh\n#\n# printdirections -- print header lines of a shell script\n#\n# Usage:\n# printdirections path\n# where\n# path is a *full* path to the shell script in question\n# beginning with '/'\n#\n# To use printdirections, you must include (as comments at the top\n# of your shell script) documentation for running the shell script.\n\nif [ $# -eq 0 -o \"$*\" = \"-h\" ]; then\n printdirections $0\n exit\nfi\n# Delete the command invocation at the top of the file, if any\n# Delete from the place where printdirections occurs to the end of the file\n# Remove the # comments\n# There is a bizarre oddity here.\n sed '/#!/d;/.*printdirections/,$d;/ *#/!d;s/# //;s/#//' $1 > /tmp/printdirections.$$\n\n# Count the number of lines\nnumlines=`wc -l /tmp/printdirections.$$ | awk '{print $1}'`\n\n# Remove the last line\nnumlines=`expr $numlines - 1`\n\n\nhead -n $numlines /tmp/printdirections.$$\nrm /tmp/printdirections.$$\n $ chmod a+x ComputeDate col printdirections\n" }, { "answer_id": 8244643, "author": "Harun Prasad", "author_id": 222765, "author_profile": "https://Stackoverflow.com/users/222765", "pm_score": 4, "selected": false, "text": "meetingDate='12/31/2011' # MM/DD/YYYY Format\nreminderDate=`date --date=$meetingDate'-1 day' +'%m/%d/%Y'`\necho $reminderDate\n date" }, { "answer_id": 10315034, "author": "Johnny Baloney", "author_id": 779449, "author_profile": "https://Stackoverflow.com/users/779449", "pm_score": 0, "selected": false, "text": "date grep > sh ./datecalc.sh \"2012-08-04 19:43:00\" + 1s\n2012-08-04 19:43:00 + 0d0h0m1s\n2012-08-04 19:43:01\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\" - 1s1m1h1d\n2012-08-04 19:43:00 - 1d1h1m1s\n2012-08-03 18:41:59\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\" - 1d2d1h2h1m2m1s2sblahblah\n2012-08-04 19:43:00 - 1d1h1m1s\n2012-08-03 18:41:59\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\" x 1d\nBad operator :-(\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\"\nMissing arguments :-(\n\n> sh ./datecalc.sh gibberish + 1h\ndate: invalid date `gibberish'\nInvalid date :-(\n #!/bin/sh\n\n# Usage:\n#\n# datecalc \"<date>\" <operator> <period>\n#\n# <date> ::= see \"man date\", section \"DATE STRING\"\n# <operator> ::= + | -\n# <period> ::= INTEGER<unit> | INTEGER<unit><period>\n# <unit> ::= s | m | h | d\n\nif [ $# -lt 3 ]; then\necho \"Missing arguments :-(\"\nexit; fi\n\ndate=`eval \"date -d \\\"$1\\\" +%s\"`\nif [ -z $date ]; then\necho \"Invalid date :-(\"\nexit; fi\n\nif ! ([ $2 == \"-\" ] || [ $2 == \"+\" ]); then\necho \"Bad operator :-(\"\nexit; fi\nop=$2\n\nminute=$[60]\nhour=$[$minute*$minute]\nday=$[24*$hour]\n\ns=`echo $3 | grep -oe '[0-9]*s' | grep -m 1 -oe '[0-9]*'`\nm=`echo $3 | grep -oe '[0-9]*m' | grep -m 1 -oe '[0-9]*'`\nh=`echo $3 | grep -oe '[0-9]*h' | grep -m 1 -oe '[0-9]*'`\nd=`echo $3 | grep -oe '[0-9]*d' | grep -m 1 -oe '[0-9]*'`\nif [ -z $s ]; then s=0; fi\nif [ -z $m ]; then m=0; fi\nif [ -z $h ]; then h=0; fi\nif [ -z $d ]; then d=0; fi\n\nms=$[$m*$minute]\nhs=$[$h*$hour]\nds=$[$d*$day]\n\nsum=$[$s+$ms+$hs+$ds]\nout=$[$date$op$sum]\nformattedout=`eval \"date -d @$out +\\\"%Y-%m-%d %H:%M:%S\\\"\"`\n\necho $1 $2 $d\"d\"$h\"h\"$m\"m\"$s\"s\"\necho $formattedout\n" }, { "answer_id": 26878392, "author": "sj26", "author_id": 158252, "author_profile": "https://Stackoverflow.com/users/158252", "pm_score": 3, "selected": false, "text": "-j -v date $ date\nWed 12 Nov 2014 13:36:00 AEDT\n -v +1d $ date -v +1d\nThu 13 Nov 2014 13:36:34 AEDT\n -j $ date -j -f \"%a %b %d %H:%M:%S %Y %z\" \"Sat Aug 09 13:37:14 2014 +1100\"\nSat 9 Aug 2014 12:37:14 AEST\n $ date -v +1d -f \"%a %b %d %H:%M:%S %Y %z\" \"Sat Aug 09 13:37:14 2014 +1100\"\nSun 10 Aug 2014 12:37:14 AEST\n -v -j $ date -v +1m -v -1w\nFri 5 Dec 2014 13:40:07 AEDT\n" }, { "answer_id": 38362241, "author": "Tulio Galdamez", "author_id": 6586682, "author_profile": "https://Stackoverflow.com/users/6586682", "pm_score": -1, "selected": false, "text": "TZ=GMT+6;\nexport TZ\nmes=`date --date='2 days ago' '+%m'`\ndia=`date --date='2 days ago' '+%d'`\nanio=`date --date='2 days ago' '+%Y'`\nhora=`date --date='2 days ago' '+%H'`\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527/" ]
6,475
<p>In a machine with AIX without <code>PERL</code> I need to filter records that will be considered duplicated if they have the same id and if they were registered between a period of four hours. </p> <p>I implemented this filter using <code>AWK</code> and work pretty well but I need a solution much faster: </p> <pre> # Generar lista de Duplicados awk 'BEGIN { FS="," } /OK/ { old[$8] = f[$8]; f[$8] = mktime($4, $3, $2, $5, $6, $7); x[$8]++; } /OK/ && x[$8]>1 && f[$8]-old[$8] <p>Any suggestions? Are there ways to improve the environment (preloading the file or someting like that)? </p> <p>The input file is already sorted.</p> <p>With the corrections suggested by <a href="https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6869">jj33</a> I made a new version with better treatment of dates, still maintaining a low profile for incorporating more operations: </p> awk 'BEGIN { FS=","; SECSPERMINUTE=60; SECSPERHOUR=3600; SECSPERDAY=86400; split("0 31 59 90 120 151 181 212 243 273 304 334", DAYSTOMONTH, " "); split("0 366 731 1096 1461 1827 2192 2557 2922 3288 3653 4018 4383 4749 5114 5479 5844 6210 6575 6940 7305", DAYSTOYEAR, " "); } /OK/ { old[$8] = f[$8]; f[$8] = mktime($4, $3, $2, $5, $6, $7); x[$8]++; } /OK/ && x[$8]>1 && f[$8]-old[$8] 2 ) && ( ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) ) ) { d2m = d2m + 1; } d2y = DAYSTOYEAR[ y - 1999 ]; return ss + (mm*SECSPERMINUTE) + (hh*SECSPEROUR) + (d*SECSPERDAY) + (d2m*SECSPERDAY) + (d2y*SECSPERDAY); } ' </pre>
[ { "answer_id": 7210, "author": "AnotherHowie", "author_id": 923, "author_profile": "https://Stackoverflow.com/users/923", "pm_score": 1, "selected": false, "text": "sort -k 8 < input.txt > output.txt\n" }, { "answer_id": 7756, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 1, "selected": false, "text": "cut -d, -f8 <infile.txt | sort | uniq -d | xargs -i grep {} infile.txt >outfile.txt\n" } ]
2008/08/08
[ "https://Stackoverflow.com/questions/6475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527/" ]
6,484
<p><a href="http://www.google.com/search?q=how%20to%20mock%20sealed%20class" rel="noreferrer">Mocking sealed classes</a> can be quite a pain. I currently favor an <a href="http://en.wikipedia.org/wiki/Adapter_pattern" rel="noreferrer">Adapter pattern</a> to handle this, but something about just keeps feels weird. </p> <p><strong>So, What is the best way you mock sealed classes?</strong></p> <p><em>Java answers are more than welcome</em>. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer.</p> <p>But here are some of the .NET opinions:</p> <ul> <li><a href="http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx" rel="noreferrer">Why Duck Typing Matters for C# Develoepers</a> </li> <li><a href="http://cs.rthand.com/blogs/blog_with_righthand/archive/2008/07/22/Creating-wrappers-for-sealed-and-other-types-for-mocking.aspx" rel="noreferrer">Creating wrappers for sealed and other types for mocking</a></li> <li><a href="http://weblogs.asp.net/cibrax/archive/2008/05/16/unit-tests-for-wcf.aspx" rel="noreferrer">Unit tests for WCF (and Moq)</a></li> </ul>
[ { "answer_id": 2587888, "author": "Adam Lenda", "author_id": 104846, "author_profile": "https://Stackoverflow.com/users/104846", "pm_score": 1, "selected": false, "text": " [TestMethod]\n public void Test()\n {\n Queue<Message> messages = new Queue<Message>();\n Action<Message> sendDelegate = msg => messages.Enqueue(msg);\n Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate =\n (v1, v2) =>\n {\n throw new Exception(\"Test Exception to simulate a failed queue read.\");\n };\n\n MessageQueue mockQueue = QueueMonitorHelper.MockQueue(sendDelegate, receiveDelegate).Object;\n }\n public static Mock<MessageQueue> MockQueue\n (Action<Message> sendDelegate, Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate)\n {\n Mock<MessageQueue> mockQueue = new Mock<MessageQueue>(MockBehavior.Strict);\n\n Expression<Action<MessageQueue>> sendMock = (msmq) => msmq.Send(It.IsAny<Message>()); //message => messages.Enqueue(message);\n mockQueue.Setup(sendMock).Callback<Message>(sendDelegate);\n\n Expression<Func<MessageQueue, Message>> receiveMock = (msmq) => msmq.Receive(It.IsAny<TimeSpan>(), It.IsAny<MessageQueueTransaction>());\n mockQueue.Setup(receiveMock).Returns<TimeSpan, MessageQueueTransaction>(receiveDelegate);\n\n return mockQueue;\n }\n" }, { "answer_id": 30200039, "author": "hassan", "author_id": 4893007, "author_profile": "https://Stackoverflow.com/users/4893007", "pm_score": 3, "selected": false, "text": "System.Runtime.Serialization.FormatterServices.GetUninitializedObject(instanceType) YourObject.GetType().GetProperty(\"PropertyName\").SetValue(dto, newValue, null); YourObject.GetType().GetField(\"FieldName\").SetValue(dto, newValue);" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307/" ]
6,499
<p>There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:</p> <pre><code>function Vector(x, y, x) { this.x = x; this.y = y; this.z = z; return this; } Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); } </code></pre> <p>and closure based approaches similar to</p> <pre><code>function Vector(x, y, z) { this.length = function() { return Math.sqrt(x * x + ...); } } </code></pre> <p>For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do.</p>
[ { "answer_id": 6516, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 2, "selected": false, "text": "function Vector(x, y, z) {\n function length() {\n return Math.sqrt(x * x + ...);\n }\n}\n" }, { "answer_id": 6533, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "var Person = Class.create({\n initialize: function(name) {\n this.name = name;\n },\n say: function(message) {\n return this.name + ': ' + message;\n }\n});\n Prototype.js" }, { "answer_id": 112916, "author": "JayTee", "author_id": 20153, "author_profile": "https://Stackoverflow.com/users/20153", "pm_score": 3, "selected": false, "text": "var Vector = function(){};\n\nVector.prototype = {\n init:function(x,y,z) {\n this.x = x;\n this.y = y;\n this.z = z;\n },\n length:function() {\n return Math.sqrt(x * x + ...);\n }\n};\n\nvar v1 = new Vector();\nv1.init(1,2,3);\n" }, { "answer_id": 19911320, "author": "James Drinkard", "author_id": 543572, "author_profile": "https://Stackoverflow.com/users/543572", "pm_score": 1, "selected": false, "text": "var james = new Person();\n function Car (type) {\n this.type = type;\n this.color = \"red\";\n}\n\nCar.prototype.getInfo = function() {\n return this.color + ' ' + this.type + ' car';\n};\n var car = {\n type: \"honda\",\n color: \"red\",\n getInfo: function () {\n return this.color + ' ' + this.type + ' car';\n }\n}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784/" ]
6,512
<p>I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal.</p> <p>What is the simplest way to implement continuations for Scheme in C?</p>
[ { "answer_id": 31951, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 3, "selected": false, "text": "setjmp longjmp" }, { "answer_id": 46927339, "author": "alinsoar", "author_id": 1419272, "author_profile": "https://Stackoverflow.com/users/1419272", "pm_score": 2, "selected": false, "text": "soegaard R. Kent Dybvig. \"Three Implementation Models for Scheme\" call/cc 1+2+3+...+1000 (call-with-current-continuation \n (lambda (break)\n ((lambda (s) (s s 1000 break))\n (lambda (s n cc)\n (if (= 0 n)\n (cc 0)\n (+ n\n ;; non-tail-recursive,\n ;; the stack grows at each recursive call\n (call-with-current-continuation\n (lambda (__)\n (s s (- n 1) __)))))))))\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
6,547
<p>One of those classic programming interview questions...</p> <p>You are given two marbles, and told that they will break when dropped from some certain height (and presumably suffer no damage if dropped from below that height). You’re then taken to a 100 story building (presumably higher than the certain height), and asked to find the highest floor your can drop a marble from without breaking it as efficiently as possible.</p> <p>Extra info</p> <ul> <li>You must find the correct floor (not a possible range)</li> <li>The marbles are both guaranteed to break at the same floor</li> <li>Assume it takes zero time for you to change floors - only the number of marble drops counts</li> <li>Assume the correct floor is randomly distributed in the building</li> </ul>
[ { "answer_id": 21133595, "author": "herohuyongtao", "author_id": 2589776, "author_profile": "https://Stackoverflow.com/users/2589776", "pm_score": 4, "selected": false, "text": "N M" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
6,557
<p>It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.</p> <pre><code>List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl; </code></pre> <p>results in Cannot implicitly convert type <code>System.Collections.Generic.List&lt;string&gt;</code> to <code>System.Collections.Generic.List&lt;object&gt;</code></p> <p>And then...</p> <pre><code>List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl; </code></pre> <p>results in Cannot convert type <code>System.Collections.Generic.List&lt;string&gt;</code> to <code>System.Collections.Generic.List&lt;object&gt;</code></p> <p>Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.</p>
[ { "answer_id": 6559, "author": "Rex M", "author_id": 67, "author_profile": "https://Stackoverflow.com/users/67", "pm_score": 4, "selected": false, "text": "List<> List<string>() ListString()" }, { "answer_id": 6567, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 6, "selected": true, "text": "List<object> ol = new List<object>();\nList<string> sl;\nsl = (List<string>)ol;\n" }, { "answer_id": 6574, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 3, "selected": false, "text": "List<string> sl = new List<string>();\n//populate sl\nList<object> ol = new List<object>(sl);\n List<object> ol = new List<object>();\nol.AddRange(sl);\n" }, { "answer_id": 6577, "author": "Ray", "author_id": 233, "author_profile": "https://Stackoverflow.com/users/233", "pm_score": 5, "selected": false, "text": "List<string> sl = new List<string>();\nIEnumerable<object> ol;\nol = sl.Cast<object>();\n" }, { "answer_id": 7168, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 4, "selected": false, "text": "List<string> sl = new List<string>();\n// Add strings to sl\n\nList<object> ol = new List<object>();\n\nforeach(string s in sl)\n{\n ol.Add((object)s); // The cast is performed implicitly even if omitted\n}\n var sl = new List<string>();\n// Add strings to sl\n\nvar ol = new List<object>(sl.Cast<object>());\n\n// OR\nvar ol = sl.Cast<object>().ToList();\n\n// OR (note that the cast to object here is required)\nvar ol = sl.Select(s => (object)s).ToList();\n" }, { "answer_id": 7205, "author": "Valters Vingolds", "author_id": 885, "author_profile": "https://Stackoverflow.com/users/885", "pm_score": 1, "selected": false, "text": "List<object> List<string>" }, { "answer_id": 189354, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "object[] a = new string[] {\"spam\", \"eggs\"};\n int a" }, { "answer_id": 215536, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 3, "selected": false, "text": "List<string> sl = new List<string>();\nList<object> ol = sl.Cast<object>().ToList();\n" }, { "answer_id": 965792, "author": "Alvin Ashcraft", "author_id": 1137, "author_profile": "https://Stackoverflow.com/users/1137", "pm_score": 0, "selected": false, "text": "public IList<B> ConvertIList<D, B>(IList<D> list) where D : B\n{\n List<B> newList = new List<B>();\n\n foreach (D item in list)\n {\n newList.Add(item);\n }\n\n return newList;\n}\n" }, { "answer_id": 1571309, "author": "Menno", "author_id": 190472, "author_profile": "https://Stackoverflow.com/users/190472", "pm_score": 0, "selected": false, "text": "private List<Leerling> Leerlingen = new List<Leerling>();\n List<object> Leerlingen = (List<Leerling>)_DeserialiseerLeerlingen._TeSerialiserenObjecten.Cast<Leerling>();\n .Cast IEnumerable IEnemuerable List<>" }, { "answer_id": 36072174, "author": "Cristinadeveloper", "author_id": 5875199, "author_profile": "https://Stackoverflow.com/users/5875199", "pm_score": 0, "selected": false, "text": "IEnumerable<object> ob;\nList<string> st = new List<string>();\nob = st.Cast<object>();\n List<string> st = new List<string>();\nList<object> ob = st.Cast<object>().ToList();\n" }, { "answer_id": 43654389, "author": "Kozen", "author_id": 7146016, "author_profile": "https://Stackoverflow.com/users/7146016", "pm_score": 0, "selected": false, "text": "List<string> sl = new List<string>();\nList<object> ol;\nol = new List<object>(sl);\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
6,578
<p>I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's <code>malloc</code> and <code>free</code> concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.</p> <p>How do <code>release</code>, <code>retain</code> and <code>autorelease</code> work and what are the conventions about their use?</p> <p>(Or failing that, what did you read which helped you get it?)</p>
[ { "answer_id": 6592, "author": "Ecton", "author_id": 457, "author_profile": "https://Stackoverflow.com/users/457", "pm_score": 3, "selected": false, "text": "id myVar = [someObject someMessage];\n.... do something ....;\n[myVar release];\nreturn someValue;\n id myVar = [[someObject someMessage] autorelease];\n... do something ...;\nreturn someValue;\n" }, { "answer_id": 6610, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 2, "selected": false, "text": "alloc/init [foo release] [foo autorelease] foo = [NSString stringWithString:@\"hello\"];\n autoreleased stringWithString [foo release]" }, { "answer_id": 6614, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 8, "selected": true, "text": "retain release autorelease NSObject retain release release malloc free retain release retain release NSString* s = [[NSString alloc] init]; // Ref count is 1\n[s retain]; // Ref count is 2 - silly\n // to do this after init\n[s release]; // Ref count is back to 1\n[s release]; // Ref count is 0, object is freed\n autorelease autorelease NSAutoreleasePool NSAutoreleasePool release release NSString* s = [NSString stringWithString:@\"Hello World\"];\n retain release autorelease - (NSString*)createHelloWorldString\n{\n NSString* s = [[NSString alloc] initWithString:@\"Hello World\"];\n\n // Now what? We want to return s, but we've upped its reference count.\n // The caller shouldn't be responsible for releasing it, since we're the\n // ones that created it. If we call release, however, the reference \n // count will hit zero and bad memory will be returned to the caller. \n // The answer is to call autorelease before returning the string. By \n // explicitly calling autorelease, we pass the responsibility for\n // releasing the string on to the thread's NSAutoreleasePool, which will\n // happen at some later time. The consequence is that the returned string \n // will still be valid for the caller of this function.\n return [s autorelease];\n}\n" }, { "answer_id": 6933, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 3, "selected": false, "text": "+alloc/+allocWithZone: +new -copy -mutableCopy -retain -release -release -release -autorelease -release -autorelease -autorelease" }, { "answer_id": 8078, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": 3, "selected": false, "text": "alloc create copy [object release] CFRelease(object) [object retain]" }, { "answer_id": 267594, "author": "Olie", "author_id": 34820, "author_profile": "https://Stackoverflow.com/users/34820", "pm_score": 2, "selected": false, "text": "NSString *foo = @\"bar\"; -(void)getBar {\n return @\"bar\";\n}\n NSString *foo = [self getBar]; // still no need to retain or release\n retainCount > 0 alloc new fooCopy" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
6,594
<p>What are some good steps to follow for a smooth migration from PHP4 to PHP5. What are some types of code that are likely to break?</p>
[ { "answer_id": 6625, "author": "Akira", "author_id": 795, "author_profile": "https://Stackoverflow.com/users/795", "pm_score": 2, "selected": false, "text": "error_reporting( E_ALL );\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
6,607
<p>I'm a new Windows programmer and I'm not sure where I should store user configurable application settings. I understand the need to provide a user friendly means for the user to change application settings, like an Edit | Settings form or similar. But where should I store the values after the user hits the Apply button on that form? </p> <p>What are the pros and cons of storing settings in the Windows registry vs. storing them in a local INI file or config file or similar?</p>
[ { "answer_id": 6622, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "GetPrivateProfileString WritePrivateProfileString" }, { "answer_id": 6757, "author": "deadtime", "author_id": 614, "author_profile": "https://Stackoverflow.com/users/614", "pm_score": 2, "selected": false, "text": "static void Parse()\n{\n StreamReader tr = new StreamReader(\"config.ini\");\n string line;\n Dictionary<string, string> config = new Dictionary<string, string>();\n\n while ((line = tr.ReadLine()) != null)\n {\n // Allow for comments and empty lines.\n if (line == \"\" || line.StartsWith(\"#\"))\n continue;\n\n string[] kvPair = line.Split('=');\n\n // Format must be option = value.\n if (kvPair.Length != 2)\n continue;\n\n // If the option already exists, it's overwritten.\n config[kvPair[0].Trim()] = kvPair[1].Trim();\n }\n}\n" }, { "answer_id": 56773065, "author": "Zac", "author_id": 971443, "author_profile": "https://Stackoverflow.com/users/971443", "pm_score": 0, "selected": false, "text": "\\Wow6432Node\\" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27687/" ]
6,612
<p>On a recent Java project, we needed a free Java based real-time data plotting utility. After much searching, we found this tool called the <a href="http://www.epic.noaa.gov/java/sgt/" rel="noreferrer">Scientific Graphics Toolkit or SGT</a> from NOAA. It seemed pretty robust, but we found out that it wasn't terribly configurable. Or at least not configurable enough to meet our needs. We ended up digging very deeply into the Java code and reverse engineering the code and changing it all around to make the plot tool look and act the way we wanted it to look and act. Of course, this killed any chance for future upgrades from NOAA. </p> <p>So what free or cheap Java based data plotting tools or libraries do you use?</p> <p><em>Followup: Thanks for the <a href="http://www.jfree.org/jfreechart/" rel="noreferrer">JFreeChart</a> suggestions. I checked out their website and it looks like a very nice data charting and plotting utility. I should have made it clear in my original question that I was looking specifically to plot real-time data. I corrected my question above to make that point clear. It appears that <a href="http://www.jfree.org/jfreechart/faq.html#FAQ5" rel="noreferrer">JFreeChart support for live data is marginal at best, though</a>. Any other suggestions out there?</em></p>
[ { "answer_id": 11265300, "author": "Bob Weigel", "author_id": 1491619, "author_profile": "https://Stackoverflow.com/users/1491619", "pm_score": 1, "selected": false, "text": "&filePollUpdates=1&tail=100" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27687/" ]
6,623
<p>After changing the output directory of a visual studio project it started to fail to build with an error very much like: </p> <pre><code>C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign- Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E) C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1. </code></pre> <p>I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this?</p>
[ { "answer_id": 27317, "author": "sphereinabox", "author_id": 2775, "author_profile": "https://Stackoverflow.com/users/2775", "pm_score": 4, "selected": true, "text": "<Target Name=\"GenerateSerializationAssembliesForAllTypes\"\n DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\"\n Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\"\n Outputs=\"$(OutputPath)$(_SGenDllName)\">\n <SGen BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(OutputPath)\" References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"true\" UseProxyTypes=\"true\"\n KeyContainer=\"$(KeyContainerName)\" KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\" ToolPath=\"$(SGenToolPath)\">\n <Output TaskParameter=\"SerializationAssembly\"\n ItemName=\"SerializationAssembly\" />\n </SGen>\n</Target>\n<!-- <Target Name=\"BeforeBuild\">\n</Target> -->\n<Target Name=\"AfterBuild\"\n DependsOnTargets=\"GenerateSerializationAssembliesForAllTypes\">\n</Target>\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
6,628
<p>What is the difference, if any, between these methods of indexing into a PHP array:</p> <pre><code>$array[$index] $array[&quot;$index&quot;] $array[&quot;{$index}&quot;] </code></pre> <p>I'm interested in both the performance and functional differences.</p> <h3>Update:</h3> <p>(In response to @Jeremy) I'm not sure that's right. I ran this code:</p> <pre><code> $array = array(100, 200, 300); print_r($array); $idx = 0; $array[$idx] = 123; print_r($array); $array[&quot;$idx&quot;] = 456; print_r($array); $array[&quot;{$idx}&quot;] = 789; print_r($array); </code></pre> <p>And got this output:</p> <pre><code>Array ( [0] =&gt; 100 [1] =&gt; 200 [2] =&gt; 300 ) Array ( [0] =&gt; 123 [1] =&gt; 200 [2] =&gt; 300 ) Array ( [0] =&gt; 456 [1] =&gt; 200 [2] =&gt; 300 ) Array ( [0] =&gt; 789 [1] =&gt; 200 [2] =&gt; 300 ) </code></pre>
[ { "answer_id": 6637, "author": "ejunker", "author_id": 796, "author_profile": "https://Stackoverflow.com/users/796", "pm_score": -1, "selected": false, "text": "$str = \"this is my string {$array[\"$index\"]}\";\n" }, { "answer_id": 6646, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "$array = array('1' => 100, '2' => 200, 1 => 300, 2 => 400);\nprint_r($array);\n Array([1] => 300 [2] => 400)\n" }, { "answer_id": 6650, "author": "svec", "author_id": 103, "author_profile": "https://Stackoverflow.com/users/103", "pm_score": 5, "selected": false, "text": "for ($ii = 0; $ii < 1000000; $ii++) {\n // TEST 1\n $array[$idx] = $ii;\n // TEST 2\n $array[\"$idx\"] = $ii;\n // TEST 3\n $array[\"{$idx}\"] = $ii;\n}\n $idx=0 $idx=\"0\" $idx=\"blah\" microtime() $idx = 0 $array[$idx] // time: 0.45435905456543 seconds\n$array[\"$idx\"] // time: 1.0537171363831 seconds\n$array[\"{$idx}\"] // time: 1.0621709823608 seconds\nratio \"$idx\" / $idx // 2.3191287282497\nratio \"{$idx}\" / $idx // 2.3377348193858\n $idx = \"0\" $array[$idx] // time: 0.5107250213623 seconds\n$array[\"$idx\"] // time: 0.77445602416992 seconds\n$array[\"{$idx}\"] // time: 0.77329802513123 seconds\nratio \"$idx\" / $idx // = 1.5163855142717\nratio \"{$idx}\" / $idx // = 1.5141181512285\n $idx = \"blah\" $array[$idx] // time: 0.48077392578125 seconds\n$array[\"$idx\"] // time: 0.73676419258118 seconds\n$array[\"{$idx}\"] // time: 0.71499705314636 seconds\nratio \"$idx\" / $idx // = 1.5324545551923\nratio \"{$idx}\" / $idx // = 1.4871793473086\n $array[$idx]" }, { "answer_id": 6657, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "$index $array[$index] $array[3] $array[\"$index\"] $array['3.14'] $array = array(3.14 => 'float', '3.14' => 'string');\nprint_r($array);\n\n$index = 3.14;\necho $array[$index].\"\\n\";\necho $array[\"$index\"].\"\\n\";\n Array([3] => float [3.14] => string)\nfloat\nstring\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103/" ]
6,633
<p>I have inherited some legacy PHP code what was written back when it was standard practice to use <a href="http://php.net/register_globals" rel="nofollow noreferrer"><code>register_globals</code></a> (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002).</p> <p>We know now that it is bad for security to have it enabled. The problem is how do I find all the places in the code where I need to use <code>$_GET</code> or <code>$_POST</code>? My only thought was to set the error reporting to warn about uninitialized variables and then test each part of the site. Is there an easier way? Will I have to test each code path in the site or will PHP give a warning on a file basis?</p>
[ { "answer_id": 13758, "author": "Eric Goodwin", "author_id": 1430, "author_profile": "https://Stackoverflow.com/users/1430", "pm_score": 2, "selected": false, "text": "// Detect bad global variables\n$bad_global_list = array('GLOBALS', '_SESSION', 'HTTP_SESSION_VARS', '_GET', 'HTTP_GET_VARS', '_POST', 'HTTP_POST_VARS', '_COOKIE', 'HTTP_COOKIE_VARS', '_REQUEST', '_SERVER', 'HTTP_SERVER_VARS', '_ENV', 'HTTP_ENV_VARS', '_FILES', 'HTTP_POST_FILES');\nforeach ($bad_global_list as $bad_global ) {\n if ( isset( $_REQUEST[$bad_global] ) ) {\n die('Bad Global');\n }\n}\n\n// Make global variables\nforeach ($_REQUEST as $name -> $value) {\n $$name = $value; // Creates a varable nammed $name equal to $value.\n}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
6,639
<p>How should I load files into my Java application?</p>
[ { "answer_id": 6640, "author": "Will", "author_id": 816, "author_profile": "https://Stackoverflow.com/users/816", "pm_score": 6, "selected": false, "text": "Class.getResource(String) Class.getResourceAsStream(String) InputStream inputStream = YourClass.class.getResourceAsStream(\"image.jpg\");\n File file = new File(\"C:\\\\Users\\\\Joe\\\\image.jpg\");\n getResource() Class" }, { "answer_id": 30854, "author": "Vinnie", "author_id": 2890, "author_profile": "https://Stackoverflow.com/users/2890", "pm_score": 3, "selected": false, "text": "BufferedReader file = new BufferedReader(new FileReader(filename)) file.readLine();" }, { "answer_id": 5058626, "author": "cibercitizen1", "author_id": 286335, "author_profile": "https://Stackoverflow.com/users/286335", "pm_score": 2, "selected": false, "text": "public byte[] loadBinaryFile (String name) {\n try {\n\n DataInputStream dis = new DataInputStream(new FileInputStream(name));\n byte[] theBytes = new byte[dis.available()];\n dis.read(theBytes, 0, dis.available());\n dis.close();\n return theBytes;\n } catch (IOException ex) {\n }\n return null;\n} // ()\n" }, { "answer_id": 59455279, "author": "Fridjato Part Fridjat", "author_id": 12087120, "author_profile": "https://Stackoverflow.com/users/12087120", "pm_score": 0, "selected": false, "text": "public static String loadTextFile(File f) {\n try {\n BufferedReader r = new BufferedReader(new FileReader(f));\n StringWriter w = new StringWriter();\n\n try {\n String line = reader.readLine();\n while (null != line) {\n w.append(line).append(\"\\n\");\n line = r.readLine();\n }\n\n return w.toString();\n } finally {\n r.close();\n w.close();\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n\n return \"\";\n }\n}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/816/" ]
6,642
<p>I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a <code>favicon.ico</code> file in the root of the website.</p> <p>I found this nice little guide: <a href="http://www.w3.org/2005/10/howto-favicon" rel="noreferrer">How to Add a Favicon</a>. However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use).</p> <p>Is there a third method that works across all the most popular browsers?</p>
[ { "answer_id": 6643, "author": "Brandon Wood", "author_id": 423, "author_profile": "https://Stackoverflow.com/users/423", "pm_score": 0, "selected": false, "text": "<link rel=\"shortcut icon\" href=\"/favicon.ico\" />\n" }, { "answer_id": 6644, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": 0, "selected": false, "text": ".png" }, { "answer_id": 6645, "author": "Stan", "author_id": 464, "author_profile": "https://Stackoverflow.com/users/464", "pm_score": 5, "selected": true, "text": "<link rel=\"icon\" href=\"favicon.ico\" type=\"image/x-icon\" /> \n<link rel=\"shortcut icon\" href=\"favicon.ico\" type=\"image/x-icon\" /> \n" }, { "answer_id": 6949, "author": "Akira", "author_id": 795, "author_profile": "https://Stackoverflow.com/users/795", "pm_score": 2, "selected": false, "text": "AddType image/x-icon .ico\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/810/" ]
6,658
<p>At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for <strong>new</strong> tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbers of tests? Having flexibility in writing tests is also important to us since our functional tests cover a wide aspect and need to be written in a variety of ways to get results.</p> <p>Old tests will not be re-written as they do their job just fine. What I would like to see in new tests though is flexibility in the way the test can be written, natural assertions, grouping, and easily distributed test executions.</p>
[ { "answer_id": 430893, "author": "Denis Bazhenov", "author_id": 53658, "author_profile": "https://Stackoverflow.com/users/53658", "pm_score": 3, "selected": false, "text": "assertEquals(operation.getStatus(), Operation.Status.Active);\n assertThat(operation, isActive());\n" }, { "answer_id": 3522444, "author": "mezmo", "author_id": 310092, "author_profile": "https://Stackoverflow.com/users/310092", "pm_score": 4, "selected": false, "text": "@BeforeClass HtmlUnit" }, { "answer_id": 22897063, "author": "djangofan", "author_id": 118228, "author_profile": "https://Stackoverflow.com/users/118228", "pm_score": 2, "selected": false, "text": "1. JUnit still requires the before/after class methods to be static, which limits\n what you can do prior to the running of tests, TestNG never has this issue.\n\n2. TestNG @Configuration methods can all take an optional argument to their \n annotated methods in the form of a ITestResult, XmlTest, Method, or \n ITestContext. This allows you to pass things around that JUnit wouldn't \n provide you. JUnit only does this in listeners and it is limited in use.\n\n3. TestNG comes with some pre-made report generation classes that you can copy\n and edit and make into your own beautiful test output with very little \n effort. Just copy the report class into your project and add a listener \n to run it. Also, ReportNG is available.\n\n4. TestNG has a handful of nice listeners that you can hook onto so you can do\n additional AOP style magic at certain phases during testing.\n" }, { "answer_id": 47765625, "author": "SkyWalker", "author_id": 2293534, "author_profile": "https://Stackoverflow.com/users/2293534", "pm_score": 3, "selected": false, "text": "@BeforeClass @AfterClass" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/782/" ]
6,661
<p>I'm aware of things like <code>onchange</code>, <code>onmousedown</code> and <code>onmouseup</code> but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover?</p>
[ { "answer_id": 6686, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "$(\"#navigation a\").addEvent(\"click\", myFunc);\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
6,719
<p>I've just been learning about master pages in ASP.NET 2.0. </p> <p>They sound great, but how well do they work in practice? </p> <p>Does anybody have experience of using them for a large web site?</p>
[ { "answer_id": 6744, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": 3, "selected": false, "text": "<%@ Master ... %>\n\n<%-- HTML code --%>\n<asp:ContentPlaceHolder id=\"plhMainContent\" runat=\"server\" />\n<%-- HTML code --%>\n aspx <%@ Page ... master=\"~/MasterPage.master\" ... %>\n\n<asp:Content ID=\"ContentIdentifier\" ContentPlaceholderid=\"plhMainContent\" runat=\"server\">\n <%-- More HTML here --%>\n <%-- Insert web controls here --%>\n</asp:content>\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133/" ]
6,765
<p>I'm going to start a new project - rewriting an existing system (PHP + SQL Server) from scratch because of some very serious limitations by design.</p> <p>We have some quite good knowledge of SQL Server (currently we're using SQL Server 2000 in existing system) and we would like to employ its newer version (2008 I guess) in our new project.</p> <p>I am really fond of technologies that Java offers - particularly Spring Framework and Wicket and I am quite familiar with Java from others projects and assignments before. Therefore, we consider using Java and Microsoft SQL Server.</p> <p>There are two JDBC drivers for SQL Server - jTDS and Microsoft's one - <a href="http://msdn.microsoft.com/en-us/data/aa937724.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/data/aa937724.aspx</a>. I think we should test both of them.<br/></p> <p>Are there any limitations in such solution I should know of? Has someone experience with such a technology combination?</p>
[ { "answer_id": 38664293, "author": "Jay", "author_id": 5641640, "author_profile": "https://Stackoverflow.com/users/5641640", "pm_score": 0, "selected": false, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n public class connectToSQL {\n\n public void connectToDB() throws Exception {\n Class.forName(\"com.microsoft.sqlserver.jdbc.SQLServerDriver\");\n String connectionUrl = \"jdbc:sqlserver://<IPADDRESS>:<PORT>;DatabaseName=<NAME OF DATABASE TO CONNECT TO>;IntegratedSecurity=false\"; \n Connection con = DriverManager.getConnection(connectionUrl, \"<SQL SERVER USER LOGIN>\", \"<SQL SERVER PASSWORD>\");\n Statement s = con.createStatement();\n ResultSet r = s.executeQuery(\"SELECT * FROM <TABLENAME TO SELECT FROM>\");\n while (r.next()) {\n System.out.println(r.getString(1));\n }\n }\n}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/837/" ]
6,778
<p>This page from Adobe says to add a "wmode" parameter and set its value to "transparent": <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14201" rel="nofollow noreferrer">http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_1420</a></p> <p>This works flawlessly in IE. The background renders correctly in Firefox and Safari, however as soon as you use the browser's scroll bar then mouse over the Flash control you must click once to activate the control. You can see this behavior if you try to hit the play button in Adobe's example.</p> <p>Anyone know a way around this?</p>
[ { "answer_id": 16830, "author": "Shawn Miller", "author_id": 247, "author_profile": "https://Stackoverflow.com/users/247", "pm_score": 0, "selected": false, "text": "var parameters:Object = LoaderInfo(this.root.loaderInfo).parameters;\nopaqueBackground = parameters[\"background-color\"];\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247/" ]
6,785
<p>Suppose I have a stringbuilder in C# that does this:</p> <pre><code>StringBuilder sb = new StringBuilder(); string cat = "cat"; sb.Append("the ").Append(cat).(" in the hat"); string s = sb.ToString(); </code></pre> <p>would that be as efficient or any more efficient as having:</p> <pre><code>string cat = "cat"; string s = String.Format("The {0} in the hat", cat); </code></pre> <p>If so, why?</p> <p><strong>EDIT</strong> </p> <p>After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at <strong><em>injecting</em></strong> one string into another.</p> <p>In both cases above I want to inject one or more strings into the middle of a predefined template string.</p> <p>Sorry for the confusion</p>
[ { "answer_id": 6786, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "String s = String.Format(\"Today is {0:dd-MMM-yyyy}.\", DateTime.Today);\n" }, { "answer_id": 6788, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 0, "selected": false, "text": "String s = \"String A\" + \"String B\";\n" }, { "answer_id": 6824, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 8, "selected": true, "text": "String.Format StringBuilder public static string Format(IFormatProvider provider, string format, params object[] args)\n{\n if ((format == null) || (args == null))\n {\n throw new ArgumentNullException((format == null) ? \"format\" : \"args\");\n }\n\n StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));\n builder.AppendFormat(provider, format, args);\n return builder.ToString();\n}\n StringBuilder.Append() StringBuilder.AppendFormat() .Append()" }, { "answer_id": 6888, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 2, "selected": false, "text": "string cat = \"cat\";\nstring s = \"The \" + cat + \" in the hat\";\n" }, { "answer_id": 902533, "author": "jrista", "author_id": 111554, "author_profile": "https://Stackoverflow.com/users/111554", "pm_score": 3, "selected": false, "text": "String.Format StringBuilder StringBuilder String.Format String.Concat FillStringChecked public static string Concat(params string[] values)\n{\n int totalLength = 0;\n\n if (values == null)\n {\n throw new ArgumentNullException(\"values\");\n }\n\n string[] strArray = new string[values.Length];\n\n for (int i = 0; i < values.Length; i++)\n {\n string str = values[i];\n strArray[i] = (str == null) ? Empty : str;\n totalLength += strArray[i].Length;\n\n if (totalLength < 0)\n {\n throw new OutOfMemoryException();\n }\n }\n\n return ConcatArray(strArray, totalLength);\n}\n\npublic static string Concat(string str0, string str1, string str2, string str3)\n{\n if (((str0 == null) && (str1 == null)) && ((str2 == null) && (str3 == null)))\n {\n return Empty;\n }\n\n if (str0 == null)\n {\n str0 = Empty;\n }\n\n if (str1 == null)\n {\n str1 = Empty;\n }\n\n if (str2 == null)\n {\n str2 = Empty;\n }\n\n if (str3 == null)\n {\n str3 = Empty;\n }\n\n int length = ((str0.Length + str1.Length) + str2.Length) + str3.Length;\n string dest = FastAllocateString(length);\n FillStringChecked(dest, 0, str0);\n FillStringChecked(dest, str0.Length, str1);\n FillStringChecked(dest, str0.Length + str1.Length, str2);\n FillStringChecked(dest, (str0.Length + str1.Length) + str2.Length, str3);\n return dest;\n}\n\nprivate static string ConcatArray(string[] values, int totalLength)\n{\n string dest = FastAllocateString(totalLength);\n int destPos = 0;\n\n for (int i = 0; i < values.Length; i++)\n {\n FillStringChecked(dest, destPos, values[i]);\n destPos += values[i].Length;\n }\n\n return dest;\n}\n\nprivate static unsafe void FillStringChecked(string dest, int destPos, string src)\n{\n int length = src.Length;\n\n if (length > (dest.Length - destPos))\n {\n throw new IndexOutOfRangeException();\n }\n\n fixed (char* chRef = &dest.m_firstChar)\n {\n fixed (char* chRef2 = &src.m_firstChar)\n {\n wstrcpy(chRef + destPos, chRef2, length);\n }\n }\n}\n string what = \"cat\";\nstring inthehat = \"The \" + what + \" in the hat!\";\n" }, { "answer_id": 3383247, "author": "Liran", "author_id": 2164233, "author_profile": "https://Stackoverflow.com/users/2164233", "pm_score": 0, "selected": false, "text": "string.Join string,Concat string.Format" }, { "answer_id": 27902469, "author": "Chris F Carroll", "author_id": 550314, "author_profile": "https://Stackoverflow.com/users/550314", "pm_score": 3, "selected": false, "text": "a + b + c const int iterations=1000000;\nvar keyprefix= this.GetType().FullName;\nvar maxkeylength=keyprefix + 1 + 1+ Math.Log10(iterations);\nConsole.WriteLine(\"KeyPrefix \\\"{0}\\\", Max Key Length {1}\",keyprefix, maxkeylength);\n\nvar concatkeys= new string[iterations];\nvar stringbuilderkeys= new string[iterations];\nvar cachedsbkeys= new string[iterations];\nvar formatkeys= new string[iterations];\n\nvar stopwatch= new System.Diagnostics.Stopwatch();\nConsole.WriteLine(\"Concatenation:\");\nstopwatch.Start();\n\nfor(int i=0; i<iterations; i++){\n var key1= keyprefix+\":\" + i.ToString();\n concatkeys[i]=key1;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nConsole.WriteLine(\"New stringBuilder for each key:\");\nstopwatch.Restart();\n\nfor(int i=0; i<iterations; i++){\n var key2= new StringBuilder(keyprefix).Append(\":\").Append(i.ToString()).ToString();\n stringbuilderkeys[i]= key2;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nConsole.WriteLine(\"Cached StringBuilder:\");\nvar cachedSB= new StringBuilder(maxkeylength);\nstopwatch.Restart();\n\nfor(int i=0; i<iterations; i++){\n var key2b= cachedSB.Clear().Append(keyprefix).Append(\":\").Append(i.ToString()).ToString();\n cachedsbkeys[i]= key2b;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nConsole.WriteLine(\"string.Format\");\nstopwatch.Restart();\n\nfor(int i=0; i<iterations; i++){\n var key3= string.Format(\"{0}:{1}\", keyprefix,i.ToString());\n formatkeys[i]= key3;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nvar referToTheComputedValuesSoCompilerCantOptimiseTheLoopsAway= concatkeys.Union(stringbuilderkeys).Union(cachedsbkeys).Union(formatkeys).LastOrDefault(x=>x[1]=='-');\nConsole.WriteLine(referToTheComputedValuesSoCompilerCantOptimiseTheLoopsAway);\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
6,811
<p>Before reading anything else, please take time to read the <a href="https://stackoverflow.com/questions/1615/how-can-i-modify-xfdl-files-update-1">original thread</a>.</p> <p>Overview: a .xfdl file is a gzipped .xml file which has then been encoded in base64. I wish to de-encode the .xfdl into xml which I can then modify and then re-encode back into a .xfdl file.</p> <blockquote> <p>xfdl > xml.gz > xml > xml.gz > xfdl</p> </blockquote> <p>I have been able to take a .xfdl file and de-encode it from base64 using uudeview:</p> <pre><code>uudeview -i yourform.xfdl </code></pre> <p>Then decommpressed it using gunzip</p> <pre><code>gunzip -S "" &lt; UNKNOWN.001 &gt; yourform-unpacked.xml </code></pre> <p>The xml produced is 100% readable and looks wonderful. Without modifying the xml then, i should be able to re-compress it using gzip:</p> <pre><code>gzip yourform-unpacked.xml </code></pre> <p>Then re-encoded in base-64:</p> <pre><code>base64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl </code></pre> <p>If my thinking is correct, the original file and the re-encoded file should be equal. If I put yourform.xfdl and yourform_reencoded.xfdl into beyond compare, however, they do not match up. Also, the original file can be viewed in an http://www.grants.gov/help/download_software.jsp#pureedge">.xfdl viewer. The viewer says that the re-encoded xfdl is unreadable. </p> <p>I have also tried uuenview to re-encode in base64, it also produces the same results. Any help would be appreciated.</p>
[ { "answer_id": 6852, "author": "CodingWithoutComments", "author_id": 25, "author_profile": "https://Stackoverflow.com/users/25", "pm_score": 0, "selected": false, "text": "H4sIAAAAAAAAC+19eZOiyNb3/34K3r4RT/WEU40ssvTtrhuIuKK44Bo3YoJdFAFZ3D79C6hVVhUq\ndsnUVN/qmIkSOLlwlt/JPCfJ/PGf9dwAlorj6pb58wv0LfcFUEzJknVT+/ml2uXuCSJP3kNf/vOQ\n+TEsFVkgoDfdn18mnmd/B8HVavWt5TsKI2vKN8magyENiH3Lf9kRfpd817PmF+jpiOhQRFZcXTMV\n H4sICJ/YnEgAAzEyNDQ2LTExNjk2NzUueGZkbC54bWwA7D1pU+JK19/9FV2+H5wpByEhJMRH\nuRUgCMom4DBYt2oqkAZyDQlmQZ1f/3YSNqGzKT3oDH6RdE4vOXuf08vFP88TFcygYSq6dnlM\nnaWOAdQGuqxoo8vjSruRyGYzfII6/id3dPGjVKwCBK+Zl8djy5qeJ5NPT09nTduAojyCZwN9\n H4SI" }, { "answer_id": 1414463, "author": "Paradigm", "author_id": 172404, "author_profile": "https://Stackoverflow.com/users/172404", "pm_score": 1, "selected": false, "text": "application/vnd.xfdl; content-encoding=\"base64-gzip\"" }, { "answer_id": 5021875, "author": "CrazyPyro", "author_id": 268066, "author_profile": "https://Stackoverflow.com/users/268066", "pm_score": 1, "selected": false, "text": "with open(filename, 'r') as f:\n header = f.readline()\n if header == 'application/vnd.xfdl; content-encoding=\"base64-gzip\"\\n':\n decoded = b''\n for line in f:\n decoded += base64.b64decode(line.encode(\"ISO-8859-1\"))\n xml = zlib.decompress(decoded, zlib.MAX_WBITS + 16)\n" }, { "answer_id": 5465913, "author": "MrWizard54", "author_id": 193827, "author_profile": "https://Stackoverflow.com/users/193827", "pm_score": 1, "selected": false, "text": "public XFDLDocument(String inputFile) \n throws IOException, \n ParserConfigurationException,\n SAXException\n\n{\n fileLocation = inputFile;\n\n try{\n\n //create file object\n File f = new File(inputFile);\n if(!f.exists()) {\n throw new IOException(\"Specified File could not be found!\");\n }\n\n //open file stream from file\n FileInputStream fis = new FileInputStream(inputFile);\n\n //Skip past the MIME header\n fis.skip(FILE_HEADER_BLOCK.length()); \n\n //Decompress from base 64 \n Base64.InputStream bis = new Base64.InputStream(fis, \n Base64.DECODE);\n\n //UnZIP the resulting stream\n GZIPInputStream gis = new GZIPInputStream(bis);\n\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n doc = db.parse(gis);\n\n gis.close();\n bis.close();\n fis.close();\n\n }\n catch (ParserConfigurationException pce) {\n throw new ParserConfigurationException(\"Error parsing XFDL from file.\");\n }\n catch (SAXException saxe) {\n throw new SAXException(\"Error parsing XFDL into XML Document.\");\n }\n}\n /**\n * Saves the current document to the specified location\n * @param destination Desired destination for the file.\n * @param asXML True if output needs should be as un-encoded XML not Base64/GZIP\n * @throws IOException File cannot be created at specified location\n * @throws TransformerConfigurationExample\n * @throws TransformerException \n */\n public void saveFile(String destination, boolean asXML) \n throws IOException, \n TransformerConfigurationException, \n TransformerException \n {\n\n BufferedWriter bf = new BufferedWriter(new FileWriter(destination));\n bf.write(FILE_HEADER_BLOCK);\n bf.newLine();\n bf.flush();\n bf.close();\n\n OutputStream outStream;\n if(!asXML) {\n outStream = new GZIPOutputStream(\n new Base64.OutputStream(\n new FileOutputStream(destination, true)));\n } else {\n outStream = new FileOutputStream(destination, true);\n }\n\n Transformer t = TransformerFactory.newInstance().newTransformer();\n t.transform(new DOMSource(doc), new StreamResult(outStream));\n\n outStream.flush();\n outStream.close(); \n }\n" }, { "answer_id": 8902867, "author": "Ross Bielski", "author_id": 958195, "author_profile": "https://Stackoverflow.com/users/958195", "pm_score": 1, "selected": false, "text": " <?php\n function gzdecode($data) {\n $len = strlen($data);\n if ($len < 18 || strcmp(substr($data,0,2),\"\\x1f\\x8b\")) {\n echo \"FILE NOT GZIP FORMAT\";\n return null; // Not GZIP format (See RFC 1952)\n }\n $method = ord(substr($data,2,1)); // Compression method\n $flags = ord(substr($data,3,1)); // Flags\n if ($flags & 31 != $flags) {\n // Reserved bits are set -- NOT ALLOWED by RFC 1952\n echo \"RESERVED BITS ARE SET. VERY BAD\";\n return null;\n }\n // NOTE: $mtime may be negative (PHP integer limitations)\n $mtime = unpack(\"V\", substr($data,4,4));\n $mtime = $mtime[1];\n $xfl = substr($data,8,1);\n $os = substr($data,8,1);\n $headerlen = 10;\n $extralen = 0;\n $extra = \"\";\n if ($flags & 4) {\n // 2-byte length prefixed EXTRA data in header\n if ($len - $headerlen - 2 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $extralen = unpack(\"v\",substr($data,8,2));\n $extralen = $extralen[1];\n if ($len - $headerlen - 2 - $extralen < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $extra = substr($data,10,$extralen);\n $headerlen += 2 + $extralen;\n }\n\n $filenamelen = 0;\n $filename = \"\";\n if ($flags & 8) {\n // C-style string file NAME data in header\n if ($len - $headerlen - 1 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $filenamelen = strpos(substr($data,8+$extralen),chr(0));\n if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $filename = substr($data,$headerlen,$filenamelen);\n $headerlen += $filenamelen + 1;\n }\n\n $commentlen = 0;\n $comment = \"\";\n if ($flags & 16) {\n // C-style string COMMENT data in header\n if ($len - $headerlen - 1 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));\n if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {\n return false; // Invalid header format\n echo \"INVALID FORMAT\";\n }\n $comment = substr($data,$headerlen,$commentlen);\n $headerlen += $commentlen + 1;\n }\n\n $headercrc = \"\";\n if ($flags & 1) {\n // 2-bytes (lowest order) of CRC32 on header present\n if ($len - $headerlen - 2 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;\n $headercrc = unpack(\"v\", substr($data,$headerlen,2));\n $headercrc = $headercrc[1];\n if ($headercrc != $calccrc) {\n echo \"BAD CRC\";\n return false; // Bad header CRC\n }\n $headerlen += 2;\n }\n\n // GZIP FOOTER - These be negative due to PHP's limitations\n $datacrc = unpack(\"V\",substr($data,-8,4));\n $datacrc = $datacrc[1];\n $isize = unpack(\"V\",substr($data,-4));\n $isize = $isize[1];\n\n // Perform the decompression:\n $bodylen = $len-$headerlen-8;\n if ($bodylen < 1) {\n // This should never happen - IMPLEMENTATION BUG!\n echo \"BIG OOPS\";\n return null;\n }\n $body = substr($data,$headerlen,$bodylen);\n $data = \"\";\n if ($bodylen > 0) {\n switch ($method) {\n case 8:\n // Currently the only supported compression method:\n $data = gzinflate($body);\n break;\n default:\n // Unknown compression method\n echo \"UNKNOWN COMPRESSION METHOD\";\n return false;\n }\n } else {\n // I'm not sure if zero-byte body content is allowed.\n // Allow it for now... Do nothing...\n echo \"ITS EMPTY\";\n }\n\n // Verifiy decompressed size and CRC32:\n // NOTE: This may fail with large data sizes depending on how\n // PHP's integer limitations affect strlen() since $isize\n // may be negative for large sizes.\n if ($isize != strlen($data) || crc32($data) != $datacrc) {\n // Bad format! Length or CRC doesn't match!\n echo \"LENGTH OR CRC DO NOT MATCH\";\n return false;\n }\n return $data;\n }\n echo \"<html><head></head><body>\";\n if (empty($_REQUEST['upload'])) {\n echo <<<_END\n <form enctype=\"multipart/form-data\" action=\"example.php\" method=\"POST\">\n <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"100000\" />\n <table>\n <th>\n <input name=\"uploadedfile\" type=\"file\" />\n </th>\n <tr>\n <td><input type=\"submit\" name=\"upload\" value=\"Convert File\" /></td>\n </tr>\n </table>\n </form>\n _END;\n\n }\n if (!empty($_REQUEST['upload'])) {\n $file = \"tmp/\" . $_FILES['uploadedfile']['name'];\n $orgfile = $_FILES['uploadedfile']['name'];\n $name = str_replace(\".xfdl\", \"\", $orgfile);\n $convertedfile = \"tmp/\" . $name . \".xml\";\n $compressedfile = \"tmp/\" . $name . \".gz\";\n $finalfile = \"tmp/\" . $name . \"new.xfdl\";\n $target_path = \"tmp/\";\n $target_path = $target_path . basename($_FILES['uploadedfile']['name']);\n if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {\n } else {\n echo \"There was an error uploading the file, please try again!\";\n }\n $firstline = \"application/vnd.xfdl; content-encoding=\\\"base64-gzip\\\"\\n\";\n $data = file($file);\n $data = array_slice($data, 1);\n $raw = implode($data);\n $decoded = base64_decode($raw);\n $decompressed = gzdecode($decoded);\n $compressed = gzencode($decompressed);\n $encoded = base64_encode($compressed);\n $decoded2 = base64_decode($encoded);\n $decompressed2 = gzdecode($decoded2);\n $header = bin2hex(substr($decoded, 0, 10));\n $tail = bin2hex(substr($decoded, -8));\n $header2 = bin2hex(substr($compressed, 0, 10));\n $tail2 = bin2hex(substr($compressed, -8));\n $header3 = bin2hex(substr($decoded2, 0, 10));\n $tail3 = bin2hex(substr($decoded2, -8));\n $filehandle = fopen($compressedfile, 'w');\n fwrite($filehandle, $decoded);\n fclose($filehandle);\n $filehandle = fopen($convertedfile, 'w');\n fwrite($filehandle, $decompressed);\n fclose($filehandle);\n $filehandle = fopen($finalfile, 'w');\n fwrite($filehandle, $firstline);\n fwrite($filehandle, $encoded);\n fclose($filehandle);\n echo \"<center>\";\n echo \"<table style='text-align:center' >\";\n echo \"<tr><th>Stage 1</th>\";\n echo \"<th>Stage 2</th>\";\n echo \"<th>Stage 3</th></tr>\";\n echo \"<tr><td>RAW DATA -></td><td>DECODED DATA -></td><td>UNCOMPRESSED DATA -></td></tr>\";\n echo \"<tr><td>LENGTH: \".strlen($raw).\"</td>\";\n echo \"<td>LENGTH: \".strlen($decoded).\"</td>\";\n echo \"<td>LENGTH: \".strlen($decompressed).\"</td></tr>\";\n echo \"<tr><td><a href='tmp/\".$orgfile.\"'/>ORIGINAL</a></td><td>GZIP HEADER:\".$header.\"</td><td><a href='\".$convertedfile.\"'/>XML CONVERTED</a></td></tr>\";\n echo \"<tr><td></td><td>GZIP TAIL:\".$tail.\"</td><td></td></tr>\";\n echo \"<tr><td><textarea cols='30' rows='20'>\" . $raw . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $decoded . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $decompressed . \"</textarea></td></tr>\";\n echo \"<tr><th>Stage 6</th>\";\n echo \"<th>Stage 5</th>\";\n echo \"<th>Stage 4</th></tr>\";\n echo \"<tr><td>ENCODED DATA <-</td><td>COMPRESSED DATA <-</td><td>UNCOMPRESSED DATA <-</td></tr>\";\n echo \"<tr><td>LENGTH: \".strlen($encoded).\"</td>\";\n echo \"<td>LENGTH: \".strlen($compressed).\"</td>\";\n echo \"<td>LENGTH: \".strlen($decompressed).\"</td></tr>\";\n echo \"<tr><td></td><td>GZIP HEADER:\".$header2.\"</td><td></td></tr>\";\n echo \"<tr><td></td><td>GZIP TAIL:\".$tail2.\"</td><td></td></tr>\";\n echo \"<tr><td><a href='\".$finalfile.\"'/>FINAL FILE</a></td><td><a href='\".$compressedfile.\"'/>RE-COMPRESSED FILE</a></td><td></td></tr>\";\n echo \"<tr><td><textarea cols='30' rows='20'>\" . $encoded . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $compressed . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $decompressed . \"</textarea></td></tr>\";\n echo \"</table>\";\n echo \"</center>\";\n }\n echo \"</body></html>\";\n ?>\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
6,816
<p>I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project.</p> <p>When using the java search on one particular project, I get an error message saying <code>Class file name must end with .class</code> (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt?</p> <p>I have already tried <code>Project -&gt; Clean</code>... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail.</p> <p>The only reference I've been able to find on Google for the problem is at <a href="http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx" rel="noreferrer">http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx</a>, but unfortunately his solution (closing, deleting class files, restarting) did not work for me.</p> <p>If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers.</p> <pre><code>Version: 3.4.0 Build id: I20080617-2000 </code></pre> <p>Also just found this thread - <a href="http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html" rel="noreferrer">http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html</a> - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck.</p> <pre><code>Caused by: java.lang.IllegalArgumentException: Class file name must end with .class at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182) at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177) at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522) at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45) at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225) at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) </code></pre> <p>Thanks McDowell, closing and opening the project seems to have fixed it (at least for now).</p>
[ { "answer_id": 1220707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<workspace>/.metadata/.plugins/org.eclipse.jdt.core/*.index <workspace>/.metadata/.plugins/org.eclipse.jdt.core/savedIndexNames.txt" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
6,847
<p>When writing code do you consciously program defensively to ensure high program quality and to avoid the possibility of your code being exploited maliciously, e.g. through buffer overflow exploits or code injection ?</p> <p>What's the "minimum" level of quality you'll always apply to your code ?</p>
[ { "answer_id": 10150, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": 1, "selected": false, "text": "inline const Vector3 Normalize( Vector3arg vec )\n{\n const float len = Length(vec);\n ASSERTMSG(len > 0.0f \"Invalid Normalization\");\n return len == 0.0f ? vec : vec / len;\n}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
6,890
<p>I have some code for starting a thread on the .NET CF 2.0:</p> <pre><code>ThreadStart tStart = new ThreadStart(MyMethod); Thread t = new Thread(tStart); t.Start(); </code></pre> <p>If I call this inside a loop the items completely out of order. How do introduce a wait after <code>t.Start()</code>, so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?</p>
[ { "answer_id": 6935, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "t.Join();\n" }, { "answer_id": 7101, "author": "Dominic Cooney", "author_id": 878, "author_profile": "https://Stackoverflow.com/users/878", "pm_score": 5, "selected": true, "text": "// Start all of the threads.\nList<Thread> startedThreads = new List<Thread>();\nforeach (...) {\n Thread thread = new Thread(new ThreadStart(MyMethod));\n thread.Start();\n startedThreads.Add(thread);\n}\n\n// Wait for all of the threads to finish.\nforeach (Thread thread in startedThreads) {\n thread.Join();\n}\n" }, { "answer_id": 17858, "author": "ollifant", "author_id": 2078, "author_profile": "https://Stackoverflow.com/users/2078", "pm_score": 3, "selected": false, "text": "AutoResetEvent private readonly AutoResetEvent mWaitForThread = new AutoResetEvent(false);\n\nprivate void Blah()\n{\n ThreadStart tStart = new ThreadStart(MyMethod);\n Thread t = new Thread(tStart);\n t.Start();\n\n //... (any other things)\n mWaitForThread.WaitOne();\n}\n\nprivate void MyMethod()\n{\n //... (execute any other action)\n mWaitForThread.Set();\n}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
6,891
<p>I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:</p> <pre><code>try { ... // some code } catch (Exception ex) { ... // Do something throw new CustomException(ex); } </code></pre> <p>Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again.</p> <p>How does this differ in Performance from the following two:</p> <pre><code>try { ... // some code } catch (Exception ex) { .. // Do something throw ex; } </code></pre> <p>or </p> <pre><code>try { ... // some code } catch (Exception ex) { .. // Do something throw; } </code></pre> <p>Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches?</p>
[ { "answer_id": 6912, "author": "ggasp", "author_id": 527, "author_profile": "https://Stackoverflow.com/users/527", "pm_score": 2, "selected": false, "text": "try {\n // something that will raise an exception almost half the time\n} catch( InsufficientFunds e) {\n // Inform the customer is broke\n} catch( UnknownAccount e ) {\n // Ask for a new account number\n}\n" }, { "answer_id": 6978, "author": "Nidonocu", "author_id": 483, "author_profile": "https://Stackoverflow.com/users/483", "pm_score": 1, "selected": false, "text": "public bool Load(string filepath)\n{\n if (File.Exists(filepath)) //Avoid throwing by checking state\n {\n //Wrap anyways in case something changes between check and operation\n try { .... }\n catch (IOException ioFault) { .... }\n catch (OtherException otherFault) { .... }\n return true; //Inform caller of success\n }\n else { return false; } //Inform caller of failure due to state\n}\n" }, { "answer_id": 13145, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "try\n{\n // some code\n}\ncatch (Exception ex) { throw ex; }\n try\n{\n // some code\n}\ncatch (Exception ex) { throw; }\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ]
6,899
<p>To illustrate, assume that I have two tables as follows:</p> <pre><code>VehicleID Name 1 Chuck 2 Larry LocationID VehicleID City 1 1 New York 2 1 Seattle 3 1 Vancouver 4 2 Los Angeles 5 2 Houston </code></pre> <p>I want to write a query to return the following results:</p> <pre><code>VehicleID Name Locations 1 Chuck New York, Seattle, Vancouver 2 Larry Los Angeles, Houston </code></pre> <p>I know that this can be done using server side cursors, ie:</p> <pre><code>DECLARE @VehicleID int DECLARE @VehicleName varchar(100) DECLARE @LocationCity varchar(100) DECLARE @Locations varchar(4000) DECLARE @Results TABLE ( VehicleID int Name varchar(100) Locations varchar(4000) ) DECLARE VehiclesCursor CURSOR FOR SELECT [VehicleID] , [Name] FROM [Vehicles] OPEN VehiclesCursor FETCH NEXT FROM VehiclesCursor INTO @VehicleID , @VehicleName WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = '' DECLARE LocationsCursor CURSOR FOR SELECT [City] FROM [Locations] WHERE [VehicleID] = @VehicleID OPEN LocationsCursor FETCH NEXT FROM LocationsCursor INTO @LocationCity WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = @Locations + @LocationCity FETCH NEXT FROM LocationsCursor INTO @LocationCity END CLOSE LocationsCursor DEALLOCATE LocationsCursor INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations END CLOSE VehiclesCursor DEALLOCATE VehiclesCursor SELECT * FROM @Results </code></pre> <p>However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this:</p> <pre><code>SELECT VehicleID , Name , JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations FROM Vehicles </code></pre> <p>Is this possible? Or something similar?</p>
[ { "answer_id": 6961, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": false, "text": "declare @s varchar(max)\nset @s = ''\nselect @s = @s + City + ',' from Locations\n\nselect @s\n" }, { "answer_id": 6980, "author": "Mun", "author_id": 775, "author_profile": "https://Stackoverflow.com/users/775", "pm_score": 9, "selected": true, "text": "SELECT [VehicleID]\n , [Name]\n , (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX)) \n FROM [Location] \n WHERE (VehicleID = Vehicle.VehicleID) \n FOR XML PATH ('')), 1, 2, '')) AS Locations\nFROM [Vehicle]\n STRING_AGG SELECT [VehicleID]\n ,[Name]\n ,(SELECT STRING_AGG([City], ', ')\n FROM [Location]\n WHERE VehicleID = V.VehicleID) AS Locations\nFROM [Vehicle] V\n" }, { "answer_id": 7192, "author": "Mike Powell", "author_id": 205, "author_profile": "https://Stackoverflow.com/users/205", "pm_score": 6, "selected": false, "text": "DECLARE @EmployeeList varchar(100)\nSELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + \n CAST(EmpUniqueID AS varchar(5))\nFROM SalesCallsEmployees\nWHERE SalCal_UniqueID = 1\n" }, { "answer_id": 7194, "author": "HS.", "author_id": 618, "author_profile": "https://Stackoverflow.com/users/618", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n[Serializable]\n[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined,MaxByteSize=8000)]\npublic class CSV:IBinarySerialize\n{\n private StringBuilder Result;\n public void Init() {\n this.Result = new StringBuilder();\n }\n\n public void Accumulate(SqlString Value) {\n if (Value.IsNull) return;\n this.Result.Append(Value.Value).Append(\",\");\n }\n public void Merge(CSV Group) {\n this.Result.Append(Group.Result);\n }\n public SqlString Terminate() {\n return new SqlString(this.Result.ToString());\n }\n public void Read(System.IO.BinaryReader r) {\n this.Result = new StringBuilder(r.ReadString());\n }\n public void Write(System.IO.BinaryWriter w) {\n w.Write(this.Result.ToString());\n }\n}\n" }, { "answer_id": 1012432, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 4, "selected": false, "text": "CREATE FUNCTION fnConcatVehicleCities(@VehicleId SMALLINT)\nRETURNS VARCHAR(1000) AS\nBEGIN\n DECLARE @csvCities VARCHAR(1000)\n SELECT @csvCities = COALESCE(@csvCities + ', ', '') + COALESCE(City,'')\n FROM Vehicles \n WHERE VehicleId = @VehicleId \n return @csvCities\nEND\n\n-- //Once the User defined function is created then run the below sql\n\nSELECT VehicleID\n , dbo.fnConcatVehicleCities(VehicleId) AS Locations\nFROM Vehicles\nGROUP BY VehicleID\n" }, { "answer_id": 2226801, "author": "JustinStolle", "author_id": 92389, "author_profile": "https://Stackoverflow.com/users/92389", "pm_score": 2, "selected": false, "text": "change: this.intermediateResult.Append(value.Value).Append(',');\n to: this.intermediateResult.Append(value.Value);\n change: output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1);\n to: output = this.intermediateResult.ToString();\n SELECT dbo.CONCATENATE(column1 + '|') from table1\n" }, { "answer_id": 3098463, "author": "John B", "author_id": 70614, "author_profile": "https://Stackoverflow.com/users/70614", "pm_score": 5, "selected": false, "text": "FOR XML COALESCE(@var... STUFF stuff(\n (select ',' + Column \n from Table\n inner where inner.Id = outer.Id \n for xml path('')\n), 1,1,'') as Values\n" }, { "answer_id": 3672902, "author": "teamchong", "author_id": 442938, "author_profile": "https://Stackoverflow.com/users/442938", "pm_score": 5, "selected": false, "text": "SELECT Stuff(\n (SELECT N', ' + Name FROM Names FOR XML PATH(''),TYPE)\n .value('text()[1]','nvarchar(max)'),1,2,N'')\n SELECT per.ID,\nEmails = JSON_VALUE(\n REPLACE(\n (SELECT _ = em.Email FROM Email em WHERE em.Person = per.ID FOR JSON PATH)\n ,'\"},{\"_\":\"',', '),'$[0]._'\n) \nFROM Person per\n Id Emails\n1 [email protected]\n2 NULL\n3 [email protected], [email protected]\n" }, { "answer_id": 4616468, "author": "ZunTzu", "author_id": 565604, "author_profile": "https://Stackoverflow.com/users/565604", "pm_score": 5, "selected": false, "text": "-- rank locations by incrementing lexicographical order\nWITH RankedLocations AS (\n SELECT\n VehicleID,\n City,\n ROW_NUMBER() OVER (\n PARTITION BY VehicleID \n ORDER BY City\n ) Rank\n FROM\n Locations\n),\n-- concatenate locations using a recursive query\n-- (Common Table Expression)\nConcatenations AS (\n -- for each vehicle, select the first location\n SELECT\n VehicleID,\n CONVERT(nvarchar(MAX), City) Cities,\n Rank\n FROM\n RankedLocations\n WHERE\n Rank = 1\n\n -- then incrementally concatenate with the next location\n -- this will return intermediate concatenations that will be \n -- filtered out later on\n UNION ALL\n\n SELECT\n c.VehicleID,\n (c.Cities + ', ' + l.City) Cities,\n l.Rank\n FROM\n Concatenations c -- this is a recursion!\n INNER JOIN RankedLocations l ON\n l.VehicleID = c.VehicleID \n AND l.Rank = c.Rank + 1\n),\n-- rank concatenation results by decrementing length \n-- (rank 1 will always be for the longest concatenation)\nRankedConcatenations AS (\n SELECT\n VehicleID,\n Cities,\n ROW_NUMBER() OVER (\n PARTITION BY VehicleID \n ORDER BY Rank DESC\n ) Rank\n FROM \n Concatenations\n)\n-- main query\nSELECT\n v.VehicleID,\n v.Name,\n c.Cities\nFROM\n Vehicles v\n INNER JOIN RankedConcatenations c ON \n c.VehicleID = v.VehicleID \n AND c.Rank = 1\n" }, { "answer_id": 6178016, "author": "Gil", "author_id": 628972, "author_profile": "https://Stackoverflow.com/users/628972", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION [dbo].[JoinTexts]\n(\n @delimiter VARCHAR(20) ,\n @whereClause VARCHAR(1)\n)\nRETURNS VARCHAR(MAX)\nAS \nBEGIN\n DECLARE @Texts VARCHAR(MAX)\n\n SELECT @Texts = COALESCE(@Texts + @delimiter, '') + T.Texto\n FROM SomeTable AS T\n WHERE T.SomeOtherColumn = @whereClause\n\n RETURN @Texts\nEND\nGO\n SELECT dbo.JoinTexts(' , ', 'Y')\n" }, { "answer_id": 32391199, "author": "Ilya Rudenko", "author_id": 5299491, "author_profile": "https://Stackoverflow.com/users/5299491", "pm_score": 1, "selected": false, "text": "SELECT v.VehicleId, v.Name, ll.LocationList\nFROM Vehicles v \nLEFT JOIN \n (SELECT \n DISTINCT\n VehicleId,\n REPLACE(\n REPLACE(\n REPLACE(\n (\n SELECT City as c \n FROM Locations x \n WHERE x.VehicleID = l.VehicleID FOR XML PATH('')\n ), \n '</c><c>',', '\n ),\n '<c>',''\n ),\n '</c>', ''\n ) AS LocationList\n FROM Locations l\n) ll ON ll.VehicleId = v.VehicleId\n" }, { "answer_id": 37036165, "author": "Mike Barlow - BarDev", "author_id": 92166, "author_profile": "https://Stackoverflow.com/users/92166", "pm_score": 2, "selected": false, "text": "SELECT\n Table_Name\n ,STUFF((\n SELECT ',' + Column_Name\n FROM INFORMATION_SCHEMA.Columns Columns\n WHERE Tables.Table_Name = Columns.Table_Name\n ORDER BY Column_Name\n FOR XML PATH ('')), 1, 1, ''\n )Columns\nFROM INFORMATION_SCHEMA.Columns Tables\nGROUP BY TABLE_NAME \n" }, { "answer_id": 40010270, "author": "nurseybushc", "author_id": 2255569, "author_profile": "https://Stackoverflow.com/users/2255569", "pm_score": 2, "selected": false, "text": "SELECT [VehicleID]\n , [Name]\n , STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,City) \n FROM [Location] \n WHERE (VehicleID = Vehicle.VehicleID) \n FOR XML PATH ('')), 1, 2, '') AS Locations\nFROM [Vehicle]\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799/" ]
6,904
<p>I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call <code>device.Connect()</code>, I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using:</p> <pre><code>static void Main(string[] args) { DatastoreManager dm = new DatastoreManager(1033); Collection&lt;Platform&gt; platforms = dm.GetPlatforms(); foreach (var p in platforms) { Console.WriteLine("{0} {1}", p.Name, p.Id); } Platform platform = platforms[3]; Console.WriteLine("Selected {0}", platform.Name); Device device = platform.GetDevices()[0]; device.Connect(); Console.WriteLine("Device Connected"); SystemInfo info = device.GetSystemInfo(); Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo); Console.ReadLine(); } </code></pre> <p>Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell.</p> <p>Here's the stack trace:</p> <pre><code>System.IO.DirectoryNotFoundException was unhandled Message="The system cannot find the path specified.\r\n" Source="Device Connection Manager" StackTrace: at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice() at Microsoft.SmartDevice.Connectivity.Device.Connect() at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() </code></pre>
[ { "answer_id": 2401184, "author": "PrateekSaluja", "author_id": 307989, "author_profile": "https://Stackoverflow.com/users/307989", "pm_score": 2, "selected": true, "text": "<systemdrive>:\\Program files\\Common Files\\Microsoft Shared\\CoreCon\\1.0\\Bin" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
6,915
<p>Is there a way to implement a singleton object in C++ that is:</p> <ol> <li>Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once).</li> <li>Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables).</li> </ol> <p>(I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..)</p> <hr> <p>Excellent, it seems that I have a couple of good answers now (shame I can't mark 2 or 3 as being <strong>the answer</strong>). There appears to be two broad solutions:</p> <ol> <li>Use static initialisation (as opposed to dynamic initialisation) of a POD static variable, and implementing my own mutex with that using the builtin atomic instructions. This was the type of solution I was hinting at in my question, and I believe I knew already.</li> <li>Use some other library function like <a href="http://opengroup.org/onlinepubs/007908799/xsh/pthread_once.html" rel="noreferrer">pthread_once</a> or <a href="http://www.boost.org/doc/libs/1_33_1/doc/html/call_once.html" rel="noreferrer">boost::call_once</a>. These I certainly didn't know about - and am very grateful for the answers posted.</li> </ol>
[ { "answer_id": 6943, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 4, "selected": false, "text": "pObj == NULL pObj int MySingleton *MySingleton::GetSingleton() {\n if (pObj == NULL) {\n // create a temporary instance of the singleton\n MySingleton *temp = new MySingleton();\n if (OSAtomicCompareAndSwapPtrBarrier(NULL, temp, &pObj) == false) {\n // if the swap didn't take place, delete the temporary instance\n delete temp;\n }\n }\n\n return pObj;\n}\n OSAtomicCompareAndSwapPtrBarrier pObj NULL temp pthread_once" }, { "answer_id": 7036, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "boost::call_once" }, { "answer_id": 18293, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 0, "selected": false, "text": "main()" }, { "answer_id": 70994, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 3, "selected": false, "text": "LazyType* GetMyLazyGlobal() {\n static const LazyType* instance = new LazyType();\n return instance;\n}\n" }, { "answer_id": 2867416, "author": "Frerich Raabe", "author_id": 91757, "author_profile": "https://Stackoverflow.com/users/91757", "pm_score": 4, "selected": false, "text": "Singleton *Singleton::self() {\n static Singleton instance;\n return &instance;\n}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/755/" ]
6,932
<p>What is the best way to transcode audio and video to show on the web? </p> <p>I need to do it programmatically. I'd like to do something like YouTube or Google Video where users can upload whatever format they want, and I encode it to flv, mp3, and/or mp4. I could do it on our server, but I would rather use an EC2 instance or even a web service. We have a Windows 2008 server.</p>
[ { "answer_id": 7186, "author": "masc", "author_id": 919, "author_profile": "https://Stackoverflow.com/users/919", "pm_score": 2, "selected": false, "text": "ffmpeg -hq -y -i $directory/$file -r 20 -s 300x200 -deinterlace -ar 22050 $directory/$file.flv 1>/dev/null 2>/dev/null\n" }, { "answer_id": 430594, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 2, "selected": false, "text": "nice +20 $MENCODER mf://${JPEGFILE} -mf w=720:h=480:fps=1/${SOUNDLENGTH}:type=jpeg -audiofile ${SOUNDFILE} -ovc lavc -oac lavc -lavcopts vcodec=mpeg4 -ofps 30000/1001 -o ${MENU_MPG}\n nice +20 $MENCODER -edl ${EDL} -ovc lavc -oac lavc -lavcopts vcodec=mpeg2video:vrc_buf_size=1835:vrc_maxrate=9800:vbitrate=${VBITRATE}:keyint=18:acodec=ac3:abitrate=192:aspect=4/3:trell:mbd=2:dia=4:cmp=3:precmp=3:ildctcmp=3:subcmp=3:mbcmp=3:cbp:mv0:dc=10 -of mpeg -mpegopts format=dvd -vf scale=720:480,harddup -srate 48000 -af lavcresample=48000 -ofps 30000/1001 -o ./${INFILE}.reformatted ${FILEPATH}\n" } ]
2008/08/09
[ "https://Stackoverflow.com/questions/6932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571/" ]
7,015
<p>I have a quad core machine and would like to write some code to parse a text file that takes advantage of all four cores. The text file basically contains one record per line.</p> <p>Multithreading isn't my forte so I'm wondering if anyone could give me some patterns that I might be able to use to parse the file in an optimal manner.</p> <p>My first thoughts are to read all the lines into some sort of queue and then spin up threads to pull the lines off the queue and process them, but that means the queue would have to exist in memory and these are fairly large files so I'm not so keen on that idea.</p> <p>My next thoughts are to have some sort of controller that will read in a line and assign it a thread to parse, but I'm not sure if the controller will end up being a bottleneck if the threads are processing the lines faster than it can read and assign them.</p> <p>I know there's probably another simpler solution than both of these but at the moment I'm just not seeing it.</p>
[ { "answer_id": 7023, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "Executors .newFixedThreadPool ExecutorService .submit System.Threading.ThreadPool" }, { "answer_id": 7045, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "open file\nfor each thread n=0,1,2,3:\n seek to file offset 1/n*filesize\n scan to next complete line\n process all lines in your part of the file\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
7,031
<p>I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p> <p><strong>For Example -</strong> You have <em>Home</em>, <em>Products</em>, <em>About Us</em>, and <em>Contact</em>. I want to have buttons for <em>Dealer</em>, <em>Distributor</em>, and maybe other information if the user is logged in. So I will have <em>Home</em>, <em>Products</em>, <em>About Us</em>, <em>Contacts</em>, Dealer (if dealer login), <em>Distributor</em> (if distributor login), and so forth. </p> <p>Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 7466, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 1, "selected": false, "text": "<?php\nrequire_once 'Auth.php';\n// output some html\nif (isLoggedIn()) {\n echo 'html for logged in user';\n}\n// rest of html\n <?php\npublic function viewCustomer($customerId) {\n if (!isLoggedIn())\n redirectToLoginPage();\n}\n" }, { "answer_id": 7473, "author": "Akira", "author_id": 795, "author_profile": "https://Stackoverflow.com/users/795", "pm_score": 3, "selected": false, "text": "<? require 'auth.php' ?>\n<ul>\n <li><a href=\"\">Home</a></li>\n <li><a href=\"\">Products</a></li>\n <? if( loggedin() ): ?><li><a href=\"\">Secret area</a></li><? endif; ?>\n</ul>\n <?php \n require 'auth.php';\n require_login();\n?>\n <?php\n function loggedin(){\n return isset( $_SESSION['loggedin'] );\n }\n\n function require_login(){\n if( !loggedin() ){\n header( 'Location: /login.php?referrer='.$_SERVER['REQUEST_URI'] );\n exit;\n }\n }\n?>\n" }, { "answer_id": 26602, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 1, "selected": false, "text": "if (logged())\n{\n elementSecretArea.style.display = \"list-item\";\n}\n" }, { "answer_id": 1446276, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<ul> <li>Home</li> </ul> </li> <?php\n if($session-logged_in) { \n?>\n\n<li>My Account</li>\n\n<?php \n }\n?> \n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/876/" ]
7,034
<p>I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around.</p> <p>Note: I'm not looking for a charting library.</p>
[ { "answer_id": 2366237, "author": "Johann Philipp Strathausen", "author_id": 284708, "author_profile": "https://Stackoverflow.com/users/284708", "pm_score": 11, "selected": true, "text": "var g = new Graph();\ng.addEdge(\"strawberry\", \"cherry\");\ng.addEdge(\"cherry\", \"apple\");\ng.addEdge(\"id34\", \"cherry\");\n" }, { "answer_id": 10319429, "author": "maxkfranz", "author_id": 947225, "author_profile": "https://Stackoverflow.com/users/947225", "pm_score": 6, "selected": false, "text": "cy.elements(\"node[weight >= 50].someClass\") cy.nodes().unselect().trigger(\"mycustomevent\")" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ]
7,035
<p>I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output.</p> <p>So far the only input required is a password for sudo - and gksudo handles that fine. But I haven't found an easy way to show a message box yet. Is there some kind of 'gkmessage' command available? I'd prefer something present in a default Ubuntu install, but I don't mind installing a new package if necessary.</p>
[ { "answer_id": 7043, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 3, "selected": false, "text": "#!/usr/bin/wish\npack [label .msg -text [lindex $argv 0]]\npack [entry .ent]\nbind .ent <KeyPress-Return> { puts [.ent get]; destroy . }\nfocus .ent\n myanswer=`gui-prompt \"type your answer and press enter\"`\n" }, { "answer_id": 78654, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 3, "selected": false, "text": "dialog kdialog dialog" }, { "answer_id": 79217, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "zenity --help\n" }, { "answer_id": 1235050, "author": "Jim", "author_id": 12419, "author_profile": "https://Stackoverflow.com/users/12419", "pm_score": 6, "selected": false, "text": "my_variable=$(zenity --entry)\n my_variable=$(zenity --entry --text=\"What's my variable:\")\n my_date=$(zenity --calendar)\n echo ${my_date}\n" }, { "answer_id": 14422397, "author": "chmac", "author_id": 198232, "author_profile": "https://Stackoverflow.com/users/198232", "pm_score": 8, "selected": false, "text": "notify-send notify-send \"My name is bash and I rock da house\"" }, { "answer_id": 21408784, "author": "Stéphane Gourichon", "author_id": 1429390, "author_profile": "https://Stackoverflow.com/users/1429390", "pm_score": 7, "selected": false, "text": "zenity \\\n--info \\\n--text=\"<span size=\\\"xx-large\\\">Time is $(date +%Hh%M).</span>\\n\\nGet your <b>coffee</b>.\" \\\n--title=\"Coffee time\" \\\n--ok-label=\"Sip\"\n gxmessage \"my text\"\n xmessage .Xdefaults xmessage -buttons Ok:0,\"Not sure\":1,Cancel:2 -default Ok -nearmouse \"Is xmessage enough for the job ?\" -timeout 10\n kdialog --error \"Some error occurred\"\n echo My text | yad \\\n--text-info \\\n--width=400 \\\n--height=200\n yad \\\n--title=\"Desktop entry editor\" \\\n--text=\"Simple desktop entry editor\" \\\n--form \\\n--field=\"Type:CB\" \\\n--field=\"Name\" \\\n--field=\"Generic name\" \\\n--field=\"Comment\" \\\n--field=\"Command:FL\" \\\n--field=\"Icon\" \\\n--field=\"In terminal:CHK\" \\\n--field=\"Startup notify:CHK\" \"Application\" \"Name\" \"Generic name\" \"This is the comment\" \"/usr/bin/yad\" \"yad\" FALSE TRUE \\\n--button=\"WebUpd8:2\" \\\n--button=\"gtk-ok:0\" \\\n--button=\"gtk-cancel:1\"\n whiptail --msgbox \"my text\" 10 20\ndialog --msgbox \"my text\" 10 20\n" }, { "answer_id": 35920711, "author": "mulya", "author_id": 315158, "author_profile": "https://Stackoverflow.com/users/315158", "pm_score": 2, "selected": false, "text": "ls -la; alert\n" }, { "answer_id": 42125720, "author": "Dave Thebuskeruk", "author_id": 7537345, "author_profile": "https://Stackoverflow.com/users/7537345", "pm_score": 3, "selected": false, "text": "alert notify-send notify-send # This will display message and then disappear after a delay:\nnotify-send \"job complete\"\n\n# This will display message and stay on-screen until clicked:\nnotify-send -u critical \"job complete\"\n" }, { "answer_id": 47193545, "author": "user6795571", "author_id": 6795571, "author_profile": "https://Stackoverflow.com/users/6795571", "pm_score": 3, "selected": false, "text": " xterm -e bash -c 'echo \"this is the message\";echo;echo -n \"press enter to continue \"; stty sane -echo;answer=$( while ! head -c 1;do true ;done);'\n" }, { "answer_id": 70455744, "author": "steve hannah", "author_id": 2935174, "author_profile": "https://Stackoverflow.com/users/2935174", "pm_score": 2, "selected": false, "text": "#!/bin/bash\necho \"Hello ${name}\"\nexit 0\n---\n[name]\n type=\"text\"\n label=\"Please enter your name\"\n required=true\n shellmarks hello.sh\n Hello Steve\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
7,074
<p>What are the differences between these two and which one should I use?</p> <pre><code>string s = &quot;Hello world!&quot;; String s = &quot;Hello world!&quot;; </code></pre>
[ { "answer_id": 7077, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 14, "selected": true, "text": "string System.String int System.Int32 string string place = \"world\";\n String string greet = String.Format(\"Hello {0}!\", place);\n" }, { "answer_id": 7079, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": 8, "selected": false, "text": "System.String string System.String Int16 Int32 UInt16 UInt32 String" }, { "answer_id": 7081, "author": "urini", "author_id": 373, "author_profile": "https://Stackoverflow.com/users/373", "pm_score": 8, "selected": false, "text": "string System.String C# System.Int32 System.String C# aliases int string C# aliases" }, { "answer_id": 12863, "author": "Luke Foust", "author_id": 646, "author_profile": "https://Stackoverflow.com/users/646", "pm_score": 9, "selected": false, "text": "BinaryReader br = new BinaryReader(...);\nfloat val = br.ReadSingle(); // OK, but feels unnatural\nSingle val = br.ReadSingle(); // OK and feels good\n" }, { "answer_id": 15002, "author": "Mel", "author_id": 1763, "author_profile": "https://Stackoverflow.com/users/1763", "pm_score": 6, "selected": false, "text": "string Int32 decimal Int64 int Int32" }, { "answer_id": 30797, "author": "user3296", "author_id": 3296, "author_profile": "https://Stackoverflow.com/users/3296", "pm_score": 9, "selected": false, "text": "String using System;" }, { "answer_id": 42306, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 8, "selected": false, "text": ".NET .NET if switch return String someString; \nstring anotherString; \n" }, { "answer_id": 215263, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 8, "selected": false, "text": "string String string" }, { "answer_id": 215266, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 7, "selected": false, "text": "string System.String using System String" }, { "answer_id": 215304, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 10, "selected": false, "text": "String System.String string System.String System.String string int System.Int32" }, { "answer_id": 215382, "author": "Pradeep Kumar Mishra", "author_id": 22710, "author_profile": "https://Stackoverflow.com/users/22710", "pm_score": 7, "selected": false, "text": "string String Int32 int int Int32 System.String" }, { "answer_id": 215422, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 12, "selected": false, "text": "string System.String String System.String String object: System.Object\nstring: System.String\nbool: System.Boolean\nbyte: System.Byte\nsbyte: System.SByte\nshort: System.Int16\nushort: System.UInt16\nint: System.Int32\nuint: System.UInt32\nlong: System.Int64\nulong: System.UInt64\nfloat: System.Single\ndouble: System.Double\ndecimal: System.Decimal\nchar: System.Char\n string object decimal System.IntPtr DateTime public enum Foo : UInt32 {} // Invalid\npublic enum Bar : uint {} // Valid\n sbyte byte short ushort int uint long ulong char ReadInt32 ReadInt int Int16 BitConverter BinaryReader Convert" }, { "answer_id": 215813, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 8, "selected": false, "text": "string String" }, { "answer_id": 215831, "author": "Lloyd Cotten", "author_id": 21807, "author_profile": "https://Stackoverflow.com/users/21807", "pm_score": 7, "selected": false, "text": "string System.String String.Format String.Join String.Concat" }, { "answer_id": 580546, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 9, "selected": false, "text": "string String string StringBuilder String = new StringBuilder(); // compiles\nStringBuilder string = new StringBuilder(); // doesn't compile \n @ StringBuilder @string = new StringBuilder();\n" }, { "answer_id": 655907, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 8, "selected": false, "text": "string System.String string System.String string java.lang.String" }, { "answer_id": 4827000, "author": "claudioalpereira", "author_id": 593614, "author_profile": "https://Stackoverflow.com/users/593614", "pm_score": 6, "selected": false, "text": "BinaryReader br = new BinaryReader(...);\nfloat val = br.ReadSingle(); // OK, but feels unnatural\nSingle val = br.ReadSingle(); // OK and feels good\n" }, { "answer_id": 5775710, "author": "user576533", "author_id": 576533, "author_profile": "https://Stackoverflow.com/users/576533", "pm_score": 6, "selected": false, "text": "String string" }, { "answer_id": 6186799, "author": "RolandK", "author_id": 558331, "author_profile": "https://Stackoverflow.com/users/558331", "pm_score": 7, "selected": false, "text": "String string String" }, { "answer_id": 7173165, "author": "Dot NET", "author_id": 856132, "author_profile": "https://Stackoverflow.com/users/856132", "pm_score": 5, "selected": false, "text": "string" }, { "answer_id": 7844012, "author": "JeeShen Lee", "author_id": 440641, "author_profile": "https://Stackoverflow.com/users/440641", "pm_score": 7, "selected": false, "text": "string System.String string System.String" }, { "answer_id": 8865991, "author": "Oded", "author_id": 1583, "author_profile": "https://Stackoverflow.com/users/1583", "pm_score": 6, "selected": false, "text": "string System.String int System.Int32" }, { "answer_id": 8866038, "author": "Joe Alfano", "author_id": 1139127, "author_profile": "https://Stackoverflow.com/users/1139127", "pm_score": 6, "selected": false, "text": "System.String Boolean vs. bool" }, { "answer_id": 12706960, "author": "Zaid Masud", "author_id": 374420, "author_profile": "https://Stackoverflow.com/users/374420", "pm_score": 5, "selected": false, "text": "String System.String" }, { "answer_id": 12725425, "author": "Inverted Llama", "author_id": 1250250, "author_profile": "https://Stackoverflow.com/users/1250250", "pm_score": 4, "selected": false, "text": "String string" }, { "answer_id": 12777808, "author": "Coder", "author_id": 1696881, "author_profile": "https://Stackoverflow.com/users/1696881", "pm_score": 5, "selected": false, "text": "bool Boolean" }, { "answer_id": 21144988, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 8, "selected": false, "text": ".NET .NET C# VB.NET System.String .NET C# String s = \"I am String\";\n string s = \"I am String\";\n System.Object System.String System.Boolean System.Byte System.SByte System.Int16 string s = String.ToUpper() ;\n" }, { "answer_id": 23762744, "author": "Geeky Ninja", "author_id": 2674680, "author_profile": "https://Stackoverflow.com/users/2674680", "pm_score": 3, "selected": false, "text": "string string String 'string' 'string' 'String' 'string' 'String'" }, { "answer_id": 24155226, "author": "Neel", "author_id": 1997103, "author_profile": "https://Stackoverflow.com/users/1997103", "pm_score": 5, "selected": false, "text": "string String = \"I am a string\";\n string System.String typeof(string) == typeof(String) == typeof(System.String)\n" }, { "answer_id": 24161540, "author": "Vijay Singh Rana", "author_id": 1537055, "author_profile": "https://Stackoverflow.com/users/1537055", "pm_score": 3, "selected": false, "text": "System.String. string int, bool, var Int32 Boolean String.Split() String.IsNullOrEmpty()" }, { "answer_id": 24319676, "author": "Kalu Singh Rao", "author_id": 3674931, "author_profile": "https://Stackoverflow.com/users/3674931", "pm_score": 3, "selected": false, "text": "string System.String bool object int string System; System.String string" }, { "answer_id": 24972696, "author": "InfZero", "author_id": 379371, "author_profile": "https://Stackoverflow.com/users/379371", "pm_score": 3, "selected": false, "text": "String XmlReader StreamReader string for while default" }, { "answer_id": 27706582, "author": "Teter28", "author_id": 3545103, "author_profile": "https://Stackoverflow.com/users/3545103", "pm_score": 4, "selected": false, "text": "System string System.String" }, { "answer_id": 27965515, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 7, "selected": false, "text": "string String using String global::System.String using String class MySequence<TElement>\n{\n public IEnumerable<TElement> String { get; set; }\n\n void Example()\n {\n var test = String.Format(\"Hello {0}.\", DateTime.Today.DayOfWeek);\n }\n}\n IEnumerable<> Format String String local = \"Hi mum!\"; using String.Concat(someSequence) using Enumerable.Concat string.Concat String class MyPiano\n{\n protected class String\n {\n }\n\n void Example()\n {\n var test1 = String.Format(\"Hello {0}.\", DateTime.Today.DayOfWeek);\n String test2 = \"Goodbye\";\n }\n}\n Example String MyPiano.String static Format \"Goodbye\"" }, { "answer_id": 29489427, "author": "Anuja Lamahewa", "author_id": 4298321, "author_profile": "https://Stackoverflow.com/users/4298321", "pm_score": 5, "selected": false, "text": "string fName = \"John\";\nstring lName = \"Smith\";\n\nstring fullName = String.Concat(fName,lName);\n\nif (String.IsNullOrEmpty(fName))\n{\n Console.WriteLine(\"Enter first name\");\n}\n" }, { "answer_id": 32893650, "author": "tic", "author_id": 1898688, "author_profile": "https://Stackoverflow.com/users/1898688", "pm_score": 4, "selected": false, "text": "string System.String var method1 = typeof(MyClass).GetMethod(\"TestString1\").GetMethodBody().GetILAsByteArray();\nvar method2 = typeof(MyClass).GetMethod(\"TestString2\").GetMethodBody().GetILAsByteArray();\n\n//...\n\npublic string TestString1()\n{\n string str = \"Hello World!\";\n return str;\n}\n\npublic string TestString2()\n{\n String str = \"Hello World!\";\n return str;\n}\n [ 0, 114, 107, 0, 0, 112, 10, 6, 11, 43, 0, 7, 42 ]\n" }, { "answer_id": 34490521, "author": "yazan_ati", "author_id": 5644664, "author_profile": "https://Stackoverflow.com/users/5644664", "pm_score": 3, "selected": false, "text": "string String int, bool, var Int32 Boolean String String.Split() String.IsNullOrEmpty()" }, { "answer_id": 34898005, "author": "Pritam Jyoti Ray", "author_id": 1324573, "author_profile": "https://Stackoverflow.com/users/1324573", "pm_score": 3, "selected": false, "text": "System.String mscorlib System System.String CLR string C#" }, { "answer_id": 37629561, "author": "hubot", "author_id": 4598557, "author_profile": "https://Stackoverflow.com/users/4598557", "pm_score": 4, "selected": false, "text": "System.String string System.Object String System.String System.String string a = new string(new char[] { 'x', 'y', 'z' });\nstring b = new String(new char[] { 'x', 'y', 'z' });\nString c = new string(new char[] { 'x', 'y', 'z' });\nString d = new String(new char[] { 'x', 'y', 'z' });\nMessageBox.Show((a.GetType() == typeof(String) && a.GetType() == typeof(string)).ToString()); // shows true\nMessageBox.Show((b.GetType() == typeof(String) && b.GetType() == typeof(string)).ToString()); // shows true\nMessageBox.Show((c.GetType() == typeof(String) && c.GetType() == typeof(string)).ToString()); // shows true\nMessageBox.Show((d.GetType() == typeof(String) && d.GetType() == typeof(string)).ToString()); // shows true\n public enum Foo : UInt32 { }\n" }, { "answer_id": 43012741, "author": "Saurabh", "author_id": 3556867, "author_profile": "https://Stackoverflow.com/users/3556867", "pm_score": 3, "selected": false, "text": "string System.String System.String str;\n string str;\n" }, { "answer_id": 46813546, "author": "DavidWainwright", "author_id": 385638, "author_profile": "https://Stackoverflow.com/users/385638", "pm_score": 3, "selected": false, "text": "string string Go to definition String" }, { "answer_id": 48120399, "author": "Taslim Oseni", "author_id": 5670752, "author_profile": "https://Stackoverflow.com/users/5670752", "pm_score": 4, "selected": false, "text": "bool Boolean" }, { "answer_id": 48223011, "author": "Hasan Jafarov", "author_id": 2806548, "author_profile": "https://Stackoverflow.com/users/2806548", "pm_score": 3, "selected": false, "text": "string System.String String System.String CTS(Common Type System)" }, { "answer_id": 48322758, "author": "BanksySan", "author_id": 442351, "author_profile": "https://Stackoverflow.com/users/442351", "pm_score": 5, "selected": false, "text": "string String nameof(String); // compiles\nnameof(string); // doesn't compile\n string String | Alias | Type |\n|-----------|------------------|\n| bool | System.Boolean |\n| byte | System.Byte |\n| sbyte | System.SByte |\n| char | System.Char |\n| decimal | System.Decimal |\n| double | System.Double |\n| float | System.Single |\n| int | System.Int32 |\n| uint | System.UInt32 |\n| long | System.Int64 |\n| ulong | System.UInt64 |\n| object | System.Object |\n| short | System.Int16 |\n| ushort | System.UInt16 |\n| string | System.String |\n" }, { "answer_id": 48563657, "author": "v.slobodzian", "author_id": 9205802, "author_profile": "https://Stackoverflow.com/users/9205802", "pm_score": 3, "selected": false, "text": "using using int = System.Int32;\nusing uint = System.UInt32;\nusing string = System.String;\n...\n" }, { "answer_id": 48680864, "author": "wild coder", "author_id": 9106094, "author_profile": "https://Stackoverflow.com/users/9106094", "pm_score": 4, "selected": false, "text": "string String String string string s; System.String" }, { "answer_id": 51296196, "author": "Jaider", "author_id": 480700, "author_profile": "https://Stackoverflow.com/users/480700", "pm_score": 3, "selected": false, "text": "string System.String string System.String String using System; System.String string" }, { "answer_id": 51467104, "author": "Just Fair", "author_id": 8207463, "author_profile": "https://Stackoverflow.com/users/8207463", "pm_score": 3, "selected": false, "text": "System.String System.String" }, { "answer_id": 52841014, "author": "Burak Yeniçeri", "author_id": 9131762, "author_profile": "https://Stackoverflow.com/users/9131762", "pm_score": 3, "selected": false, "text": "String string System String string string int and Int32\nshort and Int16\nlong and Int64 string or String" }, { "answer_id": 55628158, "author": "aloisdg", "author_id": 1248177, "author_profile": "https://Stackoverflow.com/users/1248177", "pm_score": 6, "selected": false, "text": "string String string System.String string String Widget Student string String s = \"hello\" class TricksterString { \n void Example() {\n String s = \"Hello World\"; // Okay but probably not what you expect.\n }\n}\n\nclass String {\n public static implicit operator String(string s) => null;\n}\n String String string String String string string s1 = 42; // Errors 100% of the time \nString s2 = 42; // Might error, might not, depends on the code\n String String String String string String string String" }, { "answer_id": 56133714, "author": "Gonçalo Garrido", "author_id": 11312923, "author_profile": "https://Stackoverflow.com/users/11312923", "pm_score": 3, "selected": false, "text": "String.Format()\n string name = \"\";\n" }, { "answer_id": 56753700, "author": "Ted Mucuzany", "author_id": 11652382, "author_profile": "https://Stackoverflow.com/users/11652382", "pm_score": 3, "selected": false, "text": "public static void Main()\n{\n var s = \"a string\";\n}\n .exe ildasm .method private hidebysig static void Main(string[] args) cil managed\n{\n .entrypoint\n // Code size 8 (0x8)\n .maxstack 1\n .locals init ([0] string s)\n IL_0000: nop\n IL_0001: ldstr \"a string\"\n IL_0006: stloc.0\n IL_0007: ret\n} // end of method Program::Main\n var string String ildasm IL string String" }, { "answer_id": 56846041, "author": "Ali Sufyan", "author_id": 10943076, "author_profile": "https://Stackoverflow.com/users/10943076", "pm_score": 2, "selected": false, "text": "string String String System string" }, { "answer_id": 57526143, "author": "MicroservicesOnDDD", "author_id": 7760271, "author_profile": "https://Stackoverflow.com/users/7760271", "pm_score": 2, "selected": false, "text": "System.String string System.Int32 int string int System.String System.Int32 System.String" }, { "answer_id": 66428994, "author": "TRK", "author_id": 11652409, "author_profile": "https://Stackoverflow.com/users/11652409", "pm_score": 2, "selected": false, "text": "string String String System.String System.String string string str = \"Hello\";\n String String.IsNullOrEmpty() String string" }, { "answer_id": 70405501, "author": "Ran Turner", "author_id": 7494218, "author_profile": "https://Stackoverflow.com/users/7494218", "pm_score": 2, "selected": false, "text": "string String String System.String string System.String string s1= \"hello there 1\";\nString s2 = \"hello there 2\";\n \nConsole.WriteLine(s1.GetType().FullName); // System.String\nConsole.WriteLine(s2.GetType().FullName); // System.String\n string String string System.String String.IsNullOrEmpty()" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571/" ]
7,084
<p>I've worked on a number of different embedded systems. They have all used <code>typedef</code>s (or <code>#defines</code>) for types such as <code>UINT32</code>.</p> <p>This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc.</p> <p>But on some systems you know that the compiler and processor won't change for the life of the project.</p> <p>So what should influence your decision to create and enforce project-specific types?</p> <p>EDIT I think I managed to lose the gist of my question, and maybe it's really two.</p> <p>With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler.</p> <p>For everything else the types have less importance.<br> You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to <code>UINT16</code>, <code>UCHAR</code>. Using types such as <code>UCHAR</code> can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type.<br> <PRE>i++;</PRE> can become <PRE>ADD REG,1 AND REG, 0xFF</PRE> which is unecessary.</p> <p>So I think my question should have been :-</p> <p>given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience.</p>
[ { "answer_id": 7117, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 3, "selected": false, "text": "<stdint.h> distance_t mass_t meter_t gram_t" }, { "answer_id": 7515, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "unsigned int uint32_t" }, { "answer_id": 13858, "author": "Yossi Kreinin", "author_id": 1648, "author_profile": "https://Stackoverflow.com/users/1648", "pm_score": 5, "selected": true, "text": "int16_t int16_t intfast_t INT32, int32_t, INT32_T int16_t {int,uint}{max,fast,least}{8,16,32,64}_t int_fast16_t uint_least32_t" }, { "answer_id": 37919751, "author": "Pelle", "author_id": 1549060, "author_profile": "https://Stackoverflow.com/users/1549060", "pm_score": 1, "selected": false, "text": "<stdint.h> int" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/888/" ]
7,089
<p>How can I create rounded corners using CSS?</p>
[ { "answer_id": 7098, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 8, "selected": true, "text": "border-radius border-radius" }, { "answer_id": 7099, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 6, "selected": false, "text": "border-radius:\n" }, { "answer_id": 7971, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": 3, "selected": false, "text": "<div class=\"Rounded\">\n <!-- content -->\n <div class=\"RoundedCorner RoundedCorner-TopLeft\"></div>\n <div class=\"RoundedCorner RoundedCorner-TopRight\"></div>\n <div class=\"RoundedCorner RoundedCorner-BottomRight\"></div>\n <div class=\"RoundedCorner RoundedCorner-BottomLeft\"></div>\n</div>\n /********************************\n* Rounded styling\n********************************/\n\n.Rounded {\n position: relative;\n}\n\n.Rounded .RoundedCorner {\n position: absolute;\n background-image: url('SpriteSheet.png');\n background-repeat: no-repeat;\n overflow: hidden;\n\n /* Size of the rounded corner images */\n height: 5px;\n width: 5px;\n}\n\n.Rounded .RoundedCorner-TopLeft {\n top: 0;\n left: 0;\n\n /* No background position change (or maybe depending on your sprite sheet) */\n}\n\n.Rounded .RoundedCorner-TopRight {\n top: 0;\n right: 0;\n\n /* Move the sprite sheet to show the appropriate image */\n background-position: -5px 0;\n}\n\n/* Hack for IE6 */\n* html .Rounded .RoundedCorner-TopRight {\n right: -1px;\n}\n\n.Rounded .RoundedCorner-BottomLeft {\n bottom: 0;\n left: 0;\n\n /* Move the sprite sheet to show the appropriate image */\n background-position: 0 -5px;\n}\n\n/* Hack for IE6 */\n* html .Rounded .RoundedCorner-BottomLeft {\n bottom: -20px;\n}\n\n.Rounded .RoundedCorner-BottomRight {\n bottom: 0;\n right: 0;\n\n /* Move the sprite sheet to show the appropriate image */\n background-position: -5px -5px;\n}\n\n/* Hack for IE6 */\n* html .Rounded .RoundedCorner-BottomRight {\n bottom: -20px;\n right: -1px;\n}\n" }, { "answer_id": 22222, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<div class=\"item_with_border\">\n <div class=\"border_top_left\"></div>\n <div class=\"border_top_right\"></div>\n <div class=\"border_bottom_left\"></div>\n <div class=\"border_bottom_right\"></div>\n This is the text that is displayed\n</div>\n\n<style>\n div.item_with_border\n {\n border: 1px solid #FFF;\n postion: relative;\n }\n div.item_with_border > div.border_top_left\n {\n background-image: url(topleft.png);\n position: absolute;\n top: -1px;\n left: -1px; \n width: 30px;\n height: 30px;\n z-index: 2;\n }\n div.item_with_border > div.border_top_right\n {\n background-image: url(topright.png);\n position: absolute;\n top: -1px;\n right: -1px; \n width: 30px;\n height: 30px;\n z-index: 2;\n }\n div.item_with_border > div.border_bottom_left\n {\n background-image: url(bottomleft.png);\n position: absolute;\n bottom: -1px;\n left: -1px; \n width: 30px;\n height: 30px;\n z-index: 2;\n }\n div.item_with_border > div.border_bottom_right\n {\n background-image: url(bottomright.png);\n position: absolute;\n bottom: -1px;\n right: -1px; \n width: 30px;\n height: 30px;\n z-index: 2;\n } \n</style>\n" }, { "answer_id": 210680, "author": "Jethro Larson", "author_id": 22425, "author_profile": "https://Stackoverflow.com/users/22425", "pm_score": 3, "selected": false, "text": "<div class=\"s\">Content</div>\n $(\"div.s\")\n.wrapInner(\"<div class='s-iwrap'><div class='s-iwrap2'>\")\n.prepend('<div class=\"tr\"/><div class=\"tl\"/><div class=\"br\"/><div class=\"bl\"/>');\n /*rounded corner orange box - no title*/\n.s {\n position: relative;\n margin: 0 auto 15px;\n zoom: 1;\n}\n\n.s-iwrap {\n border: 1px solid #FF9933;\n}\n\n.s-iwrap2 {\n margin: 12px;\n}\n\n.s .br,.s .bl, .s .tl, .s .tr {\n background: url(css/images/orange_corners_sprite.png) no-repeat;\n line-height: 1px;\n font-size: 1px;\n width: 9px;\n height: 9px;\n position: absolute;\n}\n\n.s .br {\n bottom: 0;\n right: 0;\n background-position: bottom right;\n}\n\n.s .bl {\n bottom: 0;\n left: 0;\n background-position: bottom left;\n}\n\n.s .tl {\n top: 0;\n left: 0;\n background-position: top left;\n}\n\n.s .tr {\n top: 0;\n right: 0;\n background-position: top right;\n}\n" }, { "answer_id": 465123, "author": "Brajeshwar", "author_id": 19564, "author_profile": "https://Stackoverflow.com/users/19564", "pm_score": 3, "selected": false, "text": "-moz-border-radius: 10px; \n-webkit-border-radius: 10px; \nborder-radius: 10px;\n -moz-border-radius-topleft: 10px; \n-moz-border-radius-topright: 7px; \n-moz-border-radius-bottomleft: 5px; \n-moz-border-radius-bottomright: 3px; \n-webkit-border-top-right-radius: 10px; \n-webkit-border-top-left-radius: 7px; \n-webkit-border-bottom-left-radius: 5px; \n-webkit-border-bottom-right-radius: 3px;\n" }, { "answer_id": 644587, "author": "juanpablob", "author_id": 77500, "author_profile": "https://Stackoverflow.com/users/77500", "pm_score": 4, "selected": false, "text": "border-radius -moz-border-radius -webkit-border-radius .htc round-corners border-radius div.box {\n background-color: yellow; \n border: 1px solid red; \n border-radius: 5px; \n behavior: url(corners.htc);\n}\n" }, { "answer_id": 823255, "author": "alex", "author_id": 31671, "author_profile": "https://Stackoverflow.com/users/31671", "pm_score": 3, "selected": false, "text": "border-radius #round-my-corners-please {\n -webkit-border-radius: 20px;\n -moz-border-radius: 20px;\n border-radius: 20px;\n}\n div" }, { "answer_id": 1121182, "author": "Sinan", "author_id": 128398, "author_profile": "https://Stackoverflow.com/users/128398", "pm_score": 5, "selected": false, "text": ".my_rounded_corners{\n -webkit-border-radius: 5px;\n border-radius: 5px;\n}\n .my_rounded_corners{\n border: 1px solid #ccc;\n\n /* each value for each corner clockwise starting from top left */\n -webkit-border-radius: 10px 3px 0 20px;\n border-radius: 10px 3px 0 20px;\n}\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
7,095
<p>In other words, is this Singleton implementation thread safe:</p> <pre><code>public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } } } </code></pre>
[ { "answer_id": 7105, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 9, "selected": true, "text": "public class Singleton\n{\n private static Singleton instance;\n // Added a static mutex for synchronising use of instance.\n private static System.Threading.Mutex mutex;\n private Singleton() { }\n static Singleton()\n {\n instance = new Singleton();\n mutex = new System.Threading.Mutex();\n }\n\n public static Singleton Acquire()\n {\n mutex.WaitOne();\n return instance;\n }\n\n // Each call to Acquire() requires a call to Release()\n public static void Release()\n {\n mutex.ReleaseMutex();\n }\n}\n" }, { "answer_id": 7107, "author": "Andrew Peters", "author_id": 608, "author_profile": "https://Stackoverflow.com/users/608", "pm_score": 3, "selected": false, "text": "private static readonly Singleton instance = new Singleton();\n" }, { "answer_id": 335734, "author": "Brian Rudolph", "author_id": 33114, "author_profile": "https://Stackoverflow.com/users/33114", "pm_score": 7, "selected": false, "text": "class MyObject<T>\n{\n static MyObject() \n {\n //this code will get executed for each T.\n }\n}\n static void Main(string[] args)\n{\n var obj = new Foo<object>();\n var obj2 = new Foo<string>();\n}\n\npublic class Foo<T>\n{\n static Foo()\n {\n System.Diagnostics.Debug.WriteLine(String.Format(\"Hit {0}\", typeof(T).ToString())); \n }\n}\n Hit System.Object\nHit System.String\n" }, { "answer_id": 8248031, "author": "Jay Juch", "author_id": 1062600, "author_profile": "https://Stackoverflow.com/users/1062600", "pm_score": 3, "selected": false, "text": "public sealed class Singleton\n{\n private static readonly Singleton instance = new Singleton();\n\n private Singleton(){}\n\n public static Singleton Instance\n {\n get \n {\n return instance; \n }\n }\n}\n" }, { "answer_id": 22634400, "author": "oleksii", "author_id": 706456, "author_profile": "https://Stackoverflow.com/users/706456", "pm_score": 2, "selected": false, "text": "using System.Threading;\nclass MyClass\n{\n static void Main() { /* Won’t run... the static constructor deadlocks */ }\n\n static MyClass()\n {\n Thread thread = new Thread(arg => { });\n thread.Start();\n thread.Join();\n }\n}\n" }, { "answer_id": 41413809, "author": "Trade-Ideas Philip", "author_id": 971955, "author_profile": "https://Stackoverflow.com/users/971955", "pm_score": 3, "selected": false, "text": " private class InitializerTest\n {\n static private int _x;\n static public string Status()\n {\n return \"_x = \" + _x;\n }\n static InitializerTest()\n {\n System.Diagnostics.Debug.WriteLine(\"InitializerTest() starting.\");\n _x = 1;\n Thread.Sleep(3000);\n _x = 2;\n System.Diagnostics.Debug.WriteLine(\"InitializerTest() finished.\");\n }\n }\n\n private void ClassInitializerInThread()\n {\n System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + \": ClassInitializerInThread() starting.\");\n string status = InitializerTest.Status();\n System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + \": ClassInitializerInThread() status = \" + status);\n }\n\n private void classInitializerButton_Click(object sender, EventArgs e)\n {\n new Thread(ClassInitializerInThread).Start();\n new Thread(ClassInitializerInThread).Start();\n new Thread(ClassInitializerInThread).Start();\n }\n 10: ClassInitializerInThread() starting.\n11: ClassInitializerInThread() starting.\n12: ClassInitializerInThread() starting.\nInitializerTest() starting.\nInitializerTest() finished.\n11: ClassInitializerInThread() status = _x = 2\nThe thread 0x2650 has exited with code 0 (0x0).\n10: ClassInitializerInThread() status = _x = 2\nThe thread 0x1f50 has exited with code 0 (0x0).\n12: ClassInitializerInThread() status = _x = 2\nThe thread 0x73c has exited with code 0 (0x0).\n" }, { "answer_id": 72322669, "author": "binki", "author_id": 429091, "author_profile": "https://Stackoverflow.com/users/429091", "pm_score": 0, "selected": false, "text": "Monitor.Enter() lock(){} ManualResetEventSlim.Wait() WaitHandle.WaitOne WaitHandle.WaitAny WaitHandle.WaitAll Monitor.Enter Monitor.TryEnter Thread.Join GC.WaitForPendingFinalizers Thread.Interrupt Thread.Abort" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373/" ]
7,118
<p>Currently, I don't really have a good method of debugging JavaScript in Internet&nbsp;Explorer and <a href="http://en.wikipedia.org/wiki/Safari_%28web_browser%29" rel="noreferrer">Safari</a>. In Firefox, you can use <a href="http://en.wikipedia.org/wiki/Firebug" rel="noreferrer">Firebug's</a> <a href="http://getfirebug.com/logging.html" rel="noreferrer">logging feature</a> and <a href="http://getfirebug.com/commandline.html" rel="noreferrer">command Line functions</a>. However, this doesn't help me when I move to other browsers.</p>
[ { "answer_id": 7129, "author": "Dominic Cooney", "author_id": 878, "author_profile": "https://Stackoverflow.com/users/878", "pm_score": 5, "selected": true, "text": "$ defaults write com.apple.Safari IncludeDebugMenu 1\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
7,209
<p>I'm trying to alpha blend sprites and backgrounds with <a href="http://www.devkitpro.org/" rel="noreferrer">devkitPro</a> (including libnds, libarm, etc).</p> <p>Does anyone know how to do this?</p>
[ { "answer_id": 10527, "author": "Cristián Romo", "author_id": 1256, "author_profile": "https://Stackoverflow.com/users/1256", "pm_score": 2, "selected": false, "text": "REG_BLDMOD REG_COLV REG_COLY REG_BLDMOD_SUB REG_COLV_SUB REG_COLY_SUB" }, { "answer_id": 119880, "author": "PypeBros", "author_id": 15304, "author_profile": "https://Stackoverflow.com/users/15304", "pm_score": 4, "selected": true, "text": "BLEND_SRC_SPRITE REG_BLDCNT[_SUB] ATTR0_TYPE_BLENDED ATTR2_PALETTE() ATTR2_ALPHA" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
7,211
<p>I currently have a relatively small (4 or 5 tables, 5000 rows) MySQL database that I would like to convert to an sqlite database. As I'd potentially have to do this more than once, I'd be grateful if anyone could recommend any useful tools, or at least any easily-replicated method.</p> <p>(I have complete admin access to the database/machines involved.)</p>
[ { "answer_id": 7218, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 2, "selected": false, "text": " tgl@moto~$ mysqldump old-database > old-database-dump.sql\n tgl@moto~$ sqlite3 -init old-database-dump.sql new-database\n" }, { "answer_id": 7298, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "SELECT * INSERT INTO" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/916/" ]
7,212
<p>What I'd like to do is something like the following:</p> <pre><code>FooClass.prototype.method = function():String { return "Something"; } var foo:FooClass = new FooClass(); foo.method(); </code></pre> <p>Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype.</p> <p>The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway.</p> <p>Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3.</p> <p>Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question. :) Also, upmods for the good suggestions.</p>
[ { "answer_id": 8886, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 3, "selected": true, "text": "foo[\"method\"]();\n foo.method();\n" }, { "answer_id": 9958, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": false, "text": "public class FooWrapper extends Foo {\n\n private var wrappedFoo : Foo;\n\n public function FooWrapper( foo : Foo ) {\n wrappedFoo = foo;\n }\n\n override public function methodFromFoo( ) : void {\n wrappedFoo.methodFromFoo();\n }\n\n override public function anotherMethodFromFoo( ) : void {\n wrappedFoo.anotherMethodFromFoo();\n }\n\n public function newMethodNotOnFoo( ) : String {\n return \"Hello world!\"\n }\n\n}\n Foo Foo FooWrapper FooWrapper" }, { "answer_id": 10884, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 2, "selected": false, "text": "package\n{\n public class Foo\n {\n public var foo:String;\n\n public function Foo()\n {\n foo = \"foo!\";\n }\n }\n}\n package\n{\n import flash.display.Sprite;\n\n public class footest extends Sprite\n {\n public function footest()\n {\n Foo.prototype.method = function():String\n {\n return \"Something\";\n }\n\n var foo:Foo = new Foo();\n trace(foo[\"method\"]());\n }\n }\n}\n" }, { "answer_id": 11259, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 2, "selected": false, "text": "public class SampleClass\n{\n public function SampleClass()\n {\n }\n\n public function method1():void {\n Alert.show(\"Hi\");\n }\n var actualClass:SampleClass = new SampleClass();\n\nvar QuickWrapper:Object = {\n ref: actualClass,\n method1: function():void {\n this.ref.method1();\n },\n method2: function():void {\n Alert.show(\"Hello!\");\n } \n};\n\nQuickWrapper.method1();\nQuickWrapper.method2();\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266/" ]
7,231
<p>Can anyone recommend software or a .NET library that will check for bounced emails and the reason for the bounce? I get bounced emails into a pop3 account that I can read then.</p> <p>I need it to keep my user database clean from invalid email addresses and want to automate this (mark user as invalid email).</p>
[ { "answer_id": 7249, "author": "Robert Ellison", "author_id": 2521991, "author_profile": "https://Stackoverflow.com/users/2521991", "pm_score": 2, "selected": false, "text": "TcpClient tcpClient = new TcpClient();\ntcpClient.Connect(POP3Server, POP3Port);\nNetworkStream stream = tcpClient.GetStream();\n int read = stream.Read(inBuffer, 0, inBuffer.Length);\nstring response = Encoding.ASCII.GetString(inBuffer, 0, read);\nif (response.IndexOf(\"+OK\") != 0) throw new ...;\n byte[] outBuffer = Encoding.ASCII.GetBytes(\"USER \" + account + \"\\r\\n\");\nstream.Write(outBuffer, 0, outBuffer.Length);\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925/" ]
7,237
<p>Our software must be able to run on SQL Server 2000 and 2005. To simplify development, we're running our SQL Server 2005 databases in compatibility level 80. However, database performance seems slower on SQL 2005 than on SQL 2000 in some cases (we have not confirmed this using benchmarks yet). Would upgrading the compatibility level to 90 improve performance on the SQL 2005 servers?</p>
[ { "answer_id": 7242, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 1, "selected": false, "text": "(*= and =*)" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799/" ]
7,244
<p>What I want to do is something like this: I have enums with combined flagged values.</p> <pre><code>public static class EnumExtension { public static bool IsSet&lt;T&gt;( this T input, T matchTo ) where T:enum //the constraint I want that doesn't exist in C#3 { return (input &amp; matchTo) != 0; } } </code></pre> <p>So then I could do:</p> <pre><code>MyEnum tester = MyEnum.FlagA | MyEnum.FlagB if( tester.IsSet( MyEnum.FlagA ) ) //act on flag a </code></pre> <p>Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.</p> <p>Does anyone know a workaround?</p>
[ { "answer_id": 7385, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": 4, "selected": false, "text": "public static bool IsSet( this Enum input, Enum matchTo )\n{\n return ( Convert.ToUInt32( input ) & Convert.ToUInt32( matchTo ) ) != 0;\n}\n" }, { "answer_id": 13517, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "public static class EnumExtension\n{\n public static bool IsSet<T>( this T input, T matchTo )\n {\n if (!typeof(T).IsEnum)\n {\n throw new ArgumentException(\"Must be an enum\", \"input\");\n }\n return (input & matchTo) != 0;\n }\n}\n" }, { "answer_id": 1409873, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "where T : struct, IEnumConstraint\n where T : struct, System.Enum\n IsSet Int64 UInt64 UInt64 tester.IsSet(MyFlags.A | MyFlags.C)\n IsSet" }, { "answer_id": 1416703, "author": "SLaks", "author_id": 34397, "author_profile": "https://Stackoverflow.com/users/34397", "pm_score": 3, "selected": false, "text": "public abstract class Enums<Temp> where Temp : class {\n public static TEnum Parse<TEnum>(string name) where TEnum : struct, Temp {\n return (TEnum)Enum.Parse(typeof(TEnum), name); \n }\n}\npublic abstract class Enums : Enums<Enum> { }\n\nEnums.IsSet<DateTimeKind>(\"Local\")\n Enums<Temp> Temp Enum" }, { "answer_id": 1416806, "author": "Brian Surowiec", "author_id": 39605, "author_profile": "https://Stackoverflow.com/users/39605", "pm_score": 1, "selected": false, "text": "public static class EnumExtensions\n{\n public static bool ContainsFlag(this Enum source, Enum flag)\n {\n var sourceValue = ToUInt64(source);\n var flagValue = ToUInt64(flag);\n\n return (sourceValue & flagValue) == flagValue;\n }\n\n public static bool ContainsAnyFlag(this Enum source, params Enum[] flags)\n {\n var sourceValue = ToUInt64(source);\n\n foreach (var flag in flags)\n {\n var flagValue = ToUInt64(flag);\n\n if ((sourceValue & flagValue) == flagValue)\n {\n return true;\n }\n }\n\n return false;\n }\n\n // found in the Enum class as an internal method\n private static ulong ToUInt64(object value)\n {\n switch (Convert.GetTypeCode(value))\n {\n case TypeCode.SByte:\n case TypeCode.Int16:\n case TypeCode.Int32:\n case TypeCode.Int64:\n return (ulong)Convert.ToInt64(value, CultureInfo.InvariantCulture);\n\n case TypeCode.Byte:\n case TypeCode.UInt16:\n case TypeCode.UInt32:\n case TypeCode.UInt64:\n return Convert.ToUInt64(value, CultureInfo.InvariantCulture);\n }\n\n throw new InvalidOperationException(\"Unknown enum type.\");\n }\n}\n" }, { "answer_id": 11574563, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 3, "selected": false, "text": "public class Sample\n{\n public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()\n { \n }\n public void MethodWithEnumConstraint<[EnumConstraint] T>()\n {\n }\n}\n public class Sample\n{\n public void MethodWithDelegateConstraint<T>() where T: Delegate\n {\n }\n\n public void MethodWithEnumConstraint<T>() where T: struct, Enum\n {\n }\n}\n" }, { "answer_id": 36078862, "author": "Jürgen Steinblock", "author_id": 98491, "author_profile": "https://Stackoverflow.com/users/98491", "pm_score": 0, "selected": false, "text": "ExtraConstraints struct IsEnum public static Converter<T, string> CreateConverter<T>() where T : struct\n {\n if (!typeof(T).IsEnum) throw new ArgumentException(\"Given Type is not an Enum\");\n return new Converter<T, string>(x => ((Enum)(object)x).GetEnumDescription());\n }\n" }, { "answer_id": 41278947, "author": "SoLaR", "author_id": 1011436, "author_profile": "https://Stackoverflow.com/users/1011436", "pm_score": 0, "selected": false, "text": " public class TestClass\n { }\n\n public struct TestStruct\n { }\n\n public enum TestEnum\n {\n e1, \n e2,\n e3\n }\n\n public static class TestEnumConstraintExtenssion\n {\n\n public static bool IsSet<TEnum>(this TEnum _this, TEnum flag)\n where TEnum : struct\n {\n return (((uint)Convert.ChangeType(_this, typeof(uint))) & ((uint)Convert.ChangeType(flag, typeof(uint)))) == ((uint)Convert.ChangeType(flag, typeof(uint)));\n }\n\n //public static TestClass ToTestClass(this string _this)\n //{\n // // #generates compile error (so no missuse)\n // return EnumConstraint.TryParse<TestClass>(_this);\n //}\n\n //public static TestStruct ToTestStruct(this string _this)\n //{\n // // #generates compile error (so no missuse)\n // return EnumConstraint.TryParse<TestStruct>(_this);\n //}\n\n public static TestEnum ToTestEnum(this string _this)\n {\n // #enum type works just fine (coding constraint to Enum type)\n return EnumConstraint.TryParse<TestEnum>(_this);\n }\n\n public static void TestAll()\n {\n TestEnum t1 = \"e3\".ToTestEnum();\n TestEnum t2 = \"e2\".ToTestEnum();\n TestEnum t3 = \"non existing\".ToTestEnum(); // default(TestEnum) for non existing \n\n bool b1 = t3.IsSet(TestEnum.e1); // you can ommit type\n bool b2 = t3.IsSet<TestEnum>(TestEnum.e2); // you can specify explicite type\n\n TestStruct t;\n // #generates compile error (so no missuse)\n //bool b3 = t.IsSet<TestEnum>(TestEnum.e1);\n\n }\n\n }\n using System;\n\n/// <summary>\n/// would be same as EnumConstraint_T&lt;Enum>Parse&lt;EnumType>(\"Normal\"),\n/// but writen like this it abuses constrain inheritence on System.Enum.\n/// </summary>\npublic class EnumConstraint : EnumConstraint_T<Enum>\n{\n\n}\n\n/// <summary>\n/// provides ability to constrain TEnum to System.Enum abusing constrain inheritence\n/// </summary>\n/// <typeparam name=\"TClass\">should be System.Enum</typeparam>\npublic abstract class EnumConstraint_T<TClass>\n where TClass : class\n{\n\n public static TEnum Parse<TEnum>(string value)\n where TEnum : TClass\n {\n return (TEnum)Enum.Parse(typeof(TEnum), value);\n }\n\n public static bool TryParse<TEnum>(string value, out TEnum evalue)\n where TEnum : struct, TClass // struct is required to ignore non nullable type error\n {\n evalue = default(TEnum);\n return Enum.TryParse<TEnum>(value, out evalue);\n }\n\n public static TEnum TryParse<TEnum>(string value, TEnum defaultValue = default(TEnum))\n where TEnum : struct, TClass // struct is required to ignore non nullable type error\n { \n Enum.TryParse<TEnum>(value, out defaultValue);\n return defaultValue;\n }\n\n public static TEnum Parse<TEnum>(string value, TEnum defaultValue = default(TEnum))\n where TEnum : struct, TClass // struct is required to ignore non nullable type error\n {\n TEnum result;\n if (Enum.TryParse<TEnum>(value, out result))\n return result;\n return defaultValue;\n }\n\n public static TEnum Parse<TEnum>(ushort value)\n {\n return (TEnum)(object)value;\n }\n\n public static sbyte to_i1<TEnum>(TEnum value)\n {\n return (sbyte)(object)Convert.ChangeType(value, typeof(sbyte));\n }\n\n public static byte to_u1<TEnum>(TEnum value)\n {\n return (byte)(object)Convert.ChangeType(value, typeof(byte));\n }\n\n public static short to_i2<TEnum>(TEnum value)\n {\n return (short)(object)Convert.ChangeType(value, typeof(short));\n }\n\n public static ushort to_u2<TEnum>(TEnum value)\n {\n return (ushort)(object)Convert.ChangeType(value, typeof(ushort));\n }\n\n public static int to_i4<TEnum>(TEnum value)\n {\n return (int)(object)Convert.ChangeType(value, typeof(int));\n }\n\n public static uint to_u4<TEnum>(TEnum value)\n {\n return (uint)(object)Convert.ChangeType(value, typeof(uint));\n }\n\n}\n" }, { "answer_id": 50289291, "author": "Ivan Ferić", "author_id": 444634, "author_profile": "https://Stackoverflow.com/users/444634", "pm_score": 5, "selected": false, "text": "public class UsingEnum<T> where T : System.Enum { }\n" }, { "answer_id": 50411982, "author": "Mik", "author_id": 1554208, "author_profile": "https://Stackoverflow.com/users/1554208", "pm_score": 3, "selected": false, "text": "public static TEnum Parse<TEnum>(string value) where TEnum : Enum\n{\n return (TEnum) Enum.Parse(typeof(TEnum), value);\n}\n public static TEnum? TryParse<TEnum>(string value) where TEnum : struct, Enum\n{\n if( Enum.TryParse(value, out TEnum res) )\n return res;\n else\n return null;\n}\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
7,245
<p>What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space?</p> <p>Let's say the screen looks like this ('#' represents filled area):</p> <pre><code>.................... ..............###### ##.................. .................### .................### #####............... #####............... #####............... </code></pre> <p>A probable solution is:</p> <pre><code>.................... ..............###### ##...++++++++++++... .....++++++++++++### .....++++++++++++### #####++++++++++++... #####++++++++++++... #####++++++++++++... </code></pre> <p>Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution?</p> <p><strong>Shog9</strong> wrote:</p> <blockquote> <p>Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)?</p> </blockquote> <p>Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any?</p>
[ { "answer_id": 7250, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 2, "selected": false, "text": " // 4. Outer double-for-loop to consider all possible positions \n // for topleft corner. \n for (int i=0; i < M; i++) {\n for (int j=0; j < N; j++) {\n\n // 2.1 With (i,j) as topleft, consider all possible bottom-right corners. \n\n for (int a=i; a < M; a++) {\n for (int b=j; b < N; b++) {\n" }, { "answer_id": 20039017, "author": "Daveed V.", "author_id": 2308239, "author_profile": "https://Stackoverflow.com/users/2308239", "pm_score": 5, "selected": false, "text": "#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n int one;\n int two;\n} Pair;\n\nPair best_ll = { 0, 0 };\nPair best_ur = { -1, -1 };\nint best_area = 0;\n\nint *c; /* Cache */\nPair *s; /* Stack */\nint top = 0; /* Top of stack */\n\nvoid push(int a, int b) {\n s[top].one = a;\n s[top].two = b;\n ++top;\n}\n\nvoid pop(int *a, int *b) {\n --top;\n *a = s[top].one;\n *b = s[top].two;\n}\n\n\nint M, N; /* Dimension of input; M is length of a row. */\n\nvoid update_cache() {\n int m;\n char b;\n for (m = 0; m!=M; ++m) {\n scanf(\" %c\", &b);\n fprintf(stderr, \" %c\", b);\n if (b=='0') {\n c[m] = 0;\n } else { ++c[m]; }\n }\n fprintf(stderr, \"\\n\");\n}\n\n\nint main() {\n int m, n;\n scanf(\"%d %d\", &M, &N);\n fprintf(stderr, \"Reading %dx%d array (1 row == %d elements)\\n\", M, N, M);\n c = (int*)malloc((M+1)*sizeof(int));\n s = (Pair*)malloc((M+1)*sizeof(Pair));\n for (m = 0; m!=M+1; ++m) { c[m] = s[m].one = s[m].two = 0; }\n /* Main algorithm: */\n for (n = 0; n!=N; ++n) {\n int open_width = 0;\n update_cache();\n for (m = 0; m!=M+1; ++m) {\n if (c[m]>open_width) { /* Open new rectangle? */\n push(m, open_width);\n open_width = c[m];\n } else /* \"else\" optional here */\n if (c[m]<open_width) { /* Close rectangle(s)? */\n int m0, w0, area;\n do {\n pop(&m0, &w0);\n area = open_width*(m-m0);\n if (area>best_area) {\n best_area = area;\n best_ll.one = m0; best_ll.two = n;\n best_ur.one = m-1; best_ur.two = n-open_width+1;\n }\n open_width = w0;\n } while (c[m]<open_width);\n open_width = c[m];\n if (open_width!=0) {\n push(m0, w0);\n }\n }\n }\n }\n fprintf(stderr, \"The maximal rectangle has area %d.\\n\", best_area);\n fprintf(stderr, \"Location: [col=%d, row=%d] to [col=%d, row=%d]\\n\",\n best_ll.one+1, best_ll.two+1, best_ur.one+1, best_ur.two+1);\n return 0;\n}\n 16 12\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0\n0 0 0 1 1 0 0 1 0 0 0 1 1 0 1 0\n0 0 0 1 1 0 1 1 1 0 1 1 1 0 1 0\n0 0 0 0 1 1 * * * * * * 0 0 1 0\n0 0 0 0 0 0 * * * * * * 0 0 1 0\n0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0\n0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 0 \n0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0\n The maximal rectangle has area 12.\nLocation: [col=7, row=6] to [col=12, row=5]\n" }, { "answer_id": 37994342, "author": "Spike2050", "author_id": 1167159, "author_profile": "https://Stackoverflow.com/users/1167159", "pm_score": 2, "selected": false, "text": "package com.test;\n\nimport java.util.Stack;\n\npublic class Test {\n\n public static void main(String[] args) {\n boolean[][] test2 = new boolean[][] { new boolean[] { false, true, true, false },\n new boolean[] { false, true, true, false }, new boolean[] { false, true, true, false },\n new boolean[] { false, true, false, false } };\n solution(test2);\n }\n\n private static class Point {\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int x;\n public int y;\n }\n\n public static int[] updateCache(int[] cache, boolean[] matrixRow, int MaxX) {\n for (int m = 0; m < MaxX; m++) {\n if (!matrixRow[m]) {\n cache[m] = 0;\n } else {\n cache[m]++;\n }\n }\n return cache;\n }\n\n public static void solution(boolean[][] matrix) {\n Point best_ll = new Point(0, 0);\n Point best_ur = new Point(-1, -1);\n int best_area = 0;\n\n final int MaxX = matrix[0].length;\n final int MaxY = matrix.length;\n\n Stack<Point> stack = new Stack<Point>();\n int[] cache = new int[MaxX + 1];\n\n for (int m = 0; m != MaxX + 1; m++) {\n cache[m] = 0;\n }\n\n for (int n = 0; n != MaxY; n++) {\n int openWidth = 0;\n cache = updateCache(cache, matrix[n], MaxX);\n for (int m = 0; m != MaxX + 1; m++) {\n if (cache[m] > openWidth) {\n stack.push(new Point(m, openWidth));\n openWidth = cache[m];\n } else if (cache[m] < openWidth) {\n int area;\n Point p;\n do {\n p = stack.pop();\n area = openWidth * (m - p.x);\n if (area > best_area) {\n best_area = area;\n best_ll.x = p.x;\n best_ll.y = n;\n best_ur.x = m - 1;\n best_ur.y = n - openWidth + 1;\n }\n openWidth = p.y;\n } while (cache[m] < openWidth);\n openWidth = cache[m];\n if (openWidth != 0) {\n stack.push(p);\n }\n }\n }\n }\n\n System.out.printf(\"The maximal rectangle has area %d.\\n\", best_area);\n System.out.printf(\"Location: [col=%d, row=%d] to [col=%d, row=%d]\\n\", best_ll.x + 1, best_ll.y + 1,\n best_ur.x + 1, best_ur.y + 1);\n }\n\n}\n" }, { "answer_id": 55718418, "author": "Primusa", "author_id": 8112138, "author_profile": "https://Stackoverflow.com/users/8112138", "pm_score": 3, "selected": false, "text": "O(NM) h l r h * (r - l) h l r h l r matrix[i] h l r height left right height[j] matrix[i][j] height h new_height[j] = old_height[j] + 1 if row[j] == '1' else 0\n left left left new_left[j] = max(old_left[j], cur_left)\n cur_left right left new_right[j] = min(old_right[j], cur_right)\n cur_right def maximalRectangle(matrix):\n if not matrix: return 0\n\n m = len(matrix)\n n = len(matrix[0])\n\n left = [0] * n # initialize left as the leftmost boundary possible\n right = [n] * n # initialize right as the rightmost boundary possible\n height = [0] * n\n\n maxarea = 0\n\n for i in range(m):\n\n cur_left, cur_right = 0, n\n # update height\n for j in range(n):\n if matrix[i][j] == '1': height[j] += 1\n else: height[j] = 0\n # update left\n for j in range(n):\n if matrix[i][j] == '1': left[j] = max(left[j], cur_left)\n else:\n left[j] = 0\n cur_left = j + 1\n # update right\n for j in range(n-1, -1, -1):\n if matrix[i][j] == '1': right[j] = min(right[j], cur_right)\n else:\n right[j] = n\n cur_right = j\n # update the area\n for j in range(n):\n maxarea = max(maxarea, height[j] * (right[j] - left[j]))\n\n return maxarea\n" }, { "answer_id": 64899570, "author": "emu", "author_id": 797845, "author_profile": "https://Stackoverflow.com/users/797845", "pm_score": 1, "selected": false, "text": "function maxRectangle(mask) {\n var best = {area: 0}\n const width = mask[0].length\n const depth = Array(width).fill(0)\n for (var y = 0; y < mask.length; y++) {\n const ranges = Array()\n for (var x = 0; x < width; x++) {\n const d = depth[x] = mask[y][x] ? depth[x] + 1 : 0\n if (!ranges.length || ranges[ranges.length - 1].height < d) {\n ranges.push({left: x, height: d})\n } else {\n for (var j = ranges.length - 1; j >= 0 && ranges[j].height >= d; j--) {\n const {left, height} = ranges[j]\n const area = (x - left) * height\n if (area > best.area) {\n best = {area, left, top: y + 1 - height, right: x, bottom: y + 1}\n }\n }\n ranges.splice(j+2)\n ranges[j+1].height = d\n }\n }\n }\n return best;\n}\n\nvar example = [\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],\n[0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],\n[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]\n\nconsole.log(maxRectangle(example))" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/758/" ]
7,260
<p>How do I setup Public-Key Authentication for SSH?</p>
[ { "answer_id": 9095, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 8, "selected": true, "text": "ssh-keygen\n id_rsa id_rsa.pub ~/.ssh/authorized_keys id_rsa.pub chmod 600 id_rsa* chmod 600 ~/.ssh/id_rsa*\n ~/.ssh/authorized_keys chmod 600 chmod 600 ~/.ssh/authorized_keys\n ssh remote.machine ssh-agent ssh-agent `ssh-agent`\n echo $SSH_AUTH_SOCK ssh-add ~/.ssh/id_rsa\n ssh-add -D" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
7,272
<p>Alright, so maybe I shouldn't have shrunk this question sooo much... I have seen the post on <a href="https://stackoverflow.com/questions/622/most-efficient-code-for-the-first-10000-prime-numbers">the most efficient way to find the first 10000 primes</a>. I'm looking for <strong>all possible ways</strong>. The goal is to have a one stop shop for primality tests. Any and all tests people know for finding prime numbers are welcome.</p> <p>And so:</p> <ul> <li><strong>What are all the different ways of finding primes?</strong></li> </ul>
[ { "answer_id": 7476, "author": "goric", "author_id": 940, "author_profile": "https://Stackoverflow.com/users/940", "pm_score": 2, "selected": false, "text": "//Assuming theInteger is the number to be tested for primality.\n// Check if theInteger is divisible by 2. If not, run this loop.\n// This loop skips all even numbers.\nfor( int i = 3; i < sqrt(theInteger); i + 2) \n{\n if( theInteger % i == 0) \n {\n //getting here denotes that theInteger is not prime \n // somehow indicate that some number, i, divides it and break\n break;\n }\n}\n" }, { "answer_id": 7487, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "a(1) = 7\na(n) = a(n-1) + gcd(n,a(n-1)). \n b(1) = 1\nb(n) = b(n-1) + lcm(n,b(n-1))\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
7,277
<p>I'm generating some XML documents and when it comes to the address part I have fragments that look like this:</p> <pre><code>&lt;Address&gt;15 Sample St Example Bay Some Country&lt;/Address&gt; </code></pre> <p>The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to &lt;br/&gt; tags.</p> <p>This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead?</p> <pre><code>&lt;Address&gt;&lt;Line&gt;15 Sample St&lt;/Line&gt; &lt;Line&gt;Example Bay&lt;/Line&gt; &lt;Line&gt;Some Country&lt;/Line&gt;&lt;/Address&gt; </code></pre> <p>Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..</p>
[ { "answer_id": 7282, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 2, "selected": false, "text": "<Something>\n <Contains>\n <An>\n <Address>15 Sample St\nExample Bay\nSome Country</Address>\n </An>\n </Contains>\n</Something>\n <br /> \\n" }, { "answer_id": 7331, "author": "Valters Vingolds", "author_id": 885, "author_profile": "https://Stackoverflow.com/users/885", "pm_score": -1, "selected": false, "text": "<br/> &#x000D;" }, { "answer_id": 7336, "author": "Ran Biron", "author_id": 931, "author_profile": "https://Stackoverflow.com/users/931", "pm_score": 0, "selected": false, "text": "<Line>" }, { "answer_id": 7358, "author": "Rob Thomas", "author_id": 803, "author_profile": "https://Stackoverflow.com/users/803", "pm_score": 2, "selected": false, "text": "<Address Street=\"15 Sample St\" City=\"Example Bay\" State=\"\" Country=\"Some Country\"/>\n" }, { "answer_id": 17033, "author": "Boris Terzic", "author_id": 1996, "author_profile": "https://Stackoverflow.com/users/1996", "pm_score": 1, "selected": false, "text": "<Address xmlns=\"http://www.w3.org/1999/xhtml\">15 Sample St<br />Example Bay<br />Some Country</Address>\n" }, { "answer_id": 25089, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 2, "selected": false, "text": "<Address>15 Sample St\nExample Bay\nSome Country</Address>\n <Address><![CDATA[15 Sample St\nExample Bay\nSome Country]]></Address>\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/755/" ]
7,284
<p>What does the expression "Turing Complete" mean? </p> <p>Can you give a simple explanation, without going into too many theoretical details?</p>
[ { "answer_id": 1610655, "author": "Gordon Gustafson", "author_id": 89989, "author_profile": "https://Stackoverflow.com/users/89989", "pm_score": 7, "selected": false, "text": "+ - * / push pop ( ) ( ) ( ) [ ] ([)] ([]] () []" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198/" ]
7,287
<p>Lately I had to change some code on older systems where not all of the code has unit tests.<br> Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard.<br> Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it.<br> Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed?</p>
[ { "answer_id": 7296, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 4, "selected": true, "text": "public class MyClass {\n public MyClass() {\n // undesirable DB logic\n }\n}\n public class MyClass {\n public MyClass() {\n loadFromDB();\n }\n\n protected void loadFromDB() {\n // undesirable DB logic\n }\n}\n public class MyClassTest {\n public void testSomething() {\n MyClass myClass = new MyClassWrapper();\n // test it\n }\n\n private static class MyClassWrapper extends MyClass {\n @Override\n protected void loadFromDB() {\n // some mock logic\n }\n }\n}\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/573/" ]
7,348
<p>My requirements:</p> <ul> <li>Support .NET Compact Framework 2.0 and Windows Mobile 6.0 devices.</li> <li>Only need to unzip the contents to a directory on a storage card. Creation of zip files is not required.</li> <li>Must be able to use in corporate/commercial software.</li> <li>Can be open source, but not have GPL or other viral license.</li> </ul> <p>I've seen the <a href="http://xceed.com/Zip_NET_CF_Intro.html" rel="noreferrer">Xceed Zip for CF</a> library. What other options are there?</p>
[ { "answer_id": 388253, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 3, "selected": false, "text": " try\n {\n using (var zip1 = Ionic.Zip.ZipFile.Read(zipToUnpack))\n {\n foreach (var entry in zip1)\n {\n entry.Extract(dir, ExtractExistingFileAction.OverwriteSilently);\n }\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Exception! \" + ex);\n }\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
7,364
<p>Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)</p> <p>I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?</p> <p>On the front-end</p>
[ { "answer_id": 7455, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 7, "selected": true, "text": "<?php\nrequire_once 'Zend/Pdf.php';\n\n$pdf = Zend_Pdf::load('blank.pdf');\n$page = $pdf->pages[0];\n$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);\n$page->setFont($font, 12);\n$page->drawText('Hello world!', 72, 720);\n$pdf->save('zend.pdf');\n" }, { "answer_id": 1598933, "author": "Nitin", "author_id": 193592, "author_profile": "https://Stackoverflow.com/users/193592", "pm_score": -1, "selected": false, "text": "<?php\n\n//getting new instance\n$pdfFile = new_pdf();\n\nPDF_open_file($pdfFile, \" \");\n\n//document info\npdf_set_info($pdfFile, \"Auther\", \"Ahmed Elbshry\");\npdf_set_info($pdfFile, \"Creator\", \"Ahmed Elbshry\");\npdf_set_info($pdfFile, \"Title\", \"PDFlib\");\npdf_set_info($pdfFile, \"Subject\", \"Using PDFlib\");\n\n//starting our page and define the width and highet of the document\npdf_begin_page($pdfFile, 595, 842);\n\n//check if Arial font is found, or exit\nif($font = PDF_findfont($pdfFile, \"Arial\", \"winansi\", 1)) {\n PDF_setfont($pdfFile, $font, 12);\n} else {\n echo (\"Font Not Found!\");\n PDF_end_page($pdfFile);\n PDF_close($pdfFile);\n PDF_delete($pdfFile);\n exit();\n}\n\n//start writing from the point 50,780\nPDF_show_xy($pdfFile, \"This Text In Arial Font\", 50, 780);\nPDF_end_page($pdfFile);\nPDF_close($pdfFile);\n\n//store the pdf document in $pdf\n$pdf = PDF_get_buffer($pdfFile);\n//get the len to tell the browser about it\n$pdflen = strlen($pdfFile);\n\n//telling the browser about the pdf document\nheader(\"Content-type: application/pdf\");\nheader(\"Content-length: $pdflen\");\nheader(\"Content-Disposition: inline; filename=phpMade.pdf\");\n//output the document\nprint($pdf);\n//delete the object\nPDF_delete($pdfFile);\n?>\n" }, { "answer_id": 4184326, "author": "metatron", "author_id": 508238, "author_profile": "https://Stackoverflow.com/users/508238", "pm_score": 6, "selected": false, "text": "require_once('fpdf.php'); \nrequire_once('fpdi.php'); \n$pdf = new FPDI();\n\n$pdf->AddPage(); \n\n$pdf->setSourceFile('gift_coupon.pdf'); \n// import page 1 \n$tplIdx = $this->pdf->importPage(1); \n//use the imported page and place it at point 0,0; calculate width and height\n//automaticallay and ajust the page size to the size of the imported page \n$this->pdf->useTemplate($tplIdx, 0, 0, 0, 0, true); \n\n// now write some text above the imported page \n$this->pdf->SetFont('Arial', '', '13'); \n$this->pdf->SetTextColor(0,0,0);\n//set position in pdf document\n$this->pdf->SetXY(20, 20);\n//first parameter defines the line height\n$this->pdf->Write(0, 'gift code');\n//force the browser to download the output\n$this->pdf->Output('gift_coupon_generated.pdf', 'D');\n" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
7,398
<p>I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes:</p> <p>I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly <a href="http://www.gnu.org/software/autoconf/manual/autoconf.html#Subdirectories" rel="nofollow noreferrer">straightforward</a>, but in this case there is a tiny snag: each project generates its own <code>config.h</code> file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:</p> <pre><code>... warning: "VERSION" redefined ... warning: this is the location of the previous definition ... warning: "PACKAGE" redefined ... warning: this is the location of the previous definition </code></pre> <p>These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is <a href="http://sourceware.org/ml/automake/2004-03/msg00130.html" rel="nofollow noreferrer">this</a> thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas?</p>
[ { "answer_id": 9214, "author": "David Joyner", "author_id": 1146, "author_profile": "https://Stackoverflow.com/users/1146", "pm_score": 2, "selected": false, "text": "config.h sed -e 's/.*PACKAGE_.*//' < config.h > config.h.sed && mv config.h.sed config.h\n" }, { "answer_id": 11269, "author": "Jason Day", "author_id": 737, "author_profile": "https://Stackoverflow.com/users/737", "pm_score": 1, "selected": false, "text": "#include config.h config.h $(top_builddir)/config.h config.h $(top_builddir)" }, { "answer_id": 26994, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 4, "selected": true, "text": "config.h config.h config.h config.h config.h config.h config.h config.h" } ]
2008/08/10
[ "https://Stackoverflow.com/questions/7398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/737/" ]
7,470
<p>After a couple of hours fighting with the <a href="http://gallery.menalto.com/" rel="nofollow noreferrer">Gallery2</a> <a href="http://codex.gallery2.org/Gallery2:Modules:rss" rel="nofollow noreferrer">RSS module</a> and getting only the message, "no feeds have yet been defined", I gave up. Based on <a href="http://www.google.com/search?q=%22no+feeds+have+yet+been+defined%22" rel="nofollow noreferrer">a Google search for "no feeds have yet been defined"</a>, this is a pretty common problem. Do you have any tips and/or tricks for getting the Gallery2 RSS module to work? Or any tips for a relatively-PHP-ignorant developer trying to debug problems with this PHP application?</p>
[ { "answer_id": 7471, "author": "ESV", "author_id": 150, "author_profile": "https://Stackoverflow.com/users/150", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python\n\"\"\"A CGI script to produce an RSS feed of top-level Gallery2 albums.\"\"\"\n\n#import cgi\n#import cgitb; cgitb.enable()\nfrom time import gmtime, strftime\nimport MySQLdb\n\nALBUM_QUERY = '''\n select g_id, g_title, g_originationTimestamp\n from g_Item\n where g_canContainChildren = 1 \n order by g_originationTimestamp desc\n limit 0, 20\n '''\n\nRSS_TEMPLATE = '''Content-Type: text/xml\n\n<?xml version=\"1.0\"?>\n<rss version=\"2.0\">\n <channel>\n <title>TITLE</title>\n <link>http://example.com/gallery2/main.php</link>\n <description>DESCRIPTION</description>\n <ttl>1440</ttl>\n%s\n </channel>\n</rss>\n'''\n\nITEM_TEMPLATE = '''\n <item>\n <title>%s</title>\n <link>http://example.com/gallery2/main.php?g2_itemId=%s</link>\n <description>%s</description>\n <pubDate>%s</pubDate>\n </item>\n'''\n\ndef to_item(row):\n item_id = row[0]\n title = row[1]\n date = strftime(\"%a, %d %b %Y %H:%M:%S GMT\", gmtime(row[2]))\n return ITEM_TEMPLATE % (title, item_id, title, date)\n\nconn = MySQLdb.connect(host = \"HOST\",\n user = \"USER\",\n passwd = \"PASSWORD\",\n db = \"DATABASE\")\ncurs = conn.cursor()\ncurs.execute(ALBUM_QUERY)\nprint RSS_TEMPLATE % ''.join([ to_item(row) for row in curs.fetchall() ])\ncurs.close()\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150/" ]
7,472
<p>Can anyone point me to a good resource (or throw me a clue) to show me how to do DataBinding to controls (ComboBox, ListBox, etc.) in WPF? I'm at a bit of a loss when all my WinForms niceities are taken away from me, and I'm not all that bright to start with...</p>
[ { "answer_id": 7475, "author": "Leon Bambrick", "author_id": 49, "author_profile": "https://Stackoverflow.com/users/49", "pm_score": 2, "selected": false, "text": "private void OnInit(object sender, EventArgs e)\n{\n //myDataSet is some IEnumerable \n\n // myListBox is a ListBox control.\n // Set the DataContext of the ListBox to myDataSet\n myListBox.DataContext = myDataSet;\n}\n <ListBox Name=\"myListBox\" Height=\"200\"\n ItemsSource=\"{Binding Path=BookTable}\"\n ItemTemplate =\"{StaticResource BookItemTemplate}\"/>\n" }, { "answer_id": 397832, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 2, "selected": false, "text": "public class EmailAddress\n{\n public string AddressAsString { get; set; }\n}\n\npublic class Person\n{\n public IEnumerable<EmailAddress> EmailAddresses { get; }\n public EmailAddress MainEmailAddress { get; set; }\n}\n <ComboBox ItemsSource=\"{Binding EmailAddresses}\" SelectedItem=\"{Binding MainEmailAddress}\">\n <ComboBox.ItemTemplate>\n <DataTemplate>\n <ComboBoxItem Content=\"{Binding AddressAsString}\"/>\n </DataTemplate>\n </ComboBox.ItemTemplate>\n</ComboBox>\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856/" ]
7,477
<p>I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.</p> <p>Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.</p> <p>Here's a screenshot of it currently.</p> <p><img src="https://i.stack.imgur.com/XK48E.png" alt="ISO Address"></p> <p>Any ideas?</p> <hr> <p>@Chris</p> <p>A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.</p> <p>I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.</p> <p>I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).</p> <p>It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.</p> <p>Though if someone comes up with another way to approach the problem I'm open to that too.</p> <hr> <p>I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.</p> <pre><code>resizeIt = function() { var str = $('iso_address').value; var cols = $('iso_address').cols; var linecount = 0; $A(str.split("\n")).each(function(l) { linecount += 1 + Math.floor(l.length / cols); // Take into account long lines }) $('iso_address').rows = linecount; }; </code></pre>
[ { "answer_id": 7523, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": true, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n <head>\n <script src=\"http://www.google.com/jsapi\"></script>\n <script language=\"javascript\">\n google.load('prototype', '1.6.0.2');\n </script>\n </head>\n\n <body>\n <textarea id=\"text-area\" rows=\"1\" cols=\"50\"></textarea>\n\n <script type=\"text/javascript\" language=\"javascript\">\n resizeIt = function() {\n var str = $('text-area').value;\n var cols = $('text-area').cols;\n\n var linecount = 0;\n $A(str.split(\"\\n\")).each( function(l) {\n linecount += Math.ceil( l.length / cols ); // Take into account long lines\n })\n $('text-area').rows = linecount + 1;\n };\n\n // You could attach to keyUp, etc. if keydown doesn't work\n Event.observe('text-area', 'keydown', resizeIt );\n\n resizeIt(); //Initial on load\n </script>\n </body>\n</html>\n" }, { "answer_id": 7875, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 5, "selected": false, "text": "function FitToContent(id, maxHeight)\n{\n var text = id && id.style ? id : document.getElementById(id);\n if (!text)\n return;\n\n /* Accounts for rows being deleted, pixel value may need adjusting */\n if (text.clientHeight == text.scrollHeight) {\n text.style.height = \"30px\";\n }\n\n var adjustedHeight = text.clientHeight;\n if (!maxHeight || maxHeight > adjustedHeight)\n {\n adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);\n if (maxHeight)\n adjustedHeight = Math.min(maxHeight, adjustedHeight);\n if (adjustedHeight > text.clientHeight)\n text.style.height = adjustedHeight + \"px\";\n }\n}\n $(\"#post-text\").keyup(function()\n{\n FitToContent(this, document.documentElement.clientHeight)\n});\n" }, { "answer_id": 68428, "author": "Mike", "author_id": 841, "author_profile": "https://Stackoverflow.com/users/841", "pm_score": 2, "selected": false, "text": "var TextAreaResize = Class.create();\nTextAreaResize.prototype = {\n initialize: function(element, options) {\n element = $(element);\n this.element = element;\n\n this.options = Object.extend(\n {},\n options || {});\n\n Event.observe(this.element, 'keyup',\n this.onKeyUp.bindAsEventListener(this));\n this.onKeyUp();\n },\n\n onKeyUp: function() {\n // We need this variable because \"this\" changes in the scope of the\n // function below.\n var cols = this.element.cols;\n\n var linecount = 0;\n $A(this.element.value.split(\"\\n\")).each(function(l) {\n // We take long lines into account via the cols divide.\n linecount += 1 + Math.floor(l.length / cols);\n })\n\n this.element.rows = linecount;\n }\n}\n new TextAreaResize('textarea_id_name_here');\n" }, { "answer_id": 946565, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function resizeIt( id, maxHeight, minHeight ) {\n var text = id && id.style ? id : document.getElementById(id);\n var str = text.value;\n var cols = text.cols;\n var linecount = 0;\n var arStr = str.split( \"\\n\" );\n $(arStr).each(function(s) {\n linecount = linecount + 1 + Math.floor(arStr[s].length / cols); // take into account long lines\n });\n linecount++;\n linecount = Math.max(minHeight, linecount);\n linecount = Math.min(maxHeight, linecount);\n text.rows = linecount;\n};\n" }, { "answer_id": 948445, "author": "Jeremy Kauffman", "author_id": 82124, "author_profile": "https://Stackoverflow.com/users/82124", "pm_score": 3, "selected": false, "text": "//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js\nif (window.Widget == undefined) window.Widget = {}; \n\nWidget.Textarea = Class.create({\n initialize: function(textarea, options)\n {\n this.textarea = $(textarea);\n this.options = $H({\n 'min_height' : 30,\n 'max_length' : 400\n }).update(options);\n\n this.textarea.observe('keyup', this.refresh.bind(this));\n\n this._shadow = new Element('div').setStyle({\n lineHeight : this.textarea.getStyle('lineHeight'),\n fontSize : this.textarea.getStyle('fontSize'),\n fontFamily : this.textarea.getStyle('fontFamily'),\n position : 'absolute',\n top: '-10000px',\n left: '-10000px',\n width: this.textarea.getWidth() + 'px'\n });\n this.textarea.insert({ after: this._shadow });\n\n this._remainingCharacters = new Element('p').addClassName('remainingCharacters');\n this.textarea.insert({after: this._remainingCharacters}); \n this.refresh(); \n },\n\n refresh: function()\n { \n this._shadow.update($F(this.textarea).replace(/\\n/g, '<br/>'));\n this.textarea.setStyle({\n height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'\n });\n\n var remaining = this.options.get('max_length') - $F(this.textarea).length;\n this._remainingCharacters.update(Math.abs(remaining) + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));\n }\n});\n new Widget.Textarea('element_id') new Widget.Textarea('element_id', { max_length: 600, min_height: 50}) Event.observe(window, 'load', function() {\n $$('textarea').each(function(textarea) {\n new Widget.Textarea(textarea);\n }); \n});\n" }, { "answer_id": 1820197, "author": "lorem monkey", "author_id": 221381, "author_profile": "https://Stackoverflow.com/users/221381", "pm_score": 1, "selected": false, "text": "/**\n * Prototype Widget: Textarea\n * Automatically resizes a textarea and displays the number of remaining chars\n * \n * From: http://stackoverflow.com/questions/7477/autosizing-textarea\n * Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js\n */\nif (window.Widget == undefined) window.Widget = {}; \n\nWidget.Textarea = Class.create({\n initialize: function(textarea, options){\n this.textarea = $(textarea);\n this.options = $H({\n 'min_height' : 30,\n 'max_length' : 400\n }).update(options);\n\n this.textarea.observe('keyup', this.refresh.bind(this));\n\n this._shadow = new Element('div').setStyle({\n lineHeight : this.textarea.getStyle('lineHeight'),\n fontSize : this.textarea.getStyle('fontSize'),\n fontFamily : this.textarea.getStyle('fontFamily'),\n position : 'absolute',\n top: '-10000px',\n left: '-10000px',\n width: this.textarea.getWidth() + 'px'\n });\n this.textarea.insert({ after: this._shadow });\n\n this._remainingCharacters = new Element('p').addClassName('remainingCharacters');\n this.textarea.insert({after: this._remainingCharacters}); \n this.refresh(); \n },\n\n refresh: function(){ \n this._shadow.update($F(this.textarea).replace(/\\n/g, '<br/>'));\n this.textarea.setStyle({\n height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'\n });\n\n // Keep the text/character count inside the limits:\n if($F(this.textarea).length > this.options.get('max_length')){\n text = $F(this.textarea).substring(0, this.options.get('max_length'));\n this.textarea.value = text;\n return false;\n }\n\n var remaining = this.options.get('max_length') - $F(this.textarea).length;\n this._remainingCharacters.update(Math.abs(remaining) + ' characters remaining'));\n }\n});\n" }, { "answer_id": 2032642, "author": "Jan Miksovsky", "author_id": 76472, "author_profile": "https://Stackoverflow.com/users/76472", "pm_score": 6, "selected": false, "text": "textarea div textarea div div textarea document.addEventListener('DOMContentLoaded', () => {\n textArea.addEventListener('change', autosize, false)\n textArea.addEventListener('keydown', autosize, false)\n textArea.addEventListener('keyup', autosize, false)\n autosize()\n}, false)\n\nfunction autosize() {\n // Copy textarea contents to div browser will calculate correct height\n // of copy, which will make overall container taller, which will make\n // textarea taller.\n textCopy.innerHTML = textArea.value.replace(/\\n/g, '<br/>')\n} html, body, textarea {\n font-family: sans-serif;\n font-size: 14px;\n}\n\n.textarea-container {\n position: relative;\n}\n\n.textarea-container > div, .textarea-container > textarea {\n word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */\n box-sizing: border-box;\n padding: 2px;\n width: 100%;\n}\n\n.textarea-container > textarea {\n overflow: hidden;\n position: absolute;\n height: 100%;\n}\n\n.textarea-container > div {\n padding-bottom: 1.5em; /* A bit more than one additional line of text. */ \n visibility: hidden;\n} <div class=\"textarea-container\">\n <textarea id=\"textArea\"></textarea>\n <div id=\"textCopy\"></div>\n</div>" }, { "answer_id": 2046661, "author": "Larry", "author_id": 248584, "author_profile": "https://Stackoverflow.com/users/248584", "pm_score": 1, "selected": false, "text": "<style>\n TEXTAREA { line-height: 14px; font-size: 12px; font-family: arial }\n</style>\n" }, { "answer_id": 3094600, "author": "Alex", "author_id": 326938, "author_profile": "https://Stackoverflow.com/users/326938", "pm_score": 1, "selected": false, "text": "$(\"#sometextarea\").textareacontrol();\n $(\"textarea\").textareacontrol();\n" }, { "answer_id": 3157451, "author": "Gyan", "author_id": 381047, "author_profile": "https://Stackoverflow.com/users/381047", "pm_score": 3, "selected": false, "text": "$(document).ready(function () {\n $('.ExpandableTextCSS').autoResize({\n // On resize:\n onResize: function () {\n $(this).css({ opacity: 0.8 });\n },\n // After resize:\n animateCallback: function () {\n $(this).css({ opacity: 1 });\n },\n // Quite slow animation:\n animateDuration: 300,\n // More extra space:\n extraSpace:20,\n //Textarea height limit\n limit:10\n });\n});\n" }, { "answer_id": 3409937, "author": "memical", "author_id": 322622, "author_profile": "https://Stackoverflow.com/users/322622", "pm_score": 3, "selected": false, "text": "JQuery $(document).ready(function() {\n var $abc = $(\"#abc\");\n $abc.css(\"height\", $abc.attr(\"scrollHeight\"));\n})\n abc teaxtarea" }, { "answer_id": 4596541, "author": "WNRosenberg", "author_id": 332472, "author_profile": "https://Stackoverflow.com/users/332472", "pm_score": 1, "selected": false, "text": "$(document).ready(function() {\n var $textarea = $(\"p.body textarea\");\n $textarea.css(\"height\", ($textarea.attr(\"scrollHeight\") + 20));\n $textarea.keyup(function(){\n var current_height = $textarea.css(\"height\").replace(\"px\", \"\")*1;\n if (current_height + 5 <= $textarea.attr(\"scrollHeight\")) {\n $textarea.css(\"height\", ($textarea.attr(\"scrollHeight\") + 20));\n }\n });\n});\n" }, { "answer_id": 7379509, "author": "Anatoly Mironov", "author_id": 632117, "author_profile": "https://Stackoverflow.com/users/632117", "pm_score": 2, "selected": false, "text": "height() $(document).ready(function() {\n $textarea = $(\"#my-textarea\");\n\n // There is some diff between scrollheight and height:\n // padding-top and padding-bottom\n var diff = $textarea.prop(\"scrollHeight\") - $textarea.height();\n $textarea.live(\"keyup\", function() {\n var height = $textarea.prop(\"scrollHeight\") - diff;\n $textarea.height(height);\n });\n});\n" }, { "answer_id": 9572832, "author": "Eduardo Mass", "author_id": 1250651, "author_profile": "https://Stackoverflow.com/users/1250651", "pm_score": 2, "selected": false, "text": "ready <div id=\"divTable\">\n <textarea ID=\"txt\" Rows=\"1\" TextMode=\"MultiLine\" />\n</div>\n\n$(document).ready(function () {\n var heightTextArea = $('#txt').height();\n var divTable = document.getElementById('divTable');\n $('#txt').attr('rows', parseInt(parseInt(divTable .style.height) / parseInt(altoFila)));\n});\n" }, { "answer_id": 15031691, "author": "Pat Murray", "author_id": 1210319, "author_profile": "https://Stackoverflow.com/users/1210319", "pm_score": 1, "selected": false, "text": "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <title>Automatic Resize TextBox</title>\n <script type=\"text/javascript\">\n function setHeight(txtarea) {\n txtarea.style.height = txtdesc.scrollHeight + \"px\";\n }\n </script>\n </head>\n\n <body>\n <form id=\"form1\" runat=\"server\">\n <asp:TextBox ID=\"txtarea\" runat= \"server\" TextMode=\"MultiLine\" onkeyup=\"setHeight(this);\" onkeydown=\"setHeight(this);\" />\n </form>\n </body>\n</html>\n" }, { "answer_id": 15686827, "author": "user1566694", "author_id": 1566694, "author_profile": "https://Stackoverflow.com/users/1566694", "pm_score": 2, "selected": false, "text": "textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }\n // Make all textareas auto-resize vertically\nvar textareas = document.getElementsByTagName('textarea');\n\nfor (i = 0; i<textareas.length; i++)\n{\n // Retain textarea's starting height as its minimum height\n textareas[i].minHeight = textareas[i].offsetHeight;\n\n textareas[i].onkeyup = function () {\n this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';\n }\n textareas[i].onkeyup(); // Trigger once to set initial height\n}\n" }, { "answer_id": 16620046, "author": "Eduard Luca", "author_id": 898423, "author_profile": "https://Stackoverflow.com/users/898423", "pm_score": 4, "selected": false, "text": "jQuery(document).ready(function(){\n jQuery(\"#textArea\").on(\"keydown keyup\", function(){\n this.style.height = \"1px\";\n this.style.height = (this.scrollHeight) + \"px\"; \n });\n});\n this.style.height = (this.scrollHeight) + \"px\";" }, { "answer_id": 17098236, "author": "Einstein47", "author_id": 2484068, "author_profile": "https://Stackoverflow.com/users/2484068", "pm_score": 1, "selected": false, "text": "<TEXTAREA style=\"overflow: visible;\" cols=\"100\" ....></TEXTAREA>\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/841/" ]
7,489
<p>I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class?</p> <p>Here's one way I thought of but it doesn't seem right:</p> <p><strong>Edit:</strong> I'm using C++.</p> <pre><code>class Gui { public: void update_all(); void draw_all() const; int add_button(Button *button); // Returns button id void remove_button(int button_id); private: Button *buttons[10]; int num_buttons; } </code></pre> <p>This code has a few problems, but I just wanted to give you an idea of what I want.</p>
[ { "answer_id": 13384, "author": "thing2k", "author_id": 3180, "author_profile": "https://Stackoverflow.com/users/3180", "pm_score": 3, "selected": true, "text": "class uiElement()\n{\n ...\n virtual void Update() = 0;\n virtual void Draw() = 0;\n ...\n}\n\nclass uiButton() public : uiElement\n{\n ...\n virtual void Update();\n virtual void Draw();\n ...\n}\n\nclass uiTextbox() public : uiElement\n{\n ...\n virtual void Update();\n virtual void Draw();\n ...\n}\n\n... // Other ui Elements\n\nclass uiWindow()\n{\n ...\n void Update();\n void Draw();\n\n void AddElement(uiElement *Element);\n void RemoveElement(uiElement *Element);\n\n std::list <uiElement*> Elements;\n\n ...\n}\n\nvoid uiWindow::Update()\n{\n ...\n for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )\n it->Update();\n ...\n}\n\nvoid uiWindow::Draw()\n{\n ...\n for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )\n it->Draw();\n ...\n}\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
7,492
<p>In the past, I used Microsoft Web Application Stress Tool and Pylot to stress test web applications. I'd written a simple home page, login script, and site walkthrough (in an ecommerce site adding a few items to a cart and checkout).</p> <p>Just hitting the homepage hard with a handful of developers would almost always locate a major problem. More scalability problems would surface at the second stage, and even more - after the launch.</p> <p>The URL of the tools I used were Microsoft Homer (aka <a href="http://www.microsoft.com/downloads/details.aspx?familyid=e2c0585a-062a-439e-a67d-75a89aa36495&amp;displaylang=en" rel="noreferrer">Microsoft Web Application Stress Tool</a>) and <a href="https://code.google.com/archive/p/pylt/" rel="noreferrer">Pylot</a>.</p> <p>The reports generated by these tools never made much sense to me, and I would spend many hours trying to figure out what kind of concurrent load the site would be able to support. It was always worth it because the stupidest bugs and bottlenecks would always come up (for instance, web server misconfigurations).</p> <p>What have you done, what tools have you used, and what success have you had with your approach? The part that is most interesting to me is coming up with some kind of a meaningful formula for calculating the number of concurrent users an app can support from the numbers reported by the stress test application.</p>
[ { "answer_id": 3546467, "author": "Ben Li", "author_id": 423840, "author_profile": "https://Stackoverflow.com/users/423840", "pm_score": 3, "selected": false, "text": "ab -c n -t 30 url\n\nsiege -b -c n -t 30s url\n /usr/local/etc/siegerc" }, { "answer_id": 33876200, "author": "Sunil Kapil", "author_id": 1801075, "author_profile": "https://Stackoverflow.com/users/1801075", "pm_score": 3, "selected": false, "text": "// your code starts here \nval scn = scenario(\"Scenario\") \n .exec(http(\"Page\")\n .get(\"http://example.com\")) \n// injecting 100 user enter code here's on above scenario. \nsetUp(scn.inject(atOnceUsers(100))) \n" }, { "answer_id": 44804131, "author": "Alireza Fattahi", "author_id": 2648077, "author_profile": "https://Stackoverflow.com/users/2648077", "pm_score": 0, "selected": false, "text": "concurrent resource download browser cache http headers setting request time out cookie management https support encoding ajax support number of users per second ramp-up time scheduling assert HTTP(S) Test Script Recorder listeners .jtl" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
7,503
<p>I know almost nothing about linq.</p> <p>I'm doing this:</p> <pre><code>var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero select app; </code></pre> <p>Which gets me all the running processes which match that criteria.</p> <p>But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this</p> <pre><code>var matchedApp = (from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero select app).First(); </code></pre> <p>which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?</p> <p><strong>UPDATE</strong></p> <p>I'm actually trying to find the first matching item, and call <code>SetForegroundWindow</code> on it</p> <p>I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?</p> <pre><code>var unused = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) &amp;&amp; app.MainWindowHandle != IntPtr.Zero select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess </code></pre>
[ { "answer_id": 7509, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 0, "selected": false, "text": "var apps = from app in Process.GetProcesses()\nwhere app.ProcessName.Contains( \"MyAppName\" ) && app.MainWindowHandle != IntPtr.Zero\nselect app;\n\nif (apps.Count > 0)\n{\n SetForegroundWindow(apps.FirstOrDefault().MainWindowHandle );\n}\n" }, { "answer_id": 7512, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains(\"MyAppName\") && p.MainWindowHandle != IntPtr.Zero);\n\nif (app == null)\n return;\n\nSetForegroundWindow(app.MainWindowHandle);\n" }, { "answer_id": 8190166, "author": "David Schwartz", "author_id": 399124, "author_profile": "https://Stackoverflow.com/users/399124", "pm_score": 2, "selected": false, "text": "Count() Count() IEnumerable Count() Count FirstOrDefault FirstOrDefault apps.First().MainWindowHandle var app = apps.FirstOrDefault();\n\nif (app != null)\n SetForegroundWindow(app.MainWindowHandle);\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
7,517
<p>Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process.</p>
[ { "answer_id": 7537, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 0, "selected": false, "text": "DROP TABLE IF EXISTS table1, table2, table3 CASCADE;\n" }, { "answer_id": 25719, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 0, "selected": false, "text": "drop table X, Y, Z" }, { "answer_id": 103183, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 1, "selected": false, "text": "sp_MSforeachtable @command1=\"print 'disabling constraints: ?'\", @command2=\"sp_drop_constraints @tablename=?\"\nGO\nsp_MSforeachtable @command1=\"print 'dropping: ?'\", @command2=\"DROP TABLE ?\"\nGO\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
7,525
<p>So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an <code>std::string</code> to a class and assigning it a value from another <code>std::string</code>:</p> <pre><code>std::string hello = "Hello, world.\n"; /* exampleString = "Hello, world.\n" would work fine. */ exampleString = hello; </code></pre> <p>crashes on my system with a stack dump. So basically I need to <strong>stop</strong> and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able. </p> <p>Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with <code>valgrind</code>, and while not knowing completely what I'm doing, it did report that the <code>std::string</code>'s destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well.</p> <p>(In before <code>rm -rf ProjectDir</code>, do again in C# :D)</p> <p>EDIT: I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were.</p>
[ { "answer_id": 7559, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 1, "selected": false, "text": " this->map = new Area*[largestY + 1];\n for (int i = 0; i < largestY + 1; i++) {\n this->map[i] = new Area[largestX + 1];\n }\n for (int i = 0; i < largestY + 1; i++) {\n delete [] this->map[i];\n}\ndelete [] this->map;\n" }, { "answer_id": 7566, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "exampleString = hello; exampleString = hello;" }, { "answer_id": 7695, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 6, "selected": true, "text": "new[] delete[] assert() assert() auto_ptr" }, { "answer_id": 71983, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 3, "selected": false, "text": "_M_dataplus._M_p (gdb) p &exampleString._M_dataplus._M_p\n$3 = (char **) 0xbfccc2d8\n(gdb) watch *$3\nHardware watchpoint 1: *$3\n Continuing.\nHardware watchpoint 2: *$3\n\nOld value = 0xb7ec2604 \"\"\nNew value = 0x804a014 \"\"\n0xb7e70a1c in std::string::_M_mutate () from /usr/lib/libstdc++.so.6\n(gdb) where\n where > MAX_INT" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
7,535
<p>What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005?</p>
[ { "answer_id": 7547, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 5, "selected": true, "text": "ALTER DATABASE <database> \nSET COMPATIBILITY_LEVEL = { 80 | 90 | 100 }\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ]
7,539
<p>Recently I tried understanding the use of <strong>java.math.MathContext</strong> but failed to understand properly. Is it used for rounding in <code>java.math.BigDecimal</code>. If yes why does not it round the decimal digits but even mantissa part.</p> <p>From API docs, I came to know that it follows the standard specified in <code>ANSI X3.274-1996</code> and <code>ANSI X3.274-1996/AM 1-2000</code> specifications but I did not get them to read online.</p> <p>Please let me know if you have any idea on this.</p>
[ { "answer_id": 7550, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "System.out.println(new BigDecimal(\"1234567890.123456789\",\n new MathContext(20)));\n\nSystem.out.println(new BigDecimal(\"1234567890.123456789\",\n new MathContext(10)));\n\nSystem.out.println(new BigDecimal(\"1234567890.123456789\",\n new MathContext(5)));\n 1234567890.123456789\n1234567890\n1.2346E+9\n" }, { "answer_id": 7552, "author": "jatanp", "author_id": 959, "author_profile": "https://Stackoverflow.com/users/959", "pm_score": 3, "selected": false, "text": "MathContext MathContext precision = 2 rounding mode = ROUND_HALF_EVEN BigDecimal Number = 0.5294 Number = 1.5294 1.5 Number = 10.5294 10 Number = 101.5294 100" }, { "answer_id": 7561, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 7, "selected": true, "text": "BigDecimal.round() BigDecimal MathContext MathContext RoundingMode 123 120 123 1.23e2 1.2e2 120 RoundingMode 123 RoundingMode HALF_UP 123 120 RoundingMode CEILING 130 System.out.println(new BigDecimal(\"123.4\",\n new MathContext(4,RoundingMode.HALF_UP)));\nSystem.out.println(new BigDecimal(\"123.4\",\n new MathContext(2,RoundingMode.HALF_UP)));\nSystem.out.println(new BigDecimal(\"123.4\",\n new MathContext(2,RoundingMode.CEILING)));\nSystem.out.println(new BigDecimal(\"123.4\",\n new MathContext(1,RoundingMode.CEILING)));\n 123.4\n1.2E+2\n1.3E+2\n2E+2\n" }, { "answer_id": 4194330, "author": "Øystein Øvrebø", "author_id": 374167, "author_profile": "https://Stackoverflow.com/users/374167", "pm_score": 6, "selected": false, "text": "BigDecimal.setScale(int newScale, int roundingMode) BigDecimal original = new BigDecimal(\"1.235\");\nBigDecimal scaled = original.setScale(2, BigDecimal.ROUND_HALF_UP);\n" }, { "answer_id": 22988977, "author": "radekEm", "author_id": 1534456, "author_profile": "https://Stackoverflow.com/users/1534456", "pm_score": 4, "selected": false, "text": "MathContext MATH_CTX = new MathContext(3, RoundingMode.HALF_UP);\n BigDecimal d1 = new BigDecimal(1234.4, MATH_CTX);\nSystem.out.println(d1);\n 1.23E+3 BigDecimal d2 = new BigDecimal(0.000000454770054, MATH_CTX);\nSystem.out.println(d2);\n 4.55E-7 0.000 BigDecimal d3 = new BigDecimal(0.001000045477, MATH_CTX);\n System.out.println(d3); // 0.00100\n\nBigDecimal d4 = new BigDecimal(0.200000477, MATH_CTX);\n System.out.println(d4); // 0.200\n\nBigDecimal d5 = new BigDecimal(0.000000004, MATH_CTX);\n System.out.println(d5); //4.00E-9\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
7,551
<p>When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management) ?</p> <p>When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints.</p> <p>While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged.</p> <p>Any discussion or links to relevant documents would be very much appreciated. If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the .NET Framework.</p>
[ { "answer_id": 24807288, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 2, "selected": false, "text": "userPrincipal HttpServletRequest ServiceSecurityContext.Current" }, { "answer_id": 47189047, "author": "Andrejs", "author_id": 2786733, "author_profile": "https://Stackoverflow.com/users/2786733", "pm_score": 6, "selected": false, "text": "Max Retry TTL RTTL JWT redirect_uri response_type=token CSRF OAuth HSTS GET POST PUT/PATCH DELETE 405 Method Not Allowed Accept application/xml application/json 406 Not Acceptable content-type application/x-www-form-urlencoded multipart/form-data application/json Authorization Rate Limit X-Content-Type-Options: nosniff X-Frame-Options: deny Content-Security-Policy: default-src 'none' X-Powered-By Server X-AspNet-Version content-type application/json application/json 200 OK 400 Bad Request 401 Unauthorized 405 Method Not Allowed" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/541/" ]
7,558
<p>I am displaying a list of items using a SAP ABAP column tree model, basically a tree of folder and files, with columns.</p> <p>I want to load the sub-nodes of folders dynamically, so I'm using the EXPAND_NO_CHILDREN event which is firing correctly.</p> <p>Unfortunately, after I add the new nodes and items to the tree, the folder is automatically collapsing again, requiring a second click to view the sub-nodes. Do I need to call a method when handling the event so that the folder stays open, or am I doing something else wrong?</p> <pre><code>* Set up event handling. LS_EVENT-EVENTID = CL_ITEM_TREE_CONTROL=&gt;EVENTID_EXPAND_NO_CHILDREN. LS_EVENT-APPL_EVENT = GC_X. APPEND LS_EVENT TO LT_EVENTS. CALL METHOD GO_MODEL-&gt;SET_REGISTERED_EVENTS EXPORTING EVENTS = LT_EVENTS EXCEPTIONS ILLEGAL_EVENT_COMBINATION = 1 UNKNOWN_EVENT = 2. SET HANDLER GO_APPLICATION-&gt;HANDLE_EXPAND_NO_CHILDREN FOR GO_MODEL. ... * Add new data to tree. CALL METHOD GO_MODEL-&gt;ADD_NODES EXPORTING NODE_TABLE = PTI_NODES[] EXCEPTIONS ERROR_IN_NODE_TABLE = 1. CALL METHOD GO_MODEL-&gt;ADD_ITEMS EXPORTING ITEM_TABLE = PTI_ITEMS[] EXCEPTIONS NODE_NOT_FOUND = 1 ERROR_IN_ITEM_TABLE = 2. </code></pre>
[ { "answer_id": 63251, "author": "tomdemuyt", "author_id": 7602, "author_profile": "https://Stackoverflow.com/users/7602", "pm_score": 0, "selected": false, "text": "ADD_NODES_AND_ITEMS EXPAND_NODE" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
7,579
<p>In the SSW rules to better SQL Server Database there is an example of a full database maintenance plan: <a href="http://www.ssw.com.au/ssw/Standards/Rules/RulesToBetterSQLServerDatabases.aspx#MaintenancePlan" rel="noreferrer">SSW</a>. In the example they run both a Reorganize Index and then a Rebuild Index and then Update Statistics. Is there any point to this? I thought Reorganize Index was a fast but less effective version of Rebuild Index? and that an index rebuild would also update the statistics automatically (on the clustered index at least).</p>
[ { "answer_id": 7635, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 3, "selected": false, "text": "EXEC [sp_MSforeachtable] @command1=\"RAISERROR('DBCC DBREINDEX(''?'') ...',10,1) WITH NOWAIT DBCC DBREINDEX('?')\"\n" }, { "answer_id": 9424260, "author": "Llew", "author_id": 1229744, "author_profile": "https://Stackoverflow.com/users/1229744", "pm_score": 6, "selected": true, "text": "REORGANIZE REBUILD REORGANIZE REBUILD SHRINK REBUILD REBUILD REORGANIZE REBUILD SHRINK TRUNCATEONLY" }, { "answer_id": 17312515, "author": "Chris KL", "author_id": 58110, "author_profile": "https://Stackoverflow.com/users/58110", "pm_score": 2, "selected": false, "text": "EXEC sp_MSforeachtable 'ALTER INDEX ALL ON ? REINDEX'\n EXEC sp_MSforeachtable 'ALTER INDEX ALL ON ? REORGANIZE'\n" }, { "answer_id": 19003874, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 3, "selected": false, "text": "CREATE PROCEDURE dbo.[IndexRebuild]\nAS \nDECLARE @TableName NVARCHAR(500);\nDECLARE @SQLIndex NVARCHAR(MAX);\nDECLARE @RowCount INT;\nDECLARE @Counter INT;\n\nDECLARE @IndexAnalysis TABLE\n (\n AnalysisID INT IDENTITY(1, 1)\n NOT NULL\n PRIMARY KEY ,\n TableName NVARCHAR(500) ,\n SQLText NVARCHAR(MAX) ,\n IndexDepth INT ,\n AvgFragmentationInPercent FLOAT ,\n FragmentCount BIGINT ,\n AvgFragmentSizeInPages FLOAT ,\n PageCount BIGINT\n )\n\nBEGIN\n INSERT INTO @IndexAnalysis\n SELECT [objects].name ,\n 'ALTER INDEX [' + [indexes].name + '] ON ['\n + [schemas].name + '].[' + [objects].name + '] '\n + ( CASE WHEN ( [dm_db_index_physical_stats].avg_fragmentation_in_percent >= 20\n AND [dm_db_index_physical_stats].avg_fragmentation_in_percent < 40\n ) THEN 'REORGANIZE'\n WHEN [dm_db_index_physical_stats].avg_fragmentation_in_percent > = 40\n THEN 'REBUILD'\n END ) AS zSQL ,\n [dm_db_index_physical_stats].index_depth ,\n [dm_db_index_physical_stats].avg_fragmentation_in_percent ,\n [dm_db_index_physical_stats].fragment_count ,\n [dm_db_index_physical_stats].avg_fragment_size_in_pages ,\n [dm_db_index_physical_stats].page_count\n FROM [sys].[dm_db_index_physical_stats](DB_ID(), NULL, NULL,\n NULL, 'LIMITED') AS [dm_db_index_physical_stats]\n INNER JOIN [sys].[objects] AS [objects] ON ( [dm_db_index_physical_stats].[object_id] = [objects].[object_id] )\n INNER JOIN [sys].[schemas] AS [schemas] ON ( [objects].[schema_id] = [schemas].[schema_id] )\n INNER JOIN [sys].[indexes] AS [indexes] ON ( [dm_db_index_physical_stats].[object_id] = [indexes].[object_id]\n AND [dm_db_index_physical_stats].index_id = [indexes].index_id\n )\n WHERE index_type_desc <> 'HEAP'\n AND [dm_db_index_physical_stats].avg_fragmentation_in_percent > 20\nEND\n\nSELECT @RowCount = COUNT(AnalysisID)\nFROM @IndexAnalysis\n\nSET @Counter = 1\nWHILE @Counter <= @RowCount \n BEGIN\n\n SELECT @SQLIndex = SQLText\n FROM @IndexAnalysis\n WHERE AnalysisID = @Counter\n\n EXECUTE sp_executesql @SQLIndex\n\n SET @Counter = @Counter + 1\n\n END\n GO\n" }, { "answer_id": 26184119, "author": "mcfea", "author_id": 984463, "author_profile": "https://Stackoverflow.com/users/984463", "pm_score": 0, "selected": false, "text": "USE [MyDbName]\nGO\n\nSET ANSI_NULLS OFF\nGO\n\nSET QUOTED_IDENTIFIER OFF\nGO\n\nCREATE PROCEDURE [maintenance].[IndexFragmentationCleanup]\nAS\nDECLARE @reIndexRequest VARCHAR(1000)\n\nDECLARE reIndexList CURSOR\nFOR\nSELECT INDEX_PROCESS\nFROM (\n SELECT CASE \n WHEN avg_fragmentation_in_percent BETWEEN 5\n AND 30\n THEN 'ALTER INDEX [' + i.NAME + '] ON [' + t.NAME + '] REORGANIZE;'\n WHEN avg_fragmentation_in_percent > 30\n THEN 'ALTER INDEX [' + i.NAME + '] ON [' + t.NAME + '] REBUILD with(ONLINE=ON);'\n END AS INDEX_PROCESS\n ,avg_fragmentation_in_percent\n ,t.NAME\n FROM sys.dm_db_index_physical_stats(NULL, NULL, NULL, NULL, NULL) AS a\n INNER JOIN sys.indexes AS i ON a.object_id = i.object_id\n AND a.index_id = i.index_id\n INNER JOIN sys.tables t ON t.object_id = i.object_id\n WHERE i.NAME IS NOT NULL\n ) PROCESS\nWHERE PROCESS.INDEX_PROCESS IS NOT NULL\nORDER BY avg_fragmentation_in_percent DESC\n\nOPEN reIndexList\n\nFETCH NEXT\nFROM reIndexList\nINTO @reIndexRequest\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n BEGIN TRY\n\n PRINT @reIndexRequest;\n\n EXEC (@reIndexRequest);\n\n END TRY\n\n BEGIN CATCH\n DECLARE @ErrorMessage NVARCHAR(4000);\n DECLARE @ErrorSeverity INT;\n DECLARE @ErrorState INT;\n\n SELECT @ErrorMessage = 'UNABLE TO CLEAN UP INDEX WITH: ' + @reIndexRequest + ': MESSAGE GIVEN: ' + ERROR_MESSAGE()\n ,@ErrorSeverity = 9 \n ,@ErrorState = ERROR_STATE();\n\n END CATCH;\n\n FETCH NEXT\n FROM reIndexList\n INTO @reIndexRequest\nEND\n\nCLOSE reIndexList;\n\nDEALLOCATE reIndexList;\n\nRETURN 0\n\nGO\n" }, { "answer_id": 28203806, "author": "vast", "author_id": 1617079, "author_profile": "https://Stackoverflow.com/users/1617079", "pm_score": 1, "selected": false, "text": "create function GetIndexCreateScript(\n @index_name nvarchar(100)\n) \nreturns nvarchar(max)\nas\nbegin\n\ndeclare @Return varchar(max)\n\nSELECT @Return = ' CREATE ' + \n CASE WHEN I.is_unique = 1 THEN ' UNIQUE ' ELSE '' END + \n I.type_desc COLLATE DATABASE_DEFAULT +' INDEX ' + \n I.name + ' ON ' + \n Schema_name(T.Schema_id)+'.'+T.name + ' ( ' + \n KeyColumns + ' ) ' + \n ISNULL(' INCLUDE ('+IncludedColumns+' ) ','') + \n ISNULL(' WHERE '+I.Filter_definition,'') + ' WITH ( ' + \n CASE WHEN I.is_padded = 1 THEN ' PAD_INDEX = ON ' ELSE ' PAD_INDEX = OFF ' END + ',' + \n 'FILLFACTOR = '+CONVERT(CHAR(5),CASE WHEN I.Fill_factor = 0 THEN 100 ELSE I.Fill_factor END) + ',' + \n -- default value \n 'SORT_IN_TEMPDB = OFF ' + ',' + \n CASE WHEN I.ignore_dup_key = 1 THEN ' IGNORE_DUP_KEY = ON ' ELSE ' IGNORE_DUP_KEY = OFF ' END + ',' + \n CASE WHEN ST.no_recompute = 0 THEN ' STATISTICS_NORECOMPUTE = OFF ' ELSE ' STATISTICS_NORECOMPUTE = ON ' END + ',' + \n -- default value \n ' DROP_EXISTING = ON ' + ',' + \n -- default value \n ' ONLINE = OFF ' + ',' + \n CASE WHEN I.allow_row_locks = 1 THEN ' ALLOW_ROW_LOCKS = ON ' ELSE ' ALLOW_ROW_LOCKS = OFF ' END + ',' + \n CASE WHEN I.allow_page_locks = 1 THEN ' ALLOW_PAGE_LOCKS = ON ' ELSE ' ALLOW_PAGE_LOCKS = OFF ' END + ' ) ON [' + \n DS.name + ' ] ' \nFROM sys.indexes I \n JOIN sys.tables T ON T.Object_id = I.Object_id \n JOIN sys.sysindexes SI ON I.Object_id = SI.id AND I.index_id = SI.indid \n JOIN (SELECT * FROM ( \n SELECT IC2.object_id , IC2.index_id , \n STUFF((SELECT ' , ' + C.name + CASE WHEN MAX(CONVERT(INT,IC1.is_descending_key)) = 1 THEN ' DESC ' ELSE ' ASC ' END \n FROM sys.index_columns IC1 \n JOIN Sys.columns C \n ON C.object_id = IC1.object_id \n AND C.column_id = IC1.column_id \n AND IC1.is_included_column = 0 \n WHERE IC1.object_id = IC2.object_id \n AND IC1.index_id = IC2.index_id \n GROUP BY IC1.object_id,C.name,index_id \n ORDER BY MAX(IC1.key_ordinal) \n FOR XML PATH('')), 1, 2, '') KeyColumns \n FROM sys.index_columns IC2 \n --WHERE IC2.Object_id = object_id('Person.Address') --Comment for all tables \n GROUP BY IC2.object_id ,IC2.index_id) tmp3 )tmp4 \n ON I.object_id = tmp4.object_id AND I.Index_id = tmp4.index_id \n JOIN sys.stats ST ON ST.object_id = I.object_id AND ST.stats_id = I.index_id \n JOIN sys.data_spaces DS ON I.data_space_id=DS.data_space_id \n JOIN sys.filegroups FG ON I.data_space_id=FG.data_space_id \n LEFT JOIN (SELECT * FROM ( \n SELECT IC2.object_id , IC2.index_id , \n STUFF((SELECT ' , ' + C.name \n FROM sys.index_columns IC1 \n JOIN Sys.columns C \n ON C.object_id = IC1.object_id \n AND C.column_id = IC1.column_id \n AND IC1.is_included_column = 1 \n WHERE IC1.object_id = IC2.object_id \n AND IC1.index_id = IC2.index_id \n GROUP BY IC1.object_id,C.name,index_id \n FOR XML PATH('')), 1, 2, '') IncludedColumns \n FROM sys.index_columns IC2 \n --WHERE IC2.Object_id = object_id('Person.Address') --Comment for all tables \n GROUP BY IC2.object_id ,IC2.index_id) tmp1 \n WHERE IncludedColumns IS NOT NULL ) tmp2 \nON tmp2.object_id = I.object_id AND tmp2.index_id = I.index_id \nWHERE I.is_primary_key = 0 AND I.is_unique_constraint = 0 \nAND I.[name] = @index_name\n\nreturn @Return\n\nend\n declare @RebuildIndex Table(\n IndexId int identity(1,1),\n IndexName varchar(100),\n TableSchema varchar(50),\n TableName varchar(100),\n Fragmentation decimal(18,2)\n)\n\n\ninsert into @RebuildIndex (IndexName,TableSchema,TableName,Fragmentation)\nSELECT \n B.[name] as 'IndexName', \n Schema_Name(O.[schema_id]) as 'TableSchema',\n OBJECT_NAME(A.[object_id]) as 'TableName',\n A.[avg_fragmentation_in_percent] Fragmentation\nFROM sys.dm_db_index_physical_stats(db_id(),NULL,NULL,NULL,'LIMITED') A \nINNER JOIN sys.indexes B ON A.[object_id] = B.[object_id] and A.index_id = B.index_id \nINNER JOIN sys.objects O ON O.[object_id] = B.[object_id] \n where B.[name] is not null and B.is_primary_key = 0 AND B.is_unique_constraint = 0 and A.[avg_fragmentation_in_percent] >= 5 \n\n--select * from @RebuildIndex\n\n declare @begin int = 1\n declare @max int\n select @max = Max(IndexId) from @RebuildIndex\n declare @IndexName varchar(100), @TableSchema varchar(50), @TableName varchar(100) , @Fragmentation decimal(18,2)\n\n while @begin <= @max\n begin\n\n Select @IndexName = IndexName from @RebuildIndex where IndexId = @begin\n select @TableSchema = TableSchema from @RebuildIndex where IndexId = @begin\n select @TableName = TableName from @RebuildIndex where IndexId = @begin \n select @Fragmentation = Fragmentation from @RebuildIndex where IndexId = @begin \n\n declare @sql nvarchar(max)\n if @Fragmentation < 31\n begin\n set @sql = 'ALTER INDEX ['+@IndexName+'] ON ['+@TableSchema+'].['+@TableName+'] REORGANIZE WITH ( LOB_COMPACTION = ON )'\n print 'Reorganized Index ' + @IndexName + ' for ' + @TableName + ' Fragmentation was ' + convert(nvarchar(18),@Fragmentation)\n end\n else\n begin\n set @sql = (select dbo.GetIndexCreateScript(@IndexName))\n if(@sql is not null)\n begin\n print 'Recreated Index ' + @IndexName + ' for ' + @TableName + ' Fragmentation was ' + convert(nvarchar(18),@Fragmentation)\n end \n else\n begin\n set @sql = 'ALTER INDEX ['+@IndexName+'] ON ['+@TableSchema+'].['+@TableName+'] REBUILD PARTITION = ALL WITH (ONLINE = ON)'\n print 'Rebuilded Index ' + @IndexName + ' for ' + @TableName + ' Fragmentation was ' + convert(nvarchar(18),@Fragmentation)\n end\n end\n\n execute(@sql)\n\n\n set @begin = @begin+1\n\nend\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/961/" ]
7,586
<p>I was trying to get my head around XAML and thought that I would try writing some code. </p> <p>Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition.</p> <p>XAML:</p> <pre><code>&lt;Page x:Class="WPF_Tester.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1" Loaded="Page_Loaded"&gt; &lt;/Page&gt; </code></pre> <p>C#:</p> <pre><code>private void Page_Loaded(object sender, RoutedEventArgs e) { //create the structure Grid g = new Grid(); g.ShowGridLines = true; g.Visibility = Visibility.Visible; //add columns for (int i = 0; i &lt; 6; ++i) { ColumnDefinition cd = new ColumnDefinition(); cd.Name = "Column" + i.ToString(); g.ColumnDefinitions.Add(cd); } //add rows for (int i = 0; i &lt; 6; ++i) { RowDefinition rd = new RowDefinition(); rd.Name = "Row" + i.ToString(); g.RowDefinitions.Add(rd); } TextBlock tb = new TextBlock(); tb.Text = "Hello World"; g.Children.Add(tb); } </code></pre> <p><strong>Update</strong></p> <p>Here is the spooky bit:</p> <ul> <li><p>Using VS2008 Pro on XP</p></li> <li><p>WPFbrowser Project Template (3.5 verified)</p></li> </ul> <p>I don't get the methods in autocomplete.</p>
[ { "answer_id": 7590, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "<TextBlock Grid.Row=\"0\" Grid.Column=\"0\" />\n g.Children.Add(tb);\nGrid.SetRow(tb, 0);\nGrid.SetColumn(tb, 0);\n" }, { "answer_id": 7591, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 0, "selected": false, "text": "TextBlock tb = new TextBlock();\n//\n// Locate tb in the second row, third column.\n// Row and column indices are zero-indexed, so this\n// equates to row 1, column 2.\n//\nGrid.SetRow(tb, 1);\nGrid.SetColumn(tb, 2);\n" }, { "answer_id": 7593, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 0, "selected": false, "text": "Grid.SetRow( cell, rownumber ) <TextBlock Grid.Row=\"1\" />" }, { "answer_id": 8346266, "author": "NoWar", "author_id": 196919, "author_profile": "https://Stackoverflow.com/users/196919", "pm_score": 0, "selected": false, "text": "Grid grid = new Grid();\n\n// Set the column and row definitions\ngrid.ColumnDefinitions.Add(new ColumnDefinition() {\n Width = new GridLength(1, GridUnitType.Auto) });\ngrid.ColumnDefinitions.Add(new ColumnDefinition() {\n Width = new GridLength(1, GridUnitType.Star) });\ngrid.RowDefinitions.Add(new RowDefinition() {\n Height = new GridLength(1, GridUnitType.Auto) });\ngrid.RowDefinitions.Add(new RowDefinition() {\n Height = new GridLength(1, GridUnitType.Auto) });\n\n// Row 0\nTextBlock tbFirstNameLabel = new TextBlock() { Text = \"First Name: \"};\nTextBlock tbFirstName = new TextBlock() { Text = \"John\"};\n\ngrid.Children.Add(tbFirstNameLabel ); // Add to the grid\nGrid.SetRow(tbFirstNameLabel , 0); // Specify row for previous grid addition\nGrid.SetColumn(tbFirstNameLabel , 0); // Specity column for previous grid addition\n\ngrid.Children.Add(tbFirstName ); // Add to the grid\nGrid.SetRow(tbFirstName , 0); // Specify row for previous grid addition\nGrid.SetColumn(tbFirstName , 1); // Specity column for previous grid addition\n\n// Row 1\nTextBlock tbLastNameLabel = new TextBlock() { Text = \"Last Name: \"};\nTextBlock tbLastName = new TextBlock() { Text = \"Smith\"};\n\ngrid.Children.Add(tbLastNameLabel ); // Add to the grid\nGrid.SetRow(tbLastNameLabel , 1); // Specify row for previous grid addition\nGrid.SetColumn(tbLastNameLabel , 0); // Specity column for previous grid addition\n\ngrid.Children.Add(tbLastName ); // Add to the grid\nGrid.SetRow(tbLastName , 1); // Specify row for previous grid addition\nGrid.SetColumn(tbLastName , 1); // Specity column for previous grid addition\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
7,592
<p>I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much.</p> <p>The mail created by the mailto action has the syntax:</p> <blockquote> <p>subject: undefined subject<br> body:</p> <p>param1=value1<br> param2=value2<br> .<br> .<br> .<br> paramn=valuen </p> </blockquote> <p>Can I use JavaScript to format the mail like this?</p> <blockquote> <p>Subject:XXXXX</p> <p>Body: Value1;Value2;Value3...ValueN</p> </blockquote>
[ { "answer_id": 7643, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 5, "selected": true, "text": "var addresses = \"\";//between the speech mark goes the receptient. Seperate addresses with a ;\nvar body = \"\"//write the message text between the speech marks or put a variable in the place of the speech marks\nvar subject = \"\"//between the speech marks goes the subject of the message\nvar href = \"mailto:\" + addresses + \"?\"\n + \"subject=\" + subject + \"&\"\n + \"body=\" + body;\nvar wndMail;\nwndMail = window.open(href, \"_blank\", \"scrollbars=yes,resizable=yes,width=10,height=10\");\nif(wndMail)\n{\n wndMail.close(); \n}\n" }, { "answer_id": 28234765, "author": "Simon", "author_id": 487846, "author_profile": "https://Stackoverflow.com/users/487846", "pm_score": 1, "selected": false, "text": " var mail = \"mailto:[email protected]?subject=New Mail&body=Mail text body\"; \n var mlink = document.createElement('a');\n mlink.setAttribute('href', mail);\n mlink.click();\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518/" ]
7,596
<p>First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier.</p> <p>I myself have always had problems with </p> <ul> <li>naming, </li> <li>placing</li> </ul> <p>So,</p> <ol> <li>Where do you put your domain specific constants (and what is the best name for such a class)?</li> <li>Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)?</li> <li>Where to put Exceptions?</li> <li>Are there any standards to which I can refer?</li> </ol>
[ { "answer_id": 7610, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 2, "selected": false, "text": "com.domain.subdomain FileStorageStrategy com.domain.subdomain.myapp.storage com.domain.subdomain.myapp.storage.file com.domain.subdomain.myapp.storage.database import FileStorageException FileStorageStrategy" }, { "answer_id": 8594, "author": "cringe", "author_id": 834, "author_profile": "https://Stackoverflow.com/users/834", "pm_score": 4, "selected": false, "text": "/src - for your packages & classes\n/test - for unit tests\n/docs - for documentation, generated and manually edited\n/lib - 3rd party libraries\n/etc - unrelated stuff\n/bin (or /classes) - compiled classes, output of your compile\n/dist - for distribution packages, hopefully auto generated by a build system\n" }, { "answer_id": 13283, "author": "Brian Laframboise", "author_id": 1557, "author_profile": "https://Stackoverflow.com/users/1557", "pm_score": 6, "selected": true, "text": "MyProject/src/main/java/com/acme/Widget.java\nMyProject/src/test/java/com/acme/WidgetTest.java\n" }, { "answer_id": 66745, "author": "Sébastien D.", "author_id": 5717, "author_profile": "https://Stackoverflow.com/users/5717", "pm_score": 4, "selected": false, "text": "com.foo.bar.common\ncom.foo.bar.entities\ncom.foo.bar.repositories\ncom.foo.bar.services\ncom.foo.bar.services.impl\n...\n src\\\n ..main\\java\n ...\\resources\n ..test\\java\n ...\\resources\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917/" ]
7,614
<p>What is the best way of testing a function that throws on failure? Or testing a function that is fairly immune to failure?</p> <p>For instance; I have a <code>I/O Completion Port</code> class that throws in the constructor if it can't initialise the port correctly. This uses the <code>Win32</code> function of <code>CreateIoCompletionPort</code> in the initialiser list. If the handle isn't set correctly - a non-null value - then the constructor will throw an exception. I have never seen this function fail.</p> <p>I am pretty certain that this (and other functions like it in my code) if they fail will behave correctly, the code is 50 lines long including white-space, so my questions are</p> <p>a) is it worth testing that it will throw<br> b) and if it is worth testing, how to?<br> c) should simple wrapper classes as these be unit-tested? </p> <p>For b) I thought about overriding <code>CreateIoCompletionPort</code> and passing the values through. In the unit test override it and cause it to return 0 when a certain value is passed in. However since this is used in the constructor then this needs to be static. Does this seem valid or not?</p>
[ { "answer_id": 7624, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "public class MyClass {\n public MyClass() throws MyClassException {\n // Whatever, including a call to invokeCreateIoCompletionPort\n }\n\n protected int invokeCreateIoCompletionPort(String str, int i) {\n return StaticClass.createIoCompletionPort(str, i);\n }\n}\n\npublic class MyTest {\n public void myTest() {\n try {\n new MyClass();\n fail(\"MyClassException was not thrown!\");\n } catch (MyClassException e) {\n }\n }\n\n private static class MyClassWrapper extends MyClass {\n @Override\n protected int invokeCreateIoCompletionPort(String str, int i) {\n throw new ExpectedException();\n }\n }\n}\n" }, { "answer_id": 7639, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "[Test, ExpectedException(typeof(SpecificException), \"Exception's specific message\")]\npublic void TestWhichHasException()\n{\n CallMethodThatThrowsSpecificException();\n}\n" }, { "answer_id": 12477581, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 0, "selected": false, "text": "CreateIoCompletionPort() ::CreateIoCompletionPort() CreateIoCompletionPort() NULL CreateIoCompletionPort()" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
7,622
<p>In C, are the shift operators (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>) arithmetic or logical?</p>
[ { "answer_id": 7632, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "signed int x1 = 5;\nassert((x1 >> 1) == 2);\nsigned int x2 = -5;\nassert((x2 >> 1) == -3);\nunsigned int x3 = (unsigned int)-5;\nassert((x3 >> 1) == 0x7FFFFFFD);\n" }, { "answer_id": 10101, "author": "Nick", "author_id": 1236, "author_profile": "https://Stackoverflow.com/users/1236", "pm_score": 4, "selected": false, "text": "~0 >> 1\n ~0U >> 1;\n" }, { "answer_id": 2463888, "author": "John Scipione", "author_id": 100444, "author_profile": "https://Stackoverflow.com/users/100444", "pm_score": 4, "selected": false, "text": "int logicalRightShift(int x, int n) {\n return (unsigned)x >> n;\n}\nint arithmeticRightShift(int x, int n) {\n if (x < 0 && n > 0)\n return x >> n | ~(~0U >> n);\n else\n return x >> n;\n}\n" }, { "answer_id": 12293923, "author": "Srikant Patnaik", "author_id": 1650989, "author_profile": "https://Stackoverflow.com/users/1650989", "pm_score": 3, "selected": false, "text": " x = 5\n x >> 1\n x = 2 ( x=5/2)\n\n x = 5\n x << 1\n x = 10 (x=5*2)\n" }, { "answer_id": 19978070, "author": "srinath", "author_id": 2952286, "author_profile": "https://Stackoverflow.com/users/2952286", "pm_score": -1, "selected": false, "text": "<< >>" }, { "answer_id": 22734721, "author": "legends2k", "author_id": 183120, "author_profile": "https://Stackoverflow.com/users/183120", "pm_score": 6, "selected": false, "text": "i n i T n [0, sizeof(i) * CHAR_BIT) | Direction | Type | Value (i) | Result |\n| ---------- | -------- | --------- | ------------------------ |\n| Right (>>) | unsigned | ≥ 0 | −∞ ← (i ÷ 2ⁿ) |\n| Right | signed | ≥ 0 | −∞ ← (i ÷ 2ⁿ) |\n| Right | signed | < 0 | Implementation-defined† |\n| Left (<<) | unsigned | ≥ 0 | (i * 2ⁿ) % (T_MAX + 1) |\n| Left | signed | ≥ 0 | (i * 2ⁿ) ‡ |\n| Left | signed | < 0 | Undefined |\n ÷ / short E1 = 1, E2 = 3;\nint R = E1 << E2;\n int E2 E2 ≥ sizeof(int) * CHAR_BIT R short int short >>> >> <<" }, { "answer_id": 22743208, "author": "asifaftab87", "author_id": 2673577, "author_profile": "https://Stackoverflow.com/users/2673577", "pm_score": 0, "selected": false, "text": "<< LSB >> MSB MSB" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/973/" ]
7,642
<p>Is there an official convention for naming private fields in VB.NET? For example, if I have a property called 'Foo', I normally call the private field '_Foo'. This seems to be frowned upon in the <a href="http://msdn.microsoft.com/en-us/library/ms229012.aspx" rel="noreferrer">Offical Guidelines</a>:</p> <p>"Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields."</p> <p>In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor. As VB.NET is case insensitive you can't do this - any suggestions?</p>
[ { "answer_id": 8092, "author": "Lance Fisher", "author_id": 571, "author_profile": "https://Stackoverflow.com/users/571", "pm_score": 0, "selected": false, "text": "Public Class Class1\n\n Private _foo As String\n Public Property Foo() As String\n Get\n Return _foo\n End Get\n Set(ByVal value As String)\n _foo = value\n End Set\n End Property\n\n Public Sub New(ByVal foo As String)\n _foo = foo\n End Sub\n\nEnd Class\n" }, { "answer_id": 7235878, "author": "crunchy", "author_id": 602542, "author_profile": "https://Stackoverflow.com/users/602542", "pm_score": 2, "selected": false, "text": "Public Property Foo As String\nPublic Property Foo2 As String\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133/" ]
7,651
<p>I have an array in Perl:</p> <pre><code>my @my_array = ("one","two","three","two","three"); </code></pre> <p>How do I remove the duplicates from the array?</p>
[ { "answer_id": 7657, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "sub uniq {\n my %seen;\n grep !$seen{$_}++, @_;\n}\n\nmy @array = qw(one two three two three);\nmy @filtered = uniq(@array);\n\nprint \"@filtered\\n\";\n one two three\n uniq List::MoreUtils" }, { "answer_id": 7658, "author": "Xetius", "author_id": 274, "author_profile": "https://Stackoverflow.com/users/274", "pm_score": 5, "selected": false, "text": "my %unique = ();\nforeach my $item (@myarray)\n{\n $unique{$item} ++;\n}\nmy @myuniquearray = keys %unique;\n" }, { "answer_id": 7829, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 7, "selected": false, "text": "% perldoc -q duplicate\n my %hash = map { $_, 1 } @array;\n # or a hash slice: @hash{ @array } = ();\n # or a foreach: $hash{$_} = 1 foreach ( @array );\n\n my @unique = keys %hash;\n use List::MoreUtils qw(uniq);\n\n my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7\n my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7\n my @unique = ();\n my %seen = ();\n\n foreach my $elem ( @array )\n {\n next if $seen{ $elem }++;\n push @unique, $elem;\n }\n my %seen = ();\n my @unique = grep { ! $seen{ $_ }++ } @array;\n" }, { "answer_id": 36739, "author": "Ranguard", "author_id": 3838, "author_profile": "https://Stackoverflow.com/users/3838", "pm_score": 6, "selected": false, "text": "use strict;\nuse warnings;\nuse List::MoreUtils qw(uniq);\n\nmy @dup_list = qw(1 1 1 2 3 4 4);\n\nmy @uniq_list = uniq(@dup_list);\n" }, { "answer_id": 475071, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "my @arr;\nmy @uniqarr;\n\nforeach my $var ( @arr ){\n if ( ! grep( /$var/, @uniqarr ) ){\n push( @uniqarr, $var );\n }\n}\n" }, { "answer_id": 4004912, "author": "Sreedhar", "author_id": 485150, "author_profile": "https://Stackoverflow.com/users/485150", "pm_score": 3, "selected": false, "text": "@array %seen=();\n@unique = grep { ! $seen{$_} ++ } @array;\n" }, { "answer_id": 8071893, "author": "Hawk", "author_id": 1038583, "author_profile": "https://Stackoverflow.com/users/1038583", "pm_score": 3, "selected": false, "text": "my @in=qw(1 3 4 6 2 4 3 2 6 3 2 3 4 4 3 2 5 5 32 3); #Sample data \nmy @out=keys %{{ map{$_=>1}@in}}; # Perform PFM\nprint join ' ', sort{$a<=>$b} @out;# Print data back out sorted and in order.\n @in map map keys @out" }, { "answer_id": 30448251, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 0, "selected": false, "text": "use strict;\n\n# Helper function to remove duplicates in a list.\nsub uniq {\n my %seen;\n grep !$seen{$_}++, @_;\n}\n\nmy @teststrings = (\"one\", \"two\", \"three\", \"one\");\n\nmy @filtered = uniq @teststrings;\nprint \"uniq: @filtered\\n\";\nmy @sorted = sort @teststrings;\nprint \"sort: @sorted\\n\";\nmy @sortedfiltered = uniq sort @teststrings;\nprint \"uniq sort : @sortedfiltered\\n\";\n" }, { "answer_id": 43114185, "author": "Sandeep_black", "author_id": 7277468, "author_profile": "https://Stackoverflow.com/users/7277468", "pm_score": 0, "selected": false, "text": "my @array = (\"a\",\"b\",\"c\",\"b\",\"a\",\"d\",\"c\",\"a\",\"d\");\nmy %hash = map { $_ => 1 } @array;\nmy @unique = keys %hash;\nprint \"@unique\",\"\\n\";\n" }, { "answer_id": 43873983, "author": "Kamal Nayan", "author_id": 4414367, "author_profile": "https://Stackoverflow.com/users/4414367", "pm_score": 3, "selected": false, "text": "my @unique = keys {map {$_ => 1} @array};\n sub get_unique {\n my %seen;\n grep !$seen{$_}++, @_;\n}\nmy @unique = get_unique(@array);\n List::MoreUtils use List::MoreUtils qw(uniq);\nmy @unique = uniq(@array);\n" }, { "answer_id": 54000062, "author": "YenForYang", "author_id": 7314180, "author_profile": "https://Stackoverflow.com/users/7314180", "pm_score": 1, "selected": false, "text": "my @record = qw( yeah I mean uh right right uh yeah so well right I maybe );\nmy %record;\nprint grep !$record{$_} && ++$record{$_}, @record;\n grep !$seen{$_}++ ... $seen{$_} %seen $record{$_} %record ...\ngrep !(exists $record{$_} || undef $record{$_}), @record;\n ...\nundef @record{@record};\nkeys %record; # your record, now probably scrambled but at least deduped\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
7,661
<p>Searching for some sample code for converting a point in WGS84 coordinate system to a map position in Google Maps (pixel position), also supporting zoom levels. </p> <p>If the codes is well commented, then it can also be in some other language.</p> <p>You can also point me to a open source Java project :)</p> <p>Some resources found:</p> <p><a href="http://trac.openlayers.org/browser/trunk/openlayers/lib/OpenLayers/Layer" rel="nofollow noreferrer">OpenLayer</a> implementation. </p> <p><a href="http://josm.openstreetmap.de/browser/trunk/src/org/openstreetmap/josm/data/projection" rel="nofollow noreferrer">JOSM</a> project</p> <p>Excellent <a href="https://github.com/OSUCartography/JMapProjLib" rel="nofollow noreferrer">Java Map Projection Library </a> from JH LABS. This is a pure java PROJ.4 port. Does projection from WGS84 to meters. From there it's quite straightforward to convert meters to tile pixels.</p>
[ { "answer_id": 2373697, "author": "Ro.", "author_id": 103446, "author_profile": "https://Stackoverflow.com/users/103446", "pm_score": 2, "selected": false, "text": "function toMercator (lon, lat) {\n var x = lon * 20037508.34 / 180;\n var y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);\n y = y * 20037508.34 / 180;\n\n return [x, y];\n }\n\nfunction inverseMercator (x, y) {\n var lon = (x / 20037508.34) * 180;\n var lat = (y / 20037508.34) * 180;\n\n lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);\n\n return [lon, lat];\n }\n" }, { "answer_id": 8051786, "author": "biphobe", "author_id": 889665, "author_profile": "https://Stackoverflow.com/users/889665", "pm_score": 2, "selected": false, "text": "$lon = ($lon * 20037508.34) / 180;\n$lat = log(tan((90 + $lat) * M_PI / 360)) / (M_PI / 180);\n$lat = $lat * 20037508.34 / 180;\n $lon = ($lon / 20037508.34) * 180;\n$lat = ($lat / 20037508.34) * 180;\n$lat = 180/M_PI * (2 * atan(exp($lat * M_PI / 180)) - M_PI / 2);\n" }, { "answer_id": 11747267, "author": "Sandeep", "author_id": 218857, "author_profile": "https://Stackoverflow.com/users/218857", "pm_score": 1, "selected": false, "text": "/*\n * Utility functions to transform between wgs84 and google projection coordinates\n * Derived from openmap http://openmap.bbn.com/\n */\n\npublic class MercatorTransform {\n public final static double NORTH_POLE = 90.0;\n public final static double SOUTH_POLE = -NORTH_POLE;\n public final static double DATELINE = 180.0;\n public final static double LON_RANGE = 360.0;\n\n final public static transient double wgs84_earthEquatorialRadiusMeters_D = 6378137.0;\n private static double latfac = wgs84_earthEquatorialRadiusMeters_D;\n private static double lonfac = wgs84_earthEquatorialRadiusMeters_D;\n\n final public static transient double HALF_PI_D = Math.PI / 2.0d;\n\n /**\n * Returns google projection coordinates from wgs84 lat,long coordinates\n */\n public static double[] forward(double lat, double lon) {\n\n lat = normalizeLatitude(lat);\n lon = wrapLongitude(lon);\n\n double latrad = Math.toRadians(lat);\n double lonrad = Math.toRadians(lon);\n\n double lat_m = latfac * Math.log(Math.tan(((latrad + HALF_PI_D) / 2d)));\n double lon_m = lonfac * lonrad;\n\n double[] x = { lon_m, lat_m };\n return x;\n }\n\n /**\n * Returns wgs84 lat,long coordinates from google projection coordinates\n */\n public static float[] inverse(float lon_m, float lat_m) {\n double latrad = (2d * Math.atan(Math.exp(lat_m / latfac))) - HALF_PI_D;\n double lonrad = lon_m / lonfac;\n\n double lat = Math.toDegrees(latrad);\n double lon = Math.toDegrees(lonrad);\n\n lat = normalizeLatitude(lat);\n lon = wrapLongitude(lon);\n float[] x = { (float) lat, (float) lon };\n\n return x;\n }\n\n private static double wrapLongitude(double lon) {\n if ((lon < -DATELINE) || (lon > DATELINE)) {\n lon += DATELINE;\n lon = lon % LON_RANGE;\n lon = (lon < 0) ? DATELINE + lon : -DATELINE + lon;\n }\n return lon;\n }\n\n private static double normalizeLatitude(double lat) {\n if (lat > NORTH_POLE) {\n lat = NORTH_POLE;\n }\n if (lat < SOUTH_POLE) {\n lat = SOUTH_POLE;\n }\n return lat;\n }\n\n}\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706/" ]
7,662
<p>Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions:</p> <ol> <li>Should table names be plural?</li> <li>Should column names be singular?</li> <li>Should I prefix tables or columns?</li> <li>Should I use any case in naming items?</li> </ol> <p>Are there any recommended guidelines out there for naming items in a database?</p>
[ { "answer_id": 7667, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 7, "selected": false, "text": "SELECT person.Name\nFROM People person\n" }, { "answer_id": 7678, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "select * from Orders Orders x = new Orders select Orders.*\nfrom Orders inner join Products\n on Orders.Key = Products.Key\n" }, { "answer_id": 7687, "author": "Lord Future", "author_id": 978, "author_profile": "https://Stackoverflow.com/users/978", "pm_score": -1, "selected": false, "text": "\n--Example SQL\n\nCREATE TABLE D001_Students\n(\n StudentID INTEGER CONSTRAINT nnD001_STID NOT NULL,\n ChristianName NVARCHAR(255) CONSTRAINT nnD001_CHNA NOT NULL,\n Surname NVARCHAR(255) CONSTRAINT nnD001_SURN NOT NULL,\n CONSTRAINT pkD001 PRIMARY KEY(StudentID)\n);\n\nCREATE INDEX idxD001_STID on D001_Students;\n\nCREATE TABLE D002_Classes\n(\n ClassID INTEGER CONSTRAINT nnD002_CLID NOT NULL,\n StudentID INTEGER CONSTRAINT nnD002_STID NOT NULL,\n ClassName NVARCHAR(255) CONSTRAINT nnD002_CLNA NOT NULL,\n CONSTRAINT pkD001 PRIMARY KEY(ClassID, StudentID),\n CONSTRAINT fkD001_STID FOREIGN KEY(StudentID) \n REFERENCES D001_Students(StudentID)\n);\n\nCREATE INDEX idxD002_CLID on D002_Classes;\n\nCREATE VIEW V001_StudentClasses\n(\n SELECT\n D001.ChristianName,\n D001.Surname,\n D002.ClassName\n FROM\n D001_Students D001\n INNER JOIN\n D002_Classes D002\n ON\n D001.StudentID = D002.StudentID\n);\n" }, { "answer_id": 7714, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 6, "selected": false, "text": "SELECT cust_nm, cust_add1, booking_dt\nFROM reg_customer\nINNER JOIN reg_booking\nON reg_customer.cust_id = reg_booking.cust_id\n" }, { "answer_id": 2121237, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "SELECT \n UserID, FirstName, MiddleInitial, LastName\nFROM Users\nORDER BY LastName\n" }, { "answer_id": 2523754, "author": "Albert", "author_id": 302565, "author_profile": "https://Stackoverflow.com/users/302565", "pm_score": 5, "selected": false, "text": "Update person set property = 'value' Select * from person where person.name = 'Greg' bob = new person() bob.person_name = 'Bob' bob.person_dob = '1958-12-21' customer.customer_customer_type_id customer_category_customer_type_id" }, { "answer_id": 7289746, "author": "Granger", "author_id": 530545, "author_profile": "https://Stackoverflow.com/users/530545", "pm_score": 4, "selected": false, "text": "SELECT cust_id, cust_name, addr_street, addr_city, addr_state\n FROM customer\n INNER JOIN address ON addr_cust_id = cust_id\n WHERE cust_name LIKE 'J%';\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
7,664
<p>I am wrapping existing C++ code from a <strong>BSD</strong> project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses <code>fprintf</code> to print to <strong>stderr</strong> in order to log / report errors.</p> <p>I want to redirect this to an alternative place within the same process. On <strong>Unix</strong> I have done this with a <code>socketpair</code> and a <code>thread</code>: one end of the socket is where I send <strong>stderr</strong> (via a call to <code>dup2</code>) and the other end is monitored in a thread, where I can then process the output.</p> <p>This does not work on <strong>Windows</strong> though because a socket is not the same as a file handle.</p> <p>All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect <strong>stderr</strong> within the same process getting a callback of some sort when output is written? (and before you say so, I've tried <code>SetStdHandle</code> but cannot find any way to make this work)...</p>
[ { "answer_id": 7669, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "DWORD CALLBACK DoDebugThread(void *)\n{\n AllocConsole();\n SetConsoleTitle(\"Copilot Debugger\");\n // The following is a really disgusting hack to make stdin and stdout attach\n // to the newly created console using the MSVC++ libraries. I hope other\n // operating systems don't need this kind of kludge.. :)\n stdout->_file = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);\n stdin->_file = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);\n debug();\n stdout->_file = -1;\n stdin->_file = -1;\n FreeConsole();\n CPU_run();\n return 0;\n} \n" }, { "answer_id": 7682, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "stdin stdout stderr" }, { "answer_id": 70478, "author": "Len Holgate", "author_id": 7925, "author_profile": "https://Stackoverflow.com/users/7925", "pm_score": 1, "selected": false, "text": "CoCreateGUID() StringFromIID() OVERLAPPED" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/912/" ]
7,665
<p>Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.</p> <p>If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):</p> <pre><code>$ ls -ld foo bar drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -&gt; bar $ cd foo $ pwd /Users/greg/tmp/foo $ </code></pre> <p>What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".</p>
[ { "answer_id": 7666, "author": "kauppi", "author_id": 964, "author_profile": "https://Stackoverflow.com/users/964", "pm_score": 8, "selected": true, "text": "pwd -P char *getcwd(char *buf, size_t size) unistd.h" }, { "answer_id": 7673, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 2, "selected": false, "text": "cat `mvn`\n if [ -z \"$M2_HOME\" ] ; then\n ## resolve links - $0 may be a link to maven's home\n PRG=\"$0\"\n\n # need this for relative symlinks\n while [ -h \"$PRG\" ] ; do\n ls=`ls -ld \"$PRG\"`\n link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n if expr \"$link\" : '/.*' > /dev/null; then\n PRG=\"$link\"\n else\n PRG=\"`dirname \"$PRG\"`/$link\"\n fi\n done\n\n saveddir=`pwd`\n\n M2_HOME=`dirname \"$PRG\"`/..\n\n # make it fully qualified\n M2_HOME=`cd \"$M2_HOME\" && pwd`\n" }, { "answer_id": 42918, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 9, "selected": false, "text": "readlink -f \"$path\"\n readlink readlink readlink -m realpath $path\n readlink -f readlink $path\n a b c b perl readlink -f perl -MCwd -le 'print Cwd::abs_path(shift)' \"$path\"" }, { "answer_id": 342461, "author": "Gregory", "author_id": 14351, "author_profile": "https://Stackoverflow.com/users/14351", "pm_score": 5, "selected": false, "text": "realpath foo" }, { "answer_id": 697552, "author": "tlrobinson", "author_id": 113, "author_profile": "https://Stackoverflow.com/users/113", "pm_score": 5, "selected": false, "text": "#!/bin/bash\n\n# get the absolute path of the executable\nSELF_PATH=$(cd -P -- \"$(dirname -- \"$0\")\" && pwd -P) && SELF_PATH=$SELF_PATH/$(basename -- \"$0\")\n\n# resolve symlinks\nwhile [[ -h $SELF_PATH ]]; do\n # 1) cd to directory of the symlink\n # 2) cd to the directory of where the symlink points\n # 3) get the pwd\n # 4) append the basename\n DIR=$(dirname -- \"$SELF_PATH\")\n SYM=$(readlink \"$SELF_PATH\")\n SELF_PATH=$(cd \"$DIR\" && cd \"$(dirname -- \"$SYM\")\" && pwd)/$(basename -- \"$SYM\")\ndone\n" }, { "answer_id": 7400673, "author": "Keymon", "author_id": 395686, "author_profile": "https://Stackoverflow.com/users/395686", "pm_score": 3, "selected": false, "text": "# Gets the real path of a link, following all links\nmyreadlink() { [ ! -h \"$1\" ] && echo \"$1\" || (local link=\"$(expr \"$(command ls -ld -- \"$1\")\" : '.*-> \\(.*\\)$')\"; cd $(dirname $1); myreadlink \"$link\" | sed \"s|^\\([^/].*\\)\\$|$(dirname $1)/\\1|\"); }\n\n# Returns the absolute path to a command, maybe in $PATH (which) or not. If not found, returns the same\nwhereis() { echo $1 | sed \"s|^\\([^/].*/.*\\)|$(pwd)/\\1|;s|^\\([^/]*\\)$|$(which -- $1)|;s|^$|$1|\"; } \n\n# Returns the realpath of a called command.\nwhereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed \"s|^\\([^/].*\\)\\$|$(dirname ${SCRIPT_PATH})/\\1|\"; } \n" }, { "answer_id": 22991587, "author": "Dave", "author_id": 689706, "author_profile": "https://Stackoverflow.com/users/689706", "pm_score": 2, "selected": false, "text": "function realpath {\n local r=$1; local t=$(readlink $r)\n while [ $t ]; do\n r=$(cd $(dirname $r) && cd $(dirname $t) && pwd -P)/$(basename $t)\n t=$(readlink $r)\n done\n echo $r\n}\n\n#example usage\nSCRIPT_PARENT_DIR=$(dirname $(realpath \"$0\"))/..\n" }, { "answer_id": 25199441, "author": "Clemens Tolboom", "author_id": 598513, "author_profile": "https://Stackoverflow.com/users/598513", "pm_score": 1, "selected": false, "text": "echo `php -r \"echo realpath('foo');\"`\n" }, { "answer_id": 25560920, "author": "diyism", "author_id": 264181, "author_profile": "https://Stackoverflow.com/users/264181", "pm_score": 1, "selected": false, "text": "cd $(dirname $([ -L $0 ] && readlink -f $0 || echo $0))\n" }, { "answer_id": 27642175, "author": "keen", "author_id": 3692967, "author_profile": "https://Stackoverflow.com/users/3692967", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n\nresolve_path() {\n #I'm bash only, please!\n # usage: resolve_path <a file or directory> \n # follows symlinks and relative paths, returns a full real path\n #\n local owd=\"$PWD\"\n #echo \"$FUNCNAME for $1\" >&2\n local opath=\"$1\"\n local npath=\"\"\n local obase=$(basename \"$opath\")\n local odir=$(dirname \"$opath\")\n if [[ -L \"$opath\" ]]\n then\n #it's a link.\n #file or directory, we want to cd into it's dir\n cd $odir\n #then extract where the link points.\n npath=$(readlink \"$obase\")\n #have to -L BEFORE we -f, because -f includes -L :(\n if [[ -L $npath ]]\n then\n #the link points to another symlink, so go follow that.\n resolve_path \"$npath\"\n #and finish out early, we're done.\n return $?\n #done\n elif [[ -f $npath ]]\n #the link points to a file.\n then\n #get the dir for the new file\n nbase=$(basename $npath)\n npath=$(dirname $npath)\n cd \"$npath\"\n ndir=$(pwd -P)\n retval=0\n #done\n elif [[ -d $npath ]]\n then\n #the link points to a directory.\n cd \"$npath\"\n ndir=$(pwd -P)\n retval=0\n #done\n else\n echo \"$FUNCNAME: ERROR: unknown condition inside link!!\" >&2\n echo \"opath [[ $opath ]]\" >&2\n echo \"npath [[ $npath ]]\" >&2\n return 1\n fi\n else\n if ! [[ -e \"$opath\" ]]\n then\n echo \"$FUNCNAME: $opath: No such file or directory\" >&2\n return 1\n #and break early\n elif [[ -d \"$opath\" ]]\n then \n cd \"$opath\"\n ndir=$(pwd -P)\n retval=0\n #done\n elif [[ -f \"$opath\" ]]\n then\n cd $odir\n ndir=$(pwd -P)\n nbase=$(basename \"$opath\")\n retval=0\n #done\n else\n echo \"$FUNCNAME: ERROR: unknown condition outside link!!\" >&2\n echo \"opath [[ $opath ]]\" >&2\n return 1\n fi\n fi\n #now assemble our output\n echo -n \"$ndir\"\n if [[ \"x${nbase:=}\" != \"x\" ]]\n then\n echo \"/$nbase\"\n else \n echo\n fi\n #now return to where we were\n cd \"$owd\"\n return $retval\n}\n %% ls -l `which mvn`\nlrwxr-xr-x 1 draistrick 502 29 Dec 17 10:50 /usr/local/bin/mvn@ -> ../Cellar/maven/3.2.3/bin/mvn\n %% cat test.sh\n#!/bin/bash\n. resolve_path.inc\necho\necho \"relative symlinked path:\"\nwhich mvn\necho\necho \"and the real path:\"\nresolve_path `which mvn`\n\n\n%% test.sh\n\nrelative symlinked path:\n/usr/local/bin/mvn\n\nand the real path:\n/usr/local/Cellar/maven/3.2.3/libexec/bin/mvn \n" }, { "answer_id": 31320634, "author": "Chuck Kollars", "author_id": 742475, "author_profile": "https://Stackoverflow.com/users/742475", "pm_score": 3, "selected": false, "text": "readlink -e [filepath]\n" }, { "answer_id": 33266819, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 2, "selected": false, "text": "readlink -f readlink -e readlink -f sh bash ksh zsh trueScriptDir=$(dirname -- \"$(rreadlink \"$0\")\")\n rreadlink bash npm install rreadlink -g #!/bin/sh\n\n# SYNOPSIS\n# rreadlink <fileOrDirPath>\n# DESCRIPTION\n# Resolves <fileOrDirPath> to its ultimate target, if it is a symlink, and\n# prints its canonical path. If it is not a symlink, its own canonical path\n# is printed.\n# A broken symlink causes an error that reports the non-existent target.\n# LIMITATIONS\n# - Won't work with filenames with embedded newlines or filenames containing \n# the string ' -> '.\n# COMPATIBILITY\n# This is a fully POSIX-compliant implementation of what GNU readlink's\n# -e option does.\n# EXAMPLE\n# In a shell script, use the following to get that script's true directory of origin:\n# trueScriptDir=$(dirname -- \"$(rreadlink \"$0\")\")\nrreadlink() ( # Execute the function in a *subshell* to localize variables and the effect of `cd`.\n\n target=$1 fname= targetDir= CDPATH=\n\n # Try to make the execution environment as predictable as possible:\n # All commands below are invoked via `command`, so we must make sure that\n # `command` itself is not redefined as an alias or shell function.\n # (Note that command is too inconsistent across shells, so we don't use it.)\n # `command` is a *builtin* in bash, dash, ksh, zsh, and some platforms do not \n # even have an external utility version of it (e.g, Ubuntu).\n # `command` bypasses aliases and shell functions and also finds builtins \n # in bash, dash, and ksh. In zsh, option POSIX_BUILTINS must be turned on for\n # that to happen.\n { \\unalias command; \\unset -f command; } >/dev/null 2>&1\n [ -n \"$ZSH_VERSION\" ] && options[POSIX_BUILTINS]=on # make zsh find *builtins* with `command` too.\n\n while :; do # Resolve potential symlinks until the ultimate target is found.\n [ -L \"$target\" ] || [ -e \"$target\" ] || { command printf '%s\\n' \"ERROR: '$target' does not exist.\" >&2; return 1; }\n command cd \"$(command dirname -- \"$target\")\" # Change to target dir; necessary for correct resolution of target path.\n fname=$(command basename -- \"$target\") # Extract filename.\n [ \"$fname\" = '/' ] && fname='' # !! curiously, `basename /` returns '/'\n if [ -L \"$fname\" ]; then\n # Extract [next] target path, which may be defined\n # *relative* to the symlink's own directory.\n # Note: We parse `ls -l` output to find the symlink target\n # which is the only POSIX-compliant, albeit somewhat fragile, way.\n target=$(command ls -l \"$fname\")\n target=${target#* -> }\n continue # Resolve [next] symlink target.\n fi\n break # Ultimate target reached.\n done\n targetDir=$(command pwd -P) # Get canonical dir. path\n # Output the ultimate target's canonical path.\n # Note that we manually resolve paths ending in /. and /.. to make sure we have a normalized path.\n if [ \"$fname\" = '.' ]; then\n command printf '%s\\n' \"${targetDir%/}\"\n elif [ \"$fname\" = '..' ]; then\n # Caveat: something like /var/.. will resolve to /private (assuming /var@ -> /private/var), i.e. the '..' is applied\n # AFTER canonicalization.\n command printf '%s\\n' \"$(command dirname -- \"${targetDir}\")\"\n else\n command printf '%s\\n' \"${targetDir%/}/$fname\"\n fi\n)\n\nrreadlink \"$@\"\n command unalias unset [ rreadlink command ls unalias unset while do unalias unset \\unalias while for if do bash zsh unalias bash shopt -s expand_aliases unalias \\unset unset unset unset" }, { "answer_id": 40584017, "author": "hpvw", "author_id": 7155668, "author_profile": "https://Stackoverflow.com/users/7155668", "pm_score": 3, "selected": false, "text": "[[ $OSTYPE != darwin* ]] -f #!/bin/bash\nMY_DIR=$( cd $(dirname $(readlink `[[ $OSTYPE == linux* ]] && echo \"-f\"` $0)) ; pwd -P)\necho \"$MY_DIR\"\n" }, { "answer_id": 45828988, "author": "solidsnack", "author_id": 48251, "author_profile": "https://Stackoverflow.com/users/48251", "pm_score": 2, "selected": false, "text": "function readlinks {(\n set -o errexit -o nounset\n declare n=0 limit=1024 link=\"$1\"\n\n # If it's a directory, just skip all this.\n if cd \"$link\" 2>/dev/null\n then\n pwd -P\n return 0\n fi\n\n # Resolve until we are out of links (or recurse too deep).\n while [[ -L $link ]] && [[ $n -lt $limit ]]\n do\n cd \"$(dirname -- \"$link\")\"\n n=$((n + 1))\n link=\"$(readlink -- \"${link##*/}\")\"\n done\n cd \"$(dirname -- \"$link\")\"\n\n if [[ $n -ge $limit ]]\n then\n echo \"Recursion limit ($limit) exceeded.\" >&2\n return 2\n fi\n\n printf '%s/%s\\n' \"$(pwd -P)\" \"${link##*/}\"\n)}\n cd set" }, { "answer_id": 48513659, "author": "Igor Afanasyev", "author_id": 1691455, "author_profile": "https://Stackoverflow.com/users/1691455", "pm_score": 2, "selected": false, "text": "FILE=$(perl -e \"use Cwd qw(abs_path); print abs_path('$0')\")\n DIR=$(perl -e \"use Cwd qw(abs_path); use File::Basename; print dirname(abs_path('$0'))\")\n" }, { "answer_id": 51089005, "author": "Daniel C. Sobral", "author_id": 53013, "author_profile": "https://Stackoverflow.com/users/53013", "pm_score": 2, "selected": false, "text": "(cd \"$DIR\"; pwd -P)\n DIR=$(cd $(dirname \"$FILE\"); pwd -P); echo \"${DIR}/$(readlink \"$FILE\")\"\n SOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n SOURCE=\"$(readlink \"$SOURCE\")\"\n [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\n SOURCE SOURCE DIR" }, { "answer_id": 54179738, "author": "RuneImp", "author_id": 3854664, "author_profile": "https://Stackoverflow.com/users/3854664", "pm_score": 0, "selected": false, "text": "crosspath()\n{\n local ref=\"$1\"\n if [ -x \"$(which realpath)\" ]; then\n path=\"$(realpath \"$ref\")\"\n else\n path=\"$(readlink -f \"$ref\" 2> /dev/null)\"\n if [ $? -gt 0 ]; then\n if [ -x \"$(which readlink)\" ]; then\n if [ ! -z \"$(readlink \"$ref\")\" ]; then\n ref=\"$(readlink \"$ref\")\"\n fi\n else\n echo \"realpath and readlink not available. The following may not be the final path.\" 1>&2\n fi\n if [ -d \"$ref\" ]; then\n path=\"$(cd \"$ref\"; pwd -P)\"\n else\n path=\"$(cd $(dirname \"$ref\"); pwd -P)/$(basename \"$ref\")\"\n fi\n fi\n fi\n echo \"$path\"\n}\n mac_realpath()\n{\n local ref=\"$1\"\n if [[ ! -z \"$(readlink \"$ref\")\" ]]; then\n ref=\"$(readlink \"$1\")\"\n fi\n if [[ -d \"$ref\" ]]; then\n echo \"$(cd \"$ref\"; pwd -P)\"\n else\n echo \"$(cd $(dirname \"$ref\"); pwd -P)/$(basename \"$ref\")\"\n fi\n}\n" }, { "answer_id": 57773331, "author": "Arunas Bartisius", "author_id": 4494515, "author_profile": "https://Stackoverflow.com/users/4494515", "pm_score": 0, "selected": false, "text": "script_home=$( dirname $(realpath \"$0\") )\necho Original script home: $script_home\n /$ /home/test2/symlink\n/home/test\nOriginal script home: /home/test\n Original script is: /home/test/realscript.sh\nCalled script is: /home/test2/symlink\n" }, { "answer_id": 60309169, "author": "nakwa", "author_id": 1643901, "author_profile": "https://Stackoverflow.com/users/1643901", "pm_score": 2, "selected": false, "text": "$(dirname $(realpath $PATH_TO_BE_RESOLVED))\n" }, { "answer_id": 73278862, "author": "dxlr8r", "author_id": 19718625, "author_profile": "https://Stackoverflow.com/users/19718625", "pm_score": 0, "selected": false, "text": "-> ls resolve_symlink() {\n test -L \"$1\" && ls -l \"$1\" | awk -v SYMLINK=\"$1\" '{ SL=(SYMLINK)\" -> \"; i=index($0, SL); s=substr($0, i+length(SL)); print s }'\n}\n file" }, { "answer_id": 73360081, "author": "Andi", "author_id": 6307827, "author_profile": "https://Stackoverflow.com/users/6307827", "pm_score": 0, "selected": false, "text": "# Read a path (similar to `readlink`) recursively, until the physical path without any links (like `cd -P`) is found.\n# Accepts any existing path, prints its physical path and exits `0`, exits `1` if some contained links don't exist.\n# Motivation: `${BASH_SOURCE[0]}` often contains links; using it directly to extract your project's path may fail.\n#\n# Example: Safely `source` a file located relative to the current script\n#\n# source \"$(dirname \"$(rreadlink \"${BASH_SOURCE[0]}\")\")/relative/script.sh\"\n#Inspiration: https://stackoverflow.com/a/51089005/6307827\nrreadlink () {\n declare p=\"$1\" d l\n while :; do\n d=\"$(cd -P \"$(dirname \"$p\")\" && pwd)\" || return $? #absolute path without symlinks\n p=\"$d/$(basename \"$p\")\"\n if [ -h \"$p\" ]; then\n l=\"$(readlink \"$p\")\" || break\n\n #A link must be resolved from its fully resolved parent dir.\n d=\"$(cd \"$d\" && cd -P \"$(dirname \"$l\")\" && pwd)\" || return $?\n p=\"$d/$(basename \"$l\")\"\n else\n break\n fi\n done\n printf '%s\\n' \"$p\"\n}\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ]
7,685
<p>I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here.</p>
[ { "answer_id": 3032462, "author": "Dave Gamble", "author_id": 133758, "author_profile": "https://Stackoverflow.com/users/133758", "pm_score": 3, "selected": false, "text": "\ntypedef struct _aList {\n struct _aList* next;\n struct _aList* prev; // Optional.\n // some data\n} aList;\n\naList *merge_sort_list(aList *list,int (*compare)(aList *one,aList *two))\n{\n int listSize=1,numMerges,leftSize,rightSize;\n aList *tail,*left,*right,*next;\n if (!list || !list->next) return list; // Trivial case\n\n do { // For each power of two<=list length\n numMerges=0,left=list;tail=list=0; // Start at the start\n\n while (left) { // Do this list_len/listSize times:\n numMerges++,right=left,leftSize=0,rightSize=listSize;\n // Cut list into two halves (but don't overrun)\n while (right && leftSize<listSize) leftSize++,right=right->next;\n // Run through the lists appending onto what we have so far.\n while (leftSize>0 || (rightSize>0 && right)) {\n // Left empty, take right OR Right empty, take left, OR compare.\n if (!leftSize) {next=right;right=right->next;rightSize--;}\n else if (!rightSize || !right) {next=left;left=left->next;leftSize--;}\n else if (compare(left,right)<0) {next=left;left=left->next;leftSize--;}\n else {next=right;right=right->next;rightSize--;}\n // Update pointers to keep track of where we are:\n if (tail) tail->next=next; else list=next;\n // Sort prev pointer\n next->prev=tail; // Optional.\n tail=next; \n }\n // Right is now AFTER the list we just sorted, so start the next sort there.\n left=right;\n }\n // Terminate the list, double the list-sort size.\n tail->next=0,listSize<<=1;\n } while (numMerges>1); // If we only did one merge, then we just sorted the whole list.\n return list;\n}\n\n" }, { "answer_id": 3032553, "author": "Dave Gamble", "author_id": 133758, "author_profile": "https://Stackoverflow.com/users/133758", "pm_score": 4, "selected": false, "text": "typedef struct _aList {\n struct _aList* next;\n struct _aList* prev; // Optional.\n // some data\n} aList;\n\naList* merge_sort_list_recursive(aList *list,int (*compare)(aList *one,aList *two))\n{\n // Trivial case.\n if (!list || !list->next)\n return list;\n\n aList *right = list,\n *temp = list,\n *last = list,\n *result = 0,\n *next = 0,\n *tail = 0;\n\n // Find halfway through the list (by running two pointers, one at twice the speed of the other).\n while (temp && temp->next)\n {\n last = right;\n right = right->next;\n temp = temp->next->next;\n }\n\n // Break the list in two. (prev pointers are broken here, but we fix later)\n last->next = 0;\n\n // Recurse on the two smaller lists:\n list = merge_sort_list_recursive(list, compare);\n right = merge_sort_list_recursive(right, compare);\n\n // Merge:\n while (list || right)\n {\n // Take from empty lists, or compare:\n if (!right) {\n next = list;\n list = list->next;\n } else if (!list) {\n next = right;\n right = right->next;\n } else if (compare(list, right) < 0) {\n next = list;\n list = list->next;\n } else {\n next = right;\n right = right->next;\n }\n if (!result) {\n result=next;\n } else {\n tail->next=next;\n }\n next->prev = tail; // Optional.\n tail = next;\n }\n return result;\n}\n" }, { "answer_id": 6608434, "author": "Pramod", "author_id": 833228, "author_profile": "https://Stackoverflow.com/users/833228", "pm_score": -1, "selected": false, "text": "public int[] msort(int[] a) {\n if (a.Length > 1) {\n int min = a.Length / 2;\n int max = min;\n\n int[] b = new int[min];\n int[] c = new int[max]; // dividing main array into two half arrays\n for (int i = 0; i < min; i++) {\n b[i] = a[i];\n }\n\n for (int i = min; i < min + max; i++) {\n c[i - min] = a[i];\n }\n\n b = msort(b);\n c = msort(c);\n\n int x = 0;\n int y = 0;\n int z = 0;\n\n while (b.Length != y && c.Length != z) {\n if (b[y] < c[z]) {\n a[x] = b[y];\n //r--\n x++;\n y++;\n } else {\n a[x] = c[z];\n x++;\n z++;\n }\n }\n\n while (b.Length != y) {\n a[x] = b[y];\n x++;\n y++;\n }\n\n while (c.Length != z) {\n a[x] = c[z];\n x++;\n z++;\n }\n }\n\n return a;\n}\n" }, { "answer_id": 8238253, "author": "jayadev", "author_id": 302987, "author_profile": "https://Stackoverflow.com/users/302987", "pm_score": 6, "selected": false, "text": "//The main function\npublic static Node merge_sort(Node head) \n{\n if(head == null || head.next == null) \n return head;\n \n Node middle = getMiddle(head); //get the middle of the list\n Node left_head = head;\n Node right_head = middle.next; \n middle.next = null; //split the list into two halfs\n\n return merge(merge_sort(left_head), merge_sort(right_head)); //recurse on that\n}\n\n//Merge subroutine to merge two sorted lists\npublic static Node merge(Node a, Node b)\n{\n Node dummyHead = new Node();\n for(Node current = dummyHead; a != null && b != null; current = current.next;)\n {\n if(a.data <= b.data) \n {\n current.next = a; \n a = a.next; \n }\n else\n { \n current.next = b;\n b = b.next; \n }\n \n }\n dummyHead.next = (a == null) ? b : a;\n return dummyHead.next;\n}\n\n//Finding the middle element of the list for splitting\npublic static Node getMiddle(Node head)\n{\n if(head == null) \n return head;\n \n Node slow = head, fast = head;\n \n while(fast.next != null && fast.next.next != null)\n {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}\n" }, { "answer_id": 11486661, "author": "Ed Wynn", "author_id": 1525946, "author_profile": "https://Stackoverflow.com/users/1525946", "pm_score": 1, "selected": false, "text": "element *knuthsort(element *list)\n{ /* This is my attempt at implementing Knuth's Algorithm 5.2.4L \"List merge sort\"\n from Vol.3 of TAOCP, 2nd ed. */\n element *p, *pnext, *q, *qnext, head1, head2, *s, *t;\n if(!list) return NULL;\n\nL1: /* This is the clever L1 from exercise 12, p.167, solution p.647. */\n head1.next=list;\n t=&head2;\n for(p=list, pnext=p->next; pnext; p=pnext, pnext=p->next) {\n if( cmp(p,pnext) > 0 ) { t->next=NULL; t->spare=pnext; t=p; }\n }\n t->next=NULL; t->spare=NULL; p->spare=NULL;\n head2.next=head2.spare;\n\nL2: /* begin a new pass: */\n t=&head2;\n q=t->next;\n if(!q) return head1.next;\n s=&head1;\n p=s->next;\n\nL3: /* compare: */\n if( cmp(p,q) > 0 ) goto L6;\nL4: /* add p onto the current end, s: */\n if(s->next) s->next=p; else s->spare=p;\n s=p;\n if(p->next) { p=p->next; goto L3; } \n else p=p->spare;\nL5: /* complete the sublist by adding q and all its successors: */\n s->next=q; s=t;\n for(qnext=q->next; qnext; q=qnext, qnext=q->next);\n t=q; q=q->spare;\n goto L8;\nL6: /* add q onto the current end, s: */\n if(s->next) s->next=q; else s->spare=q;\n s=q;\n if(q->next) { q=q->next; goto L3; } \n else q=q->spare;\nL7: /* complete the sublist by adding p and all its successors: */\n s->next=p;\n s=t;\n for(pnext=p->next; pnext; p=pnext, pnext=p->next);\n t=p; p=p->spare;\nL8: /* is this end of the pass? */\n if(q) goto L3;\n if(s->next) s->next=p; else s->spare=p;\n t->next=NULL; t->spare=NULL;\n goto L2;\n}\n" }, { "answer_id": 11491064, "author": "Ed Wynn", "author_id": 1525946, "author_profile": "https://Stackoverflow.com/users/1525946", "pm_score": 2, "selected": false, "text": "element* mergesort(element *head,long lengtho)\n{ \n long count1=(lengtho/2), count2=(lengtho-count1);\n element *next1,*next2,*tail1,*tail2,*tail;\n if (lengtho<=1) return head->next; /* Trivial case. */\n\n tail1 = mergesort(head,count1);\n tail2 = mergesort(tail1,count2);\n tail=head;\n next1 = head->next;\n next2 = tail1->next;\n tail1->next = tail2->next; /* in case this ends up as the tail */\n while (1) {\n if(cmp(next1,next2)<=0) {\n tail->next=next1; tail=next1;\n if(--count1==0) { tail->next=next2; return tail2; }\n next1=next1->next;\n } else {\n tail->next=next2; tail=next2;\n if(--count2==0) { tail->next=next1; return tail1; }\n next2=next2->next;\n }\n }\n}\n" }, { "answer_id": 27663998, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 2, "selected": false, "text": "SingleListNode<T> SortLinkedList<T>(SingleListNode<T> head) where T : IComparable<T>\n{\n int blockSize = 1, blockCount;\n do\n {\n //Maintain two lists pointing to two blocks, left and right\n SingleListNode<T> left = head, right = head, tail = null;\n head = null; //Start a new list\n blockCount = 0;\n\n //Walk through entire list in blocks of size blockCount\n while (left != null)\n {\n blockCount++;\n\n //Advance right to start of next block, measure size of left list while doing so\n int leftSize = 0, rightSize = blockSize;\n for (;leftSize < blockSize && right != null; ++leftSize)\n right = right.Next;\n\n //Merge two list until their individual ends\n bool leftEmpty = leftSize == 0, rightEmpty = rightSize == 0 || right == null;\n while (!leftEmpty || !rightEmpty)\n {\n SingleListNode<T> smaller;\n //Using <= instead of < gives us sort stability\n if (rightEmpty || (!leftEmpty && left.Value.CompareTo(right.Value) <= 0))\n {\n smaller = left; left = left.Next; --leftSize;\n leftEmpty = leftSize == 0;\n }\n else\n {\n smaller = right; right = right.Next; --rightSize;\n rightEmpty = rightSize == 0 || right == null;\n }\n\n //Update new list\n if (tail != null)\n tail.Next = smaller;\n else\n head = smaller;\n tail = smaller;\n }\n\n //right now points to next block for left\n left = right;\n }\n\n //terminate new list, take care of case when input list is null\n if (tail != null)\n tail.Next = null;\n\n //Lg n iterations\n blockSize <<= 1;\n\n } while (blockCount > 1);\n\n return head;\n}\n" }, { "answer_id": 33899907, "author": "Jon Meyer", "author_id": 5600008, "author_profile": "https://Stackoverflow.com/users/5600008", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Sort a linked list in place. Returns the sorted list.\n/// Originally by Jonathan Cunningham in Pop-11, May 1981.\n/// Ported to C# by Jon Meyer.\n/// </summary>\npublic class ListSorter<T> where T : IComparable<T> {\n SingleListNode<T> workNode = new SingleListNode<T>(default(T));\n SingleListNode<T> list;\n\n /// <summary>\n /// Sorts a linked list. Returns the sorted list.\n /// </summary>\n public SingleListNode<T> Sort(SingleListNode<T> head) {\n if (head == null) throw new NullReferenceException(\"head\");\n list = head;\n\n var run = GetRun(); // get first run\n // As we progress, we increase the recursion depth. \n var n = 1;\n while (list != null) {\n var run2 = GetSequence(n);\n run = Merge(run, run2);\n n++;\n }\n return run;\n }\n\n // Get the longest run of ordered elements from list.\n // The run is returned, and list is updated to point to the\n // first out-of-order element.\n SingleListNode<T> GetRun() {\n var run = list; // the return result is the original list\n var prevNode = list;\n var prevItem = list.Value;\n\n list = list.Next; // advance to the next item\n while (list != null) {\n var comp = prevItem.CompareTo(list.Value);\n if (comp > 0) {\n // reached end of sequence\n prevNode.Next = null;\n break;\n }\n prevItem = list.Value;\n prevNode = list;\n list = list.Next;\n }\n return run;\n }\n\n // Generates a sequence of Merge and GetRun() operations.\n // If n is 1, returns GetRun()\n // If n is 2, returns Merge(GetRun(), GetRun())\n // If n is 3, returns Merge(Merge(GetRun(), GetRun()),\n // Merge(GetRun(), GetRun()))\n // and so on.\n SingleListNode<T> GetSequence(int n) {\n if (n < 2) {\n return GetRun();\n } else {\n n--;\n var run1 = GetSequence(n);\n if (list == null) return run1;\n var run2 = GetSequence(n);\n return Merge(run1, run2);\n }\n }\n\n // Given two ordered lists this returns a list that is the\n // result of merging the two lists in-place (modifying the pairs\n // in list1 and list2).\n SingleListNode<T> Merge(SingleListNode<T> list1, SingleListNode<T> list2) {\n // we reuse a single work node to hold the result.\n // Simplifies the number of test cases in the code below.\n var prevNode = workNode;\n while (true) {\n if (list1.Value.CompareTo(list2.Value) <= 0) {\n // list1 goes first\n prevNode.Next = list1;\n prevNode = list1;\n if ((list1 = list1.Next) == null) {\n // reached end of list1 - join list2 to prevNode\n prevNode.Next = list2;\n break;\n }\n } else { // same but for list2\n prevNode.Next = list2;\n prevNode = list2;\n if ((list2 = list2.Next) == null) {\n prevNode.Next = list1;\n break;\n }\n }\n }\n\n // the result is in the back of the workNode\n return workNode.Next;\n }\n}\n" }, { "answer_id": 33987943, "author": "rcgldr", "author_id": 3282056, "author_profile": "https://Stackoverflow.com/users/3282056", "pm_score": 1, "selected": false, "text": "std::list::sort array[i] typedef struct NODE_{\n struct NODE_ * next;\n uint32_t data;\n}NODE;\n\nNODE * MergeLists(NODE *, NODE *); /* prototype */\n\n/* sort a list using array of pointers to list */\n/* aList[i] == NULL or ptr to list with 2^i nodes */\n \n#define NUMLISTS 32 /* number of lists */\nNODE * SortList(NODE *pList)\n{\nNODE * aList[NUMLISTS]; /* array of lists */\nNODE * pNode;\nNODE * pNext;\nint i;\n if(pList == NULL) /* check for empty list */\n return NULL;\n for(i = 0; i < NUMLISTS; i++) /* init array */\n aList[i] = NULL;\n pNode = pList; /* merge nodes into array */\n while(pNode != NULL){\n pNext = pNode->next;\n pNode->next = NULL;\n for(i = 0; (i < NUMLISTS) && (aList[i] != NULL); i++){\n pNode = MergeLists(aList[i], pNode);\n aList[i] = NULL;\n }\n if(i == NUMLISTS) /* don't go beyond end of array */\n i--;\n aList[i] = pNode;\n pNode = pNext;\n }\n pNode = NULL; /* merge array into one list */\n for(i = 0; i < NUMLISTS; i++)\n pNode = MergeLists(aList[i], pNode);\n return pNode;\n}\n\n/* merge two already sorted lists */\n/* compare uses pSrc2 < pSrc1 to follow the STL rule */\n/* of only using < and not <= */\nNODE * MergeLists(NODE *pSrc1, NODE *pSrc2)\n{\nNODE *pDst = NULL; /* destination head ptr */\nNODE **ppDst = &pDst; /* ptr to head or prev->next */\n if(pSrc1 == NULL)\n return pSrc2;\n if(pSrc2 == NULL)\n return pSrc1;\n while(1){\n if(pSrc2->data < pSrc1->data){ /* if src2 < src1 */\n *ppDst = pSrc2;\n pSrc2 = *(ppDst = &(pSrc2->next));\n if(pSrc2 == NULL){\n *ppDst = pSrc1;\n break;\n }\n } else { /* src1 <= src2 */\n *ppDst = pSrc1;\n pSrc1 = *(ppDst = &(pSrc1->next));\n if(pSrc1 == NULL){\n *ppDst = pSrc2;\n break;\n }\n }\n }\n return pDst;\n}\n std::list::sort std::list::sort()" }, { "answer_id": 44095098, "author": "Vinayak Bansal", "author_id": 5016535, "author_profile": "https://Stackoverflow.com/users/5016535", "pm_score": 0, "selected": false, "text": "class MergeNode {\n Object value;\n MergeNode next;\n\n MergeNode(Object val) {\n value = val;\n next = null;\n\n }\n\n MergeNode() {\n value = null;\n next = null;\n\n }\n\n public Object getValue() {\n return value;\n }\n\n public void setValue(Object value) {\n this.value = value;\n }\n\n public MergeNode getNext() {\n return next;\n }\n\n public void setNext(MergeNode next) {\n this.next = next;\n }\n\n @Override\n public String toString() {\n return \"MergeNode [value=\" + value + \", next=\" + next + \"]\";\n }\n\n}\n\npublic class MergesortLinkList {\n MergeNode head;\n static int totalnode;\n\n public MergeNode getHead() {\n return head;\n }\n\n public void setHead(MergeNode head) {\n this.head = head;\n }\n\n MergeNode add(int i) {\n // TODO Auto-generated method stub\n if (head == null) {\n head = new MergeNode(i);\n // System.out.println(\"head value is \"+head);\n return head;\n\n }\n MergeNode temp = head;\n\n while (temp.next != null) {\n temp = temp.next;\n }\n temp.next = new MergeNode(i);\n return head;\n\n }\n\n MergeNode mergesort(MergeNode nl1) {\n // TODO Auto-generated method stub\n\n if (nl1.next == null) {\n return nl1;\n }\n\n int counter = 0;\n\n MergeNode temp = nl1;\n\n while (temp != null) {\n counter++;\n temp = temp.next;\n\n }\n System.out.println(\"total nodes \" + counter);\n\n int middle = (counter - 1) / 2;\n\n temp = nl1;\n MergeNode left = nl1, right = nl1;\n int leftindex = 0, rightindex = 0;\n\n if (middle == leftindex) {\n right = left.next;\n }\n while (leftindex < middle) {\n\n leftindex++;\n left = left.next;\n right = left.next;\n }\n\n left.next = null;\n left = nl1;\n\n System.out.println(left.toString());\n System.out.println(right.toString());\n\n MergeNode p1 = mergesort(left);\n MergeNode p2 = mergesort(right);\n\n MergeNode node = merge(p1, p2);\n\n return node;\n\n }\n\n MergeNode merge(MergeNode p1, MergeNode p2) {\n // TODO Auto-generated method stub\n\n MergeNode L = p1;\n MergeNode R = p2;\n\n int Lcount = 0, Rcount = 0;\n\n MergeNode tempnode = null;\n\n while (L != null && R != null) {\n\n int val1 = (int) L.value;\n\n int val2 = (int) R.value;\n\n if (val1 > val2) {\n\n if (tempnode == null) {\n tempnode = new MergeNode(val2);\n R = R.next;\n } else {\n\n MergeNode store = tempnode;\n\n while (store.next != null) {\n store = store.next;\n }\n store.next = new MergeNode(val2);\n\n R = R.next;\n }\n\n } else {\n if (tempnode == null) {\n tempnode = new MergeNode(val1);\n L = L.next;\n } else {\n\n MergeNode store = tempnode;\n\n while (store.next != null) {\n store = store.next;\n }\n store.next = new MergeNode(val1);\n\n L = L.next;\n }\n\n }\n\n }\n\n MergeNode handle = tempnode;\n\n while (L != null) {\n\n while (handle.next != null) {\n\n handle = handle.next;\n\n }\n handle.next = L;\n\n L = null;\n\n }\n\n // Copy remaining elements of L[] if any\n while (R != null) {\n while (handle.next != null) {\n\n handle = handle.next;\n\n }\n handle.next = R;\n\n R = null;\n\n }\n\n System.out.println(\"----------------sorted value-----------\");\n System.out.println(tempnode.toString());\n return tempnode;\n }\n\n public static void main(String[] args) {\n MergesortLinkList objsort = new MergesortLinkList();\n MergeNode n1 = objsort.add(9);\n MergeNode n2 = objsort.add(7);\n MergeNode n3 = objsort.add(6);\n MergeNode n4 = objsort.add(87);\n MergeNode n5 = objsort.add(16);\n MergeNode n6 = objsort.add(81);\n\n MergeNode n7 = objsort.add(21);\n MergeNode n8 = objsort.add(16);\n\n MergeNode n9 = objsort.add(99);\n MergeNode n10 = objsort.add(31);\n\n MergeNode val = objsort.mergesort(n1);\n\n System.out.println(\"===============sorted values=====================\");\n while (val != null) {\n System.out.println(\" value is \" + val.value);\n val = val.next;\n }\n }\n\n}\n" }, { "answer_id": 51832084, "author": "Testing123", "author_id": 3021645, "author_profile": "https://Stackoverflow.com/users/3021645", "pm_score": 0, "selected": false, "text": "class Solution {\npublic:\n ListNode *merge(ListNode *left, ListNode *right){\n ListNode *head = NULL, *temp = NULL;\n // Find which one is the head node for the merged list\n if(left->val <= right->val){\n head = left, temp = left;\n left = left->next;\n }\n else{\n head = right, temp = right;\n right = right->next;\n }\n while(left && right){\n if(left->val <= right->val){\n temp->next = left;\n temp = left;\n left = left->next;\n }\n else{\n temp->next = right;\n temp = right;\n right = right->next;\n }\n }\n // If some elements still left in the left or the right list\n if(left)\n temp->next = left;\n if(right)\n temp->next = right;\n return head;\n }\n\n ListNode* sortList(ListNode* head){\n if(!head || !head->next)\n return head;\n\n // Find the length of the list\n int length = 0;\n ListNode *temp = head;\n while(temp){\n length++;\n temp = temp->next;\n }\n // Reset temp\n temp = head;\n // Store half of it in left and the other half in right\n // Create two lists and sort them\n ListNode *left = temp, *prev = NULL;\n int i = 0, mid = length / 2;\n // Left list\n while(i < mid){\n prev = temp;\n temp = temp->next;\n i++;\n }\n // The end of the left list should point to NULL\n if(prev)\n prev->next = NULL;\n // Right list\n ListNode *right = temp;\n // Sort left list\n ListNode *sortedLeft = sortList(left);\n // Sort right list\n ListNode *sortedRight = sortList(right);\n // Merge them\n ListNode *sortedList = merge(sortedLeft, sortedRight);\n return sortedList;\n }\n};\n" }, { "answer_id": 53996320, "author": "Pratik Patil", "author_id": 4773290, "author_profile": "https://Stackoverflow.com/users/4773290", "pm_score": 0, "selected": false, "text": "class Solution\n{\n public ListNode mergeSortList(ListNode head) \n {\n if(head == null || head.next == null)\n return head;\n\n ListNode mid = getMid(head), second_head = mid.next; mid.next = null;\n\n return merge(mergeSortList(head), mergeSortList(second_head));\n }\n\n private ListNode merge(ListNode head1, ListNode head2)\n {\n ListNode result = new ListNode(0), current = result;\n\n while(head1 != null && head2 != null)\n {\n if(head1.val < head2.val)\n {\n current.next = head1;\n head1 = head1.next;\n }\n else\n {\n current.next = head2;\n head2 = head2.next;\n }\n current = current.next;\n }\n\n if(head1 != null) current.next = head1;\n if(head2 != null) current.next = head2;\n\n return result.next;\n }\n\n private ListNode getMid(ListNode head)\n {\n ListNode slow = head, fast = head.next;\n\n while(fast != null && fast.next != null)\n {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n }\n}\n" }, { "answer_id": 54035854, "author": "Rick", "author_id": 5983841, "author_profile": "https://Stackoverflow.com/users/5983841", "pm_score": 1, "selected": false, "text": "C++ #pragma once\n#include <stdexcept>\n#include <iostream>\n#include <initializer_list>\nnamespace ythlearn{\n template<typename T>\n class Linkedlist{\n public:\n class Node{\n public:\n Node* next;\n T elem;\n };\n Node head;\n int _size;\n public:\n Linkedlist(){\n head.next = nullptr; \n _size = 0;\n }\n\n Linkedlist(std::initializer_list<T> init_list){\n head.next = nullptr; \n _size = 0;\n for(auto s = init_list.begin(); s!=init_list.end(); s++){\n push_left(*s);\n }\n }\n\n int size(){\n return _size;\n }\n\n bool isEmpty(){\n return size() == 0;\n }\n\n bool isSorted(){\n Node* n_ptr = head.next;\n while(n_ptr->next != nullptr){\n if(n_ptr->elem > n_ptr->next->elem)\n return false;\n n_ptr = n_ptr->next;\n }\n return true;\n }\n\n Linkedlist& push_left(T elem){\n Node* n = new Node;\n n->elem = elem;\n n->next = head.next;\n head.next = n;\n ++_size;\n return *this;\n }\n\n void print(){\n Node* loopPtr = head.next;\n while(loopPtr != nullptr){\n std::cout << loopPtr->elem << \" \";\n loopPtr = loopPtr->next;\n }\n std::cout << std::endl;\n }\n\n void call_merge(){\n head.next = merge_sort(head.next);\n }\n\n Node* merge_sort(Node* n){\n if(n == nullptr || n->next == nullptr)\n return n;\n Node* middle = getMiddle(n);\n Node* left_head = n;\n Node* right_head = middle->next;\n middle->next = nullptr;\n return merge(merge_sort(left_head), merge_sort(right_head));\n }\n\n Node* getMiddle(Node* n){\n if(n == nullptr)\n return n;\n Node* slow, *fast;\n slow = fast = n;\n while(fast->next != nullptr && fast->next->next != nullptr){\n slow = slow->next;\n fast = fast->next->next;\n }\n return slow;\n }\n\n Node* merge(Node* a, Node* b){\n Node dummyHead;\n Node* current = &dummyHead;\n while(a != nullptr && b != nullptr){\n if(a->elem < b->elem){\n current->next = a;\n a = a->next;\n }else{\n current->next = b;\n b = b->next;\n }\n current = current->next;\n }\n current->next = (a == nullptr) ? b : a;\n return dummyHead.next;\n }\n\n Linkedlist(const Linkedlist&) = delete;\n Linkedlist& operator=(const Linkedlist&) const = delete;\n ~Linkedlist(){\n Node* node_to_delete;\n Node* ptr = head.next;\n while(ptr != nullptr){\n node_to_delete = ptr;\n ptr = ptr->next;\n delete node_to_delete;\n }\n\n }\n\n };\n}\n #include <iostream>\n#include <cassert>\n#include \"singlelinkedlist.h\"\nusing namespace std;\nusing namespace ythlearn;\n\nint main(){\n Linkedlist<int> l = {3,6,-5,222,495,-129,0};\n l.print();\n l.call_merge();\n l.print();\n assert(l.isSorted());\n return 0;\n}\n" }, { "answer_id": 56240818, "author": "kundus", "author_id": 11531469, "author_profile": "https://Stackoverflow.com/users/11531469", "pm_score": 0, "selected": false, "text": "class Node {\n int data;\n Node next;\n Node(int d) {\n data = d;\n }\n}\n\nclass LinkedList {\n Node head;\n public Node mergesort(Node head) {\n if(head == null || head.next == null) return head;\n Node middle = middle(head), middle_next = middle.next;\n middle.next = null;\n Node left = mergesort(head), right = mergesort(middle_next), node = merge(left, right);\n return node;\n } \n\n public Node merge(Node first, Node second) {\n Node node = null;\n if (first == null) return second;\n else if (second == null) return first;\n else if (first.data <= second.data) {\n node = first;\n node.next = merge(first.next, second);\n\n } else {\n node = second;\n node.next = merge(first, second.next);\n }\n return node;\n }\n\n public Node middle(Node head) {\n if (head == null) return head;\n Node second = head, first = head.next;\n while(first != null) {\n first = first.next;\n if (first != null) {\n second = second.next;\n first = first.next;\n }\n }\n return second;\n }\n\n}\n" }, { "answer_id": 59963477, "author": "kam", "author_id": 7039094, "author_profile": "https://Stackoverflow.com/users/7039094", "pm_score": 0, "selected": false, "text": "// split the list into a singleton list\nlet split list = List.map (fun x -> [x]) lst\n\n// takes to list and merge them into a sorted list\nlet sort lst1 lst2 =\n // nested function to hide accumulator\n let rec s acc pair =\n match pair with\n // empty list case, return the sorted list\n | [], [] -> List.rev acc\n | xs, [] | [], xs ->\n // one empty list case, \n // append the rest of xs onto acc and return the sorted list\n List.fold (fun ys y -> y :: ys) acc xs\n |> List.rev\n // general case\n | x::xs, y::ys ->\n match x < y with\n | true -> // cons x onto the accumulator\n s (x::acc) (xs,y::ys)\n | _ ->\n // cons y onto the accumulator\n s (y::acc) (x::xs,ys)\n\n s [] (lst1, lst2) \n\nlet msort lst =\n let rec merge acc lst =\n match lst with\n | [] ->\n match acc with\n | [] -> [] // empty list case\n | _ -> merge [] acc\n | x :: [] -> // single list case (x is a list)\n match acc with\n | [] -> x // since acc are empty there are only x left, hence x are the sorted list.\n | _ -> merge [] (x::acc) // still need merging.\n | x1 :: x2 :: xs ->\n // merge the lists x1 and x2 and add them to the acummulator. recursiv call\n merge (sort x1 x2 :: acc) xs\n\n // return part\n split list // expand to singleton list list\n |> merge [] // merge and sort recursively.\n" }, { "answer_id": 63142081, "author": "Merouane T.", "author_id": 11200033, "author_profile": "https://Stackoverflow.com/users/11200033", "pm_score": 0, "selected": false, "text": "//Main MergeSort Function\nfunc mergeSort(head: Node?) -> Node? {\n guard let head = head else { return nil }\n guard let _ = head.next else { return head }\n\n let middle = getMiddle(head: head)\n let left = head\n let right = middle.next\n\n middle.next = nil\n\n return merge(left: mergeSort(head: left), right: mergeSort(head: right))\n}\n\n//Merge Function\nfunc merge(left: Node?, right: Node?) -> Node? {\n\n guard let left = left, let right = right else { return nil}\n\n let dummyHead: Node = Node(value: 0)\n\n var current: Node? = dummyHead\n var currentLeft: Node? = left\n var currentRight: Node? = right\n\n while currentLeft != nil && currentRight != nil {\n if currentLeft!.value < currentRight!.value {\n current?.next = currentLeft\n currentLeft = currentLeft!.next\n } else {\n current?.next = currentRight\n currentRight = currentRight!.next\n }\n current = current?.next\n }\n\n\n if currentLeft != nil {\n current?.next = currentLeft\n }\n\n if currentRight != nil {\n current?.next = currentRight\n }\n\n return dummyHead.next!\n}\n class Node { \n //Node Class which takes Integers as value\n var value: Int\n var next: Node?\n \n init(value: Int) {\n self.value = value\n }\n}\n\nfunc getMiddle(head: Node) -> Node {\n guard let nextNode = head.next else { return head }\n \n var slow: Node = head\n var fast: Node? = head\n \n while fast?.next?.next != nil {\n slow = slow.next!\n fast = fast!.next?.next\n }\n \n \n return slow\n}\n" } ]
2008/08/11
[ "https://Stackoverflow.com/questions/7685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/608/" ]