qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
133,698
<p>I've created a new C++ project in Visual Studio 2008. No code has been written yet; Only project settings have been changed.</p> <p>When I compile the project, I receive the following fatal error:</p> <blockquote> <p>fatal error LNK1104: cannot open file 'C:\Program.obj'</p> </blockquote>
[ { "answer_id": 34412895, "author": "Patrizio Bertoni", "author_id": 1315480, "author_profile": "https://Stackoverflow.com/users/1315480", "pm_score": 3, "selected": false, "text": ".lib mylib mylib.obj" }, { "answer_id": 34875485, "author": "Matthias", "author_id": 5272567, "author_profile": "https://Stackoverflow.com/users/5272567", "pm_score": 2, "selected": false, "text": "Project -> Properties -> Linker -> General <boost/filesystem.hpp> \"cannot open file 'llibboost_filesystem-vc140-mt-gd-1_59.lib'\"" }, { "answer_id": 37671806, "author": "Nazarii Plebanskii", "author_id": 4030395, "author_profile": "https://Stackoverflow.com/users/4030395", "pm_score": 2, "selected": false, "text": "MyProg.exe" }, { "answer_id": 41393772, "author": "Lissandro", "author_id": 2516699, "author_profile": "https://Stackoverflow.com/users/2516699", "pm_score": 2, "selected": false, "text": "msbuild32.exe" }, { "answer_id": 46939703, "author": "zar", "author_id": 841330, "author_profile": "https://Stackoverflow.com/users/841330", "pm_score": 0, "selected": false, "text": "fatal error LNK1104: cannot open file 'GTest.lib;'\n ; ;" }, { "answer_id": 53293688, "author": "user3860869", "author_id": 3860869, "author_profile": "https://Stackoverflow.com/users/3860869", "pm_score": -1, "selected": false, "text": "LNK1104: cannot open file 'debug\\****.exe\n" }, { "answer_id": 62933404, "author": "Imad", "author_id": 3664659, "author_profile": "https://Stackoverflow.com/users/3664659", "pm_score": 0, "selected": false, "text": "msbuild32.exe" }, { "answer_id": 65196059, "author": "Alfred Meier", "author_id": 5621302, "author_profile": "https://Stackoverflow.com/users/5621302", "pm_score": 2, "selected": false, "text": "..\\..\\..\\..\\..\\..\\..\\SWX\\Binary\\VS2008\\Output\\Win32\\Debug\\boost_unit_test_framework-vc90-mt-gd-1_57.lib;\n ..\\..\\..\\..\\..\\..\\..\\SWX\\Binary\\VS2008\\Output\\Win32\\Release\\boost_unit_test_framework-vc90-mt-1_57.lib;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21277/" ]
133,703
<p>I want to know how to create a table where you can adjust the column widths. I have not figured out how to do this. If you know the secret sauce to this technique please let me know.</p>
[ { "answer_id": 142856, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "$('#myTableID').flexigrid();\n $('.classOfTables').flexigrid({height:'auto',striped:false});\n" }, { "answer_id": 48142456, "author": "user4723924", "author_id": 9185690, "author_profile": "https://Stackoverflow.com/users/9185690", "pm_score": 3, "selected": false, "text": " th {resize:horizontal; overflow:auto;}\n" }, { "answer_id": 49551149, "author": "Ataman Semyonov", "author_id": 1676758, "author_profile": "https://Stackoverflow.com/users/1676758", "pm_score": 1, "selected": false, "text": "resize:horizontal <th> <div> .mytable th div{\n resize:horizontal;\n overflow: auto;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
133,710
<p>When I use the task, the property is only set to TRUE if the resource (say file) is available. If not, the property is undefined.</p> <p>When I print the value of the property, it gives true if the resource was available, but otherwise just prints the property name.</p> <p>Is there a way to set the property to some value if the resource is <em>not</em> available? I have tried setting the property explicitly before the available check, but then ant complains:</p> <pre> [available] DEPRECATED - used to override an existing property. [available] Build file should not reuse the same property name for different values. </pre>
[ { "answer_id": 133770, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 5, "selected": true, "text": " <condition property=\"fooDoesNotExist\">\n <not>\n <available filepath=\"path/to/foo\"/>\n </not>\n </condition>\n" }, { "answer_id": 1368355, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<available filepath=\"/path/to/foo\" property=\"foosThere\" value=\"true\"/>\n<property name=\"foosThere\" value=\"false\"/>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
133,719
<p>I am running Ruby and MySQL on a Windows box.</p> <p>I have some Ruby code that needs to connect to a MySQL database a perform a select. To connect to the database I need to provide the password among other things. </p> <p>The Ruby code can display a prompt requesting the password, the user types in the password and hits the Enter key. What I need is for the password, as it is typed, to be displayed as a line of asterisks.</p> <p>How can I get Ruby to display the typed password as a line of asterisks in the 'dos box'?</p>
[ { "answer_id": 133745, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 5, "selected": false, "text": "system \"stty -echo\"\n# read password\nsystem \"stty echo\"\n" }, { "answer_id": 134323, "author": "Simon Knights", "author_id": 15868, "author_profile": "https://Stackoverflow.com/users/15868", "pm_score": 7, "selected": true, "text": "require 'rubygems'\nrequire 'highline/import'\n\ndef get_password(prompt=\"Enter Password\")\n ask(prompt) {|q| q.echo = false}\nend\n\nthePassword = get_password()\n" }, { "answer_id": 2639732, "author": "Eric Monti", "author_id": 316790, "author_profile": "https://Stackoverflow.com/users/316790", "pm_score": 4, "selected": false, "text": "#!/usr/local/bin/ruby\nrequire 'rubygems'\nrequire 'highline/import'\n\nusername = ask(\"Enter your username: \") { |q| q.echo = true }\npassword = ask(\"Enter your password: \") { |q| q.echo = \"*\" }\n $ ruby highline.rb \nEnter your username: doug\nEnter your password: ******\n" }, { "answer_id": 18751693, "author": "Jesse Schwartz", "author_id": 2358439, "author_profile": "https://Stackoverflow.com/users/2358439", "pm_score": 2, "selected": false, "text": "require 'highline/import'\n\n$userid = ask(\"Enter your username: \") { |q| q.echo = true }\n$passwd = ask(\"Enter your password: \") { |q| q.echo = \"*\" }\n E:\\Tools>ruby login.rb\nEnter your username: username\nEnter your password: ********\n E:\\Tools>jruby login.rb\nEnter your username: username\nEnter your password:\n" }, { "answer_id": 39392777, "author": "Lorin Thwaits", "author_id": 5068758, "author_profile": "https://Stackoverflow.com/users/5068758", "pm_score": 0, "selected": false, "text": "require 'fancy_gets'\ninclude FancyGets\n\nputs \"Password:\"\npwd = gets_password\n# ...\n" }, { "answer_id": 50649664, "author": "Kris", "author_id": 22237, "author_profile": "https://Stackoverflow.com/users/22237", "pm_score": 3, "selected": false, "text": "IO#getpass require 'io/console' \n\nSTDIN.getpass(\"Password: \")\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15868/" ]
133,772
<p>I've got a class that I'm using as a settings class that is serialized into an XML file that administrators can then edit to change settings in the application. (The settings are a little more complex than the <code>App.config</code> allows for.)</p> <p>I'm using the <code>XmlSerializer</code> class to deserialize the XML file, and I want it to be able to set the property class but I don't want other developers using the class/assembly to be able to set/change the property through code. Can I make this happen with the XmlSerializer class?</p> <p>To add a few more details: This particular class is a Collection and according to FxCop the <code>XmlSerializer</code> class has special support for deserializing read-only collections, but I haven't been able to find any more information on it. The exact details on the rule this violates is:</p> <blockquote> <p>Properties that return collections should be read-only so that users cannot entirely replace the backing store. Users can still modify the contents of the collection by calling relevant methods on the collection. Note that the XmlSerializer class has special support for deserializing read-only collections. See the XmlSerializer overview for more information.</p> </blockquote> <p>This is exactly what I want, but how do it do it?</p> <p><strong>Edit:</strong> OK, I think I'm going a little crazy here. In my case, all I had to do was initialize the Collection object in the constructor and then remove the property setter. Then the XmlSerializable object actually knows to use the Add/AddRange and indexer properties in the Collection object. The following actually works!</p> <pre><code>public class MySettings { private Collection&lt;MySubSettings&gt; _subSettings; public MySettings() { _subSettings = new Collection&lt;MySubSettings&gt;(); } public Collection&lt;MySubSettings&gt; SubSettings { get { return _subSettings; } } } </code></pre>
[ { "answer_id": 133804, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "public List<MyObject> Collection\n{\n get { return _collection; }\n set { _collection = value; }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21807/" ]
133,774
<p>I am using RRDTool (<a href="http://oss.oetiker.ch/rrdtool/" rel="nofollow noreferrer">http://oss.oetiker.ch/rrdtool/</a>) as a graphing back-end for storing performance metrics. This is done via the RRDTool CLI from a Python script.</p> <p>My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace. Sometimes an update fails because one thread is accessing the RRD file while another one tries to access it also.</p> <p>I was under the impression that this is OK to try since RRDTool uses its own locking mechanism, but I guess that isn't true.</p> <p>Does anyone have a good approach for concurrent access to an RRD?</p> <p>I can think of a few ways to go:</p> <ol> <li><p>have 1 thread create a queue and only feed the RRD from a single thread.</p></li> <li><p>create my own locking mechanism inside the Python script. (how would I do this?)</p></li> </ol> <p>got anything better or have you run into this issue before?</p>
[ { "answer_id": 134023, "author": "Johan Buret", "author_id": 15366, "author_profile": "https://Stackoverflow.com/users/15366", "pm_score": 2, "selected": true, "text": "lock = new Lock()" }, { "answer_id": 26704889, "author": "Steve Shipway", "author_id": 2480362, "author_profile": "https://Stackoverflow.com/users/2480362", "pm_score": 0, "selected": false, "text": "rrdcached rrdtool rrdcached" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ]
133,777
<p>I have a subversion repository that contains a number so subfolders, corresponding to the various applications, configuration files, DLLs, etc (I'll call them 'modules') that make up my project. Now we are starting to "branch" into several related projects. That is, each high-level project will use a number of the modules, possibly slightly modified from project to project. The number of projects is smaller (~5) than the number of modules (~20)</p> <p>Now I'm trying to figure out how to organize the repo. Does it make sense to keep the top level subfolders on a module-by-module basis, with sub-subfolders for each project? Or should the top level be for each project, with each project having its own module subfolders:</p> <p>repo:</p> <pre><code>module 1 Project 1 Project 2 ... Project 5 module 2 Project 1 .... Project 5 .... module 20 Project 1 ... Project 5 </code></pre> <p>-or-</p> <p>repo:</p> <pre><code>Project 1 module 1 module 2 ... module 20 Project 2 module 1 module 2 ... module 20 ... Project 5 module 1 module 2 ... module 20 </code></pre>
[ { "answer_id": 133828, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "Projects\n Project 1\n Project 2\n ...\nModules\n Module 1\n Module 2\n ...\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17962/" ]
133,837
<p>What might be the best way to start programming using boost lambda libraries.</p>
[ { "answer_id": 135367, "author": "Fruny", "author_id": 16815, "author_profile": "https://Stackoverflow.com/users/16815", "pm_score": 5, "selected": true, "text": "for_each(a.begin(), a.end(), std::cout << _1 << ' ');\n std::cout << _1 << ' ' cout std::ostream_iterator std::sort( c.begin(), c.end(), bind(&Foo::x, _1) < bind(&Foo::x, _2) );\n for" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
133,840
<p>I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?</p> <p>Thanks!</p> <p>-fREW</p>
[ { "answer_id": 136249, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "content_tag render :partial return %Q(<a href=\"#{something}\">#{text}>)" }, { "answer_id": 11813612, "author": "Victor Pudeyev", "author_id": 484460, "author_profile": "https://Stackoverflow.com/users/484460", "pm_score": -1, "selected": false, "text": "=hr =render 'hr' def hr\n raw '<hr />'\nend\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
[ { "answer_id": 133983, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 3, "selected": false, "text": "svn --config-dir /home/myuser/.subversion checkout http://example.com/path\n" }, { "answer_id": 138587, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 0, "selected": false, "text": "id > /tmp/id\n" }, { "answer_id": 145501, "author": "victorz", "author_id": 140995, "author_profile": "https://Stackoverflow.com/users/140995", "pm_score": 0, "selected": false, "text": " QAHOME=/home/qa\n ...\n HOME=$QAHOME LANG=$HTTPD_LANG daemon $httpd $OPTIONS\n" }, { "answer_id": 3105538, "author": "Lathan", "author_id": 118993, "author_profile": "https://Stackoverflow.com/users/118993", "pm_score": 0, "selected": false, "text": "sudo /etc/init.d/apache2 stop\nsudo /etc/init.d/apache2 start\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140995/" ]
133,879
<p>When developing an app that will listen on a TCP/IP port, how should one go about selecting a default port? Assume that this app will be installed on many computers, and that avoiding port conflicts is desired.</p>
[ { "answer_id": 133888, "author": "Kevin Wong", "author_id": 4792, "author_profile": "https://Stackoverflow.com/users/4792", "pm_score": 7, "selected": true, "text": "Unassigned" }, { "answer_id": 43427640, "author": "Mahdi Perfect", "author_id": 1231603, "author_profile": "https://Stackoverflow.com/users/1231603", "pm_score": 0, "selected": false, "text": "for port in {N..M}; do if ! grep -q $port service-names-port-numbers.csv; then echo $port;fi; done;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ]
133,883
<p>How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?</p>
[ { "answer_id": 133900, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "net start net stop" }, { "answer_id": 133913, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 8, "selected": false, "text": "net start [serviceName]\n net stop [serviceName]\n U:\\>net stop alerter\nThe Alerter service is not started.\n\nMore help is available by typing NET HELPMSG 3521.\n error.bat @echo off\nnet stop alerter\nif ERRORLEVEL 1 goto error\nexit\n:error\necho There was a problem\npause\n U:\\>error.bat\nThe Alerter service is not started.\n\nMore help is available by typing NET HELPMSG 3521.\n\nThere was a problem\nPress any key to continue . . .\n - 0 = Success\n - 1 = Not Supported\n - 2 = Access Denied\n - 3 = Dependent Services Running\n - 4 = Invalid Service Control\n - 5 = Service Cannot Accept Control\n - 6 = Service Not Active\n - 7 = Service Request Timeout\n - 8 = Unknown Failure\n - 9 = Path Not Found\n - 10 = Service Already Running\n - 11 = Service Database Locked\n - 12 = Service Dependency Deleted\n - 13 = Service Dependency Failure\n - 14 = Service Disabled\n - 15 = Service Logon Failure\n - 16 = Service Marked For Deletion\n - 17 = Service No Thread\n - 18 = Status Circular Dependency\n - 19 = Status Duplicate Name\n - 20 = Status Invalid Name\n - 21 = Status Invalid Parameter \n - 22 = Status Invalid Service Account\n - 23 = Status Service Exists\n - 24 = Service Already Paused\n" }, { "answer_id": 133918, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 5, "selected": false, "text": "net start [your service]\nif %errorlevel% == 2 echo Could not start service.\nif %errorlevel% == 0 echo Service started successfully.\necho Errorlevel: %errorlevel%\n" }, { "answer_id": 133926, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 9, "selected": true, "text": "SC start stop" }, { "answer_id": 133981, "author": "Axeman", "author_id": 22108, "author_profile": "https://Stackoverflow.com/users/22108", "pm_score": 2, "selected": false, "text": "SC" }, { "answer_id": 9030892, "author": "onionpsy", "author_id": 1173117, "author_profile": "https://Stackoverflow.com/users/1173117", "pm_score": 2, "selected": false, "text": "sc \\\\<computer> start <service>" }, { "answer_id": 20443855, "author": "vanval", "author_id": 1928410, "author_profile": "https://Stackoverflow.com/users/1928410", "pm_score": 3, "selected": false, "text": "net start \"Apache tomcat\" || goto ExitError\n\n:End \nexit 0 \n\n:ExitError \necho An error has occurred while starting the tomcat services \nexit 1 \n" }, { "answer_id": 21416584, "author": "ATSiem", "author_id": 903877, "author_profile": "https://Stackoverflow.com/users/903877", "pm_score": 3, "selected": false, "text": "sc \\\\ip.ip.ip.ip stop p4_1\n sc \\\\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance\n" }, { "answer_id": 30814270, "author": "Nathanial Wilson", "author_id": 4967539, "author_profile": "https://Stackoverflow.com/users/4967539", "pm_score": 3, "selected": false, "text": "@echo off\nset /p c= Would you like to start a service [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :1\n if /I \"%c%\" EQU \"N\" goto :2\n :1 \n set /p var= Service name: \n:2 \nset /p c= Would you like to stop a service [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :3\n if /I \"%c%\" EQU \"N\" goto :4\n :3 \n set /p var1= Service name:\n:4\nset /p c= Would you like to disable a service [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :5\n if /I \"%c%\" EQU \"N\" goto :6\n :5 \n set /p var2= Service name:\n:6 \nset /p c= Would you like to set a service to auto [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :7\n if /I \"%c%\" EQU \"N\" goto :10\n :7 \n set /p var3= Service name:\n:10\nsc start %var%\nsc stop %var1%\nsc config %var2% start=disabled\nsc config %var3% start=auto\n" }, { "answer_id": 35367669, "author": "Clinton", "author_id": 5919517, "author_profile": "https://Stackoverflow.com/users/5919517", "pm_score": 2, "selected": false, "text": "net start net stop errorlevel net stop postgresql-9.1\nif %errorlevel% == 2 echo Access Denied - Could not stop service\nif %errorlevel% == 0 echo Service stopped successfully\necho Errorlevel: %errorlevel%\n stop start" }, { "answer_id": 50250397, "author": "andrew pate", "author_id": 2668869, "author_profile": "https://Stackoverflow.com/users/2668869", "pm_score": 2, "selected": false, "text": "taskkill /pid [pid number] /f\n" }, { "answer_id": 52671741, "author": "sh87", "author_id": 6106864, "author_profile": "https://Stackoverflow.com/users/6106864", "pm_score": 0, "selected": false, "text": "reploy.bat servicename slndir binpath msbuild SET servicename=\"My Amazing Service\"\nSET slndir=\"C:dir\\that\\contains\\sln\\file\"\nSET binpath=\"C:path\\to\\service.exe\"\nSET currdir=%cd%\n\ncall net stop %servicename%\ncall sc delete %servicename%\ncd %slndir%\ncall msbuild \ncd %bindir%\ncall sc create %servicename% binpath=%binpath%\ncall net start %servicename%\ncd %currdir%\n" }, { "answer_id": 53488088, "author": "djibe", "author_id": 6375640, "author_profile": "https://Stackoverflow.com/users/6375640", "pm_score": 2, "selected": false, "text": "sc config swprv start= Auto\n" }, { "answer_id": 64701072, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 2, "selected": false, "text": "wmic service MyService call StartService\nwmic service MyService call StopService\n wmic service where \"name like '%%32Time%%' and ErrorControl='Normal'\" call StartService\n 32Time wmic service get /FORMAT:VALUE\n" }, { "answer_id": 70105303, "author": "Mick", "author_id": 342669, "author_profile": "https://Stackoverflow.com/users/342669", "pm_score": 0, "selected": false, "text": ":loop\nnet stop tomcat8 \nsc query tomcat8 | find \"STOPPED\"\nif errorlevel 1 (\n timeout 1\n goto loop\n)\n:loop2\nnet start tomcat8\nsc query tomcat8 | find \"RUNNING\"\nif errorlevel 1 (\n timeout 1\n goto loop2\n)\n" }, { "answer_id": 71428591, "author": "jlberlanga", "author_id": 17347547, "author_profile": "https://Stackoverflow.com/users/17347547", "pm_score": 0, "selected": false, "text": "@echo\ntaskkill /im service.exe /f\ntaskkill /im service.exe /f\nset \"reply=y\"\nset /p \"reply=Restart service? [y|n]: \"\nif /i not \"%reply%\" == \"y\" goto :eof\ncd \"C:\\Users\\user\\Desktop\"\nstart service.lnk\nsc start service\neof\nexit\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
[ { "answer_id": 134065, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "re.match pos = 0\nend = len(text)\nwhile pos < end:\n match = regexp.match(text, pos)\n # do something with your match\n pos = match.end()\n" }, { "answer_id": 135421, "author": "apg", "author_id": 22277, "author_profile": "https://Stackoverflow.com/users/22277", "pm_score": 2, "selected": false, "text": "x = re.compile('(?P<NUMBER>[0-9]+)|(?P<VAR>[a-z]+)')\na = x.match('9999').groupdict() # => {'VAR': None, 'NUMBER': '9999'}\nif a:\n token = [a for a in a.items() if a[1] != None][0]\n def find_token(lst):\n for tok in lst:\n if tok[1] != None: return tok\n raise Exception\n" }, { "answer_id": 4136323, "author": "dan_waterworth", "author_id": 393783, "author_profile": "https://Stackoverflow.com/users/393783", "pm_score": 4, "selected": false, "text": "import re\n\nscanner = re.Scanner([\n (r\"-?[0-9]+\\.[0-9]+([eE]-?[0-9]+)?\", lambda scanner, token: float(token)),\n (r\"-?[0-9]+\", lambda scanner, token: int(token)),\n (r\" +\", lambda scanner, token: None),\n])\n\n>>> scanner.scan(\"0 -1 4.5 7.8e3\")[0]\n[0, -1, 4.5, 7800.0]\n" }, { "answer_id": 14919449, "author": "Ray", "author_id": 976201, "author_profile": "https://Stackoverflow.com/users/976201", "pm_score": 3, "selected": false, "text": "import collections\nimport re\n\nToken = collections.namedtuple('Token', ['typ', 'value', 'line', 'column'])\n\ndef tokenize(s):\n keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'}\n token_specification = [\n ('NUMBER', r'\\d+(\\.\\d*)?'), # Integer or decimal number\n ('ASSIGN', r':='), # Assignment operator\n ('END', r';'), # Statement terminator\n ('ID', r'[A-Za-z]+'), # Identifiers\n ('OP', r'[+*\\/\\-]'), # Arithmetic operators\n ('NEWLINE', r'\\n'), # Line endings\n ('SKIP', r'[ \\t]'), # Skip over spaces and tabs\n ]\n tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)\n get_token = re.compile(tok_regex).match\n line = 1\n pos = line_start = 0\n mo = get_token(s)\n while mo is not None:\n typ = mo.lastgroup\n if typ == 'NEWLINE':\n line_start = pos\n line += 1\n elif typ != 'SKIP':\n val = mo.group(typ)\n if typ == 'ID' and val in keywords:\n typ = val\n yield Token(typ, val, line, mo.start()-line_start)\n pos = mo.end()\n mo = get_token(s, pos)\n if pos != len(s):\n raise RuntimeError('Unexpected character %r on line %d' %(s[pos], line))\n\nstatements = '''\n IF quantity THEN\n total := total + price * quantity;\n tax := price * 0.05;\n ENDIF;\n'''\n\nfor token in tokenize(statements):\n print(token)\n tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)\n (?P<ID>PATTERN) ID" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
133,887
<p>I need to create a multi-dimensional (nested) hashtable/dictionary so that I can use syntax like </p> <pre><code>val = myHash("Key").("key") </code></pre> <p>I know I need to use Generics but I can't figure out the correct syntax using VB in ASP.NET 2.0, there are plenty of c# examples on the net but they aren't helping much.</p> <p>Cheers!</p>
[ { "answer_id": 133907, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": true, "text": "Dim myHash as Dictionary(Of string, Dictionary(Of string, Integer));\n" }, { "answer_id": 141675, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "val = myHash(\"key\")(\"key\")\n val = myHash(\"key\").(\"key\")\n" }, { "answer_id": 141704, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 0, "selected": false, "text": "class Multikey {\n private keys;\n public setKey1(...)\n public setKey2(...)\n}\nDim myKey as MultiKey(...)\nmyKey.key1 = ...\nmyKey.key2 = ...\n\nDim mydic as Dictionary(Of MultiKey, Integer)\n\nval = mydic(myKey)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12226/" ]
133,897
<p>I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length.</p> <p>Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (x1,y1).</p> <p>So how do you calculate a point (x3,y3) given it needs to be at a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?</p>
[ { "answer_id": 133952, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 8, "selected": true, "text": "dx = x1-x2\ndy = y1-y2\ndist = sqrt(dx*dx + dy*dy)\ndx /= dist\ndy /= dist\nx3 = x1 + (N/2)*dy\ny3 = y1 - (N/2)*dx\nx4 = x1 - (N/2)*dy\ny4 = y1 + (N/2)*dx\n" }, { "answer_id": 133967, "author": "Giacomo Degli Esposti", "author_id": 20796, "author_profile": "https://Stackoverflow.com/users/20796", "pm_score": 3, "selected": false, "text": "vx = x2-x1\nvy = y2-y1\nlen = sqrt( vx*vx + vy*vy )\nux = -vy/len\nuy = vx/len\n\nx3 = x1 + N/2 * ux\nY3 = y1 + N/2 * uy\n\nx4 = x1 - N/2 * ux\nY4 = y1 - N/2 * uy\n" }, { "answer_id": 134073, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "in: line_length, cap_length, rotation, position of line centre\n\ndefine points:\n tl (-line_length/2, cap_length)\n tr (line_length/2, cap_length)\n bl (-line_length/2, -cap_length)\n br (line_length/2, -cap_length)\n\nrotate the four points by 'rotation'\noffset four points by 'position'\n\ndrawline (midpoint tl,bl to midpoint tr,br)\ndrawline (tl to bl)\ndrawline (tr to br)\n" }, { "answer_id": 5439737, "author": "user677616", "author_id": 677616, "author_profile": "https://Stackoverflow.com/users/677616", "pm_score": 2, "selected": false, "text": "while x21 is negative, y13 will be positive\nwhile x21 is positive, y13 will be negative\nwhile y21 is positive, x13 will be positive\nwhile y21 is negative, x13 will be negative\n x21 = x1 - x2\ny21 = y1 - y2\n x13^2 + y13^2 = |1->3|^2\nx13^2 + y13^2 = (N/2)^2\n x21*x13 + y21*y13 = 2->1 dot 1->3\nx21*x13 + y21*y13 = 0\n x21*x13 = -y21*y13\nx13 = -(y21/x21)y13\n\nx13 = -phi*y13\n plug x13 into a\nphi^2*y13^2 + y13^2 = |1->3|^2\n\n factor out y13\ny13^2 * (phi^2 + 1) = \n\n plug in phi\ny13^2 * (y21^2/x21^2 + 1) = \n\n multiply both sides by x21^2\ny13^2 * (y21^2 + x21^2) = |1->3|^2 * x21^2\n\n plug in Pythagorean theorem of 2->1\ny13^2 * |2->1|^2 = |1->3|^2 * x21^2\n\n take square root of both sides\ny13 * |2->1| = |1->3| * x21\n\n divide both sides by the length of 1->2\ny13 = (|1->3|/|2->1|) *x21\n\n lets call the ratio of 1->3 to 2->1 lengths psi\ny13 = psi * x21\n\n check the signs\n when x21 is negative, y13 will be positive\n when x21 is positive, y13 will be negative\n\ny13 = -psi * x21\n plug y13 into a\nx13^2 + x13^2/phi^2 = |1->3|^2\n\n factor out x13\nx13^2 * (1 + 1/phi^2) = \n\n plug in phi\nx13^2 * (1 + x21^2/y21^2) = \n\n multiply both sides by y21^2\nx13^2 * (y21^2 + x21^2) = |1->3|^2 * y21^2\n\n plug in Pythagorean theorem of 2->1\nx13^2 * |2->1|^2 = |1->3|^2 * y21^2\n\n take square root of both sides\nx13 * |2->1| = |1->3| * y21\n\n divide both sides by the length of 2->1\nx13 = (|1->3|/|2->1|) *y21\n\n lets call the ratio of |1->3| to |2->1| psi\nx13 = psi * y21\n\n check the signs\n when y21 is negative, x13 will be negative\n when y21 is positive, x13 will be negative\n\nx13 = psi * y21\n x21 = x1 - x2\ny21 = y1 - y2\n\n|2->1| = sqrt( x21^2 + y^21^2 )\n|1->3| = N/2\n\npsi = |1->3|/|2->1|\n\ny13 = -psi * x21\nx13 = psi * y21\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12058/" ]
133,922
<p>This is a <em>super basic</em> question but I'm trying to execute a Query that I'm building via some form values against the MS Access database the form resides in. I don't think I need to go through ADO formally, but maybe I do.</p> <p>Anyway, some help would be appreciated. Sorry for being a n00b. ;)</p>
[ { "answer_id": 134347, "author": "jinsungy", "author_id": 1316, "author_profile": "https://Stackoverflow.com/users/1316", "pm_score": 2, "selected": false, "text": "Dim rs As DAO.Recordset\nDim db As Database\n\nSet db = CurrentDb\nSet rs = db.OpenRecordset(\"SELECT * FROM Attendance WHERE ClassID = \" & ClassID)\n\ndo while not rs.EOF\n 'do stuff\n rs.movenext\nloop\n\nrs.Close\nSet rs = Nothing\n" }, { "answer_id": 135278, "author": "Tim Visher", "author_id": 16562, "author_profile": "https://Stackoverflow.com/users/16562", "pm_score": 0, "selected": false, "text": "Dim rs As DAO.Recordset\nDim db As Database\n\nSet db = CurrentDB\nSet rs = db.OpenRecordset(SQL Statement)\n\nWhile Not rs.EOF\n 'do stuff\nWend\n\nrs.Close\n" }, { "answer_id": 141512, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 0, "selected": false, "text": " Set db = CurrentDB()\n Set rs = db.OpenRecordset(\"[sql]\")\n If rs.RecordCount > 0\n rs.MoveFirst\n Do While Not rs.EOF\n rs.Edit\n rs!Field = \"New Data\"\n rs.Update\n rs.MoveNext\n Loop \n End If\n rs.Close\n Set rs = Nothing\n Set db = Nothing\n UPDATE MyTable SET Field = \"New Data\"\n CurrentDb.Execute \"UPDATE MyTable SET Field = 'New Data'\"\n" }, { "answer_id": 151405, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 0, "selected": false, "text": "Dim cn as new ADODB.Connection, rs as new ADODB.RecordSet\nDim sql as String\n\nset cn = CurrentProject.Connection\nsql = \"my dynamic sql string\"\n\nrs.Open sql, cn ', Other options for the type of recordset to open, adoOpenStatic, etc.\n\nWhile Not rs.EOF\n 'do things with recordset\n rs.MoveNext ' Can't tell you how many times I have forgotten the MoveNext. silly.\nWend\nrs.Close\ncn.Close\nSet rs = Nothing\nSet cn = Nothing\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
133,925
<p>I'm trying to direct a browser to a different page. If I wanted a GET request, I might say</p> <pre><code>document.location.href = 'http://example.com/q=a'; </code></pre> <p>But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML</p> <pre><code>&lt;form action="http://example.com/" method="POST"&gt; &lt;input type="hidden" name="q" value="a"&gt; &lt;/form&gt; </code></pre> <p>Then I would just submit the form from the DOM.</p> <p>But really I would like JavaScript code that allows me to say</p> <pre><code>post_to_url('http://example.com/', {'q':'a'}); </code></pre> <p>What's the best cross browser implementation?</p> <p><strong>Edit</strong> </p> <p>I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with <a href="http://en.wikipedia.org/wiki/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a>, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.</p>
[ { "answer_id": 133996, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 3, "selected": false, "text": "$req = new Ajax.Request(\"http://foo.com/bar.php\",{\n method: 'post',\n parameters: $H({\n name: 'Diodeus',\n question: 'JavaScript posts a request like a form request',\n ...\n }).toQueryString();\n};\n" }, { "answer_id": 133997, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 12, "selected": true, "text": "<input> /**\n * sends a request to the specified url from a form. this will change the window location.\n * @param {string} path the path to send the post request to\n * @param {object} params the parameters to add to the url\n * @param {string} [method=post] the method to use on the form\n */\n\nfunction post(path, params, method='post') {\n\n // The rest of this code assumes you are not using a library.\n // It can be made less verbose if you use one.\n const form = document.createElement('form');\n form.method = method;\n form.action = path;\n\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n const hiddenField = document.createElement('input');\n hiddenField.type = 'hidden';\n hiddenField.name = key;\n hiddenField.value = params[key];\n\n form.appendChild(hiddenField);\n }\n }\n\n document.body.appendChild(form);\n form.submit();\n}\n\n post('/contact/', {name: 'Johnny Bravo'});\n hasOwnProperty" }, { "answer_id": 134003, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "createElement document.createElement function postToURL(url, values) {\n values = values || {};\n\n var form = createElement(\"form\", {action: url,\n method: \"POST\",\n style: \"display: none\"});\n for (var property in values) {\n if (values.hasOwnProperty(property)) {\n var value = values[property];\n if (value instanceof Array) {\n for (var i = 0, l = value.length; i < l; i++) {\n form.appendChild(createElement(\"input\", {type: \"hidden\",\n name: property,\n value: value[i]}));\n }\n }\n else {\n form.appendChild(createElement(\"input\", {type: \"hidden\",\n name: property,\n value: value}));\n }\n }\n }\n document.body.appendChild(form);\n form.submit();\n document.body.removeChild(form);\n}\n" }, { "answer_id": 134033, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 6, "selected": false, "text": "document.body.innerHTML += '<form id=\"dynForm\" action=\"http://example.com/\" method=\"post\"><input type=\"hidden\" name=\"q\" value=\"a\"></form>';\ndocument.getElementById(\"dynForm\").submit();\n" }, { "answer_id": 134069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "var xmlHttpReq = false;\n\nvar self = this;\n// Mozilla/Safari\nif (window.XMLHttpRequest) {\n self.xmlHttpReq = new XMLHttpRequest();\n}\n// IE\nelse if (window.ActiveXObject) {\n self.xmlHttpReq = new ActiveXObject(\"Microsoft.XMLHTTP\");\n}\n\nself.xmlHttpReq.open(\"POST\", \"YourPageHere.asp\", true);\nself.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');\n\nself.xmlHttpReq.setRequestHeader(\"Content-length\", QueryString.length);\n\n\n\nself.xmlHttpReq.send(\"?YourQueryString=Value\");\n" }, { "answer_id": 134082, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 1, "selected": false, "text": "httpobj.open(\"POST\", url, true);\nhttpobj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');\nhttpobj.onreadystatechange=handler;\nhttpobj.send(post);\n" }, { "answer_id": 134222, "author": "Joseph Holsten", "author_id": 16981, "author_profile": "https://Stackoverflow.com/users/16981", "pm_score": 4, "selected": false, "text": "function post_to_url(url, params) {\n var form = document.createElement('form');\n form.action = url;\n form.method = 'POST';\n\n for (var i in params) {\n if (params.hasOwnProperty(i)) {\n var input = document.createElement('input');\n input.type = 'hidden';\n input.name = i;\n input.value = params[i];\n form.appendChild(input);\n }\n }\n\n form.submit();\n}\n javascript:post_to_url('http://is.gd/create.php', {'URL': location.href});\n" }, { "answer_id": 475112, "author": "Head", "author_id": 30951, "author_profile": "https://Stackoverflow.com/users/30951", "pm_score": 5, "selected": false, "text": " var form = new Element('form',\n {method: 'post', action: 'http://example.com/'});\n form.insert(new Element('input',\n {name: 'q', value: 'a', type: 'hidden'}));\n $(document.body).insert(form);\n form.submit();\n" }, { "answer_id": 3259946, "author": "Kendall Hopkins", "author_id": 188044, "author_profile": "https://Stackoverflow.com/users/188044", "pm_score": 5, "selected": false, "text": "submit post_to_url(\"http://google.com/\",{ submit: \"submit\" } ); function post_to_url(path, params, method) {\n method = method || \"post\";\n\n var form = document.createElement(\"form\");\n\n //Move the submit function to another variable\n //so that it doesn't get overwritten.\n form._submit_function_ = form.submit;\n\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n for(var key in params) {\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", params[key]);\n\n form.appendChild(hiddenField);\n }\n\n document.body.appendChild(form);\n form._submit_function_(); //Call the renamed function.\n }\n post_to_url(\"http://google.com/\", { submit: \"submit\" } ); //Works!\n" }, { "answer_id": 3764598, "author": "bburrier", "author_id": 352311, "author_profile": "https://Stackoverflow.com/users/352311", "pm_score": 4, "selected": false, "text": "function postToUrl(url, params, newWindow) {\n var form = $('<form>');\n form.attr('action', url);\n form.attr('method', 'POST');\n if(newWindow){ form.attr('target', '_blank'); \n }\n\n var addParam = function(paramName, paramValue) {\n var input = $('<input type=\"hidden\">');\n input.attr({ 'id': paramName,\n 'name': paramName,\n 'value': paramValue });\n form.append(input);\n };\n\n // Params is an Array.\n if(params instanceof Array){\n for(var i=0; i<params.length; i++) {\n addParam(i, params[i]);\n }\n }\n\n // Params is an Associative array or Object.\n if(params instanceof Object) {\n for(var key in params){\n addParam(key, params[key]);\n }\n }\n\n // Submit the form, then remove it from the page\n form.appendTo(document.body);\n form.submit();\n form.remove();\n}\n" }, { "answer_id": 5533477, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 7, "selected": false, "text": "// Post to the provided URL with the specified parameters.\nfunction post(path, parameters) {\n var form = $('<form></form>');\n\n form.attr(\"method\", \"post\");\n form.attr(\"action\", path);\n\n $.each(parameters, function(key, value) {\n var field = $('<input></input>');\n\n field.attr(\"type\", \"hidden\");\n field.attr(\"name\", key);\n field.attr(\"value\", value);\n\n form.append(field);\n });\n\n // The form needs to be a part of the document in\n // order for us to be able to submit it.\n $(document.body).append(form);\n form.submit();\n}\n" }, { "answer_id": 6152790, "author": "bobef", "author_id": 325443, "author_profile": "https://Stackoverflow.com/users/325443", "pm_score": 1, "selected": false, "text": "function post(url, params, urlEncoded, newWindow) {\n var form = $('<form />').hide();\n form.attr('action', url)\n .attr('method', 'POST')\n .attr('enctype', urlEncoded ? 'application/x-www-form-urlencoded' : 'multipart/form-data');\n if(newWindow) form.attr('target', '_blank');\n\n function addParam(name, value, parent) {\n var fullname = (parent.length > 0 ? (parent + '[' + name + ']') : name);\n if(value instanceof Object) {\n for(var i in value) {\n addParam(i, value[i], fullname);\n }\n }\n else $('<input type=\"hidden\" />').attr({name: fullname, value: value}).appendTo(form);\n };\n\n addParam('', params, '');\n\n $('body').append(form);\n form.submit();\n}\n" }, { "answer_id": 9815335, "author": "kritzikratzi", "author_id": 347508, "author_profile": "https://Stackoverflow.com/users/347508", "pm_score": 5, "selected": false, "text": "function post_to_url(path, params, method) {\n method = method || \"post\"; // Set method to post by default, if not specified.\n\n // The rest of this code assumes you are not using a library.\n // It can be made less wordy if you use one.\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n var addField = function( key, value ){\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", value );\n\n form.appendChild(hiddenField);\n }; \n\n for(var key in params) {\n if(params.hasOwnProperty(key)) {\n if( params[key] instanceof Array ){\n for(var i = 0; i < params[key].length; i++){\n addField( key, params[key][i] )\n }\n }\n else{\n addField( key, params[key] ); \n }\n }\n }\n\n document.body.appendChild(form);\n form.submit();\n}\n function post_to_url(path, params, method) {\n method = method || \"post\"; // Set method to post by default, if not specified.\n\n var form = $(document.createElement( \"form\" ))\n .attr( {\"method\": method, \"action\": path} );\n\n $.each( params, function(key,value){\n $.each( value instanceof Array? value : [value], function(i,val){\n $(document.createElement(\"input\"))\n .attr({ \"type\": \"hidden\", \"name\": key, \"value\": val })\n .appendTo( form );\n }); \n } ); \n\n form.appendTo( document.body ).submit(); \n}\n" }, { "answer_id": 15704473, "author": "Chintan Thummar", "author_id": 2049788, "author_profile": "https://Stackoverflow.com/users/2049788", "pm_score": 3, "selected": false, "text": "document.getElementById(\"form1\").submit();\n function formSubmit() {\n document.getElementById(\"frmUserList\").submit();\n} \n" }, { "answer_id": 18305156, "author": "gaby de wilde", "author_id": 2117400, "author_profile": "https://Stackoverflow.com/users/2117400", "pm_score": 5, "selected": false, "text": "<form id=\"ninja\" action=\"http://example.com/\" method=\"POST\">\n <input id=\"donaldduck\" type=\"hidden\" name=\"q\" value=\"a\">\n</form>\n function postToURL(a,b,c){\n document.getElementById(\"ninja\").action = a;\n document.getElementById(\"donaldduck\").name = b;\n document.getElementById(\"donaldduck\").value = c;\n document.getElementById(\"ninja\").submit();\n}\n postToURL(\"http://example.com/\",\"q\",\"a\");\n document.getElementById('donaldduck').value = \"a\";\ndocument.getElementById(\"ninja\").submit();\n #ninja{ \n display:none;\n}\n" }, { "answer_id": 18728068, "author": "JLavoie", "author_id": 2414919, "author_profile": "https://Stackoverflow.com/users/2414919", "pm_score": 4, "selected": false, "text": "$.ajax({\n type: \"POST\",\n url: 'http://www.myrestserver.com/api',\n data: data,\n success: success,\n dataType: dataType\n });\n" }, { "answer_id": 21392016, "author": "emragins", "author_id": 219072, "author_profile": "https://Stackoverflow.com/users/219072", "pm_score": 4, "selected": false, "text": "/**\n * Posts javascript data to a url using form.submit(). \n * Note: Handles json and arrays.\n * @param {string} path - url where the data should be sent.\n * @param {string} data - data as javascript object (JSON).\n * @param {object} options -- optional attributes\n * { \n * {string} method: get/post/put/etc,\n * {string} arrayName: name to post arraylike data. Only necessary when root data object is an array.\n * }\n * @example postToUrl('/UpdateUser', {Order {Id: 1, FirstName: 'Sally'}});\n */\nfunction postToUrl(path, data, options) {\n if (options === undefined) {\n options = {};\n }\n\n var method = options.method || \"post\"; // Set method to post by default if not specified.\n\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n function constructElements(item, parentString) {\n for (var key in item) {\n if (item.hasOwnProperty(key) && item[key] != null) {\n if (Object.prototype.toString.call(item[key]) === '[object Array]') {\n for (var i = 0; i < item[key].length; i++) {\n constructElements(item[key][i], parentString + key + \"[\" + i + \"].\");\n }\n } else if (Object.prototype.toString.call(item[key]) === '[object Object]') {\n constructElements(item[key], parentString + key + \".\");\n } else {\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", parentString + key);\n hiddenField.setAttribute(\"value\", item[key]);\n form.appendChild(hiddenField);\n }\n }\n }\n }\n\n //if the parent 'data' object is an array we need to treat it a little differently\n if (Object.prototype.toString.call(data) === '[object Array]') {\n if (options.arrayName === undefined) console.warn(\"Posting array-type to url will doubtfully work without an arrayName defined in options.\");\n //loop through each array item at the parent level\n for (var i = 0; i < data.length; i++) {\n constructElements(data[i], (options.arrayName || \"\") + \"[\" + i + \"].\");\n }\n } else {\n //otherwise treat it normally\n constructElements(data, \"\");\n }\n\n document.body.appendChild(form);\n form.submit();\n};\n" }, { "answer_id": 37171171, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 2, "selected": false, "text": "function createHiddenInput(name, value) {\n let input = document.createElement('input');\n input.setAttribute('type','hidden');\n input.setAttribute('name',name);\n input.setAttribute('value',value);\n return input;\n}\n\nfunction appendInput(form, name, value) {\n if(_.isArray(value)) {\n _.each(value, (v,i) => {\n appendInput(form, `${name}[${i}]`, v);\n });\n } else if(_.isObject(value)) {\n _.forOwn(value, (v,p) => {\n appendInput(form, `${name}[${p}]`, v);\n });\n } else {\n form.appendChild(createHiddenInput(name, value));\n }\n}\n\nfunction postToUrl(url, data) {\n let form = document.createElement('form');\n form.setAttribute('method', 'post');\n form.setAttribute('action', url);\n\n _.forOwn(data, (value, name) => {\n appendInput(form, name, value);\n });\n\n form.submit();\n}\n" }, { "answer_id": 46396723, "author": "rauprog", "author_id": 4798975, "author_profile": "https://Stackoverflow.com/users/4798975", "pm_score": 0, "selected": false, "text": " <form name=\"form1\" method=\"post\" action=\"somepage.php\">\n <input name=\"fielda\" type=\"text\" id=\"fielda\" type=\"hidden\">\n\n <textarea name=\"fieldb\" id=\"fieldb\" cols=\"\" rows=\"\" style=\"display:none\"></textarea>\n</form>\n document.getElementById('fielda').value=\"some text for field a\";\n document.getElementById('fieldb').innerHTML=\"some text for multiline fieldb\";\n form1.submit();\n fieldapost=<?php echo $_post['fielda'];>\nif (fieldapost !=\"\") {\ndocument.write(\"<form name='form1' method='post' action='previouspage.php'>\n <input name='fielda' type='text' id='fielda' type='hidden'>\n</form>\");\ndocument.getElementById('fielda').value=fieldapost;\nform1.submit();\n}\n" }, { "answer_id": 48351819, "author": "drtechno", "author_id": 6797108, "author_profile": "https://Stackoverflow.com/users/6797108", "pm_score": 1, "selected": false, "text": " <!DOCTYPE html>\n <html>\n <body>\n <form>\n First name: <input type=\"text\" name=\"fname\" value=\"Donald\"><br>\n Last name: <input type=\"text\" name=\"lname\" value=\"Duck\"><br>\n Addr1: <input type=\"text\" name=\"add\" value=\"123 Pond Dr\"><br>\n City: <input type=\"text\" name=\"city\" value=\"Duckopolis\"><br>\n </form> \n\n\n\n <button onclick=\"smc()\">Submit</button>\n\n <script>\n function smc() {\n var http = new XMLHttpRequest();\n var url = \"yourphpfile.php\";\n var x = document.forms[0];\n var xstr = \"\";\n var ta =\"\";\n var tb =\"\";\n var i;\n for (i = 0; i < x.length; i++) {\n if (i==0){ta = x.elements[i].name+\"=\"+ x.elements[i].value;}else{\n tb = tb+\"&\"+ x.elements[i].name +\"=\" + x.elements[i].value;\n } }\n\n xstr = ta+tb;\n http.open(\"POST\", url, true);\n http.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\n http.onreadystatechange = function() {\n if(http.readyState == 4 && http.status == 200) {\n\n // do whatever you want to with the html output response here\n\n } \n\n }\n http.send(xstr);\n\n }\n </script>\n\n </body>\n </html>\n" }, { "answer_id": 49141576, "author": "nikksan", "author_id": 5268653, "author_profile": "https://Stackoverflow.com/users/5268653", "pm_score": 0, "selected": false, "text": "function redirectWithPost(url, data){\n var form = document.createElement('form');\n form.method = 'POST';\n form.action = url;\n\n for(var key in data){\n var input = document.createElement('input');\n input.name = key;\n input.value = data[key];\n input.type = 'hidden';\n form.appendChild(input)\n }\n document.body.appendChild(form);\n form.submit();\n }\n" }, { "answer_id": 51236942, "author": "OG Sean", "author_id": 220325, "author_profile": "https://Stackoverflow.com/users/220325", "pm_score": 0, "selected": false, "text": "$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});\n" }, { "answer_id": 52120330, "author": "cmrichards", "author_id": 1096436, "author_profile": "https://Stackoverflow.com/users/1096436", "pm_score": 3, "selected": false, "text": "import qs from \"qs\"\n\nfunction normalPost(url, params) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"POST\");\n form.setAttribute(\"action\", url);\n\n const keyValues = qs\n .stringify(params, { arrayFormat: \"brackets\", encode: false })\n .split(\"&\")\n .map(field => field.split(\"=\"));\n\n keyValues.forEach(field => {\n var key = field[0];\n var value = field[1];\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", value);\n form.appendChild(hiddenField);\n });\n document.body.appendChild(form);\n form.submit();\n}\n normalPost(\"/people/new\", {\n people: [\n {\n name: \"Chris\",\n address: \"My address\",\n dogs: [\"Jordan\", \"Elephant Man\", \"Chicken Face\"],\n information: { age: 10, height: \"3 meters\" }\n },\n {\n name: \"Andrew\",\n address: \"Underworld\",\n dogs: [\"Doug\", \"Elf\", \"Orange\"]\n },\n {\n name: \"Julian\",\n address: \"In a hole\",\n dogs: [\"Please\", \"Help\"]\n }\n ]\n });\n {\"authenticity_token\"=>\"...\",\n \"people\"=>\n [{\"name\"=>\"Chris\", \"address\"=>\"My address\", \"dogs\"=>[\"Jordan\", \"Elephant Man\", \"Chicken Face\"], \"information\"=>{\"age\"=>\"10\", \"height\"=>\"3 meters\"}},\n {\"name\"=>\"Andrew\", \"address\"=>\"Underworld\", \"dogs\"=>[\"Doug\", \"Elf\", \"Orange\"]},\n {\"name\"=>\"Julian\", \"address\"=>\"In a hole\", \"dogs\"=>[\"Please\", \"Help\"]}]}\n" }, { "answer_id": 54666386, "author": "Canaan Etai", "author_id": 2138243, "author_profile": "https://Stackoverflow.com/users/2138243", "pm_score": 0, "selected": false, "text": "$('form').trigger('submit')\n" }, { "answer_id": 59263995, "author": "ling", "author_id": 405042, "author_profile": "https://Stackoverflow.com/users/405042", "pm_score": 0, "selected": false, "text": " /**\n * Original code found here: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js\n * I just simplified it for my own taste.\n */\n function postForm(parameters, url) {\n\n // generally we post the form with a blank action attribute\n if ('undefined' === typeof url) {\n url = '';\n }\n\n\n //----------------------------------------\n // SOME HELPER FUNCTIONS\n //----------------------------------------\n var getForm = function (url, values) {\n\n values = removeNulls(values);\n\n var form = $('<form>')\n .attr(\"method\", 'POST')\n .attr(\"action\", url);\n\n iterateValues(values, [], form, null);\n return form;\n };\n\n var removeNulls = function (values) {\n var propNames = Object.getOwnPropertyNames(values);\n for (var i = 0; i < propNames.length; i++) {\n var propName = propNames[i];\n if (values[propName] === null || values[propName] === undefined) {\n delete values[propName];\n } else if (typeof values[propName] === 'object') {\n values[propName] = removeNulls(values[propName]);\n } else if (values[propName].length < 1) {\n delete values[propName];\n }\n }\n return values;\n };\n\n var iterateValues = function (values, parent, form, isArray) {\n var i, iterateParent = [];\n Object.keys(values).forEach(function (i) {\n if (typeof values[i] === \"object\") {\n iterateParent = parent.slice();\n iterateParent.push(i);\n iterateValues(values[i], iterateParent, form, Array.isArray(values[i]));\n } else {\n form.append(getInput(i, values[i], parent, isArray));\n }\n });\n };\n\n var getInput = function (name, value, parent, array) {\n var parentString;\n if (parent.length > 0) {\n parentString = parent[0];\n var i;\n for (i = 1; i < parent.length; i += 1) {\n parentString += \"[\" + parent[i] + \"]\";\n }\n\n if (array) {\n name = parentString + \"[\" + name + \"]\";\n } else {\n name = parentString + \"[\" + name + \"]\";\n }\n }\n\n return $(\"<input>\").attr(\"type\", \"hidden\")\n .attr(\"name\", name)\n .attr(\"value\", value);\n };\n\n\n //----------------------------------------\n // NOW THE SYNOPSIS\n //----------------------------------------\n var generatedForm = getForm(url, parameters);\n\n $('body').append(generatedForm);\n generatedForm.submit();\n generatedForm.remove();\n }\n <button id=\"testButton\">Button</button>\n\n<script>\n $(document).ready(function () {\n $(\"#testButton\").click(function () {\n postForm({\n csrf_token: \"abcd\",\n rows: [\n {\n user_id: 1,\n permission_group_id: 1\n },\n {\n user_id: 1,\n permission_group_id: 2\n }\n ],\n object: {\n apple: {\n color: \"red\",\n age: \"23 days\",\n types: [\n \"golden\",\n \"opal\",\n ]\n }\n },\n the_null: null, // this will be dropped, like non-checked checkboxes are dropped\n });\n });\n });\n</script>\n\n array(3) {\n [\"csrf_token\"] => string(4) \"abcd\"\n [\"rows\"] => array(2) {\n [0] => array(2) {\n [\"user_id\"] => string(1) \"1\"\n [\"permission_group_id\"] => string(1) \"1\"\n }\n [1] => array(2) {\n [\"user_id\"] => string(1) \"1\"\n [\"permission_group_id\"] => string(1) \"2\"\n }\n }\n [\"object\"] => array(1) {\n [\"apple\"] => array(3) {\n [\"color\"] => string(3) \"red\"\n [\"age\"] => string(7) \"23 days\"\n [\"types\"] => array(2) {\n [0] => string(6) \"golden\"\n [1] => string(4) \"opal\"\n }\n }\n }\n}\n postForm({'q':'a'}, 'http://example.com/');\n" }, { "answer_id": 62396049, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "function post_to_url(url, obj) {\n let id=`form_${+new Date()}`;\n document.body.innerHTML+=`\n <form id=\"${id}\" action=\"${url}\" method=\"POST\">\n ${Object.keys(obj).map(k=>`\n <input type=\"hidden\" name=\"${k}\" value=\"${obj[k]}\">\n `)}\n </form>`\n this[id].submit(); \n}\n\n// TEST - in second param object can have more keys\nfunction jump() { post_to_url('https://example.com/', {'q':'a'}); } Open chrome>networks and push button:\n<button onclick=\"jump()\">Send POST</button>" }, { "answer_id": 74464920, "author": "Meir", "author_id": 11681480, "author_profile": "https://Stackoverflow.com/users/11681480", "pm_score": 1, "selected": false, "text": "function post(path, params) {\n const form = document.createElement('form');\n\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n const hiddenField = document.createElement('input');\n hiddenField.type = 'hidden';\n hiddenField.name = key;\n hiddenField.value = params[key];\n\n form.appendChild(hiddenField);\n }\n }\n var button = form.ownerDocument.createElement('input');\n button.type = 'submit';\n form.appendChild(button);\n\n form.onsubmit = async function (e) {\n console.log('hi');\n\n e.preventDefault();\n const form = e.currentTarget;\n\n try {\n const formData = new FormData(form);\n const response = await fetch(path, {\n method: 'POST',\n body: formData,\n });\n\n console.log(response);\n } catch (error) {\n console.error(error);\n }\n };\n\n document.body.appendChild(form);\n button.click();\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16981/" ]
133,935
<p>For example, if I have an echo statement, there's no guarantee that the browser might display it right away, might display a few dozen echo statements at once, and might wait until the entire page is done before displaying anything.</p> <p>Is there a way to have each echo appear in a browser as it is executed?</p>
[ { "answer_id": 133972, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 1, "selected": false, "text": "flush() ob_flush()" }, { "answer_id": 133994, "author": "blueyed", "author_id": 15690, "author_profile": "https://Stackoverflow.com/users/15690", "pm_score": 4, "selected": true, "text": "flush() ob_implicit_flush(true)" }, { "answer_id": 134050, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "function printnow($str, $bbreak=true){\n print \"$str\";\n if($bbreak){\n print \"<br />\";\n }\n ob_flush(); flush();\n}\n" }, { "answer_id": 136574, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 1, "selected": false, "text": "header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');\nheader('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past\nheader('Pragma: no-cache');\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
133,950
<p>What are the best/most popular ways to do aspect-oriented programming (AOP) in C#/.Net?</p>
[ { "answer_id": 134115, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 3, "selected": false, "text": "Spring.Aop" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6783/" ]
133,953
<p>I am developing, a simple SharePoint Sequential Workflow which should be bound to a document library. When associating the little workflow to a document library, I checked these options </p> <ul> <li>Allow this workflow to be manually started by an authenticated user with Edit Items Permissions. </li> <li>Start this workflow when a new item is created.</li> <li>Start this workflow when an item is changed.</li> </ul> <p>Now I upload a document to this library and the workflow starts and for instance sends a mail. It completes and everything is fine.</p> <p>When I select Edit Properties on the new Item and save a change, the workflow is fired again. Absolutely what we expected.</p> <p>Even when copying a new Item into the library with help of the Copy.asmx Webservice, the workflow starts normally.</p> <p>But <strong>now</strong> I want to update the item <strong>via the SharePoint WebService Lists.asmx</strong>.</p> <p>My <a href="http://en.wikipedia.org/wiki/Collaborative_Application_Markup_Language" rel="nofollow noreferrer">CAML</a> goes here:</p> <pre><code>&lt;Method ID='1' Cmd='Update'&gt; &lt;Field Name='ID'&gt;1&lt;/Field&gt; &lt;Field Name='myDummyPropertyField'&gt;NewValue&lt;/Field&gt; &lt;/Method&gt; </code></pre> <p>The Item is being updated (timestamp changed and a dummy property, too) but the workflow does NOT start again. </p> <p>This behaviour is reproducable on our development <strong>and</strong> test system.</p> <p>Checking the error logs (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS) I discovered a strange error message:</p> <pre><code>09/25/2008 16:51:40.17 w3wp.exe (0x1D94) 0x1D60 Windows SharePoint Services General 6875 Critical Error loading and running event receiver Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver in Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c. Additional information is below. : The object specified does not belong to a list. </code></pre> <p>Anybody who can confirm this behavior? Or any solution hints? </p> <hr> <p>I am keeping you informed of any developments on this topic. </p>
[ { "answer_id": 368475, "author": "Johannes Hädrich", "author_id": 18246, "author_profile": "https://Stackoverflow.com/users/18246", "pm_score": 5, "selected": true, "text": "<Method ID='1' Cmd='Update'>\n <Field Name='ID'>1</Field>\n <Field Name='myDummyPropertyField'>NewValue</Field>\n</Method>\n The object specified does not belong to a list.\n <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field>\n <Method ID='1' Cmd='Update'>\n <Field Name='ID'>1</Field>\n <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field>\n <Field Name='myDummyPropertyField'>NewValue</Field>\n </Method>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18246/" ]
133,956
<p>I am currently running into a problem where an element is coming back from my xml file with a single quote in it. This is causing xml_parse to break it up into multiple chunks, example: Get Wired, You're Hired! Is then enterpreted as 'Get Wired, You' being one object, the single quote being a second, and 're Hired!' as a third.</p> <p>What I want to do is:</p> <pre><code>while($data = fread($fp, 4096)){ if(!xml_parse($xml_parser, htmlentities($data,ENT_QUOTES), feof($fp))) { break; } } </code></pre> <p>But that keeps breaking. I can run a str_replace in place of htmlentities and it runs without issue, but does not want to with htmlentities.</p> <p>Any ideas?</p> <p><strong>Update:</strong> As per JimmyJ's response below, I have attempted the following solution with no luck (FYI there is a response or two above the linked post that update the code that is linked directly):</p> <pre><code>function XMLEntities($string) { $string = preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '_privateXMLEntities("$0")', $string); return $string; } function _privateXMLEntities($num) { $chars = array( 39 =&gt; '&amp;#39;', 128 =&gt; '&amp;#8364;', 130 =&gt; '&amp;#8218;', 131 =&gt; '&amp;#402;', 132 =&gt; '&amp;#8222;', 133 =&gt; '&amp;#8230;', 134 =&gt; '&amp;#8224;', 135 =&gt; '&amp;#8225;', 136 =&gt; '&amp;#710;', 137 =&gt; '&amp;#8240;', 138 =&gt; '&amp;#352;', 139 =&gt; '&amp;#8249;', 140 =&gt; '&amp;#338;', 142 =&gt; '&amp;#381;', 145 =&gt; '&amp;#8216;', 146 =&gt; '&amp;#8217;', 147 =&gt; '&amp;#8220;', 148 =&gt; '&amp;#8221;', 149 =&gt; '&amp;#8226;', 150 =&gt; '&amp;#8211;', 151 =&gt; '&amp;#8212;', 152 =&gt; '&amp;#732;', 153 =&gt; '&amp;#8482;', 154 =&gt; '&amp;#353;', 155 =&gt; '&amp;#8250;', 156 =&gt; '&amp;#339;', 158 =&gt; '&amp;#382;', 159 =&gt; '&amp;#376;'); $num = ord($num); return (($num &gt; 127 &amp;&amp; $num &lt; 160) ? $chars[$num] : "&amp;#".$num.";" ); } if(!xml_parse($xml_parser, XMLEntities($data), feof($fp))) { break; } </code></pre> <p><strong>Update:</strong> As per tom's question below, magic quotes is/was indeed turned off.</p> <p><strong>Solution:</strong> What I have ended up doing to solve the problem is the following:</p> <p>After collecting the data for each individual item/post/etc, I store that data to an array that I use later for output, then clear the local variables used during collection. I added in a step that checks if data is already present, and if it is, I concatenate it to the end, rather than overwriting it.</p> <p>So, if I end up with three chunks (as above, let's stick with 'Get Wired, You're Hired!', I will then go from doing</p> <pre><code>$x = 'Get Wired, You' $x = "'" $x = 're Hired!' </code></pre> <p>To doing:</p> <pre><code>$x = 'Get Wired, You' . "'" . 're Hired!' </code></pre> <p>This isn't the optimal solution, but appears to be working.</p>
[ { "answer_id": 368475, "author": "Johannes Hädrich", "author_id": 18246, "author_profile": "https://Stackoverflow.com/users/18246", "pm_score": 5, "selected": true, "text": "<Method ID='1' Cmd='Update'>\n <Field Name='ID'>1</Field>\n <Field Name='myDummyPropertyField'>NewValue</Field>\n</Method>\n The object specified does not belong to a list.\n <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field>\n <Method ID='1' Cmd='Update'>\n <Field Name='ID'>1</Field>\n <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field>\n <Field Name='myDummyPropertyField'>NewValue</Field>\n </Method>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22216/" ]
133,965
<p>How can I find/replace all CR/LF characters in Notepad++?</p> <p>I am looking for something equivalent to the ^p special character in Microsoft Word.</p>
[ { "answer_id": 133989, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 10, "selected": true, "text": "[\\r\\n]+ \\r\\n CRLF Normal EOL EOL EOL EOL LF \\n \\r \\r \\n \\r \\n ^ $ return;$ \\r \\n $ \\r\\n 0a Edit -> EOL Conversion -> Convert to Unix Format Edit -> EOL Conversion -> Convert to Windows Format" }, { "answer_id": 9469622, "author": "Fred Gandt", "author_id": 1832568, "author_profile": "https://Stackoverflow.com/users/1832568", "pm_score": 0, "selected": false, "text": "\\r\\n , , " }, { "answer_id": 9885173, "author": "alex", "author_id": 1294891, "author_profile": "https://Stackoverflow.com/users/1294891", "pm_score": 2, "selected": false, "text": "\\r\\n #GO# \\r\\n #GO# ICON=\"*\" ICON=.[^\"]+.> by > #GO# \\r\\n" }, { "answer_id": 58317867, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": false, "text": "\\R\n + \\R \\R+ U+000DU+000A - U+000A LINE FEED U+000B LINE TABULATION U+000C FORM FEED U+000D CARRIAGE RETURN U+0085 NEXT LINE U+2028 LINE SEPARATOR U+2029 PARAGRAPH SEPARATOR" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8754/" ]
133,973
<p>I just came across an interesting situation in JavaScript. I have a class with a method that defines several objects using object-literal notation. Inside those objects, the <code>this</code> pointer is being used. From the behavior of the program, I have deduced that the <code>this</code> pointer is referring to the class on which the method was invoked, and not the object being created by the literal. </p> <p>This seems arbitrary, though it is the way I would expect it to work. Is this defined behavior? Is it cross-browser safe? Is there any reasoning underlying why it is the way it is beyond "the spec says so" (for instance, is it a consequence of some broader design decision/philosophy)? Pared-down code example:</p> <pre><code>// inside class definition, itself an object literal, we have this function: onRender: function() { this.menuItems = this.menuItems.concat([ { text: 'Group by Module', rptletdiv: this }, { text: 'Group by Status', rptletdiv: this }]); // etc } </code></pre>
[ { "answer_id": 134062, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 3, "selected": false, "text": "this this new this this this" }, { "answer_id": 134100, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 2, "selected": false, "text": "this this" }, { "answer_id": 134149, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 10, "selected": true, "text": "class var foo = {};\nfoo.someMethod = function(){\n alert(this);\n}\n var foo = function(){\n alert(this);\n }\n foo();\n var foo = {};\nfoo.someMethod = function (){\n var that=this;\n function bar(){\n alert(that);\n }\n}\n use strict this undefined function Foo(){\n this.confusing = 'hell yeah';\n}\nvar myObject = new Foo();\n function foo(a,b){\n alert(a);\n alert(b);\n alert(this);\n}\nvar args = ['ah','be'];\nfoo.apply('omg',args);\n" }, { "answer_id": 136578, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "this null undefined window this whereAmI = \"window\";\n\nfunction foo()\n{\n return \"this is \" + this.whereAmI + \" with \" + arguments.length + \" + arguments\";\n}\n foo() foo.call(undefined) foo.apply(undefined) foo.call(window) foo.apply(window) >>> foo()\n\"this is window with 0 arguments\"\n>>> foo.call()\n\"this is window with 0 arguments\"\n call apply foo(1, 2, 3) foo.call(null, 1, 2, 3) foo.apply(null, [1, 2, 3]) >>> foo(1, 2, 3)\n\"this is window with 3 arguments\"\n>>> foo.apply(null, [1, 2, 3])\n\"this is window with 3 arguments\"\n var obj =\n{\n whereAmI: \"obj\",\n foo: foo\n};\n obj.foo() foo.call(obj) foo.apply(obj) obj >>> baz = obj.foo;\n>>> baz();\n\"this is window with 0 arguments\"\n baz baz.call(undefined) this window baz obj baz call apply function bind(func, context)\n{\n return function()\n {\n func.apply(context, arguments);\n };\n}\n bind [global scope (window)] - whereAmI, foo, obj, baz\n |\n [bind scope] - func, context\n |\n [anonymous scope]\n bind bind bind this >>> baz = bind(obj.foo, obj);\n>>> baz(1, 2);\n\"this is obj with 2 arguments\"\n" }, { "answer_id": 64113798, "author": "Qiulang", "author_id": 301513, "author_profile": "https://Stackoverflow.com/users/301513", "pm_score": 0, "selected": false, "text": "this let testThis = {\n x: 12,\n y: 20,\n add({ a, b, c }) {\n let d = a + b + c()\n console.log(d)\n },\n test() {\n //the result is NaN\n this.add({\n a: this.x,\n b: this.y,\n c: () => {\n //this here is testThis, NOT the object literal here\n return this.a + this.b \n },\n })\n },\n test2() {\n //64 as expected\n this.add({\n a: this.x,\n b: this.y,\n c: () => {\n return this.x + this.y\n },\n })\n },\n test3() {\n //NaN\n this.add({\n a: this.x,\n b: this.y,\n c: function () {\n //this here is the global object\n return this.x + this.y \n },\n })\n },\n}\n" }, { "answer_id": 72701773, "author": "Willem van der Veen", "author_id": 8059459, "author_profile": "https://Stackoverflow.com/users/8059459", "pm_score": 0, "selected": false, "text": "this this // In a constructor function this refers to newly created object\n// Every function can be a constructor function in JavaScript e.g.\nfunction Dog(color){\n this.color = color;\n}\n\n// constructor functions are invoked by putting new in front of the function call \nconst myDog = new Dog('red');\n\n// logs Dog has color red\nconsole.log('Dog has color ' + myDog.color); // Browswer example:\n\nconsole.log(this === window) // true\n\nfunction myFn(){\n console.log(this === window)\n}\n\nmyFn(); // logs true\n// The value of this depends on the context object.\n// In this case the context from where the function is called is global.\n// For the global context in the browser the context object is window.\n\nconst myObj = {fn: myFn}\n\nmyObj.fn() // logs false\n// In this case the context from where the function is called is myObj.\n// Therefore, false is logged.\n\nmyObj.fn2 = function myFn(){\n console.log(this === myObj)\n}\n\nmyObj.fn2() // logs true\n// In this case the context from where the function is called is myObj.\n// Therefore, true is logged. this" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ]
133,977
<p>In VB6, I used a call to the Windows API, <strong>GetAsyncKeyState</strong>, to determine if the user has hit the ESC key to allow them to exit out of a long running loop.</p> <pre><code>Declare Function GetAsyncKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer </code></pre> <p>Is there an equivalent in pure .NET that does require a direct call to the API?</p>
[ { "answer_id": 134009, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": true, "text": "[DllImport(\"user32.dll\")]\nstatic extern short GetAsyncKeyState(int vKey);\n" }, { "answer_id": 134179, "author": "Brian B.", "author_id": 21817, "author_profile": "https://Stackoverflow.com/users/21817", "pm_score": 1, "selected": false, "text": "bool exitLoop = false;\nfor(int i=0;i<bigNumber && !exitLoop;i++)\n{\n // Do Stuff.\n if(Console.KeyAvailable)\n {\n // Read the key and display it (false to hide it)\n ConsoleKeyInfo key = Console.ReadKey(true);\n if(ConsoleKey.Escape == key.Key)\n {\n exitLoop=false;\n }\n }\n}\n public partial class Form1 : Form\n{\n private bool exitLoop;\n public Form1()\n {\n InitializeComponent();\n this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyUp);\n }\n public void doSomething()\n {\n // reset our exit flag:\n this.exitLoop = false;\n System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(delegate(object notUsed)\n {\n while (!exitLoop)\n {\n // Do something\n }\n }));\n }\n private void Form1_KeyUp(object sender, KeyEventArgs e)\n {\n if (Keys.Escape == e.KeyCode)\n {\n e.Handled = true;\n this.exitLoop = true;\n }\n }\n\n}\n public override bool PreProcessMessage(ref Message msg)\n{\n // Handle the message or pass it to the default handler...\n base.PreProcessMessage(msg);\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
133,988
<p>I have a webapp that I am in the middle of doing some load/performance testing on, particularily on a feature where we expect a few hundred users to be accessing the same page and hitting refresh about every 10 seconds on this page. One area of improvement that we found we could make with this function was to cache the responses from the web service for some period of time, since the data is not changing.</p> <p>After implementing this basic caching, in some further testing I found out that I didn't consider how concurrent threads could access the Cache at the same time. I found that within the matter of ~100ms, about 50 threads were trying to fetch the object from the Cache, finding that it had expired, hitting the web service to fetch the data, and then putting the object back in the cache.</p> <p>The original code looked something like this:</p> <pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { final String key = &quot;Data-&quot; + email; SomeData[] data = (SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug(&quot;getSomeDataForEmail: using cached object&quot;); } return data; } </code></pre> <p>So, to make sure that only one thread was calling the web service when the object at <code>key</code> expired, I thought I needed to synchronize the Cache get/set operation, and it seemed like using the cache key would be a good candidate for an object to synchronize on (this way, calls to this method for email b@b.com would not be blocked by method calls to a@a.com).</p> <p>I updated the method to look like this:</p> <pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { SomeData[] data = null; final String key = &quot;Data-&quot; + email; synchronized(key) { data =(SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug(&quot;getSomeDataForEmail: using cached object&quot;); } } return data; } </code></pre> <p>I also added logging lines for things like &quot;before synchronization block&quot;, &quot;inside synchronization block&quot;, &quot;about to leave synchronization block&quot;, and &quot;after synchronization block&quot;, so I could determine if I was effectively synchronizing the get/set operation.</p> <p>However it doesn't seem like this has worked. My test logs have output like:</p> <pre><code>(log output is 'threadname' 'logger name' 'message') http-80-Processor253 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor253 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor253 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor253 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor263 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor263 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor263 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor263 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor131 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor131 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor131 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor131 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor104 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor104 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor252 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor283 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: inside synchronization block </code></pre> <p>I wanted to see only one thread at a time entering/exiting the synchronization block around the get/set operations.</p> <p>Is there an issue in synchronizing on String objects? I thought the cache-key would be a good choice as it is unique to the operation, and even though the <code>final String key</code> is declared within the method, I was thinking that each thread would be getting a reference to <em>the same object</em> and therefore would synchronization on this single object.</p> <p>What am I doing wrong here?</p> <p><strong>Update</strong>: after looking further at the logs, it seems like methods with the same synchronization logic where the key is always the same, such as</p> <pre><code>final String key = &quot;blah&quot;; ... synchronized(key) { ... </code></pre> <p>do not exhibit the same concurrency problem - only one thread at a time is entering the block.</p> <p><strong>Update 2</strong>: Thanks to everyone for the help! I accepted the first answer about <code>intern()</code>ing Strings, which solved my initial problem - where multiple threads were entering synchronized blocks where I thought they shouldn't, because the <code>key</code>'s had the same value.</p> <p>As others have pointed out, using <code>intern()</code> for such a purpose and synchronizing on those Strings does indeed turn out to be a bad idea - when running JMeter tests against the webapp to simulate the expected load, I saw the used heap size grow to almost 1GB in just under 20 minutes.</p> <p>Currently I'm using the simple solution of just synchronizing the entire method - but I <strong>really</strong> like the code samples provided by martinprobst and MBCook, but since I have about 7 similar <code>getData()</code> methods in this class currently (since it needs about 7 different pieces of data from a web service), I didn't want to add almost-duplicate logic about getting and releasing locks to each method. But this is definitely very, very valuable info for future usage. I think these are ultimately the correct answers on how best to make an operation like this thread-safe, and I'd give out more votes to these answers if I could!</p>
[ { "answer_id": 134014, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 7, "selected": true, "text": "final String firstkey = \"Data-\" + email;\nfinal String key = firstkey.intern();\n // do not attempt double-check locking here. I mean it.\nsynchronized(StaticObject) {\n data = StaticCache.get(key);\n while (data == IN_PROGRESS) {\n // another thread is getting the data\n StaticObject.wait();\n data = StaticCache.get(key);\n }\n if (data == null) {\n // we must get the data\n StaticCache.put(key, IN_PROGRESS, TIME_MAX_VALUE);\n }\n}\nif (data == null) {\n // we must get the data\n try {\n data = server.DoSlowThing(key);\n } finally {\n synchronized(StaticObject) {\n // WARNING: failure here is fatal, and must be allowed to terminate\n // the app or else waiters will be left forever. Choose a suitable\n // collection type in which replacing the value for a key is guaranteed.\n StaticCache.put(key, data, CURRENT_TIME);\n StaticObject.notifyAll();\n }\n }\n}\n" }, { "answer_id": 134066, "author": "Mario Ortegón", "author_id": 2309, "author_profile": "https://Stackoverflow.com/users/2309", "pm_score": 2, "selected": false, "text": " final String key = \"Data-\" + email;\n" }, { "answer_id": 134154, "author": "Martin Probst", "author_id": 22227, "author_profile": "https://Stackoverflow.com/users/22227", "pm_score": 5, "selected": false, "text": "Object data = StaticCache.get(key, ...);\nif (data == null) {\n Object lock = lockTable.get(key);\n if (lock == null) {\n // we're the only one looking for this\n lock = new Object();\n synchronized(lock) {\n lockTable.put(key, lock);\n // get stuff\n lockTable.remove(key);\n }\n } else {\n synchronized(lock) {\n // just to wait for the updater\n }\n data = StaticCache.get(key);\n }\n} else {\n // use from cache\n}\n" }, { "answer_id": 134218, "author": "MBCook", "author_id": 18189, "author_profile": "https://Stackoverflow.com/users/18189", "pm_score": 3, "selected": false, "text": "Map<String, Object> emailLocks = new HashMap<String, Object>();\n\nObject lock = null;\n\nsynchronized (emailLocks) {\n lock = emailLocks.get(emailAddress);\n\n if (lock == null) {\n lock = new Object();\n emailLocks.put(emailAddress, lock);\n }\n}\n\nsynchronized (lock) {\n // See if this email is in the cache\n // If so, serve that\n // If not, generate the data\n\n // Since each of this person's threads synchronizes on this, they won't run\n // over eachother. Since this lock is only for this person, it won't effect\n // other people. The other synchronized block (on emailLocks) is small enough\n // it shouldn't cause a performance problem.\n}\n" }, { "answer_id": 135309, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 0, "selected": false, "text": "final String key = \"Data-\" + email;\n final String key = email;\n" }, { "answer_id": 144083, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 3, "selected": false, "text": " private ConcurrentMap<String, Future<SomeData[]> cache;\n private SomeData[] getSomeDataByEmail(final WebServiceInterface service, final String email) throws Exception {\n\n final String key = \"Data-\" + email;\n Callable<SomeData[]> call = new Callable<SomeData[]>() {\n public SomeData[] call() {\n return service.getSomeDataForEmail(email);\n }\n }\n FutureTask<SomeData[]> ft; ;\n Future<SomeData[]> f = cache.putIfAbsent(key, ft= new FutureTask<SomeData[]>(call)); //atomic\n if (f == null) { //this means that the cache had no mapping for the key\n f = ft;\n ft.run();\n }\n return f.get(); //wait on the result being available if it is being calculated in another thread\n}\n" }, { "answer_id": 18389011, "author": "Thomas Bitonti", "author_id": 2647036, "author_profile": "https://Stackoverflow.com/users/2647036", "pm_score": 1, "selected": false, "text": "private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n\n\n SomeData[] data = null;\n final String key = \"Data-\" + email;\n\n synchronized(key) { \n data =(SomeData[]) StaticCache.get(key);\n\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data, CACHE_TIME);\n }\n else {\n logger.debug(\"getSomeDataForEmail: using cached object\");\n }\n }\n\n return data;\n}\n" }, { "answer_id": 39989607, "author": "celen", "author_id": 6001541, "author_profile": "https://Stackoverflow.com/users/6001541", "pm_score": -1, "selected": false, "text": "String cacheKey = ...;\n\n Object obj = cache.get(cacheKey)\n\n if(obj==null){\n synchronized (Integer.valueOf(Math.abs(cacheKey.hashCode()) % 127)){\n obj = cache.get(cacheKey)\n if(obj==null){\n //some cal obtain obj value,and put into cache\n }\n }\n}\n" }, { "answer_id": 47243259, "author": "Vadzim", "author_id": 603516, "author_profile": "https://Stackoverflow.com/users/603516", "pm_score": 4, "selected": false, "text": "private static final Map<String, Object> keyLocks = new ConcurrentHashMap<>();\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n final String key = \"Data-\" + email;\n synchronized (keyLocks.computeIfAbsent(key, k -> new Object())) {\n SomeData[] data = StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data);\n }\n }\n return data;\n}\n private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n final String key = \"Data-\" + email;\n synchronized (keyLocks.computeIfAbsent(key, k -> new Object())) {\n try {\n SomeData[] data = StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data);\n }\n } finally {\n keyLocks.remove(key); // vulnerable to race-conditions\n }\n }\n return data;\n}\n private static final LoadingCache<String, Object> keyLocks = CacheBuilder.newBuilder()\n .expireAfterAccess(10, TimeUnit.MINUTES) // max lock time ever expected\n .build(CacheLoader.from(Object::new));\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n final String key = \"Data-\" + email;\n synchronized (keyLocks.getUnchecked(key)) {\n SomeData[] data = StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data);\n }\n }\n return data;\n}\n StaticCache" }, { "answer_id": 47491816, "author": "ragnaroh", "author_id": 506678, "author_profile": "https://Stackoverflow.com/users/506678", "pm_score": 0, "selected": false, "text": "import java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Supplier;\n\npublic class KeySynchronizer<T> {\n\n private Map<T, CounterLock> locks = new ConcurrentHashMap<>();\n\n public <U> U synchronize(T key, Supplier<U> supplier) {\n CounterLock lock = locks.compute(key, (k, v) -> \n v == null ? new CounterLock() : v.increment());\n synchronized (lock) {\n try {\n return supplier.get();\n } finally {\n if (lock.decrement() == 0) {\n // Only removes if key still points to the same value,\n // to avoid issue described below.\n locks.remove(key, lock);\n }\n }\n }\n }\n\n private static final class CounterLock {\n\n private AtomicInteger remaining = new AtomicInteger(1);\n\n private CounterLock increment() {\n // Returning a new CounterLock object if remaining = 0 to ensure that\n // the lock is not removed in step 5 of the following execution sequence:\n // 1) Thread 1 obtains a new CounterLock object from locks.compute (after evaluating \"v == null\" to true)\n // 2) Thread 2 evaluates \"v == null\" to false in locks.compute\n // 3) Thread 1 calls lock.decrement() which sets remaining = 0\n // 4) Thread 2 calls v.increment() in locks.compute\n // 5) Thread 1 calls locks.remove(key, lock)\n return remaining.getAndIncrement() == 0 ? new CounterLock() : this;\n }\n\n private int decrement() {\n return remaining.decrementAndGet();\n }\n }\n}\n private KeySynchronizer<String> keySynchronizer = new KeySynchronizer<>();\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n String key = \"Data-\" + email;\n return keySynchronizer.synchronize(key, () -> {\n SomeData[] existing = (SomeData[]) StaticCache.get(key);\n if (existing == null) {\n SomeData[] data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data, CACHE_TIME);\n return data;\n }\n logger.debug(\"getSomeDataForEmail: using cached object\");\n return existing;\n });\n}\n public void synchronize(T key, Runnable runnable) {\n CounterLock lock = locks.compute(key, (k, v) -> \n v == null ? new CounterLock() : v.increment());\n synchronized (lock) {\n try {\n runnable.run();\n } finally {\n if (lock.decrement() == 0) {\n // Only removes if key still points to the same value,\n // to avoid issue described below.\n locks.remove(key, lock);\n }\n }\n }\n}\n" }, { "answer_id": 50298278, "author": "igor.zh", "author_id": 2366397, "author_profile": "https://Stackoverflow.com/users/2366397", "pm_score": 2, "selected": false, "text": "public class ValueLock<T> {\n\n private Lock lock = new ReentrantLock();\n private Map<T, Condition> conditions = new HashMap<T, Condition>();\n\n public void lock(T t){\n lock.lock();\n try {\n while (conditions.containsKey(t)){\n conditions.get(t).awaitUninterruptibly();\n }\n conditions.put(t, lock.newCondition());\n } finally {\n lock.unlock();\n }\n }\n\n public void unlock(T t){\n lock.lock();\n try {\n Condition condition = conditions.get(t);\n if (condition == null)\n throw new IllegalStateException();// possibly an attempt to release what wasn't acquired\n conditions.remove(t);\n condition.signalAll();\n } finally {\n lock.unlock();\n }\n }\n lock Condition unlock Condition Map lock() ReentrantLock.lock() lock() unlock() ValueLock<String> lock = new ValueLock<String>();\n // ... share the lock \n String email = \"...\";\n try {\n lock.lock(email);\n //... \n } finally {\n lock.unlock(email);\n }\n" }, { "answer_id": 50549906, "author": "AlikElzin-kilaka", "author_id": 435605, "author_profile": "https://Stackoverflow.com/users/435605", "pm_score": 0, "selected": false, "text": "public class DynamicKeyLock<T> implements Lock\n{\n private final static ConcurrentHashMap<Object, LockAndCounter> locksMap = new ConcurrentHashMap<>();\n\n private final T key;\n\n public DynamicKeyLock(T lockKey)\n {\n this.key = lockKey;\n }\n\n private static class LockAndCounter\n {\n private final Lock lock = new ReentrantLock();\n private final AtomicInteger counter = new AtomicInteger(0);\n }\n\n private LockAndCounter getLock()\n {\n return locksMap.compute(key, (key, lockAndCounterInner) ->\n {\n if (lockAndCounterInner == null) {\n lockAndCounterInner = new LockAndCounter();\n }\n lockAndCounterInner.counter.incrementAndGet();\n return lockAndCounterInner;\n });\n }\n\n private void cleanupLock(LockAndCounter lockAndCounterOuter)\n {\n if (lockAndCounterOuter.counter.decrementAndGet() == 0)\n {\n locksMap.compute(key, (key, lockAndCounterInner) ->\n {\n if (lockAndCounterInner == null || lockAndCounterInner.counter.get() == 0) {\n return null;\n }\n return lockAndCounterInner;\n });\n }\n }\n\n @Override\n public void lock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n lockAndCounter.lock.lock();\n }\n\n @Override\n public void unlock()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n lockAndCounter.lock.unlock();\n\n cleanupLock(lockAndCounter);\n }\n\n\n @Override\n public void lockInterruptibly() throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n try\n {\n lockAndCounter.lock.lockInterruptibly();\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n }\n\n @Override\n public boolean tryLock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired = lockAndCounter.lock.tryLock();\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public boolean tryLock(long time, TimeUnit unit) throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired;\n try\n {\n acquired = lockAndCounter.lock.tryLock(time, unit);\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public Condition newCondition()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n\n return lockAndCounter.lock.newCondition();\n }\n}\n public DynamicKeyLock(T lockKey) {\n this.key = lockKey;\n }\n\n private static class LockAndCounter {\n private final Lock lock = new ReentrantLock();\n private final AtomicInteger counter = new AtomicInteger(0);\n }\n\n private LockAndCounter getLock()\n {\n while (true) // Try to init lock\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n\n if (lockAndCounter == null)\n {\n LockAndCounter newLock = new LockAndCounter();\n lockAndCounter = locksMap.putIfAbsent(key, newLock);\n\n if (lockAndCounter == null)\n {\n lockAndCounter = newLock;\n }\n }\n\n lockAndCounter.counter.incrementAndGet();\n\n synchronized (lockAndCounter)\n {\n LockAndCounter lastLockAndCounter = locksMap.get(key);\n if (lockAndCounter == lastLockAndCounter)\n {\n return lockAndCounter;\n }\n // else some other thread beat us to it, thus try again.\n }\n }\n }\n\n private void cleanupLock(LockAndCounter lockAndCounter)\n {\n if (lockAndCounter.counter.decrementAndGet() == 0)\n {\n synchronized (lockAndCounter)\n {\n if (lockAndCounter.counter.get() == 0)\n {\n locksMap.remove(key);\n }\n }\n }\n }\n\n @Override\n public void lock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n lockAndCounter.lock.lock();\n }\n\n @Override\n public void unlock()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n lockAndCounter.lock.unlock();\n\n cleanupLock(lockAndCounter);\n }\n\n\n @Override\n public void lockInterruptibly() throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n try\n {\n lockAndCounter.lock.lockInterruptibly();\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n }\n\n @Override\n public boolean tryLock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired = lockAndCounter.lock.tryLock();\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public boolean tryLock(long time, TimeUnit unit) throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired;\n try\n {\n acquired = lockAndCounter.lock.tryLock(time, unit);\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public Condition newCondition()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n\n return lockAndCounter.lock.newCondition();\n }\n}\n public class DynamicKeyLockTest\n{\n @Test\n public void testDifferentKeysDontLock() throws InterruptedException\n {\n DynamicKeyLock<Object> lock = new DynamicKeyLock<>(new Object());\n lock.lock();\n AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);\n try\n {\n new Thread(() ->\n {\n DynamicKeyLock<Object> anotherLock = new DynamicKeyLock<>(new Object());\n anotherLock.lock();\n try\n {\n anotherThreadWasExecuted.set(true);\n }\n finally\n {\n anotherLock.unlock();\n }\n }).start();\n Thread.sleep(100);\n }\n finally\n {\n Assert.assertTrue(anotherThreadWasExecuted.get());\n lock.unlock();\n }\n }\n\n @Test\n public void testSameKeysLock() throws InterruptedException\n {\n Object key = new Object();\n DynamicKeyLock<Object> lock = new DynamicKeyLock<>(key);\n lock.lock();\n AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);\n try\n {\n new Thread(() ->\n {\n DynamicKeyLock<Object> anotherLock = new DynamicKeyLock<>(key);\n anotherLock.lock();\n try\n {\n anotherThreadWasExecuted.set(true);\n }\n finally\n {\n anotherLock.unlock();\n }\n }).start();\n Thread.sleep(100);\n }\n finally\n {\n Assert.assertFalse(anotherThreadWasExecuted.get());\n lock.unlock();\n }\n }\n}\n" }, { "answer_id": 55029752, "author": "val", "author_id": 3071391, "author_profile": "https://Stackoverflow.com/users/3071391", "pm_score": -1, "selected": false, "text": " @Service \n public class MySyncService{\n\n public Map<String, String> lockMap=new HashMap<String, String>();\n\n public void syncMethod(String email) {\n\n String lock = lockMap.get(email);\n if(lock==null) {\n lock = UUID.randomUUID().toString();\n lockMap.put(email, lock);\n } \n\n synchronized(lock.intern()) {\n //do your sync code here\n }\n }\n" }, { "answer_id": 56694923, "author": "Matej Tymes", "author_id": 720163, "author_profile": "https://Stackoverflow.com/users/720163", "pm_score": 0, "selected": false, "text": "private Synchronizer<String> synchronizer = new Synchronizer();\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n String key = \"Data-\" + email;\n\n return synchronizer.synchronizeOn(key, () -> {\n\n SomeData[] data = (SomeData[]) StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data, CACHE_TIME);\n } else {\n logger.debug(\"getSomeDataForEmail: using cached object\");\n }\n return data;\n\n });\n}\n compile 'com.github.matejtymes:javafixes:1.3.0'\n" }, { "answer_id": 64239564, "author": "pveentjer", "author_id": 2245707, "author_profile": "https://Stackoverflow.com/users/2245707", "pm_score": 0, "selected": false, "text": "static final Object[] locks = newLockArray();\n\nObject lock = locks[hashToIndex(key.hashcode(),locks.length];\nsynchronized(lock){\n ....\n}\n\nint hashToIndex(int hash, int length) {\n if (hash == Integer.MIN_VALUE return 0;\n return abs(hash) % length;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
133,993
<p>We have a web application that can be deployed on many application servers, including Oracle 10g. On that platform, however, we are having classpath issues. The webapp uses JAXB 2, but Oracle 10g ships with JAXB 1, and this was causing errors. To get around those we configured Oracle to prefer classes in our webapp, but now we are getting the above error when attempting to instantiate a JAXB context.</p> <p>Looking up the "loader constraints violated" exception - it seems to be thrown when a class that has been loaded with one classloader attempts to access something that is package private in the same package but loaded by a different classloader. I have tried removing any jars in our webapp that include javax.xml.namespace.QName, and have verified that it is the instance included in Oracle that is being picked up, but the error still occurs. Any ideas?</p> <p>(This is a follow-on from an <a href="https://stackoverflow.com/questions/132409/jaxb-2-in-an-oracle-10g-webapp">earlier question</a> regarding 10g and JAXB 2.)</p>
[ { "answer_id": 226609, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "lib" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998/" ]
133,999
<p>What assemblies are loaded by default when you create a new ASP.NET 2.0 Web Application Project ?</p>
[ { "answer_id": 226609, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "lib" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/133999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13337/" ]
134,001
<p>I need to be able to load the entire contents of a text file and load it into a variable for further processing. </p> <p>How can I do that?</p> <hr> <p>Here's what I did thanks to Roman Odaisky's answer.</p> <pre><code>SetLocal EnableDelayedExpansion set content= for /F "delims=" %%i in (test.txt) do set content=!content! %%i echo %content% EndLocal </code></pre>
[ { "answer_id": 134135, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": 5, "selected": true, "text": "for set content=\nfor /f \"delims=\" %%i in ('filename') do set content=%content% %%i\n setlocal enabledelayedexpansion !content! %content%" }, { "answer_id": 134195, "author": "pdavis", "author_id": 7819, "author_profile": "https://Stackoverflow.com/users/7819", "pm_score": 0, "selected": false, "text": "set FileContents=\n @echo off\n copy SetFile.bat + %1 $tmp$.bat > nul\n call $tmp$.bat\n del $tmp$.bat\n" }, { "answer_id": 134290, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "%i %%i for /f \"tokens=1 delims=\" %%i in (file.txt) do echo %%i\n for /f \"tokens=1 delims=\" %%i in (file.txt) do call :part2 %%i\ngoto :fin\n\n:part2\necho %1\n::do further processing here\ngoto :eof\n\n:fin\n" }, { "answer_id": 134341, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": 2, "selected": false, "text": "set content=\nfor /f \"delims=\" %%i in ('type text.txt') do set content=!content! %%i\n" }, { "answer_id": 14634551, "author": "Will Bickford", "author_id": 43012, "author_profile": "https://Stackoverflow.com/users/43012", "pm_score": 6, "selected": false, "text": "set /p set /p VAR1=<test.txt\nset /? |find \"/P\"\n" }, { "answer_id": 25122300, "author": "clichok", "author_id": 2396663, "author_profile": "https://Stackoverflow.com/users/2396663", "pm_score": 0, "selected": false, "text": "for /f \"delims=\" %%i in (count.txt) do set c=%%i\necho %c%\npause\n" }, { "answer_id": 66714820, "author": "Erik Erikson", "author_id": 4825613, "author_profile": "https://Stackoverflow.com/users/4825613", "pm_score": 2, "selected": false, "text": "@echo OFF\nSETLOCAL EnableDelayedExpansion\nset N=^\n\n\nREM These two empty lines are required\nset CONTENT=\nset FILE=<...>\nfor /f \"delims=\" %%x in ('type %FILE%') do set \"CONTENT=!CONTENT!%%x!N!\"\necho !CONTENT!\n\nENDLOCAL\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
134,018
<p>I'm trying to create with Delphi a component inherited from TLabel, with some custom graphics added to it on TLabel.Paint. I want the graphics to be on left side of text, so I overrode GetClientRect:</p> <pre><code>function TMyComponent.GetClientRect: TRect; begin result := inherited GetClientRect; result.Left := 20; end; </code></pre> <p>This solution has major problem I'd like to solve: It's not possible to click on the "graphics area" of the control, only label area. If the caption is empty string, it's not possible to select the component in designer by clicking it at all. Any ideas?</p>
[ { "answer_id": 134306, "author": "Germán Estévez -Neftalí-", "author_id": 17487, "author_profile": "https://Stackoverflow.com/users/17487", "pm_score": 3, "selected": true, "text": "procedure TGrlabel.DoDrawText(var Rect: TRect; Flags: Integer);\nbegin\n Rect.Left := 20;\n inherited;\nend;\n\nprocedure TGrlabel.Paint;\nbegin\n inherited;\n\n Canvas.Brush.Color := clRed;\n Canvas.Pen.Color := clRed;\n Canvas.pen.Width := 3;\n Canvas.MoveTo(5,5);\n Canvas.LineTo(15,8);\n\nend;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7735/" ]
134,029
<p>A quick Google search of this issue shows it's common, I just can't for the life of me figure out the solution in my case.</p> <p>I have a straight forward install of wxWidgets 2.8.8 for Windows straight from the wxWidgets website.</p> <p>Whenever I try to compile anything (such as the sample app described in "First Programs for wxWidgets" - <a href="http://zetcode.com/tutorials/wxwidgetstutorial/firstprograms/" rel="noreferrer">http://zetcode.com/tutorials/wxwidgetstutorial/firstprograms/</a> ) I get:</p> <p>wx/setup.h: No such file or directory</p> <p>I've included both C:\wxWidgets-2.8.8\include and C:\wxWidgets-2.8.8\include\wx in my compiler search list.</p> <p>It should be simple - but it's not! :(</p> <p>The same thing happens if I try to use an IDE integrated with wxWidgets (such as Code::Blocks) - and this, I would have thought, would have just worked out the box...</p> <p>So, some help please... Why is setup.h not found?</p>
[ { "answer_id": 209172, "author": "kbluck", "author_id": 13402, "author_profile": "https://Stackoverflow.com/users/13402", "pm_score": 6, "selected": true, "text": "nmake -f makefile.vc BUILD=debug nmake -f makefile.vc BUILD=release" }, { "answer_id": 7640751, "author": "Roger Dahl", "author_id": 442006, "author_profile": "https://Stackoverflow.com/users/442006", "pm_score": 3, "selected": false, "text": "c:\\wxWidgets-2.9.2\\lib\\vc_lib\\mswu\n c:\\wxWidgets-2.9.2\\include\n c:\\wxWidgets-2.9.2\\lib\\vc_lib\n wxbase29ud.lib\n #include \"wx/setup.h\"\n #include <wx/slider.h>\n#include <wx/image.h>\n#include <wx/control.h>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
134,034
<p>I have a custom login component in Flex that is a simple form that dispatches a custom LoginEvent when a user click the login button:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?> &lt;mx:Form xmlns:mx="http://www.adobe.com/2006/mxml" defaultButton="{btnLogin}"> &lt;mx:Metadata> [Event(name="login",tpye="events.LoginEvent")] &lt;/mx:Metadata> &lt;mx:Script> import events.LoginEvent; private function _loginEventTrigger():void { var t:LoginEvent = new LoginEvent( LoginEvent.LOGIN, txtUsername.text, txtPassword.text); dispatchEvent(t); } &lt;/mx:Script> &lt;mx:FormItem label="username:"> &lt;mx:TextInput id="txtUsername" color="black" /> &lt;/mx:FormItem> &lt;mx:FormItem label="password:"> &lt;mx:TextInput id="txtPassword" displayAsPassword="true" /> &lt;/mx:FormItem> &lt;mx:FormItem> &lt;mx:Button id="btnLogin" label="login" cornerRadius="0" click="_loginEventTrigger()" /> &lt;/mx:FormItem> &lt;/mx:Form> </code></pre> <p>I then have a main.mxml file that contains the flex application, I add my component to the application without any problem:</p> <pre><code> &lt;custom:login_form id="cLogin" /> </code> </pre> <p>I then try to wire up my event in actionscript:</p> <pre> <code> import events.LoginEvent; cLogin.addEventListener(LoginEvent.LOGIN,_handler); private function _handler(event:LoginEvent):void { mx.controls.Alert.show("logging in..."); } </code> </pre> <p>Everything looks good to me, but when I compile I get an "error of undefined property cLogin...clearly I have my control with the id "cLogin" but I can't seem to get a"handle to it"...what am I doing wrong?</p> <p>Thanks.</p>
[ { "answer_id": 134802, "author": "JustLogic", "author_id": 21664, "author_profile": "https://Stackoverflow.com/users/21664", "pm_score": 0, "selected": false, "text": "<custom:login_form id='cLogin' login='_handler' />\n" }, { "answer_id": 237949, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<custom:login_form id='cLogin' login='_handler' />\n <mx:Metadata>\n [Event(name=\"login\", type=\"events.LoginEvent\")]\n</mx:Metadata>\n login='_handler' cLogin.addEventListener(LoginEvent.LOGIN,_handler);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
134,049
<p>Earlier this week I ask a question about filtering out duplicate values in sequence at run time. Had some good answers but the amount of data I was going over was to slow and not feasible.</p> <p>Currently in our database, event values are not filtered. Resulting in duplicate data values (with varying timestamps). We need to process that data at run time and at the database level it’s to time costly ( and cannot pull it into code because it’s used a lot in stored procs) resulting in high query times. We need a data structure that we can query that has this data store filtered out so that no additional filtering is needed at runtime. </p> <p><strong>Currently in our DB</strong> </p> <ul> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-08 04:03:47.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-08 10:02:08.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-09 10:03:24.000’ (Need to delete this) **</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-10 04:05:05.000'</li> </ul> <p><strong>What we need</strong></p> <ul> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-08 04:03:47.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-08 10:02:08.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-10 04:51:05.000'</li> </ul> <p>This seems trivial, but our issue is that we get this data from wireless devices, resulting in out of sequence packets and our gateway is multithreaded so we cannot guarantee the values we get are in order. Something may come in like a '1' for 4 seconds ago and a '0' for 2 seconds ago, but we process the '1' already because it was first in. we have been spinning our heads on how to implement this. We cannot compare data to the latest value in the database because the latest may actually not have come in yet, so to throw that data out we'd be screwed and our sequence may be completely off. So currently we store every value that comes in and the database shuffles itself around based off of time.. but the units can send 1,1,1,0 and its valid because the event is still active, but we only want to store the on and off state ( first occurrence of the on state 1,0,1,0,1,0).. we thought about a trigger, but we'd have to shuffle the data around every time a new value came in because it might be earlier then the last message and it can change the entire sequence (inserts would be slow). </p> <p>Any Ideas?</p> <p>Ask if you need any further information.</p> <p>[EDIT] PK Wont work - the issue is that our units actually send in different timestamps. so the PK wouldn't work because 1,1,1 are the same.. but there have different time stamps. Its like event went on at time1, event still on at time2, it sends us back both.. same value different time.</p>
[ { "answer_id": 135031, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": true, "text": "DECLARE @MyTable TABLE\n(\n DeviceName varchar(100),\n EventTime DateTime,\n OnOff int,\n GoodForRead int\n)\n\nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 1, '2008-05-08 04:03:47.000' \nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 0, '2008-05-08 10:02:08.000' \nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 0, '2008-05-09 10:03:24.000'\nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 1, '2008-05-10 04:05:05.000' \n\nUPDATE mt\nSET GoodForRead = \nCASE\n (SELECT top 1 OnOff\n FROM @MyTable mt2\n WHERE mt2.DeviceName = mt.DeviceName\n and mt2.EventTime < mt.EventTime\n ORDER BY mt2.EventTime desc\n )\n WHEN null THEN 1\n WHEN mt.OnOff THEN 0\n ELSE 1\nEND\nFROM @MyTable mt\n -- Limit the update to recent data\n--WHERE EventTime >= DateAdd(dd, -1, GetDate())\n\nSELECT *\nFROM @MyTable\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20737/" ]
134,063
<p>Why are 'out' parameters in .NET a bad idea?</p> <p>I was recently asked this, but I had no real answer besides it's simply unnecessarily complicating an application. What other reasons are there?</p>
[ { "answer_id": 134076, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 1, "selected": false, "text": "out" }, { "answer_id": 134084, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 7, "selected": true, "text": "Dictionary<K, V> TryGetValue out" }, { "answer_id": 134096, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "SortedDictionart.TryGetValue int value;\nsome_function (out value);\n some_function" }, { "answer_id": 134116, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "DateTime NewDate = new DateTime();\nif (DateTime.TryParse(UserInput, out NewDate) == false) {\n NewDate = DateTime.Now;\n}\n" }, { "answer_id": 134130, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 2, "selected": false, "text": "bool TryGetSomeValue(out SomeValue value, [...]);\n void CreateNullProjectionMatrix(out Matrix matrix);\n" }, { "answer_id": 134677, "author": "Mohamed Faramawi", "author_id": 20006, "author_profile": "https://Stackoverflow.com/users/20006", "pm_score": 2, "selected": false, "text": "Int.TryParse(\"1\",out myInt) try/catch out" }, { "answer_id": 134799, "author": "Jonas", "author_id": 10833, "author_profile": "https://Stackoverflow.com/users/10833", "pm_score": 1, "selected": false, "text": "out" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
134,064
<p>I am adding a service reference to one of my projects in Visual Studio 2008. On the "Service Reference Settings" screen I am selecting the default option which says "Reuse types in all referenced assemblies". I have referenced the project for which I want to reuse a type. That type is being passed in as a parameter to a web method.</p> <p>However, when the References.cs file is generated, it still creates a duplicate proxy version of that type. Is there something I am missing? Do you need to do anything special to the referenced type? Perhaps add some special attributes? </p>
[ { "answer_id": 300000, "author": "Rich Reuter", "author_id": 283, "author_profile": "https://Stackoverflow.com/users/283", "pm_score": 3, "selected": false, "text": "[assembly: ContractNamespace(\"YOUR_NAMESPACE_HERE\")]\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436/" ]
134,068
<p>I'm trying to achieve the equivalent of a WinForms <code>ListView</code> with its <code>View</code> property set to <code>View.List</code>. Visually, the following works fine. The file names in my <code>Listbox</code> go from top to bottom, and then wrap to a new column.</p> <p>Here's the basic XAML I'm working with:</p> <pre><code>&lt;ListBox Name="thelist" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Disabled"&gt; &lt;ListBox.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;WrapPanel IsItemsHost="True" Orientation="Vertical" /&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.ItemsPanel&gt; &lt;/ListBox&gt; </code></pre> <p>However, default arrow key navigation does not wrap. If the last item in a column is selected, pressing the down arrow does not go to the first item of the next column.</p> <p>I tried handling the <code>KeyDown</code> event like this:</p> <pre><code>private void thelist_KeyDown( object sender, KeyEventArgs e ) { if ( object.ReferenceEquals( sender, thelist ) ) { if ( e.Key == Key.Down ) { e.Handled = true; thelist.Items.MoveCurrentToNext(); } if ( e.Key == Key.Up ) { e.Handled = true; thelist.Items.MoveCurrentToPrevious(); } } } </code></pre> <p>This produces the last-in-column to first-in-next-column behavior that I wanted, but also produces an oddity in the left and right arrow handling. Any time it wraps from one column to the next/previous using the up/down arrows, a single subsequent use of the left or right arrow key moves the selection to the left or right of the item that was selected just before the wrap occured.</p> <p>Assume the list is filled with strings "0001" through "0100" with 10 strings per column. If I use the down arrow key to go from "0010" to "0011", then press the right arrow key, selection moves to "0020", just to the right of "0010". If "0011" is selected and I use the up arrow key to move selection to "0010", then a press of the right arrow keys moves selection to "0021" (to the right of "0011", and a press of the left arrow key moves selection to "0001".</p> <p>Any help achieving the desired column-wrap layout and arrow key navigation would be appreciated.</p> <p>(Edits moved to my own answer, since it technically is an answer.)</p>
[ { "answer_id": 135908, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 4, "selected": true, "text": "KeyDown KeyDown Items ListBoxItem ListBoxItem Focus() MoveCurrentToLast() MoveCurrentToFirst() private void thelist_KeyDown( object sender, KeyEventArgs e ) {\n if ( object.ReferenceEquals( sender, thelist ) ) {\n if ( thelist.Items.Count > 0 ) {\n switch ( e.Key ) {\n case Key.Down:\n if ( !thelist.Items.MoveCurrentToNext() ) {\n thelist.Items.MoveCurrentToLast();\n }\n break;\n\n case Key.Up:\n if ( !thelist.Items.MoveCurrentToPrevious() ) {\n thelist.Items.MoveCurrentToFirst();\n }\n break;\n\n default:\n return;\n }\n\n e.Handled = true;\n ListBoxItem lbi = (ListBoxItem) thelist.ItemContainerGenerator.ContainerFromItem( thelist.SelectedItem );\n lbi.Focus();\n }\n }\n}\n" }, { "answer_id": 269029, "author": "Bryan Anderson", "author_id": 21186, "author_profile": "https://Stackoverflow.com/users/21186", "pm_score": 3, "selected": false, "text": "<ListBox Name=\"thelist\"\n IsSynchronizedWithCurrentItem=\"True\"\n ItemsSource=\"{Binding}\"\n ScrollViewer.VerticalScrollBarVisibility=\"Disabled\"\n KeyboardNavigation.DirectionalNavigation=\"Cycle\">\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22211/" ]
134,086
<p>I wrote C++ for 10 years. I encountered memory problems, but they could be fixed with a reasonable amount of effort.</p> <p>For the last couple of years I've been writing C#. I find I still get lots of memory problems. They're difficult to diagnose and fix due to the non-determinancy, and because the C# philosophy is that you shouldn't have to worry about such things when you very definitely do.</p> <p>One particular problem I find is that I have to explicitly dispose and cleanup everything in code. If I don't, then the memory profilers don't really help because there is so much chaff floating about you can't find a leak within all the data they're trying to show you. I wonder if I've got the wrong idea, or if the tool I've got isn't the best.</p> <p>What kind of strategies and tools are useful for tackling memory leaks in .NET?</p>
[ { "answer_id": 134141, "author": "Mark", "author_id": 5904, "author_profile": "https://Stackoverflow.com/users/5904", "pm_score": 4, "selected": false, "text": "class ParentObject\n Private mRelatedObject as New CRelatedObject\n public Readonly property RelatedObject() as CRelatedObject\n get\n mRelatedObject.getWithID(RelatedObjectID)\n return mRelatedObject\n end get\n end property\nEnd class\n class ParentObject\n Private mRelatedObject as CRelatedObject\n Public ReadOnly Property RelatedObject() as CRelatedObject\n Get\n If mRelatedObject is Nothing\n mRelatedObject = New CRelatedObject\n End If\n If mRelatedObject.isEmptyObject\n mRelatedObject.getWithID(RelatedObjectID)\n End If\n return mRelatedObject\n end get\n end Property\nend class\n" }, { "answer_id": 134361, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 5, "selected": false, "text": " public void Dispose ()\n {\n // Dispose logic here ...\n\n // It's a bad error if someone forgets to call Dispose,\n // so in Debug builds, we put a finalizer in to detect\n // the error. If Dispose is called, we suppress the\n // finalizer.\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n }\n\n#if DEBUG\n ~TimedLock()\n {\n // If this finalizer runs, someone somewhere failed to\n // call Dispose, which means we've failed to leave\n // a monitor!\n System.Diagnostics.Debug.Fail(\"Undisposed lock\");\n }\n#endif\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898/" ]
134,099
<p>Let's say I have code like this:</p> <pre><code>$dbh = new PDO("blahblah"); $stmt = $dbh-&gt;prepare('SELECT * FROM users where username = :username'); $stmt-&gt;execute( array(':username' =&gt; $_REQUEST['username']) ); </code></pre> <p>The PDO documentation says:</p> <blockquote> <p>The parameters to prepared statements don't need to be quoted; the driver handles it for you.</p> </blockquote> <p><strong>Is that truly all I need to do to avoid SQL injections? Is it really that easy?</strong></p> <p>You can assume MySQL if it makes a difference. Also, I'm really only curious about the use of prepared statements against SQL injection. In this context, I don't care about XSS or other possible vulnerabilities.</p>
[ { "answer_id": 134138, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 9, "selected": false, "text": "' ' + (SELECT UserName + '_' + Password FROM Users LIMIT 1) + '\n" }, { "answer_id": 2681487, "author": "Tower", "author_id": 283055, "author_profile": "https://Stackoverflow.com/users/283055", "pm_score": 6, "selected": false, "text": "$dbh = new PDO(\"blahblah\");\n\n$tableToUse = $_GET['userTable'];\n\n$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');\n$stmt->execute( array(':username' => $_REQUEST['username']) );\n $dbh = new PDO(\"blahblah\");\n\n$tableToUse = $_GET['userTable'];\n$allowedTables = array('users','admins','moderators');\nif (!in_array($tableToUse,$allowedTables)) \n $tableToUse = 'users';\n\n$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');\n$stmt->execute( array(':username' => $_REQUEST['username']) );\n $stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');\n DESC ASC ' DESC ASC" }, { "answer_id": 12201912, "author": "PeeHaa", "author_id": 508666, "author_profile": "https://Stackoverflow.com/users/508666", "pm_score": 5, "selected": false, "text": "$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n $dbh = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');\n htmlspecialchars()" }, { "answer_id": 12202218, "author": "ircmaxell", "author_id": 338665, "author_profile": "https://Stackoverflow.com/users/338665", "pm_score": 11, "selected": true, "text": "$pdo->query('SET NAMES gbk');\n$var = \"\\xbf\\x27 OR 1=1 /*\";\n$query = 'SELECT * FROM test WHERE name = ? LIMIT 1';\n$stmt = $pdo->prepare($query);\n$stmt->execute(array($var));\n $pdo->query('SET NAMES gbk');\n ' 0x27 \\ 0x5c big5 cp932 gb2312 gbk sjis gbk SET NAMES 0xbf27 gbk latin1 ¿' latin1 gbk 0x27 ' addslashes() \\ 0x5c ' 0xbf5c27 gbk 0xbf5c 0x27 ' addslashes() mysql_real_escape_string() mysql_real_escape_string() addslashes() latin1 gbk latin1 mysql_real_escape_string() ' $var gbk SELECT * FROM test WHERE name = '縗' OR 1=1 /*' LIMIT 1\n $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n SET NAMES mysql_set_charset() mysql_set_charset() SET NAMES mysql_real_escape_string() utf8mb4 utf8 NO_BACKSLASH_ESCAPES mysql_real_escape_string() 0x27 0x2727 0x5c27 0xbf27 0xbf27 mysql_query('SET NAMES utf8');\n$var = mysql_real_escape_string(\"\\xbf\\x27 OR 1=1 /*\");\nmysql_query(\"SELECT * FROM test WHERE name = '$var' LIMIT 1\");\n utf8 mysql_set_charset('gbk');\n$var = mysql_real_escape_string(\"\\xbf\\x27 OR 1=1 /*\");\nmysql_query(\"SELECT * FROM test WHERE name = '$var' LIMIT 1\");\n $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n$pdo->query('SET NAMES gbk');\n$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');\n$stmt->execute(array(\"\\xbf\\x27 OR 1=1 /*\"));\n $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);\n$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');\n$stmt->execute(array(\"\\xbf\\x27 OR 1=1 /*\"));\n $mysqli->query('SET NAMES gbk');\n$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');\n$param = \"\\xbf\\x27 OR 1=1 /*\";\n$stmt->bind_param('s', $param);\n$stmt->execute();\n utf8 latin1 ascii NO_BACKSLASH_ESCAPES" }, { "answer_id": 49099975, "author": "snipershady", "author_id": 3635698, "author_profile": "https://Stackoverflow.com/users/3635698", "pm_score": -1, "selected": false, "text": "if (isset($value) && intval($value)) <99) {...}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
134,103
<p>On occasion, I find myself wanting to search the text of changelist descriptions in Perforce. There doesn't appear to be a way to do this in P4V. I can do it by redirecting the output of the changes command to a file...</p> <pre><code>p4 changes -l &gt; p4changes.txt </code></pre> <p>...(the -l switch tells it to dump the full text of the changelist descriptions) and then searching the file, but this is rather cumbersome. Has anyone found a better way?</p>
[ { "answer_id": 134183, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": false, "text": "select change from changes where description like '%text%' and p4options = 'longdesc'\n" }, { "answer_id": 1571910, "author": "Paul Medcraft", "author_id": 190566, "author_profile": "https://Stackoverflow.com/users/190566", "pm_score": 5, "selected": false, "text": "p4 changes -L | grep -B 3 searchstring -B 3" }, { "answer_id": 3881058, "author": "Julian Martin", "author_id": 275282, "author_profile": "https://Stackoverflow.com/users/275282", "pm_score": 3, "selected": false, "text": "p4 changes -L | select-string \"search string\" -Context (3,0)\n" }, { "answer_id": 12443354, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 2, "selected": false, "text": "less less p4 changes -l | less\n less" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
134,125
<p>I have three <code>divs</code>:</p> <pre><code>&lt;div id="login" /&gt; &lt;div id="content" /&gt; &lt;div id="menu" /&gt; </code></pre> <p>How would I define the CSS styles (without touching the HTML) to have the <code>menu-div</code> as the left column, the <code>login-div</code> in the right column and the <code>content-div</code> also in the right column but below the <code>login-div</code>.</p> <p>The <code>width</code> of every div is fixed, but the <code>height</code> isn't.</p>
[ { "answer_id": 134162, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": true, "text": "#menu {\n position:absolute;\n top:0;\n left:0;\n width:100px;\n}\n#content, #login {\n margin-left:120px;\n}\n #content, #login {\n float:right;\n clear:right\n}\n" }, { "answer_id": 134187, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 0, "selected": false, "text": "#login {\n float: right;\n width: 400px;\n border: 1px solid #f00;\n}\n\n#content {\n clear: right;\n float: right;\n width: 400px;\n border: 1px solid #f00;\n}\n\n#menu {\n float: left;\n width: 400px;\n border: 1px solid #f00;\n} <div id=\"login\">Login</div>\n<div id=\"content\">Content</div>\n<div id=\"menu\">Menu</div>" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9632/" ]
134,158
<p>Please, provide code examples in a language of your choice.</p> <p><strong>Update</strong>: No constraints set on external storage.</p> <p>Example: Integers are received/sent via network. There is a sufficient space on local disk for intermediate results.</p>
[ { "answer_id": 135106, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env python\nimport random\nfrom sort import Pickle, Polyphase\n\n\nnrecords = 1000000\navailable_memory = 2000000 # number of bytes\n #NOTE: it doesn't count memory required by Python interpreter \n\nrecord_size = 24 # (20 + 4) number of bytes per element in a Python list\nheap_size = available_memory / record_size \np = Polyphase(compare=lambda x,y: cmp(y, x), # descending order\n file_maker=Pickle, \n verbose=True,\n heap_size=heap_size,\n max_files=4 * (nrecords / heap_size + 1))\n\n# put records\nmaxel = 1000000000\nfor _ in xrange(nrecords):\n p.put(random.randrange(maxel))\n\n# get sorted records\nlast = maxel\nfor n, el in enumerate(p.get_all()):\n if el > last: # elements must be in descending order\n print \"not sorted %d: %d %d\" % (n, el ,last)\n break\n last = el\n\nassert nrecords == (n + 1) # check all records read\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
134,161
<p>I want to create a class which implements IEnumerable&lt;T&gt; but, using reflection, generates T's and returns them via IEnumerable&lt;T&gt;, where T' is a entirely constructed subclass of T with some properties hidden and others read-only. </p> <p>Okay., that might not be very clear. Let me explain this via the medium of code - I'd like to have a class CollectionView&lt;T&gt; as follows:-</p> <pre><code>public class CollectionView&lt;T&gt; : IEnumerable&lt;T&gt; { public CollectionView(IEnumerable&lt;T&gt; inputCollection, List&lt;string&gt; hiddenProperties, List&lt;string&gt; readonlyProperties) { // ... } // IEnumerable&lt;T&gt; implementation which returns a collection of T' where T':T. } ... public class SomeObject { public A { get; set; } public B { get; set; } public C { get; set; } } ... var hiddenProperties = new List&lt;string&gt;(new[] { "A" }); var readOnlyProperties = new List&lt;string&gt;(new[] { "C" }); IEnumerable&lt;SomeObject&gt; someObjects = CollectionView&lt;SomeObject&gt;(hiddenProperties, readOnlyProperties); ... dataGridView1.DataSource = someObjects; </code></pre> <p>(When displayed in dataGridView1 shows columns B and C and C has an underlying store which is read-only)</p> <p>Is this possible/desirable or have I completely lost my mind/does this question demonstrate my deep inadequacy as a programmer?</p> <p>I want to do this so I can manipulate a collection that is to be passed into a DataGridView, <em>without having to directly manipulate the DataGridView to hide columns/make columns read-only</em>. So no 'oh just use dataGridView1.Columns.Remove(blah) / dataGridView1.Columns[blah].ReadOnly = true' answers please!!</p> <p>Help!</p>
[ { "answer_id": 134318, "author": "Gilligan", "author_id": 12356, "author_profile": "https://Stackoverflow.com/users/12356", "pm_score": 1, "selected": false, "text": "new" }, { "answer_id": 134369, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 0, "selected": false, "text": "T" }, { "answer_id": 139058, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 0, "selected": false, "text": "public static DataTable ToDataTable<T>(this IEnumerable<T> collection)\n{\n DataTable ret = new DataTable();\n\n Type type = typeof(T);\n\n foreach (PropertyInfo propertyInfo in type.GetProperties())\n {\n // Ignore indexed properties.\n if (propertyInfo.GetIndexParameters().Length > 0) continue;\n ret.Columns.Add(propertyInfo.Name);\n }\n\n foreach (T data in collection)\n {\n DataRow row = ret.NewRow();\n foreach (PropertyInfo propertyInfo in type.GetProperties())\n {\n // Ignore indexed properties.\n if (propertyInfo.GetIndexParameters().Length > 0) continue;\n\n row[propertyInfo.Name] = propertyInfo.GetValue(data, null);\n }\n\n ret.Rows.Add(row);\n }\n\n return ret;\n}\n" }, { "answer_id": 12979726, "author": "Stephen", "author_id": 1272132, "author_profile": "https://Stackoverflow.com/users/1272132", "pm_score": 0, "selected": false, "text": "public sealed class MyPropertyDescriptor : System.ComponentModel.PropertyDescriptor\n{\n private PropertyDescriptor innerProperty;\n private Boolean isReadonly;\n\n public MyPropertyDescriptor(PropertyDescriptor innerProperty, Boolean isReadonly)\n : base(innerProperty.Name, GetAttributeArray(innerProperty.Attributes))\n {\n this.innerProperty = innerProperty;\n this.isReadonly = isReadonly;\n if (!isReadonly) this.isReadonly = innerProperty.IsReadOnly;\n }\n\n public override Type ComponentType\n {\n get { return this.innerProperty.ComponentType; }\n }\n public override Boolean IsReadOnly\n {\n get { return this.isReadonly; }\n }\n public override Type PropertyType\n {\n get { return this.innerProperty.PropertyType; }\n }\n public override String Name\n {\n get\n {\n return this.innerProperty.Name;\n }\n }\n public override String DisplayName\n {\n get\n {\n return this.innerProperty.DisplayName;\n }\n }\n public override Boolean SupportsChangeEvents\n {\n get\n {\n return true;\n }\n }\n public override void SetValue(Object component, Object value)\n {\n if (!this.isReadonly)\n {\n this.innerProperty.SetValue(component, value);\n if (component is MyWrapper) (component as MyWrapper).NotifyPropertyChanged(this.innerProperty.Name);\n }\n }\n public override Object GetValue(Object component)\n {\n return this.innerProperty.GetValue(component);\n }\n\n public override Boolean CanResetValue(Object component)\n {\n return false;\n }\n public override void ResetValue(Object component)\n {\n }\n public override Boolean ShouldSerializeValue(Object component)\n {\n return true;\n }\n\n private static Attribute[] GetAttributeArray(AttributeCollection attributes)\n {\n List<Attribute> attr = new List<Attribute>();\n foreach (Attribute a in attributes) attr.Add(a);\n\n return attr.ToArray();\n }\n}\n public sealed class MyWrapper : System.ComponentModel.ICustomTypeDescriptor, System.ComponentModel.INotifyPropertyChanged\n{\n private Object innerObject;\n private String[] hiddenProps;\n private String[] readonlyProps;\n\n private Type innerType;\n\n public MyWrapper(Object innerObject, String[] hiddenProps, String[] readonlyProps)\n : base()\n {\n this.innerObject = innerObject;\n this.hiddenProps = hiddenProps;\n this.readonlyProps = readonlyProps;\n this.innerType = innerObject.GetType();\n }\n\n public static PropertyDescriptorCollection FilterProperties(PropertyDescriptorCollection pdc, String[] hiddenProps, String[] readonlyProps)\n {\n List<PropertyDescriptor> list = new List<PropertyDescriptor>();\n\n foreach (PropertyDescriptor pd in pdc)\n {\n if (hiddenProps != null)\n {\n Boolean isHidden = false;\n foreach (String hidden in hiddenProps)\n {\n if (hidden.Equals(pd.Name, StringComparison.OrdinalIgnoreCase))\n {\n isHidden = true;\n break;\n }\n }\n if (isHidden) continue; // skip hidden\n }\n\n Boolean isReadonly = false;\n if (readonlyProps != null)\n {\n foreach (String rp in readonlyProps)\n {\n if (rp.Equals(pd.Name, StringComparison.OrdinalIgnoreCase))\n {\n isReadonly = true;\n break;\n }\n }\n }\n\n list.Add(new MyPropertyDescriptor(pd, isReadonly));\n }\n\n return new PropertyDescriptorCollection(list.ToArray());\n }\n\n #region ICustomTypeDescriptor Members\n\n PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)\n {\n return FilterProperties(TypeDescriptor.GetProperties(this.innerType, attributes), hiddenProps, readonlyProps);\n }\n PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()\n {\n return FilterProperties(TypeDescriptor.GetProperties(this.innerType), hiddenProps, readonlyProps);\n }\n\n AttributeCollection ICustomTypeDescriptor.GetAttributes()\n {\n return TypeDescriptor.GetAttributes(this.innerType);\n }\n\n String ICustomTypeDescriptor.GetClassName()\n {\n return TypeDescriptor.GetClassName(this.GetType());\n }\n String ICustomTypeDescriptor.GetComponentName()\n {\n return TypeDescriptor.GetComponentName(this.GetType());\n }\n TypeConverter ICustomTypeDescriptor.GetConverter()\n {\n return TypeDescriptor.GetConverter(this.GetType());\n }\n EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()\n {\n return TypeDescriptor.GetDefaultEvent(this.GetType());\n }\n PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()\n {\n return null;\n }\n Object ICustomTypeDescriptor.GetEditor(Type editorBaseType)\n {\n return TypeDescriptor.GetEditor(this.GetType(), editorBaseType);\n }\n EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)\n {\n return null;\n }\n EventDescriptorCollection ICustomTypeDescriptor.GetEvents()\n {\n return null;\n }\n\n Object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)\n {\n return this.innerObject;\n }\n\n #endregion\n\n #region INotifyPropertyChanged Members\n internal void NotifyPropertyChanged(String propertyName)\n {\n if (this.propertyChanged != null) this.propertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n private event PropertyChangedEventHandler propertyChanged;\n event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged\n {\n add { propertyChanged += value; }\n remove { propertyChanged -= value; }\n }\n #endregion\n}\n public sealed class CollectionView<T> : IEnumerable<MyWrapper>, System.Collections.IList, IList<MyWrapper>, ITypedList\n{\n private String[] hiddenProps;\n private String[] readonlyProps;\n private List<MyWrapper> collection;\n\n public CollectionView(IEnumerable<T> innerCollection, String[] hiddenProps, String[] readonlyProps)\n : base()\n {\n this.hiddenProps = hiddenProps;\n this.readonlyProps = readonlyProps;\n\n this.collection = new List<MyWrapper>();\n foreach (T item in innerCollection)\n {\n this.collection.Add(new MyWrapper(item, hiddenProps, readonlyProps));\n }\n }\n\n #region ITypedList Members\n\n PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)\n {\n return MyWrapper.FilterProperties(TypeDescriptor.GetProperties(typeof(T)), this.hiddenProps, this.readonlyProps);\n }\n\n String ITypedList.GetListName(PropertyDescriptor[] listAccessors)\n {\n return null;\n }\n #endregion\n\n #region IEnumerable<MyWrapper> Members\n\n IEnumerator<MyWrapper> IEnumerable<MyWrapper>.GetEnumerator()\n {\n return this.collection.GetEnumerator();\n }\n\n #endregion\n\n #region IEnumerable Members\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return this.collection.GetEnumerator();\n }\n\n #endregion\n\n #region IList Members\n Int32 System.Collections.IList.Add(Object value)\n {\n return (this.collection as System.Collections.IList).Add(value);\n }\n void System.Collections.IList.Clear()\n {\n (this.collection as System.Collections.IList).Clear();\n }\n Boolean System.Collections.IList.Contains(Object value)\n {\n return (this.collection as System.Collections.IList).Contains(value);\n }\n Int32 System.Collections.IList.IndexOf(Object value)\n {\n return (this.collection as System.Collections.IList).IndexOf(value);\n }\n void System.Collections.IList.Insert(Int32 index, Object value)\n {\n (this.collection as System.Collections.IList).Insert(index, value);\n }\n Boolean System.Collections.IList.IsFixedSize\n {\n get { return (this.collection as System.Collections.IList).IsFixedSize; }\n }\n Boolean System.Collections.IList.IsReadOnly\n {\n get { return (this.collection as System.Collections.IList).IsReadOnly; }\n }\n void System.Collections.IList.Remove(Object value)\n {\n (this.collection as System.Collections.IList).Remove(value);\n }\n void System.Collections.IList.RemoveAt(Int32 index)\n {\n (this.collection as System.Collections.IList).RemoveAt(index);\n }\n Object System.Collections.IList.this[Int32 index]\n {\n get\n {\n return (this.collection as System.Collections.IList)[index];\n }\n set\n {\n (this.collection as System.Collections.IList)[index] = value;\n }\n }\n #endregion\n\n #region ICollection Members\n void System.Collections.ICollection.CopyTo(Array array, Int32 index)\n {\n (this.collection as System.Collections.ICollection).CopyTo(array, index);\n }\n Int32 System.Collections.ICollection.Count\n {\n get { return (this.collection as System.Collections.ICollection).Count; }\n }\n Boolean System.Collections.ICollection.IsSynchronized\n {\n get { return (this.collection as System.Collections.ICollection).IsSynchronized; }\n }\n Object System.Collections.ICollection.SyncRoot\n {\n get { return (this.collection as System.Collections.ICollection).SyncRoot; }\n }\n #endregion\n\n #region IList<MyWrapper> Members\n Int32 IList<MyWrapper>.IndexOf(MyWrapper item)\n {\n return this.collection.IndexOf(item);\n }\n void IList<MyWrapper>.Insert(Int32 index, MyWrapper item)\n {\n this.collection.Insert(index, item);\n }\n void IList<MyWrapper>.RemoveAt(Int32 index)\n {\n this.collection.RemoveAt(index);\n }\n MyWrapper IList<MyWrapper>.this[Int32 index]\n {\n get\n {\n return this.collection[index];\n }\n set\n {\n this.collection[index] = value;\n }\n }\n #endregion\n\n #region ICollection<MyWrapper> Members\n void ICollection<MyWrapper>.Add(MyWrapper item)\n {\n this.collection.Add(item);\n }\n void ICollection<MyWrapper>.Clear()\n {\n this.collection.Clear();\n }\n Boolean ICollection<MyWrapper>.Contains(MyWrapper item)\n {\n return this.collection.Contains(item);\n }\n void ICollection<MyWrapper>.CopyTo(MyWrapper[] array, Int32 arrayIndex)\n {\n this.collection.CopyTo(array, arrayIndex);\n }\n Int32 ICollection<MyWrapper>.Count\n {\n get { return this.collection.Count; }\n }\n Boolean ICollection<MyWrapper>.IsReadOnly\n {\n get { return false; }\n }\n Boolean ICollection<MyWrapper>.Remove(MyWrapper item)\n {\n return this.collection.Remove(item);\n }\n #endregion\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
134,182
<p>Here's the code that I'm attempting to do:</p> <pre><code>public IList&lt;IOperator&gt; GetAll() { using (var c = new MyDataContext()) { return c.Operators.ToList(); } } </code></pre> <p>Operator implements IOperator, but I'm getting the following compilation error:</p> <pre><code>Cannot implicitly convert type 'System.Collections.Generic.List&lt;MyProject.Core.Operator&gt;' to 'System.Collections.Generic.IList&lt;MyProject.Core.Model.IOperator&gt;'. An explicit conversion exists (are you missing a cast?) </code></pre> <p>How do I cast this to get what I need?</p>
[ { "answer_id": 134268, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "Cast<>() return c.Operators.Cast<IOperator>().ToList();\n" }, { "answer_id": 134370, "author": "kenstone", "author_id": 11097, "author_profile": "https://Stackoverflow.com/users/11097", "pm_score": 2, "selected": false, "text": "public IList<IOperator> GetAll()\n{\n using (var c = new MyDataContext())\n {\n var operators = (from o in c.Operators\n select o).Cast<IOperator>();\n\n return operators.ToList();\n }\n}\n" }, { "answer_id": 2068765, "author": "Frank Tzanabetis", "author_id": 251210, "author_profile": "https://Stackoverflow.com/users/251210", "pm_score": 0, "selected": false, "text": "List<Operator> to List<IOperator> public static IList<IBusinessUnit> toIBusinessUnitIList(List<TEntity> items)\n {\n\n return items.ConvertAll<IBusinessUnit>(new Converter<TEntity, IBusinessUnit>(TEntityToIBuisinessUnit));\n }\n\n /// <summary>\n /// Callback for List<>.ConvertAll() used above.\n /// </summary>\n /// <param name=\"md\"></param>\n /// <returns></returns>\n private static IBusinessUnit TEntityToIBuisinessUnit(TEntity te)\n {\n return te; // In your case, do whatever magic you need to do to convert an Operator to an IOperator here.\n }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11097/" ]
134,214
<p>Right now, I have code that looks something like this:</p> <pre><code>Private Sub ShowReport(ByVal reportName As String) Select Case reportName Case "Security" Me.ShowSecurityReport() Case "Configuration" Me.ShowConfigurationReport() Case "RoleUsers" Me.ShowRoleUsersReport() Case Else pnlMessage.Visible = True litMessage.Text = "The report name """ + reportName + """ is invalid." End Select End Sub </code></pre> <p>Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for:</p> <pre><code>Private Sub ShowReport(ByVal reportName As String) Try Call("Show" + reportName + "Report") Catch ex As Exception 'method not found End Try End Sub </code></pre>
[ { "answer_id": 134231, "author": "Rick Minerich", "author_id": 9251, "author_profile": "https://Stackoverflow.com/users/9251", "pm_score": 0, "selected": false, "text": "string ModuleName = \"TestAssembly.dll\";\nstring TypeName = \"TestClass\";\nstring MethodName = \"TestMethod\";\n\nAssembly myAssembly = Assembly.LoadFrom(ModuleName);\n\nBindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | \n BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);\n\nModule [] myModules = myAssembly.GetModules();\nforeach (Module Mo in myModules) \n{\n if (Mo.Name == ModuleName) \n {\n Type[] myTypes = Mo.GetTypes();\n foreach (Type Ty in myTypes)\n {\n if (Ty.Name == TypeName) \n {\n MethodInfo[] myMethodInfo = Ty.GetMethods(flags);\n foreach(MethodInfo Mi in myMethodInfo)\n {\n if (Mi.Name == MethodName) \n {\n Object obj = Activator.CreateInstance(Ty);\n Object response = Mi.Invoke(obj, null);\n }\n }\n }\n }\n }\n}\n" }, { "answer_id": 134236, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 2, "selected": false, "text": "System.Reflection MethodInfo GetMethod(\"methodName\") MethodInfo .Invoke() System.Reflection.MethodInfo method = this.GetType().GetMethod(\"foo\");\nmethod.Invoke(this, null);\n" }, { "answer_id": 134238, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": true, "text": "Type type = GetType();\nMethodInfo method = type.GetMethod(\"Show\"+reportName+\"Report\");\nif (method != null)\n{\n method.Invoke(this, null);\n}\n" }, { "answer_id": 134246, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 2, "selected": false, "text": "MethodInfo Invoke" }, { "answer_id": 134247, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 0, "selected": false, "text": "Private Sub InvokeMethod(instance as object, methodName as string )\n 'Getting the method information using the method info class\n Dim mi as MethodInfo = instance.GetType().GetMethod(methodName)\n\n 'invoing the method\n 'null- no parameter for the function [or] we can pass the array of parameters\n mi.Invoke(instance, Nothing)\nEnd Sub\n" }, { "answer_id": 134250, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 2, "selected": false, "text": "private void ShowReport(string methodName)\n{\n Type type = this.GetType();\n MethodInfo method = type.GetMethod(\"Show\"+methodName+\"Report\", BindingFlags.Public)\n method.Invoke(this, null);\n}\n" }, { "answer_id": 134292, "author": "axel_c", "author_id": 20272, "author_profile": "https://Stackoverflow.com/users/20272", "pm_score": 0, "selected": false, "text": "Case \"financial\" :\n{\n Assembly asm = Assembly.GetExecutingAssembly ();\n\n MethodInfo mi = asm.GetType (\"thisClassType\").GetMethod (\"showFinancialReport\");\n\n if (mi != null)\n mi.Invoke (null, new object[] {});\n\n}\n" }, { "answer_id": 134293, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 0, "selected": false, "text": "Type t = this.GetType();\ntry \n{\n MethodInfo mi = t.GetMethod(methodName, ...);\n\n if (mi != null)\n {\n mi.Invoke(this, parameters);\n }\n} \n" }, { "answer_id": 134941, "author": "Dustman", "author_id": 16398, "author_profile": "https://Stackoverflow.com/users/16398", "pm_score": 0, "selected": false, "text": "Public Sub New()\n '...\n ReportTable.Add(\"Security\", New ReportDelegate(AddressOf ShowSecurityReport))\n ReportTable.Add(\"Config\", New ReportDelegate(AddressOf ShowConfigReport))\n ReportTable.Add(\"RoleUsers\", New ReportDelegate(AddressOf ShowRoleUsersReport))\n '...\nEnd Sub\n\nPrivate Sub ShowSecurityReport()\n '...\nEnd Sub\n\nPrivate Sub ShowConfigReport()\n '...\nEnd Sub\n\nPrivate Sub ShowRoleUsersReport()\n '...\nEnd Sub\n\nPrivate Delegate Sub ReportDelegate()\n\nPrivate ReportTable As New Dictionary(Of String, ReportDelegate)\n\nPrivate Sub ShowReport(ByVal reportName As String)\n Dim ReportToRun As ReportDelegate\n If ReportTable.TryGetValue(reportName, ReportToRun) Then\n ReportToRun()\n Else\n pnlMessage.Visible = True\n litMessage.Text = \"The report name \"\"\" + reportName + \"\"\" is invalid.\"\n End If\nEnd Sub\n" }, { "answer_id": 54516322, "author": "Andrew Xxx", "author_id": 11012407, "author_profile": "https://Stackoverflow.com/users/11012407", "pm_score": 0, "selected": false, "text": "Dim tip As Type = GetType(MODULENAME)'if sub() or function() in module\n Dim method As MethodInfo = tip.GetMethod(\"MaxV\") 'name of function (gets 2 params double type)\n Dim res As Double = 0 'temporary variable\n If (Not Nothing = method) Then 'if found function \"MaxV\"\n\n res = method.Invoke(Me, New Object() {10, 20})\n End If\n MsgBox(res.ToString())\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
134,224
<p>This code produces a FileNotFoundException, but ultimately runs without issue:</p> <pre><code>void ReadXml() { XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); //... } </code></pre> <p>Here is the exception:</p> <hr> <p>A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll</p> <p>Additional information: Could not load file or assembly 'MyAssembly.XmlSerializers, Version=1.4.3190.15950, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.</p> <hr> <p><strong>It appears that the framework automatically generates the serialization assembly if it isn't found.</strong> I can generate it manually using sgen.exe, which alleviates the exception. </p> <p><strong>How do I get visual studio to generate the XML Serialization assembly automatically?</strong></p> <hr> <p><strong>Update: The Generate Serialization Assembly: On setting doesn't appear to do anything.</strong></p>
[ { "answer_id": 204993, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 7, "selected": true, "text": "<!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets.\n<Target Name=\"BeforeBuild\">\n</Target>\n<Target Name=\"AfterBuild\">\n</Target>\n-->\n <Target Name=\"AfterBuild\" DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\" Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\" Outputs=\"$(OutputPath)$(_SGenDllName)\">\n <!-- Delete the file because I can't figure out how to force the SGen task. -->\n <Delete\n Files=\"$(TargetDir)$(TargetName).XmlSerializers.dll\"\n ContinueOnError=\"true\" />\n <SGen\n BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(OutputPath)\"\n References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"true\"\n UseProxyTypes=\"false\"\n KeyContainer=\"$(KeyContainerName)\"\n KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\"\n ToolPath=\"$(TargetFrameworkSDKToolsDirectory)\"\n Platform=\"$(Platform)\">\n <Output\n TaskParameter=\"SerializationAssembly\"\n ItemName=\"SerializationAssembly\" />\n </SGen>\n</Target>\n" }, { "answer_id": 8798289, "author": "heavyd", "author_id": 94928, "author_profile": "https://Stackoverflow.com/users/94928", "pm_score": 6, "selected": false, "text": "/proxytypes /proxytypes SGenUseProxyTypes <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x86' \">\n <!-- Snip... -->\n <GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>\n <SGenUseProxyTypes>false</SGenUseProxyTypes>\n </PropertyGroup>\n <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|x86' \">\n <!-- Snip... -->\n <GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>\n <SGenUseProxyTypes>false</SGenUseProxyTypes>\n </PropertyGroup>\n" }, { "answer_id": 15538240, "author": "brain backup", "author_id": 2043133, "author_profile": "https://Stackoverflow.com/users/2043133", "pm_score": 4, "selected": false, "text": "<TargetFrameworkVersion>v?.?</TargetFrameworkVersion> <SGenUseProxyTypes>false</SGenUseProxyTypes> <SGenPlatformTarget>$(Platform)</SGenPlatformTarget> <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Debug|x86'\"> <GenerateSerializationAssemblies>On</GenerateSerializationAssemblies> <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n <TargetFrameworkVersion> <Target\n Name=\"GenerateSerializationAssemblies\"\n Condition=\"'$(_SGenGenerateSerializationAssembliesConfig)' == 'On' or ('@(WebReferenceUrl)'!='' and '$(_SGenGenerateSerializationAssembliesConfig)' == 'Auto')\"\n DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\"\n Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\"\n Outputs=\"$(IntermediateOutputPath)$(_SGenDllName)\">\n\n <SGen\n BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(IntermediateOutputPath)\"\n References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"$(SGenShouldGenerateSerializer)\"\n UseProxyTypes=\"$(SGenUseProxyTypes)\"\n KeyContainer=\"$(KeyContainerName)\"\n KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\"\n ToolPath=\"$(SGenToolPath)\"\n SdkToolsPath=\"$(TargetFrameworkSDKToolsDirectory)\"\n EnvironmentVariables=\"$(SGenEnvironment)\"\n SerializationAssembly=\"$(IntermediateOutputPath)$(_SGenDllName)\"\n Platform=\"$(SGenPlatformTarget)\"\n Types=\"$(SGenSerializationTypes)\">\n <Output TaskParameter=\"SerializationAssembly\" ItemName=\"SerializationAssembly\"/>\n </SGen>\n</Target>\n" }, { "answer_id": 21015945, "author": "Timoty Weis", "author_id": 2416998, "author_profile": "https://Stackoverflow.com/users/2416998", "pm_score": 1, "selected": false, "text": "<!-- Check the platform target value and if present use that for a correct *.XmlSerializer.dll platform setup (default is MSIL)-->\n<PropertyGroup Condition=\" '$(PlatformTarget)'=='' \">\n <SGenPlatform>$(Platform)</SGenPlatform>\n</PropertyGroup>\n<PropertyGroup Condition=\" '$(PlatformTarget)'!='' \">\n <SGenPlatform>$(PlatformTarget)</SGenPlatform>\n</PropertyGroup>\n\n<!-- Delete the file because I can't figure out how to force the SGen task. -->\n<Delete Files=\"$(TargetDir)$(TargetName).XmlSerializers.dll\" ContinueOnError=\"true\" />\n<SGen\n BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(OutputPath)\"\n References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"true\"\n UseProxyTypes=\"false\"\n KeyContainer=\"$(KeyContainerName)\"\n KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\"\n ToolPath=\"$(SGenToolPath)\"\n SdkToolsPath=\"$(TargetFrameworkSDKToolsDirectory)\"\n EnvironmentVariables=\"$(SGenEnvironment)\"\n Platform=\"$(SGenPlatform)\">\n <Output TaskParameter=\"SerializationAssembly\" ItemName=\"SerializationAssembly\" />\n</SGen>\n" }, { "answer_id": 25247534, "author": "mcfea", "author_id": 984463, "author_profile": "https://Stackoverflow.com/users/984463", "pm_score": 2, "selected": false, "text": "\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\\NETFX 4.0 Tools\\sgen.exe\" \"$(TargetPath)\" /force\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
134,237
<p>I'm trying to use the <code>this</code> keyword in a static method, but the compiler won't allow me to use it.</p> <p>Why not?</p>
[ { "answer_id": 134587, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 3, "selected": false, "text": "public static void StaticMethod(Object o)\n{\n MyClass.StaticProperty = o;\n}\n" }, { "answer_id": 135305, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "this" }, { "answer_id": 27267355, "author": "Rohit Shirgaonkar", "author_id": 4228445, "author_profile": "https://Stackoverflow.com/users/4228445", "pm_score": 1, "selected": false, "text": " Class ClsProgram(){\npublic static void staticfunc(){\nClsProgram Obj = new ClsPrograM()\nObj.NonStaticFunc();\n}\npublic void NonStaticFunc(){}\n}\n" }, { "answer_id": 40296414, "author": "Baz Guvenkaya", "author_id": 3298119, "author_profile": "https://Stackoverflow.com/users/3298119", "pm_score": 0, "selected": false, "text": "Application.OpenForms[\"MainForm\"];\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ]
134,251
<p>I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to import the file the application errors out because you can't have duplicate keys in a HashTable. I want my program to be able to handle this error though. When I run into a duplicate key I would like to put that key into a arraylist and continue importing the rest of the data into the hashtable. How can I do this in C#</p> <p>Here is my code:</p> <hr> <p>private static Hashtable importFile(Hashtable myHashtable, String myFileName) {</p> <pre><code> StreamReader sr = new StreamReader(myFileName); CSVReader csvReader = new CSVReader(); ArrayList tempArray = new ArrayList(); int count = 0; while (!sr.EndOfStream) { String temp = sr.ReadLine(); if (temp.StartsWith(" ")) { ServMissing.Add(temp); } else { tempArray = csvReader.CSVParser(temp); Boolean first = true; String key = ""; String value = ""; foreach (String x in tempArray) { if (first) { key = x; first = false; } else { value += x + ","; } } myHashtable.Add(key, value); } count++; } Console.WriteLine("Import Count: " + count); return myHashtable; } </code></pre>
[ { "answer_id": 134326, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": true, "text": "if (myHashtable.ContainsKey(key))\n duplicates.Add(key);\nelse\n myHashtable.Add(key, value);\n" }, { "answer_id": 134431, "author": "Morten Christiansen", "author_id": 4055, "author_profile": "https://Stackoverflow.com/users/4055", "pm_score": 1, "selected": false, "text": "Dictionary<T, List<K>> dict = new Dictionary<T, List<K>>();\n\n//Insert item\nif (!dict.ContainsKey(key))\n dict[key] = new List<string>();\ndict[key].Add(value);\n" }, { "answer_id": 134831, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "CSVReader csvReader = new CSVReader();\nList<string> source = new List<string>();\nusing(StreamReader sr = new StreamReader(myFileName))\n{\n while (!sr.EndOfStream)\n {\n source.Add(sr.ReadLine());\n }\n}\nList<string> ServMissing =\n source\n .Where(s => s.StartsWith(\" \")\n .ToList();\n//--------------------------------------------------\nList<IGrouping<string, string>> groupedSource = \n(\n from s in source\n where !s.StartsWith(\" \")\n let parsed = csvReader.CSVParser(s)\n where parsed.Any()\n let first = parsed.First()\n let rest = String.Join( \",\" , parsed.Skip(1).ToArray())\n select new {first, rest}\n)\n.GroupBy(x => x.first, x => x.rest) //GroupBy(keySelector, elementSelector)\n.ToList()\n//--------------------------------------------------\nList<string> myExtras = new List<string>();\nforeach(IGrouping<string, string> g in groupedSource)\n{\n myHashTable.Add(g.Key, g.First());\n if (g.Skip(1).Any())\n {\n myExtras.Add(g.Key);\n } \n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8664/" ]
134,253
<p>3-Tier design has been my standard design philosophy for years for database driven applications, and it has never failed me. For those who practice it, describe your layers.</p> <p>I've found that many people muddle up the business tier and the data access tier, making it more like a 2.5-Tier design.</p> <p>I prefer to move the data tier almost entirely into the database using stored procedures, and just have a very lightweight data tier in code that wraps sproc calls into business objects.</p> <p>How do you approach it?</p> <p>EDIT: If all you are going to do is define what 3-tier is, don't waste your time replying. I am looking for how specific people implemented it, did you use stored procedures or an ORM, how did you handle circular dependancies between the DAL and the BLL? Theres a lot of depth to this topic besides saying</p> <ul> <li>UI</li> <li>Business</li> <li>Data</li> </ul>
[ { "answer_id": 1980663, "author": "Jason", "author_id": 240962, "author_profile": "https://Stackoverflow.com/users/240962", "pm_score": 0, "selected": false, "text": "Company.Data Company.Web PageBase Company.Web.WebApplication Company.Data\n Settings Setting SettingCollection Dim setting As New Setting(1) 'pass in the id of the specific setting\nsetting.Value = \"False\" 'change the value\nsetting.Save() ' Call the save method to persist changes back to the database\n Dim setting as New Setting()\nsetting.Name = \"SmtpServer\"\nsetting.Value = \"localhost\"\n\nsetting.Save()\n Company.Data Company.Data.Entites\nCompany.Data.Collections\nCompany.Data.BusinessObjects\n GetSettingByName Company.Data.BusinessObjects" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
134,263
<p>Currently Tomcat's login support redirects users back to where they initially were when the application figured out they weren't logged in.</p> <p>For this particular application I need to force them to always go back to <code>index.jsp</code>.</p> <p>I'm pretty sure this is a simple configuration option in the WAR's <code>web.xml</code>, but I haven't found the answer in google.</p>
[ { "answer_id": 136266, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": -1, "selected": false, "text": "<%\nif (request.getParameter(\"login\") == null) {\n response.sendRedirect(request.getContextPath() + \"/index.jsp?login\");\n return;\n}\n%>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9594/" ]
134,295
<p>I've gone through just about every property I can think of, but haven't found a simple way to hide the header on a winform UltraCombo control from Infragistics.</p> <p>Headers make sense when I have multiple visible columns and whatnot, but sometimes it would be nice to hide it.</p> <p>To give a simple example, let's say I have a combobox that displays whether something is active or not. There's a label next to it that says "Active". The combobox has one visible column with two rows -- "Yes" and "No".</p> <p>When the user opens the drop down, they see "Active" or whatever the header caption for the column is and then the choices. I'd like it to just show "Yes" and "No" only.</p> <p>It's a minor aesthetic issue that probably just bothers me and isn't even noticed by the users, but I'd still really like to know if there's a way around this default behavior.</p> <p><strong>RESOLUTION:</strong> As @Craig suggested, <em>ColHeadersVisible</em> is what I needed. The location of the property was slightly different, but it was easy enough to track down. Once I set <em>DisplayLayout.Bands(0).ColHeadersVisible=False</em>, the dropdown display the way I wanted it to.</p>
[ { "answer_id": 134310, "author": "Craig", "author_id": 7861, "author_profile": "https://Stackoverflow.com/users/7861", "pm_score": 3, "selected": true, "text": "<DropDownLayout ColHeadersVisible=\"No\"></DropDownLayout>" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3743/" ]
134,309
<p>I'm an IIS guy and know its as simple as just using the <a href="http://[computername]/path" rel="noreferrer">http://[computername]/path</a> to webapp.. however, I can't seem to figure out how to make this possible for a JSP application I'm writing that runs under Tomcat. Is there a configuration setting I need to set somewhere? </p>
[ { "answer_id": 46736522, "author": "John Rattz", "author_id": 5449970, "author_profile": "https://Stackoverflow.com/users/5449970", "pm_score": 2, "selected": false, "text": "Host CATALINA_HOME(Tomcat dir)/conf/server.xml tomcat#.exe # javaw javaw" }, { "answer_id": 56793684, "author": "Vader", "author_id": 9952453, "author_profile": "https://Stackoverflow.com/users/9952453", "pm_score": 0, "selected": false, "text": "<Connector port=\"8080\" protocol=\"HTTP/1.1\"\n connectionTimeout=\"20000\"\n redirectPort=\"8443\"/>\n <Connector port=\"8080\" protocol=\"HTTP/1.1\"\n connectionTimeout=\"20000\"\n redirectPort=\"8443\"\n address=\"0.0.0.0\" />\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
134,331
<p>I'm familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especially on a live site or web app. Is it something that can be overused and if so, what does overuse look like? Are there cases where it shouldn't be used? Also, what are some of the common security concerns in regard to error handling?</p>
[ { "answer_id": 134385, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 2, "selected": false, "text": "try\n{\n // Code that may error\n}\ncatch (Exception $e)\n{\n // Do other stuff if there's an error\n}\n @mysql_query($query);\n @mysql_query($query)\n or die('Invalid query: ' . mysql_error() . '<br />Line: ' . __LINE__ . '<br />File: ' . __FILE__ . '<br /><br />');\n" }, { "answer_id": 134852, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 1, "selected": false, "text": "mysql_connet FALSE new DBConnectionException(mysql_error())" }, { "answer_id": 136449, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 2, "selected": false, "text": "<?php\n\nclass Debug {\n\n public static setAsErrorHandler() {\n set_error_handler(array(__CLASS__, '__error_handler'));\n }\n\npublic static function __error_handler($errcode, $errmsg, $errfile, $errline) {\n if (IN DEV) {\n print on screen\n }\n else if (IN PRO) {\n log and mail\n } \n }\n}\n\nDebug::setAsErrorHandler();\n\n?>\n" }, { "answer_id": 143419, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 5, "selected": false, "text": "function exceptions_error_handler($severity, $message, $filename, $lineno) {\n if (error_reporting() == 0) {\n return;\n }\n if (error_reporting() & $severity) {\n throw new ErrorException($message, 0, $severity, $filename, $lineno);\n }\n}\nset_error_handler('exceptions_error_handler');\nerror_reporting(E_ALL ^ E_STRICT);\n schemaValidate DomDocument class errorhandler_LoggingCaller {\n protected $errors = array();\n function call($callback, $arguments = array()) {\n set_error_handler(array($this, \"onError\"));\n $orig_error_reporting = error_reporting(E_ALL);\n try {\n $result = call_user_func_array($callback, $arguments);\n } catch (Exception $ex) {\n restore_error_handler();\n error_reporting($orig_error_reporting);\n throw $ex;\n }\n restore_error_handler();\n error_reporting($orig_error_reporting);\n return $result;\n }\n function onError($severity, $message, $file = null, $line = null) {\n $this->errors[] = $message;\n }\n function getErrors() {\n return $this->errors;\n }\n function hasErrors() {\n return count($this->errors) > 0;\n }\n}\n $doc = new DomDocument();\n$doc->load($xml_filename);\n$validation = new errorhandler_LoggingCaller();\n$validation->call(\n array($doc, 'schemaValidate'),\n array($xsd_filename));\nif ($validation->hasErrors()) {\n var_dump($validation->getErrors());\n}\n" }, { "answer_id": 70635793, "author": "mohammad fanoodi", "author_id": 17213387, "author_profile": "https://Stackoverflow.com/users/17213387", "pm_score": 0, "selected": false, "text": "public $error=array();\npublic function Errors($Err)\n{\n\n ------ how to use -------\n $Err = array(\"func\" => \"constr\", \"ref\" => \"constrac\",\"context\" => \n \"2222222ت\",\"state\" => 3,);\n $ResultErr=$this->Errors($Err);\n $context=(array_filter(explode(',', $ResultErr['context'])));\n $func=(array_filter(explode(',', $ResultErr['func'])));\n $ref=(array_filter(explode(',', $ResultErr['ref'])));\n $state=($ResultErr['state']);\n $errors=array_merge([\"context\"=>$context], [\"func\"=>$func], \n [\"ref\"=>$ref], [\"state\"=>$state]);\n var_dump($errors);\n\n ---------------begine ------------------------ \n global $error;\n if (!is_array($Err)) {\n return $error;\n } else {\n if (!(isset($error['state']))) {\n $error['state']=\"\";\n }\n if (!(isset($error['func']))) {\n $error['func']=\"\";\n }\n if (!(isset($error['ref']))) {\n $error['ref']=\"\";\n }\n if (!(isset($error['context']))) {\n $error['context']=\"\";\n }\n $error['state']=$error['state'];\n $error['func']=$error['func'].= $Err[\"func\"].\",\";\n $error['ref']=$error['ref'].= $Err[\"ref\"].\",\";\n $error['context']=$error['context'].= $Err[\"context\"].\",\";\n $error[\"state\"]=$Err[\"state\"];\n return $error;\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
134,338
<p>In Java projects in Eclipse version 3.4.1 sometimes the folder "Referenced Libraries" disappears from the "Project Explorer" view. All third party jars are shown directly in the root of the project folder. The project compiles and runs fine. It seems to be a GUI problem.</p> <p>How can I get this folder back?</p>
[ { "answer_id": 11308148, "author": "user219882", "author_id": 419516, "author_profile": "https://Stackoverflow.com/users/419516", "pm_score": 3, "selected": false, "text": "down arrow Customize view Libraries from external" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ]
134,344
<p>Is there a way to retrieve the time zone choices in Windows Mobile in order to display them in a GUI? It would be much better not to have to show every 15 minutes just to be able to display GMT+5:45 for Kathmandu.</p>
[ { "answer_id": 232925, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 1, "selected": false, "text": "Note Microsoft bears no responsibility for the content or\nusage of these files. Certain locales have specific legal requirements with\nregard to providing data of this type; ensure you are in compliance with such\nregulations. \n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
134,374
<p>I would like to listen to method calls.</p> <p>For example, when an element is appended by anything to the document, I would like to be passed that element to act on it, like:</p> <p>//somewhere</p> <pre><code>aParent.appendChild(aChild); </code></pre> <p>//when the former, a function I defined as listener is called with the <code>aChild</code> as argument</p> <p>Does anybody know how to do that?</p>
[ { "answer_id": 134420, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 1, "selected": false, "text": "\nfunction AppendChild(oParent, oChild) {\n\n // your stuff on oParent\n\n // append oChild\n oParent.appendChild(oChild)\n}\n" }, { "answer_id": 134451, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 0, "selected": false, "text": "Node.prototype._appendChild = Node.prototype.appendChild;\nNode.prototype.appendChild = function myFunct(el){....; this._appendChild(el);}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
134,379
<p>Is it possible to do a <code>SELECT</code> statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 <strong>and returning them in that order</strong>, based on nothing more than the ID field?</p> <p>Both these statements return them in the same order: </p> <pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8) </code></pre> <pre><code>SELECT id FROM table WHERE id in (8,2,5,9,7) </code></pre>
[ { "answer_id": 134394, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "SELECT ID_FIELD\nFROM SOME_TABLE\nWHERE ID_FIELD IN(11,10,14,12,13)\nORDER BY\n CASE WHEN ID_FIELD = 11 THEN 0\n WHEN ID_FIELD = 10 THEN 1\n WHEN ID_FIELD = 14 THEN 2\n WHEN ID_FIELD = 12 THEN 3\n WHEN ID_FIELD = 13 THEN 4\n END\n" }, { "answer_id": 134401, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": true, "text": "SELECT id FROM table WHERE id in (7,2,5,9,8) \nORDER BY FIND_IN_SET(id,\"7,2,5,9,8\");\n SELECT id FROM table WHERE id in (7,2,5,9,8) \nORDER BY FIND_IN_SET(id,\"8,2,5,9,7\");\n FIND_IN_SET id id id | FIND_IN_SET\n---|-----------\n7 | 1\n2 | 2\n5 | 3\n FIND_IN_SET" }, { "answer_id": 134410, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 0, "selected": false, "text": "SELECT id FROM table WHERE id = 7\nUNION ALL SELECT id FROM table WHERE id = 2\nUNION ALL SELECT id FROM table WHERE id = 5\nUNION ALL SELECT id FROM table WHERE id = 9\nUNION ALL SELECT id FROM table WHERE id = 8;\n" }, { "answer_id": 134412, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": -1, "selected": false, "text": "7 1\n2 2\n5 3\n9 4 \n8 5\n" }, { "answer_id": 134417, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "SELECT * FROM table WHERE id IN (3, 2, 1, 4) ORDER BY id=4, id=1, id=2, id=3\n" }, { "answer_id": 134432, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 2, "selected": false, "text": "ORDER BY FIELD(ID,7,2,4,5,8) \n" }, { "answer_id": 341907, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SELECT id FROM table WHERE id in (7,2,5,9,8)\nORDER BY DECODE(id,7,1,2,2,5,3,9,4,8,5,6);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21716/" ]
134,387
<p>I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.</p> <p>How can I launch a controller as a stand alone script?</p> <p>I currently have:</p> <pre><code>from warehouse2.controllers import importServer importServer.runServer(60) </code></pre> <p>and in the controller file, but not part of the controller class:</p> <pre><code>def runServer(sleep_secs): try: imp = ImportserverController() while(True): imp.runImport() sleepFor(sleep_secs) except Exception, e: log.info("Unexpected error: %s" % sys.exc_info()[0]) log.info(e) </code></pre> <p>But starting ImportServer.py on the command line results in:</p> <pre><code>2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I mportJob|n_imports, SQL expression or this Session </code></pre>
[ { "answer_id": 784421, "author": "Ben Bangert", "author_id": 95274, "author_profile": "https://Stackoverflow.com/users/95274", "pm_score": 4, "selected": false, "text": "from paste.deploy import appconfig\nfrom pylons import config\n\nfrom YOURPROJ.config.environment import load_environment\n\nconf = appconfig('config:development.ini', relative_to='.')\nload_environment(conf.global_conf, conf.local_conf)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1566663/" ]
134,392
<p>I have a form in which people will be entering dollar values.</p> <p>Possible inputs:<br> $999,999,999.99<br> 999,999,999.99<br> 999999999<br> 99,999<br> $99,999<br></p> <p>The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.</p> <p>I tried just typecasting the strings to doubles but that didn't work. Total just equals 50 when it is output:</p> <pre><code>$string1 = "$50,000"; $string2 = "$50000"; $string3 = "50,000"; $total = (double)$string1 + (double)$string2 + (double)$string3; echo $total; </code></pre>
[ { "answer_id": 134458, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 0, "selected": false, "text": " m/^\\$?(\\d+)(?:\\.(\\d\\d))?$/\n $value = $1 + $2/100;\n" }, { "answer_id": 134467, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": true, "text": "function validateCurrency($string)\n{\n return preg_match('/^\\$?(\\d{1,3})(,\\d{3})*(.\\d{2})?$/', $string) ||\n preg_match('/^\\$?\\d+(.\\d{2})?$/', $string);\n}\n\nfunction makeCurrency($string)\n{\n $newstring = \"\";\n\n $array = str_split($string);\n foreach($array as $char)\n {\n if (($char >= '0' && $char <= '9') || $char == '.')\n {\n $newstring .= $char;\n }\n }\n\n return $newstring;\n}\n" }, { "answer_id": 134881, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": false, "text": "$x = 1.0;\nfor ($ii=0; $ii < 10; $ii++) {\n $x = $x - .1;\n}\nvar_dump($x);\n $x $x == 0" }, { "answer_id": 135175, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 0, "selected": false, "text": "(pseudocode) \nnewnumber = replace(oldnumber, /[^0-9.]/, //)\n double(newnumber)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16292/" ]
134,453
<p>Are there any tools available to log the page load time for a php site?</p> <p>Mainly looking for something that I can see trends of load times over time, I was considering dumping them into a file using error_log(), but I don't know what I could use to parse it and display graphs</p>
[ { "answer_id": 134503, "author": "Buzz", "author_id": 13113, "author_profile": "https://Stackoverflow.com/users/13113", "pm_score": 3, "selected": false, "text": "footer() $time_start = microtime_float();\n\nfunction microtime_float() {\n list($usec, $sec) = explode(\" \", microtime());\n return ((float)$usec + (float)$sec);\n}\n\n//at the start. \n\n//at the end:\n\n$time_end = microtime_float();\n$time = round($time_end - $time_start, 4);\n\necho \"Last uncached content render took $time seconds\";\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
134,456
<p>This</p> <pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%'; </code></pre> <p>is slower than this</p> <pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value'; </code></pre> <p>but what about this?</p> <pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value'; </code></pre> <p>My testing indicates the second and third examples are exactly the same. If that's true, my question is, why ever use "=" ?</p>
[ { "answer_id": 134527, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "insert into some_table (some_field) values ('some_value');\ninsert into some_table (some_fieled) values ('1some_value2');\ninsert into some_table (some_field) values ('some1value');\n\nSELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';\n\nSELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';\n\nSELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';\n" }, { "answer_id": 134553, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 5, "selected": true, "text": "SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE :b1\n" }, { "answer_id": 134717, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 1, "selected": false, "text": "like $% like '%foobar' 'joh$' '='" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
134,459
<p>I'm refactoring "spaghetti code" C module to work in multitasking (RTOS) environment.</p> <p>Now, there are very long functions and many unnecessary global variables.</p> <p>When I try to replace global variables that exists only in one function with locals, I get into dilemma. Every global variable is behave like local "static" - e.g. keep its value even you exit and re-enter to the function.</p> <p>For multitasking "static" local vars are worst from global. They make the functions non reentered.</p> <p>There are a way to examine if the function is relay on preserving variable value re-entrancing without tracing all the logical flow?</p>
[ { "answer_id": 134516, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 0, "selected": false, "text": "int global_c; // can be used by any other file with 'extern int global_c;'\n\nstatic int static_c; // cannot be seen or used outside of this file.\n\nint foo(...)\n{\n int local_c; // cannot be seen or used outside of this function.\n}\n" }, { "answer_id": 138041, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "int nplus4; int nplus4 = 0; // used only in add5\nint add5 (int n) {\n nplus4 = n + 4; // set\n return nplus4 + 1; // use\n}\n nplus4 static int nextn = 0; int nextn = 0; // used only in getn\nint getn (void) {\n int n = nextn++; // use, then use, then set\n return n;\n}\n nextn++ nextn = nextn + 1 char buffer[10000]" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22249/" ]
134,463
<p>I am using a popup menu in Delphi. I want to use it in a "radio group" fashion where if the user selects an item it is checked and the other items are not checked. I tried using the AutoCheck property, but this allows multiple items to be checked. Is there a way to set the popup menu so that only one item can be checked?</p>
[ { "answer_id": 134583, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": true, "text": "procedure TForm2.OnPopupItemClick(Sender: TObject);\nvar\n i : integer;\nbegin\n with (Sender as TMenuItem) do begin\n //if they just checked something...\n if Checked then begin\n //go through the list and *un* check everything *else*\n for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin\n if i <> MenuIndex then begin //don't uncheck the one they just clicked!\n (GetParentComponent as TPopupMenu).Items[i].Checked := False;\n end; //if not the one they just clicked\n end; //for each item in the popup\n end; //if we checked something\n end; //with\nend;\n procedure TForm2.FormCreate(Sender: TObject);\nvar\n i,j: integer;\nbegin\n inherited;\n\n //look for any popup menus, and assign our custom checkbox handler to them\n if Sender is TForm then begin\n with (Sender as TForm) do begin\n for i := 0 to ComponentCount - 1 do begin\n if (Components[i] is TPopupMenu) then begin\n for j := 0 to (Components[i] as TPopupMenu).Items.Count - 1 do begin\n (Components[i] as TPopupMenu).Items[j].OnClick := OnPopupItemClick;\n end; //for every item in the popup list we found\n end; //if we found a popup list\n end; //for every component on the form\n end; //with the form\n end; //if we are looking at a form\nend;\n procedure TForm2.OnPopupItemClick(Sender: TObject);\nvar\n i : integer;\nbegin\n with (Sender as TMenuItem) do begin\n //go through the list and make sure *only* the clicked item is checked\n for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin\n (GetParentComponent as TPopupMenu).Items[i].Checked := (i = MenuIndex);\n end; //for each item in the popup\n end; //with\nend;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12833/" ]
134,470
<p>I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app_controller.php, but it's kind of messy there.</p>
[ { "answer_id": 134504, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": 4, "selected": true, "text": "<?php\nclass UtilComponent extends Object {\n function yourMethod($param) {\n // logic here.......\n\n return $param;\n }\n}\n?>\n var $components = array('Util');\n $this->Util->yourMethod($yourparam);\n" }, { "answer_id": 138542, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 2, "selected": false, "text": "Router::connect('/posts', array('controller' => 'posts', 'action' => 'index'));\nRouter::connect('/comments', array('controller' => 'posts', 'action' => 'list_comments'));\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18396/" ]
134,481
<p>What I have now (which successfully loads the plug-in) is this:</p> <pre><code>Assembly myDLL = Assembly.LoadFrom("my.dll"); IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass; </code></pre> <p>This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor?</p>
[ { "answer_id": 134502, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 2, "selected": false, "text": "public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)\n" }, { "answer_id": 134768, "author": "Magnus Akselvoll", "author_id": 4683, "author_profile": "https://Stackoverflow.com/users/4683", "pm_score": 5, "selected": true, "text": "using System;\nusing Host;\n\nnamespace Client\n{\n public class MyClass : IMyInterface\n {\n public int _id;\n public string _name;\n\n public MyClass(int id,\n string name)\n {\n _id = id;\n _name = name;\n }\n\n public string GetOutput()\n {\n return String.Format(\"{0} - {1}\", _id, _name);\n }\n }\n}\n\n\nnamespace Host\n{\n public interface IMyInterface\n {\n string GetOutput();\n }\n}\n\n\nusing System;\nusing System.Reflection;\n\nnamespace Host\n{\n internal class Program\n {\n private static void Main()\n {\n //These two would be read in some configuration\n const string dllName = \"Client.dll\";\n const string className = \"Client.MyClass\";\n\n try\n {\n Assembly pluginAssembly = Assembly.LoadFrom(dllName);\n Type classType = pluginAssembly.GetType(className);\n\n var plugin = (IMyInterface) Activator.CreateInstance(classType,\n 42, \"Adams\");\n\n if (plugin == null)\n throw new ApplicationException(\"Plugin not correctly configured\");\n\n Console.WriteLine(plugin.GetOutput());\n }\n catch (Exception e)\n {\n Console.Error.WriteLine(e.ToString());\n }\n }\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22252/" ]
134,492
<p>I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?</p> <pre><code>LinkedList&lt;Diff_match_patch.Patch&gt; patches = // whatever... FileOutputStream fileStream = new FileOutputStream("foo.ser"); ObjectOutputStream os = new ObjectOutputStream(fileStream); os.writeObject(patches1); os.close(); FileInputStream fileInputStream = new FileInputStream("foo.ser"); ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream); Object one = oInputStream.readObject(); LinkedList&lt;Diff_match_patch.Patch&gt; patches3 = (LinkedList&lt;Diff_match_patch.Patch&gt;) one; os.close(); </code></pre>
[ { "answer_id": 134556, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "BLOB XMLEncoder" }, { "answer_id": 134661, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 3, "selected": false, "text": "LinkedList<Patch> patches1 = diff.patch_make(text2, text1);\ntry {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n ObjectOutputStream os = new ObjectOutputStream(bos);\n os.writeObject(patches1);\n String serialized_patches1 = bos.toString();\n os.close();\n\n\n ByteArrayInputStream bis = new ByteArrayInputStream(serialized_patches1.getBytes());\n ObjectInputStream oInputStream = new ObjectInputStream(bis);\n LinkedList<Patch> restored_patches1 = (LinkedList<Patch>) oInputStream.readObject(); \n\n\n\n // patches1 equals restored_patches1\n oInputStream.close();\n} catch(Exception ex) {\n ex.printStackTrace();\n}\n" }, { "answer_id": 134918, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 9, "selected": true, "text": "import java.util.*;\nimport java.io.*;\n\n/** \n * Usage sample serializing SomeClass instance \n */\npublic class ToStringSample {\n\n public static void main( String [] args ) throws IOException,\n ClassNotFoundException {\n String string = toString( new SomeClass() );\n System.out.println(\" Encoded serialized version \" );\n System.out.println( string );\n SomeClass some = ( SomeClass ) fromString( string );\n System.out.println( \"\\n\\nReconstituted object\");\n System.out.println( some );\n\n\n }\n\n /** Read the object from Base64 string. */\n private static Object fromString( String s ) throws IOException ,\n ClassNotFoundException {\n byte [] data = Base64.getDecoder().decode( s );\n ObjectInputStream ois = new ObjectInputStream( \n new ByteArrayInputStream( data ) );\n Object o = ois.readObject();\n ois.close();\n return o;\n }\n\n /** Write the object to a Base64 string. */\n private static String toString( Serializable o ) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream( baos );\n oos.writeObject( o );\n oos.close();\n return Base64.getEncoder().encodeToString(baos.toByteArray()); \n }\n}\n\n/** Test subject. A very simple class. */ \nclass SomeClass implements Serializable {\n\n private final static long serialVersionUID = 1; // See Nick's comment below\n\n int i = Integer.MAX_VALUE;\n String s = \"ABCDEFGHIJKLMNOP\";\n Double d = new Double( -1.0 );\n public String toString(){\n return \"SomeClass instance says: Don't worry, \" \n + \"I'm healthy. Look, my data is i = \" + i \n + \", s = \" + s + \", d = \" + d;\n }\n}\n C:\\samples>javac *.java\n\nC:\\samples>java ToStringSample\nEncoded serialized version\nrO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T\nAABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w\nQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ\nDREVGR0hJSktMTU5PUA==\n\n\nReconstituted object\nSomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0\n" }, { "answer_id": 44328319, "author": "Markus Schulte", "author_id": 1645517, "author_profile": "https://Stackoverflow.com/users/1645517", "pm_score": 3, "selected": false, "text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.Base64;\nimport java.util.Optional;\n\nfinal class ObjectHelper {\n\n private ObjectHelper() {}\n\n static Optional<String> convertToString(final Serializable object) {\n try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos)) {\n oos.writeObject(object);\n return Optional.of(Base64.getEncoder().encodeToString(baos.toByteArray()));\n } catch (final IOException e) {\n e.printStackTrace();\n return Optional.empty();\n }\n }\n\n static <T extends Serializable> Optional<T> convertFrom(final String objectAsString) {\n final byte[] data = Base64.getDecoder().decode(objectAsString);\n try (final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {\n return Optional.of((T) ois.readObject());\n } catch (final IOException | ClassNotFoundException e) {\n e.printStackTrace();\n return Optional.empty();\n }\n }\n}\n" }, { "answer_id": 44646354, "author": "priyanka_rao", "author_id": 3568094, "author_profile": "https://Stackoverflow.com/users/3568094", "pm_score": 1, "selected": false, "text": "public static byte[] serialize(Object obj) throws IOException {\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n ObjectOutputStream os = new ObjectOutputStream(out);\n os.writeObject(obj);\n return out.toByteArray();\n}\n" }, { "answer_id": 64569159, "author": "yurin", "author_id": 2534191, "author_profile": "https://Stackoverflow.com/users/2534191", "pm_score": 0, "selected": false, "text": "Gson gson = new Gson();\nPerson[] persons = getArrayOfPersons();\nString json = gson.toJson(persons);\nSystem.out.println(json);\n//output: [{\"name\":\"Tom\",\"age\":11},{\"name\":\"Jack\",\"age\":12}]\nPerson[] personsFromJson = gson.fromJson(json, Person[].class);\n//...\nclass Person {\n public String name;\n public int age;\n} \n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
134,494
<p>I wasn't aware of a difference, but a coworker says there is, although he can't back it up. What's the difference if any?</p>
[ { "answer_id": 134557, "author": "ZachPruckowski", "author_id": 22255, "author_profile": "https://Stackoverflow.com/users/22255", "pm_score": 3, "selected": false, "text": "<whatever /> <whatever>" }, { "answer_id": 20547914, "author": "Kent Pawar", "author_id": 985766, "author_profile": "https://Stackoverflow.com/users/985766", "pm_score": 1, "selected": false, "text": "IF is_well_formed(<XML_doc>) THEN\n # It is well-formed, and can be parsed\n IF is_valid(<XML_doc>) THEN\n # Well-formed and ALSO valid. Hurray! \n # **A valid XML doc, is a well-formed doc!**\n ELSE\n # Only well-formed, NOT valid\n END IF\nELSE\n # Not well-formed, or valid!\nEND IF\n\nFUNCTION is_well_formed\n IF <does_not_contain_syntax,_spelling,_punctuation,_grammar_errors,_etc._errors> THEN\n RETURN TRUE\n ELSE \n RETURN FALSE\n END IF\nEND FUNCTION \n\nFUNCTION is_valid\n IF <markup_of_the_XML_document_matches_\"some\"_defined_standard> THEN\n # Standards used to validate XML could be a DTDs or XML Schemas, referenced within the XML document\n RETURN TRUE\n ELSE \n RETURN FALSE\n END IF\nEND FUNCTION\n" }, { "answer_id": 25830482, "author": "kjhughes", "author_id": 290085, "author_profile": "https://Stackoverflow.com/users/290085", "pm_score": 5, "selected": false, "text": "<a><b></a></b> < & &lt &amp;" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ]
134,501
<p>Usually when I need to fork in C, I do something like this:</p> <pre><code>pid_t p = fork(); if(p == 0) { /* do child stuff */ } else { /* do parent stuff and pray there wasn't an error */ } </code></pre> <p>It occured to me that I could ditch the extra variable and use:</p> <pre><code>if(fork() == 0) { /* child */ } else { /* parent/pray */ } </code></pre> <p>Improper error handling aside, (why) does this work/not work?</p>
[ { "answer_id": 134531, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "int p;\nif((p = fork()) == 0) { /* child */ }\nelse { /* parent/pray */ }\n" }, { "answer_id": 134545, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 5, "selected": true, "text": "switch (pid = fork()) {\ncase -1: /* Failure */\n /* ... */\ncase 0: /* Child */\n /* ... */\ndefault: /* Parent */\n /* ... */\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12926/" ]
134,505
<p>I've found mention of a data application block existing for ODBC, but can't seem to find it anywhere. If i didn't have a copy of the Access DB application block I wouldn't believe it ever existed either.</p> <p>Anyone know where to download either the DLL or the code-base from?</p> <p>--UPDATE: It is NOT included in either the v1, v2, or Enterprise Library versions of the Data ApplicationBlocks</p> <p>Thanks, Brian Swanson</p>
[ { "answer_id": 1014310, "author": "ChrisC_46259", "author_id": 95063, "author_profile": "https://Stackoverflow.com/users/95063", "pm_score": 3, "selected": true, "text": "Imports Microsoft.Practices.EnterpriseLibrary.Data\nImports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling\n\n Public Class MyClass\n\n Private dbMyDatabase As Database\n\n dbMyDatabase = DatabaseFactory.CreateDatabase(\"MyConnection\")\n\n Public Function GetMyData(ByVal FacilityCode As String) As Data.DataSet\n\n Try\n Dim SQL As String\n SQL = \"SELECT * from MyDataTable\"\n Dim cmd As Data.Common.DbCommand = dbMyDatabase.GetSqlStringCommand(SQL)\n Return dbMyDatabase.ExecuteDataSet(cmd)\n Catch ex As Exception\n ExceptionPolicy.HandleException(ex, \"All\")\n Throw\n End Try\n End Function \n\n End Class\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1795/" ]
134,517
<p>I distribute software online, and always wonder if there is a proper way to better define version numbers.</p> <p>Let's assume A.B.C.D in the answers. When do you increase each of the components?</p> <p>Do you use any other version number tricks such as D mod 2 == 1 means it is an in house release only?</p> <p>Do you have beta releases with their own version numbers, or do you have beta releases per version number?</p>
[ { "answer_id": 134647, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "1.1.2.3\n 1.0.1.23\n 1.0.1.12537\n" }, { "answer_id": 134695, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "[Program #] . [Year] . [Month] . [Release # of this app within the month]\n 15.2008.9.3\n" }, { "answer_id": 145227, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "if VERSION > 900 if (VERSION >= 900 || (VERSION >= 280 && VERSION < 400)" }, { "answer_id": 929478, "author": "Finglas", "author_id": 102482, "author_profile": "https://Stackoverflow.com/users/102482", "pm_score": 1, "selected": false, "text": "Major.Minor.*.*" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
134,520
<p>Okay, this is just a crazy idea I have. Stack Overflow looks very structured and integrable into development applications. So would it be possible, even useful, to have a Stack Overflow plugin for, say, Eclipse? </p> <p>Which features of Stack Overflow would you like to have directly integrated into your IDE so you can use it "natively" without changing to a browser?</p> <p>EDIT: I'm thinking about ways of deeper integration than just using the web page inside the IDE. Like when you use a certain Java class and have a problem, answers from SO might flare up. There would probably be cases where something like this is annoying, but others may be very helpful.</p>
[ { "answer_id": 134588, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 2, "selected": false, "text": "//# read an XML file\n" }, { "answer_id": 134935, "author": "Chris Lawlor", "author_id": 21245, "author_profile": "https://Stackoverflow.com/users/21245", "pm_score": 5, "selected": true, "text": "Public Sub SearchStackOverflowForSelectedText()\n Dim s As String = ActiveWindowSelection().Trim()\n If s.Length > 0 Then\n DTE.ItemOperations.Navigate(\"http://www.stackoverflow.com/search?q=\" & _\n Web.HttpUtility.UrlEncode(s))\n End If\nEnd Sub\n\nPrivate Function ActiveWindowSelection() As String\n If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then\n Return OutputWindowSelection()\n End If\n If DTE.ActiveWindow.ObjectKind = \"{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}\" Then\n Return HTMLEditorSelection()\n End If\n Return SelectionText(DTE.ActiveWindow.Selection)\nEnd Function\n\nPrivate Function HTMLEditorSelection() As String\n Dim hw As HTMLWindow = ActiveDocument.ActiveWindow.Object\n Dim tw As TextWindow = hw.CurrentTabObject\n Return SelectionText(tw.Selection)\nEnd Function\n\nPrivate Function OutputWindowSelection() As String\n Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)\n Dim ow As OutputWindow = w.Object\n Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name)\n Return SelectionText(owp.TextDocument.Selection)\nEnd Function\n\nPrivate Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String\n If sel Is Nothing Then\n Return \"\"\n End If\n If sel.Text.Length = 0 Then\n SelectWord(sel)\n End If\n If sel.Text.Length <= 2 Then\n Return \"\"\n End If\n Return sel.Text\nEnd Function\n\nPrivate Sub SelectWord(ByVal sel As EnvDTE.TextSelection)\n Dim leftPos As Integer\n Dim line As Integer\n Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()\n\n sel.WordLeft(True, 1)\n line = sel.TextRanges.Item(1).StartPoint.Line\n leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset\n pt.MoveToLineAndOffset(line, leftPos)\n sel.MoveToPoint(pt)\n sel.WordRight(True, 1)\nEnd Sub\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19734/" ]
134,569
<p>I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a <code>std::string</code> pointer?</p> <p>Here's what I was looking forward to doing:</p> <pre><code>void Foo::Bar() { if(!QueryPerformanceTimer(&amp;m_baz)) { throw new std::string("it's the end of the world!"); } } void Foo::Caller() { try { this-&gt;Bar(); // should throw } catch(std::string *caught) { // not quite sure the syntax is OK here... std::cout &lt;&lt; "Got " &lt;&lt; caught &lt;&lt; std::endl; } } </code></pre>
[ { "answer_id": 134596, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 3, "selected": false, "text": "std::string string" }, { "answer_id": 134612, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 6, "selected": false, "text": "struct MyException : public std::exception\n{\n std::string s;\n MyException(std::string ss) : s(ss) {}\n ~MyException() throw () {} // Updated\n const char* what() const throw() { return s.c_str(); }\n};\n void Foo::Bar(){\n if(!QueryPerformanceTimer(&m_baz)){\n throw MyException(\"it's the end of the world!\");\n }\n}\n\nvoid Foo::Caller(){\n try{\n this->Bar();// should throw\n }catch(MyException& caught){\n std::cout<<\"Got \"<<caught.what()<<std::endl;\n }\n}\n" }, { "answer_id": 134623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\n//Good, because manual memory management isn't needed and this uses\n//less heap memory (or no heap memory) so this is safer if\n//used in a low memory situation\nvoid f() { throw string(\"foo\"); }\n\n//Valid, but avoid manual memory management if there's no reason to use it\nvoid g() { throw new string(\"foo\"); }\n\n//Best. Just a pointer to a string literal, so no allocation is needed,\n//saving on cleanup, and removing a chance for an allocation to fail.\nvoid h() { throw \"foo\"; }\n\nint main() {\n try { f(); } catch (string s) { cout << s << endl; }\n try { g(); } catch (string* s) { cout << *s << endl; delete s; }\n try { h(); } catch (const char* s) { cout << s << endl; }\n return 0;\n}\n" }, { "answer_id": 134640, "author": "christopher_f", "author_id": 9224, "author_profile": "https://Stackoverflow.com/users/9224", "pm_score": 8, "selected": true, "text": "std::exception" }, { "answer_id": 135184, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "void Foo::Bar(){\n if(!QueryPerformanceTimer(&m_baz)){\n throw std::string(\"it's the end of the world!\");\n }\n}\n\nvoid Foo:Caller(){\n try{\n this->Bar();// should throw\n }catch(std::string& caught){ // not quite sure the syntax is ok here...\n std::cout<<\"Got \"<<caught<<std::endl;\n }\n}\n" }, { "answer_id": 17600616, "author": "Eric Leschinski", "author_id": 445131, "author_profile": "https://Stackoverflow.com/users/445131", "pm_score": 2, "selected": false, "text": "#include <iostream>\nusing namespace std;\nvoid purturb(){\n throw \"Cannot purturb at this time.\";\n}\nint main() {\n try{\n purturb();\n }\n catch(const char* msg){\n cout << \"We caught a message: \" << msg << endl;\n }\n cout << \"done\";\n return 0;\n}\n We caught a message: Cannot purturb at this time.\ndone\n This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information." }, { "answer_id": 47619071, "author": "GPMueller", "author_id": 4069571, "author_profile": "https://Stackoverflow.com/users/4069571", "pm_score": 2, "selected": false, "text": "std::nested_exception std::throw_with_nested Library API: Exception caught in function 'api_function'\nBacktrace:\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file \"nonexistent.txt\"\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22187/" ]
134,572
<p>I am using the jQuery AutoComplete plugin in an html page where I also have an accordion menu which uses prototype.</p> <p>They both work perfectly separately but when I tried to implement both components in a single page I get an error that I have not been able to understand.</p> <blockquote> <p>uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMViewCSS.getComputedStyle]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: file:///C:/Documents and Settings/Administrator/Desktop/website/js/jquery-1.2.6.pack.js :: anonymous :: line 11" data: no]</p> </blockquote> <p>I found out the file conflicting with jQuery is 'effects.js' which is used by the accordion menu. I tried replacing this file with a newer version but newer seems to break the accordion behavior. </p> <p>My guess is that the 'effects.js' file used in the accordion was modified to obtain the accordion demo output. I also tried using the overriding methods jQuery needs to avoid conflict with other libraries and that did not work.</p> <p>I obtained the accordion demo from <a href="http://www.stickmanlabs.com/accordion/" rel="nofollow noreferrer">stickmanlabs.com</a>.</p> <p>And the jQuery AutoComplete can be obtained from <a href="http://docs.jquery.com/Plugins/Autocomplete#Setup" rel="nofollow noreferrer">jQuery site</a>.</p> <p>Has any one else experienced this issue?</p>
[ { "answer_id": 134635, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 3, "selected": false, "text": "$ var J = jQuery.noConflict();\n" }, { "answer_id": 136502, "author": "John Resig", "author_id": 6524, "author_profile": "https://Stackoverflow.com/users/6524", "pm_score": 7, "selected": false, "text": "noConflict() <script src=\"jquery.js\"></script>\n<script src=\"jquery.autocomplete.js\"></script>\n<script>\n jQuery.noConflict();\n jQuery(document).ready(function($){\n $(\"#example\").autocomplete(options);\n });\n</script>\n<script src=\"prototype.js\"></script>\n<script src=\"effects.js\"></script>\n<script src=\"accordion.js\"></script>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
134,574
<p>I am working on a web application developed on C#/ASP.NET. We are using third-party controls for displaying Grids, Tabs, Trees and other complex controls in our pages. The problem is that these controls render a huge amount of HTML. Due to this the size of pages have grown heavily and the browser takes a while to load a page. I want to find some general techniques to make HTML rendering in a browser (Internet Explorer, Firefox, etc.) fast.</p> <p>Note that all the pages have ViewState turned off.</p>
[ { "answer_id": 134625, "author": "Jason N. Gaylord", "author_id": 21318, "author_profile": "https://Stackoverflow.com/users/21318", "pm_score": 2, "selected": false, "text": "ViewState ViewState" }, { "answer_id": 142852, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": false, "text": "javascript:var tags = document.getElementsByTagName('*');alert('Page weight: ' + tags.length + ' tags.');\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965628/" ]
134,575
<p>I'm very early in the iPhone development learning process. I'm trying to get my head around various pieces. Right now I've just taken the basic NavigationController template and I'm trying to create a simple grouped table view with a couple of text fields. What I can't seem to do is to get Interface Builder to allow me to drop a UITableViewCell into a UITableView so that I can then add a text field to the Cell. Is this even possible (it would seem that its supposed to be given the fact that UITableViewCell is a draggable control)?</p> <p>If not, does that mean all of that is code I will need to just write myself?</p>
[ { "answer_id": 136384, "author": "user19087", "author_id": 19087, "author_profile": "https://Stackoverflow.com/users/19087", "pm_score": 3, "selected": false, "text": "IBOutlets UITableViewCell UIViewController UITableController IBOutlet UITableViewCell *cellFactory UITableViewDataSource tableView:cellForRowAtIndexPath: [NSBundle mainBundle] loadNibNamed:owner:options: cell = cellFactory cellFactory" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13036/" ]
134,581
<p>This is a follow-up to <a href="https://stackoverflow.com/questions/43778/sqlite3-ruby-gem-failed-to-build-gem-native-extension">this question</a>.</p> <p>When I issue the <strong><code>gem update</code></strong> command on Windows, whenever it gets to a gem whose latest version DOESN'T have Windows binaries, it'll attempt to build the native extension which will, of course, fail. For example:</p> <pre><code>Updating sqlite3-ruby Building native extensions. This could take a while... ERROR: While executing gem ... (Gem::Installer::ExtensionBuildError) ERROR: Failed to build gem native extension. c:/ruby/bin/ruby.exe extconf.rb update checking for fdatasync() in rt.lib... no checking for sqlite3.h... no nmake 'nmake' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>The old pre-1.x behavior of asking for the required platform at least made updating possible. Now I can't update at all unless I uninstall the troublesome gems (currently sqlite3-ruby and hpricot), run the update, then re-install the gems using the --version switch.</p> <p>Does anyone have a solution to this conundrum or are we stuck with it?</p> <hr> <p><strong>Note:</strong></p> <pre><code>$ gem -v 1.2.0 $ ruby -v ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32] </code></pre> <hr> <p><strong>Note (26 September 2008):</strong> I just updated to gems 1.3.0 and this problem persists.</p> <p><strong>Note (18 November 2008):</strong> Just updated to gems 1.3.1 and the problem persists.</p> <p><strong>Note (28 April 2009):</strong> The latest version of Gems (<a href="http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2" rel="nofollow noreferrer">1.3.2</a>) now skips any gems where building of native extensions fails during update; in other words, the problem is fixed. Hooray!</p>
[ { "answer_id": 136226, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 2, "selected": false, "text": "gem install sqlite3-ruby --version '1.2.3'\n" }, { "answer_id": 144510, "author": "Charles Roper", "author_id": 1944, "author_profile": "https://Stackoverflow.com/users/1944", "pm_score": 3, "selected": true, "text": "gem update --system\n `gem.bat outdated`.split(/\\n/).map{|z|z.scan(/^[^[:space:]]+/)}.flatten.each{|z| `gem.bat update #{z}`}\n gem outdated gem update" }, { "answer_id": 3772754, "author": "AMIC MING", "author_id": 206401, "author_profile": "https://Stackoverflow.com/users/206401", "pm_score": 2, "selected": false, "text": "gem install sqlite3-ruby --platform=mswin32\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
134,626
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.</p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)</p> <p>Does it even matter? If it doesn't then does that violate the Pythonic principle:</p> <blockquote> <p><a href="https://www.python.org/dev/peps/pep-0020/" rel="noreferrer">There should be one-- and preferably only one --obvious way to do it.</a>.</p> </blockquote>
[ { "answer_id": 134638, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 8, "selected": true, "text": "lambda def def lambda map() filter() operator operator.add lambda x, y: x + y lambda def operator def lambda" }, { "answer_id": 134664, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "def lambda a = [ (1,2), (3,4), (5,6) ]\nb = map( lambda x: x[0]+x[1], a )\n" }, { "answer_id": 134709, "author": "Chris Lawlor", "author_id": 21245, "author_profile": "https://Stackoverflow.com/users/21245", "pm_score": 5, "selected": false, "text": "str(reduce(lambda x,y:x+y,map(lambda x:x**x,range(1,1001))))[-10:]\n" }, { "answer_id": 135353, "author": "apg", "author_id": 22277, "author_profile": "https://Stackoverflow.com/users/22277", "pm_score": 2, "selected": false, "text": "x = [f for f in range(1, 40) if f % 2]\n" }, { "answer_id": 135815, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 0, "selected": false, "text": "myFunction(data, (lambda x, y : x + y))\n import operator\nmyFunction(data, operator.add)\n" }, { "answer_id": 138625, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 5, "selected": false, "text": "d.addCallback(lambda result: setattr(self, _someVariable, result))\n def p(x): print x\n lambda x: print x\n print sys.stdout.write import __import__" }, { "answer_id": 298045, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 1, "selected": false, "text": "fun = lambda a, b: a ** b # a pointless use of lambda\nmap(fun, someList)\n def fun(a, b): return a ** b # more readable\nmap(fun, someList)\n" }, { "answer_id": 788533, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": ">>> def somefunc(x): return lambda y: x+y\n>>> f = somefunc(10)\n>>> f(2)\n12\n>>> f(4)\n14\n" }, { "answer_id": 1004492, "author": "SingleNegationElimination", "author_id": 65696, "author_profile": "https://Stackoverflow.com/users/65696", "pm_score": 2, "selected": false, "text": "def lambda def (1).__add__ lambda def operator itertools functools" }, { "answer_id": 11988012, "author": "Andy Hayden", "author_id": 1240268, "author_profile": "https://Stackoverflow.com/users/1240268", "pm_score": 4, "selected": false, "text": "In [11]: def f(a, b):\n return a * b\n\nIn [12]: g = lambda x, y: x * y\n\nIn [13]: %%timeit -n 100\nfor a in xrange(n):\n for b in xrange(n):\n f(a, b)\n ....:\n100 loops, best of 3: 285 ms per loop\n\nIn [14]: %%timeit -n 100\nfor a in xrange(n):\n for b in xrange(n):\n g(a, b)\n ....:\n100 loops, best of 3: 298 ms per loop\n\nIn [15]: %%timeit -n 100\nfor a in xrange(n):\n for b in xrange(n):\n (lambda x, y: x * y)(a, b)\n ....:\n100 loops, best of 3: 462 ms per loop\n" }, { "answer_id": 20799400, "author": "Jonathan Livni", "author_id": 348545, "author_profile": "https://Stackoverflow.com/users/348545", "pm_score": 3, "selected": false, "text": "lambda defaultdict from collections import defaultdict\nd = defaultdict(lambda: defaultdict(list))\nd['Foo']['Bar'].append(something)\n def" }, { "answer_id": 33269715, "author": "Glushiator", "author_id": 1284183, "author_profile": "https://Stackoverflow.com/users/1284183", "pm_score": 1, "selected": false, "text": "log.debug(lambda: \"this is my message: %r\" % (some_data,))\n log.debug(\"this is my message: %r\" % (some_data,))\n def mif(condition, when_true, when_false):\n if condition:\n return when_true()\n else:\n return when_false()\n\nmif(a < b, lambda: a + a, lambda: b + b)\n def mif(condition, when_true, when_false):\n if condition:\n return when_true\n else:\n return when_false\n\nmif(a < b, a + a, b + b)\n" }, { "answer_id": 35346979, "author": "Pi Marillion", "author_id": 2892254, "author_profile": "https://Stackoverflow.com/users/2892254", "pm_score": 3, "selected": false, "text": "lambda def def # Using non-functional version.\n\nheading(math.sqrt(v.x * v.x + v.y * v.y), math.atan(v.y / v.x))\n\n# Using lambda with functional version.\n\nfheading(v, lambda v: math.sqrt(v.x * v.x + v.y * v.y), lambda v: math.atan(v.y / v.x))\n\n# Using def with functional version.\n\ndef size(v):\n return math.sqrt(v.x * v.x + v.y * v.y)\n\ndef direction(v):\n return math.atan(v.y / v.x)\n\ndeal_with_headings(v, size, direction)\n lambda lambda v: lambda lambda def lambda def lambda def lambda lambda operator do_something(x, y, lambda x, y: x + y)\ndo_something(x, y, operator.add)\n map filter [e for e in some_array if some_condition(e)]\nfilter(some_array, some_condition)\n lambda def" }, { "answer_id": 46809756, "author": "Ali Rasim Kocal", "author_id": 2230666, "author_profile": "https://Stackoverflow.com/users/2230666", "pm_score": 0, "selected": false, "text": "def lambda my_list.sort(key=lambda o: o.x)\n" }, { "answer_id": 49520604, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 4, "selected": false, "text": "def '<lambda>' def >>> l = lambda: 0\n>>> type(l)\n<class 'function'>\n>>> def foo(): return 0\n... \n>>> type(foo)\n<class 'function'>\n>>> type(foo) is type(l)\nTrue\n __name__ '<lambda>' >>> l.__name__\n'<lambda>'\n>>> foo.__name__\n'foo'\n foo l >>> import pickle\n>>> pickle.loads(pickle.dumps(l))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n_pickle.PicklingError: Can't pickle <function <lambda> at 0x7fbbc0464e18>: \nattribute lookup <lambda> on __main__ failed\n foo >>> pickle.loads(pickle.dumps(foo))\n<function foo at 0x7fbbbee79268>\n foo def foo() -> int:\n \"\"\"a nullary function, returns 0 every time\"\"\"\n return 0\n >>> foo.__annotations__\n{'return': <class 'int'>}\n>>> help(foo)\nHelp on function foo in module __main__:\n\nfoo() -> int\n a nullary function, returns 0 every time\n >>> help(l)\nHelp on function <lambda> in module __main__:\n\n<lambda> lambda (...)\n >>> l.__doc__ = 'nullary -> 0'\n>>> l.__annotations__ = {'return': int}\n>>> help(l)\nHelp on function <lambda> in module __main__:\n\n<lambda> lambda ) -> in\n nullary -> 0\n >>> lambda: if True: 0\n File \"<stdin>\", line 1\n lambda: if True: 0\n ^\nSyntaxError: invalid syntax\n timeit.repeat import timeit\n\ndef return_nullary_lambda(return_value=0):\n return lambda: return_value\n\ndef return_nullary_function(return_value=0):\n def nullary_fn():\n return return_value\n return nullary_fn\n >>> min(timeit.repeat(lambda: return_nullary_lambda(1)))\n0.24312214995734394\n>>> min(timeit.repeat(lambda: return_nullary_function(1)))\n0.24894469301216304\n return_nullary_function def lambda" }, { "answer_id": 51536929, "author": "bhargav patel", "author_id": 4977235, "author_profile": "https://Stackoverflow.com/users/4977235", "pm_score": 2, "selected": false, "text": "# CREATE ONE FUNCTION AND USE IT TO PERFORM MANY OPERATIONS ON SAME TYPE OF DATA STRUCTURE.\ndef variousUse(a,b=lambda x:x[0]):\n return [b(i) for i in a]\n\ndummyList = [(0,1,2,3),(4,5,6,7),(78,45,23,43)]\nvariousUse(dummyList) # extract first element\nvariousUse(dummyList,lambda x:[x[0],x[2],x[3]]) # extract specific indexed element\nvariousUse(dummyList,lambda x:x[0]+x[2]) # add specific elements\nvariousUse(dummyList,lambda x:x[0]*x[2]) # multiply specific elements\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
134,629
<p>In my <code>urls.py</code> file, I have:</p> <pre><code>from myapp import views ... (r'^categories/$', views.categories) </code></pre> <p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p> <p>In a unit test file, I’m trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p> <pre><code>from django.core.urlresolvers import reverse from myapp import views ... url = reverse(views.categories) </code></pre> <p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p> <pre><code>NoReverseMatch: Reverse for '&lt;function categories at 0x1082f30&gt;' with arguments '()' and keyword arguments '{}' not found. </code></pre> <p>It matches just fine if I make the URL pattern a named pattern, like this:</p> <pre><code>url(r'^categories/$', views.categories, 'myapp-categories') </code></pre> <p>And use the pattern name to match it:</p> <pre><code>url = reverse('myapp-categories') </code></pre> <p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse" rel="noreferrer">the <code>reverse</code> documentation</a>, I shouldn’t need to make it a named URL pattern just to use <code>reverse</code>.</p> <p>Any ideas what I’m doing wrong?</p>
[ { "answer_id": 134651, "author": "Jack M.", "author_id": 3421, "author_profile": "https://Stackoverflow.com/users/3421", "pm_score": -1, "selected": false, "text": "urlpatterns = patterns('',\n (r'^no_monkeys/$', 'views.noMonkeys', {}, \"no-monkeys\"),\n (r'^admin/(.*)', admin.site.root),\n)\n" }, { "answer_id": 136721, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 2, "selected": false, "text": "url(r'^no_monkeys/$', 'views.noMonkeys', {}, \"no-monkeys\"),\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20578/" ]
134,644
<p>Suppose you have a collection of <code>Foo</code> classes:</p> <pre><code>class Foo { public string Bar; public string Baz; } List&lt;Foo&gt; foolist; </code></pre> <p>And you want to check this collection to see if another entry has a matching <code>Bar</code>.</p> <pre><code>bool isDuplicate = false; foreach (Foo f in foolist) { if (f.Bar == SomeBar) { isDuplicate = true; break; } } </code></pre> <p><code>Contains()</code> doesn't work because it compares the classes as whole.</p> <p>Does anyone have a better way to do this that works for .NET 2.0?</p>
[ { "answer_id": 134675, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "public class MyFooComparer: IEqualityComparer<Foo> {\n\n public bool Equals(Foo foo1, Foo foo2) {\n return Equals(foo1.Bar, foo2.Bar);\n }\n\n public int GetHashCode(Foo foo) {\n return foo.Bar.GetHashCode();\n }\n}\n\nFoo exampleFoo = new Foo();\nexampleFoo.Bar = \"someBar\";\nif(myList.Contains(exampleFoo, new MyFooComparer())) {\n ...\n}\n" }, { "answer_id": 134679, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "class Foo\n{\n public string Bar;\n public string Baz;\n}\n\nclass FooList : KeyedCollection<string, Foo>\n{\n protected override string GetKeyForItem(Foo item)\n {\n return item.Bar;\n }\n}\n\nFooList fooList;\n" }, { "answer_id": 134700, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "fooList.Exists(item => item.Bar == SomeBar)\n fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});\n" }, { "answer_id": 135131, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "bool contains = foolist.Where(f => f.Bar == someBar).Count() != 0;\n" }, { "answer_id": 74630064, "author": "Majid Shahabfar", "author_id": 2053617, "author_profile": "https://Stackoverflow.com/users/2053617", "pm_score": 0, "selected": false, "text": "public static bool LinqAll<T>(IEnumerable<T> enumerable)\n{\n HashSet<T> set = new();\n\n return !enumerable.All(set.Add);\n}\n\npublic static bool LinqAny<T>(IEnumerable<T> enumerable)\n{\n HashSet<T> set = new();\n\n return enumerable.Any(element => !set.Add(element));\n}\n\npublic static bool LinqDistinct<T>(IEnumerable<T> enumerable)\n{\n return enumerable.Distinct().Count() != enumerable.Count();\n}\n\npublic static bool ToHashSet<T>(IEnumerable<T> enumerable)\n{\n return enumerable.ToHashSet().Count != enumerable.Count();\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
134,650
<p>What is your preferred method for reading through the contents of zipped directories with Perl ?</p>
[ { "answer_id": 135102, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 1, "selected": false, "text": "open(DIR_LISTING, \"gzip -dc concert25.tgz | tar -tf -|\") || die;\nwhile (<DIR_LISTING>) {\n print;\n}\nclose (DIR_LISTING);\n" }, { "answer_id": 135788, "author": "Jeff MacDonald", "author_id": 22374, "author_profile": "https://Stackoverflow.com/users/22374", "pm_score": 2, "selected": false, "text": "require Archive::Zip;\nmy $zip = Archive::Zip->new($somefile);\nfor($zip->memberNames()) {\n print \"$_\\n\";\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759/" ]
134,653
<p><b>Summary:</b> C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...</p> <p><b>The problem</b></p> <p>Today, on a training session on C#, the teacher showed us some code which contained a bug only when run on multiprocessors.</p> <p>I'll summarize to say that sometimes, the compiler or the JIT screws up by calling the finalizer of a C# class object before returning from its called method.</p> <p>The full code, given in Visual C++ 2005 documentation, will be posted as an &quot;answer&quot; to avoid making a very very large questions, but the essential are below:</p> <p>The following class has a &quot;Hash&quot; property which will return a cloned copy of an internal array. At is construction, the first item of the array has a value of 2. In the destructor, its value is set to zero.</p> <p>The point is: If you try to get the &quot;Hash&quot; property of &quot;Example&quot;, you'll get a clean copy of the array, whose first item is still 2, as the object is being used (and as such, not being garbage collected/finalized):</p> <pre><code>public class Example { private int nValue; public int N { get { return nValue; } } // The Hash property is slower because it clones an array. When // KeepAlive is not used, the finalizer sometimes runs before // the Hash property value is read. private byte[] hashValue; public byte[] Hash { get { return (byte[])hashValue.Clone(); } } public Example() { nValue = 2; hashValue = new byte[20]; hashValue[0] = 2; } ~Example() { nValue = 0; if (hashValue != null) { Array.Clear(hashValue, 0, hashValue.Length); } } } </code></pre> <p>But nothing is so simple... The code using this class is wokring inside a thread, and of course, for the test, the app is heavily multithreaded:</p> <pre><code>public static void Main(string[] args) { Thread t = new Thread(new ThreadStart(ThreadProc)); t.Start(); t.Join(); } private static void ThreadProc() { // running is a boolean which is always true until // the user press ENTER while (running) DoWork(); } </code></pre> <p>The DoWork static method is the code where the problem happens:</p> <pre><code>private static void DoWork() { Example ex = new Example(); byte[] res = ex.Hash; // [1] // If the finalizer runs before the call to the Hash // property completes, the hashValue array might be // cleared before the property value is read. The // following test detects that. if (res[0] != 2) { // Oops... The finalizer of ex was launched before // the Hash method/property completed } } </code></pre> <p>Once every 1,000,000 excutions of DoWork, apparently, the Garbage Collector does its magic, and tries to reclaim &quot;ex&quot;, as it is not anymore referenced in the remaning code of the function, and this time, it is faster than the &quot;Hash&quot; get method. So what we have in the end is a clone of a zero-ed byte array, instead of having the right one (with the 1st item at 2).</p> <p>My guess is that there is inlining of the code, which essentially replaces the line marked [1] in the DoWork function by something like:</p> <pre><code> // Supposed inlined processing byte[] res2 = ex.Hash2; // note that after this line, &quot;ex&quot; could be garbage collected, // but not res2 byte[] res = (byte[])res2.Clone(); </code></pre> <p>If we supposed Hash2 is a simple accessor coded like:</p> <pre><code>// Hash2 code: public byte[] Hash2 { get { return (byte[])hashValue; } } </code></pre> <p>So, the question is: <b>Is this supposed to work that way in C#/.NET, or could this be considered as a bug of either the compiler of the JIT?</b></p> <h1>edit</h1> <p>See Chris Brumme's and Chris Lyons' blogs for an explanation.</p> <p><a href="http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx</a><br> <a href="http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx</a></p> <p>Everyone's answer was interesting, but I couldn't choose one better than the other. So I gave you all a +1...</p> <p>Sorry</p> <p>:-)</p> <h1>Edit 2</h1> <p>I was unable to reproduce the problem on Linux/Ubuntu/Mono, despite using the same code on the same conditions (multiple same executable running simultaneously, release mode, etc.)</p>
[ { "answer_id": 134687, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Threading;\n\npublic class Example\n{\n private int nValue;\n public int N { get { return nValue; } }\n\n // The Hash property is slower because it clones an array. When\n // KeepAlive is not used, the finalizer sometimes runs before \n // the Hash property value is read.\n\n private byte[] hashValue;\n public byte[] Hash { get { return (byte[])hashValue.Clone(); } }\n public byte[] Hash2 { get { return (byte[])hashValue; } }\n\n public int returnNothing() { return 25; }\n\n public Example()\n {\n nValue = 2;\n hashValue = new byte[20];\n hashValue[0] = 2;\n }\n\n ~Example()\n {\n nValue = 0;\n\n if (hashValue != null)\n {\n Array.Clear(hashValue, 0, hashValue.Length);\n }\n }\n}\n\npublic class Test\n{\n private static int totalCount = 0;\n private static int finalizerFirstCount = 0;\n\n // This variable controls the thread that runs the demo.\n private static bool running = true;\n\n // In order to demonstrate the finalizer running first, the\n // DoWork method must create an Example object and invoke its\n // Hash property. If there are no other calls to members of\n // the Example object in DoWork, garbage collection reclaims\n // the Example object aggressively. Sometimes this means that\n // the finalizer runs before the call to the Hash property\n // completes. \n\n private static void DoWork()\n {\n totalCount++;\n\n // Create an Example object and save the value of the \n // Hash property. There are no more calls to members of \n // the object in the DoWork method, so it is available\n // for aggressive garbage collection.\n\n Example ex = new Example();\n\n // Normal processing\n byte[] res = ex.Hash;\n\n // Supposed inlined processing\n //byte[] res2 = ex.Hash2;\n //byte[] res = (byte[])res2.Clone();\n\n // successful try to keep reference alive\n //ex.returnNothing();\n\n // Failed try to keep reference alive\n //ex = null;\n\n // If the finalizer runs before the call to the Hash \n // property completes, the hashValue array might be\n // cleared before the property value is read. The \n // following test detects that.\n\n if (res[0] != 2)\n {\n finalizerFirstCount++;\n Console.WriteLine(\"The finalizer ran first at {0} iterations.\", totalCount);\n }\n\n //GC.KeepAlive(ex);\n }\n\n public static void Main(string[] args)\n {\n Console.WriteLine(\"Test:\");\n\n // Create a thread to run the test.\n Thread t = new Thread(new ThreadStart(ThreadProc));\n t.Start();\n\n // The thread runs until Enter is pressed.\n Console.WriteLine(\"Press Enter to stop the program.\");\n Console.ReadLine();\n\n running = false;\n\n // Wait for the thread to end.\n t.Join();\n\n Console.WriteLine(\"{0} iterations total; the finalizer ran first {1} times.\", totalCount, finalizerFirstCount);\n }\n\n private static void ThreadProc()\n {\n while (running) DoWork();\n }\n}\n" }, { "answer_id": 134710, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "byte[] res = ex.Hash;\n" }, { "answer_id": 134756, "author": "Palad1", "author_id": 22187, "author_profile": "https://Stackoverflow.com/users/22187", "pm_score": 1, "selected": false, "text": "private static void DoWork()\n{\n Example ex = new Example();\n\n byte[] res = ex.Hash; // [1]\n\n // If the finalizer runs before the call to the Hash \n // property completes, the hashValue array might be\n // cleared before the property value is read. The \n // following test detects that.\n\n if (res[0] != 2) // NOTE\n {\n // Oops... The finalizer of ex was launched before\n // the Hash method/property completed\n }\n GC.KeepAlive(ex); // keep our instance alive in case we need it.. uh.. we don't\n}\n" }, { "answer_id": 134758, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "GC.KeepAlive(ex);\n" }, { "answer_id": 135598, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 1, "selected": false, "text": "class C {<br>\n IntPtr _handle;\n Static void OperateOnHandle(IntPtr h) { ... }\n void m() {\n OperateOnHandle(_handle);\n ...\n }\n ...\n}\n\nclass Other {\n void work() {\n if (something) {\n C aC = new C();\n aC.m();\n ... // most guess here\n } else {\n ...\n }\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
134,655
<p>What are the advantages/disadvantages of the major Ruby VMs (things like features, compatibility, performance, and quirks?) I know there are also some bonus features like being able to use Java interfaces through JRuby, too. Those would also be helpful to note. Does any VM have a clear advantage at this point, and in what contexts?</p>
[ { "answer_id": 134687, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Threading;\n\npublic class Example\n{\n private int nValue;\n public int N { get { return nValue; } }\n\n // The Hash property is slower because it clones an array. When\n // KeepAlive is not used, the finalizer sometimes runs before \n // the Hash property value is read.\n\n private byte[] hashValue;\n public byte[] Hash { get { return (byte[])hashValue.Clone(); } }\n public byte[] Hash2 { get { return (byte[])hashValue; } }\n\n public int returnNothing() { return 25; }\n\n public Example()\n {\n nValue = 2;\n hashValue = new byte[20];\n hashValue[0] = 2;\n }\n\n ~Example()\n {\n nValue = 0;\n\n if (hashValue != null)\n {\n Array.Clear(hashValue, 0, hashValue.Length);\n }\n }\n}\n\npublic class Test\n{\n private static int totalCount = 0;\n private static int finalizerFirstCount = 0;\n\n // This variable controls the thread that runs the demo.\n private static bool running = true;\n\n // In order to demonstrate the finalizer running first, the\n // DoWork method must create an Example object and invoke its\n // Hash property. If there are no other calls to members of\n // the Example object in DoWork, garbage collection reclaims\n // the Example object aggressively. Sometimes this means that\n // the finalizer runs before the call to the Hash property\n // completes. \n\n private static void DoWork()\n {\n totalCount++;\n\n // Create an Example object and save the value of the \n // Hash property. There are no more calls to members of \n // the object in the DoWork method, so it is available\n // for aggressive garbage collection.\n\n Example ex = new Example();\n\n // Normal processing\n byte[] res = ex.Hash;\n\n // Supposed inlined processing\n //byte[] res2 = ex.Hash2;\n //byte[] res = (byte[])res2.Clone();\n\n // successful try to keep reference alive\n //ex.returnNothing();\n\n // Failed try to keep reference alive\n //ex = null;\n\n // If the finalizer runs before the call to the Hash \n // property completes, the hashValue array might be\n // cleared before the property value is read. The \n // following test detects that.\n\n if (res[0] != 2)\n {\n finalizerFirstCount++;\n Console.WriteLine(\"The finalizer ran first at {0} iterations.\", totalCount);\n }\n\n //GC.KeepAlive(ex);\n }\n\n public static void Main(string[] args)\n {\n Console.WriteLine(\"Test:\");\n\n // Create a thread to run the test.\n Thread t = new Thread(new ThreadStart(ThreadProc));\n t.Start();\n\n // The thread runs until Enter is pressed.\n Console.WriteLine(\"Press Enter to stop the program.\");\n Console.ReadLine();\n\n running = false;\n\n // Wait for the thread to end.\n t.Join();\n\n Console.WriteLine(\"{0} iterations total; the finalizer ran first {1} times.\", totalCount, finalizerFirstCount);\n }\n\n private static void ThreadProc()\n {\n while (running) DoWork();\n }\n}\n" }, { "answer_id": 134710, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "byte[] res = ex.Hash;\n" }, { "answer_id": 134756, "author": "Palad1", "author_id": 22187, "author_profile": "https://Stackoverflow.com/users/22187", "pm_score": 1, "selected": false, "text": "private static void DoWork()\n{\n Example ex = new Example();\n\n byte[] res = ex.Hash; // [1]\n\n // If the finalizer runs before the call to the Hash \n // property completes, the hashValue array might be\n // cleared before the property value is read. The \n // following test detects that.\n\n if (res[0] != 2) // NOTE\n {\n // Oops... The finalizer of ex was launched before\n // the Hash method/property completed\n }\n GC.KeepAlive(ex); // keep our instance alive in case we need it.. uh.. we don't\n}\n" }, { "answer_id": 134758, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "GC.KeepAlive(ex);\n" }, { "answer_id": 135598, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 1, "selected": false, "text": "class C {<br>\n IntPtr _handle;\n Static void OperateOnHandle(IntPtr h) { ... }\n void m() {\n OperateOnHandle(_handle);\n ...\n }\n ...\n}\n\nclass Other {\n void work() {\n if (something) {\n C aC = new C();\n aC.m();\n ... // most guess here\n } else {\n ...\n }\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9128/" ]
134,656
<p>Where can I find a Perl module for converting a Perl data structure into a JavaScript one?</p> <p>e.g. this is my code (Mason):</p> <pre><code>% # convert our @cti data structure into a javascript one var cti = [ % foreach my $cti_category (@cti) { { label: "&lt;% $cti_category-&gt;{'label'} %&gt;", value: "&lt;% $cti_category-&gt;{'value'} %&gt;", children: [ % foreach my $cti_type (@{$cti_category-&gt;{'children'}}) { { label: "&lt;% $cti_type-&gt;{'label'} %&gt;", value: "&lt;% $cti_type-&gt;{'value'} %&gt;", }, % } ] }, % } ]; </code></pre> <p>is there a module for this?</p>
[ { "answer_id": 135182, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 4, "selected": false, "text": "use JSON::Any;\n\nmy $j = JSON::Any->new;\n\n$json = $j->objToJson($perl_data);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8913/" ]
134,658
<p>I am trying to encrypt the "system.web.membership" element within the Web.Config of our .Net application to secure username and password to Active Directory. I am using the aspnet_regiis command to encrypt, and have tried several different strings for the value of the "pe" option with no success. I have successfully encrypted the "connectstrings" element on my web.config.</p> <p>Cmd</p> <pre>C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "connectionStrings" -site MySite -app /MyApp Encrypting configuration section... Succeeded! C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "membership" -site MySite -app /MyApp Encrypting configuration section... The configuration section 'membership' was not found. Failed! C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "system.web.membership" -site MySite -app /MyApp Encrypting configuration section... The configuration section 'system.web.membership' was not found. Failed!</pre> <p>Web.Config</p> <pre><code>&lt;configuration&gt; ... &lt;system.web&gt; ... &lt;authentication mode="Forms"&gt; &lt;forms name=".ADAuthCookie" timeout="30"/&gt; &lt;/authentication&gt; &lt;authorization&gt; &lt;deny users="?"/&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;membership defaultProvider="MyADMembershipProvider"&gt; &lt;providers&gt; &lt;add name="MyADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString" connectionUsername="MyUserName" connectionPassword="MyPassowrd"/&gt; &lt;/providers&gt; &lt;/membership&gt; ... &lt;/system.web&gt; ... &lt;/configuration&gt; </code></pre> <p>So what gives? What am I missing?</p>
[ { "answer_id": 134733, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 4, "selected": true, "text": "system.web/membership membership system.web.membership" }, { "answer_id": 638730, "author": "Ben Mills", "author_id": 203, "author_profile": "https://Stackoverflow.com/users/203", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\"?>\n<configuration>\n <system.net>\n <mailSettings>\n <smtp>\n <network host=\"myhost\" port=\"25\" userName=\"myusername\" password=\"mypassword\" />\n </smtp>\n </mailSettings>\n </system.net>\n</configuration>\n aspnet_regiis.exe -pef \"system.net/mailSettings/smtp\" \"path_to_site\" -prov \"DataProtectionConfigurationProvider\"\n aspnet_regiis.exe -pef \"system.net/mailSettings\" \"path_to_site\" -prov \"DataProtectionConfigurationProvider\"\n\naspnet_regiis.exe -pef \"system.net\" \"path_to_site\" -prov \"DataProtectionConfigurationProvider\"\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ]
134,673
<p>I've got a VS2008 deployment project that builds an installer for a couple of Windows services.</p> <p>Each service references several different projects:</p> <pre> CustomerName.MailSendingService -> CustomerName.Network -> CustomerName.Data -> CustomerName.Security CustomerName.ProductIntegrationService -> CustomerName.Core -> CustomerName.Security </pre> <p>The Windows service projects, the projects they reference, and the deployment project are all in the same VS2008 solution.</p> <p>I've added the primary output from the Windows service projects in the deployment project's file system editor. </p> <p>My expectation is that the primary output for the Windows service projects would include the DLLs from the referenced projects. However, when the deployment project is built, the DLL from one of the referenced projects is missing. (<code>CustomerName.ProductIntegrationService</code> is missing <code>CustomerName.Security</code>) </p> <p>Maddeningly, the DLLs for the other projects referenced by the Windows service are present; just one project's output is missing.</p> <p>(Edit) I've verified that the reference is set to Copy Local in the reference properties window. The DLL for the referenced project is placed in the windows service project's <code>bin\Release</code> folder, but isn't packaged in the MSI file built for the deployment project.</p> <p>(Edit 2) Following Joseph Daigle's suggestion, I checked that the dependency is in the dependencies list for the primary output, and it's not marked "excluded," so that doesn't appear to be the cause of this issue.</p> <p>Why would just one project's output be missing?</p>
[ { "answer_id": 152295, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 0, "selected": false, "text": "public const string LockPanelUrn = \"ApplicationRack.LockPanel\";\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18102/" ]
134,680
<p>I have a DataGrid, with an ItemTemplate that has an image and label. In the EditItemTemplate the label is replaced by a textbox. My problem is that the edit template only shows when I click the Edit button the second time. What gives?</p>
[ { "answer_id": 134715, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 1, "selected": false, "text": "If Not Page.IsPostBack() Then\n DoDataBinding()\nEnd If\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
134,683
<p>This might be a stupid question but if there's a better or proper way to do this, I'd love to learn it.</p> <p>I have run across this a few times, including recently, where small spaces show up in the rendered version of my HTML page. Intuitively I think these should not be there because outside of text or entities the formatting of a page's HTML shouldn't matter but apparently it does.</p> <p>What I'm referring to is this - I have some Photoshop file from the client on how they want their site to look. They want it to look basically pixel perfect to the image in this file. </p> <p>One of the places in the page calls for a menu bar, where each one does the changing bit on hovering, acts like a hyperlink, etc. In the Photoshop file this is one long bar, so a cheap and easy way to do this is to just split that segment into multiple images and then place them next to each other in the file. </p> <p>So instinctively I lay it out like so (there's more to it but this is the gist)</p> <pre><code>&lt;a href="page1.html"&gt; &lt;img src="image1.png" /&gt; &lt;/a&gt; &lt;a href="page2.html"&gt; &lt;img src="image2.png" /&gt; &lt;/a&gt; &lt;a href="page3.html"&gt; &lt;img src="image3.png" /&gt; &lt;/a&gt; </code></pre> <p>and so forth. </p> <p>The problem is the images have this tiny space between them which is unacceptable since the client wants this thing pixel-perfect (and it just plain looks bad).</p> <p>One way to get it to render properly is to remove the carriage returns between the images</p> <pre><code>&lt;a href="page1.html"&gt; &lt;img src="image1.png" /&gt; &lt;/a&gt; &lt;a href="page2.html"&gt; &lt;img src="image2.png" /&gt; &lt;/a&gt; &lt;a href="page3.html"&gt; &lt;img src="image3.png" /&gt; &lt;/a&gt; </code></pre> <p>Which makes the images go right up against each other (the desired effect) but it makes the line incredibly long and the code more difficult to maintain (it wraps here in SO and this is a simplified version - the real one has longer filenames and JavaScript sprinkled in to do the hovering).</p> <p>It seems to me that this shouldn't happen but it looks like the carriage return in the HTML is being rendered as a small empty space. And this happens in all browsers, looks like.</p> <p>Am I right or wrong for thinking the two snippets above should render the same? And is there something I'm doing wrong? Maybe saving the file with the wrong encoding? Should I make every one of these links a perfectly positioned CSS element instead?</p>
[ { "answer_id": 134701, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 5, "selected": true, "text": "<a href=\"page1.html\"><img src=\"image1.png\" \n/></a><a href=\"page2.html\"><img src=\"image2.png\" \n/></a><a href=\"page3.html\"><img src=\"image3.png\" \n/></a>\n" }, { "answer_id": 134706, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 2, "selected": false, "text": " <a href=\"...\"><img src=\"..\" /></a\n ><a href=\"...\"><img src=\"..\" /></a\n ><a href=\"...\"><img src=\"..\" /></a\n" }, { "answer_id": 134714, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<style>\n a.together {\n float:left;\n }\n</style>\n\n<a class='together' href=\"page1.html\"><img src=\"image1.png\" /></a>\n<a class='together' href=\"page2.html\"><img src=\"image2.png\" /></a>\n<a class='together' href=\"page3.html\"><img src=\"image3.png\" /></a>\n" }, { "answer_id": 134739, "author": "Kevin Chan", "author_id": 1877, "author_profile": "https://Stackoverflow.com/users/1877", "pm_score": 2, "selected": false, "text": "a { display: block; float: left; }\n #nav a { display: block; float: left; }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
134,691
<p>I am trying to create a jar file which includes some class and java files needed, but I also would like to include some extra xml, xsl, html, txt (README) files.</p> <p>I am using Eclipse on Windows XP.</p> <p>Is there an easy way for me to set up a directory structure and package all my files into a jar?</p>
[ { "answer_id": 134744, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<target name=\"makejar\" depends=\"compile, copyfiles\">\n\n <jar destfile=\"${jars.dir}/myjarfile.jar\" index=\"true\" basedir=\"${build.dir}\" />\n\n</target>\n" }, { "answer_id": 134751, "author": "Sam Martin", "author_id": 19088, "author_profile": "https://Stackoverflow.com/users/19088", "pm_score": 1, "selected": false, "text": "jar" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
134,698
<p>I always felt that expecting exceptions to be thrown on a regular basis and using them as flow logic was a bad thing. Exceptions feel like they should be, well, the "<em>exception</em>". If you're expecting and planning for an exception, that would seem to indicate that your code should be refactored, at least in .NET...<br /> However. A recent scenario gave me pause. I posted this on msdn a while ago, but I'd like to generate more discussion about it and this is the perfect place!<br /> <br /> So, say you've got a database table which has a foreign key for several other tables (in the case that originally prompted the debate, there were 4 foreign keys pointing to it). You want to allow the user to delete, but only if there are NO foreign key references; you DON'T want to cascade delete.<br /> I normally just do a check to see if there are any references, and if there are, I inform the user instead of doing the delete. It's very easy and relaxing to write that in LINQ as related tables are members on the object, so Section.Projects and Section.Categories and et cetera is nice to type with intellisense and all...<br /> But the fact is that LINQ then has to hit potentially all 4 tables to see if there are any result rows pointing to that record, and hitting the database is obviously always a relatively expensive operation.<br /> <br/> The lead on this project asked me to change it to just catch a SqlException with a code of 547 (foreign key constraint) and deal with it that way.<br /> <br/> I was...<br/> <em>resistant</em>.<br /> <br/> But in this case, it's probably a lot more efficient to swallow the exception-related overhead than to swallow the 4 table hits... Especially since we have to do the check in every case, but we're spared the exception in the case when there are no children...<br /> Plus the database really should be the one responsible for handling referential integrity, that's its job and it does it well...<br /> So they won and I changed it.<br/> <br /> On some level it still feels <em>wrong</em> to me though.<br /> <br/> What do you guys think about expecting and intentionally handling exceptions? Is it okay when it looks like it'll be more efficient than checking beforehand? Is it more confusing to the next developer looking at your code, or less confusing? Is it safer, since the database might know about new foreign key constraints that the developer might not think to add a check for? Or is it a matter of perspective on what exactly you think best practice is?<br /></p>
[ { "answer_id": 134766, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 3, "selected": true, "text": "File.Exists File.Exists" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
134,712
<p>I would like to sort a matrix according to a particular column. There is a <code>sort</code> function, but it sorts all columns independently.</p> <p>For example, if my matrix <code>data</code> is:</p> <pre><code> 1 3 5 7 -1 4 </code></pre> <p>Then the desired output (sorting by the first column) would be:</p> <pre><code>-1 4 1 3 5 7 </code></pre> <p>But the output of <code>sort(data)</code> is:</p> <pre><code>-1 3 1 4 5 7 </code></pre> <p>How can I sort this matrix by the first column?</p>
[ { "answer_id": 135115, "author": "Kena", "author_id": 8027, "author_profile": "https://Stackoverflow.com/users/8027", "pm_score": 7, "selected": true, "text": ">> sortrows(data,1)\n\nans =\n\n -1 4\n 1 3\n 5 7\n" }, { "answer_id": 35832813, "author": "AlessioX", "author_id": 5149764, "author_profile": "https://Stackoverflow.com/users/5149764", "pm_score": 3, "selected": false, "text": "sortrows() [~,idx]=sort(data(:,1));\n data=data(idx,:)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9425/" ]
134,727
<p>What are the key differences between <a href="http://www.w3.org/TR/REC-html40/" rel="noreferrer">HTML4</a> and <a href="http://www.w3.org/html/wg/html5/" rel="noreferrer">HTML5 draft</a>?</p> <p>Please keep the answers related to changed syntax and added/removed html elements.</p>
[ { "answer_id": 577778, "author": "Xanthir", "author_id": 58347, "author_profile": "https://Stackoverflow.com/users/58347", "pm_score": 9, "selected": true, "text": "<canvas> <video> <audio> <strong> <em> <b> <i> <article> <section> <header> <aside> <nav> <div> </div> </header> </article>" }, { "answer_id": 799851, "author": "Mathias Bynens", "author_id": 96656, "author_profile": "https://Stackoverflow.com/users/96656", "pm_score": 2, "selected": false, "text": "text/html" }, { "answer_id": 4773978, "author": "Viktor", "author_id": 336806, "author_profile": "https://Stackoverflow.com/users/336806", "pm_score": 4, "selected": false, "text": "contenteditable draggable" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21473/" ]
134,728
<p>I have a class declared as follows:</p> <pre><code>Public MustInherit Container(Of T As {New, BaseClass}) Inherits ArrayList(Of T) </code></pre> <p>I have classes that inherit this class.</p> <p>I have another class that I must pass instances in this method:</p> <pre><code>Public Sub LoadCollection(Of T As {BaseClass, New})(ByRef Collection As Container(Of T)) </code></pre> <p>I need to store the passed in object in a global variable, but i can't simply declare it:</p> <pre><code>Private _Container as Collection(Of BaseClass) </code></pre> <p>What is the syntax to declare this object?</p>
[ { "answer_id": 137165, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Private _Container as Container(Of BaseClass)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
134,731
<p>Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:</p> <pre><code>class foo { private: std::string name_; public: std::string name() { return name_; } }; </code></pre> <p>Surely the getter would be better returning a <code>const std::string&amp;</code>? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems?</p>
[ { "answer_id": 134777, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 7, "selected": true, "text": "foo *pFoo = new foo;\nconst std::string &myName = pFoo->getName();\ndelete pFoo;\ncout << myName; // error! dangling reference\n" }, { "answer_id": 136053, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "const std::string & str = myObject.getSomeString() ;\n std::string const std::string & MyObject * myObject = new MyObject(\"My String\") ;\nconst std::string & str = myObject->getSomeString() ;\ndelete myObject ;\n// Use str... which references a destroyed object.\n" }, { "answer_id": 701398, "author": "Frank", "author_id": 60628, "author_profile": "https://Stackoverflow.com/users/60628", "pm_score": 3, "selected": false, "text": "std::string std::string name = obj.name(); shared_ptr shared_ptr get()" }, { "answer_id": 5095204, "author": "Ogre Psalm33", "author_id": 13140, "author_profile": "https://Stackoverflow.com/users/13140", "pm_score": 5, "selected": false, "text": "std::string const char* name() foo myFoo = getFoo(); // Get the foo from somewhere.\nconst char* fooCName = foo.name().c_str(); // Woops! foo.name() creates a temporary that's destructed as soon as this line executes!\njniEnv->NewStringUTF(fooCName); // No good, fooCName was released when the temporary was deleted.\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
134,741
<p>Is there anyway to have items in an ASP.NET DropDownList have either their Text or Value bound to a method on the source rather than a property? </p>
[ { "answer_id": 134879, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": -1, "selected": false, "text": "<asp:DropDownList ID=\"ddlType\" runat=\"server\" Width=\"250px\" AppendDataBoundItems=\"true\" DataSourceID=\"dsTypeList\" DataTextField=\"Description\" DataValueField=\"ID\">\n <asp:ListItem Value=\"0\">All Categories</asp:ListItem>\n</asp:DropDownList><br />\n<asp:ObjectDataSource ID=\"dsTypeList\" runat=\"server\" DataObjectTypeName=\"MyType\" SelectMethod=\"GetList\" TypeName=\"MyTypeManager\">\n</asp:ObjectDataSource>\n" }, { "answer_id": 1593557, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 2, "selected": false, "text": "<asp:DropDownList ID=\"dropDownList\" runat=\"server\" DataSourceID=\"dataSource\" DataValueField=\"DataValueField\" DataTextField=\"DataTextField\" />\n<asp:ObjectDataSource ID=\"dataSource\" runat=\"server\" SelectMethod=\"SelectForDataSource\" TypeName=\"CategoryDao\" />\n\npublic IEnumerable<object> SelectForDataSource()\n{\n return _repository.Search().Select(x => new{\n DataValueField = x.CategoryId, \n DataTextField = x.ToString() // Here is the trick!\n }).Cast<object>();\n}\n" }, { "answer_id": 8528796, "author": "Toni Rossmann", "author_id": 892836, "author_profile": "https://Stackoverflow.com/users/892836", "pm_score": 0, "selected": false, "text": "public class RTIDropDownList : DropDownList\n{\n public delegate void ItemDataBoundDelegate( ListItem item, object dataRow );\n [Description( \"ItemDataBound Event\" )]\n public event ItemDataBoundDelegate ItemDataBound;\n\n protected override void PerformDataBinding( IEnumerable dataSource )\n {\n if ( dataSource != null )\n {\n if ( !AppendDataBoundItems )\n this.Items.Clear();\n\n IEnumerator e = dataSource.GetEnumerator();\n\n while ( e.MoveNext() )\n {\n object row = e.Current;\n\n var item = new ListItem( DataBinder.Eval( row, DataTextField, DataTextFormatString ).ToString(), DataBinder.Eval( row, DataValueField ).ToString() );\n\n this.Items.Add( item );\n\n if ( ItemDataBound != null ) // \n ItemDataBound( item, row );\n }\n }\n }\n}\n" }, { "answer_id": 15035854, "author": "Pascal Carmoni", "author_id": 2101369, "author_profile": "https://Stackoverflow.com/users/2101369", "pm_score": 1, "selected": false, "text": " <asp:DropDownList ID=\"DropDownListJour1\" runat=\"server\">\n </asp:DropDownList>\n <br />\n <asp:DropDownList ID=\"DropDownListJour2\" runat=\"server\">\n </asp:DropDownList>\n protected void Page_Load(object sender, EventArgs e)\n {\n //Exemple with value different same as text (dropdown)\n DropDownListJour1.DataSource = jour.ListSameValueText(); \n DropDownListJour1.DataBind();\n\n //Exemple with value different of text (dropdown)\n DropDownListJour2.DataSource = jour.ListDifferentValueText();\n DropDownListJour2.DataValueField = \"Key\";\n DropDownListJour2.DataTextField = \"Value\";\n DropDownListJour2.DataBind(); \n }\n public class jour\n{\n\n public static string[] ListSameValueText()\n {\n string[] myarray = {\"a\",\"b\",\"c\",\"d\",\"e\"} ;\n return myarray;\n }\n\n public static Dictionary<int, string> ListDifferentValueText()\n {\n var joursem2 = new Dictionary<int, string>();\n joursem2.Add(1, \"Lundi\");\n joursem2.Add(2, \"Mardi\");\n joursem2.Add(3, \"Mercredi\");\n joursem2.Add(4, \"Jeudi\");\n joursem2.Add(5, \"Vendredi\");\n return joursem2;\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11097/" ]
134,742
<p>I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header.</p> <pre><code>&lt;rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/&gt; &lt;rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}" var="fieldValues" rowKeyVar="rowKey"&gt; &lt;rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx"&gt; &lt;f:facet name="header"&gt; &lt;h:outputText value="#{column}"/&gt; &lt;/f:facet&gt; &lt;h:outputText value="#{classFieldValues[idx]}" /&gt; &lt;/rich:columns&gt; &lt;/rich:dataTable&gt; </code></pre> <p>I already have a method on the bean for executing the sort.</p> <pre><code>public void sort(int column) </code></pre>
[ { "answer_id": 135958, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "<h:outputText value=\"#{column}\">\n <a4j:support event=\"onclick\" action=\"#{pageDataModel.sort(idx)}\"\n eventsQueue=\"instancesQueue\"\n reRender=\"instanceList,instanceListScroller\"/>\n</h:outputText>\n <h:outputText value=\"#{column}\" styleClass=\"#{pageDataModel.getOrderClass(idx)}\" >\n <a4j:support event=\"onclick\" action=\"#{pageDataModel.sort(idx)}\"\n eventsQueue=\"instancesQueue\"\n reRender=\"instanceList,instanceListScroller\"/>\n</h:outputText>\n" }, { "answer_id": 2835046, "author": "Philipp", "author_id": 341340, "author_profile": "https://Stackoverflow.com/users/341340", "pm_score": 1, "selected": false, "text": "modify()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
134,746
<p>What is the difference between <code>bool</code> and <code>Boolean</code> types in C#?</p>
[ { "answer_id": 134760, "author": "bhinks", "author_id": 5877, "author_profile": "https://Stackoverflow.com/users/5877", "pm_score": 6, "selected": false, "text": "bool System.Boolean" }, { "answer_id": 134771, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 10, "selected": true, "text": "bool System.Boolean int System.Int32" }, { "answer_id": 134773, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "bool System.Boolean Boolean Boolean" }, { "answer_id": 19256129, "author": "B. Clay Shannon-B. Crow Raven", "author_id": 875317, "author_profile": "https://Stackoverflow.com/users/875317", "pm_score": -1, "selected": false, "text": "namespace DuckbillServerWebAPI.Models\n{\n public class Expense\n {\n . . .\n public bool CanUseOnItems { get; set; }\n }\n}\n namespace DuckbillServerWebAPI.Models\n{\n public class Expense\n {\n . . .\n public Boolean CanUseOnItems { get; set; }\n }\n}\n" }, { "answer_id": 25122137, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "Boolean using System; System.Boolean bool using System;" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
134,748
<p>I am currently working on a program to immediately clear the list of previously-run-commands which appears in the Windows <em>Start</em> -> <em>Run</em> dialog. The procedure for clearing this list by removing the <em>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU</em> key is <a href="http://support.microsoft.com/kb/142298" rel="nofollow noreferrer">well documented</a>; however, before these changes take effect, it seems to be necessary to do one of the following:</p> <ol> <li>Restart the computer</li> <li>Select <em>Start</em> -> <em>Shut down</em>, and then select <em>Cancel</em>.</li> </ol> <p>Neither of these is ideal for the task I am trying to accomplish: #1 is extremely disruptive to the user, and #2 appears to require additional user interaction.</p> <p>Does anyone know how to immediately (and programmatically) force a reload of this information without requiring any user interaction, <em>while also minimizing disruption of the user's other activities</em>? <strong>I would like for the user's Run history to be cleared out immediately after executing my program, <em>without</em> requiring any further action on their part (such as using the "Shut Down" -> "Cancel" trick in #2 above) or forcing a reboot.</strong></p> <p>Or, to approach the problem from a different angle: When clicking <em>Start</em> -> <em>Shut Down</em> -> <em>Cancel</em>, Windows Explorer reloads the RunMUI key. <strong>Is there a way to force a similar reload without having the user select <em>Shut Down</em> and then <em>Cancel</em>?</strong></p> <h2>Things I have already tried:</h2> <ul> <li>Monitoring the explorer.exe status using <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">procmon</a> while selecting <em>Shutdown</em> and then <em>Cancel</em>. I see Explorer writing to the RunMRU key, but have not been able to determine what triggers this.</li> <li>Numerous Google searches along the lines of "reload runmru without reboot". Most results still recommend method #1 above, although a few suggest #2.</li> <li>Limited MSDN API examination. The <a href="http://msdn.microsoft.com/en-us/library/ms724867(VS.85).aspx" rel="nofollow noreferrer">RegFlushKey</a> call appears promising, but I haven't ever used it before, so I don't know if it will apply to registry information cached by different processes.</li> </ul> <p>Any suggestions or other information would be greatly appreciated.</p>
[ { "answer_id": 3842993, "author": "csauve", "author_id": 65580, "author_profile": "https://Stackoverflow.com/users/65580", "pm_score": 0, "selected": false, "text": " using System.Diagnostics;\n\n Process[] procs = Process.GetProcessesByName(\"explorer\");\n foreach (Process proc in procs)\n {\n proc.Kill();\n }\n\n Process.Start(\"explorer.exe\");\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12657/" ]
134,778
<p>I work for a product development company.We first do internal releases,and then public release.I was wondering, how other product developing companies manage their release? How do you give release number? Tag the source control?</p>
[ { "answer_id": 134826, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 1, "selected": false, "text": "R_2_1 R_2_1_0 R_X_Y R_2_1_1 Mainline\n|\n|- R_2_1\n| |\n| |-R_2_1_0 (locked)\n| |\n| |\n| |-R_2_1_1 (locked)\n| |\n. .\n. .\n. .\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
134,796
<p>I know I can compile individual source files, but sometimes -- say, when editing a header file used by many <code>.cpp</code> files -- multiple source files need to be recompiled. That's what Build is for.</p> <p>Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes this just results in many failed compiles. I usually just watch for errors and hit ctrl-break to stop the build manually.</p> <p>Is there a way to configure it such the build stops at the <strong>very first compile error</strong> (not the first failed project build) automatically?</p>
[ { "answer_id": 194748, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 4, "selected": false, "text": "Private Sub BuildEvents_OnBuildProjConfigDone(ByVal Project As String, ByVal ProjectConfig As String, ByVal Platform As String, ByVal SolutionConfig As String, ByVal Success As Boolean) Handles BuildEvents.OnBuildProjConfigDone\n\n If Success = False Then\n DTE.ExecuteCommand(\"Build.Cancel\")\n End If\n\nEnd Sub\n" }, { "answer_id": 1085245, "author": "Eric", "author_id": 119301, "author_profile": "https://Stackoverflow.com/users/119301", "pm_score": 6, "selected": true, "text": "Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated\n If Not (pPane.Name = \"Build\") Then Exit Sub\n\n pPane.TextDocument.Selection.SelectAll()\n Dim Context As String = pPane.TextDocument.Selection.Text\n pPane.TextDocument.Selection.EndOfDocument()\n\n Dim found As Integer = Context.IndexOf(\": error \")\n\n If found > 0 Then\n DTE.ExecuteCommand(\"Build.Cancel\")\n End If\n\nEnd Sub \n" }, { "answer_id": 4757629, "author": "Anders Glent Buch", "author_id": 584300, "author_profile": "https://Stackoverflow.com/users/584300", "pm_score": 3, "selected": false, "text": "Public Module EnvironmentEvents\n Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated\n If Not (pPane.Name = \"Build\") Then Exit Sub\n\n Dim foundError As Boolean = pPane.TextDocument.StartPoint.CreateEditPoint().FindPattern(\": error\")\n Dim foundFatal As Boolean = pPane.TextDocument.StartPoint.CreateEditPoint().FindPattern(\": fatal error\")\n\n If foundError Or foundFatal Then\n DTE.ExecuteCommand(\"Build.Cancel\")\n End If\n End Sub\nEnd Module\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
134,815
<p>Is there a way to listen for a javascript function to exit? A trigger that could be setup when a function has completed?</p> <p>I am attempting to use a user interface obfuscation technique (BlockUI) while an AJAX object is retrieving data from the DB, but the function doesn't necessarily execute last, even if you put it at the end of the function call. </p> <p>Example:</p> <pre><code>function doStuff() { blockUI(); ajaxCall(); unblockUI(); }; </code></pre> <p>Is there a way for doStuff to listen for ajaxCall to complete, before firing the unBlockUI? As it is, it processes the function linearly, calling each object in order, then a separate thread is spawned to complete each one. So, though my AJAX call might take 10-15 seconds to complete, I am only blocking the user for just a split-second, due to the linear execution of the function.</p> <p>There are less elegant ways around this...putting a loop to end only when a return value set by the AJAX function is set to true, or something of that nature. But that seems unnecessarily complicated and inefficient.</p>
[ { "answer_id": 134839, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 3, "selected": true, "text": "function ajaxCall(callback){\n //do ajax stuff...\n callback();\n}\n function doStuff(){\n blockUI();\n ajaxCall(unblockUI);\n}\n" }, { "answer_id": 136995, "author": "Ahmad", "author_id": 22449, "author_profile": "https://Stackoverflow.com/users/22449", "pm_score": 0, "selected": false, "text": "function doStuff(){\n\n blockUI();\n\n jQuery.ajax({\n url: \"example.com\",\n type: \"POST\", //you can use GET or POST\n success: function(){\n\n unblockUI();\n }\n });\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5405/" ]
134,833
<p>I have an <em>index.php</em> file which has to process many different file types. How do I guess the filetype based on the <code>REQUEST_URI</code>?</p> <p>If I request <code>http://site/image.jpg</code>, and all requests redirect through <em>index.php</em>, which looks like this</p> <pre><code>&lt;?php include('/www/site'.$_SERVER['REQUEST_URI']); ?&gt; </code></pre> <p>How would I make that work correctly?</p> <p>Should I test based on the extension of the file requested, or is there a way to get the filetype?</p>
[ { "answer_id": 134916, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 0, "selected": false, "text": "[getimagesize()][1] mime_content_type()" }, { "answer_id": 134930, "author": "Eric_WVGG", "author_id": 82944, "author_profile": "https://Stackoverflow.com/users/82944", "pm_score": 5, "selected": false, "text": "$file = escapeshellarg($filename);\n$mime = shell_exec(\"file -bi \" . $file);\n$filename should probably include the absolute path.\n" }, { "answer_id": 12191939, "author": "Ale", "author_id": 1593459, "author_profile": "https://Stackoverflow.com/users/1593459", "pm_score": 4, "selected": false, "text": "function get_mime($file) {\n if (function_exists(\"finfo_file\")) {\n $finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type a la the 'mimetype' extension\n $mime = finfo_file($finfo, $file);\n finfo_close($finfo);\n return $mime;\n } else if (function_exists(\"mime_content_type\")) {\n return mime_content_type($file);\n } else if (!stristr(ini_get(\"disable_functions\"), \"shell_exec\")) {\n // http://stackoverflow.com/a/134930/1593459\n $file = escapeshellarg($file);\n $mime = shell_exec(\"file -bi \" . $file);\n return $mime;\n } else {\n return false;\n }\n}\n mime_content_type finfo shell_exec" }, { "answer_id": 12387464, "author": "vizzy", "author_id": 1665635, "author_profile": "https://Stackoverflow.com/users/1665635", "pm_score": -1, "selected": false, "text": "function get_mime_type($filename, $mimePath = '../etc') { ...\n" }, { "answer_id": 15256393, "author": "Andrew", "author_id": 560972, "author_profile": "https://Stackoverflow.com/users/560972", "pm_score": 3, "selected": false, "text": "$file = 'path/to/image.jpg';\n$image_mime = image_type_to_mime_type(exif_imagetype($file));\n" }, { "answer_id": 17984348, "author": "Shane", "author_id": 1042193, "author_profile": "https://Stackoverflow.com/users/1042193", "pm_score": 3, "selected": false, "text": "require_once(\"MimeReader.php\");\n\n$mime = new MimeReader(<YOUR FILE PATH>);\n$mime_type_string = $mime->getType(); // \"image/jpeg\", etc.\n" }, { "answer_id": 35110617, "author": "David", "author_id": 867903, "author_profile": "https://Stackoverflow.com/users/867903", "pm_score": 1, "selected": false, "text": "mime_content_type() mime_content_type()" }, { "answer_id": 39131097, "author": "Klemen Tusar", "author_id": 1040452, "author_profile": "https://Stackoverflow.com/users/1040452", "pm_score": 0, "selected": false, "text": "/**\n * Helper function to extract all mime types from the default Linux /etc/mime.types\n */\nfunction get_mime_types() {\n $mime_types = array();\n if (\n file_exists('/etc/mime.types') &&\n ($fh = fopen('/etc/mime.types', 'r')) !== false\n ) {\n while (($line = fgets($fh)) !== false) {\n if (!trim($line) || substr($line, 0, 1) === '#') continue;\n $mime_type = preg_split('/\\t+/', rtrim($line));\n if (\n is_array($mime_type) &&\n isset($mime_type[0]) && $mime_type[0] &&\n isset($mime_type[1]) && $mime_type[1]\n ) {\n foreach (explode(' ', $mime_type[1]) as $ext) {\n $mime_types[$ext] = $mime_type[0];\n }\n }\n }\n fclose($fh);\n }\n return $mime_types;\n}\n" }, { "answer_id": 40004903, "author": "jhaagsma", "author_id": 2444435, "author_profile": "https://Stackoverflow.com/users/2444435", "pm_score": 1, "selected": false, "text": "<?php\n$info = new finfo(FILEINFO_MIME_TYPE);\necho $info->file('myImage.jpg');\n// prints \"image/jpeg\"\n" }, { "answer_id": 47522347, "author": "Joshua", "author_id": 6768138, "author_profile": "https://Stackoverflow.com/users/6768138", "pm_score": 0, "selected": false, "text": "<?php\n function get_mime($file_path){\n $finfo = new finfo(FILEINFO_MIME_TYPE);\n $type = $finfo->file(file_path);\n }\n\n $mime = get_mime('path/to/file.ext');\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
134,834
<p>This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.</p> <p>Could you guys please comment on how I can make the following code more pythonic?</p> <pre><code>from math import sqrt # recursively computes the factors of a number def factors(num): factorList = [] numroot = int(sqrt(num)) + 1 numleft = num # brute force divide the number until you find a factor for i in range(2, numroot): if num % i == 0: # if we found a factor, add it to the list and compute the remainder factorList.append(i) numleft = num / i break # if we didn't find a factor, get out of here! if numleft == num: factorList.append(num) return factorList # now recursively find the rest of the factors restFactors = factors(numleft) factorList.extend(restFactors) return factorList # grabs all of the twos in the list and puts them into 2 ^ x form def transformFactorList(factorList): num2s = 0 # remove all twos, counting them as we go while 2 in factorList: factorList.remove(2) num2s += 1 # simply return the list with the 2's back in the right spot if num2s == 0: return factorList if num2s == 1: factorList.insert(0, 2) return factorList factorList.insert(0, '2 ^ ' + str(num2s)) return factorList print transformFactorList(factors(#some number)) </code></pre>
[ { "answer_id": 134946, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 2, "selected": false, "text": "def transformFactorList(factorList):\n oldsize = len(factorList)\n factorList = [f for f in factorList if f != 2]\n num2s = oldsize - len(factorList)\n if num2s == 0:\n return []\n if num2s == 1:\n return [2]+factorList\n return ['2 ^ %s' % num2s] + [factorList]\n [f for f in factorList if f != 2]" }, { "answer_id": 134954, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 3, "selected": false, "text": "range() xrange() range() xrange() if num2s -- 0: return factorList [sympy][1] factorList.insert(0, '2 ^ ' + str(num2s))\n factorlist.insert(0, '2 ^ %s' % num2s)\n from __future__ import division\n" }, { "answer_id": 135001, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "from itertools import takewhile\n\ndef transform_factor_list(factor_list):\n num_2s = len(list(takewhile(lambda e: e == 2, factor_list)))\n if num_2s > 1:\n factor_list[:num_2s] = [\"2 ^ %i\" % (num_2s, )]\n return factor_list\n" }, { "answer_id": 135009, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": false, "text": "import math\n\n# recursively computes the factors of a number as a generator\ndef factors(num):\n numroot = int(math.sqrt(num)) + 1\n # brute force divide the number until you find a factor\n for i in xrange(2, numroot):\n divider, remainder = divmod(num, i)\n if not remainder:\n # if we found a factor, add it to the list and compute the\n # remainder\n yield i\n break\n else:\n # if we didn't find a factor, get out of here!\n yield num\n return\n # now recursively find the rest of the factors\n for factor in factors(divider):\n yield factor\n" }, { "answer_id": 136657, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 5, "selected": false, "text": "joined_lower joined_lower StudlyCaps camelCase" }, { "answer_id": 136713, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 4, "selected": false, "text": "# recursively computes the factors of a number\ndef factors(num):\n def factors(num):\n \"\"\" recursively computes the factors of a number\"\"\"\n \"\"\"This is a docstring\"\"\"\n >>> import docstring\n>>> help(docstring)\n Help on module docstring:\n\nNAME\n docstring - This is a docstring\n\nFILE\n /Users/jason/docstring.py\n" }, { "answer_id": 434498, "author": "Nope", "author_id": 41718, "author_profile": "https://Stackoverflow.com/users/41718", "pm_score": 2, "selected": false, "text": "def factors(num):\n return [i for i in xrange(1, num+1) if num % i == 0]\n" }, { "answer_id": 1160144, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "import itertools\nimport collections\n\ndef factorize(n):\n # ideally an iterator of prime numbers\n # this'll work though\n divisors = itertools.count(2)\n\n divisor = divisors.next()\n while True:\n if divisor**2 > n:\n yield n\n break\n\n a,b = divmod(n, divisor)\n\n if b == 0:\n yield divisor\n n = a\n else:\n divisor = divisors.next()\n\ndef compress(factors):\n summands = collections.defaultdict(lambda: 0)\n\n for factor in factors:\n summands[factor] += 1\n\n return [(base, summands[base]) for base in sorted(summands)]\n\ndef tostring(compressed):\n return ' * '.join(\"%d**%d\" % factor for factor in compressed)\n" }, { "answer_id": 2021548, "author": "Beni Cherniavsky-Paskin", "author_id": 239657, "author_profile": "https://Stackoverflow.com/users/239657", "pm_score": 2, "selected": false, "text": "import itertools\n\ndef factorize(n):\n # ideally an iterator of prime numbers\n # this'll work though\n divisors = itertools.count(2)\n\n for divisor in divisors:\n # This condition is very clever!\n # Note that `n` is decreasing, while `divisor` is increasing.\n # And we know that `n` is not divisible by anything smaller,\n # so this stops as soon as the remaining `n` is obviously prime.\n if divisor**2 > n:\n yield n\n break\n\n while n % divisor == 0:\n yield divisor\n n //= divisor\n\ndef compress(factors):\n for (factor, copies) in itertools.groupby(factors):\n # The second object yielded by groupby is a generator of equal factors.\n # Using list() to count its length.\n power = len(list(copies))\n yield (factor, power)\n\ndef tostring(compressed):\n return ' * '.join(\"%d**%d\" % (factor, power) for (factor, power) in compressed)\n\n# test\nassert tostring(compress(factorize(12))) == '2**2 * 3**1'\n" }, { "answer_id": 2021849, "author": "fortran", "author_id": 106979, "author_profile": "https://Stackoverflow.com/users/106979", "pm_score": 1, "selected": false, "text": "import this \"\"\"returns an iterator of tuples (factor, power) such that \nreduce(operator.mul, (factor**power for factor, power in factors(n))) == n \"\"\"\ndef factors(n):\n i = 2\n while n > 1:\n p = 0\n while n > 1 and n % i == 0:\n p += 1\n n /= i\n if p:\n yield (i, p)\n i += 1\n" }, { "answer_id": 2023313, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "def transformFactorList(factorList):\n twos = [x for x in factorList if x == 2]\n rest = [x for x in factorList if x != 2]\n rest.insert(0, \"2 ^ %d\" % len(twos))\n return rest\n 2^0 2^1 def transformFactorList(factorList):\n twos = [x for x in factorList if x == 2]\n rest = [x for x in factorList if x != 2]\n if twos:\n rest.insert(0, 2 if len(twos)==1 else \"2 ^ %d\" % len(twos))\n return rest\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/134834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]