qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
224,038
<p>My $SHELL is tcsh. I want to run a C shell script that will call a program many times with some arguments changed each time. The program I need to call is in Fortran. I do not want to edit it. The program only takes arguments once it is executed, but not on the command line. Upon calling the program in the script, the program takes control (this is where I am stuck currently, I can never get out because the script will not execute anything until after the program process stops). At this point I need to pass it some variables, then after several iterations I will need to <kbd>Ctrl</kbd>+<kbd>C</kbd> out of the program and continue with the script.</p> <p>How can this be done?</p>
[ { "answer_id": 224045, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 0, "selected": false, "text": "tcsh stdin < & sleep ps grep awk kill SIGTERM" }, { "answer_id": 224068, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": true, "text": "./myfortranprogram << EOF\nfirst line of input\nsecond line of input\nEOF\n <<EOF EOF <<EOF" }, { "answer_id": 36287163, "author": "Steve", "author_id": 787832, "author_profile": "https://Stackoverflow.com/users/787832", "pm_score": 0, "selected": false, "text": "foreach f ($forecastTimes)\n custom_command << EOF\n arg1=x$f;2\n arg2=ya\n arg3=z,z$f\n run\n exit\n EOF\nend\n foreach f ($forecastTimes)\n custom_command <<EOF\n arg1=x$f;2\n arg2=ya\n arg3=z,z$f\n run\n exit\nEOF\nend\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30181/" ]
224,040
<p>What is the most elegant way to calculate the previous business day in shell ksh script ?</p> <p>What I got until now is :</p> <pre><code>#!/bin/ksh set -x DAY_DIFF=1 case `date '+%a'` in "Sun") DAY_DIFF=2 ;; "Mon") DAY_DIFF=3 ;; esac PREV_DT=`perl -e '($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time()-${DAY_DIFF}*24*60*60);printf "%4d%02d%02d",$year+1900,$mon+1,$mday;'` echo $PREV_DT </code></pre> <p>How do I make the ${DAY_DIFF} variable to be transmitted as value and not as string ?</p>
[ { "answer_id": 224428, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "#!/bin/perl -w\nuse strict;\nuse POSIX;\nuse constant SECS_PER_DAY => 24 * 60 * 60;\nmy(@days) = (2, 3, 1, 1, 1, 1, 1);\nmy($now) = time;\nmy($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($now);\nprint strftime(\"%Y-%m-%d\\n\", localtime($now - $days[$wday] * SECS_PER_DAY));\n" }, { "answer_id": 229222, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 2, "selected": false, "text": "ksh sh #!/bin/ksh\n\ndiff=-1\n[ `date +%u` == 1 ] && diff=-3\n\nseconds=$((`date +%s` + $diff * 24 * 3600))\nformat=+%Y-%m-%d\n\nif date --help 2>/dev/null | grep -q -- -d ; then\n # GNU date (e.g., Linux)\n date -d \"1970-01-01 00:00 UTC + $seconds seconds\" $format\nelse\n # For BSD date (e.g., Mac OS X)\n date -r $seconds $format\nfi\n" }, { "answer_id": 1455968, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#!/bin/ksh\n# GNU date is a veritable Swiss Army Knife...\n((D=$(date +%w)+2))\nif [ $D -gt 3 ]; then D=1; fi\nPREV_DT=$(date -d \"-$D days\" +%F)\n" }, { "answer_id": 1852385, "author": "user224243", "author_id": 224243, "author_profile": "https://Stackoverflow.com/users/224243", "pm_score": 0, "selected": false, "text": "date -d '-d24 hour ago' TZ=CET+24 date #!/usr/bin/ksh\n\nlbd=5 # last business day (1=Mon, 2=Thu ... 6=Sat, 7=Sun)\nlbd_date=\"\" # last business day date\n\nfunction lbdSunOS\n{\n typeset back=$1\n typeset tz=`date '+%Z'` # timezone\n\n lbd_date=`TZ=${tz}+$back date '+%Y%m%d'`\n}\n\nfunction lbdLinux\n{\n typeset back=$1\n\n lbd_date=`date -d \"-d$back hour ago\"`\n}\n\nfunction calcHoursBack\n{\n typeset lbd=$1\n typeset dow=`date '+%u'` # day of the week\n\n if [ $dow -ge $lbd ]\n then\n return $(((dow-lbd)*24))\n else\n return $(((dow-lbd+7)*24))\n fi\n}\n\n# Main\n\ncalcHoursBack $lbd\nlbd`uname -s` $?\n\necho $lbd_date\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,041
<p>So I have an Access database with a front and a back end. I will be distributing it to users soon, but I have no control over where exactly they will put the files on their computers. However, I think I can count on them putting front and back ends in the same folder.</p> <p>As such, when the front end opens, I want it to check that the linked tables are correctly connected to the back-end database. I have working code for this; however I don't know where to put it. When the front end opens, a menu form is automatically opened (configured through the start-up dialogue box). I have put the code in the <code>OnOpen</code> event, which I thought occurred before any data is loaded, but when I test this out, I get a message telling me that the back-end cannot be found (it's looking in its old location).</p> <p>Basically, is there an event I can use that runs before any forms have opened?</p>
[ { "answer_id": 224943, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "Me.Visible = False\n'Determines if the database window is displayed\nSetProp \"StartupShowDBWindow\", False, dbBoolean\n'Hide hidden and system objects\nSetOption \"Show Hidden Objects\", False\nSetOption \"Show System Objects\", False\n\n'Find back end\nCheckLinkPath\n Set RS = CurrentDb.OpenRecordset(\"Select TableName From sysTables \" _\n& \"WHERE TableType = 'LINK'\")\n\nRS.MoveFirst\nstrConnect = db.TableDefs(RS!TableName).Connect\nIf Not FileExists(Mid(strConnect, InStr(strConnect, \"DATABASE=\") + 9)) Then\n 'All is not well\n blnConnectError = True\nElse\n Do Until RS.EOF()\n If db.TableDefs(RS!TableName).Connect <> strConnect Then\n blnConnectError = True\n Exit Do\n End If\n\n RS.MoveNext\n Loop\nEnd If\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,043
<p>Can someone please point me to the easiest way to have a timer in a Win32 service?</p> <p>I suppose I could create a dummy window for this purpose or have a second thread do tick counts, but what's best? Is there a more elegant way?</p> <p>Thanks in advance.</p>
[ { "answer_id": 224055, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 1, "selected": false, "text": "{ \n\n case IDT_TIMER1: \n\n // Boom goes the dynamite\n" }, { "answer_id": 224061, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "UINT timer;\n\nVOID CALLBACK Timer(HWND hwnd,\n UINT uMsg,\n UINT_PTR idEvent,\n DWORD dwTime\n)\n{\n KillTimer(0, timer);\n}\n\ntimer=SetTimer(0, // window handle\n 0, // id of the timer message, leave 0 in this case\n 10000, // millis\n Timer // callback\n );\n\n// pump messages\nwhile (GetMessage) etc...\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
224,049
<p>Regarding cross-site request forgery (CSRF) attacks, if cookies are most used authentication method, why do web browsers allow sending cookies of some domain (and to that domain) from a page generated from another domain?</p> <p>Isn't CSRF easily preventable in browser by disallowing such behavior? </p> <p>As far as I know, this kind of security check isn't implemented in web browsers, but I don't understand why. Did I get something wrong?</p> <p>About CSRF:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Csrf" rel="noreferrer">On wikipedia</a></li> <li><a href="http://www.codinghorror.com/blog/archives/001171.html" rel="noreferrer">On coding horror</a></li> </ul> <p>Edit: I think that cookies should not be sent on http POST in the above case. That's the browser behavior that surprises me.</p>
[ { "answer_id": 224125, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<img src=\"http://domain.com/do_something_bad\" />\n <img src=\"http://domain.com/show_picture_if_authenticated\" />\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30187/" ]
224,059
<p>When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.</p> <p>As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:</p> <pre><code>if (condition) { do { ... } while (same condition); } </code></pre> <p>or the inverse (<code>if</code> inside the <code>while</code>), it makes me wonder if they actually wrote it that way or if they added the <code>if</code> statement when they realized the loop didn't handle the null case.</p> <p>I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?</p>
[ { "answer_id": 225472, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "try {\n someOperation();\n} catch (Exception e) {\n do {\n if (e instanceof ExceptionIHandleInAWierdWay) {\n HandleWierdException((ExceptionIHandleInAWierdWay)e);\n }\n } while ((e = e.getInnerException())!= null);\n}\n public Node findSelfOrParentWithText(string text) {\n Node node = this;\n do {\n if(node.containsText(text)) {\n break;\n }\n } while((node = node.getParent()) != null);\n return node;\n}\n" }, { "answer_id": 390634, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 2, "selected": false, "text": "startOfLoop:\n if (!condition)\n goto endOfLoop;\n\n //loop body goes here\n\n goto startOfLoop;\nendOfLoop:\n startOfLoop:\n\n //loop body\n\n //goes here\n if (condition)\n goto startOfLoop;\n" }, { "answer_id": 390646, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "do { y; } while(x); \n { y; } while(x) { y; }\n y do {\n // do something\n} while (condition is true);\n {\n // do something\n}\nwhile (condition is true) {\n // do something\n}\n" }, { "answer_id": 390647, "author": "PolyThinker", "author_id": 47707, "author_profile": "https://Stackoverflow.com/users/47707", "pm_score": 2, "selected": false, "text": "a++;\nwhile (a < n) {\n a++;\n}\n do {\n a++;\n} while (a < n)\n while (++a < n) {}\n" }, { "answer_id": 995884, "author": "Greg", "author_id": 42882, "author_profile": "https://Stackoverflow.com/users/42882", "pm_score": 1, "selected": false, "text": "begin loop\n <Code block A>\n loop condition\n <Code block B>\nend loop\n" }, { "answer_id": 3094995, "author": "Yacoby", "author_id": 118145, "author_profile": "https://Stackoverflow.com/users/118145", "pm_score": 6, "selected": false, "text": "func();\nwhile (condition) {\n func();\n}\n\n//or:\n\nwhile (true){\n func();\n if (!condition) break;\n}\n do{\n func();\n} while(condition);\n" }, { "answer_id": 3095307, "author": "AshleysBrain", "author_id": 177222, "author_profile": "https://Stackoverflow.com/users/177222", "pm_score": 3, "selected": false, "text": "do... while do {\n get_tasks_for_core();\n launch_thread();\n} while (cores_remaining());\n while true while" }, { "answer_id": 3376526, "author": "James McNellis", "author_id": 151292, "author_profile": "https://Stackoverflow.com/users/151292", "pm_score": 4, "selected": false, "text": "do while do while do while" }, { "answer_id": 3376531, "author": "Marcelo Cantos", "author_id": 9990, "author_profile": "https://Stackoverflow.com/users/9990", "pm_score": 2, "selected": false, "text": "while do...while do...while" }, { "answer_id": 9221127, "author": "Mark", "author_id": 1044742, "author_profile": "https://Stackoverflow.com/users/1044742", "pm_score": 2, "selected": false, "text": "while( someConditionMayBeFalse ){\n\n// this will never run...\n\n}\n\n\n// then the alternative\n\ndo{\n\n// this will run once even if the condition is false\n\nwhile( someConditionMayBeFalse );\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
224,072
<p>After much searching, I found the download for the <a href="http://sourceforge.net/project/showfiles.php?group_id=45216" rel="nofollow noreferrer">eclipse version of jalopy</a>. Is this compatible with Eclipse 3.4? It's dated 2006.</p> <p>I've copied the extracted folder to my plugins directory and run <code>eclipse -clean</code>, but I can't find anything matching 'jalopy' in preferences.</p> <p>If it's not compatible, are there any (free) alternatives?</p>
[ { "answer_id": 241842, "author": "tunaranch", "author_id": 27708, "author_profile": "https://Stackoverflow.com/users/27708", "pm_score": 0, "selected": false, "text": "Window > Jalopy Preferences" }, { "answer_id": 1437039, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "codeFormatter" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27708/" ]
224,078
<p>I am trying to hide some divs before the user prints this giant form, then display the divs again afterward. Thus I want to ignore the rest of the page, and only print the form itself.</p> <p>Sure I <em>could</em> open a separate page when the user clicks the print button. The only thing is that the form is really long and it would be quite tedious to do that.</p> <p><br> Edit: My previous question did not actually reflect what I was looking for. So I changed it to the current one.</p> <p>Also thanks to all that suggested window.onbeforeprint and window.onafterprint. That was relevant to my edited question.</p>
[ { "answer_id": 224084, "author": "Micky McQuade", "author_id": 12908, "author_profile": "https://Stackoverflow.com/users/12908", "pm_score": 5, "selected": false, "text": "<div class=\"someClass noPrint\">My Info</div>\n .someClass {font-family:arial;}\n@media print {\n .noPrint { display: none; }\n} \n <link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\">\n" }, { "answer_id": 224089, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 5, "selected": true, "text": "onbeforeprint onafterprint <link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\">\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
224,106
<p>How do I extend my parent's options array for child classes in PHP?</p> <p>I have something like this:</p> <pre><code>class ParentClass { public $options = array( 'option1'=&gt;'setting1' ); //The rest of the functions would follow } </code></pre> <p>I would like to append to that options array in a child class without erasing any of the parent options. I've tried doing something like this, but haven't quite got it to work yet:</p> <pre><code>class ChildClass extends ParentClass { public $options = parent::options + array( 'option2'=&gt;'setting2' ); //The rest of the functions would follow } </code></pre> <p>What would be the best way to do something like this?</p>
[ { "answer_id": 224121, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 4, "selected": true, "text": "<?php\nclass ParentClass {\n\n public $options;\n public function __construct() {\n $this->options = array(\n 'option1'=>'setting1'\n );\n }\n //The rest of the functions would follow\n}\n\nclass ChildClass extends ParentClass {\n public function __construct() {\n parent::__construct();\n $this->options['option2'] = 'setting2';\n }\n //The rest of the functions would follow\n}\n?>\n" }, { "answer_id": 224124, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "$self->append_elements( 'foo' => 'bar' );" }, { "answer_id": 224160, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "public function __construct(array $foo)\n{\n $this->options = array_merge(parent::$options, $foo);\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
224,128
<p>Currently, if I want to apply a method to a group of ActiveRecord objects, I have to structure the call like so:</p> <pre><code>messages = Message.find(:all) csv = Message.to_csv(messages) </code></pre> <p>How can I define the method so it's structured like so?</p> <pre><code>messages = Message.find(:all) csv = messages.to_csv </code></pre> <p>This is the current model code:</p> <pre><code>require 'fastercsv' class Message &lt; ActiveRecord::Base def Message.to_csv(messages) FasterCSV.generate do |csv| csv &lt;&lt; ["from","to", "received"] for m in messages csv &lt;&lt; [m.from,m.to,m.created_at] end end end end </code></pre>
[ { "answer_id": 224140, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 0, "selected": false, "text": "@csv_file = Message.send_all_to_csv\n require 'fastercsv'\nclass Message < ActiveRecord::Base\n def send_all_to_csv\n @messages = Find.all\n FasterCSV.generate do |csv|\n csv << [\"from\",\"to\", \"received\"]\n for message in @messages\n csv << [message.from,message.to,message.created_at]\n end\n end\n # do something with your csv object (return it to the controller\n # or pass it on to another class method\n end\nend\n" }, { "answer_id": 224171, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 0, "selected": false, "text": "messages def messages.to_csv()\n\n FasterCSV.generate do |csv|\n csv << [\"from\", \"to\", \"received\"]\n self.each { |m| csv << [m.from, m.to, m.created_at] } \n end\n\nend\n messages.to_csv\n" }, { "answer_id": 224350, "author": "Sam Gibson", "author_id": 29319, "author_profile": "https://Stackoverflow.com/users/29319", "pm_score": 2, "selected": false, "text": "class Array\n def to_csv(options = Hash.new)\n collect { |item| item.to_csv }.join \"\\n\"\n end\nend\n" }, { "answer_id": 236010, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 3, "selected": false, "text": "messages = Message.find(:all)\ncsv = messages.map { |message| message.to_csv }\n csv = messages.map(&:to_csv)\n csv = messages.map { |message| \n if message.length < 1000\n message.to_csv\n else\n \"Too long\"\n end\n}\n" }, { "answer_id": 312304, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 2, "selected": false, "text": "base_ext.rb require 'fastercsv'\nclass ActiveRecord::Base\n def self.to_csv(objects, skip_attributes=[])\n FasterCSV.generate do |csv|\n csv << attribute_names - skip_attributes\n objects.each do |object|\n csv << (attribute_names - skip_attributes).map { |a| \"'#{object.attributes[a]}'\" }.join(\", \")\n end\n end\n end\nend\n require 'base_ext' to_csv" }, { "answer_id": 695103, "author": "james2m", "author_id": 84330, "author_profile": "https://Stackoverflow.com/users/84330", "pm_score": 0, "selected": false, "text": "def to_custom_csv_array\n [self.from,self.to,self.created_at]\nend\n def self.find(*args)\n collection = super\n collection.extend(CustomToCSV) if collection.is_a?(Array)\nend\n module CustomToCSV\n def to_custom_csv\n FasterCSV.generate do |csv|\n csv << [\"from\",\"to\", \"received\"]\n csv << self.map {|obj| obj.to_custom_csv_array}\n end\n end\nend\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,138
<p>In the spirit of questions like <a href="https://stackoverflow.com/questions/224059/do-your-loops-test-at-the-top-or-bottom">Do your loops test at the top or bottom?</a>:</p> <p>Which style do you use for an <em>infinite</em> loop, and why?</p> <ul> <li>while (true) { }</li> <li>do { } while (true);</li> <li>for (;;) { }</li> <li>label: ... goto label;</li> </ul>
[ { "answer_id": 224142, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 5, "selected": false, "text": "while(true) {}\n" }, { "answer_id": 224144, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 3, "selected": false, "text": "while(1)\n{\n//do it \n}\n" }, { "answer_id": 224146, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "while(1) while(true) do { } while(true) for(;;) while(true) label: ... goto label;" }, { "answer_id": 224164, "author": "None", "author_id": 25012, "author_profile": "https://Stackoverflow.com/users/25012", "pm_score": 2, "selected": false, "text": "10 some l33t code\n20 goto 10\n" }, { "answer_id": 224172, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 5, "selected": false, "text": "for (;;)\n{\n /* No warnings are generated about constant value in the loop conditional\n plus it is easy to change when you realize you do need limits */ \n}\n" }, { "answer_id": 224175, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 3, "selected": false, "text": "void main()\n{\n while(1) // test.cpp(5) : warning C4127: conditional expression is constant\n {\n }\n\n for(;;)\n {\n }\n}\n" }, { "answer_id": 224195, "author": "Moishe Lettvin", "author_id": 23786, "author_profile": "https://Stackoverflow.com/users/23786", "pm_score": 1, "selected": false, "text": "for (;;)" }, { "answer_id": 224197, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 2, "selected": false, "text": "for(;;) { } repeat { } for(;;) { } for() while(1) { }" }, { "answer_id": 224205, "author": "moo", "author_id": 23107, "author_profile": "https://Stackoverflow.com/users/23107", "pm_score": 1, "selected": false, "text": "for(;;);\n" }, { "answer_id": 224216, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "for (;;) while true for (;;)" }, { "answer_id": 224257, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "while() {} for(;;) {}" }, { "answer_id": 224736, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 4, "selected": false, "text": "#define forever for(;;)\n\nforever {\n /*stuff*/\n}\n" }, { "answer_id": 226011, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 0, "selected": false, "text": "for (;;) while (true) for (;;)" }, { "answer_id": 1772337, "author": "Dan Moulding", "author_id": 95706, "author_profile": "https://Stackoverflow.com/users/95706", "pm_score": 2, "selected": false, "text": "goto while for do ... while goto goto" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28258/" ]
224,155
<p>I have something here that is really catching me off guard.</p> <p>I have an ObservableCollection of T that is filled with items. I also have an event handler attached to the CollectionChanged event.</p> <p>When you <strong>Clear</strong> the collection it causes an CollectionChanged event with e.Action set to NotifyCollectionChangedAction.Reset. Ok, that's normal. But what is weird is that neither e.OldItems or e.NewItems has anything in it. <strong>I would expect e.OldItems to be filled with all items that were removed from the collection.</strong></p> <p>Has anyone else seen this? And if so, how have they gotten around it?</p> <p>Some background: I am using the CollectionChanged event to attach and detach from another event and thus if I don't get any items in e.OldItems ... I won't be able to detach from that event.</p> <p><br></p> <p><strong>CLARIFICATION:</strong> I do know that the documentation doesn't <em>outright</em> state that it has to behave this way. But for every other action, it is notifying me of what it has done. So, my assumption is that it would tell me ... in the case of Clear/Reset as well.</p> <p><br></p> <p>Below is the sample code if you wish to reproduce it yourself. First off the xaml:</p> <pre><code>&lt;Window x:Class="ObservableCollection.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" &gt; &lt;StackPanel&gt; &lt;Button x:Name="addButton" Content="Add" Width="100" Height="25" Margin="10" Click="addButton_Click"/&gt; &lt;Button x:Name="moveButton" Content="Move" Width="100" Height="25" Margin="10" Click="moveButton_Click"/&gt; &lt;Button x:Name="removeButton" Content="Remove" Width="100" Height="25" Margin="10" Click="removeButton_Click"/&gt; &lt;Button x:Name="replaceButton" Content="Replace" Width="100" Height="25" Margin="10" Click="replaceButton_Click"/&gt; &lt;Button x:Name="resetButton" Content="Reset" Width="100" Height="25" Margin="10" Click="resetButton_Click"/&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>Next, the code behind:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace ObservableCollection { /// &lt;summary&gt; /// Interaction logic for Window1.xaml /// &lt;/summary&gt; public partial class Window1 : Window { public Window1() { InitializeComponent(); _integerObservableCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_integerObservableCollection_CollectionChanged); } private void _integerObservableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Move: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Replace: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Reset: break; default: break; } } private void addButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Add(25); } private void moveButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Move(0, 19); } private void removeButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.RemoveAt(0); } private void replaceButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection[0] = 50; } private void resetButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Clear(); } private ObservableCollection&lt;int&gt; _integerObservableCollection = new ObservableCollection&lt;int&gt; { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; } } </code></pre>
[ { "answer_id": 225590, "author": "decasteljau", "author_id": 12082, "author_profile": "https://Stackoverflow.com/users/12082", "pm_score": 5, "selected": false, "text": "public static void RemoveAll(this IList list)\n{\n while (list.Count > 0)\n {\n list.RemoveAt(list.Count - 1);\n }\n}\n" }, { "answer_id": 225778, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 4, "selected": true, "text": "public class TrulyObservableCollection<T> : ObservableCollection<T>\n{\n public event EventHandler<EventArgs> Clearing;\n protected virtual void OnClearing(EventArgs e)\n {\n if (Clearing != null)\n Clearing(this, e);\n }\n\n protected override void ClearItems()\n {\n OnClearing(EventArgs.Empty);\n base.ClearItems();\n }\n}\n" }, { "answer_id": 1082900, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// An observable collection with support for addrange and clear\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n[Serializable]\n[TypeConverter(typeof(ExpandableObjectConverter))]\npublic class ObservableCollectionRange<T> : ObservableCollection<T>\n{\n private bool _addingRange;\n\n [field: NonSerialized]\n public event NotifyCollectionChangedEventHandler CollectionChangedRange;\n\n protected virtual void OnCollectionChangedRange(NotifyCollectionChangedEventArgs e)\n {\n if ((CollectionChangedRange == null) || _addingRange) return;\n using (BlockReentrancy())\n {\n CollectionChangedRange(this, e);\n }\n }\n\n public void AddRange(IEnumerable<T> collection)\n {\n CheckReentrancy();\n var newItems = new List<T>();\n if ((collection == null) || (Items == null)) return;\n using (var enumerator = collection.GetEnumerator())\n {\n while (enumerator.MoveNext())\n {\n _addingRange = true;\n Add(enumerator.Current);\n _addingRange = false;\n newItems.Add(enumerator.Current);\n }\n }\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems));\n }\n\n protected override void ClearItems()\n {\n CheckReentrancy();\n var oldItems = new List<T>(this);\n base.ClearItems();\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItems));\n }\n\n protected override void InsertItem(int index, T item)\n {\n CheckReentrancy();\n base.InsertItem(index, item);\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));\n }\n\n protected override void MoveItem(int oldIndex, int newIndex)\n {\n CheckReentrancy();\n var item = base[oldIndex];\n base.MoveItem(oldIndex, newIndex);\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, item, newIndex, oldIndex));\n }\n\n protected override void RemoveItem(int index)\n {\n CheckReentrancy();\n var item = base[index];\n base.RemoveItem(index);\n OnCollectionChangedRange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));\n }\n\n protected override void SetItem(int index, T item)\n {\n CheckReentrancy();\n var oldItem = base[index];\n base.SetItem(index, item);\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, oldItem, item, index));\n }\n}\n\n/// <summary>\n/// A read only observable collection with support for addrange and clear\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n[Serializable]\n[TypeConverter(typeof(ExpandableObjectConverter))]\npublic class ReadOnlyObservableCollectionRange<T> : ReadOnlyObservableCollection<T>\n{\n [field: NonSerialized]\n public event NotifyCollectionChangedEventHandler CollectionChangedRange;\n\n public ReadOnlyObservableCollectionRange(ObservableCollectionRange<T> list) : base(list)\n {\n list.CollectionChangedRange += HandleCollectionChangedRange;\n }\n\n private void HandleCollectionChangedRange(object sender, NotifyCollectionChangedEventArgs e)\n {\n OnCollectionChangedRange(e);\n }\n\n protected virtual void OnCollectionChangedRange(NotifyCollectionChangedEventArgs args)\n {\n if (CollectionChangedRange != null)\n {\n CollectionChangedRange(this, args);\n }\n }\n\n}\n" }, { "answer_id": 1138654, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 1, "selected": false, "text": "/// <summary>\n/// An observable collection that cannot be reset. When clear is called\n/// items are removed individually, giving listeners the chance to detect\n/// each remove event and perform operations such as unhooking event \n/// handlers.\n/// </summary>\n/// <typeparam name=\"T\">The type of item in the collection.</typeparam>\npublic class NoResetObservableCollection<T> : ObservableCollection<T>\n{\n public NoResetObservableCollection()\n {\n }\n\n /// <summary>\n /// Clears all items in the collection by removing them individually.\n /// </summary>\n protected override void ClearItems()\n {\n IList<T> items = new List<T>(this);\n foreach (T item in items)\n {\n Remove(item);\n }\n }\n}\n" }, { "answer_id": 1505868, "author": "HaxElit", "author_id": 182703, "author_profile": "https://Stackoverflow.com/users/182703", "pm_score": 2, "selected": false, "text": "protected override void ClearItems()\n{\n CheckReentrancy();\n List<TItem> oldItems = new List<TItem>(Items);\n\n Items.Clear();\n\n OnPropertyChanged(new PropertyChangedEventArgs(\"Count\"));\n OnPropertyChanged(new PropertyChangedEventArgs(\"Item[]\"));\n\n NotifyCollectionChangedEventArgs e =\n new NotifyCollectionChangedEventArgs\n (\n NotifyCollectionChangedAction.Reset\n );\n\n FieldInfo field =\n e.GetType().GetField\n (\n \"_oldItems\",\n BindingFlags.Instance | BindingFlags.NonPublic\n );\n field.SetValue(e, oldItems);\n\n OnCollectionChanged(e);\n }\n" }, { "answer_id": 2931145, "author": "Chris", "author_id": 353126, "author_profile": "https://Stackoverflow.com/users/353126", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// Helper class that allows to \"detach\" all current Eventhandlers by setting\n /// DelegateHandler to null.\n /// </summary>\n public class PropertyChangedDelegator\n {\n /// <summary>\n /// Callback to the real event handling code.\n /// </summary>\n public PropertyChangedEventHandler DelegateHandler;\n /// <summary>\n /// Eventhandler that is registered by the elements.\n /// </summary>\n /// <param name=\"sender\">the element that has been changed.</param>\n /// <param name=\"e\">the event arguments</param>\n public void PropertyChangedHandler(Object sender, PropertyChangedEventArgs e)\n {\n if (DelegateHandler != null)\n {\n DelegateHandler(sender, e);\n }\n else\n {\n INotifyPropertyChanged s = sender as INotifyPropertyChanged;\n if (s != null)\n s.PropertyChanged -= PropertyChangedHandler;\n } \n }\n }\n" }, { "answer_id": 2963340, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": false, "text": "ListView .Reset .Remove .Reset Move" }, { "answer_id": 3237039, "author": "Rick Beerendonk", "author_id": 260821, "author_profile": "https://Stackoverflow.com/users/260821", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n\n/// <summary>\n/// Notifies listeners of the following situations:\n/// <list type=\"bullet\">\n/// <item>Elements have been added.</item>\n/// <item>Elements are about to be removed.</item>\n/// </list>\n/// </summary>\n/// <typeparam name=\"T\">The type of elements in the collection.</typeparam>\ninterface INotifyCollection<T>\n{\n /// <summary>\n /// Occurs when elements have been added.\n /// </summary>\n event EventHandler<NotifyCollectionEventArgs<T>> Added;\n\n /// <summary>\n /// Occurs when elements are about to be removed.\n /// </summary>\n event EventHandler<NotifyCollectionEventArgs<T>> Removing;\n}\n\n/// <summary>\n/// Provides data for the NotifyCollection event.\n/// </summary>\n/// <typeparam name=\"T\">The type of elements in the collection.</typeparam>\npublic class NotifyCollectionEventArgs<T> : EventArgs\n{\n /// <summary>\n /// Gets or sets the elements.\n /// </summary>\n /// <value>The elements.</value>\n public IEnumerable<T> Items\n {\n get;\n set;\n }\n}\n" }, { "answer_id": 5356516, "author": "Eric Ouellet", "author_id": 452845, "author_profile": "https://Stackoverflow.com/users/452845", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Reflection;\n\nnamespace WpfUtil.Collections\n{\n public static class ObservableCollectionExtension\n {\n public static void RemoveAllOneByOne<T>(this ObservableCollection<T> obsColl)\n {\n foreach (T item in obsColl)\n {\n while (obsColl.Count > 0)\n {\n obsColl.RemoveAt(0);\n }\n }\n }\n\n public static void RemoveAll<T>(this ObservableCollection<T> obsColl)\n {\n if (obsColl.Count > 0)\n {\n List<T> removedItems = new List<T>(obsColl);\n obsColl.Clear();\n\n NotifyCollectionChangedEventArgs e =\n new NotifyCollectionChangedEventArgs\n (\n NotifyCollectionChangedAction.Remove,\n removedItems\n );\n var eventInfo =\n obsColl.GetType().GetField\n (\n \"CollectionChanged\",\n BindingFlags.Instance | BindingFlags.NonPublic\n );\n if (eventInfo != null)\n {\n var eventMember = eventInfo.GetValue(obsColl);\n // note: if eventMember is null\n // nobody registered to the event, you can't call it.\n if (eventMember != null)\n eventMember.GetType().GetMethod(\"Invoke\").\n Invoke(eventMember, new object[] { obsColl, e });\n }\n }\n }\n }\n}\n" }, { "answer_id": 8660754, "author": "Stéphane", "author_id": 1119933, "author_profile": "https://Stackoverflow.com/users/1119933", "pm_score": 1, "selected": false, "text": "public class PeopleAttributeList : ObservableCollection<PeopleAttributeDto>, {\n{\n protected override void ClearItems()\n {\n Do what ever you want\n base.ClearItems();\n }\n\n rest of the code omitted\n}\n" }, { "answer_id": 8950505, "author": "grantnz", "author_id": 350550, "author_profile": "https://Stackoverflow.com/users/350550", "pm_score": 4, "selected": false, "text": "public class ObservableCollectionNoReset<T> : ObservableCollection<T>\n{\n protected override void ClearItems()\n {\n List<T> removed = new List<T>(this);\n base.ClearItems();\n base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));\n }\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (e.Action != NotifyCollectionChangedAction.Reset)\n base.OnCollectionChanged(e);\n }\n // Constructors omitted\n ...\n}\n public class ObservableCollectionNoReset<T> : ObservableCollection<T>\n{\n // Some CollectionChanged listeners don't support range actions.\n public Boolean RangeActionsSupported { get; set; }\n\n protected override void ClearItems()\n {\n if (RangeActionsSupported)\n {\n List<T> removed = new List<T>(this);\n base.ClearItems();\n base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));\n }\n else\n {\n while (Count > 0 )\n base.RemoveAt(Count - 1);\n } \n }\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (e.Action != NotifyCollectionChangedAction.Reset)\n base.OnCollectionChanged(e);\n }\n\n public ObservableCollectionNoReset(Boolean rangeActionsSupported = false) \n {\n RangeActionsSupported = rangeActionsSupported;\n }\n\n // Additional constructors omitted.\n }\n" }, { "answer_id": 9416535, "author": "Alain", "author_id": 529618, "author_profile": "https://Stackoverflow.com/users/529618", "pm_score": 3, "selected": false, "text": "NotifyCollectionChangedAction.Reset public class BaseObservableCollection<T> : ObservableCollection<T>\n{\n //Flag used to prevent OnCollectionChanged from firing during a bulk operation like Add(IEnumerable<T>) and Clear()\n private bool _SuppressCollectionChanged = false;\n\n /// Overridden so that we may manually call registered handlers and differentiate between those that do and don't require Action.Reset args.\n public override event NotifyCollectionChangedEventHandler CollectionChanged;\n\n public BaseObservableCollection() : base(){}\n public BaseObservableCollection(IEnumerable<T> data) : base(data){}\n\n #region Event Handlers\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if( !_SuppressCollectionChanged )\n {\n base.OnCollectionChanged(e);\n if( CollectionChanged != null )\n CollectionChanged.Invoke(this, e);\n }\n }\n\n //CollectionViews raise an error when they are passed a NotifyCollectionChangedEventArgs that indicates more than\n //one element has been added or removed. They prefer to receive a \"Action=Reset\" notification, but this is not suitable\n //for applications in code, so we actually check the type we're notifying on and pass a customized event args.\n protected virtual void OnCollectionChangedMultiItem(NotifyCollectionChangedEventArgs e)\n {\n NotifyCollectionChangedEventHandler handlers = this.CollectionChanged;\n if( handlers != null )\n foreach( NotifyCollectionChangedEventHandler handler in handlers.GetInvocationList() )\n handler(this, !(handler.Target is ICollectionView) ? e : new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n #endregion\n\n #region Extended Collection Methods\n protected override void ClearItems()\n {\n if( this.Count == 0 ) return;\n\n List<T> removed = new List<T>(this);\n _SuppressCollectionChanged = true;\n base.ClearItems();\n _SuppressCollectionChanged = false;\n OnCollectionChangedMultiItem(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));\n }\n\n public void Add(IEnumerable<T> toAdd)\n {\n if( this == toAdd )\n throw new Exception(\"Invalid operation. This would result in iterating over a collection as it is being modified.\");\n\n _SuppressCollectionChanged = true;\n foreach( T item in toAdd )\n Add(item);\n _SuppressCollectionChanged = false;\n OnCollectionChangedMultiItem(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List<T>(toAdd)));\n }\n\n public void Remove(IEnumerable<T> toRemove)\n {\n if( this == toRemove )\n throw new Exception(\"Invalid operation. This would result in iterating over a collection as it is being modified.\");\n\n _SuppressCollectionChanged = true;\n foreach( T item in toRemove )\n Remove(item);\n _SuppressCollectionChanged = false;\n OnCollectionChangedMultiItem(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new List<T>(toRemove)));\n }\n #endregion\n}\n" }, { "answer_id": 16646352, "author": "Manas", "author_id": 2401140, "author_profile": "https://Stackoverflow.com/users/2401140", "pm_score": -1, "selected": false, "text": "ObservableCollection private TestEntities context; // This is your context\n\ncontext.Refresh(System.Data.Objects.RefreshMode.StoreWins, context.UserTables); // to refresh the object context\n" }, { "answer_id": 20110760, "author": "hypehuman", "author_id": 1269598, "author_profile": "https://Stackoverflow.com/users/1269598", "pm_score": 0, "selected": false, "text": "// overriden so that we can call GetInvocationList\npublic override event NotifyCollectionChangedEventHandler CollectionChanged;\n\nprotected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n{\n NotifyCollectionChangedEventHandler collectionChanged = CollectionChanged;\n if (collectionChanged != null)\n {\n lock (collectionChanged)\n {\n foreach (NotifyCollectionChangedEventHandler handler in collectionChanged.GetInvocationList())\n {\n try\n {\n handler(this, e);\n }\n catch (NotSupportedException ex)\n {\n // this will occur if this collection is used as an ItemsControl.ItemsSource\n if (ex.Message == \"Range actions are not supported.\")\n {\n handler(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n else\n {\n throw ex;\n }\n }\n }\n }\n }\n}\n public void SetItems(IEnumerable<T> newItems)\n{\n Items.Clear();\n foreach (T newItem in newItems)\n {\n Items.Add(newItem);\n }\n NotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n}\n\npublic void AddRange(IEnumerable<T> newItems)\n{\n int index = Count;\n foreach (T item in newItems)\n {\n Items.Add(item);\n }\n NotifyCollectionChangedEventArgs e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List<T>(newItems), index);\n NotifyCollectionChanged(e);\n}\n\npublic void RemoveRange(int startingIndex, int count)\n{\n IList<T> oldItems = new List<T>();\n for (int i = 0; i < count; i++)\n {\n oldItems.Add(Items[startingIndex]);\n Items.RemoveAt(startingIndex);\n }\n NotifyCollectionChangedEventArgs e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new List<T>(oldItems), startingIndex);\n NotifyCollectionChanged(e);\n}\n\n// this needs to be overridden to avoid raising a NotifyCollectionChangedEvent with NotifyCollectionChangedAction.Reset, which our other lists don't support\nnew public void Clear()\n{\n RemoveRange(0, Count);\n}\n\npublic void RemoveWhere(Func<T, bool> criterion)\n{\n List<T> removedItems = null;\n int startingIndex = default(int);\n int contiguousCount = default(int);\n for (int i = 0; i < Count; i++)\n {\n T item = Items[i];\n if (criterion(item))\n {\n if (removedItems == null)\n {\n removedItems = new List<T>();\n startingIndex = i;\n contiguousCount = 0;\n }\n Items.RemoveAt(i);\n removedItems.Add(item);\n contiguousCount++;\n }\n else if (removedItems != null)\n {\n NotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, startingIndex));\n removedItems = null;\n i = startingIndex;\n }\n }\n if (removedItems != null)\n {\n NotifyCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, startingIndex));\n }\n}\n\nprivate void NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)\n{\n OnPropertyChanged(new PropertyChangedEventArgs(\"Count\"));\n OnPropertyChanged(new PropertyChangedEventArgs(\"Item[]\"));\n OnCollectionChanged(e);\n}\n" }, { "answer_id": 25529403, "author": "Formentz", "author_id": 2645207, "author_profile": "https://Stackoverflow.com/users/2645207", "pm_score": 0, "selected": false, "text": "public class ObservableCollectionClearable<T> : ObservableCollection<T>\n{\n private T[] ClearingItems = null;\n\n protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n {\n switch (e.Action)\n {\n case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:\n if (this.ClearingItems != null)\n {\n ReplaceOldItems(e, this.ClearingItems);\n this.ClearingItems = null;\n }\n break;\n }\n base.OnCollectionChanged(e);\n }\n\n protected override void ClearItems()\n {\n this.ClearingItems = this.ToArray();\n base.ClearItems();\n }\n\n private static void ReplaceOldItems(System.Collections.Specialized.NotifyCollectionChangedEventArgs e, T[] olditems)\n {\n Type t = e.GetType();\n System.Reflection.FieldInfo foldItems = t.GetField(\"_oldItems\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (foldItems != null)\n {\n foldItems.SetValue(e, olditems);\n }\n }\n}\n" }, { "answer_id": 32650327, "author": "Artem Illarionov", "author_id": 1376506, "author_profile": "https://Stackoverflow.com/users/1376506", "pm_score": 0, "selected": false, "text": "public class ObservableCollection<T> : System.Collections.ObjectModel.ObservableCollection<T>\n{\n protected override void ClearItems()\n {\n CheckReentrancy();\n var items = Items.ToList();\n base.ClearItems();\n OnPropertyChanged(new PropertyChangedEventArgs(\"Count\"));\n OnPropertyChanged(new PropertyChangedEventArgs(\"Item[]\"));\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, items, -1));\n }\n}\n System.Collections.ObjectModel.ObservableCollection<T> public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged\n{\n protected override void ClearItems()\n {\n CheckReentrancy();\n base.ClearItems();\n OnPropertyChanged(CountString);\n OnPropertyChanged(IndexerName);\n OnCollectionReset();\n }\n\n private void OnPropertyChanged(string propertyName)\n {\n OnPropertyChanged(new PropertyChangedEventArgs(propertyName));\n }\n\n private void OnCollectionReset()\n {\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n\n private const string CountString = \"Count\";\n\n private const string IndexerName = \"Item[]\";\n}\n" }, { "answer_id": 42713996, "author": "DeadlyEmbrace", "author_id": 2017251, "author_profile": "https://Stackoverflow.com/users/2017251", "pm_score": 4, "selected": false, "text": " public static void Clear<T>(this ObservableCollection<T> collection, Action<ObservableCollection<T>> unhookAction)\n {\n unhookAction.Invoke(collection);\n collection.Clear();\n }\n Action" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22294/" ]
224,163
<p>I currently capture MiniDumps of unhandled exceptions using <Code>SetUnhandledExceptionFilter</Code> however at times I am getting "R6025: pure virtual function".</p> <p>I understand how a pure virtual function call happens I am just wondering if it is possible to capture them so I can create a MiniDump at that point.</p>
[ { "answer_id": 224176, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": false, "text": "int __cdecl _purecall(void)\n _set_purecall_handler()" }, { "answer_id": 224177, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": true, "text": "#include <signal.h>\n\ninline void signal_handler(int)\n{\n terminator();\n}\n\ninline void terminator() \n{\n int*z = 0; *z=13; \n}\n\ninline void __cdecl invalid_parameter_handler(const wchar_t *, const wchar_t *, const wchar_t *, unsigned int, uintptr_t)\n{\n terminator();\n} \n signal(SIGABRT, signal_handler);\n _set_abort_behavior(0, _WRITE_ABORT_MSG|_CALL_REPORTFAULT);\n\n set_terminate( &terminator );\n set_unexpected( &terminator );\n _set_purecall_handler( &terminator );\n _set_invalid_parameter_handler( &invalid_parameter_handler );\n" }, { "answer_id": 224179, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": -1, "selected": false, "text": "virtual void bla() = 0 { }" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675/" ]
224,173
<p>Is it possible to use a variable from one page in a piece of code on another? e.g. submit a form on one page and on the second page use a PHP script to add the data from the form to a MySQL table</p> <p>Thanks for all the help </p>
[ { "answer_id": 224290, "author": "mrm", "author_id": 30191, "author_profile": "https://Stackoverflow.com/users/30191", "pm_score": 3, "selected": false, "text": "session_start();\n // set\n$_SESSION['varname'] = \"something\";\n// retrieve\n$somevar = $_SESSION['varname'];\n" }, { "answer_id": 40275404, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "session <?php\n\nsession_start();\n$_SESSION['yourData'] = 'yourData';\n?>\n <?php\n echo $_SESSION['yourData'];\n?>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29912/" ]
224,181
<p>When I add a reference to <strong>Microsoft.Office.Interop.Excel</strong> on my computer, Visual Studio adds this to the project file:</p> <pre><code>&lt;COMReference Include="Excel"&gt; &lt;Guid&gt;{00020813-0000-0000-C000-000000000046}&lt;/Guid&gt; &lt;VersionMajor&gt;1&lt;/VersionMajor&gt; &lt;VersionMinor&gt;5&lt;/VersionMinor&gt; &lt;Lcid&gt;0&lt;/Lcid&gt; &lt;WrapperTool&gt;primary&lt;/WrapperTool&gt; &lt;Isolated&gt;False&lt;/Isolated&gt; &lt;/COMReference&gt; </code></pre> <p>There is another developer on the team who gets errors and needs to add a DLL file to the project called Interop.Excel.dll, which replaces the code above with this in the project file:</p> <pre><code>&lt;Reference Include="Interop.Excel, Version=1.5.0.0, Culture=neutral, processorArchitecture=MSIL"&gt; &lt;SpecificVersion&gt;False&lt;/SpecificVersion&gt; &lt;HintPath&gt;My Project\Interop.Excel.dll&lt;/HintPath&gt; &lt;/Reference&gt; </code></pre> <p>This does work on my computer.</p> <p>Could you please explain the differences between the two methods, which is best, and how to get the first one working on other computers?</p>
[ { "answer_id": 317125, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 4, "selected": false, "text": "<WrapperTool>primary</WrapperTool>\n C:\\WINDOWS\\assembly\\GAC\\Microsoft.Office.Interop.Excel\\12.0.0.0__71e9bce111e9429c\\Microsoft.Office.Interop.Excel.dll\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10786/" ]
224,200
<p>Thanks a million everyone for everyone's response. Unfortunately, none of the solutions appear to be working on my end, and my guess is that the example I've provided is messed up.</p> <p>So let me try again.</p> <p>My table looks like this:</p> <pre><code> contract project activity row1 1000 8000 10 row2 1000 8000 20 row3 1000 8001 10 row4 2000 9000 49 row5 2000 9001 49 row6 3000 9000 79 row7 3000 9000 78 </code></pre> <p>Basically, the query I'm looking for would return "2000,49" for "contract, activity" because only contract #2000 has one, and ONLY one, unique activity value.</p> <p>Again, thanks a million in advance, boroatel</p>
[ { "answer_id": 224210, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 4, "selected": false, "text": "DECLARE @T TABLE( [contract] INT, project INT, activity INT )\nINSERT INTO @T VALUES( 1000, 8000, 10 )\nINSERT INTO @T VALUES( 1000, 8000, 20 )\nINSERT INTO @T VALUES( 1000, 8001, 10 )\nINSERT INTO @T VALUES( 2000, 9000, 49 )\nINSERT INTO @T VALUES( 2000, 9001, 49 )\nINSERT INTO @T VALUES( 3000, 9000, 79 )\nINSERT INTO @T VALUES( 3000, 9000, 78 )\n\nSELECT DISTINCT [contract], activity FROM @T AS A WHERE\n (SELECT COUNT( DISTINCT activity ) \n FROM @T AS B WHERE B.[contract] = A.[contract]) = 1\n SELECT Col1, Count( col1 ) AS count FROM table \nGROUP BY col1\nHAVING count > 1\n DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )\n\nINSERT INTO @t VALUES( 'A', 'B', 'C' );\nINSERT INTO @t VALUES( 'D', 'E', 'F' );\nINSERT INTO @t VALUES( 'A', 'J', 'K' );\nINSERT INTO @t VALUES( 'G', 'H', 'H' );\n\nSELECT * FROM @t\n\nSELECT col1, col2 FROM @t WHERE col1 NOT IN \n (SELECT col1 FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) > 1)\n D E\nG H\n DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )\n\nINSERT INTO @t VALUES( 'A', 'B', 'C' );\nINSERT INTO @t VALUES( 'D', 'E', 'F' );\nINSERT INTO @t VALUES( 'A', 'J', 'K' );\nINSERT INTO @t VALUES( 'G', 'H', 'H' );\n\nSELECT * FROM @t\n\nDROP TABLE #temp_table \nSELECT col1 INTO #temp_table\n FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) = 1\n\nSELECT t.col1, t.col2 FROM @t AS t\n INNER JOIN #temp_table AS tt ON t.col1 = tt.col1\n D E\nG H\n" }, { "answer_id": 224231, "author": "mrm", "author_id": 30191, "author_profile": "https://Stackoverflow.com/users/30191", "pm_score": 3, "selected": false, "text": "SELECT contract, activity\nFROM table\nGROUP BY contract\nHAVING COUNT(DISTINCT activity) = 1\n" }, { "answer_id": 224292, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 2, "selected": false, "text": "SELECT distinct contract, activity from @t a\nWHERE (SELECT COUNT(DISTINCT activity) FROM @t b WHERE b.contract = a.contract) = 1\n select contract, max(activity) from @t\ngroup by contract\nhaving count(distinct activity) = 1\n" }, { "answer_id": 224338, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": false, "text": "select \n contract,\n max (activity) \nfrom\n mytable \ngroup by\n contract \nhaving\n count (activity) = 1\n" }, { "answer_id": 224351, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "SELECT DISTINCT Contract, Activity\n FROM ProjectInfo\n WHERE Contract = (SELECT Contract\n FROM (SELECT DISTINCT Contract, Activity\n FROM ProjectInfo) AS ContractActivities\n GROUP BY Contract\n HAVING COUNT(*) = 1);\n" }, { "answer_id": 224369, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 1, "selected": false, "text": "DECLARE @T TABLE( [contract] INT, project INT, activity INT )\nINSERT INTO @T VALUES( 1000, 8000, 10 )\nINSERT INTO @T VALUES( 1000, 8000, 20 )\nINSERT INTO @T VALUES( 1000, 8001, 10 )\nINSERT INTO @T VALUES( 2000, 9000, 49 )\nINSERT INTO @T VALUES( 2000, 9001, 49 )\nINSERT INTO @T VALUES( 3000, 9000, 79 )\nINSERT INTO @T VALUES( 3000, 9000, 78 )\n\n\n\nSELECT DISTINCT [contract], activity FROM @T AS A WHERE\n (SELECT COUNT( DISTINCT activity ) \n FROM @T AS B WHERE B.[contract] = A.[contract]) = 1\n" }, { "answer_id": 224431, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 1, "selected": false, "text": "SELECT DISTINCT Contract, Activity\nFROM Contract WHERE Contract IN (\nSELECT Contract \nFROM Contract\nGROUP BY Contract\nHAVING COUNT( DISTINCT Activity ) = 1 )\n" }, { "answer_id": 224603, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 2, "selected": false, "text": "DECLARE @T TABLE(\n [contract] INT,\n project INT,\n activity INT\n)\n\nINSERT INTO @T VALUES( 1000, 8000, 10 )\nINSERT INTO @T VALUES( 1000, 8000, 20 )\nINSERT INTO @T VALUES( 1000, 8001, 10 )\nINSERT INTO @T VALUES( 2000, 9000, 49 )\nINSERT INTO @T VALUES( 2000, 9001, 49 )\nINSERT INTO @T VALUES( 3000, 9000, 79 )\nINSERT INTO @T VALUES( 3000, 9000, 78 )\n\nSELECT\n [contract],\n [Activity] = max (activity)\nFROM\n (\n SELECT\n [contract],\n [Activity]\n FROM\n @T\n GROUP BY\n [contract],\n [Activity]\n ) t\nGROUP BY\n [contract]\nHAVING count (*) = 1\n" }, { "answer_id": 251513, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT contract, activity FROM table t1\nWHERE NOT EXISTS (\n SELECT * FROM table t2\n WHERE t2.contract = t1.contract AND t2.activity != t1.activity\n)\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,204
<p>Another poster asked about <a href="https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom">preferred syntax for infinite loops</a>.</p> <p>A follow-up question: <i>Why</i> do you use infinite loops in your code? I typically see a construct like this:</p> <pre><code>for (;;) { int scoped_variable = getSomeValue(); if (scoped_variable == some_value) { break; } } </code></pre> <p>Which lets you get around not being able to see the value of scoped_variable in the <code>for</code> or <code>while</code> clause. What are some other uses for "infinite" loops?</p>
[ { "answer_id": 224215, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 6, "selected": true, "text": "while (true)\n{\n // do something\n if (something else) break;\n // do more\n}\n" }, { "answer_id": 224218, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "break break" }, { "answer_id": 224219, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 3, "selected": false, "text": "while( 1 )\n{\n game->update();\n game->render();\n}\n" }, { "answer_id": 224228, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 2, "selected": false, "text": "int scoped_variable;\ndo {\n scoped_variable = getSomeValue();\n} while (scoped_variable != some_value);\n" }, { "answer_id": 224237, "author": "Loren Pechtel", "author_id": 10659, "author_profile": "https://Stackoverflow.com/users/10659", "pm_score": 0, "selected": false, "text": "Repeat\n Something\nUntil Exit_Condition;\n" }, { "answer_id": 224242, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 1, "selected": false, "text": "break" }, { "answer_id": 224914, "author": "orj", "author_id": 20480, "author_profile": "https://Stackoverflow.com/users/20480", "pm_score": 1, "selected": false, "text": "const bool heatDeathOfTheUniverse = false;\ndo \n{\n // stuff\n} while(!heatDeathOfTheUniverse);\n bool done = false;\nwhile(!done) \n{\n if(done = AreWeDone()) continue; // continue jumps back to start of the loop \n} \n" }, { "answer_id": 1184149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "while(true)\n{\n //Do something like respond to requests\n}\n" }, { "answer_id": 2918307, "author": "emory", "author_id": 348975, "author_profile": "https://Stackoverflow.com/users/348975", "pm_score": 2, "selected": false, "text": "while ( true ) { go2Target ( ) ; }\n while ( ! blown2Bits ( ) ) { go2Target ( ) ; }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23786/" ]
224,225
<p>How would you program a C/C++ application that could run without opening a window or console? </p>
[ { "answer_id": 224226, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "#include <windows.h>\n\nint APIENTRY WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPTSTR lpCmdLine,\n int nCmdShow)\n{\n // <-- Program logic here\n return 0;\n} \n int main(int argc, char**argv)\n{\n // <-- Program logic here\n return 0;\n}\n" }, { "answer_id": 224372, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 6, "selected": true, "text": "#include <Windows.h>\n\nint WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance, \n LPTSTR lpCmdLine, \n int cmdShow)\n {\n /* do your stuff here. If you return from this function the program ends */\n }\n" }, { "answer_id": 54832944, "author": "WndProc", "author_id": 11053032, "author_profile": "https://Stackoverflow.com/users/11053032", "pm_score": 2, "selected": false, "text": "#include <windows.h>\n#include <stdio.h>\n\nint CALLBACK WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n MSG msg;\n DWORD curThreadId;\n\n curThreadId = GetCurrentThreadId();\n\n // Send messages to self:\n PostThreadMessage(curThreadId, WM_USER, 1, 2);\n PostThreadMessage(curThreadId, WM_USER+1, 3, 4);\n PostThreadMessage(curThreadId, WM_USER+2, 5, 6);\n PostThreadMessage(curThreadId, WM_USER+3, 7, 8);\n PostThreadMessage(curThreadId, WM_QUIT, 9, 10);\n\n while (GetMessage(&msg, NULL, 0, 0)) {\n printf(\"message: %d; wParam: %d; lParam: %d\\n\", msg.message, msg.wParam, msg.lParam);\n }\n\n return (int) msg.wParam;\n} \n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27211/" ]
224,232
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/25458/how-costly-is-net-reflection">How costly is .NET reflection?</a> </p> </blockquote> <p>I am currently in a programming mentality that reflection is my best friend. I use it a lot for dynamic loading of content that allows "loose implementation" rather than strict interfaces, as well as a lot of custom attributes.</p> <p>What is the "real" cost to using reflection?</p> <p>Is it worth the effort for frequently reflected types to have cached reflection, such as our own pre-LINQ DAL object code on all the properties to table definitions?</p> <p>Would the caching memory footprint outwieght the reflection CPU usage?</p>
[ { "answer_id": 224280, "author": "Tom Anderson", "author_id": 13502, "author_profile": "https://Stackoverflow.com/users/13502", "pm_score": 2, "selected": false, "text": "[TableName(\"Table\")]\npublic class SomeDal : BaseDal\n{\n [FieldName(\"Field\")]\n public string Field\n}\n" }, { "answer_id": 224611, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "Delegate.CreateDelegate CreateDelegate Delegate.CreateDelegate Expression" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13502/" ]
224,236
<p>I have a string.</p> <pre><code>string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@"; </code></pre> <p>I need to add a newline after every occurence of "@" symbol in the string.</p> <p>My Output should be like this</p> <pre><code>fkdfdsfdflkdkfk@ dfsdfjk72388389@ kdkfkdfkkl@ jkdjkfjd@ jjjk@ </code></pre>
[ { "answer_id": 224244, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 10, "selected": true, "text": "Environment.NewLine string text = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n\ntext = text.Replace(\"@\", \"@\" + System.Environment.NewLine);\n" }, { "answer_id": 224248, "author": "Jason", "author_id": 4486, "author_profile": "https://Stackoverflow.com/users/4486", "pm_score": 6, "selected": false, "text": "string newString = oldString.Replace(\"@\", \"@\\n\"); \n NewLine Environment" }, { "answer_id": 224250, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 3, "selected": false, "text": "using System;\n\nnamespace NewLineThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n string str = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n str = str.Replace(\"@\", \"@\" + Environment.NewLine);\n Console.WriteLine(str);\n Console.ReadKey();\n }\n }\n}\n" }, { "answer_id": 224261, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 4, "selected": false, "text": "@ str.Replace(\"@\", \"@\" + System.Environment.NewLine) @" }, { "answer_id": 224413, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 4, "selected": false, "text": "Console.Write(strToProcess.Replace(\"@\", \"@\" + Environment.NewLine));\n" }, { "answer_id": 225491, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 2, "selected": false, "text": "string file = @\"C:\\file.txt\";\nstring strToProcess = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\nstring[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);\n\nusing (StreamWriter writer = new StreamWriter(file))\n{\n foreach (string line in lines)\n {\n writer.WriteLine(line + \"@\");\n }\n}\n" }, { "answer_id": 225580, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 3, "selected": false, "text": "using System;\nusing System.IO;\n\nstatic class Program\n{\n static void Main()\n {\n WriteToFile\n (\n @\"C:\\test.txt\",\n \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\",\n \"@\"\n );\n\n /*\n output in test.txt in windows =\n fkdfdsfdflkdkfk@\n dfsdfjk72388389@\n kdkfkdfkkl@\n jkdjkfjd@\n jjjk@ \n */\n }\n\n public static void WriteToFile(string filename, string text, string newLineDelim)\n {\n bool equal = Environment.NewLine == \"\\r\\n\";\n\n //Environment.NewLine == \\r\\n = True\n Console.WriteLine(\"Environment.NewLine == \\\\r\\\\n = {0}\", equal);\n\n //replace newLineDelim with newLineDelim + a new line\n //trim to get rid of any new lines chars at the end of the file\n string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();\n\n using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))\n {\n sw.Write(filetext);\n }\n }\n}\n" }, { "answer_id": 4276814, "author": "Glinas", "author_id": 520103, "author_profile": "https://Stackoverflow.com/users/520103", "pm_score": 2, "selected": false, "text": "string str = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\nstr = str.Replace(\"@\", Environment.NewLine);\nrichTextBox1.Text = str;\n" }, { "answer_id": 34466976, "author": "TehSpowage", "author_id": 5717479, "author_profile": "https://Stackoverflow.com/users/5717479", "pm_score": 1, "selected": false, "text": "string[] something = text.Split('@') char element + System.Environment.NewLine System.IO.File.WriteAllLines([file path + name and extension], [array name])" }, { "answer_id": 47693380, "author": "Papun Sahoo", "author_id": 8504431, "author_profile": "https://Stackoverflow.com/users/8504431", "pm_score": -1, "selected": false, "text": "protected void Button1_Click(object sender, EventArgs e)\n{\n string str = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n str = str.Replace(\"@\", \"@\" + \"<br/>\");\n Response.Write(str); \n}\n" }, { "answer_id": 48092915, "author": "FAREH", "author_id": 1489592, "author_profile": "https://Stackoverflow.com/users/1489592", "pm_score": -1, "selected": false, "text": "using System;\nusing System.IO;\nusing System.Text;\n\nclass Test\n{\n public static void Main()\n {\n string strToProcess = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\n strToProcess.Replace(\"@\", Environment.NewLine);\n Console.WriteLine(strToProcess);\n }\n}\n" }, { "answer_id": 49152020, "author": "Kathiravan C", "author_id": 9456644, "author_profile": "https://Stackoverflow.com/users/9456644", "pm_score": 2, "selected": false, "text": "string strToProcess = \"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@\";\nvar result = strToProcess.Replace(\"@\", \"@ \\r\\n\");\nConsole.WriteLine(result);\n" }, { "answer_id": 68949483, "author": "Mohamed Musthaque", "author_id": 4121708, "author_profile": "https://Stackoverflow.com/users/4121708", "pm_score": 2, "selected": false, "text": "string strToProcess = \"fkdfdsfdflkdkfk\"+ System.Environment.NewLine +\" dfsdfjk72388389\"+ System.Environment.NewLine +\"kdkfkdfkkl\"+ System.Environment.NewLine +\"jkdjkfjd\"+ System.Environment.NewLine +\"jjjk\"+ System.Environment.NewLine;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
224,239
<p>I have an array of shorts (short[]) that I need to write out to a file. What's the quickest way to do this?</p>
[ { "answer_id": 224251, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 5, "selected": true, "text": " static void WriteShorts(short[] values, string path)\n {\n using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))\n {\n using (BinaryWriter bw = new BinaryWriter(fs))\n {\n foreach (short value in values)\n {\n bw.Write(value);\n }\n }\n }\n }\n" }, { "answer_id": 224275, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": false, "text": "static void WriteShorts(short[] values, string path)\n{\n using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))\n {\n using (BinaryWriter bw = new BinaryWriter(fs))\n {\n // Write the number of items\n bw.Write(values.Length);\n\n foreach (short value in values)\n {\n bw.Write(value);\n }\n }\n }\n}\n" }, { "answer_id": 42907226, "author": "Andreas Zita", "author_id": 382838, "author_profile": "https://Stackoverflow.com/users/382838", "pm_score": 1, "selected": false, "text": "[Test]\npublic void TestShortArray()\n{\n var n = 100000000;\n var input = new short[n];\n var r = new Random();\n for (var i = 0; i < n; i++) input[i] = (short)r.Next();\n var bf = new BinaryFormatter();\n var sw = new Stopwatch();\n using (var ms = new MemoryStream())\n {\n sw.Start();\n bf.Serialize(ms, input);\n sw.Stop();\n Console.WriteLine(\"BinaryFormatter serialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n sw.Reset();\n ms.Seek(0, SeekOrigin.Begin);\n sw.Start();\n var output = (short[])bf.Deserialize(ms);\n sw.Stop();\n Console.WriteLine(\"BinaryFormatter deserialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n Assert.AreEqual(input, output);\n }\n sw.Reset();\n using (var ms = new MemoryStream())\n {\n var bw = new BinaryWriter(ms, Encoding.UTF8, true);\n sw.Start();\n bw.Write(input.Length);\n for (var i = 0; i < input.Length; i++) bw.Write(input[i]);\n sw.Stop();\n Console.WriteLine(\"BinaryWriter serialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n sw.Reset();\n ms.Seek(0, SeekOrigin.Begin);\n var br = new BinaryReader(ms, Encoding.UTF8, true);\n sw.Start();\n var length = br.ReadInt32();\n var output = new short[length];\n for (var i = 0; i < length; i++) output[i] = br.ReadInt16();\n sw.Stop();\n Console.WriteLine(\"BinaryReader deserialize: \" +\n sw.ElapsedMilliseconds + \" ms, \" + ms.ToArray().Length + \" bytes\");\n Assert.AreEqual(input, output);\n }\n}\n BinaryFormatter serialize: 175 ms, 200000028 bytes\nBinaryFormatter deserialize: 79 ms, 200000028 bytes\nBinaryWriter serialize: 1499 ms, 200000004 bytes\nBinaryReader deserialize: 1599 ms, 200000004 bytes\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
224,253
<p>I want to change the order of XML using XDocument</p> <pre><code>&lt;root&gt; &lt;one&gt;1&lt;/one&gt; &lt;two&gt;2&lt;/two&gt; &lt;/root&gt; </code></pre> <p>I want to change the order so that 2 appears before 1. Is this capability baked in or do I have to do it myself. For example, remove then AddBeforeSelf()?</p> <p>Thanks</p>
[ { "answer_id": 224299, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 1, "selected": false, "text": "static void Main(string[] args)\n{\n XDocument doc = new XDocument(\n new XElement(\"root\",\n new XElement(\"one\", 1),\n new XElement(\"two\", 2)\n ));\n\n var results = from XElement el in doc.Element(\"root\").Descendants()\n orderby el.Value descending\n select el;\n\n foreach (var item in results)\n Console.WriteLine(item);\n\n doc.Root.ReplaceAll( results.ToArray());\n\n Console.WriteLine(doc);\n\n Console.ReadKey();\n}\n" }, { "answer_id": 720918, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public static class XElementExtensions\n{\n public static void OrderElements(this XElement parent, params string[] orderedLocalNames)\n { \n List<string> order = new List<string>(orderedLocalNames); \n var orderedNodes = parent.Elements().OrderBy(e => order.IndexOf(e.Name.LocalName) >= 0? order.IndexOf(e.Name.LocalName): Int32.MaxValue);\n parent.ReplaceNodes(orderedNodes);\n }\n}\n// using the extension method before persisting xml\nthis.Root.Element(\"parentNode\").OrderElements(\"one\", \"two\", \"three\", \"four\");\n" }, { "answer_id": 3941422, "author": "podeig", "author_id": 284405, "author_profile": "https://Stackoverflow.com/users/284405", "pm_score": 2, "selected": false, "text": "XElement node = ...get the element...\n\n//Move up\nif (node.PreviousNode != null) {\n node.PreviousNode.AddBeforeSelf(node);\n node.Remove();\n}\n\n//Move down\nif (node.NextNode != null) {\n node.NextNode.AddAfterSelf(node);\n node.Remove();\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30210/" ]
224,295
<p>I have two tables, one that contains volunteers, and one that contains venues. <strong>Volunteers are assigned one venue each</strong>.</p> <p>The id of the venues table (venues.id) is placed within the volunteers table in the venue_id column (volunteers.venue_id).</p> <p>I know I could get a count of how many matching values are in the volunteers.venue_id column by</p> <pre><code>SELECT venue_id, COUNT(*) FROM volunteers GROUP BY venue_id </code></pre> <p>Why I want to do this: so the user can go in and see how many volunteers are assigned to each venue.</p> <p>table: volunteers -- columns: id, name, venue_id</p> <p>table: venues -- columns: id, venue_name</p> <p>volunteers.venue_id = venues.id</p> <p>I know this would be a join statement of some sort so it will get a count of each venue, then match up volunteers.venue_id to venues.id and print out the venues.venue_name along with the count.</p> <p>How would I go about joining the two tables to print out the venue name and next to it, list the count of each volunteer with that venue_id?</p>
[ { "answer_id": 224304, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 1, "selected": false, "text": "SELECT venues.venue_name, COUNT(volunteers.*) AS cvolun\n FROM venues\n INNER JOIN volunteers\n ON venues.id = volunteers.venue_id\n" }, { "answer_id": 224317, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "select venues.venue_name, count(*) as volunteer_count\nfrom venues\nleft outer join volunteers\n on venues.id = volunteers.venue_id\ngroup by venues.venue_name\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
224,297
<p>I have the following models.</p> <pre><code># app/models/domain/domain_object.rb class Domain::DomainObject &lt; ActiveRecord::Base has_many :links_from, :class_name =&gt; "Link", :as =&gt; :from, :dependent =&gt; :destroy end # app/models/link.rb class Link &lt; ActiveRecord::Base belongs_to :from, :polymorphic =&gt; true belongs_to :object_value, :polymorphic =&gt; true end </code></pre> <p>Problem is, when I do the following, the from_type doesn't prefix the Domain namespace to the model e.g.</p> <pre><code> Domain::DomainObject.all(:include=&gt; :links_from ) </code></pre> <p>That causes the following SELECT:</p> <pre><code> SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'DomainObject') </code></pre> <p>The query should be:</p> <pre><code> SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'Domain::DomainObject') </code></pre> <p>because Rails automatically saves the model with the namespace. </p> <p>I've seen a few recommendations on Rails sites about doing something like this:</p> <pre><code> belongs_to :from, :polymorphic =&gt; true, :class_name =&gt; "Domain::DomainObject" </code></pre> <p>However, that doesn't appear to work either. </p> <p>So, is there a better way to do this? Or is this not supported?</p>
[ { "answer_id": 231901, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 4, "selected": true, "text": "include Domain DomainObject ActiveRecord::Base.store_full_sti_class = true config/environment.rb" }, { "answer_id": 37234120, "author": "progfan", "author_id": 1998200, "author_profile": "https://Stackoverflow.com/users/1998200", "pm_score": 2, "selected": false, "text": "x.store_full_sti_class = true config/environment.rb class User < ActiveRecord::Base\n self.store_full_sti_class = true\n ...\nend\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499/" ]
224,298
<p>We have just 'migrated' an SQL Server 2005 database from DEVEL into TEST. Somehow during the migration process the DB was changed from case insensitive to sensitive - so most SQL queries broke spectacularly.</p> <p>What I would like to know, is - are there any clear benefits to having a case sensitive schema? </p> <p>NOTE: By this I mean table names, column names, stored proc names etc. I am NOT referring to the actually data being stored in the tables.</p> <p>At first inspection, I cannot find a valid reason that offers benefits over case insensitivity.</p>
[ { "answer_id": 224357, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 3, "selected": false, "text": "table_file = lc(table_name) this_table This_Table SELECT this, that FROM Table;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15052/" ]
224,301
<p>I have an Excel 2003 workbook that contains a macro to copy certain of its sheets across to a new workbook, then save and close the new workbook. It does this several dozen times, with slightly different sheet selections each time.</p> <p>I would like to add an extra step to the macro to export the secondary workbooks' spreadsheets to PDF. The obvious way to do this would be to use a PDF printer and Excel's built in Print function, but most PDF printers give you a "Save As..." dialogue box before they finish. Obviously, typing this in individually for seventy-odd occasions lacks appeal - so I'd like something that allows me to set it ahead of time (probably "Use the filename of the file I'm printing minus its extension") then just select the default options.</p> <p>Any ideas for a free PDF printer that does this? Or a suitable alternative?</p>
[ { "answer_id": 7766561, "author": "Diego Castro", "author_id": 193971, "author_profile": "https://Stackoverflow.com/users/193971", "pm_score": 2, "selected": false, "text": "Sub PDF_Print() \n Dim p \n p = ActivePrinter \n ActivePrinter = \"PDFCreator\" \n ActiveDocument.PrintOut \n ActivePrinter = p \nEnd Sub \n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27290/" ]
224,311
<p>Is there a better way to negate a boolean in Java than a simple if-else?</p> <pre><code>if (theBoolean) { theBoolean = false; } else { theBoolean = true; } </code></pre>
[ { "answer_id": 224314, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 10, "selected": true, "text": "theBoolean = !theBoolean;\n" }, { "answer_id": 224380, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "theBoolean ^= true;\n" }, { "answer_id": 29409907, "author": "Nikhil Kumar", "author_id": 2845282, "author_profile": "https://Stackoverflow.com/users/2845282", "pm_score": -1, "selected": false, "text": "boolean result = isresult();\nif (result) {\n result = false;\n} else {\n result = true;\n}\n boolean result = isresult();\nresult ^= true;\n" }, { "answer_id": 40594008, "author": "Levite", "author_id": 1680919, "author_profile": "https://Stackoverflow.com/users/1680919", "pm_score": 6, "selected": false, "text": "theBoolean = !theBoolean;\n theBoolean ^= true;\n theBoolean = theBoolean ? false : true;\n theMethod( theBoolean ^= true );\n" }, { "answer_id": 44861689, "author": "Steven Spungin", "author_id": 5093961, "author_profile": "https://Stackoverflow.com/users/5093961", "pm_score": 2, "selected": false, "text": "static public boolean toggle(Boolean aBoolean) {\n if (aBoolean == null) return true;\n else return !aBoolean;\n}\n static public boolean toggle(boolean aBoolean) {\n return !aBoolean;\n}\n boolean bTrue = true\nboolean bFalse = false\nboolean bNull = null\n\ntoggle(bTrue) // == false\ntoggle(bFalse) // == true\ntoggle(bNull) // == true\n Boolean b = false\nb = b.toggle() // == true\n" }, { "answer_id": 55638309, "author": "Will D.", "author_id": 9591616, "author_profile": "https://Stackoverflow.com/users/9591616", "pm_score": -1, "selected": false, "text": "public class Util {\n\n\npublic Util() {}\npublic boolean flip(boolean bool) { return !bool; }\npublic void sop(String str) { System.out.println(str); }\n\n}\n Util u = new Util(); System.out.println( u.flip(bool) );" }, { "answer_id": 57517945, "author": "Doctor Parameter", "author_id": 2414189, "author_profile": "https://Stackoverflow.com/users/2414189", "pm_score": 3, "selected": false, "text": "Boolean.valueOf(aBool).equals(false)\n Boolean.FALSE.equals(aBool)\n Boolean.FALSE::equals\n" }, { "answer_id": 62198314, "author": "Alex", "author_id": 3512734, "author_profile": "https://Stackoverflow.com/users/3512734", "pm_score": 1, "selected": false, "text": "BooleanUtils BooleanUtils.negate(theBoolean)\n" }, { "answer_id": 72028627, "author": "Dan Morton", "author_id": 6831227, "author_profile": "https://Stackoverflow.com/users/6831227", "pm_score": 1, "selected": false, "text": "Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;\nBoolean inverse = original == null ? null : !original;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26237/" ]
224,337
<p>I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.</p> <p>However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.</p> <p>I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.</p> <p>However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.</p> <p>Are there any tutorials for making "dynamic panels" or better management of a wizard?</p>
[ { "answer_id": 224800, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 4, "selected": true, "text": "import wx\nimport wx.lib.newevent\n\n\n(PageChangeEvent, EVT_PAGE_CHANGE) = wx.lib.newevent.NewEvent()\n\n\nclass Data:\n foo = None\n bar = None\n\n\nclass Page1(wx.Panel):\n def __init__(self, parent, data):\n wx.Panel.__init__(self, parent)\n self.parent = parent\n self.data = data\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(sizer)\n label = wx.StaticText(self, label=\"Page 1 - foo\")\n self.foo = wx.TextCtrl(self)\n goto_page2 = wx.Button(self, label=\"Go to page 2\")\n\n for c in (label, self.foo, goto_page2):\n sizer.Add(c, 0, wx.TOP, 5)\n\n goto_page2.Bind(wx.EVT_BUTTON, self.OnPage2)\n\n def OnPage2(self, event):\n self.data.foo = self.foo.Value\n wx.PostEvent(self.parent, PageChangeEvent(page=Page2))\n\n\nclass Page2(wx.Panel):\n def __init__(self, parent, data):\n wx.Panel.__init__(self, parent)\n self.parent = parent\n self.data = data\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(sizer)\n label = wx.StaticText(self, label=\"Page 2 - bar\")\n self.bar = wx.TextCtrl(self)\n goto_finish = wx.Button(self, label=\"Finish\")\n\n for c in (label, self.bar, goto_finish):\n sizer.Add(c, 0, wx.TOP, 5)\n\n goto_finish.Bind(wx.EVT_BUTTON, self.OnFinish)\n\n def OnFinish(self, event):\n self.data.bar = self.bar.Value\n wx.PostEvent(self.parent, PageChangeEvent(page=finish))\n\n\ndef finish(parent, data):\n wx.MessageBox(\"foo = %s\\nbar = %s\" % (data.foo, data.bar))\n wx.GetApp().ExitMainLoop()\n\n\nclass Test(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.data = Data()\n self.current_page = None\n\n self.Bind(EVT_PAGE_CHANGE, self.OnPageChange)\n wx.PostEvent(self, PageChangeEvent(page=Page1))\n\n def OnPageChange(self, event):\n page = event.page(self, self.data)\n if page == None:\n return\n if self.current_page:\n self.current_page.Destroy()\n self.current_page = page\n page.Layout()\n page.Fit()\n page.Refresh()\n\n\napp = wx.PySimpleApp()\napp.TopWindow = Test()\napp.TopWindow.Show()\napp.MainLoop()\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
224,345
<p>I have been trying to learn how to add testing to existing code -- currently reading reading <a href="https://rads.stackoverflow.com/amzn/click/com/0131177052" rel="noreferrer" rel="nofollow noreferrer">Working Effectively With Legacy Code</a>. I have been trying to apply some of the principles in JavaScript, and now I'm trying to extract an interface.</p> <p>In searching for creating interfaces in JavaScript, I can't find a lot -- and what I find about inheritance seems like their are several different ways. (Some people create their own base classes to provide helpful methods to make it easier to do inheritance, some use functions, some use prototypes).</p> <p>What's the right way? Got a simple example for extracting an interface in JavaScript?</p>
[ { "answer_id": 224377, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "function Implements(obj, inter)\n{\n var len = inter.length, i = 0;\n for (; i < len; ++i)\n {\n if (!obj[inter[i]])\n return false;\n }\n return true;\n}\n\nvar IUser = [\"LoadUser\", \"SaveUser\"];\n\nvar user = {\n LoadUser : function()\n {\n alert(\"Load\");\n },\n\n SaveUser : function()\n {\n alert(\"Save\");\n }\n };\n\nvar notUser = {\n LoadUser : function()\n {\n alert(\"Load\");\n }\n };\n\nalert(Implements(user, IUser));\nalert(Implements(notUser, IUser));\n function InheritObject(base, obj)\n{\n for (name in base)\n {\n if (!obj[name])\n obj[name] = base[name];\n }\n}\n\nvar Base = {\n BaseFunc : function() { alert(\"BaseFunc from base\"); },\n InheritFunc : function() { alert(\"InheritFunc from base\"); }\n }\n\nvar Inherit = {\n InheritFunc : function() { alert(\"InheritFunc from inherit\"); },\n AnotherFunc : function() { alert(\"AnotherFunc from inherit\"); }\n }\n\nInheritObject(Base, Inherit);\n\nInherit.InheritFunc();\nInherit.BaseFunc();\nInherit.AnotherFunc();\n\nBase.BaseFunc();\nBase.InheritFunc();\n" }, { "answer_id": 225697, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 0, "selected": false, "text": "var Animal = Class.create({\n initialize: function(name, sound) {\n this.name = name;\n this.sound = sound;\n },\n\n speak: function() {\n alert(this.name + \" says: \" + this.sound + \"!\");\n }\n});\n\n// subclassing Animal\nvar Snake = Class.create(Animal, {\n initialize: function($super, name) {\n $super(name, 'hissssssssss');\n }\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525/" ]
224,359
<p>What is the best way to delete a database record using LINQ when I have the primary key? </p>
[ { "answer_id": 224401, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 1, "selected": false, "text": "var products = from p in db.Products select p;\ndb.Products.DeleteOnSubmit(products.Take(1).Single()); <--seemed nasty\ndb.SubmitChanges();\n Service service = db.Services.Where(s => s.id == serviceID).FirstOrDefault(); <--nicer\ndb.Services.DeleteOnSubmit(service);\ndb.SubmitChanges();\n" }, { "answer_id": 224452, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": " public static Delete(this ITable table, object key)\n { var t = table.GetType();\n var tableName = t.GetCustomAttributes\n (typeof(TableAttribute),false)[0].Name;\n var primaryKey = (from p in t.GetProperties()\n from c in p.GetCustomAttributes\n (typeof(ColumnAttribute),false)\n where c.IsPrimaryKey\n select c.Name).Single();\n using (var cmd = table.Context.Connection.CreateCommand())\n { cmd.CommandText = string.Format( \"DELETE FROM {0} WHERE {1} = @key\"\n ,tableName, primaryKey);\n cmd.Parameters.Add(new SqlParameter(\"@key\", key));\n cmd.ExecuteNonQuery(); \n } \n }\n\n/* ... */\ndataContext.Table1.Delete(id);\n" }, { "answer_id": 225804, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "public void DeleteCustomer(int CustomerID)\n{\n NorthwindContext c = new NorthwindContext c;\n Customer target = new Customer(){CustomerID = CustomerID};\n c.Customers.Attach(target);\n c.Customers.DeleteOnSubmit(target);\n c.SubmitChanges(); \n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
224,379
<p>I see this all the time in Ruby:</p> <pre><code>require File.dirname(__FILE__) + "/../../config/environment" </code></pre> <p>What does <code>__FILE__</code> mean?</p>
[ { "answer_id": 224383, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 8, "selected": true, "text": "foo.rb __FILE__ \"foo.rb\" # test.rb\nputs __FILE__\nrequire './dir2/test.rb'\n # dir2/test.rb\nputs __FILE__\n ruby test.rb test.rb\n/full/path/to/dir2/test.rb\n" }, { "answer_id": 335191, "author": "Ethan", "author_id": 42595, "author_profile": "https://Stackoverflow.com/users/42595", "pm_score": 5, "selected": false, "text": "__FILE__ foo.rb __FILE__ foo.rb /home/josh File.dirname(__FILE__) /home/josh" }, { "answer_id": 784792, "author": "Matt Wolfe", "author_id": 94557, "author_profile": "https://Stackoverflow.com/users/94557", "pm_score": 4, "selected": false, "text": "__FILE__ __FILE__ File.expand_path(File.dirname(__FILE__) + \"relative/path/to/file\")\n __FILE__" }, { "answer_id": 894056, "author": "Luke Bayes", "author_id": 105023, "author_profile": "https://Stackoverflow.com/users/105023", "pm_score": 6, "selected": false, "text": "__FILE__ Dir.chdir puts __FILE__\nDir.chdir '../../'\nputs __FILE__\n __FILE__ require Dir.chdir $MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))\n\n# open class and do some stuff that changes directory\n\nputs $MY_FILE_PATH\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
224,397
<p>I was taking a look through some open-source C++ code and I noticed a lot of double underscores used within in the code, mainly at the start of variable names.</p> <pre><code>return __CYGWIN__; </code></pre> <p>Just wondering: Is there a reason for this, or is it just some people's code styles? I would think that it makes it hard to read.</p>
[ { "answer_id": 224426, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 4, "selected": false, "text": "__Symbol__ __FILE__ __LINE__" }, { "answer_id": 56388858, "author": "RemarkableBucket", "author_id": 8453543, "author_profile": "https://Stackoverflow.com/users/8453543", "pm_score": 3, "selected": false, "text": "lex.name" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
224,408
<p>Is there a better/simpler way to find the number of images in a directory and output them to a variable?</p> <pre><code>function dirCount($dir) { $x = 0; while (($file = readdir($dir)) !== false) { if (isImage($file)) {$x = $x + 1} } return $x; } </code></pre> <p>This seems like such a long way of doing this, is there no simpler way?</p> <p><strong>Note:</strong> The isImage() function returns true if the file is an image.</p>
[ { "answer_id": 224439, "author": "bbxbby", "author_id": 29230, "author_profile": "https://Stackoverflow.com/users/29230", "pm_score": 6, "selected": true, "text": "$dir = new DirectoryIterator('/path/to/dir');\nforeach($dir as $file ){\n $x += (isImage($file)) ? 1 : 0;\n}\n" }, { "answer_id": 224505, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 4, "selected": false, "text": "iterator_count(new DirectoryIterator('path/to/dir/'));\n" }, { "answer_id": 224509, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "glob $count = 0;\nforeach (glob(\"*.*\") as $file) {\n if (isImage($file)) ++$count;\n}\n $count = count(glob(\"*.{jpg,png,gif,bmp}\"));\n" }, { "answer_id": 931870, "author": "salathe", "author_id": 113938, "author_profile": "https://Stackoverflow.com/users/113938", "pm_score": 1, "selected": false, "text": "DirectoryIterator isImage FilterIterator class ImageIterator extends FilterIterator {\n\n public function __construct($path)\n {\n parent::__construct(new DirectoryIterator($path));\n }\n\n public function accept()\n {\n return isImage($this->getInnerIterator());\n }\n}\n iterator_count Countable count $images = new ImageIterator('/path/to/images');\nprintf('Found %d images!', iterator_count($images));\n isImage ImageIterator" }, { "answer_id": 3905596, "author": "Josh Dunbar", "author_id": 472213, "author_profile": "https://Stackoverflow.com/users/472213", "pm_score": 2, "selected": false, "text": "$count = count(glob(\"*.{jpg,png,gif,bmp}\"));\n GLOB_BRACE $count = count(glob(\"*.{jpg,png,gif,bmp}\", GLOB_BRACE));\n" }, { "answer_id": 14567412, "author": "haheute", "author_id": 2018961, "author_profile": "https://Stackoverflow.com/users/2018961", "pm_score": 3, "selected": false, "text": "$files = scandir($dir);\n$x = count($files);\necho $x;\n" }, { "answer_id": 16444356, "author": "Marc", "author_id": 1067109, "author_profile": "https://Stackoverflow.com/users/1067109", "pm_score": 0, "selected": false, "text": "return count(glob(\"/path/to/file/[!\\.]*\"));\n" }, { "answer_id": 16881552, "author": "user2444847", "author_id": 2444847, "author_profile": "https://Stackoverflow.com/users/2444847", "pm_score": 0, "selected": false, "text": "$nfiles = glob(\"/path/to/file/[!\\\\.]*\");\n\nif ($nfiles !== FALSE){\n\n return count($nfiles);\n\n} else {\n\n return 0;\n\n}\n" }, { "answer_id": 35602891, "author": "Shailesh Ladumor", "author_id": 5974595, "author_profile": "https://Stackoverflow.com/users/5974595", "pm_score": 1, "selected": false, "text": " $dir = public_path('img/');\n $files = glob($dir . '*.*');\n\n if ( $files !== false )\n {\n $total_count = count( $files );\n return $totalCount;\n }\n else\n {\n return 0;\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
224,410
<p>I'm having some trouble getting log4net to work from ASP.NET 3.5. This is the first time I've tried to use log4net, I feel like I'm missing a piece of the puzzle.</p> <p>My project references the log4net assembly, and as far as I can tell, it is being deployed successfully on my server.</p> <p>My web.config contains the following:</p> <pre><code> &lt;configSections&gt; &lt;section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler , log4net" requirePermission="false"/&gt; &lt;/configSections&gt; &lt;log4net&gt; &lt;appender name="InfoAppender" type="log4net.Appender.FileAppender"&gt; &lt;file value="..\..\logs\\InfoLog.html" /&gt; &lt;appendToFile value="true" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%d [%t] %-5p %c [%x] - %m%n" /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;logger name="_Default"&gt; &lt;level value="INFO" /&gt; &lt;appender-ref ref="InfoAppender" /&gt; &lt;/logger&gt; &lt;/log4net&gt; </code></pre> <p>I'm using the following code to test the logger:</p> <pre><code>using log4net; using log4net.Config; public partial class _Default : System.Web.UI.Page { private static readonly ILog log = LogManager.GetLogger("_Default"); protected void Page_Load(object sender, EventArgs e) { log.Info("Hello logging world!"); } } </code></pre> <p>In my Global.asax, I'm doing the following:</p> <pre><code>void Application_Start(object sender, EventArgs e) { log4net.Config.XmlConfigurator.Configure(); } </code></pre> <p>At this point, I can't think of what else I might be doing wrong. The directory I'm trying to store the log in is writable, and even if I try different directories I get the same result: no file, no logs.</p> <p>Any suggestions? :-)</p> <hr> <p>Edit: I've tried several different formats for the path &amp; name of the log file, some of which include "..\..\InfoLog.html", "InfoLog.html", "logs\InfoLog.html", etc, just in case someone is wondering if that's the problem.</p> <hr> <p>Edit: I've added the root logger node back into the log4net section, I ommitted that on accident when copying from the samples. The root logger node looks like this:</p> <pre><code>&lt;root&gt; &lt;level value="INFO" /&gt; &lt;appender-ref ref="InfoAppender" /&gt; &lt;/root&gt; </code></pre> <p>Even with it, however, I'm still having no luck.</p>
[ { "answer_id": 289160, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<%@ Application Language=\"C#\" %>\n\n<script runat=\"server\">\n\n void Application_Start(object sender, EventArgs e) \n {\n // Code that runs on application startup\n log4net.Config.XmlConfigurator.Configure(); \n }\n\n void Application_End(object sender, EventArgs e) \n {\n // Code that runs on application shutdown\n log4net.LogManager.Shutdown();\n }\n\n void Application_Error(object sender, EventArgs e) \n { \n // Code that runs when an unhandled error occurs\n }\n\n void Session_Start(object sender, EventArgs e) \n {\n // Code that runs when a new session is started\n }\n\n void Session_End(object sender, EventArgs e) \n {\n // Code that runs when a session ends. \n // Note: The Session_End event is raised only when the sessionstate mode\n // is set to InProc in the Web.config file. If session mode is set to StateServer \n // or SQLServer, the event is not raised.\n }\n</script>\n" }, { "answer_id": 289184, "author": "Chris", "author_id": 34942, "author_profile": "https://Stackoverflow.com/users/34942", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key=\"log4net.Internal.Debug\" value=\"true\"/>\n </appSettings>\n</configuration>\n" }, { "answer_id": 380539, "author": "Peter Lillevold", "author_id": 35245, "author_profile": "https://Stackoverflow.com/users/35245", "pm_score": 1, "selected": false, "text": "<file value=\"..\\\\..\\\\logs\\\\InfoLog.html\" />\n" }, { "answer_id": 380562, "author": "Pawel Krakowiak", "author_id": 41420, "author_profile": "https://Stackoverflow.com/users/41420", "pm_score": -1, "selected": false, "text": "private static readonly ILog log = LogManager.GetLogger(typeof(_Default));\n" }, { "answer_id": 719598, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 2, "selected": false, "text": "<section name=\"SubSonicService\" type=\"SubSonic.SubSonicSection, SubSonic\" requirePermission=\"false\"/>\n <section name=\"log4net\"\n type=\"log4net.Config.Log4NetConfigurationSectionHandler\n , log4net\"\n requirePermission=\"false\"/>\n <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" requirePermission=\"false\"/>\n" }, { "answer_id": 3860596, "author": "Herries E", "author_id": 466398, "author_profile": "https://Stackoverflow.com/users/466398", "pm_score": 1, "selected": false, "text": "// Configure log4net using the .config file\n[assembly: log4net.Config.XmlConfigurator(ConfigFile = \"log4net.config\", Watch = true)]\n\n//My Web Services class name\nprivate static readonly log4net.ILog log = log4net.LogManager.GetLogger(\"Service1\");\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18505/" ]
224,421
<p>In a <a href="https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom">coding style question about infinite loops</a>, some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant.</p> <p>This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoiding #ifdef hell. For instance, you can have in your header:</p> <pre><code>#ifdef CONFIG_FOO extern int foo_enabled; #else #define foo_enabled 0 #endif </code></pre> <p>And the code can simply use a conditional and trust the compiler to elide the dead code when CONFIG_FOO isn't defined:</p> <pre><code>if (foo_enabled) { ... } </code></pre> <p>Instead of having to test for CONFIG_FOO every time foo_enabled is used:</p> <pre><code>#ifdef CONFIG_FOO if (foo_enabled) { ... } #endif </code></pre> <p>This design pattern is used all the time in the Linux kernel (for instance, include/linux/cpumask.h defines several macros to 1 or 0 when SMP is disabled and to a function call when SMP is enabled).</p> <p>What is the reason for that MSVC warning? Additionally, is there a better way to avoid #ifdef hell without having to disable that warning? Or is it an overly broad warning which should not be enabled in general?</p>
[ { "answer_id": 224427, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": " if( x=0 )\n if( x==0 )\n" }, { "answer_id": 224435, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 0, "selected": false, "text": "#ifdef CONFIG_FOO\nextern int foo_enabled;\n#else\nextern int foo_enabled = 0;\n#endif\n" }, { "answer_id": 224437, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "const int x = 0;\n if (x != 0) ...\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28258/" ]
224,422
<p>My Flash (AS3/AIR) application is currently using a slightly unusual architecture (for a Flash app) to provide particular base classes for loaded content at runtime. The external content is published with 'stub' base classes, which are eclipsed by the 'real' base classes at runtime when it is loaded. I've heard this referred to by Adobe as <em>bootstrapping</em> (<a href="http://blogs.adobe.com/flexdoc/loadingSubApps.pdf" rel="nofollow noreferrer">pdf</a>), and it has been working very well for me until now. It's not unlike a DLL architecture I believe, although I'm not qualified to say for sure.</p> <p>Until now, the external content I have been loading has been loaded from within the same <code>SecurityDomain</code> (same sandbox), which allows me to easily load the content in a child <code>ApplicationDomain</code>. Unfortunately, as far as I can tell, an <code>ApplicationDomain</code>s that span <code>SecurityDomain</code>s cannot be related - that is, I cannot make an AppDom of one SecurityDom the child of an AppDom from another SecurityDom.</p> <p>But now I need to load this external content from outside my Application sandbox. There are plenty of ways to achieve communication across <code>SecurityDomain</code>s - although most of them are very limited, AIR's <code>sandboxBridge</code> API is probably the most powerful. Unfortunately, none of these communication methods allow me to achieve this bootstrapping architecture. </p> <p>I notice that the <code>LoaderContext</code> object has a <code>securityDomain</code> property, but Flash security prohibits 'local swfs' from touching it (it throws a <code>SecurityError</code> or similar).</p> <p>Flex's <code>SWFLoader</code> has a <code>trustContent</code> property that looks promising, but I'm inclined to assume that it has the same restrictions as setting the <code>SecurityDomain</code> in the <code>Loader</code>'s <code>LoaderContext</code>.</p> <p>I suspect I'll have to redesign (which won't be easy), but I thought I'd just check here that I've not missed something in my research.</p> <p>So ... any ideas or pearls of wisdom? I'd especially freaking love it if someone from Adobe who works on the Security model could gimme a definitive "yes/no it can/can't be done"...</p> <p>Thanks in advance!</p> <p><em>Addendum:</em> I've since decided to re-design the architecture so that the bootstrapping all happens on the external domain. My question still stands, however, out of curiosity.</p>
[ { "answer_id": 224427, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": " if( x=0 )\n if( x==0 )\n" }, { "answer_id": 224435, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 0, "selected": false, "text": "#ifdef CONFIG_FOO\nextern int foo_enabled;\n#else\nextern int foo_enabled = 0;\n#endif\n" }, { "answer_id": 224437, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "const int x = 0;\n if (x != 0) ...\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26331/" ]
224,430
<p>I'm currently using Subversion to manage my ASP.NET website. I'm finding that whenever I go to upload my website to my server, I'm copying a large number of hidden .svn folders and whatever contents may lie within them.</p> <p>Does anyone have any suggestions for avoiding this? I don't particularly want those hidden .svn folders on the production server, but short of manually deleting each .svn folder before I upload my website, I'm at a loss for how to have a .svn-folder-free production environment.</p> <hr> <p>Edit: Thank you everyone, those are great suggestions, I really appreciate it!</p>
[ { "answer_id": 224438, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 2, "selected": false, "text": ".svn svn export .svn" }, { "answer_id": 224448, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": " <PropertyGroup>\n <DropPath>..\\..\\drop\\</DropPath>\n <TestDropPath>..\\..\\test\\</TestDropPath>\n </PropertyGroup>\n <Target Name=\"AfterBuild\">\n <ItemGroup>\n <Binaries Include=\"$(OutputPath)**\\*.*\" />\n </ItemGroup>\n <ConvertToAbsolutePath Paths=\"$(DropPath)\">\n <Output TaskParameter=\"AbsolutePaths\" ItemName=\"FullDropPath\" />\n </ConvertToAbsolutePath>\n <Message Importance=\"High\" Text=\"Binplacing -&gt; @(FullDropPath)\" />\n <Copy SourceFiles=\"@(Compile)\" DestinationFiles=\"@(Compile->'$(DropPath)%(Identity)')\" />\n <Copy SourceFiles=\"@(Content)\" DestinationFiles=\"@(Content->'$(DropPath)%(Identity)')\" />\n <Copy SourceFiles=\"@(EntityDeploy)\" DestinationFiles=\"@(EntityDeploy->'$(DropPath)%(Identity)')\" />\n <Copy SourceFiles=\"@(Binaries)\" DestinationFiles=\"@(Binaries->'$(DropPath)%(Identity)')\" />\n </Target>\n svn export" }, { "answer_id": 224454, "author": "Cihan Ucar", "author_id": 12510, "author_profile": "https://Stackoverflow.com/users/12510", "pm_score": 2, "selected": false, "text": "Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Folder\\shell\\DeleteSVN]\n@=\"Delete SVN Folders\"\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Folder\\shell\\DeleteSVN\\command]\n@=\"cmd.exe /c \\\"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \\\"%1\\\" %%f IN (.svn) DO RD /s /q \\\"%%f\\\" \\\"\"\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18505/" ]
224,453
<p>I have a string encrypted in PHP that I would like to decrypt in C#. I used the tutorial below to do the encryption, but am having problems decrypting. Can anyone post an example on how to do this? </p> <p><a href="http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html" rel="noreferrer">http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html</a></p>
[ { "answer_id": 224524, "author": "deepcode.co.uk", "author_id": 20524, "author_profile": "https://Stackoverflow.com/users/20524", "pm_score": 5, "selected": true, "text": "class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(Decrypt(\"47794945c0230c3d\"));\n }\n\n static string Decrypt(string input)\n {\n TripleDES tripleDes = TripleDES.Create();\n tripleDes.IV = Encoding.ASCII.GetBytes(\"password\");\n tripleDes.Key = Encoding.ASCII.GetBytes(\"passwordDR0wSS@P6660juht\");\n tripleDes.Mode = CipherMode.CBC;\n tripleDes.Padding = PaddingMode.Zeros;\n\n ICryptoTransform crypto = tripleDes.CreateDecryptor();\n byte[] decodedInput = Decoder(input);\n byte[] decryptedBytes = crypto.TransformFinalBlock(decodedInput, 0, decodedInput.Length);\n return Encoding.ASCII.GetString(decryptedBytes);\n }\n\n static byte[] Decoder(string input)\n {\n byte[] bytes = new byte[input.Length/2];\n int targetPosition = 0;\n\n for( int sourcePosition=0; sourcePosition<input.Length; sourcePosition+=2 )\n {\n string hexCode = input.Substring(sourcePosition, 2);\n bytes[targetPosition++] = Byte.Parse(hexCode, NumberStyles.AllowHexSpecifier);\n }\n\n return bytes;\n }\n}\n" }, { "answer_id": 1765846, "author": "Richard Varno", "author_id": 214891, "author_profile": "https://Stackoverflow.com/users/214891", "pm_score": 4, "selected": false, "text": "<?php\n\nini_set('display_errors', 1);\nerror_reporting(E_ALL);\n\n// I blantantly stole, tweaked and happily used this code from: \n// Lord of Ports http://www.experts-exchange.com/M_1736399.html\n\n$ky = 'lkirwf897+22#bbtrm8814z5qq=498j5'; // 32 * 8 = 256 bit key\n$iv = '741952hheeyy66#cs!9hjv887mxx7@8y'; // 32 * 8 = 256 bit iv\n\n$text = \"Here is my data to encrypt!!!\";\n\n$from_vb = \"QBlgcQ2+v3wd8RLjhtu07ZBd8aQWjPMfTc/73TPzlyA=\"; // enter value from vb.net app here to test\n\n$etext = encryptRJ256($ky, $iv, $text);\n$dtext = decryptRJ256($ky, $iv, $etext);\n$vtext = decryptRJ256($ky, $iv, $from_vb);\n\necho \"<HR>orignal string: $text\";\necho \"<HR>encrypted in php: $etext\";\necho \"<HR>decrypted in php: $dtext\";\necho \"<HR>encrypted in vb: $from_vb\";\necho \"<HR>from vb decrypted in php: $vtext\"; \necho \"<HR>If you like it say thanks! richard dot varno at gmail dot com\";\n\nexit;\n\n\nfunction decryptRJ256($key,$iv,$string_to_decrypt)\n{\n $string_to_decrypt = base64_decode($string_to_decrypt);\n $rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);\n $rtn = rtrim($rtn, \"\\0\\4\");\n return($rtn);\n}\n\nfunction encryptRJ256($key,$iv,$string_to_encrypt)\n{\n $rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);\n $rtn = base64_encode($rtn);\n return($rtn);\n} \n?>\n Imports System\nImports System.Text\nImports System.Security.Cryptography\nImports System.IO\n\nModule Module1\n\n ' I blantantly stole, tweaked and happily used this code from: \n ' Lord of Ports http://www.experts-exchange.com/M_1736399.html\n\n Sub Main()\n\n 'Shared 256 bit Key and IV here\n Dim sKy As String = \"lkirwf897+22#bbtrm8814z5qq=498j5\" '32 chr shared ascii string (32 * 8 = 256 bit)\n Dim sIV As String = \"741952hheeyy66#cs!9hjv887mxx7@8y\" '32 chr shared ascii string (32 * 8 = 256 bit)\n\n Dim sTextVal As String = \"Here is my data to encrypt!!!\"\n\n Dim eText As String\n Dim dText As String\n\n eText = EncryptRJ256(sKy, sIV, sTextVal)\n dText = DecryptRJ256(sKy, sIV, eText)\n\n Console.WriteLine(\"key: \" & sKy)\n Console.WriteLine()\n Console.WriteLine(\" iv: \" & sIV)\n Console.WriteLine(\"txt: \" & sTextVal)\n Console.WriteLine(\"encrypted: \" & eText)\n Console.WriteLine(\"decrypted: \" & dText)\n Console.WriteLine(\"If you like it say thanks! richard dot varno at gmail dot com\")\n Console.WriteLine(\"press any key to exit\")\n Console.ReadKey(True)\n\n End Sub\n\n Public Function DecryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_decrypt As String)\n\n Dim sEncryptedString As String = prm_text_to_decrypt\n\n Dim myRijndael As New RijndaelManaged\n myRijndael.Padding = PaddingMode.Zeros\n myRijndael.Mode = CipherMode.CBC\n myRijndael.KeySize = 256\n myRijndael.BlockSize = 256\n\n Dim key() As Byte\n Dim IV() As Byte\n\n key = System.Text.Encoding.ASCII.GetBytes(prm_key)\n IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)\n\n Dim decryptor As ICryptoTransform = myRijndael.CreateDecryptor(key, IV)\n\n Dim sEncrypted As Byte() = Convert.FromBase64String(sEncryptedString)\n\n Dim fromEncrypt() As Byte = New Byte(sEncrypted.Length) {}\n\n Dim msDecrypt As New MemoryStream(sEncrypted)\n Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)\n\n csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)\n\n Return (System.Text.Encoding.ASCII.GetString(fromEncrypt))\n\n End Function\n\n\n Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String)\n\n Dim sToEncrypt As String = prm_text_to_encrypt\n\n Dim myRijndael As New RijndaelManaged\n myRijndael.Padding = PaddingMode.Zeros\n myRijndael.Mode = CipherMode.CBC\n myRijndael.KeySize = 256\n myRijndael.BlockSize = 256\n\n Dim encrypted() As Byte\n Dim toEncrypt() As Byte\n Dim key() As Byte\n Dim IV() As Byte\n\n key = System.Text.Encoding.ASCII.GetBytes(prm_key)\n IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)\n\n Dim encryptor As ICryptoTransform = myRijndael.CreateEncryptor(key, IV)\n\n Dim msEncrypt As New MemoryStream()\n Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)\n\n toEncrypt = System.Text.Encoding.ASCII.GetBytes(sToEncrypt)\n\n csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)\n csEncrypt.FlushFinalBlock()\n\n encrypted = msEncrypt.ToArray()\n\n Return (Convert.ToBase64String(encrypted))\n\n End Function\n\nEnd Module\n using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\nclass Program {\n static void Main(string[] args) {\n\n //Shared 256 bit Key and IV here\n const string sKy = \"lkirwf897+22#bbtrm8814z5qq=498j5\"; //32 chr shared ascii string (32 * 8 = 256 bit)\n const string sIV = \"741952hheeyy66#cs!9hjv887mxx7@8y\"; //32 chr shared ascii string (32 * 8 = 256 bit)\n\n var sTextVal = \"Here is my data to encrypt!!!\";\n\n var eText = EncryptRJ256(sKy, sIV, sTextVal);\n var dText = DecryptRJ256(sKy, sIV, eText);\n\n Console.WriteLine(\"key: \" + sKy);\n Console.WriteLine();\n Console.WriteLine(\" iv: \" + sIV);\n Console.WriteLine(\"txt: \" + sTextVal);\n Console.WriteLine(\"encrypted: \" + eText);\n Console.WriteLine(\"decrypted: \" + dText);\n Console.WriteLine(\"press any key to exit\");\n Console.ReadKey(true);\n }\n\n public static string DecryptRJ256(string prm_key, string prm_iv, string prm_text_to_decrypt) {\n\n var sEncryptedString = prm_text_to_decrypt;\n\n var myRijndael = new RijndaelManaged() {\n Padding = PaddingMode.Zeros,\n Mode = CipherMode.CBC,\n KeySize = 256,\n BlockSize = 256\n };\n\n var key = Encoding.ASCII.GetBytes(prm_key);\n var IV = Encoding.ASCII.GetBytes(prm_iv);\n\n var decryptor = myRijndael.CreateDecryptor(key, IV);\n\n var sEncrypted = Convert.FromBase64String(sEncryptedString);\n\n var fromEncrypt = new byte[sEncrypted.Length];\n\n var msDecrypt = new MemoryStream(sEncrypted);\n var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);\n\n csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);\n\n return (Encoding.ASCII.GetString(fromEncrypt));\n }\n\n public static string EncryptRJ256(string prm_key, string prm_iv, string prm_text_to_encrypt) {\n\n var sToEncrypt = prm_text_to_encrypt;\n\n var myRijndael = new RijndaelManaged() {\n Padding = PaddingMode.Zeros,\n Mode = CipherMode.CBC,\n KeySize = 256,\n BlockSize = 256\n };\n\n var key = Encoding.ASCII.GetBytes(prm_key);\n var IV = Encoding.ASCII.GetBytes(prm_iv);\n\n var encryptor = myRijndael.CreateEncryptor(key, IV);\n\n var msEncrypt = new MemoryStream();\n var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);\n\n var toEncrypt = Encoding.ASCII.GetBytes(sToEncrypt);\n\n csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);\n csEncrypt.FlushFinalBlock();\n\n var encrypted = msEncrypt.ToArray();\n\n return (Convert.ToBase64String(encrypted));\n }\n\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291/" ]
224,462
<p>I'm using a decimal column to store money values on a database, and today I was wondering what precision and scale to use.</p> <p>Since supposedly char columns of a fixed width are more efficient, I was thinking the same could be true for decimal columns. Is it?</p> <p>And what precision and scale should I use? I was thinking precision 24/8. Is that overkill, not enough or ok?</p> <hr> <p>This is what I've decided to do:</p> <ul> <li>Store the conversion rates (when applicable) in the transaction table itself, as a float</li> <li>Store the currency in the account table</li> <li>The transaction amount will be a <code>DECIMAL(19,4)</code></li> <li>All calculations using a conversion rate will be handled by my application so I keep control of rounding issues</li> </ul> <p>I don't think a float for the conversion rate is an issue, since it's mostly for reference, and I'll be casting it to a decimal anyway.</p> <p>Thank you all for your valuable input.</p>
[ { "answer_id": 224866, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 9, "selected": true, "text": "DECIMAL(19, 4) Decimal Currency DECIMAL(19, 4) Currency DECIMAL(p, s) DECIMAL DECIMAL(24, 8) DECIMAL(p, 6) MONEY" }, { "answer_id": 224936, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "DECIMAL" }, { "answer_id": 225592, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 7, "selected": false, "text": "round floor ceil class Currency {\n String code; // eg \"USD\"\n int value; // eg 2500\n boolean converted;\n}\n\nclass Price {\n Currency grossValue;\n Currency netValue;\n Tax taxRate;\n}\n USD:2500\n" }, { "answer_id": 23855833, "author": "pollux1er", "author_id": 1383351, "author_profile": "https://Stackoverflow.com/users/1383351", "pm_score": 3, "selected": false, "text": "DECIMAL(13, 2)\n DECIMAL(13, 4)\n" }, { "answer_id": 32182871, "author": "Mike Upjohn", "author_id": 3570183, "author_profile": "https://Stackoverflow.com/users/3570183", "pm_score": 0, "selected": false, "text": "DECIMAL(13,2)\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957/" ]
224,466
<p>Today someone asked me what was wrong with their source code. It was obvious. "Use double equals in place of that single equal in that if statement. Um, I think..." As I remember some languages actually take a single equals for comparison. Since I sometimes forget or mix up the syntax details among the several languages I use, I stepped over to my laptop to try a quickie experiment.</p> <p>It costs a bit of time and is a break in the flow to try "quick" experiments (though maybe the practice is good for memory.) What tips do you have for keeping straight in your mind the syntax (and other) details of multiple languages? </p> <p>(And nowadays, this applies just as well to the many wiki-like markups!)</p>
[ { "answer_id": 224650, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "if (a = b) var v" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10468/" ]
224,467
<p>I'm using Microsoft WebTest and want to be able to do something similar to NUnit's <code>Assert.Fail()</code>. The best i have come up with is to <code>throw new webTestException()</code> but this shows in the test results as an <code>Error</code> rather than a <code>Failure</code>. </p> <p>Other than reflecting on the <code>WebTest</code> to set a private member variable to indicate the failure, is there something I've missed?</p> <p>EDIT: I have also used the <code>Assert.Fail()</code> method, but this still shows up as an error rather than a failure when used from within WebTest, and the <code>Outcome</code> property is read-only (has no public setter).</p> <p>EDIT: well now I'm really stumped. I used reflection to set the <code>Outcome</code> property to Failed but the test <em>still</em> passes!</p> <p>Here's the code that sets the Oucome to failed:</p> <pre><code>public static class WebTestExtensions { public static void Fail(this WebTest test) { var method = test.GetType().GetMethod("set_Outcome", BindingFlags.NonPublic | BindingFlags.Instance); method.Invoke(test, new object[] {Outcome.Fail}); } } </code></pre> <p>and here's the code that I'm trying to fail:</p> <pre><code> public override IEnumerator&lt;WebTestRequest&gt; GetRequestEnumerator() { this.Fail(); yield return new WebTestRequest("http://google.com"); } </code></pre> <p><code>Outcome</code> is getting set to <code>Oucome.Fail</code> but apparently the WebTest framework doesn't really use this to determine test pass/fail results.</p>
[ { "answer_id": 224472, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "Outcome = Outcome.Fail;\n Assert.Fail()" }, { "answer_id": 2782006, "author": "nathandelane", "author_id": 334511, "author_profile": "https://Stackoverflow.com/users/334511", "pm_score": 1, "selected": false, "text": "public class FailValidationRule : ValidationRule\n{\n public override void Validate(object sender, ValidationEventArgs e)\n {\n e.IsValid = false;\n }\n}\n public class CodedWebTest : WebTest\n{\n public override IEnumerator<WebTestRequest> GetRequestEnumerator()\n {\n WebTestRequest request1 = new WebTestRequest(\"http://www.google.com\");\n FailValidationRule failValidation = new FailValidationRule();\n request1.ValidateResponse += new EventHandler<ValidationEventArgs>(failValidation.Validate);\n yield return request1;\n }\n}\n" }, { "answer_id": 17027680, "author": "yvandd", "author_id": 2471562, "author_profile": "https://Stackoverflow.com/users/2471562", "pm_score": 1, "selected": false, "text": "Public Overrides Sub PostRequest(ByVal sender As Object, ByVal e As PostRequestEventArgs)\n\n If YourTest = True Then\n\n Throw New WebTestException(\"My test Failed\")\n\n End If\n\n MyBase.PostRequest(sender, e)\n\n End Sub\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18590/" ]
224,471
<p>Uhm I'm not sure if anyone has encountered this problem <br> a brief description is on IE6 any <code>&lt;select&gt;</code> objects get displayed over any other item, even div's... meaning if you have a fancy javascript effect that displays a div that's supposed to be on top of everything (e.g: lightbox, multibox etc..) onclick of a certain element and that div overlaps a <code>&lt;select&gt;</code> your div get's to be displayed as if it's under the <code>&lt;select&gt;</code> [on this case a max and minimum z-index doesn't work ]</p> <p>I've tried googling and found the iframe shim solution <br> but I wanted some pretty clean alternatives or better yet has anyone found a better solution? since the method using iframes uses around 130mb of ram might slow down poor people's machines</p>
[ { "answer_id": 224793, "author": "pawel", "author_id": 4879, "author_profile": "https://Stackoverflow.com/users/4879", "pm_score": 4, "selected": true, "text": "select * html .hideSelects select { visibility: hidden; }\n //hide:\ndocument.body.className +=' hideSelects'\n\n//show:\ndocument.body.className = document.body.className.replace(' hideSelects', '');\n addClass removeClass" }, { "answer_id": 310229, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 2, "selected": false, "text": "* html .shimmed {\n _azimuth: expression(\n this.shimmed = this.shimmed || 'shimmed:'+this.insertAdjacentHTML('beforeBegin','<iframe style=\"filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);position:absolute;top:0px;left:0px;width:100%;height:100%\" frameBorder=0 scrolling=no src=\"javascript:false;document.write('+\"''\"+');\"></iframe>'),\n 'inherit');\n}\n" }, { "answer_id": 5236046, "author": "Andrew Chaa", "author_id": 437961, "author_profile": "https://Stackoverflow.com/users/437961", "pm_score": 0, "selected": false, "text": "$(':date').dateinput({\n format: 'dd/mm/yyyy',\n onBeforeShow: function(event) {\n $('select').hide();\n },\n onHide: function(event) {\n $('select').show();\n }\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24744/" ]
224,473
<p>I am new to creating Java web applications and came across this problem when trying to interact with my database (called ccdb) through my application:</p> <p><code>java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ccdb/</code></p> <p>My application runs on JBoss and uses Hibernate to interact with the MySQL database. I have the MySQL Driver in lib\mysql-connector-java-5.1.6-bin.jar of my project and I have the .jar configured in Eclipse as a "Java EE Module Dependency" so that it gets copied over to web-inf\lib\ when I deploy it to JBoss through Eclipse. I double checked and the driver is definitely in the .war file with the project, so it should be findable, right? </p> <p>My hibernate.cfg.xml contains this line which should point hibernate to the driver.</p> <p><code>&lt;property name="hibernate.connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;</code></p> <p>Does anyone know what I need to do to get this to work? Do I have to configure the MySQL database as a JBoss datasource for it to work?</p> <p>Thanks in advance.</p> <p>Edit: kauppi's solution works, but I would prefer to have it in lib\ with the other jars, and I'm really curious as to why it won't work that way. Any ideas...?</p>
[ { "answer_id": 224793, "author": "pawel", "author_id": 4879, "author_profile": "https://Stackoverflow.com/users/4879", "pm_score": 4, "selected": true, "text": "select * html .hideSelects select { visibility: hidden; }\n //hide:\ndocument.body.className +=' hideSelects'\n\n//show:\ndocument.body.className = document.body.className.replace(' hideSelects', '');\n addClass removeClass" }, { "answer_id": 310229, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 2, "selected": false, "text": "* html .shimmed {\n _azimuth: expression(\n this.shimmed = this.shimmed || 'shimmed:'+this.insertAdjacentHTML('beforeBegin','<iframe style=\"filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);position:absolute;top:0px;left:0px;width:100%;height:100%\" frameBorder=0 scrolling=no src=\"javascript:false;document.write('+\"''\"+');\"></iframe>'),\n 'inherit');\n}\n" }, { "answer_id": 5236046, "author": "Andrew Chaa", "author_id": 437961, "author_profile": "https://Stackoverflow.com/users/437961", "pm_score": 0, "selected": false, "text": "$(':date').dateinput({\n format: 'dd/mm/yyyy',\n onBeforeShow: function(event) {\n $('select').hide();\n },\n onHide: function(event) {\n $('select').show();\n }\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20177/" ]
224,475
<p>I wonder if is possible to use FTS with LINQ using .NET Framework 3.5. I'm searching around the documentation that I didn't find anything useful yet.</p> <p>Does anyone have any experience on this?</p>
[ { "answer_id": 224483, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 3, "selected": false, "text": "LIKE" }, { "answer_id": 385808, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 7, "selected": true, "text": "create function udf_sessionSearch\n (@keywords nvarchar(4000))\nreturns table\nas\n return (select [SessionId],[rank]\n from containstable(Session,(description,title),@keywords))\n var sessList = from s in DB.Sessions\n join fts in DB.udf_sessionSearch(SearchText) \n on s.sessionId equals fts.SessionId\n select s;\n" }, { "answer_id": 4222797, "author": "Victor Gelmutdinov", "author_id": 129812, "author_profile": "https://Stackoverflow.com/users/129812", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION ad_Search\n(\n @keyword nvarchar(4000)\n)\nRETURNS TABLE\nAS\nRETURN\n(\n select * from Ad where \n (CONTAINS(Description, @keyword) OR CONTAINS(Title, @keyword))\n)\n string searchKeyword = \"word and subword\";\nvar result = from ad in context.ad_Search(searchKeyword)\n select ad;\n SELECT [t0].ID, [t0].Title, [t0].Description\nFROM [dbo].[ad_Search](@p0) AS [t0]\n" }, { "answer_id": 17969124, "author": "AqD", "author_id": 2183221, "author_profile": "https://Stackoverflow.com/users/2183221", "pm_score": 0, "selected": false, "text": "var query = context.CreateObjectSet<MyFile>()\n .Where(file => file.FileName.Contains(\"pdf\")\n && FullTextFunctions.ContainsBinary(file.FileTable_Ref.file_stream, \"Hello\"));\n <Function Name=\"conTAINs\" BuiltIn=\"true\" IsComposable=\"true\" ParameterTypeSemantics=\"AllowImplicitConversion\" ReturnType=\"bit\" Schema=\"dbo\">\n <Parameter Name=\"dataColumn\" Type=\"varbinary\" Mode=\"In\" />\n <Parameter Name=\"keywords\" Type=\"nvarchar\" Mode=\"In\" />\n</Function>\n<Function Name=\"conTAInS\" BuiltIn=\"true\" IsComposable=\"true\" ParameterTypeSemantics=\"AllowImplicitConversion\" ReturnType=\"bit\" Schema=\"dbo\">\n <Parameter Name=\"textColumn\" Type=\"nvarchar\" Mode=\"In\" />\n <Parameter Name=\"keywords\" Type=\"nvarchar\" Mode=\"In\" />\n</Function>\n using System.Data.Objects.DataClasses;\n\npublic static class FullTextFunctions\n{\n [EdmFunction(\"MyModel.Store\", \"conTAINs\")]\n public static bool ContainsBinary(byte[] dataColumn, string keywords)\n {\n throw new System.NotSupportedException(\"Direct calls are not supported.\");\n }\n\n [EdmFunction(\"MyModel.Store\", \"conTAInS\")]\n public static bool ContainsString(string textColumn, string keywords)\n {\n throw new System.NotSupportedException(\"Direct calls are not supported.\");\n }\n}\n using EFProviderWrapperToolkit;\nusing EFTracingProvider;\n\npublic class TracedMyDataContext : MyDataContext\n{\n public TracedMyDataContext()\n : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(\n \"name=MyDataContext\", \"EFTracingProvider\"))\n {\n var tracingConnection = (EFTracingConnection) ((EntityConnection) Connection).StoreConnection;\n tracingConnection.CommandExecuting += TracedMyDataContext_CommandExecuting;\n }\n\n protected static void TracedMyDataContext_CommandExecuting(object sender, CommandExecutionEventArgs e)\n {\n e.Command.CommandText = FixFullTextContainsBinary(e.Command.CommandText);\n e.Command.CommandText = FixFullTextContainsString(e.Command.CommandText);\n }\n\n\n private static string FixFullTextContainsBinary(string commandText, int startIndex = 0)\n {\n var patternBeg = \"(conTAINs(\";\n var patternEnd = \")) = 1\";\n var exprBeg = commandText.IndexOf(patternBeg, startIndex, StringComparison.Ordinal);\n if (exprBeg == -1)\n return commandText;\n var exprEnd = FindEnd(commandText, exprBeg + patternBeg.Length, ')');\n if (commandText.Substring(exprEnd).StartsWith(patternEnd))\n {\n var newCommandText = commandText.Substring(0, exprEnd + 2) + commandText.Substring(exprEnd + patternEnd.Length);\n return FixFullTextContainsBinary(newCommandText, exprEnd + 2);\n }\n return commandText;\n }\n\n private static string FixFullTextContainsString(string commandText, int startIndex = 0)\n {\n var patternBeg = \"(conTAInS(\";\n var patternEnd = \")) = 1\";\n var exprBeg = commandText.IndexOf(patternBeg, startIndex, StringComparison.Ordinal);\n if (exprBeg == -1)\n return commandText;\n var exprEnd = FindEnd(commandText, exprBeg + patternBeg.Length, ')');\n if (exprEnd != -1 && commandText.Substring(exprEnd).StartsWith(patternEnd))\n {\n var newCommandText = commandText.Substring(0, exprEnd + 2) + commandText.Substring(exprEnd + patternEnd.Length);\n return FixFullTextContainsString(newCommandText, exprEnd + 2);\n }\n return commandText;\n }\n\n private static int FindEnd(string commandText, int startIndex, char endChar)\n {\n // TODO: handle escape chars between parens/squares/quotes\n var lvlParan = 0;\n var lvlSquare = 0;\n var lvlQuoteS = 0;\n var lvlQuoteD = 0;\n for (var i = startIndex; i < commandText.Length; i++)\n {\n var c = commandText[i];\n if (c == endChar && lvlParan == 0 && lvlSquare == 0\n && (lvlQuoteS % 2) == 0 && (lvlQuoteD % 2) == 0)\n return i;\n switch (c)\n {\n case '(':\n ++lvlParan;\n break;\n case ')':\n --lvlParan;\n break;\n case '[':\n ++lvlSquare;\n break;\n case ']':\n --lvlSquare;\n break;\n case '\\'':\n ++lvlQuoteS;\n break;\n case '\"':\n ++lvlQuoteD;\n break;\n }\n }\n return -1;\n }\n}\n <system.data>\n <DbProviderFactories>\n <add name=\"EFTracingProvider\" invariant=\"EFTracingProvider\" description=\"Tracing Provider Wrapper\" type=\"EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b\" />\n <add name=\"EFProviderWrapper\" invariant=\"EFProviderWrapper\" description=\"Generic Provider Wrapper\" type=\"EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b\" />\n </DbProviderFactories>\n</system.data>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18623/" ]
224,485
<p>I am using a Cursor in my stored procedure. It works on a database that has a huge number of data. for every item in the cursor i do a update operation. This is taking a huge amount of time to complete. Almost 25min. :( .. Is there anyway i can reduce the time consumed for this?</p>
[ { "answer_id": 224738, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "UPDATE\n MyTable\nSET\n Col1 = CASE WHEN b.Foo = \"Bar\" THEN LOWER(b.Baz) ELSE \"\" END,\n Col2 = ISNULL(c.Bling, 0) * 100 / Col3\nFROM\n MyTable \n INNER JOIN MySecondTable AS b ON b.Id = MyTable.SecondId\n LEFT JOIN ##MyTempTable AS c ON c.Id = b.ThirdId\nWHERE\n MyTabe.Col3 > 0\n AND b.Foo NOT IS NULL\n AND MyTable.TheDate > GETDATE() - 10\n" }, { "answer_id": 224763, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "UPDATE t1\nSET t1.col1 = (SELECT top 1 col FROM other_table WHERE t1_id = t1.ID AND ...)\nWHERE ...\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
224,499
<p>There are some good examples on how to calculate word frequencies in C#, but none of them are comprehensive and I really need one in VB.NET.</p> <p>My current approach is limited to one word per frequency count. What is the best way to change this so that I can get a completely accurate word frequency listing?</p> <pre><code>wordFreq = New Hashtable() Dim words As String() = Regex.Split(inputText, "(\W)") For i As Integer = 0 To words.Length - 1 If words(i) &lt;&gt; "" Then Dim realWord As Boolean = True For j As Integer = 0 To words(i).Length - 1 If Char.IsLetter(words(i).Chars(j)) = False Then realWord = False End If Next j If realWord = True Then If wordFreq.Contains(words(i).ToLower()) Then wordFreq(words(i).ToLower()) += 1 Else wordFreq.Add(words(i).ToLower, 1) End If End If End If Next Me.wordCount = New SortedList For Each de As DictionaryEntry In wordFreq If wordCount.ContainsKey(de.Value) = False Then wordCount.Add(de.Value, de.Key) End If Next </code></pre> <p>I'd prefer an actual code snippet, but generic 'oh yeah...use this and run that' would work as well.</p>
[ { "answer_id": 224514, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 2, "selected": false, "text": " Dim Words = \"Hello World ))))) This is a test Hello World\"\n Dim CountTheWords = From str In Words.Split(\" \") _\n Where Char.IsLetter(str) _\n Group By str Into Count()\n" }, { "answer_id": 224543, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "Public Class CountWords\n\n Public Function WordCount(ByVal str As String) As Dictionary(Of String, Integer)\n Dim ret As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)\n\n Dim word As String = \"\"\n Dim add As Boolean = True\n Dim ch As Char\n\n str = str.ToLower\n For index As Integer = 1 To str.Length - 1 Step index + 1\n ch = str(index)\n If Char.IsLetter(ch) Then\n add = True\n word += ch\n ElseIf add And word.Length Then\n If Not ret.ContainsKey(word) Then\n ret(word) = 1\n Else\n ret(word) += 1\n End If\n word = \"\"\n End If\n Next\n\n Return ret\n End Function\n\nEnd Class\n Imports System.Windows.Forms.ListViewItem\n\nPublic Class MainForm\n\n Private WordCounts As CountWords = New CountWords\n\n Private Sub CountBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CountBtn.Click\n OutputList.Items.Clear()\n Dim ret As Dictionary(Of String, Integer) = Me.WordCounts.WordCount(InputBox.Text)\n For Each item As String In ret.Keys\n Dim litem As ListViewItem = New ListViewItem\n litem.Text = item\n Dim csitem As ListViewSubItem = New ListViewSubItem(litem, ret.Item(item).ToString())\n\n litem.SubItems.Add(csitem)\n OutputList.Items.Add(litem)\n\n Word.Width = -1\n Freq.Width = -1\n Next\n End Sub\nEnd Class\n" }, { "answer_id": 224555, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 1, "selected": false, "text": "Public Function CountWords(ByVal inputText as String) As Dictionary(Of String, Integer)\n Dim frequency As New Dictionary(Of String, Integer)\n\n For Each wordMatch as Match in Regex.Match(inputText, \"\\w+\")\n If frequency.ContainsKey(wordMatch.Value.ToLower()) Then\n frequency(wordMatch.Value.ToLower()) += 1\n Else\n frequency.Add(wordMatch.Value.ToLower(), 1)\n End If\n Next\n Return frequency\nEnd Function\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965/" ]
224,503
<p>Short of putting a UIWebView as the back-most layer in my nib file, how can I add a repeating background image to an iPhone app (like the corduroy look in the background of a grouped UITableView)?</p> <p>Do I need to create an image that's the size of the iPhone's screen and manually repeat it using copy and paste?</p>
[ { "answer_id": 224513, "author": "Frank Schmitt", "author_id": 27951, "author_profile": "https://Stackoverflow.com/users/27951", "pm_score": 8, "selected": true, "text": "- (void)viewDidLoad {\n [super viewDidLoad];\n self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@\"gingham.png\"]]; \n}\n - (void)viewDidLoad {\n [super viewDidLoad];\n self.view.backgroundColor = [UIColor groupTableViewBackgroundColor]; \n}\n" }, { "answer_id": 224972, "author": "Dan", "author_id": 9774, "author_profile": "https://Stackoverflow.com/users/9774", "pm_score": 2, "selected": false, "text": "CGContextDrawTiledImage\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27951/" ]
224,504
<p>Ok, so I have a Rails app set up on DreamHost and I had it working a while ago and now it's broken. I don't know a lot about deployment environments or anything like that so please forgive my ignorance. Anyway, it looks like the app is crashing at this line in config/environment.rb:</p> <pre><code>require File.join(File.dirname(__FILE__), 'boot') </code></pre> <p>config/boot.rb is pretty much normal, but I'll include it here anyway.</p> <pre><code># Don't change this file! # Configure your app in config/environment.rb and config/environments/*.rb RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class &lt;&lt; self def boot! unless booted? preinitialize pick_boot.run end end def booted? defined? Rails::Initializer end def pick_boot (vendor_rails? ? VendorBoot : GemBoot).new end def vendor_rails? File.exist?("#{RAILS_ROOT}/vendor/rails") end def preinitialize load(preinitializer_path) if File.exist?(preinitializer_path) end def preinitializer_path "#{RAILS_ROOT}/config/preinitializer.rb" end end class Boot def run load_initializer Rails::Initializer.run(:set_load_path) end end class VendorBoot &lt; Boot def load_initializer require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" Rails::Initializer.run(:install_gem_spec_stubs) end end class GemBoot &lt; Boot def load_initializer self.class.load_rubygems load_rails_gem require 'initializer' end def load_rails_gem if version = self.class.gem_version gem 'rails', version else gem 'rails' end rescue Gem::LoadError =&gt; load_error $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.) exit 1 end class &lt;&lt; self def rubygems_version Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion end def gem_version if defined? RAILS_GEM_VERSION RAILS_GEM_VERSION elsif ENV.include?('RAILS_GEM_VERSION') ENV['RAILS_GEM_VERSION'] else parse_gem_version(read_environment_rb) end end def load_rubygems require 'rubygems' min_version = '1.1.1' unless rubygems_version &gt;= min_version $stderr.puts %Q(Rails requires RubyGems &gt;= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) exit 1 end rescue LoadError $stderr.puts %Q(Rails requires RubyGems &gt;= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org) exit 1 end def parse_gem_version(text) $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~&lt;&gt;=]*\s*[\d.]+)["']/ end private def read_environment_rb File.read("#{RAILS_ROOT}/config/environment.rb") end end end end # All that for this: Rails.boot! </code></pre> <p>Does anyone have any ideas? I am not getting any errors in the log or on the page.</p> <p>-fREW</p>
[ { "answer_id": 885592, "author": "alex", "author_id": 71953, "author_profile": "https://Stackoverflow.com/users/71953", "pm_score": 2, "selected": false, "text": "rake rails:freeze:gems\nrake gems:unpack:dependencies\n" }, { "answer_id": 2433057, "author": "Taryn East", "author_id": 219883, "author_profile": "https://Stackoverflow.com/users/219883", "pm_score": 0, "selected": false, "text": "boot.rb boot.rb config/environment.rb RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION\n gem list gem install rails -v=2.3.4 rake gems script/console script/console" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
224,512
<p>I am working on creating a daemon in Ruby using the daemons gem. I want to add output from the daemon into a log file. I am wondering what is the easiest way to redirect <code>puts</code> from the console to a log file.</p>
[ { "answer_id": 224523, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 4, "selected": false, "text": "$stdout = File.new( '/tmp/output', 'w' )\n $stdout = STDOUT\n" }, { "answer_id": 224659, "author": "Vitalie", "author_id": 27913, "author_profile": "https://Stackoverflow.com/users/27913", "pm_score": 5, "selected": true, "text": " logger = Logger.new(STDOUT)\n logger = Logger.new(\"/var/log/my-daemon.log\")\n #!/bin/sh\nset -e\n\nLOG=/var/log/my-daemon\n\ntest -d \"$LOG\" || mkdir -p -m2750 \"$LOG\" && chown nobody:adm \"$LOG\"\nexec chpst -unobody svlogd -tt \"$LOG\"\n" }, { "answer_id": 2480439, "author": "Eric Walker", "author_id": 61048, "author_profile": "https://Stackoverflow.com/users/61048", "pm_score": 5, "selected": false, "text": "$stdout.reopen(\"my.log\", \"w\")\n$stdout.sync = true\n$stderr.reopen($stdout)\n $stdout = STDOUT\n" }, { "answer_id": 22617214, "author": "Peterdk", "author_id": 107029, "author_profile": "https://Stackoverflow.com/users/107029", "pm_score": 0, "selected": false, "text": "puts def puts(message)\n #write message to file\nend\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
224,541
<p>On my website, I have several html files I do not link off the main portal page. Without other people linking to them, is it possible for Jimmy Evil Hacker to find them?</p>
[ { "answer_id": 225069, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": ".htaccess Options -Indexes\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26227/" ]
224,553
<p>I want to know how events are used in embedded system code.</p> <p>Main intention is to know how exactly event flags are set/reset in code. and how to identify which task is using which event flag and which bits of the flag are getting set/reset by each task.</p> <p>Please put your suggestion or comments about it.</p> <p>Thanks in advance.</p> <hr> <p>(edit 1: copied from clarification in answer below)</p> <p>Sorry for not specifying the details required. Actually I am interested in the analysis of any application written in C language using vxworks/Itron/OSEK OS. For example there is eventLib library in vxworks to support event handling. I want to know that how one can make use of such system routines to handle events in task. What is event flag(is it global/local...or what ?), how to set bits of any event flag and which can be the possible relationship between task and event flags ??</p> <p>How task can wait for multiple events in AND and OR mode ?? I came across one example in which the scenario given below looks dangerous, but why ??</p> <pre><code> Scenarios is ==&gt; *[Task1 : Set(e1), Task2 : Wait(e1) and Set(e2), Task3 : Wait(e2) ]* </code></pre> <p>I know that multiple event flags waited by one task or circular dependency between multiple tasks(deadlock) are dangerous cases in task-event relationship, but how above scenario is dangerous, I am not getting it....Kindly explain.</p> <pre><code> (Are there any more such scenarios possible in task-event handling which should be reviewed in code ?? ) </code></pre> <p>I hope above information is sufficient ....</p>
[ { "answer_id": 226698, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 2, "selected": false, "text": " #define EVENT1 0x00000001\n #define EVENT2 0x00000002\n #define EVENT3 0x00000004\n ...\n #define EVENT_EXIT 0x80000000\n\n /* Spawn the event handler task (event receiver) */\n rcvTaskId = taskSpawn(\"tRcv\",priority,0,stackSize,handleEvents,0,0,0,0,0,0,0,0,0,0);\n ...\n\n /* Receive thread: Loop to receive events */\n STATUS handleEvents(void)\n {\n UINT32 rcvEventMask = 0xFFFFFFFF;\n\n while(1)\n {\n UINT32 events = 0;\n\n if (eventReceive(rcvEventMask. EVENTS_WAIT_ANY, WAIT_FOREVER, &events) == OK)\n {\n /* Process events */\n if (events & EVENT1)\n handleEvent1();\n if (events & EVENT2)\n handleEvent2();\n ...\n if (events & EVENT_EXIT)\n break;\n }\n }\n\n return OK;\n }\n int RcvTaskID = ERROR;\n...\neventSend(RcvTaskID, eventMask);\n static int RcvTaskID = ERROR;\n\nvoid DRIVER_setRcvTaskID(int rcvTaskID)\n{\n RcvTaskID = rcvTaskID;\n}\n...\neventSend(RcvTaskID, eventMask);\n static int RcvTaskID;\nvoid RECV_sendEvents(UINT32 eventMask)\n{\n eventSend(RcvTaskID, eventMask);\n}\n" }, { "answer_id": 267711, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "unsigned char bit_flags = 0;\n #define TIMER_EXPIRED 0x01 // 0000 0001\n#define DATA_READY 0x02 // 0000 0010\n#define BUFFER_OVERFLOW 0x04 // 0000 0100\n // Bitwise OR: bit_flags | 00000001 sets the first bit.\nbit_flags |= TIMER_EXPIRED; // Set TIMER_EXPIRED bit.\n\n// Bitwise AND w/complement clears bits: flags & 11111101 clears the 2nd bit.\nbit_flags &= ~DATA_READY; // Clear DATA_READY bit.\n\n// Bitwise AND tests a bit. The result is BUFFER_OVERFLOW\n// if the bit is set, 0 if the bit is clear.\nhad_ovflow = bit_flags & BUFFER_OVERFLOW;\n // Set DATA_READY and BUFFER_OVERFLOW bits.\nbit_flags |= (DATA_READY | BUFFER_OVERFLOW);\n #define SET_BITS(bits, data) data |= (bits)\n#define CLEAR_BITS(bits, data) data &= ~(bits)\n#define CHECK_BITS(bits, data) (data & (bits))\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,562
<p>I am reading over the K&amp;R book, and am a little stuck.</p> <p>What is wrong with the following?</p> <pre><code>void getInput(int* output) { int c, i; for(i=0; (c = getchar()) != '\n'; i++) output[i] = c; // printf("%c", c) prints the c value as expected output[++i] = '\0'; } </code></pre> <p>When I run the program it never gets out of the loop and I have to <kbd>Ctrl+C</kbd> to exit. However if I replace the fifth line with <code>printf("%c", c);</code>, it prints out all the input just fine after hitting enter and creating the new line.</p>
[ { "answer_id": 224600, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": 4, "selected": true, "text": "1. void getInput(int* output) {\n void getInput(char* output) {\n 5. output[++i] = '\\0';\n output[i] = '\\0';\n int main(void)\n{\n char o[100];\n getInput(o);\n printf(\"%s\", o);\n return 0;\n}\n" }, { "answer_id": 224604, "author": "chris", "author_id": 26849, "author_profile": "https://Stackoverflow.com/users/26849", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\n#define STACK_SIZE 50\n#define MAX_INPUT_SIZE 1000\n#define FALSE 0\n#define TRUE 1\n\nvoid getInput();\nint validInput();\n\nint main() {\n char* userInput[MAX_INPUT_SIZE];\n\n getInput(&userInput);\n\n if (validInput(&userInput) == TRUE)\n printf(\"Compile complete\");\n else\n printf(\"Error\");\n}\n\n// Functions\nvoid getInput(char* output) {\n int c, i;\n for(i=0; (c = getchar()) != '\\n' && c != EOF && i <= MAX_INPUT_SIZE; i++)\n output[i] = c;\n output[i] = '\\0';\n}\n\nint validInput(char* input) {\n char stack[STACK_SIZE];\n int c;\n int j;\n\n for (j=0; (c = input[j]) != '\\0'; ) {\n switch(c){\n case '[': case '(': case '{':\n stack[j++] = c;\n break;\n case ']': case ')': case '}':\n if (c == ']' && stack[j] != '[')\n return FALSE;\n else if (c == '}' && stack[j] != '{')\n return FALSE;\n else if (c == ')' && stack[j] != '(')\n return FALSE;\n\n // decrement the stack's index \n --j;\n break;\n }\n }\n\n return TRUE;\n}\n" }, { "answer_id": 224724, "author": "Raz", "author_id": 5661, "author_profile": "https://Stackoverflow.com/users/5661", "pm_score": 1, "selected": false, "text": "char* userInput[MAX_INPUT_SIZE];\n char userInput[MAX_INPUT_SIZE+1];\n getInput(&userInput);\n getInput( userInput );\n" }, { "answer_id": 228506, "author": "chris", "author_id": 26849, "author_profile": "https://Stackoverflow.com/users/26849", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\n#define STACK_SIZE 50\n#define MAX_INPUT_SIZE 1000\n#define FALSE 0\n#define TRUE !FALSE\n\nvoid get_input();\nint valid_input();\n\nint main() {\n char user_input[MAX_INPUT_SIZE + 1]; // +1 for the \\0\n\n get_input(user_input);\n\n if (valid_input(user_input))\n printf(\"Success\\n\");\n else\n printf(\"Error\\n\");\n}\n\n// Functions\nvoid get_input(char* output) {\n int c, i;\n for(i=0; (c = getchar()) != '\\n' && c != EOF && i <= MAX_INPUT_SIZE; i++)\n output[i] = c;\n output[i] = '\\0';\n}\n\nint valid_input(char* input) {\n char stack[STACK_SIZE];\n char c;\n int i = 0;\n int stack_index = -1;\n\n while ((c = input[i]) != '\\0' && i < STACK_SIZE) {\n switch(c){\n case '[': case '(': case '{':\n stack_index++; \n stack[stack_index] = c;\n break;\n case ']': case ')': case '}':\n if ((c == ']' && stack[stack_index] != '[') ||\n (c == '}' && stack[stack_index] != '{') ||\n (c == ')' && stack[stack_index] != '('))\n return FALSE;\n\n // decrement the stack's index now that the closing bracket is found \n stack_index--;\n break;\n }\n i++;\n }\n\n // stack index should be back where it started\n return (stack_index == -1);\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26849/" ]
224,569
<p>What is difference between <code>Server.Transfer</code> and <code>Response.Redirect</code>?</p> <ul> <li>What are advantages and disadvantages of each?</li> <li>When is one appropriate over the other?</li> <li>When is one not appropriate?</li> </ul>
[ { "answer_id": 224577, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 9, "selected": true, "text": "Response.Redirect Server.Transfer" }, { "answer_id": 224586, "author": "Christian Payne", "author_id": 5188, "author_profile": "https://Stackoverflow.com/users/5188", "pm_score": 7, "selected": false, "text": "Response.Redirect() Server.Transfer() Server.Transfer() Response.Redirect()" }, { "answer_id": 521604, "author": "TStamper", "author_id": 39809, "author_profile": "https://Stackoverflow.com/users/39809", "pm_score": 6, "selected": false, "text": "Response.Redirect Server.Transfer Server.Transfer Server.Transfer(\"WebForm2.aspx\") Server.Transfer Server.Transfer Response.Redirect Server.Transfer Server.Transfer True Server.Transfer(\"WebForm2.aspx\", True) Request.Form(\"TextBox1\")" }, { "answer_id": 8091370, "author": "SoftDev", "author_id": 804572, "author_profile": "https://Stackoverflow.com/users/804572", "pm_score": 5, "selected": false, "text": "Response.Redirect() Server.Transfer()" }, { "answer_id": 15071812, "author": "Israel Margulies", "author_id": 1346806, "author_profile": "https://Stackoverflow.com/users/1346806", "pm_score": 4, "selected": false, "text": "TextBox myTxt = (TextBox)this.Page.PreviousPage.FindControl(\"TextBoxID\");\n" }, { "answer_id": 18145331, "author": "Microsoft Developer", "author_id": 662320, "author_profile": "https://Stackoverflow.com/users/662320", "pm_score": 3, "selected": false, "text": "Response.Redirect() Server.Transfer() //This will work.\nResponse.Redirect(\"http://www.google.com\");\n\n//This will not work.\nServer.Transfer(\"http://www.google.com\");\n" }, { "answer_id": 18756214, "author": "rockXrock", "author_id": 1254006, "author_profile": "https://Stackoverflow.com/users/1254006", "pm_score": 2, "selected": false, "text": "public void Transfer (string path, bool preserveForm)\n{\n this.Execute (path, null, preserveForm, true);\n this.context.Response.End ();\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18709/" ]
224,576
<p>I'm considering altering some tables to use nvarchar(50) as primary key instead of an int primary key. Using an int ID for a key really is irrelevant data, it's the string I'm interested in. What sort of performance hit will occur, or where do you research this? Other than cut and try that is.</p>
[ { "answer_id": 225195, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": -1, "selected": false, "text": "NVARCHAR(50)" }, { "answer_id": 225407, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "Tbl_whatever\n id_whatever, unique identifier, primary key\n code_whatever, nvarchar(your favorite length), indexed\n .....\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28343/" ]
224,602
<p>Given this HTML:</p> <pre><code>&lt;div&gt;foo&lt;/div&gt;&lt;div&gt;bar&lt;/div&gt;&lt;div&gt;baz&lt;/div&gt; </code></pre> <p>How do you make them display inline like this:</p> <blockquote> <p>foo bar baz</p> </blockquote> <p>not like this:</p> <blockquote> <p>foo<br> bar<br> baz </p> </blockquote>
[ { "answer_id": 224612, "author": "Randy Sugianto 'Yuku'", "author_id": 11238, "author_profile": "https://Stackoverflow.com/users/11238", "pm_score": 8, "selected": false, "text": "div { border: 1px solid #CCC; } <div style=\"display: inline\">a</div>\n <div style=\"display: inline\">b</div>\n <div style=\"display: inline\">c</div>" }, { "answer_id": 224616, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\ndiv.inline { display:inline; }\n</style>\n<div class=\"inline\">a</div>\n<div class=\"inline\">b</div>\n<div class=\"inline\">c</div>\n" }, { "answer_id": 224626, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 9, "selected": true, "text": "div.inline { float:left; }\n.clearBoth { clear:both; } <div class=\"inline\">1<br />2<br />3</div>\n<div class=\"inline\">1<br />2<br />3</div>\n<div class=\"inline\">1<br />2<br />3</div>\n<br class=\"clearBoth\" /><!-- you may or may not need this -->" }, { "answer_id": 224903, "author": "Pirat", "author_id": 22326, "author_profile": "https://Stackoverflow.com/users/22326", "pm_score": 3, "selected": false, "text": "<span>" }, { "answer_id": 403149, "author": "bochgoch", "author_id": 50450, "author_profile": "https://Stackoverflow.com/users/50450", "pm_score": 8, "selected": false, "text": "<span>foo</span>\n<span>bar</span>\n<span>baz</span>\n" }, { "answer_id": 403321, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 5, "selected": false, "text": "br br divs div ===== ======= == **** ***** ****** +++++ ++++\n===== ==== ===== ******** ***** ** ++ +++++++\n=== ======== === ******* **** **** \n===== ==== ===== +++++++ ++\n====== == ======\n ====== ==== ===== ===== == ==== *** ******* ***** ***** \n**** ++++ +++ ++ ++++ ++ +++++++ +++ ++++\n br <div style=\"float: left;\" >\n <p>block level content or <span>inline content</span>.</p>\n <p>block level content or <span>inline content</span>.</p>\n</div>\n<div style=\"float: left;\" >\n <p>block level content or <span>inline content</span>.</p>\n <p>block level content or <span>inline content</span>.</p>\n</div>\n<div style=\"float: left;\" >\n <p>block level content or <span>inline content</span>.</p>\n <p>block level content or <span>inline content</span>.</p>\n</div>\n" }, { "answer_id": 4805310, "author": "word5150", "author_id": 590678, "author_profile": "https://Stackoverflow.com/users/590678", "pm_score": 2, "selected": false, "text": "div.contain\n{\n margin:3%;\n border: none;\n height: auto;\n width: auto;\n float: left;\n}\n\ndiv.contain div\n{\n display:inline;\n width:200px;\n height:300px;\n padding: 15px;\n margin: auto;\n border:1px solid red;\n background-color:#fffff7;\n -moz-border-radius:25px; /* Firefox */\n border-radius:25px;\n}\n <div class=\"contain\">\n <div>Foo</div>\n</div>\n\n<div class=\"contain\">\n <div>Bar</div>\n</div>\n\n<div class=\"contain\">\n <div>Baz</div>\n</div>\n" }, { "answer_id": 4976019, "author": "David Eison", "author_id": 72670, "author_profile": "https://Stackoverflow.com/users/72670", "pm_score": 2, "selected": false, "text": "/* below is a set of hacks to make inline-block work right on divs in IE. */\nhtml > body .ib { display:inline-block; }\n.ib {display:inline-block;position:relative;}\n* html .ib { display: inline; }\n:first-child + html .ib { display:inline; }\n" }, { "answer_id": 7484528, "author": "A. Bender", "author_id": 954660, "author_profile": "https://Stackoverflow.com/users/954660", "pm_score": 3, "selected": false, "text": "wrapperline{\nwidth: 300px;\nfloat: left;\nheight: 60px;\nbackground-color:#CCCCCC;}\n\n.boxinside{\nwidth: 50px;\nfloat: left;\nheight: 50px;\nmargin: 5px;\nbackground-color:#9C0;\nfloat:left;}\n <div class=\"wrapperline\">\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n<div class=\"boxinside\">Box 1</div>\n</div>\n" }, { "answer_id": 8766107, "author": "Paul Sweatte", "author_id": 1113772, "author_profile": "https://Stackoverflow.com/users/1113772", "pm_score": 5, "selected": false, "text": "display:inline-block <html>\n <head>\n <style>\n div { display:inline-block; }\n /* IE6-7 */\n @media,\n {\n div { display: inline; margin-right:10px; }\n }\n </style>\n </head>\n <div>foo</div>\n <div>bar</div>\n <div>baz</div>\n</html>\n" }, { "answer_id": 12575608, "author": "omnath", "author_id": 1839501, "author_profile": "https://Stackoverflow.com/users/1839501", "pm_score": 0, "selected": false, "text": ".left {\n float:left;\n margin:3px;\n}\n<div class=\"left\">foo</div>\n<div class=\"left\">bar</div>\n<div class=\"left\">baz</div>\n" }, { "answer_id": 25396475, "author": "Ipog", "author_id": 3958650, "author_profile": "https://Stackoverflow.com/users/3958650", "pm_score": 0, "selected": false, "text": "<div class=\"cdiv\">\n<div class=\"inline\"><p>para 1</p></div>\n <div class=\"inline\">\n <p>para 1</p>\n <span>para 2</span>\n <h1>para 3</h1>\n</div>\n <div class=\"inline\"><p>para 1</p></div>\n" }, { "answer_id": 27600870, "author": "flairon", "author_id": 2007147, "author_profile": "https://Stackoverflow.com/users/2007147", "pm_score": 3, "selected": false, "text": "<style type=\"text/css\">\n div{\n position: relative;\n display: inline-block;\n width:25px;\n height:25px;\n }\n</style>\n<div>toto</div>\n<div>toto</div>\n<div>toto</div>\n" }, { "answer_id": 28671130, "author": "Pankaj Bisht", "author_id": 3611958, "author_profile": "https://Stackoverflow.com/users/3611958", "pm_score": 2, "selected": false, "text": "<table>\n <tr>\n <td>foo</td>\n </tr>\n <tr>\n <td>bar</td>\n </tr>\n <tr>\n <td>baz</td>\n </tr>\n</table>\n <span>foo</span><span>bar</span><span>baz</span>\n" }, { "answer_id": 33629161, "author": "Hidayt Rahman", "author_id": 2927228, "author_profile": "https://Stackoverflow.com/users/2927228", "pm_score": 4, "selected": false, "text": "<span> <div> <div class=\"main-div\">\n <div>foo</div>\n <div>bar</div>\n <div>baz</div>`\n</div>\n display:inline-block; float:left; display:inline-block; div {\n display: inline-block;\n}\n div {\n float: left;\n}\n .main-div:after {\n content: \"\";\n clear: both;\n display: table;\n}\n" }, { "answer_id": 35261602, "author": "Waah Ronald", "author_id": 5896727, "author_profile": "https://Stackoverflow.com/users/5896727", "pm_score": 0, "selected": false, "text": "<div>foo</div><div>bar</div><div>baz</div>\n//solution 1\n<style>\n #div01, #div02, #div03 {\n float:left;\n width:2%;\n } \n </style>\n <div id=\"div01\">foo</div><div id=\"div02\">bar</div><div id=\"div03\">baz</div>\n\n //solution 2\n\n <style>\n #div01, #div02, #div03 {\n display:inline;\n padding-left:5px;\n } \n</style>\n<div id=\"div01\">foo</div><div id=\"div02\">bar</div><div id=\"div03\">baz</div>\n\n /* I think this would help but if you have any other thoughts just let me knw kk */\n" }, { "answer_id": 70798931, "author": "Josiah Mahachi", "author_id": 14094598, "author_profile": "https://Stackoverflow.com/users/14094598", "pm_score": 1, "selected": false, "text": " <div class=\"form-group form-inline-radio\">\n <div class=\"form-check form-radio-outline form-radio-primary mb-3\">\n <input type=\"radio\" name=\"formRadio4\" id=\"formRadio4\" checked=\"\" class=\"form-check-input\">\n <label for=\"formRadio4\" class=\"form-check-label\"> Radio Outline Warning </label>\n </div>\n <div class=\"form-check form-radio-outline form-radio-primary mb-3\">\n <input type=\"radio\" name=\"formRadio4\" id=\"formRadio4\" checked=\"\" class=\"form-check-input\">\n <label for=\"formRadio4\" class=\"form-check-label\"> Radio Outline Warning </label>\n </div>\n </div>\n .form-inline-radio {\n display: flex;\n overflow: hidden;\n}\n\n.form-check {\n margin-right: 10px;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
224,617
<p>i have a 3 column datafile and i wanted to use splot to plot the same. But what i want is that gnuplot plots first row (in some colour, say red) and then pauses for say 0.3 secs and then moves on to plotting next row (in other colour, not in red, say in green), pauses for 0.3 secs and then proceeds to next row....so on n so forth.</p> <p>Any help will be greately appreciated.</p> <p>thanks in advance</p> <p>Regards Pankaj</p>
[ { "answer_id": 224680, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 2, "selected": false, "text": "file=\"your input file.dat\"\nlines=$(wc -l $file)\ni=1\nwhile [ $i -le $lines ] ; do\n head -${i} ${file} > ${file%.dat}-${i}lines.dat\ndone\n for f in *lines.dat ; do\n gnuplot ... $f \ndone\n #!/bin/bash\nwhile read l ; do\n echo \"$l\"\n sleep 1\ndone\n (pause-input.sh | gnuplot ...) < somefile.dat\n" }, { "answer_id": 2343408, "author": "Pankaj", "author_id": 282223, "author_profile": "https://Stackoverflow.com/users/282223", "pm_score": 2, "selected": false, "text": "splot x1 y1 z1\npause 1\nreplot x2 y2 z2\npause 1\nreplot x3 y3 z3\npause 1\nreplot x4 y4 z4\n" }, { "answer_id": 2538780, "author": "Born2Smile", "author_id": 250287, "author_profile": "https://Stackoverflow.com/users/250287", "pm_score": 0, "selected": false, "text": "!sleep $Number_of_Seconds_to_Pause gnuplot myplotfile.plt set title 'x squared'\nplot x**2 title ''\n!sleep 5\nset title 'x cubed'\nplot x**3 title ''\n!sleep 5" }, { "answer_id": 14205246, "author": "Hugo Heden", "author_id": 1956362, "author_profile": "https://Stackoverflow.com/users/1956362", "pm_score": 2, "selected": false, "text": "for every # Find out the number of lines in the data somehow, \n# for example like this:\nnum_lines=\"`cat my_datafile.d | wc -l`\"\n\n# Plot the first line in the data-file:\nplot './my_datafile.d' every 1::0::0\n\n# For the remaining lines:\ndo for [line_index = 1:num_lines-1] { \n pause 0.3\n # Replot (from the same datafile) each line \n # in the data file from the first one up to \n # the current line_index \n replot '' every 1::0::line_index\n}\n every 1::0::line_index 1 0 line_index <point_incr> <start_point> <end_point> gnuplot> help every\n The `every` keyword allows a periodic sampling of a data set to be plotted.\n [...]\n\n Syntax:\n plot 'file' every {<point_incr>}\n {:{<block_incr>}\n {:{<start_point>}\n {:{<start_block>}\n {:{<end_point>}\n {:<end_block>}}}}}\n [...]\n $ gnuplot --version\ngnuplot 4.6 patchlevel 0\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,635
<p>I'm trying to program ARM using Eclipse + CDT + yagarto (gnu toolchain) + OpenOCD. In several sample projects (from yagarto site for example) I found linker scripts (*.ld) where a lot of linking information specified (along with sections definitions). Actually I haven't faced this files before (IAR doesn't need them), and I find them somewhat difficult to understand from a first glance. So my question is can I use one single such script file for my target processor (STR710FZ2T6) with all my projects or I have to get familiar in writing this scripts and write them for each project. If I can use single file for all projects for particular target processor can you please advice where I can find such universal one.</p>
[ { "answer_id": 871532, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 3, "selected": true, "text": "MEMORY\n{\n bob (RX) : ORIGIN = 0x0000000, LENGTH = 32K\n joe (WAIL) : ORIGIN = 0x2000000, LENGTH = 256K\n}\n\nSECTIONS\n{\n JANE : { startup.o } >bob\n}\n MEMORY\n{\n rom(RX) : ORIGIN = 0x00000000, LENGTH = 0x8000\n ram(WAIL) : ORIGIN = 0x20000000, LENGTH = 0x2000\n}\n\nSECTIONS\n{\n .text : { *(.text*) } > rom\n}\n arm-thumb-elf-gcc -Wall $(COPS) vectors.o putget.o blinker2.c -T memmap -o blinker2.elf\n arm-thumb-elf-ld vectors.o putget.o blinker2.o -T memmap -o blinker2.elf\n int rx;\n\nint main ( void )\n{\n rx = 7;\n int rx=7;\n\nint main ( void )\n{\n .globl _start\n_start:\n b reset\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n b hang\n\nhang : b hang\n\nreset:\n ldr sp,=0x10004000\n bl main\n b hang\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535/" ]
224,637
<p>I'm trying to use multiple attributes in my custom tag, e.g.:</p> <pre><code>&lt;mytaglib:mytag firstname="Thadeus" lastname="Jones" /&gt; </code></pre> <p>How can I access the attributes in the TagHandler code?</p>
[ { "answer_id": 224690, "author": "LizB", "author_id": 13616, "author_profile": "https://Stackoverflow.com/users/13616", "pm_score": 2, "selected": false, "text": "public class TagHandler extends TagSupport {\n private String firstName;\n private String lastName;\n\n public void setFirstName(String firstname) { firstName = firstname; }\n public void setLastName(String lastname) { lastName = lastname;}\n}\n public int doStartTag() throws JspException {\n pageContext.getOut().print(lastName + \", \" + firstName);\n}\n" }, { "answer_id": 45534831, "author": "Sachindra N. Pandey", "author_id": 3977387, "author_profile": "https://Stackoverflow.com/users/3977387", "pm_score": -1, "selected": false, "text": "<body>\n\n<%\nString name=request.getParameter(\"name\");\nString password=request.getParameter(\"password\");\n%>\n\n<%@ taglib prefix=\"c\" uri=\"/WEB-INF/mytag.tld\" %>\n\n<c:logintag name=\"<%=name %>\" password=\"<%=password %>\"/>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28557/" ]
224,643
<p>Recently I wrote an extremely basic Java Swing program with a couple of text fields and buttons. The program works fine for me on Ubuntu with Java 1.5. But when I try to run it on OSX (10.4), the main window is displayed correctly but the program seems unresponsive. Nothing seems to happen, no matter which button I click on.</p> <p>I know next to nothing about Mac OSX, so is there something I might be doing wrong?</p>
[ { "answer_id": 224847, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 2, "selected": false, "text": "JTextArea main" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
224,646
<pre><code>Double out = otherTypes.someMethod(c, c2); assertEquals((Double)-1.0D, out); </code></pre> <p>I get error "Double cannot be resolved" (the Double in assertEquals), is there any way to hack around it except extracting variable?</p> <p>Is this bug in Java or just very usefull feature that wont be fix?</p>
[ { "answer_id": 224685, "author": "Johann Zacharee", "author_id": 24290, "author_profile": "https://Stackoverflow.com/users/24290", "pm_score": 2, "selected": false, "text": "assertEquals(Double.valueOf(-1.0D), out)\n" }, { "answer_id": 224757, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 3, "selected": false, "text": "abs(double1 - double2) < delta assertEquals(double expected, double actual, double delta) assertEquals(-1.0d, (double) out, 0.000001d)\n" }, { "answer_id": 224937, "author": "jassuncao", "author_id": 1009, "author_profile": "https://Stackoverflow.com/users/1009", "pm_score": 0, "selected": false, "text": "assertEquals(Double.doubleToLongBits(-1.0), Double.doubleToLongBits(out));\n" }, { "answer_id": 225335, "author": "Miserable Variable", "author_id": 18573, "author_profile": "https://Stackoverflow.com/users/18573", "pm_score": 0, "selected": false, "text": "assertEquals(Double.class.cast(-1.0D), out);\n" }, { "answer_id": 227375, "author": "Sam", "author_id": 13979, "author_profile": "https://Stackoverflow.com/users/13979", "pm_score": 1, "selected": false, "text": "out.doubleValue() assertTrue(Math.abs(-1.0D-out.doubleValue()) < delta);\n assertEquals(-1.0d, out.doubleValue(), delta);\n double tDelta = delta*(Math.abs(-1.0D)+Math.abs(out.doubleValue()));\nassertEquals(-1.0d, out.doubleValue(), tDelta);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,648
<p>What is an external and internal iterator in Java ?</p>
[ { "answer_id": 224663, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 4, "selected": false, "text": "// using iterators for a clloection of String objects:\n// using in a for loop\nfor (Iterator it = options.iterator(); it.hasNext(); ) {\n String name = (String)it.next();\n System.out.println(name);\n}\n\n// using in while loop\nIterator name = options.iterator();\n while (name.hasNext() ){\n System.out.println(name.next() );\n }\n\n// using in a for-each loop (syntax available from java 1.5 and above)\n for (Object item : options)\n System.out.println(((String)item));\n collection do: [:each | each doSomething] (Smalltalk) \n Functor Functor" }, { "answer_id": 224675, "author": "Johann Zacharee", "author_id": 24290, "author_profile": "https://Stackoverflow.com/users/24290", "pm_score": 5, "selected": false, "text": "for (Iterator iter = var.iterator(); iter.hasNext(); ) {\n Object obj = iter.next();\n // Operate on obj\n}\n var.each( new Functor() {\n public void operate(Object arg) {\n arg *= 2;\n }\n});\n" }, { "answer_id": 51666760, "author": "Manas Kumar Maharana", "author_id": 6482564, "author_profile": "https://Stackoverflow.com/users/6482564", "pm_score": 0, "selected": false, "text": "package java8;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class IteratorExpr {\n\n public static void main(String[] args) {\n List<Integer> myList = new ArrayList<Integer>();\n for(int i=0; i<10; i++) myList.add(i);\n\n //Get sum of all value which is more than 5 using External Iterator\n int sum = 0;\n for(int no: myList) {\n if(no >=5) {\n sum += no;\n }\n }\n System.out.println(\"Sum of numbers using External api : \"+sum);\n\n int summ = myList.stream()\n .filter(p->p>=5)\n .mapToInt(p->p).sum();\n System.out.println(\"Sum of numbers using internal api : \"+summ);\n }\n\n}\n Sum of numbers using External api : 35\nSum of numbers using internal api : 35\n" }, { "answer_id": 51810958, "author": "Kishon", "author_id": 10215524, "author_profile": "https://Stackoverflow.com/users/10215524", "pm_score": 1, "selected": false, "text": "public class InternalIterator {\n\n public static void main(String args[]){\n\n List<String> namesList=Arrays.asList(\"Tom\", \"Dick\", \"Harry\");\n\n namesList.forEach(name -> System.out.println(name));//Internal Iteration\n\n }\n\n}\n import java.util.*;\n\npublic class ExternalIterator {\n\n public static void main(String args[]){\n List<String> namesList=Arrays.asList(\"Tom\", \"Dick\", \"Harry\");\n for(String name:namesList){\n System.out.println(name);\n }\n\n }\n\n}\n" }, { "answer_id": 52987994, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "int count = 0;\nIterator<SomeStaff> iterator = allTheStaffs.iterator();\nwhile(iterator.hasNext()) {\n SomeStaff staff = iterator.next();\n if(staff.getSalary() > 25) {\n count++;\n }\n}\n long count = allTheStaffs.stream()\n .filter(staff -> staff.getSalary() > 25)\n .count();\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,658
<p>I implemented a small OOP library in Lua, and two things are not quite right yet. I need your advice!</p> <h2>How to call super()?</h2> <p>I need to make a choice. The three arguments I need to resolve a call to super() are:</p> <ul> <li>The class from where the call is being made (CallerClass)</li> <li>The instance to be passed (self)</li> <li>The name of the method (method)</li> </ul> <p>I hesitate between these three forms:</p> <pre><code>--# Current way: self:super(CallerClass):method() --# Variant, which I now find cleaner: CallerClass:super(self):method() --# Python style, which is nice too: super(CallerClass, self):method() </code></pre> <p>Which one looks nicer and or easier to remember to you?</p> <h2>Do I need a Class symbol?</h2> <p>In the current version, the only concept is a table named <code>Object</code>, which you can subclass. I have another version where I introduced a Class symbol.</p> <p>Its use is to tell instances from classes. I.e. :</p> <pre><code>assert(Object:isKindOf(Class)) local object = Object:new() assert(not object:isKindOf(Class)) </code></pre> <p>I find it very handy to document and enforce that a method must be called from a class, by starting the method with:</p> <pre><code>assert(self:isKindOf(Class)) </code></pre> <p>Is it usefull in Lua? What do you think? Thanks!</p>
[ { "answer_id": 224682, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 2, "selected": true, "text": "--# Python style, which is nice too:\nsuper(CallerClass, self):method()\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2797/" ]
224,660
<p>Hi Guys could you please help me refactor this so that it is sensibly pythonic.</p> <pre><code>import sys import poplib import string import StringIO, rfc822 import datetime import logging def _dump_pop_emails(self): self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1])) self.popinstance = poplib.POP3(self.account[0]) self.logger.info(self.popinstance.getwelcome()) self.popinstance.user(self.account[1]) self.popinstance.pass_(self.account[2]) try: (numMsgs, totalSize) = self.popinstance.stat() for thisNum in range(1, numMsgs+1): (server_msg, body, octets) = self.popinstance.retr(thisNum) text = string.join(body, '\n') mesg = StringIO.StringIO(text) msg = rfc822.Message(mesg) name, email = msg.getaddr("From") emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml") emailpath = self._replace_whitespace(emailpath) file = open(emailpath,"wb") file.write(text) file.close() self.popinstance.dele(thisNum) finally: self.logger.info(self.popinstance.quit()) def _replace_whitespace(self,name): name = str(name) return name.replace(" ", "_") </code></pre> <p>Also in the _replace_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing.</p> <p>Basically I want to write the email to the inbox directory in a standard way.</p> <p>Am i doing something wrong here?</p>
[ { "answer_id": 224713, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "logger.info (\"foo %s %s\" % (bar, baz)) \"foo %s %s\", bar, baz try...finally emailpath '\\n'.join (body) string.join (body, '\\n') msg.getaddr(\"From\") msg.From" }, { "answer_id": 224752, "author": "Setori", "author_id": 21537, "author_profile": "https://Stackoverflow.com/users/21537", "pm_score": 0, "selected": false, "text": "def _dump_pop_emails(self):\n self.logger.info(\"open pop account %s with username: %s\", self.account[0], self.account[1])\n self.popinstance = poplib.POP3(self.account[0])\n self.logger.info(self.popinstance.getwelcome()) \n self.popinstance.user(self.account[1])\n self.popinstance.pass_(self.account[2])\n try:\n (numMsgs, totalSize) = self.popinstance.stat()\n for thisNum in range(1, numMsgs+1):\n (server_msg, body, octets) = self.popinstance.retr(thisNum)\n text = '\\n'.join(body)\n mesg = StringIO.StringIO(text) \n msg = rfc822.Message(mesg)\n name, email = msg.getaddr(\"From\")\n emailpath = str(self._emailpath + self._inboxfolder + \"\\\\\" + self._sanitize_string(email + \" \" + msg.getheader(\"Subject\") + \".eml\"))\n emailpath = self._replace_whitespace(emailpath)\n print emailpath\n file = open(emailpath,\"wb\")\n file.write(text)\n file.close()\n self.popinstance.dele(thisNum)\n finally:\n self.logger.info(self.popinstance.quit())\n\ndef _replace_whitespace(self,name):\n name = str(name)\n return name.replace(\" \", \"_\") \n\ndef _sanitize_string(self,name):\n illegal_chars = \":\", \"/\", \"\\\\\"\n name = str(name)\n for item in illegal_chars:\n name = name.replace(item, \"_\")\n return name\n" }, { "answer_id": 225029, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 2, "selected": true, "text": "emailpath = str(self._emailpath + self._inboxfolder + \"\\\\\" + email + \"_\" + msg.getheader(\"Subject\") + \".eml\")\n emailpath = os.path.join(self._emailpath + self._inboxfolder, email + \"_\" + msg.getheader(\"Subject\") + \".eml\")\n try:\n import cStringIO as StringIO\nexcept ImportError:\n import StringIO\n emailpath = \"\".join([c for c in emailpath if c in (string.letters + string.digits + \"_ \")])\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
224,662
<p>I have a composite control that adds a TextBox and a Label control to its Controls collection. When i try to set the Label's AssociatedControlID to the ClientID of the Textbox i get this error</p> <pre><code>Unable to find control with id 'ctl00_MainContentPlaceholder_MatrixSetControl_mec50_tb' that is associated with the Label 'lb'. </code></pre> <p>Ok so a little background. I got this main-composite control that dynamically adds a number of 'elements' to its control collection. One of these elements happen to be this 'MatrixTextBox' which is the control consisting of a TextBox and a Label.</p> <p>I hold the Label and TextBox as protected class variables and init them in CreateChildControls:</p> <pre><code> ElementTextBox = new TextBox(); ElementTextBox.ID = "tb"; Controls.Add(ElementTextBox); ElementLabel = new Label(); ElementLabel.ID = "lb"; Controls.Add(ElementLabel); </code></pre> <p>I tried setting the</p> <pre><code>ElementLabel.AssociatedControlID = ElementTextBox.ClientID; </code></pre> <p>both right after adding the controls to the Controls collection and even in PreRender - both yield the same error. What am i doing wrong?</p>
[ { "answer_id": 224710, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": true, "text": "ElementLabel.AssociatedControlID = ElementTextBox.ID;\n" }, { "answer_id": 292789, "author": "Patrick de Kleijn", "author_id": 33221, "author_profile": "https://Stackoverflow.com/users/33221", "pm_score": 2, "selected": false, "text": "private void AddRadioButton(PlaceHolder placeholder, string groupname, string text)\n{\n RadioButton radio = new RadioButton();\n radio.GroupName = groupname;\n radio.ID = Guid.NewGuid().ToString(); // Always set an ID.\n\n Label label = new Label();\n label.Text = text;\n label.AssociatedControlID = radio.ID;\n\n placeholder.Controls.Add(radio);\n placeholder.Controls.Add(label);\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
224,664
<p>What is the difference between a proxy server and a reverse proxy server?</p>
[ { "answer_id": 366212, "author": "qyb2zm302", "author_id": 44862, "author_profile": "https://Stackoverflow.com/users/44862", "pm_score": 12, "selected": false, "text": "X --> Z. Y --> Z X X --> Y --> Z X Z familypostcards2008.com facebook.com playboy.com wikipedia.org Z X X X --> Z. Z Y --> Z X X --> Y --> Z X Z X Y Z Y X Y X --> Y Y X --> Y --> Z Z Y" }, { "answer_id": 49607717, "author": "tinyhare", "author_id": 5232323, "author_profile": "https://Stackoverflow.com/users/5232323", "pm_score": 3, "selected": false, "text": " User side | Server side\nclient <-> proxy <--> reverse_proxy <-> real server\n" }, { "answer_id": 55736802, "author": "Fotios Basagiannis", "author_id": 1263190, "author_profile": "https://Stackoverflow.com/users/1263190", "pm_score": 1, "selected": false, "text": "c--\n |--p--s\nc--\n s--\n |--p--c\ns--\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,665
<p>i want to get datetime for 2days before. i.e) how to subtract 2 days from datetime.now</p>
[ { "answer_id": 224667, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 5, "selected": false, "text": "DateTime.Now.AddDays(-2);\n" }, { "answer_id": 224673, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 3, "selected": false, "text": "DateTime.Now.Subtract(TimeSpan.FromDays(2));\n" }, { "answer_id": 224676, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 1, "selected": false, "text": "DateTime twoDays = DateTime.Now.Subtract(new TimeSpan(2,0,0,0));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,687
<p>This is sort of a follow-up to <a href="https://stackoverflow.com/questions/223678">this question</a>.</p> <p>If there are multiple blobs with the same contents, they are only stored once in the git repository because their SHA-1's will be identical. How would one go about finding all duplicate files for a given tree? </p> <p>Would you have to walk the tree and look for duplicate hashes, or does git provide backlinks from each blob to all files in a tree that reference it?</p>
[ { "answer_id": 224948, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 2, "selected": false, "text": "git ls-tree -r HEAD\n git ls-tree -r" }, { "answer_id": 225041, "author": "lmop", "author_id": 22260, "author_profile": "https://Stackoverflow.com/users/22260", "pm_score": 4, "selected": true, "text": "#!/usr/bin/perl\n\n# usage: git ls-tree -r HEAD | $PROGRAM_NAME\n\nuse strict;\nuse warnings;\n\nmy $sha1_path = {};\n\nwhile (my $line = <STDIN>) {\n chomp $line;\n\n if ($line =~ m{ \\A \\d+ \\s+ \\w+ \\s+ (\\w+) \\s+ (\\S+) \\z }xms) {\n my $sha1 = $1;\n my $path = $2;\n\n push @{$sha1_path->{$sha1}}, $path;\n }\n}\n\nforeach my $sha1 (keys %$sha1_path) {\n if (scalar @{$sha1_path->{$sha1}} > 1) {\n foreach my $path (@{$sha1_path->{$sha1}}) {\n print \"$sha1 $path\\n\";\n }\n\n print '-' x 40, \"\\n\";\n }\n}\n" }, { "answer_id": 2743798, "author": "Romuald Brunet", "author_id": 286182, "author_profile": "https://Stackoverflow.com/users/286182", "pm_score": 3, "selected": false, "text": "ls-tree git ls-tree -r HEAD |\n sort -t ' ' -k 3 |\n perl -ne '$1 && / $1\\t/ && print \"\\e[0;31m\" ; / ([0-9a-f]{40})\\t/; print \"$_\\e[0m\"'\n" }, { "answer_id": 8408640, "author": "bsb", "author_id": 1462529, "author_profile": "https://Stackoverflow.com/users/1462529", "pm_score": 5, "selected": false, "text": "[alias]\n # find duplicate files from root\n alldupes = !\"git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40\"\n\n # find duplicate files from the current folder (can also be root)\n dupes = !\"cd `pwd`/$GIT_PREFIX && git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40\"\n" }, { "answer_id": 46964828, "author": "druud62", "author_id": 8840510, "author_profile": "https://Stackoverflow.com/users/8840510", "pm_score": 0, "selected": false, "text": "( for f in `find .`; do test -f $f && echo $(wc -c <$f) $(md5 -q $f) ; done ) |sort |uniq -c |grep -vE '^\\s*1\\b' |sed 's/.* //' > ~/dup.md5 ; \\\n( for f in `find .`; do test -f $f && echo $(wc -c <$f) $(md5 -q $f) $f; done ) |fgrep -f ~/dup.md5 |sort\n" }, { "answer_id": 49167126, "author": "bart", "author_id": 230899, "author_profile": "https://Stackoverflow.com/users/230899", "pm_score": 0, "selected": false, "text": "git ls-tree -r HEAD | group { $_ -replace '.{12}(.{40}).*', '$1' } | ? { $_.Count -gt 1 } | select -expand Group\n 100644 blob 8a49bcbae578c405ba2596c06f46fabbbc331c64 filename1\n100644 blob 8a49bcbae578c405ba2596c06f46fabbbc331c64 filename2\n100644 blob c1720b20bb3ad5761c1afb6a3113fbc2ba94994e filename3\n100644 blob c1720b20bb3ad5761c1afb6a3113fbc2ba94994e filename4\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
224,689
<p>What are the best practices to do transactions in C# .Net 2.0. What are the classes that should be used? What are the pitfalls to look out for etc. All that commit and rollback stuff. I'm just starting a project where I might need to do some transactions while inserting data into the DB. Any responses or links for even basic stuff about transactions are welcome. </p>
[ { "answer_id": 224702, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 9, "selected": true, "text": "using (IDbTransaction tran = conn.BeginTransaction()) {\n try {\n // your code\n tran.Commit();\n } catch {\n tran.Rollback();\n throw;\n }\n}\n using(TransactionScope tran = new TransactionScope()) {\n CallAMethodThatDoesSomeWork();\n CallAMethodThatDoesSomeMoreWork();\n tran.Complete();\n}\n" }, { "answer_id": 224707, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 0, "selected": false, "text": "SQLTransaction trans = null;\nusing(trans = new SqlTransaction)\n{\n ...\n Do SQL stuff here passing my trans into my various SQL executers\n ...\n trans.Commit // May not be quite right\n}\n using" }, { "answer_id": 13228090, "author": "Ali Gholizadeh", "author_id": 1799521, "author_profile": "https://Stackoverflow.com/users/1799521", "pm_score": 4, "selected": false, "text": "protected void Button1_Click(object sender, EventArgs e)\n {\n\n\n using (SqlConnection connection1 = new SqlConnection(\"Data Source=.\\\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\\\Database.mdf;Integrated Security=True;User Instance=True\"))\n {\n connection1.Open();\n\n // Start a local transaction.\n SqlTransaction sqlTran = connection1.BeginTransaction();\n\n // Enlist a command in the current transaction.\n SqlCommand command = connection1.CreateCommand();\n command.Transaction = sqlTran;\n\n try\n {\n // Execute two separate commands.\n command.CommandText =\n \"insert into [doctor](drname,drspecialization,drday) values ('a','b','c')\";\n command.ExecuteNonQuery();\n command.CommandText =\n \"insert into [doctor](drname,drspecialization,drday) values ('x','y','z')\";\n command.ExecuteNonQuery();\n\n // Commit the transaction.\n sqlTran.Commit();\n Label3.Text = \"Both records were written to database.\";\n }\n catch (Exception ex)\n {\n // Handle the exception if the transaction fails to commit.\n Label4.Text = ex.Message;\n\n\n try\n {\n // Attempt to roll back the transaction.\n sqlTran.Rollback();\n }\n catch (Exception exRollback)\n {\n // Throws an InvalidOperationException if the connection \n // is closed or the transaction has already been rolled \n // back on the server.\n Label5.Text = exRollback.Message;\n\n }\n }\n }\n\n\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
224,698
<p>I have a page which dynamically loads a section of content via AJAX. I'm concerned that this means the content will not be found by search engines.</p> <p>To show you what I mean, the site is at <a href="http://www.gold09.net" rel="nofollow noreferrer">http://www.gold09.net</a> and the dynamic content is at <a href="http://www.gold09.net/speakers.php" rel="nofollow noreferrer">/speakers.php</a> - Normally no one would visit that second link, it's just loaded into the first page.</p> <p>I know I can tell the crawlers to read the <code>speakers.php</code> by using a <code>sitemap.xml</code>, but then I'll get links to the speakers.php showing up in search results.</p> <p>I guess the ultimate solution would be so that if someone requests <code>/speakers.php</code> it redirects them to the main page, whereas it lets crawlers read the data.</p> <p>Any suggestions?</p>
[ { "answer_id": 224728, "author": "lock", "author_id": 24744, "author_profile": "https://Stackoverflow.com/users/24744", "pm_score": 0, "selected": false, "text": "index.php?ajaxpageneeded=page1\n <body onload=\"ajaxloaderscript(<?=page1?>);\" >\n" }, { "answer_id": 224973, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": true, "text": "viewSpeakers.php speakers.php index.php viewSpeakers.php viewSpeakers.php index.php" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
224,704
<p>I ran into a problem while cleaning up some old code. This is the function:</p> <pre><code>uint32_t ADT::get_connectivity_data( std::vector&lt; std::vector&lt;uint8_t&gt; &gt; &amp;output ) { output.resize(chunks.size()); for(chunk_vec_t::iterator it = chunks.begin(); it &lt; chunks.end(); ++it) { uint32_t success = (*it)-&gt;get_connectivity_data(output[it-chunks.begin()]); } return TRUE; } </code></pre> <p>What i am interested in doing is cleaning up the for loop to be a lambda expression but quickly got stuck on how exactly I would pass the correct argument to get_connectivity_data. get_connectivity_data takes a std::vector by reference and fills it with some data. output contains a std::vector for each "chunk".</p> <p>Basically my conclusion for this was that it was substantially easier, cleaner and <em>shorter</em> to leave my code as-is.</p> <p>EDIT:</p> <p>So the closest answer to my question as I envisioned it would look was this:</p> <pre><code> std::for_each( chunks.begin(), chunks.end(), bind( &amp;chunk_vec_t::value::type::get_connectivity_data, _1, output[ std::distance( _1, chunks.begn() ] ) ); </code></pre> <p>Yet that code does not compile, I made some modifications to the code to get it to compile but I ran into 2 issues:</p> <ol> <li>_ 1 is a smart ptr, and std::distance did not work on it, I think i needed to use &amp;chunks[0] as the start</li> <li>Since _ 1 is a smart pointer, I had to do: &amp;chunk_vec_t::value_ type::ValueType::get_ connectivity_ data which caused a crash in the VC9 compiler...</li> </ol> <p>The answer regarding zip_ iterators looked good until i read more into it and discovered that for this particular use, the amount of extra code needed was substantial (binding this and that, etc).</p> <p>EDIT2:</p> <p>I found an acceptable solution that is both low on extraneous syntax and clear, which I've posted here and below.</p> <pre><code>std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&amp;ADTChunk::get_connectivity_data, _1) ); </code></pre>
[ { "answer_id": 224739, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "typedef std::vector<uint8_t> Chunks;\ntypedef std::vector<Chunks> Output;\nuint32_t ADT::get_connectivity_data( Output &output )\n BOOST_FOREACH(chunk_vec_t::value_type &chunk, chunks)\n uint32_t success =\n chunk->get_connectivity_data(output[std::distance(&chunk, chunks.begin())]);\n typedef const boost::function2<uint32_t, chunk_vec_t::value_type, Chunks>\n GetConnectivity;\nuint32_t ADT::get_connectivity_data(Output &output, GetConnectivity &getConnectivity)\n{\n output.resize(chunks.size());\n BOOST_FOREACH(chunk_vec_t::value_type &chunk, chunks)\n uint32_t success =\n getConnectivity(chunk, output[std::distance(&chunk, chunks.begin())]);\n return TRUE;\n}\n get_connectivity_data(output,\n boost::bind(&chunk_vec_t::value_type::get_connectivity_data, _1, _2));\n" }, { "answer_id": 226150, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 2, "selected": false, "text": "uint32_t ADT::get_connectivity_data( std::vector< std::vector<uint8_t> > &output )\n{\n using namespace boost::lambda;\n\n output.resize( chunks.size() );\n\n std::for_each( chunks.begin(), chunks.end(), \n bind( &chunk_vec_t::value::type::get_connectivity_data, \n _1, \n output[ std::distance( _1, chunks.begn() ] \n )\n );\n return TRUE;\n}\n" }, { "answer_id": 227115, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "it-chunks.begin() for (size_t i = 0, size = chunks.size(); i < size; ++i)\n{\n chunks[i]->get_connectivity_data(output[i]);\n} \n" }, { "answer_id": 231060, "author": "Raindog", "author_id": 29049, "author_profile": "https://Stackoverflow.com/users/29049", "pm_score": 3, "selected": true, "text": "std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29049/" ]
224,712
<p>I had setup my clients &amp; server for passwordless login. Like passwordless login by copying RSA key of server to all client's /root/.ssh/id-rsa.pub. but this, I have done manually. I like to automate this process using shell script and providing password to the machines through script. If this problem is solved then I also want to use rsync to automate push items to all servers. Can any body help me in this regard.</p> <p>Thank you</p>
[ { "answer_id": 224716, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "ssh-copy-id [-i identity_file] [user@]machine\n #!/bin/sh\n\n# Shell script to install your identity.pub on a remote machine\n# Takes the remote machine name as an argument.\n# Obviously, the remote machine must accept password authentication,\n# or one of the other keys in your ssh-agent, for this to work.\n\nID_FILE=\"${HOME}/.ssh/identity.pub\"\n\nif [ \"-i\" = \"$1\" ]; then\n shift\n # check if we have 2 parameters left, if so the first is the new ID file\n if [ -n \"$2\" ]; then\n if expr \"$1\" : \".*\\.pub\" ; then\n ID_FILE=\"$1\"\n else\n ID_FILE=\"$1.pub\"\n fi\n shift # and this should leave $1 as the target name\n fi\nelse\n if [ x$SSH_AUTH_SOCK != x ] ; then\n GET_ID=\"$GET_ID ssh-add -L\"\n fi\nfi\n\nif [ -z \"`eval $GET_ID`\" ] && [ -r \"${ID_FILE}\" ] ; then\n GET_ID=\"cat ${ID_FILE}\"\nfi\n\nif [ -z \"`eval $GET_ID`\" ]; then\n echo \"$0: ERROR: No identities found\" >&2\n exit 1\nfi\n\nif [ \"$#\" -lt 1 ] || [ \"$1\" = \"-h\" ] || [ \"$1\" = \"--help\" ]; then\n echo \"Usage: $0 [-i [identity_file]] [user@]machine\" >&2\n exit 1\nfi\n\n{ eval \"$GET_ID\" ; } | ssh $1 \"umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys\" || exit 1\n\ncat <<EOF\nNow try logging into the machine, with \"ssh '$1'\", and check in:\n\n .ssh/authorized_keys\n\nto make sure we haven't added extra keys that you weren't expecting.\n\nEOF\n" }, { "answer_id": 224731, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": ".ssh/authorized_keys #!/usr/bin/expect\n\nspawn ssh user@remote-host\nexpect \"*password: $\"\nsend \"YOUR PASSWORD HERE\\n\"\nsend \"bash\\n\"\ninteract\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24813/" ]
224,714
<p>I just read a post mentioning "full text search" in SQL. </p> <p>I was just wondering what the difference between FTS and LIKE are. I did read a couple of articles but couldn't find anything that explained it well.</p>
[ { "answer_id": 29383200, "author": "Kingz", "author_id": 1642266, "author_profile": "https://Stackoverflow.com/users/1642266", "pm_score": 4, "selected": false, "text": "Document sets = {d1, d2, d3, d4, ... dn}\nTerm sets = {t1, t2, t3, .. tn}\n t1 -> {d1, d5, d9,.. dn}\nt2 -> {d11, d50, d2,.. dn}\nt3 -> {d23, d67, d34,.. dn}\n:\ntn -> {d90, d87, d57,.. dn}\n {d1, d5, d9,.. dn SELECT * \nFROM my_table \nWHERE MATCH (my_text_column) against ('XYZ' IN boolean mode) ;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
224,721
<p>I have the following class:</p> <pre><code>public abstract class AbstractParent { static String method() { return "OriginalOutput"; } } </code></pre> <p>I want to mock this method. I decide to use <a href="http://jmockit.dev.java.net" rel="noreferrer">JMockit</a>. So I create a mock class:</p> <pre><code>public class MockParent { static String method() { return "MOCK"; } } </code></pre> <p>And my test code looks like this:</p> <pre><code>public class RealParentTest { @Before public void setUp() throws Exception { Mockit.redefineMethods( AbstractParent.class, MockParent.class ); } @Test public void testMethod() { assertEquals(MockParent.method(),AbstractParent.method()); } } </code></pre> <p>Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.</p> <p><strong>Edit</strong> Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope.</p> <p><strong>Answer</strong> Only the mock method needs to be public, you can leave the original method as is.</p>
[ { "answer_id": 224773, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 4, "selected": true, "text": "public class MockParent {\n public static String method() {\n return \"MOCK\";\n }\n}\n" }, { "answer_id": 4439821, "author": "Gareth Davis", "author_id": 31480, "author_profile": "https://Stackoverflow.com/users/31480", "pm_score": 2, "selected": false, "text": "MockUp<T> new MockUp<AbstractParent>(){\n @Mock String method() {\n return \"MOCK\";\n }\n};\n\nassertEquals(\"MOCK\" AbstractParent.method());\n MockParent @MockClass" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
224,730
<p>I'm after some good tips for fluent interfaces in C#. I'm just learning about it myself but keen to hear what others think outside of the articles I am reading. In particular I'm after:</p> <ol> <li>when is fluent too much?</li> <li>are there any fluent patterns?</li> <li>what is in C# that makes fluent interfaces more fluent (e.g. extension methods)</li> <li>is a complex fluent interface still a fluent one?</li> <li>refactoring to arrive at a fluent interface or refactoring an existing fluent interface</li> <li>any good examples out there that you have worked with or could recommend?</li> </ol> <p>If you could post one tip or thought, or whatever per post. I want to see how they get voted on, too.</p> <p>Thank you in advance.</p>
[ { "answer_id": 224790, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 3, "selected": false, "text": "using(var transaction = new Transaction())\n{\n // ..\n // ..\n}\n (new Transaction()).Run( () => mycode(); );\n class Runner\n{\n Transaction StartTransaction()\n {\n return new Transaction(this);\n }\n}\n\nclass Transaction\n{\n Transaction Run()\n Transaction StopTransaction()\n}\n var runner = new Runner();\nrunner\n .StartTransaction()\n .Run()\n .StopTransaction();\n" }, { "answer_id": 500793, "author": "sbohlen", "author_id": 23208, "author_profile": "https://Stackoverflow.com/users/23208", "pm_score": 5, "selected": false, "text": "Assert().That().This(actual).Is().Equal().To(expected).\n Except().If(x => x.GreaterThan(10));\n" }, { "answer_id": 1327459, "author": "Finglas", "author_id": 102482, "author_profile": "https://Stackoverflow.com/users/102482", "pm_score": 3, "selected": false, "text": "ToString" }, { "answer_id": 1794940, "author": "sam", "author_id": 154462, "author_profile": "https://Stackoverflow.com/users/154462", "pm_score": 3, "selected": false, "text": "public class Coffee\n{\n private bool _cream;\n private int _ounces;\n\n public Coffee Make { get new Coffee(); }\n\n public Coffee WithCream()\n {\n _cream = true;\n return this;\n }\n\n public Coffee WithOuncesToServe(int ounces)\n {\n _ounces = ounces;\n return this;\n }\n}\n" }, { "answer_id": 18338222, "author": "An00bus", "author_id": 1794730, "author_profile": "https://Stackoverflow.com/users/1794730", "pm_score": 2, "selected": false, "text": "// Snarky employees get a raise.\nemployees.WhereSnarky().GiveRaise();\n // Depending on implementation, everyone may get a raise.\nemployees.GiveRaise().WhereSnarky();\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26625/" ]
224,732
<p>I have a database with <code>account numbers</code> and <code>card numbers</code>. I match these to a file to <code>update</code> any card numbers to the account number so that I am only working with account numbers.</p> <p>I created a view linking the table to the account/card database to return the <code>Table ID</code> and the related account number, and now I need to update those records where the ID matches the Account Number.</p> <p>This is the <code>Sales_Import</code> table, where the <code>account number</code> field needs to be updated:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LeadID</th> <th>AccountNumber</th> </tr> </thead> <tbody> <tr> <td>147</td> <td>5807811235</td> </tr> <tr> <td>150</td> <td>5807811326</td> </tr> <tr> <td>185</td> <td>7006100100007267039</td> </tr> </tbody> </table> </div> <p>And this is the <code>RetrieveAccountNumber</code> table, where I need to update from:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LeadID</th> <th>AccountNumber</th> </tr> </thead> <tbody> <tr> <td>147</td> <td>7006100100007266957</td> </tr> <tr> <td>150</td> <td>7006100100007267039</td> </tr> </tbody> </table> </div> <p>I tried the below, but no luck so far:</p> <pre><code>UPDATE [Sales_Lead].[dbo].[Sales_Import] SET [AccountNumber] = (SELECT RetrieveAccountNumber.AccountNumber FROM RetrieveAccountNumber WHERE [Sales_Lead].[dbo].[Sales_Import]. LeadID = RetrieveAccountNumber.LeadID) </code></pre> <p>It updates the card numbers to account numbers, but the account numbers get replaced by <code>NULL</code></p>
[ { "answer_id": 224740, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 11, "selected": false, "text": "UPDATE FROM JOIN UPDATE\n Sales_Import\nSET\n Sales_Import.AccountNumber = RAN.AccountNumber\nFROM\n Sales_Import SI\nINNER JOIN\n RetrieveAccountNumber RAN\nON \n SI.LeadID = RAN.LeadID;\n UPDATE\n Sales_Import SI,\n RetrieveAccountNumber RAN\nSET\n SI.AccountNumber = RAN.AccountNumber\nWHERE\n SI.LeadID = RAN.LeadID;\n" }, { "answer_id": 224742, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "UPDATE [Sales_Lead].[dbo].[Sales_Import] SET [AccountNumber] = \nRetrieveAccountNumber.AccountNumber \nFROM RetrieveAccountNumber \nWHERE [Sales_Lead].[dbo].[Sales_Import].LeadID = RetrieveAccountNumber.LeadID\n" }, { "answer_id": 224807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "UPDATE Sales_Import \nSET AccountNumber = (SELECT RetrieveAccountNumber.AccountNumber \n FROM RetrieveAccountNumber \n WHERE Sales_Import.leadid =RetrieveAccountNumber.LeadID) \nWHERE Sales_Import.leadid = (SELECT RetrieveAccountNumber.LeadID \n FROM RetrieveAccountNumber \n WHERE Sales_Import.leadid = RetrieveAccountNumber.LeadID) \n" }, { "answer_id": 803651, "author": "Kjell Andreassen", "author_id": 97874, "author_profile": "https://Stackoverflow.com/users/97874", "pm_score": 5, "selected": false, "text": "foo.new null foo bar" }, { "answer_id": 2101278, "author": "Shivkant", "author_id": 240706, "author_profile": "https://Stackoverflow.com/users/240706", "pm_score": 8, "selected": false, "text": "UPDATE table2 \nSET table2.col1 = table1.col1, \ntable2.col2 = table1.col2,\n...\nFROM table1, table2 \nWHERE table1.memberid = table2.memberid\n" }, { "answer_id": 9241260, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 7, "selected": false, "text": "MERGE UPDATE ... FROM MERGE INTO Sales_Import\n USING RetrieveAccountNumber\n ON Sales_Import.LeadID = RetrieveAccountNumber.LeadID\nWHEN MATCHED THEN\n UPDATE \n SET AccountNumber = RetrieveAccountNumber.AccountNumber;\n MERGE" }, { "answer_id": 9264291, "author": "marsanvi", "author_id": 880252, "author_profile": "https://Stackoverflow.com/users/880252", "pm_score": 5, "selected": false, "text": "UPDATE\n Sales_Import SI,RetrieveAccountNumber RAN\nSET\n SI.AccountNumber = RAN.AccountNumber\nWHERE\n SI.LeadID = RAN.LeadID\n" }, { "answer_id": 10880839, "author": "user824910", "author_id": 824910, "author_profile": "https://Stackoverflow.com/users/824910", "pm_score": 2, "selected": false, "text": " DECLARE @TB1 TABLE\n (\n No Int\n ,Name NVarchar(50)\n )\n\n DECLARE @TB2 TABLE\n (\n No Int\n ,Name NVarchar(50)\n )\n\n INSERT INTO @TB1 VALUES(1,'asdf');\n INSERT INTO @TB1 VALUES(2,'awerq');\n\n\n INSERT INTO @TB2 VALUES(1,';oiup');\n INSERT INTO @TB2 VALUES(2,'lkjhj');\n\n SELECT * FROM @TB1\n\n UPDATE @TB1 SET Name =S.Name\n FROM @TB1 T\n INNER JOIN @TB2 S\n ON S.No = T.No\n\n SELECT * FROM @TB1\n" }, { "answer_id": 13743594, "author": "NCP", "author_id": 1130019, "author_profile": "https://Stackoverflow.com/users/1130019", "pm_score": 2, "selected": false, "text": " DECLARE @TB1 TABLE\n (\n No Int\n ,Name NVarchar(50)\n ,linkNo int\n )\n\n DECLARE @TB2 TABLE\n (\n No Int\n ,Name NVarchar(50)\n ,linkNo int\n )\n\n INSERT INTO @TB1 VALUES(1,'changed person data', 0);\n INSERT INTO @TB1 VALUES(2,'old linked data of person', 1);\n\nINSERT INTO @TB2 SELECT * FROM @TB1 WHERE linkNo = 0\n\n\nSELECT * FROM @TB1\nSELECT * FROM @TB2\n\n\n UPDATE @TB1 \n SET Name = T2.Name\n FROM @TB1 T1\n INNER JOIN @TB2 T2 ON T2.No = T1.linkNo\n\n SELECT * FROM @TB1\n" }, { "answer_id": 24789509, "author": "petter", "author_id": 1749695, "author_profile": "https://Stackoverflow.com/users/1749695", "pm_score": 6, "selected": false, "text": "UPDATE Sales_Import SI\nSET AccountNumber = RAN.AccountNumber\nFROM RetrieveAccountNumber RAN\nWHERE RAN.LeadID = SI.LeadID; \n" }, { "answer_id": 29416743, "author": "CG_DEV", "author_id": 1426462, "author_profile": "https://Stackoverflow.com/users/1426462", "pm_score": 2, "selected": false, "text": "UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (\n SELECT * \n FROM (\n SELECT table1.id\n FROM table1 \n LEFT JOIN table2 ON ( table2.column = table1.column ) \n WHERE table1.column = 'some_expected_val'\n AND table12.column IS NULL\n ) AS Xalias\n)\n UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (\n SELECT * \n FROM (\n SELECT table1.id\n FROM table1 \n JOIN table2 ON ( table2.column = table1.column ) \n WHERE table1.column = 'some_expected_val'\n ) AS Xalias\n)\n" }, { "answer_id": 30233811, "author": "jakentus", "author_id": 1182664, "author_profile": "https://Stackoverflow.com/users/1182664", "pm_score": 3, "selected": false, "text": "UPDATE application\nSET omts_received_date = (\n SELECT\n date_created\n FROM\n application_history\n WHERE\n application.id = application_history.application_id\n AND application_history.application_status_id = 8\n);\n" }, { "answer_id": 37779007, "author": "Dr Inner Join", "author_id": 6455074, "author_profile": "https://Stackoverflow.com/users/6455074", "pm_score": 3, "selected": false, "text": "UPDATE table2 \nSET table2.col1 = table1.col1, \ntable2.col2 = table1.col2,\n...\nFROM table1, table2 \nWHERE table1.memberid = table2.memberid\n NOT IN NOT EXISTS JOIN NOT IN NOT IN NOT EXISTS UPDATE" }, { "answer_id": 39212355, "author": "Tigerjz32", "author_id": 1556242, "author_profile": "https://Stackoverflow.com/users/1556242", "pm_score": 7, "selected": false, "text": "UPDATE \n t1\nSET \n t1.column = t2.column\nFROM \n Table1 t1 \n INNER JOIN Table2 t2 \n ON t1.id = t2.id;\n UPDATE \n t1\nSET \n t1.colmun = t2.column \nFROM \n Table1 t1, \n Table2 t2 \nWHERE \n t1.ID = t2.ID;\n UPDATE \n Table1 t1, \n Table2 t2\nSET \n t1.column = t2.column \nWHERE\n t1.ID = t2.ID;\n" }, { "answer_id": 40589359, "author": "Developer", "author_id": 6757851, "author_profile": "https://Stackoverflow.com/users/6757851", "pm_score": 2, "selected": false, "text": "UPDATE\n Table_A\nSET\n Table_A.AccountNumber = Table_B.AccountNumber ,\nFROM\n dbo.Sales_Import AS Table_A\n INNER JOIN dbo.RetrieveAccountNumber AS Table_B\n ON Table_A.LeadID = Table_B.LeadID \nWHERE\n Table_A.LeadID = Table_B.LeadID\n" }, { "answer_id": 41132526, "author": "pacreely", "author_id": 6173015, "author_profile": "https://Stackoverflow.com/users/6173015", "pm_score": 0, "selected": false, "text": "DROP TABLE #TMP1\nDROP TABLE #TMP2\nCREATE TABLE #TMP1(LeadID Int,AccountNumber NVarchar(50))\nCREATE TABLE #TMP2(LeadID Int,AccountNumber NVarchar(50))\n\nINSERT INTO #TMP1 VALUES\n(147,'5807811235')\n,(150,'5807811326')\n,(185,'7006100100007267039');\n\nINSERT INTO #TMP2 VALUES\n(147,'7006100100007266957')\n,(150,'7006100100007267039')\n,(185,'7006100100007267039');\n\nUPDATE A\nSET A.AccountNumber = B.AccountNumber\nFROM\n #TMP1 A \n INNER JOIN #TMP2 B\n ON\n A.LeadID = B.LeadID\nWHERE\n A.AccountNumber <> B.AccountNumber --DON'T OVERWRITE A VALUE WITH THE SAME VALUE\n\nSELECT * FROM #TMP1\n" }, { "answer_id": 47251209, "author": "Gil Baggio", "author_id": 6037997, "author_profile": "https://Stackoverflow.com/users/6037997", "pm_score": 4, "selected": false, "text": "UPDATE Sales_Import, RetrieveAccountNumber \nSET Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber \nwhere Sales_Import.LeadID = RetrieveAccountNumber.LeadID;\n" }, { "answer_id": 48180175, "author": "Shaw", "author_id": 6137822, "author_profile": "https://Stackoverflow.com/users/6137822", "pm_score": -1, "selected": false, "text": "Update Sales_Import A left join RetrieveAccountNumber B on A.LeadID = B.LeadID\nSet A.AccountNumber = B.AccountNumber\nwhere A.LeadID = B.LeadID \n" }, { "answer_id": 52222942, "author": "Abhimanyu", "author_id": 1386991, "author_profile": "https://Stackoverflow.com/users/1386991", "pm_score": 5, "selected": false, "text": "UPDATE [AspNetUsers] SET\n\n[AspNetUsers].[OrganizationId] = [UserProfile].[OrganizationId],\n[AspNetUsers].[Name] = [UserProfile].[Name]\n\nFROM [AspNetUsers], [UserProfile]\nWHERE [AspNetUsers].[Id] = [UserProfile].[Id];\n" }, { "answer_id": 54294280, "author": "Bruno", "author_id": 10874278, "author_profile": "https://Stackoverflow.com/users/10874278", "pm_score": 1, "selected": false, "text": "merge into Sales_Import\nusing RetrieveAccountNumber\non (Sales_Import.LeadId = RetrieveAccountNumber.LeadId)\nwhen matched then update set Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber;\n" }, { "answer_id": 55805490, "author": "saman samadi", "author_id": 11387413, "author_profile": "https://Stackoverflow.com/users/11387413", "pm_score": 4, "selected": false, "text": "UPDATE c4 SET Price=cp.Price*p.FactorRate FROM TableNamea_A c4\ninner join TableNamea_B p on c4.Calcid=p.calcid \ninner join TableNamea_A cp on c4.Calcid=cp.calcid \nWHERE c4..Name='MyName';\n MERGE INTO TableNamea_A u \n using\n (\n SELECT c4.TableName_A_ID,(cp.Price*p.FactorRate) as CalcTot \n FROM TableNamea_A c4\n inner join TableNamea_B p on c4.Calcid=p.calcid \n inner join TableNamea_A cp on c4.Calcid=cp.calcid \n WHERE p.Name='MyName' \n ) rt\n on (u.TableNamea_A_ID=rt.TableNamea_B_ID)\n WHEN MATCHED THEN\n Update set Price=CalcTot ;\n" }, { "answer_id": 55822338, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "update database1..Ciudad\nset CiudadDistrito=c2.CiudadDistrito\n\nFROM database1..Ciudad c1\n inner join \n database2..Ciudad c2 on c2.CiudadID=c1.CiudadID\n" }, { "answer_id": 65393612, "author": "Shilwant Gupta", "author_id": 14554291, "author_profile": "https://Stackoverflow.com/users/14554291", "pm_score": 3, "selected": false, "text": "UPDATE \n TABLE1 t1, \n TABLE2 t2\nSET \n t1.column_name = t2.column_name \nWHERE\n t1.id = t2.id;\n" }, { "answer_id": 65593452, "author": "dobrivoje", "author_id": 1551368, "author_profile": "https://Stackoverflow.com/users/1551368", "pm_score": 2, "selected": false, "text": "reasonId id UPDATE `site` AS destination \nINNER JOIN `site_copy` AS backupOnTuesday \n ON backupOnTuesday.`id` = destination.`id`\nSET destdestination.`reasonId` = backupOnTuesday.`reasonId`\n" }, { "answer_id": 66529407, "author": "ABODE", "author_id": 7617526, "author_profile": "https://Stackoverflow.com/users/7617526", "pm_score": 3, "selected": false, "text": "UPDATE table2, table1 SET table2.by_department = table1.department WHERE table1.id = table2.by_id\n SET SQL_SAFE_UPDATES=0;\nUPDATE table2, table1 SET table2.by_department = table1.department WHERE table1.id = table2.by_id\n" }, { "answer_id": 70895998, "author": "Cuado", "author_id": 6189492, "author_profile": "https://Stackoverflow.com/users/6189492", "pm_score": 0, "selected": false, "text": "UPDATE suppliers\nSET supplier_name = (SELECT customers.customer_name\n FROM customers\n WHERE customers.customer_id = suppliers.supplier_id)\nWHERE EXISTS (SELECT customers.customer_name\n FROM customers\n WHERE customers.customer_id = suppliers.supplier_id);\n\n" }, { "answer_id": 71217836, "author": "Pasindu Perera", "author_id": 7095871, "author_profile": "https://Stackoverflow.com/users/7095871", "pm_score": 1, "selected": false, "text": "UPDATE Sales_Lead.dbo.Sales_Import SI \nSET SI.AccountNumber = (SELECT RAN.AccountNumber FROM RetrieveAccountNumber RAN WHERE RAN.LeadID = SI.LeadID);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,748
<p>I'm having trouble with a custom tag:-</p> <p>org.apache.jasper.JasperException: /custom_tags.jsp(1,0) Unable to find setter method for attribute : firstname</p> <p>This is my TagHandler class:</p> <pre><code>package com.cg.tags; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class NameTag extends TagSupport{ public String firstname; public String lastname; public void setFirstName(String firstname){ this.firstname=firstname; } public void setLastName(String lastname){ this.lastname=lastname; } public int doStartTag() throws JspException { try { JspWriter out=pageContext.getOut(); out.println( "First name: "+firstname+ "Last name: "+lastname); } catch (Exception ex) { throw new JspException("IO problems"); } return SKIP_BODY; } } </code></pre> <p>This is my TLD file:</p> <pre><code>?xml version="1.0" encoding="UTF-8"?&gt; &lt;taglib&gt; &lt;tlibversion&gt;1.1&lt;/tlibversion&gt; &lt;jspversion&gt;1.1&lt;/jspversion&gt; &lt;shortname&gt;utility&lt;/shortname&gt; &lt;uri&gt;/WEB-INF/nametagdesc.tld&lt;/uri&gt; &lt;info&gt; A simple tag library for the examples &lt;/info&gt; &lt;tag&gt; &lt;name&gt;name&lt;/name&gt; &lt;tagclass&gt;com.cg.tags.NameTag&lt;/tagclass&gt; &lt;bodycontent&gt;empty&lt;/bodycontent&gt; &lt;attribute&gt; &lt;name&gt;firstname&lt;/name&gt; &lt;required&gt;true&lt;/required&gt; &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt; &lt;/attribute&gt; &lt;attribute&gt; &lt;name&gt;lastname&lt;/name&gt; &lt;required&gt;true&lt;/required&gt; &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt; &lt;/attribute&gt; &lt;/tag&gt; &lt;/taglib&gt; </code></pre> <p>And this is my JSP page:</p> <pre><code>&lt;%@ taglib uri="/WEB-INF/nametagdesc.tld" prefix="cg" %&gt; &lt;cg:name firstname="fname" lastname="lname"/&gt; </code></pre> <p>I have checked that the code is recompiled and deployed correctly etc etc....</p> <p>So, the question is , why can't it find the setter method???</p>
[ { "answer_id": 224833, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "<tag>\n <name>...</name>\n <tag-class>...</tag-class>\n <body-content>...</body-content>\n <display-name>...</display-name>\n <description>...</description>\n\n <attribute>\n <name>firstName</name>\n <required>true</required>\n <rtexprvalue>true</rtexprvalue>\n <description>...</description>\n </attribute>\n</tag>\n" }, { "answer_id": 224911, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 5, "selected": true, "text": "'firstname' 'setFirstName' 'firstName' 'lastname' 'lastName' IntelliJ" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28557/" ]
224,756
<p>Our customers application seems to hang with the following stack trace:</p> <pre><code> java.lang.Thread.State: RUNNABLE at java.io.UnixFileSystem.getBooleanAttributes0(Native Method) at java.io.UnixFileSystem.getBooleanAttributes(Unknown Source) at java.io.File.isFile(Unknown Source) at org.tmatesoft.svn.core.internal.wc.SVNFileType.getType(SVNFileType.java:118) at org.tmatesoft.svn.core.internal.wc.SVNFileUtil.createUniqueFile(SVNFileUtil.java:299) - locked &lt;0x92ebb2a0&gt; (a java.lang.Class for org.tmatesoft.svn.core.internal.wc.SVNFileUtil) at org.tmatesoft.svn.core.internal.wc.SVNRemoteDiffEditor.createTempFile(SVNRemoteDiffEditor.java:415) at org.tmatesoft.svn.core.internal.wc.SVNRemoteDiffEditor.applyTextDelta(SVNRemoteDiffEditor.java:255) </code></pre> <p>Anyone know what could cause it to hang in isFile?</p>
[ { "answer_id": 224838, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "getBooleanAttributes0 stat stat64 jdk/src/solaris/native/java/io/UnixFileSystem_md.c stat strace stat" }, { "answer_id": 224864, "author": "staffan", "author_id": 988, "author_profile": "https://Stackoverflow.com/users/988", "pm_score": 3, "selected": false, "text": "stat getBooleanAttributes0" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,765
<p>I am trying to create a user interface using XAML. However, the file is quickly becoming very large and difficult to work with. What is the best way for splitting it across several files.</p> <p>I would like to be able to set the content of an element such as a ComboBox to an element that is defined in a different xaml file (but in the same VS project).</p> <p>thanks</p>
[ { "answer_id": 224803, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 5, "selected": false, "text": "<Page.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"myresourcedictionary.xaml\"/>\n <ResourceDictionary Source=\"myresourcedictionary2.xaml\"/>\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n</Page.Resources>\n" }, { "answer_id": 224805, "author": "Andrey Neverov", "author_id": 6698, "author_profile": "https://Stackoverflow.com/users/6698", "pm_score": -1, "selected": false, "text": "\n<Window>\n <VeryBigControl>\n <VeryBigControl.Style>\n ... <!--very long style-->\n </VeryBigControl.Style>\n .. <!--content of very big control-->\n </VeryBigControl\n</Window>\n" }, { "answer_id": 224816, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 7, "selected": true, "text": "<Window x:Class=\"YourCompany.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:Controls=\"clr-namespace:YourCompany.Controls\">\n\n <Controls:Foo ... />\n" }, { "answer_id": 40079551, "author": "Mike de Klerk", "author_id": 1567665, "author_profile": "https://Stackoverflow.com/users/1567665", "pm_score": 2, "selected": false, "text": "UserControl Page Window" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18966/" ]
224,771
<p>In python how do you read multiple files from a mysql database using the cursor or loop one by one and store the output in a separate table?</p>
[ { "answer_id": 224801, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": ">>> import MySQLdb\n>>> conn = MySQLdb.connect(host=\"localhost\",\n user=\"root\",\n password=\"merlin\",\n db=\"files\")\n>>> cursor = conn.cursor()\n>>> cursor.execute(\"SELECT * FROM files\")\n5L\n>>> rows = cursor.fetchall()\n>>> cursor.execute(\"CREATE TABLE destination (file varchar(255))\")\n0L\n>>> for row in rows:\n... cursor.execute(\"INSERT INTO destination VALUES (%s)\" % row[0])\n...\n1L\n1L\n1L\n1L\n1L\n" }, { "answer_id": 224844, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 0, "selected": false, "text": ">>> import MySQLdb\n>>> conn = MySQLdb.connect(user='username', db='dbname')\n>>> cur = conn.cursor()\n>>> cur.execute('select files from old_table where conditions=met')\n>>> a = cur.fetchall()\n>>> for item in a:\n... cur.execute('update new_table set new_field = %s' % item) # `item` should be tuple with one value, else use \"(item,)\" with comma\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
224,797
<p>I've got the following code to end a process, but I still receive an error code 2 (Access Denied).</p> <pre><code>strComputer = "." Set objWMIService = GetObject("winmgmts:\\" &amp; strComputer &amp; "\root\cimv2") Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'MSSEARCH.exe'") For each objProcess in colProcessList wscript.echo objProcess.processid intrc = objProcess.Terminate() if intrc = 0 then wscript.echo "succesfully killed process" else wscript.echo "Could not kill process. Error code: " &amp; intrc End if </code></pre>
[ { "answer_id": 224858, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "WScript.Shell net stop sc.exe Win32_Service Set Services = objWMIService.ExecQuery _\n (\"SELECT * FROM Win32_Service WHERE Name = '\" & ServiceName & \"'\")\n\nFor Each Service In Services\n Service.StopService()\n WSCript.Sleep 2000 ' wait for the service to terminate '\nNext\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28139/" ]
224,799
<p>I've noticed that plenty of opensource project doesn't use BITWISE flags anymore, even if it's fully supported by programming enviroment common for web ( php/Mysql). It's that a "lost practise" for some effective problem, or is just that a lot of php programmers don't know how to handle this type of implementation?</p> <p>Nothing too important, just very curious :) thanks to you all</p>
[ { "answer_id": 225292, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "OpenFile(\"...\", true, false)\n OpenFile(\"...\", writeonly | append)\n" }, { "answer_id": 6473736, "author": "Cory House", "author_id": 26180, "author_profile": "https://Stackoverflow.com/users/26180", "pm_score": 2, "selected": false, "text": "WHERE (ISNULL(flags, 0) & 4096 = 0 -- What does this bit refer to? \n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15392/" ]
224,820
<p>I'm trying to figure out how to pass arguments to an anonymous function in JavaScript.</p> <p>Check out this sample code and I think you will see what I mean:</p> <pre><code>&lt;input type="button" value="Click me" id="myButton" /&gt; &lt;script type="text/javascript"&gt; var myButton = document.getElementById("myButton"); var myMessage = "it's working"; myButton.onclick = function(myMessage) { alert(myMessage); }; &lt;/script&gt; </code></pre> <p>When clicking the button the message: <code>it's working</code> should appear. However the <code>myMessage</code> variable inside the anonymous function is null.</p> <p>jQuery uses a lot of anonymous functions, what is the best way to pass that argument?</p>
[ { "answer_id": 224834, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 7, "selected": true, "text": "<script type=\"text/javascript\">\n var myButton = document.getElementById(\"myButton\");\n var myMessage = \"it's working\";\n myButton.onclick = function() { alert(myMessage); };\n</script>\n" }, { "answer_id": 224835, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 3, "selected": false, "text": " myButton.onclick = function() { alert(myMessage); };\n" }, { "answer_id": 224839, "author": "jmcd", "author_id": 2285, "author_profile": "https://Stackoverflow.com/users/2285", "pm_score": 5, "selected": false, "text": "<input type=\"button\" value=\"Click me\" id=\"myButton\"/>\n\n<script type=\"text/javascript\">\n\n var myButton = document.getElementById(\"myButton\");\n\n var myMessage = \"it's working\";\n\n var myDelegate = function(message) {\n alert(message);\n }\n\n myButton.onclick = function() { \n myDelegate(myMessage);\n };\n\n</script>\n" }, { "answer_id": 224842, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 0, "selected": false, "text": "myButton.onclick = function() { alert(myMessage); };\n" }, { "answer_id": 224869, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "<input type=\"button\" value=\"Click me\" id=\"myButton\">\n<script>\n var myButton = document.getElementById(\"myButton\");\n var test = \"zipzambam\";\n myButton.onclick = function(eventObject) {\n if (!eventObject) {\n eventObject = window.event;\n }\n if (!eventObject.target) {\n eventObject.target = eventObject.srcElement;\n }\n alert(eventObject.target);\n alert(test);\n };\n (function(myMessage) {\n alert(myMessage);\n })(\"Hello\");\n</script>\n" }, { "answer_id": 224870, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "function displayMessage(message, f)\n{\n f(message); // execute function \"f\" with variable \"message\"\n}\n\nfunction alerter(message)\n{\n alert(message);\n}\n\nfunction writer(message)\n{\n document.write(message);\n}\n function runDelegate()\n{\n displayMessage(\"Hello World!\", alerter); // alert message\n\n displayMessage(\"Hello World!\", writer); // write message to DOM\n}\n" }, { "answer_id": 3834579, "author": "Un Known", "author_id": 463271, "author_profile": "https://Stackoverflow.com/users/463271", "pm_score": 2, "selected": false, "text": "<input type=\"button\" value=\"Click me\" id=\"myButton\" />\n\n<script type=\"text/javascript\">\n var myButton = document.getElementById(\"myButton\");\n\n myButton.myMessage = \"it's working\";\n\n myButton.onclick = function() { alert(this.myMessage); };\n\n\n</script>\n" }, { "answer_id": 3950023, "author": "Gabriel", "author_id": 204210, "author_profile": "https://Stackoverflow.com/users/204210", "pm_score": 4, "selected": false, "text": "var msg = (function(message){\n var _message = message;\n return {\n say:function(){alert(_message)},\n change:function(message){_message = message}\n };\n})(\"My Message\");\n$(\"#myButton\").click(msg.say);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29886/" ]
224,830
<p>I have a large script file (nearly 300MB, and feasibly bigger in the future) that I am trying to run. It has been suggested in the comments of Gulzar's answer to my <a href="https://stackoverflow.com/questions/222442/sql-server-running-large-script-files">question about it</a> that I should change the script timeout to 0 (no timeout).</p> <p>What is the best way to set this timeout from within the script? At the moment I have all of this at the top of the script file in the hopes that one of them does something:</p> <pre><code>sp_configure 'remote login timeout', 600 go sp_configure 'remote query timeout', 0 go sp_configure 'query wait', 0 go reconfigure with override go </code></pre> <p>However, I'm still getting the same result and I can't tell if I'm succeeding in setting the timeout because the response from sqlcmd.exe is the world's least helpful error message:</p> <blockquote> <p>Sqlcmd: Error: Scripting error.</p> </blockquote>
[ { "answer_id": 224955, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "exec sp_configure 'remote query timeout', 0 \ngo \nreconfigure with override \ngo \n" }, { "answer_id": 224956, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 4, "selected": true, "text": "sqlcmd -t {n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
224,845
<p>I am using the ruby daemons gem to create a custom daemon for my rails project. The only problem is that when I try to start the daemons <code>ruby lib/daemons/test_ctl start</code> that it fails and will not start. The log file has this output.</p> <pre><code># Logfile created on Wed Oct 22 16:14:23 +0000 2008 by / *** below you find the most recent exception thrown, this will be likely (but not certainly) the exception that made the application exit abnormally \*\*\* # MissingSourceFile: no such file to load -- utf8proc_native *** below you find all exception objects found in memory, some of them may have been thrown in your application, others may just be in memory because they are standard exceptions *** # NoMemoryError: failed to allocate memory&gt; # SystemStackError: stack level too deep&gt; # fatal: exception reentered&gt; # LoadError: no such file to load -- daemons&gt; # LoadError: no such file to load -- active_support&gt; # MissingSourceFile: no such file to load -- lib/string&gt; # MissingSourceFile: no such file to load -- utf8proc_native&gt; </code></pre> <p>It even happens when I generate a daemon (from the rails plugin) and try to run it. Does anybody know how to fix this problem? </p>
[ { "answer_id": 224990, "author": "Josh Moore", "author_id": 5004, "author_profile": "https://Stackoverflow.com/users/5004", "pm_score": 3, "selected": true, "text": "config/environment.rb" }, { "answer_id": 366241, "author": "Dave Smylie", "author_id": 1505600, "author_profile": "https://Stackoverflow.com/users/1505600", "pm_score": 1, "selected": false, "text": "LoadError: no such file to load -- active_support\n active_support lib/daemons/mailer_ctl require 'active_support'\n require './vendor/rails/activesupport/lib/active_support.rb'\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
224,865
<p>I'm wondering if there are any simple ways to get a list of all fixed-width (monospaced) fonts installed on a user's system in C#?</p> <p>I'm using .net 3.5 so have access to the WPF System.Windows.Media namespace and LINQ to get font information, but I'm not sure what I'm looking for.</p> <p>I want to be able to provide a filtered list of monospaced fonts and/or pick out monospaced fonts from a larger list of fonts (as seen in the VS options dialog).</p>
[ { "answer_id": 225027, "author": "Tim Ebenezer", "author_id": 30273, "author_profile": "https://Stackoverflow.com/users/30273", "pm_score": 5, "selected": true, "text": "foreach (FontFamily ff in System.Drawing.FontFamily.Families)\n{\n if (ff.IsStyleAvailable(FontStyle.Regular))\n {\n Font font = new Font(ff, 10);\n LOGFONT lf = new LOGFONT();\n font.ToLogFont(lf);\n if (lf.lfPitchAndFamily ^ 1)\n {\n do stuff here......\n }\n }\n}\n" }, { "answer_id": 8545011, "author": "Panos Theof", "author_id": 917341, "author_profile": "https://Stackoverflow.com/users/917341", "pm_score": 3, "selected": false, "text": " foreach ( FontFamily ff in FontFamily.Families ) {\n if ( ff.IsStyleAvailable( FontStyle.Regular ) ) {\n float diff;\n using ( Font font = new Font( ff, 16 ) ) {\n diff = TextRenderer.MeasureText( \"WWW\", font ).Width - TextRenderer.MeasureText( \"...\", font ).Width;\n }\n if ( Math.Abs( diff ) < float.Epsilon * 2 ) {\n Debug.WriteLine( ff.ToString() );\n }\n }\n\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
224,868
<p>I know it's simple to implement, but I want to reuse something that already exist.</p> <p>Problem I want to solve is that I load configuration (from XML so I want to cache them) for different pages, roles, ... so the combination of inputs can grow quite much (but in 99% will not). To handle this 1%, I want to have some max number of items in cache...</p> <p>Till know I have found org.apache.commons.collections.map.LRUMap in apache commons and it looks fine but want to check also something else. Any recommendations?</p>
[ { "answer_id": 224886, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 8, "selected": true, "text": "// Create cache\nfinal int MAX_ENTRIES = 100;\nMap cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {\n // This method is called just after a new entry has been added\n public boolean removeEldestEntry(Map.Entry eldest) {\n return size() > MAX_ENTRIES;\n }\n};\n\n// Add to cache\nObject key = \"key\";\ncache.put(key, object);\n\n// Get object\nObject o = cache.get(key);\nif (o == null && !cache.containsKey(key)) {\n // Object not in cache. If null is not a possible value in the cache,\n // the call to cache.contains(key) is not needed\n}\n\n// If the cache is to be used by multiple threads,\n// the cache must be wrapped with code to synchronize the methods\ncache = (Map)Collections.synchronizedMap(cache);\n" }, { "answer_id": 7584179, "author": "Bobby Powers", "author_id": 367650, "author_profile": "https://Stackoverflow.com/users/367650", "pm_score": 5, "selected": false, "text": "ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>()\n .maximumWeightedCapacity(1000)\n .build();\n" }, { "answer_id": 11731495, "author": "botek", "author_id": 1564403, "author_profile": "https://Stackoverflow.com/users/1564403", "pm_score": 4, "selected": false, "text": "public class Cache<K,V> {\nfinal Map<K,V> MRUdata;\nfinal Map<K,V> LRUdata;\n\npublic Cache(final int capacity)\n{\n LRUdata = new WeakHashMap<K, V>();\n\n MRUdata = new LinkedHashMap<K, V>(capacity+1, 1.0f, true) {\n protected boolean removeEldestEntry(Map.Entry<K,V> entry)\n {\n if (this.size() > capacity) {\n LRUdata.put(entry.getKey(), entry.getValue());\n return true;\n }\n return false;\n };\n };\n}\n\npublic synchronized V tryGet(K key)\n{\n V value = MRUdata.get(key);\n if (value!=null)\n return value;\n value = LRUdata.get(key);\n if (value!=null) {\n LRUdata.remove(key);\n MRUdata.put(key, value);\n }\n return value;\n}\n\npublic synchronized void set(K key, V value)\n{\n LRUdata.remove(key);\n MRUdata.put(key, value);\n}\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1128722/" ]
224,875
<p>Is it possible to do the equivalent of the following in xslt:</p> <pre><code>.//TagA[./TagB/[@AttrA='AttrAValue'] = 'TagBValue'] </code></pre> <p>This is failing within Visual Studio 2008 with the following error:</p> <pre><code>error: Unexpected token '[' in the expression. .//TagA[./TagB/ --&gt;[&lt;-- @AttrA='AttrAValue'] = 'TagBValue'] </code></pre> <p>Should this be working? Is this a problem in the MS implementation of XSLT, or is there a way I can get all TagA nodes that have a TagB node whose AttrA is equal to AttrAValue and whose TagB innerText is equal to TagBValue.</p>
[ { "answer_id": 224886, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 8, "selected": true, "text": "// Create cache\nfinal int MAX_ENTRIES = 100;\nMap cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {\n // This method is called just after a new entry has been added\n public boolean removeEldestEntry(Map.Entry eldest) {\n return size() > MAX_ENTRIES;\n }\n};\n\n// Add to cache\nObject key = \"key\";\ncache.put(key, object);\n\n// Get object\nObject o = cache.get(key);\nif (o == null && !cache.containsKey(key)) {\n // Object not in cache. If null is not a possible value in the cache,\n // the call to cache.contains(key) is not needed\n}\n\n// If the cache is to be used by multiple threads,\n// the cache must be wrapped with code to synchronize the methods\ncache = (Map)Collections.synchronizedMap(cache);\n" }, { "answer_id": 7584179, "author": "Bobby Powers", "author_id": 367650, "author_profile": "https://Stackoverflow.com/users/367650", "pm_score": 5, "selected": false, "text": "ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>()\n .maximumWeightedCapacity(1000)\n .build();\n" }, { "answer_id": 11731495, "author": "botek", "author_id": 1564403, "author_profile": "https://Stackoverflow.com/users/1564403", "pm_score": 4, "selected": false, "text": "public class Cache<K,V> {\nfinal Map<K,V> MRUdata;\nfinal Map<K,V> LRUdata;\n\npublic Cache(final int capacity)\n{\n LRUdata = new WeakHashMap<K, V>();\n\n MRUdata = new LinkedHashMap<K, V>(capacity+1, 1.0f, true) {\n protected boolean removeEldestEntry(Map.Entry<K,V> entry)\n {\n if (this.size() > capacity) {\n LRUdata.put(entry.getKey(), entry.getValue());\n return true;\n }\n return false;\n };\n };\n}\n\npublic synchronized V tryGet(K key)\n{\n V value = MRUdata.get(key);\n if (value!=null)\n return value;\n value = LRUdata.get(key);\n if (value!=null) {\n LRUdata.remove(key);\n MRUdata.put(key, value);\n }\n return value;\n}\n\npublic synchronized void set(K key, V value)\n{\n LRUdata.remove(key);\n MRUdata.put(key, value);\n}\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30273/" ]
224,878
<p>What is the best way to find out whether two number ranges intersect?</p> <p>My number range is <strong>3023-7430</strong>, now I want to test which of the following number ranges intersect with it: &lt;3000, 3000-6000, 6000-8000, 8000-10000, >10000. The answer should be <strong>3000-6000</strong> and <strong>6000-8000</strong>.</p> <p>What's the nice, efficient mathematical way to do this in any programming language?</p>
[ { "answer_id": 224897, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 5, "selected": true, "text": "Set<Range> determineIntersectedRanges(Range range, Set<Range> setofRangesToTest)\n{\n Set<Range> results;\n foreach (rangeToTest in setofRangesToTest)\n do\n if (rangeToTest.end <range.start) continue; // skip this one, its below our range\n if (rangeToTest.start >range.end) continue; // skip this one, its above our range\n results.add(rangeToTest);\n done\n return results;\n}\n" }, { "answer_id": 224907, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 3, "selected": false, "text": "foreach(Range r : rangeset) { if (range.intersects(r)) res.add(r) }\n rangeset.stream().filter(range::intersects).collect(Collectors.toSet())\n this.start <= other.end && this.end >= other.start\n" }, { "answer_id": 225079, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 1, "selected": false, "text": "class nrange(object):\n def __init__(self, lower = None, upper = None):\n self.lower = lower\n self.upper = upper\n def intersection(self, aRange):\n if self.upper < aRange.lower or aRange.upper < self.lower:\n return None\n else:\n return nrange(max(self.lower,aRange.lower), \\\n min(self.upper,aRange.upper))\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476/" ]
224,926
<p>for example, I have the following xml document:</p> <pre><code>def CAR_RECORDS = ''' &lt;records&gt; &lt;car name='HSV Maloo' make='Holden' year='2006'/&gt; &lt;car name='P50' make='Peel' year='1962'/&gt; &lt;car name='Royale' make='Bugatti' year='1931'/&gt; &lt;/records&gt; ''' </code></pre> <p>and I want to move the car "Royale" up to first one, and insert a new car just after car"HSV Maloo", the result would be:</p> <pre><code>''' &lt;records&gt; &lt;car name='Royale' make='Bugatti' year='1931'/&gt; &lt;car name='HSV Maloo' make='Holden' year='2006'/&gt; &lt;car name='My New Car' make='Peel' year='1962'/&gt; &lt;car name='P50' make='Peel' year='1962'/&gt; &lt;/records&gt; ''' </code></pre> <p>How to do it with Groovy? comments are welcome.</p>
[ { "answer_id": 227467, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 2, "selected": false, "text": "Node root = new XmlParser().parseText(CAR_RECORDS)\nNodeList carNodes = root.car\nNode royale = carNodes[2]\ncarNodes.remove(royale)\ncarNodes.add(0, royale)\ncarNodes.add(2, new Node(root, 'car', [name:'My New Card', make:'Peel', year:'1962']))\n" }, { "answer_id": 228505, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 5, "selected": true, "text": "def CAR_RECORDS = '''\n <records>\n <car name='HSV Maloo' make='Holden' year='2006'/>\n <car name='P50' make='Peel' year='1962'/>\n <car name='Royale' make='Bugatti' year='1931'/>\n </records>\n '''\n\ndef carRecords = new XmlParser().parseText(CAR_RECORDS)\n\ndef cars = carRecords.children()\ndef royale = cars.find { it.@name == 'Royale' } \ncars.remove(royale)\ncars.add(0, royale)\ndef newCar = new Node(carRecords, 'car', [name:'My New Car', make:'Peel', year:'1962'])\n\nassert [\"Royale\", \"HSV Maloo\", \"P50\", \"My New Car\"] == carRecords.car*.@name\n\nnew XmlNodePrinter().print(carRecords)\n <records>\n <car year=\"1931\" make=\"Bugatti\" name=\"Royale\"/>\n <car year=\"2006\" make=\"Holden\" name=\"HSV Maloo\"/>\n <car year=\"1962\" make=\"Peel\" name=\"P50\"/>\n <car name=\"My New Car\" make=\"Peel\" year=\"1962\"/>\n</records>\n" }, { "answer_id": 228905, "author": "flyisland", "author_id": 30275, "author_profile": "https://Stackoverflow.com/users/30275", "pm_score": 3, "selected": false, "text": "def newCar = new Node(null, 'car', [name:'My New Car', make:'Peel', year:'1962'])\ncars.add(2, newCar)\n\nnew XmlNodePrinter().print(carRecords)\n <records>\n <car year=\"1931\" make=\"Bugatti\" name=\"Royale\"/>\n <car year=\"2006\" make=\"Holden\" name=\"HSV Maloo\"/>\n <car name=\"My New Car\" make=\"Peel\" year=\"1962\"/>\n <car year=\"1962\" make=\"Peel\" name=\"P50\"/>\n</records>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30275/" ]
224,933
<p>Imagine you're creating a presentation that will be translated into a dozen different languages, including ones with non-latin characters (Chinese, for instance). The client's branding style guide dictates that certain fonts are acceptable for certain languages. The content itself is required to be externalized, so that the text can be replaced without ever opening a .fla, or re-saving a graphic.</p> <p>So we're talking dynamic TextField s, populated from XML, with the font swapped out to accommodate the viewer's locale - what's the most painless way to dynamically load only the fonts required (regardless of the filesize), and apply them as necessary? I'm looking for solutions using <strong>Flash only, not Flex</strong>.</p>
[ { "answer_id": 224975, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 0, "selected": false, "text": "[Embed(src=\"someFont.ttf\", fontFamily=\"myFont\", mimeType=\"application/x-font\")]\nprivate var fontClass:Class;\n\n...\n\nFont.registerFont(fontClass);\n" }, { "answer_id": 225024, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 0, "selected": false, "text": "_sans _serif _typewriter" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14026/" ]
224,952
<p>What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just</p> <pre><code>String content = new File("test.txt").readFully(); </code></pre>
[ { "answer_id": 224970, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 1, "selected": false, "text": "String content = (new RandomAccessFile(new File(\"test.txt\"))).readUTF();\n" }, { "answer_id": 225268, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "String[] lines = NioUtils.readInFile(componentxml);\n /**\n * Read lines in a file. <br />\n * File must exist\n * @param f file to be read\n * @return array of lines, empty if file empty\n * @throws IOException if prb during access or closing of the file\n */\npublic static String[] readInFile(final File f) throws IOException\n{\n final ArrayList lines = new ArrayList();\n IOException anioe = null;\n BufferedReader br = null; \n try \n {\n br = new BufferedReader(new FileReader(f));\n String line;\n line = br.readLine();\n while(line != null)\n {\n lines.add(line);\n line = br.readLine();\n }\n br.close();\n br = null;\n } \n catch (final IOException e) \n {\n anioe = e;\n }\n finally\n {\n if(br != null)\n {\n try {\n br.close();\n } catch (final IOException e) {\n anioe = e;\n }\n }\n if(anioe != null)\n {\n throw anioe;\n }\n }\n final String[] myStrings = new String[lines.size()];\n //myStrings = lines.toArray(myStrings);\n System.arraycopy(lines.toArray(), 0, myStrings, 0, lines.size());\n return myStrings;\n}\n" }, { "answer_id": 576480, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 3, "selected": false, "text": "Scanner s = new Scanner(new File(\"file\"));\nStringBuilder builder = new StringBuilder();\nwhile(s.hasNextLine()) builder.append(s.nextLine());\n" }, { "answer_id": 576485, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "private static String readFile(String path) throws IOException {\n FileInputStream stream = new FileInputStream(new File(path));\n try {\n FileChannel fc = stream.getChannel();\n MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());\n /* Instead of using default, pass in a decoder. */\n return CharSet.defaultCharset().decode(bb).toString();\n }\n finally {\n stream.close();\n }\n}\n" }, { "answer_id": 577356, "author": "Brian Agnew", "author_id": 12960, "author_profile": "https://Stackoverflow.com/users/12960", "pm_score": 4, "selected": true, "text": "IOUtils InputStream is = ...\nString contents = IOUtils.toString(is);\n// or\nList lines = IOUtils.readLines(is)\n" }, { "answer_id": 41591108, "author": "Doc Brown", "author_id": 3198272, "author_profile": "https://Stackoverflow.com/users/3198272", "pm_score": 0, "selected": false, "text": "try {\n String str = new String(Files.readAllBytes(Paths.get(\"myfile.txt\")));\n ...\n} catch (IOException ex) {\n Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ]
224,966
<p>What is the difference between <code>private</code> and <code>protected</code> members in C++ classes?</p> <p>I understand from best practice conventions that variables and functions which are not called outside the class should be made <code>private</code>—but looking at my MFC project, MFC seems to favor <code>protected</code>.</p> <p>What's the difference and which should I use?</p>
[ { "answer_id": 224980, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 3, "selected": false, "text": "protected private" }, { "answer_id": 224992, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 6, "selected": false, "text": "class Base {\n\nprivate: \n int MyPrivateInt;\nprotected: \n int MyProtectedInt;\npublic:\n int MyPublicInt;\n};\n\nclass Derived : Base\n{\npublic:\n int foo1() { return MyPrivateInt;} // Won't compile!\n int foo2() { return MyProtectedInt;} // OK \n int foo3() { return MyPublicInt;} // OK\n};‌‌\n\nclass Unrelated \n{\nprivate:\n Base B;\npublic:\n int foo1() { return B.MyPrivateInt;} // Won't compile!\n int foo2() { return B.MyProtectedInt;} // Won't compile\n int foo3() { return B.MyPublicInt;} // OK\n};\n" }, { "answer_id": 225014, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 3, "selected": false, "text": "class A\n{\nprivate:\n int _privInt = 0;\n int privFunc(){return 0;}\n virtual int privVirtFunc(){return 0;}\nprotected:\n int _protInt = 0;\n int protFunc(){return 0;}\npublic:\n int _publInt = 0;\n int publFunc()\n {\n return privVirtFunc();\n }\n};\n\nclass B : public A\n{\nprivate:\n virtual int privVirtFunc(){return 1;}\npublic:\n void func()\n {\n _privInt = 1; // wont work\n _protInt = 1; // will work\n _publInt = 1; // will work\n privFunc(); // wont work\n privVirtFunc(); // will work, simply calls the derived version.\n protFunc(); // will work\n publFunc(); // will return 1 since it's overridden in this class\n }\n}\n" }, { "answer_id": 225057, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 3, "selected": false, "text": "class" }, { "answer_id": 50870035, "author": "Barmak Shemirani", "author_id": 4603670, "author_profile": "https://Stackoverflow.com/users/4603670", "pm_score": 2, "selected": false, "text": "private private public public private protected public protected protected public private SetWindowText public OnLButtonDown protected private public public" }, { "answer_id": 71024182, "author": "zerocool", "author_id": 5104016, "author_profile": "https://Stackoverflow.com/users/5104016", "pm_score": 0, "selected": false, "text": "protected public private Class members protected protected private static friend" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
224,969
<p>I have a string (char) and I want to extract numbers out of it.</p> <p>So I have string: <code>1 2 3 4 /0</code><br> And now I want some variables, so I can use them as integer: <code>a=1, a=2, a=3, a=4</code></p> <p>How can I do that?</p>
[ { "answer_id": 224994, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\nint main(void)\n{\n int a, b, c, d;\n sscanf(\"1 2 3 4\", \"%d %d %d %d\", &a, &b, &c, &d);\n printf(\"%d,%d,%d,%d\\n\", a, b, c, d);\n}\n" }, { "answer_id": 224995, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 3, "selected": true, "text": "sscanf(string, \"%d %d %d %d\", &a, &b, &c, &d);\n" }, { "answer_id": 225003, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "char* copy;\nchar* token;\n\ncopy = strdup(string); /* strtok modifies the string, so we need a copy */\n\ntoken = strtok(copy, \" \");\nwhile(token!=NULL){\n /* token now points to one number.\n token = strtok(copy, \" \"); \n}\n" }, { "answer_id": 225012, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 2, "selected": false, "text": "if (4 != sscanf(buf, \"%d %d %d %d\", &a, &b, &c, &d))\n{\n /* deal with error */\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
224,996
<p>Some of us still "live" in a programming environment where unit testing has not yet been embraced. To get started, the obvious first step would be to try to implement a decent framework for unit testing, and I guess xUnit is the "standard".</p> <p>So what is a good starting point for implementing xUnit in a new programming language?</p> <p>BTW, since people are asking: My target environment is Visual Dataflex.</p>
[ { "answer_id": 225082, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "void Main() \n{\n var algorithmToTest = MyUniversalQuestionSolver();\n var question = Answer to { Life, Universe && Everything };\n\n var actual = algorithmToTest(question);\n var expected = 42;\n if (actual != expected) Error();\n\n // ... add a bunch of tests\n}\n MAIN.\n COMPUTE EXPECTED_ANSWER = 42\n SOLVE ANSWER_TO_EVERYTHING GIVING ACTUAL_ANSWER\n SUBTRACT ACTUAL_ANSWER FROM EXPECTED_ANSWER GIVING DIFFERENCE\n IF DIFFERENCE NOT.EQ 0 THEN\n DISPLAY \"ERROR!\"\n END-IF\n\n * ... add a bunch of tests\n STOP RUN\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18651/" ]
225,030
<p>When debugging in Internet Explorer, I first get an alert box with extremely limited if not useless information (sorry IE) and choose to debug it. After selecting yes, I get another option <em>every time</em> to choose between 'New instance of Microsoft script debugger' and 'New instance of Visual Studio'. I'm fed up with having to click the yes button again after having clicked it once already on the alert box.</p> <p>Update: I found that you can disable the Microsoft script debugger from within its own options; just disabling the JIT debugger from Tools -&gt; Options, and JIT. This stops it appearing on the menu but now I get the dialog box asking me which one to choose and it only displays the Visual Studio - WHY? If there's only one option and you've already asked me if I want to debug, why ask again?!?! Bleh.</p> <p>Can you tell I'm getting sick of clicking, &quot;yes&quot; twice? Lol.</p>
[ { "answer_id": 225676, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 0, "selected": false, "text": "Options -> Advanced -> Browsing -> Disable script debugging.\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24525/" ]
225,032
<p>I am using a native library which returns an IntPtr to a memory location, which contains the value of an attribute. I know what the type of the attribute is and I have a method for marshalling a value (taking the IntPtr and the type of the attribute) from the memory pointed at by the pointer. This method either calls Marshal.ReadInt32, or reads a series of bytes and converts them to a double, or reads a string with Marshal.PtrToStringUni etc etc. I would like to write some unit tests for this method but am not sure how I go about creating the IntPtr to pass to the method. I'm using NUnit and cannot use a mocking framework.</p>
[ { "answer_id": 225200, "author": "orj", "author_id": 20480, "author_profile": "https://Stackoverflow.com/users/20480", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.InteropServices;\nusing System.Diagnostics;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n private static double myDouble = 3.14;\n private static unsafe void TestPtrToDouble()\n {\n fixed(double* pDouble = &myDouble)\n {\n IntPtr intp = new IntPtr(pDouble);\n double[] copy = new double[1];\n Marshal.Copy(intp, copy, 0, 1);\n\n Debug.Assert(copy[0] == myDouble);\n } \n }\n\n private static char[] myString = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'm', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g' };\n\n private static unsafe void TestPtrToUnicodeString()\n {\n fixed (char* pChar = &myString[0])\n {\n IntPtr intp = new IntPtr(pChar);\n string copy = Marshal.PtrToStringUni(intp);\n\n Debug.Assert(copy == \"This is my string\");\n }\n }\n\n static void Main(string[] args)\n {\n TestPtrToUnicodeString();\n TestPtrToDouble();\n }\n }\n}\n fixed" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
225,034
<p>I'm currently looking for a possibility in Java to identify a font as symbolic like OpenOffice does. Characters with the font Windings or Webdings and so on should be rendered with the correct "pictures".</p> <p>Anyone an idea how to distinguish between normal fonts and fonts with symbols?</p>
[ { "answer_id": 5084272, "author": "Geoffrey Zheng", "author_id": 62479, "author_profile": "https://Stackoverflow.com/users/62479", "pm_score": 0, "selected": false, "text": "SYMBOL_CHARSET if( !java.awt.Font#canDisplay('a') )" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18633/" ]
225,045
<p>I've been reading up on conditional-style expressions in ruby. However I came across one I couldn't quite understand to define the classic FizzBuzz problem. I understand the FizzBuzz problem and even wrote my own before finding the following quick solution utilising the ternary operator. If someone can explain to me how this chain works to satisfy the FizzBuzz problem it would be very much appreciated :)</p> <pre><code>for i in 0...100 puts i%3==0 ? i%5==0 ? "FizzBuzz" : "Buzz" : i%5==0 ? "Fizz" : i end </code></pre>
[ { "answer_id": 225055, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "puts (i%3 == 0) ? ((i%5 == 0) ? \"FizzBuzz\" : \"Buzz\") : ((i%5 == 0) ? \"Fizz\" : i)\n" }, { "answer_id": 225056, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 1, "selected": false, "text": "if (i%3 == 0) { // multiple of 3\n if (i%5 == 0) { // multiple of 3 and 5\n puts \"FizzBuzz\"\n } else { // not multiple of 5, only of 3\n puts \"Buzz\"\n }\n} else ( // not multiple of 3\n if (i%5 == 0) { // multiple of 5, not of 3\n puts \"Fizz\"\n } else { // multiple of neither 5 nor 3\n puts i\n }\n}\n" }, { "answer_id": 225059, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 2, "selected": false, "text": "if i%3 ==0\n if i%5 == 0\n \"FizzBuzz\"\n else\n \"Buzz\"\nelse\n if i%5 == 0\n \"Fizz\"\n else\n i\n puts i%3==0 ? ( i%5==0 ? \"FizzBuzz\" : \"Buzz\" ) : ( i%5==0 ? \"Fizz\" : i )\n" }, { "answer_id": 225084, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": "int isEven = (i % 2 == 0) ? 1 : 0;\n if (i % 2 == 0) {\n isEven = 1;\n} else {\n isEven = 0;\n}\n i % 2 == 0 1 0 i%3==0 ?\n i%5==0 ?\n \"FizzBuzz\"\n : \"Buzz\"\n : i%5==0 ?\n \"Fizz\"\n : i\n if (i%3==0) {\n if (i%5==0) {\n \"FizzBuzz\"\n } else {\n \"Buzz\"\n }\n} else {\n if (i%5==0) {\n \"Fizz\"\n } else {\n i\n }\n}\n" }, { "answer_id": 227308, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 3, "selected": false, "text": "puts (1..100).map {|i| (fb = [[\"Fizz\"][i%3],[\"Buzz\"][i%5]].compact.join).empty? ? i : fb}\n (1..100).zip([nil,nil,\"Fizz\"]*34,[nil,nil,nil,nil,\"Buzz\"]*20).map {|a,b,c| b || c ? [b,c].join : a}\n" }, { "answer_id": 59937599, "author": "user3225968", "author_id": 3225968, "author_profile": "https://Stackoverflow.com/users/3225968", "pm_score": 0, "selected": false, "text": "for(int i = 1; i <= 100; i++) {\n string result = (i % 3 == 0 && i % 5 == 0) ? \n \"FizzBuzz\" : \n (i % 3 == 0) ? \n \"Fizz\" : \n (i % 5 == 0) ? \n \"Buzz\" : \n i.ToString();\n Console.WriteLine(result);\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2294/" ]
225,052
<p>How do I get the KeyDown event to work in a Delphi (2007) MDI Applications Parent window, even if a Child window has focus?</p> <p>I would like to implement a shortcut key (F1) that brings up a help screen in a MDI application, I have added the KeyDown procedure to the MDI Parent window and enabled KeyPreview in both the Parent and Child windows, but it does not work as expected.</p> <p>If I put a break point in the Parents KeyDown code I can see it never executes, even it there are no child windows open. But if I add the same code to the child window it works fine.</p> <p>Is there a way to get the parent window to receive the key presses, even if the child window has focus, as adding the code to 25+ forms seams a little wasteful?</p>
[ { "answer_id": 225996, "author": "Jeremy Mullin", "author_id": 7893, "author_profile": "https://Stackoverflow.com/users/7893", "pm_score": 2, "selected": false, "text": "Application.OnMessage := AppMessage;\n\nprocedure TMainForm.Appmessage(var Msg: TMsg; var Handled: Boolean);\nvar\n message: TWMKey;\nbegin\n If (msg.message = WM_KEYDOWN) and\n ( LoWord(msg.wparam) = VK_TAB ) and\n (GetKeyState( VK_CONTROL ) < 0 ) and\n Assigned( ActiveMDIChild ) then\n Begin\n Move( msg.message, message.msg, 3*sizeof(Cardinal));\n message.result := 0;\n Handled := ActiveMDIChild.IsShortcut( message );\n End;\nend;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
225,071
<p>I am making an web based appliaction in java (using jsp). When the appliaction is invoked login page will come, when the user enter the valid credientials, he will be taken to the index page. But the problem is, when the login is success, the index page is coming but it is opening behind the login page. (means login page appears on the top of the monitor, I want index page should appear on the top of the window.) Can anyone help me out in this...Please</p>
[ { "answer_id": 225996, "author": "Jeremy Mullin", "author_id": 7893, "author_profile": "https://Stackoverflow.com/users/7893", "pm_score": 2, "selected": false, "text": "Application.OnMessage := AppMessage;\n\nprocedure TMainForm.Appmessage(var Msg: TMsg; var Handled: Boolean);\nvar\n message: TWMKey;\nbegin\n If (msg.message = WM_KEYDOWN) and\n ( LoWord(msg.wparam) = VK_TAB ) and\n (GetKeyState( VK_CONTROL ) < 0 ) and\n Assigned( ActiveMDIChild ) then\n Begin\n Move( msg.message, message.msg, 3*sizeof(Cardinal));\n message.result := 0;\n Handled := ActiveMDIChild.IsShortcut( message );\n End;\nend;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]