qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
60,680
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever() </code></pre>
[ { "answer_id": 60753, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 6, "selected": true, "text": "from threading import Thread\nfrom SocketServer import ThreadingMixIn\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\n\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/plain\")\n self.end_headers()\n self.wfile.write(\"Hello World!\")\n\nclass ThreadingHTTPServer(ThreadingMixIn, HTTPServer):\n daemon_threads = True\n\ndef serve_on_port(port):\n server = ThreadingHTTPServer((\"localhost\",port), Handler)\n server.serve_forever()\n\nThread(target=serve_on_port, args=[1111]).start()\nserve_on_port(2222)\n from socketserver import ThreadingMixIn\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n self.wfile.write(bytes(\"Hello World!\", \"utf-8\"))\n" }, { "answer_id": 60754, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 3, "selected": false, "text": "def serve_forever(self, poll_interval=0.5):\n \"\"\"Handle one request at a time until shutdown.\n\n Polls for shutdown every poll_interval seconds. Ignores\n self.timeout. If you need to do periodic tasks, do them in\n another thread.\n \"\"\"\n self.__serving = True\n self.__is_shut_down.clear()\n while self.__serving:\n # XXX: Consider using another file descriptor or\n # connecting to the socket to wake this up instead of\n # polling. Polling reduces our responsiveness to a\n # shutdown request and wastes cpu at all other times.\n r, w, e = select.select([self], [], [], poll_interval)\n if r:\n self._handle_request_noblock()\n self.__is_shut_down.set()\n def serve_forever(server1,server2):\n while True:\n r,w,e = select.select([server1,server2],[],[],0)\n if server1 in r:\n server1.handle_request()\n if server2 in r:\n server2.handle_request()\n" }, { "answer_id": 61322, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 3, "selected": false, "text": "from twisted.internet import reactor\nfrom twisted.web import resource, server\n\nclass MyResource(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n return 'gotten'\n\nsite = server.Site(MyResource())\n\nreactor.listenTCP(8000, site)\nreactor.listenTCP(8001, site)\nreactor.run()\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4321/" ]
60,683
<p>Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated.</p> <p>I am using visual studio 2005</p>
[ { "answer_id": 60695, "author": "Winter", "author_id": 6227, "author_profile": "https://Stackoverflow.com/users/6227", "pm_score": 4, "selected": true, "text": "\n GlacialList mylist = new GlacialList();\n\nmylist.Columns.Add( \"Column1\", 100 ); // this can also be added \n\n // through the design time support \n\nmylist.Columns.Add( \"Column2\", 100 ); \nmylist.Columns.Add( \"Column3\", 100 ); \nmylist.Columns.Add( \"Column4\", 100 ); \n\nGLItem item;\n\nitem = this.glacialList1.Items.Add( \"Atlanta Braves\" );\nitem.SubItems[1].Text = \"8v\";\nitem.SubItems[2].Text = \"Live\";\nitem.SubItems[2].BackColor = Color.Bisque;\nitem.SubItems[3].Text = \"MLB.TV\"; \n\nitem = this.glacialList1.Items.Add( \"Florida Marlins\" );\nitem.SubItems[1].Text = \"\";\nitem.SubItems[2].Text = \"Delayed\";\nitem.SubItems[2].BackColor = Color.LightCoral;\nitem.SubItems[3].Text = \"Audio\";\n\n\nitem.SubItems[1].BackColor = Color.Aqua; // set the background \n\n // of this particular subitem ONLY\n\nitem.UserObject = myownuserobjecttype; // set a private user object\n\nitem.Selected = true; // set this item to selected state\n\nitem.SubItems[1].Span = 2; // set this sub item to span 2 spaces\n\n\nArrayList selectedItems = mylist.SelectedItems; \n // get list of selected items\n" }, { "answer_id": 83882, "author": "Makis Arvanitis", "author_id": 66654, "author_profile": "https://Stackoverflow.com/users/66654", "pm_score": 5, "selected": false, "text": "this.listView1.CheckBoxes = true;\n" }, { "answer_id": 5534056, "author": "CharithJ", "author_id": 591656, "author_profile": "https://Stackoverflow.com/users/591656", "pm_score": 3, "selected": false, "text": "myListView.CheckBoxes = true;\nmyListView.Columns.Add(text, width, alignment);\n ListViewItem lstViewItem = new ListViewItem();\nlstViewItem.SubItems.Add(\"Testing..\");\nlstViewItem.SubItems.Add(\"Testing1..\");\n\nmyListView.Items.Add(lstViewItem);\n" }, { "answer_id": 30975220, "author": "Sohaib Afzal", "author_id": 4228223, "author_profile": "https://Stackoverflow.com/users/4228223", "pm_score": 2, "selected": false, "text": "CheckBoxes true listView1.CheckBoxes = true;\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
60,684
<p><strong><em>Edit:</em></strong> This question had been tagged "Tolstoy" in appreciation of the quality and length of my writing:) Just reading the first and the last paragraph should be enough:) If you tend to select and move code with the mouse, the stuff in middle could be interesting to you.</p> <p>This question is about how you use text editors in general. I’m looking for the best way to <em>delete</em> a plurality of lines of code (no intent to patent it:) This extends to <em>transposing</em> lines, i.e. deleting and adding them somewhere else. Most importantly, I don’t want to be creating any blank lines that I have to delete separately. Sort of like Visual Studio's SHIFT+DELETE feature, but working for multiple lines at once.</p> <p>Say you want to delete line 3 from following code (tabs and newlines visualized as well). The naïve way would be to select the text between angle brackets:</p> <pre> if (true) {\n \t int i = 1;\n \t &lt;i *= 2;&gt;\n \t i += 3;\n }\n </pre> <p>Then hit backspace. This creates a blank line. Hit backspace twice more to delete \t and \n. </p> <p>You end up with:</p> <pre> if (true) {\n \t int i = 1;\n \t i += 3;\n }\n </pre> <p>When you try to select a whole line, Visual Studio doesn't let you select the trailing newline character. For example, placing the cursor on a line and hitting SHIFT+END will not select the newline at the end. Neither will you select the newline if you use your mouse, i.e. clicking in the middle of a line and dragging the cursor all the way to the right. You only select the trailing newline characters if you make a selection that spans at least two lines. Most editors I use do it this way; Microsoft WordPad and Word are counter-examples (and I frequently get newlines wrong when deleting text there; at least Word has a way to display end-of-line and end-of-paragraph characters explicitly).</p> <p>When using Visual Studio and other editors in general, here’s the solution that currently works best for me:</p> <p>Using the mouse, I select the characters that I put between angle brackets:</p> <pre> if (true) {\n \t int i = 1;&lt;\n \t i *= 2;&gt;\n \t i += 3;\n }\n </pre> <p>Hitting backspace now, you delete the line in one go without having to delete any other characters. This works for several contiguous lines at once. Additionally, it can be used for transposing lines. You could drag the selection between the angle brackets to the point marked with a caret:</p> <pre> if (true) {\n \t int i = 1;&lt;\n \t i *= 2;&gt;\n \t i += 3;^\n }\n </pre> <p>This leaves you with:</p> <pre> if (true) {\n \t int i = 1;\n \t i += 3;&lt;\n \t i *= 2;&gt;\n }\n </pre> <p>where lines 3 and 4 have switched place.</p> <p>There are variations on this theme. When you want to delete line 3, you could also select the following characters:</p> <pre> if (true) {\n \t int i = 1;\n &lt;\t i *= 2;\n &gt;\t i += 3;\n }\n </pre> <p>In fact, this is what Visual Studio does if you tell it to select a complete line. You do this by clicking in the margin between your code and the column where the red circles go which indicate breakpoints. The mouse pointer is mirrored in that area to distinguish it a little better, but I think it's too narrow and physically too far removed from the code I want to select.</p> <p>Maybe this method is useful to other people as well, even if it only serves to make them aware of how newlines are handled when selecting/deleting text:) It works nicely for most non-specialized text editors. However, given the vast amount of features and plugins for Visual Studio (which I use most), I'm sure there is better way to use it to delete and move lines of code. Getting the indentation right automatically when moving code between different blocks would be nice (i.e. without hitting "Format Document/Selection"). I'm looking forward to suggestions; no rants on micro-optimization, please:)</p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <p>With respect to Visual Studio: Navigating well with the cursor keys.</p> <p>The solution that would best suit my style of going over and editing code is the <em>Eclipse</em> way:</p> <p>You can select several consecutive lines of code, where the first and the last selected line may be selected only partially. Pressing ALT+{up,down} moves the complete lines (not just the selection) up and down, fixing indentation as you go. Hitting CTRL+D deletes the lines completely (not just the selection) without leaving any unwanted blank lines. I would love to see this in Visual Studio!</p>
[ { "answer_id": 60697, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "kill-whole-line" }, { "answer_id": 60709, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 2, "selected": false, "text": "dd dd p 10 dd\n :10,15d\n :10,15m20\n :10,15t20\n" }, { "answer_id": 20648989, "author": "Drew", "author_id": 729907, "author_profile": "https://Stackoverflow.com/users/729907", "pm_score": 0, "selected": false, "text": "C-k C-k" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6103/" ]
60,685
<p>What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.</p> <p>Here's the regex:</p> <pre><code>\s*#define(.*\\\n)+[\S]+(?!\\) </code></pre> <p>It should match all of this:</p> <pre><code>#define foo(x) if(x) \ doSomething(x) </code></pre> <p>But only some of this (shouldn't match the next line of code:</p> <pre><code>#define foo(x) if(x) \ doSomething(x) normalCode(); </code></pre> <p>And also shouldn't match single-line preprocessor macros.</p> <p>I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. Can anyone suggest any?</p>
[ { "answer_id": 60723, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 4, "selected": true, "text": "#!/usr/bin/env python\n\nTEST1=\"\"\"\n#include \"Foo.h\"\n#define bar foo\\\\\n x\n#include \"Bar.h\"\n\"\"\"\n\nTEST2=\"\"\"\n#define bar foo\n#define x 1 \\\\\n 12 \\\\\n 2 \\\\\\\\ 3\nFoobar\n\"\"\"\n\nTEST3=\"\"\"\n#define foo(x) if(x) \\\\\ndoSomething(x)\n\"\"\"\n\nTEST4=\"\"\"\n#define foo(x) if(x) \\\\\ndoSomething(x)\nnormalCode();\n\"\"\"\n\nimport re\nmatcher = re.compile(r\"^[ \\t]*#define(.*\\\\\\n)+.*$\",re.MULTILINE)\n\ndef extractDefines(s):\n mo = matcher.search(s)\n if not mo:\n print mo\n return\n print mo.group(0)\n\nextractDefines(TEST1)\nextractDefines(TEST2)\nextractDefines(TEST3)\nextractDefines(TEST4)\n r\"^[ \\t]*#define(.*\\\\\\n)+.*$\"\n" }, { "answer_id": 60729, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "start = r\"^\\s*#define\\s+\"\ncontinuation = r\"(?:.*\\\\\\n)+\"\nlastline = r\".*$\"\n\nre_multiline_macros = re.compile(start + continuation + lastline, \n re.MULTILINE)\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304/" ]
60,720
<p>What is the best way for me to determine a controller variable's value during execution?</p> <p>For example, is there a way I can insert a break in the code, and cause the value of the variable to be output to the screen (or the log)?</p>
[ { "answer_id": 60731, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 5, "selected": true, "text": "raise @foo.to_s gem install ruby-debug --debugger debugger p" }, { "answer_id": 60732, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 3, "selected": false, "text": "@foo logger.debug \"@foo is: #{@foo}\"\n <%= debug @foo %>\n" }, { "answer_id": 60737, "author": "Jaryl", "author_id": 6291, "author_profile": "https://Stackoverflow.com/users/6291", "pm_score": 3, "selected": false, "text": "raise @foo.inspect\n" }, { "answer_id": 63453, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 2, "selected": false, "text": "raise @foo.inspect\n <% raise @foo.inspect %>\n development.log logger.debug \"@foo == #{@foo.inspect}\"\n gem install ruby-debug --debugger debugger p" }, { "answer_id": 50114810, "author": "Daniel Garmoshka", "author_id": 1751321, "author_profile": "https://Stackoverflow.com/users/1751321", "pm_score": 0, "selected": false, "text": "gem 'pry-moves' binding.pry c n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
60,736
<p>I have a laptop running Ubuntu that I would like to act as a Subversion server. Both for myself to commit to locally, and for others remotely. What are the steps required to get this working? Please include steps to:</p> <ul> <li>Get and configure Apache, and necessary modules (I know there are other ways to create a SVN server, but I would like it Apache-specific)</li> <li>Configure a secure way of accessing the server (SSH/HTTPS)</li> <li>Configure a set of authorised users (as in, they must authorised to commit, but are free to browse)</li> <li>Validate the setup with an initial commit (a "Hello world" of sorts)</li> </ul> <p>These steps can involve any mixture of command line or GUI application instructions. If you can, please note where instructions are specific to a particular distribution or version, and where a users' choice of a particular tool can be used instead (say, <a href="https://en.wikipedia.org/wiki/GNU_nano" rel="noreferrer">nano</a> instead of <a href="http://en.wikipedia.org/wiki/Vi" rel="noreferrer">vi</a>).</p>
[ { "answer_id": 60741, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "sudo apt-get -yq install apache2\n sudo apt-get -yq install openssh-server\n sudo apt-get -yq install subversion subversion-tools\n sudo apt-get -yq install apache2 openssh-server subversion subversion-tools\n" }, { "answer_id": 60792, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 8, "selected": true, "text": "sudo apt-get install libapache2-svn apache2\n apache2-mpm-worker apache2-utils apache2.2-common\n sudo a2enmod ssl\nsudo kate /etc/apache2/ports.conf\n <IfModule mod_ssl.c>\n Listen 443\n</IfModule>\n sudo apt-get install ssl-cert\nsudo mkdir /etc/apache2/ssl\nsudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/apache.pem\n sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/svnserver\nsudo kate /etc/apache2/sites-available/svnserver\n \"NameVirtualHost *\" to \"NameVirtualHost *:443\"\n <VirtualHost *> to <VirtualHost *:443>\n SSLEngine on\nSSLCertificateFile /etc/apache2/ssl/apache.pem\nSSLProtocol all\nSSLCipherSuite HIGH:MEDIUM\n sudo a2ensite svnserver\nsudo /etc/init.d/apache2 restart\n sudo kate /etc/apache2/apache2.conf\n \"ServerName $your_server_name\"\n sudo mkdir /var/svn\n\nREPOS=myFirstRepo\nsudo svnadmin create /var/svn/$REPOS\nsudo chown -R www-data:www-data /var/svn/$REPOS\nsudo chmod -R g+ws /var/svn/$REPOS\n mkdir /var/svn sudo htpasswd -c -m /etc/apache2/dav_svn.passwd $user_name\n sudo kate /etc/apache2/mods-available/dav_svn.conf\n <Location /svn>\nDAV svn\n\n# for multiple repositories - see comments in file\nSVNParentPath /var/svn\n\nAuthType Basic\nAuthName \"Subversion Repository\"\nAuthUserFile /etc/apache2/dav_svn.passwd\nRequire valid-user\nSSLRequireSSL\n</Location>\n sudo /etc/init.d/apache2 restart\n http://localhost/svn/$REPOS\nhttps://localhost/svn/$REPOS\n <LimitExcept GET PROPFIND OPTIONS REPORT>\n\n</LimitExcept>\n /etc/apache2/mods-available/dav_svn.conf svn import --username $user_name anyfile.txt https://localhost/svn/$REPOS/anyfile.txt -m “Testing”\n svn co --username $user_name https://localhost/svn/$REPOS\n" }, { "answer_id": 26987985, "author": "Ashish Saini", "author_id": 834799, "author_profile": "https://Stackoverflow.com/users/834799", "pm_score": -1, "selected": false, "text": "$sudo apt-get install subversion\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
60,740
<p>Is there an IE6/PNG fix that is officially developed by the jQuery team?</p> <p>If not which of the available plugins should I use?</p>
[ { "answer_id": 2163740, "author": "Guilherme Santos", "author_id": 262002, "author_profile": "https://Stackoverflow.com/users/262002", "pm_score": 1, "selected": false, "text": "// this line\njQuery(this).find(\"img[src$=.png]:visible\").each(function() { \n// this line\njQuery(this).find(\":visible\").each(function(){\n// and this line\njQuery(this).find(\"input[src$=.png]:visible\").each(function() {\n // Store a reference to the original method.\nvar _show = jQuery.fn.show;\n\n// Overriding Show method.\njQuery.fn.show = function(){\n // Execute the original method.\n _show.apply( this, arguments );\n // Fix Png \n return $(this).pngFix();\n}\n\n//No more problems with hidden images\n\n})(jQuery);\n\n//The End\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
60,751
<p>Currently my app uses just Direct3D9 for graphics, however in the future I' m planning to extend this to D3D10 and possibly OpenGL. The question is how can I do this in a tidy way?</p> <p>At present there are various Render methods in my code</p> <pre><code>void Render(boost::function&lt;void()&gt; &amp;Call) { D3dDevice-&gt;BeginScene(); Call(); D3dDevice-&gt;EndScene(); D3dDevice-&gt;Present(0,0,0,0); } </code></pre> <p>The function passed then depends on the exact state, eg MainMenu->Render, Loading->Render, etc. These will then oftern call the methods of other objects.</p> <pre><code>void RenderGame() { for(entity::iterator it = entity::instances.begin();it != entity::instance.end(); ++it) (*it)-&gt;Render(); UI-&gt;Render(); } </code></pre> <p>And a sample class derived from entity::Base</p> <pre><code>class Sprite: public Base { IDirect3DTexture9 *Tex; Point2 Pos; Size2 Size; public: Sprite(IDirect3DTexture9 *Tex, const Point2 &amp;Pos, const Size2 &amp;Size); virtual void Render(); }; </code></pre> <p>Each method then takes care of how best to render given the more detailed settings (eg are pixel shaders supported or not).</p> <p>The problem is I'm really not sure how to extend this to be able to use one of, what may be somewhat different (D3D v OpenGL) render modes...</p>
[ { "answer_id": 60790, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 4, "selected": true, "text": "class IRenderer {\n public:\n virtual ~IRenderer() {}\n virtual void RenderModel(CModel* model) = 0;\n virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) = 0;\n // ...etc...\n};\n\nclass COpenGLRenderer : public IRenderer {\n public:\n virtual void RenderModel(CModel* model) {\n // render model using OpenGL\n }\n virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) {\n // draw screen aligned quad using OpenGL\n }\n};\n\nclass CDirect3DRenderer : public IRenderer {\n // similar, but render using Direct3D\n};\n class IRenderer {\n //...\n virtual ITexture* CreateTexture(const char* filename) = 0;\n //...\n};\n\nclass COpenGLRenderer : public IRenderer {\n //...\n virtual ITexture* CreateTexture(const char* filename) {\n // COpenGLTexture is the OpenGL specific ITexture implementation\n return new COpenGLTexture(filename);\n }\n //...\n};\n" }, { "answer_id": 69100, "author": "Baxissimo", "author_id": 9631, "author_profile": "https://Stackoverflow.com/users/9631", "pm_score": 1, "selected": false, "text": "Ogre3D D3D OpenGL" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
60,757
<p>What is the best way to handle user account management in a system, without having your employees who have access to a database, to have access to the accounts.</p> <p>Examples:</p> <ol> <li><p>Storing username/password in the database. This is a bad idea because anyone that has access to a database can see the username and password. And hence use it.</p></li> <li><p>Storing username/password hash. This is a better method, but the account can be accessed by replacing the password hash in the database with the hash of another account that you know the auth info for. Then after access is granted reverting it back in the database. </p></li> </ol> <p>How does windows/*nix handle this?</p>
[ { "answer_id": 60864, "author": "Mr Shark", "author_id": 6093, "author_profile": "https://Stackoverflow.com/users/6093", "pm_score": 2, "selected": false, "text": "SetPassword(user, password)\n salt = RandomString()\n hash = Hashfunction(salt+password)\n StoreInDatabase(user, salt, hash)\n\nCheckPassword(user, password)\n (salt, hash) = GetFromDatabase(user)\n if Hashfunction(salt+password) == hash\n return \"Success\"\n else\n return \"Login Failed\"\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
60,764
<p>Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own <code>ClassLoader</code>, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.</p> <p>Any suggestions for simple code that does this?</p>
[ { "answer_id": 60766, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 7, "selected": false, "text": "File file = ...\nURL url = file.toURI().toURL();\n\nURLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();\nMethod method = URLClassLoader.class.getDeclaredMethod(\"addURL\", URL.class);\nmethod.setAccessible(true);\nmethod.invoke(classLoader, url);\n" }, { "answer_id": 60775, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 9, "selected": true, "text": "URLClassLoader child = new URLClassLoader(\n new URL[] {myJar.toURI().toURL()},\n this.getClass().getClassLoader()\n);\nClass classToLoad = Class.forName(\"com.MyClass\", true, child);\nMethod method = classToLoad.getDeclaredMethod(\"myMethod\");\nObject instance = classToLoad.newInstance();\nObject result = method.invoke(instance);\n" }, { "answer_id": 63892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public void initialize(String libDir) throws Exception {\n File dependencyDirectory = new File(libDir);\n File[] files = dependencyDirectory.listFiles();\n ArrayList<URL> urls = new ArrayList<URL>();\n for (int i = 0; i < files.length; i++) {\n if (files[i].getName().endsWith(\".jar\")) {\n urls.add(files[i].toURL());\n //urls.add(files[i].toURI().toURL());\n }\n }\n classLoader = new JarFileClassLoader(\"Scheduler CL\" + System.currentTimeMillis(), \n urls.toArray(new URL[urls.size()]), \n GFClassLoader.class.getClassLoader());\n}\n classLoader.loadClass(name);\n" }, { "answer_id": 1450837, "author": "Chris", "author_id": 92813, "author_profile": "https://Stackoverflow.com/users/92813", "pm_score": 5, "selected": false, "text": "JarClassLoader jcl = new JarClassLoader();\njcl.add(\"myjar.jar\"); // Load jar file \njcl.add(new URL(\"http://myserver.com/myjar.jar\")); // Load jar from a URL\njcl.add(new FileInputStream(\"myotherjar.jar\")); // Load jar file from stream\njcl.add(\"myclassfolder/\"); // Load class folder \njcl.add(\"myjarlib/\"); // Recursively load all jar files in the folder/sub-folder(s)\n\nJclObjectFactory factory = JclObjectFactory.getInstance();\n// Create object of loaded class \nObject obj = factory.create(jcl, \"mypackage.MyClass\");\n" }, { "answer_id": 2593771, "author": "Jonathan Nadeau", "author_id": 311140, "author_profile": "https://Stackoverflow.com/users/311140", "pm_score": 4, "selected": false, "text": "/**************************************************************************************************\n * Copyright (c) 2004, Federal University of So Carlos *\n * *\n * All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, with or without modification, are permitted *\n * provided that the following conditions are met: *\n * *\n * * Redistributions of source code must retain the above copyright notice, this list of *\n * conditions and the following disclaimer. *\n * * Redistributions in binary form must reproduce the above copyright notice, this list of *\n * * conditions and the following disclaimer in the documentation and/or other materials *\n * * provided with the distribution. *\n * * Neither the name of the Federal University of So Carlos nor the names of its *\n * * contributors may be used to endorse or promote products derived from this software *\n * * without specific prior written permission. *\n * *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR *\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\n **************************************************************************************************/\n/*\n * Created on Oct 6, 2004\n */\npackage tools;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.net.URL;\nimport java.net.URLClassLoader;\n\n/**\n * Useful class for dynamically changing the classpath, adding classes during runtime. \n */\npublic class ClasspathHacker {\n /**\n * Parameters of the method to add an URL to the System classes. \n */\n private static final Class<?>[] parameters = new Class[]{URL.class};\n\n /**\n * Adds a file to the classpath.\n * @param s a String pointing to the file\n * @throws IOException\n */\n public static void addFile(String s) throws IOException {\n File f = new File(s);\n addFile(f);\n }\n\n /**\n * Adds a file to the classpath\n * @param f the file to be added\n * @throws IOException\n */\n public static void addFile(File f) throws IOException {\n addURL(f.toURI().toURL());\n }\n\n /**\n * Adds the content pointed by the URL to the classpath.\n * @param u the URL pointing to the content to be added\n * @throws IOException\n */\n public static void addURL(URL u) throws IOException {\n URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();\n Class<?> sysclass = URLClassLoader.class;\n try {\n Method method = sysclass.getDeclaredMethod(\"addURL\",parameters);\n method.setAccessible(true);\n method.invoke(sysloader,new Object[]{ u }); \n } catch (Throwable t) {\n t.printStackTrace();\n throw new IOException(\"Error, could not add URL to system classloader\");\n } \n }\n\n public static void main(String args[]) throws IOException, SecurityException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{\n addFile(\"C:\\\\dynamicloading.jar\");\n Constructor<?> cs = ClassLoader.getSystemClassLoader().loadClass(\"test.DymamicLoadingTest\").getConstructor(String.class);\n DymamicLoadingTest instance = (DymamicLoadingTest)cs.newInstance();\n instance.test();\n }\n}\n" }, { "answer_id": 18253109, "author": "Caner", "author_id": 448625, "author_profile": "https://Stackoverflow.com/users/448625", "pm_score": 3, "selected": false, "text": "String jarFile = \"path/to/jarfile.jar\";\nDexClassLoader classLoader = new DexClassLoader(jarFile, \"/data/data/\" + context.getPackageName() + \"/\", null, getClass().getClassLoader());\nClass<?> myClass = classLoader.loadClass(\"MyClass\");\n" }, { "answer_id": 31624177, "author": "venergiac", "author_id": 1645339, "author_profile": "https://Stackoverflow.com/users/1645339", "pm_score": 2, "selected": false, "text": "Thread.currentThread().setContextClassLoader(classLoader);\n" }, { "answer_id": 46457506, "author": "fgb", "author_id": 298029, "author_profile": "https://Stackoverflow.com/users/298029", "pm_score": 4, "selected": false, "text": "URLClassLoader java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClassLoader\n package ClassPathAgent;\n\nimport java.io.IOException;\nimport java.lang.instrument.Instrumentation;\nimport java.util.jar.JarFile;\n\npublic class ClassPathAgent {\n public static void agentmain(String args, Instrumentation instrumentation) throws IOException {\n instrumentation.appendToSystemClassLoaderSearch(new JarFile(args));\n }\n}\n Manifest-Version: 1.0\nAgent-Class: ClassPathAgent.ClassPathAgent\n import java.io.File;\n\nimport net.bytebuddy.agent.ByteBuddyAgent;\n\npublic class ClassPathUtil {\n private static File AGENT_JAR = new File(\"/path/to/agent.jar\");\n\n public static void addJarToClassPath(File jarFile) {\n ByteBuddyAgent.attach(AGENT_JAR, String.valueOf(ProcessHandle.current().pid()), jarFile.getPath());\n }\n}\n" }, { "answer_id": 50521611, "author": "Aleksey", "author_id": 1433446, "author_profile": "https://Stackoverflow.com/users/1433446", "pm_score": 2, "selected": false, "text": " File libDir = new File(\"path/to/jar\");\n\n ProxyCallerInterface caller = ObjectBuilder.builder()\n .setClassName(\"net.proxy.lib.test.LibClass\")\n .setArtifact(DirArtifact.builder()\n .withClazz(ObjectBuilderTest.class)\n .withVersionInfo(newVersionInfo(libDir))\n .build())\n .build();\n String version = caller.call(\"getLibVersion\").asString();\n" }, { "answer_id": 52616924, "author": "czdepski", "author_id": 10448469, "author_profile": "https://Stackoverflow.com/users/10448469", "pm_score": 2, "selected": false, "text": "File file = ...\nURL url = file.toURI().toURL();\nURLClassLoader sysLoader = new URLClassLoader(new URL[0]);\n\nMethod sysMethod = URLClassLoader.class.getDeclaredMethod(\"addURL\", new Class[]{URL.class});\nsysMethod.setAccessible(true);\nsysMethod.invoke(sysLoader, new Object[]{url});\n" }, { "answer_id": 52741647, "author": "czdepski", "author_id": 10448469, "author_profile": "https://Stackoverflow.com/users/10448469", "pm_score": 3, "selected": false, "text": "package agent;\n\nimport java.io.IOException;\nimport java.lang.instrument.Instrumentation;\nimport java.util.jar.JarFile;\n\npublic class Agent {\n public static Instrumentation instrumentation;\n\n public static void premain(String args, Instrumentation instrumentation) {\n Agent.instrumentation = instrumentation;\n }\n\n public static void agentmain(String args, Instrumentation instrumentation) {\n Agent.instrumentation = instrumentation;\n }\n\n public static void appendJarFile(JarFile file) throws IOException {\n if (instrumentation != null) {\n instrumentation.appendToSystemClassLoaderSearch(file);\n }\n }\n}\n Launcher-Agent-Class: agent.Agent\nAgent-Class: agent.Agent\nPremain-Class: agent.Agent\n Launcher-Agent-Class java -jar <your jar>\n -javaagent java -javaagent:<your jar> -jar <your jar>\n Agent.appendJarFile(new JarFile(<your file>));\n" }, { "answer_id": 52911129, "author": "steve212", "author_id": 10534683, "author_profile": "https://Stackoverflow.com/users/10534683", "pm_score": 2, "selected": false, "text": "import jhplot.Web;\nWeb.load(\"http://central.maven.org/maven2/it/unimi/dsi/fastutil/8.2.2/fastutil-8.2.2.jar\"); // now you can start using this library\n" }, { "answer_id": 53111471, "author": "Anton Tananaev", "author_id": 2548565, "author_profile": "https://Stackoverflow.com/users/2548565", "pm_score": 4, "selected": false, "text": "ClassLoader classLoader = ClassLoader.getSystemClassLoader();\ntry {\n Method method = classLoader.getClass().getDeclaredMethod(\"addURL\", URL.class);\n method.setAccessible(true);\n method.invoke(classLoader, new File(jarPath).toURI().toURL());\n} catch (NoSuchMethodException e) {\n Method method = classLoader.getClass()\n .getDeclaredMethod(\"appendToClassPathForInstrumentation\", String.class);\n method.setAccessible(true);\n method.invoke(classLoader, jarPath);\n}\n" }, { "answer_id": 59743937, "author": "Mordechai", "author_id": 1751640, "author_profile": "https://Stackoverflow.com/users/1751640", "pm_score": 6, "selected": false, "text": "java -Djava.system.class.loader=com.example.MyCustomClassLoader\n ClassLoader.getSystemClassLoader() add()" }, { "answer_id": 60281394, "author": "Bằng Rikimaru", "author_id": 2028440, "author_profile": "https://Stackoverflow.com/users/2028440", "pm_score": 1, "selected": false, "text": "public static synchronized void loadLibrary(java.io.File jar) {\n try { \n java.net.URL url = jar.toURI().toURL();\n java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod(\"addURL\", new Class[]{java.net.URL.class});\n method.setAccessible(true); /*promote the method to public access*/\n method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});\n } catch (Exception ex) {\n throw new RuntimeException(\"Cannot load library from jar file '\" + jar.getAbsolutePath() + \"'. Reason: \" + ex.getMessage());\n }\n}\n" }, { "answer_id": 60662896, "author": "ZGorlock", "author_id": 7427882, "author_profile": "https://Stackoverflow.com/users/7427882", "pm_score": 2, "selected": false, "text": "File object = new File(pack.getObjectFile()).getAbsoluteFile();\nObject packObject;\ntry {\n URLClassLoader classloader;\n\n List<URL> classpath = new ArrayList<>();\n classpath.add(new File(pack.getObjectRootPath()).toURI().toURL());\n for (File jar : FileUtils.listFiles(new File(pack.getLibPath()), new String[] {\"jar\"}, true)) {\n classpath.add(jar.toURI().toURL());\n }\n classloader = new URLClassLoader(classpath.toArray(new URL[] {}));\n\n Class<?> clazz = classloader.loadClass(object.getName());\n packObject = clazz.getDeclaredConstructor().newInstance();\n\n} catch (Exception e) {\n e.printStackTrace();\n throw e;\n}\nreturn packObject;\n" }, { "answer_id": 63094644, "author": "Sergio Santiago", "author_id": 1563297, "author_profile": "https://Stackoverflow.com/users/1563297", "pm_score": 3, "selected": false, "text": "public interface Greeting extends ExtensionPoint {\n\n String getGreeting();\n\n}\n @Extension @Extension\npublic class WelcomeGreeting implements Greeting {\n\n public String getGreeting() {\n return \"Welcome\";\n }\n\n}\n public static void main(String[] args) {\n\n // create the plugin manager\n PluginManager pluginManager = new JarPluginManager(); // or \"new ZipPluginManager() / new DefaultPluginManager()\"\n\n // start and load all plugins of application\n pluginManager.loadPlugins();\n pluginManager.startPlugins();\n\n // retrieve all extensions for \"Greeting\" extension point\n List<Greeting> greetings = pluginManager.getExtensions(Greeting.class);\n for (Greeting greeting : greetings) {\n System.out.println(\">>> \" + greeting.getGreeting());\n }\n\n // stop and unload all plugins\n pluginManager.stopPlugins();\n pluginManager.unloadPlugins();\n\n}\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
60,768
<p>I am trying to dynamicaly compile code using CodeDom. I can load other assemblies, but I cannot load System.Data.Linq.dll. I get an error:</p> <p>Metadata file 'System.Data.Linq.dll' could not be found</p> <p>My code looks like:</p> <pre><code>CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.Linq.dll"); </code></pre> <p>Any ideas? </p>
[ { "answer_id": 60781, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": true, "text": "compilerParams.ReferencedAssemblies.Add(typeof(DataContext).Assembly.Location);\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
60,779
<p>Trying to do this sort of thing...</p> <pre><code>WHERE username LIKE '%$str%' </code></pre> <p>...but using bound parameters to prepared statements in PDO. e.g.:</p> <pre><code>$query = $db-&gt;prepare("select * from comments where comment like :search"); $query-&gt;bindParam(':search', $str); $query-&gt;execute(); </code></pre> <p>I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.</p> <p>I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?</p>
[ { "answer_id": 60782, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 5, "selected": true, "text": "$str = \"%$str%\";\n$query = $db->prepare(\"select * from comments where comment like :search\");\n$query->bindParam(':search', $str);\n$query->execute();\n" }, { "answer_id": 15377644, "author": "Dominic P", "author_id": 931860, "author_profile": "https://Stackoverflow.com/users/931860", "pm_score": 2, "selected": false, "text": "$query = $db->prepare(\"select * FROM table WHERE field LIKE CONCAT('%',:search,'%')\");\n$query->bindParam(':search', $str);\n$query->execute();\n CONCAT" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
60,785
<p>How can I show a grey transparent overlay in C#?<br> It should overlay other process which are not owned by the application doing the overlay.</p>
[ { "answer_id": 60782, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 5, "selected": true, "text": "$str = \"%$str%\";\n$query = $db->prepare(\"select * from comments where comment like :search\");\n$query->bindParam(':search', $str);\n$query->execute();\n" }, { "answer_id": 15377644, "author": "Dominic P", "author_id": 931860, "author_profile": "https://Stackoverflow.com/users/931860", "pm_score": 2, "selected": false, "text": "$query = $db->prepare(\"select * FROM table WHERE field LIKE CONCAT('%',:search,'%')\");\n$query->bindParam(':search', $str);\n$query->execute();\n CONCAT" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
60,802
<p>I'm having trouble ordering by more than one field in my Linq to NHibernate query. Does anyone either know what might be wrong or if there is a work around?</p> <p>Code:</p> <pre><code>IQueryable&lt;AgendaItem&gt; items = _agendaRepository.GetAgendaItems(location) .Where(item =&gt; item.Minutes.Contains(query) || item.Description.Contains(query)); int total = items.Count(); var results = items .OrderBy(item =&gt; item.Agenda.Date) .ThenBy(item =&gt; item.OutcomeType) .ThenBy(item =&gt; item.OutcomeNumber) .Skip((page - 1)*pageSize) .Take(pageSize) .ToArray(); return new SearchResult(query, total, results); </code></pre> <p>I've tried replacing ThenBy with multiple OrderBy calls. Same result. The method works great if I comment out the two ThenBy calls.</p> <p>Error I'm receiving:</p> <pre> [SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'. Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392 [ADOException: could not execute query [ SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc ] Positional parameters: #0>1 #0>%Core% #0>%Core% [SQL: SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +258 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +87 NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) +342 NHibernate.Impl.CriteriaImpl.List(IList results) +41 NHibernate.Impl.CriteriaImpl.List() +35 NHibernate.Linq.CriteriaResultReader`1.List() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:22 NHibernate.Linq.d__0.MoveNext() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:27 </pre>
[ { "answer_id": 86686, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 4, "selected": true, "text": "var results = items\n .ToArray()\n .OrderBy(item => item.Agenda.Date)\n .ThenBy(item => item.OutcomeType)\n .ThenBy(item => item.OutcomeNumber)\n .Skip((page - 1)*pageSize)\n .Take(pageSize)\n" }, { "answer_id": 51985649, "author": "Alexander Levinson", "author_id": 4715783, "author_profile": "https://Stackoverflow.com/users/4715783", "pm_score": 0, "selected": false, "text": "var results = items\n .OrderBy(item => item.Agenda.Date).Asc\n .ThenBy(item => item.OutcomeType).Asc\n .ThenBy(item => item.OutcomeNumber).Asc\n .Skip((page - 1)*pageSize)\n .Take(pageSize)\n .ToArray();\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ]
60,805
<p>How do I select one or more random rows from a table using SQLAlchemy? </p>
[ { "answer_id": 60811, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": -1, "selected": false, "text": "SELECT colum FROM table\nORDER BY RAND()\nLIMIT 1\n SELECT column FROM table\nORDER BY RANDOM()\nLIMIT 1\n SELECT TOP 1 column FROM table\nORDER BY NEWID()\n SELECT column, RAND() as IDX\nFROM table\nORDER BY IDX FETCH FIRST 1 ROWS ONLY\n SELECT column FROM\n(SELECT column FROM table\nORDER BY dbms_random.value)\nWHERE rownum = 1\n" }, { "answer_id": 60815, "author": "Łukasz", "author_id": 4999, "author_profile": "https://Stackoverflow.com/users/4999", "pm_score": 8, "selected": true, "text": "from sqlalchemy.sql.expression import func, select\n\nselect.order_by(func.random()) # for PostgreSQL, SQLite\n\nselect.order_by(func.rand()) # for MySQL\n\nselect.order_by('dbms_random.value') # For Oracle\n .limit()" }, { "answer_id": 390676, "author": "David Raznick", "author_id": 20842, "author_profile": "https://Stackoverflow.com/users/20842", "pm_score": 5, "selected": false, "text": "import random\nrand = random.randrange(0, session.query(Table).count()) \nrow = session.query(Table)[rand]\n" }, { "answer_id": 14906244, "author": "GuySoft", "author_id": 311268, "author_profile": "https://Stackoverflow.com/users/311268", "pm_score": 5, "selected": false, "text": "import random\nquery = DBSession.query(Table)\nrowCount = int(query.count())\nrandomRow = query.offset(int(rowCount*random.random())).first()\n" }, { "answer_id": 21242325, "author": "med116", "author_id": 1784279, "author_profile": "https://Stackoverflow.com/users/1784279", "pm_score": -1, "selected": false, "text": "import random\nmax_model_id = YourModel.query.order_by(YourModel.id.desc())[0].id\nrandom_id = random.randrange(0,max_model_id)\nrandom_row = YourModel.query.get(random_id)\nprint random_row\n" }, { "answer_id": 33583008, "author": "Jeff Widman", "author_id": 770425, "author_profile": "https://Stackoverflow.com/users/770425", "pm_score": 5, "selected": false, "text": "timeit from sqlalchemy.sql import func\nfrom sqlalchemy.orm import load_only\n\ndef simple_random():\n return random.choice(model_name.query.all())\n\ndef load_only_random():\n return random.choice(model_name.query.options(load_only('id')).all())\n\ndef order_by_random():\n return model_name.query.order_by(func.random()).first()\n\ndef optimized_random():\n return model_name.query.options(load_only('id')).offset(\n func.floor(\n func.random() *\n db.session.query(func.count(model_name.id))\n )\n ).limit(1).all()\n timeit simple_random(): \n 90.09954111799925\nload_only_random():\n 65.94714171699889\norder_by_random():\n 23.17819356000109\noptimized_random():\n 19.87806927999918\n func.random() random.choice() order_by_random() ORDER BY COUNT optimized_random()" }, { "answer_id": 42780139, "author": "ChickenFeet", "author_id": 5387193, "author_profile": "https://Stackoverflow.com/users/5387193", "pm_score": 0, "selected": false, "text": "from random import randint\n\nrows_query = session.query(Table) # get all rows\nif rows_query.count() > 0: # make sure there's at least 1 row\n rand_index = randint(0,rows_query.count()-1) # get random index to rows \n rand_row = rows_query.all()[rand_index] # use random index to get random row\n" }, { "answer_id": 50345203, "author": "Charles Wang", "author_id": 3155630, "author_profile": "https://Stackoverflow.com/users/3155630", "pm_score": 2, "selected": false, "text": "from sqlalchemy.sql.expression import func\n\ndef random_find_rows(sample_num):\n if not sample_num:\n return []\n\n session = DBSession()\n return session.query(Table).order_by(func.random()).limit(sample_num).all()\n" }, { "answer_id": 52692368, "author": "Ilja Everilä", "author_id": 2681632, "author_profile": "https://Stackoverflow.com/users/2681632", "pm_score": 3, "selected": false, "text": "TABLESAMPLE SYSTEM BERNOULLI FromClause.tablesample() tablesample() TableSample # Approx. 1%, using SYSTEM method\nsample1 = mytable.tablesample(1)\n\n# Approx. 1%, using BERNOULLI method\nsample2 = mytable.tablesample(func.bernoulli(1))\n TableSample sample = aliased(MyModel, tablesample(MyModel, 1))\nres = session.query(sample).all()\n In [24]: %%timeit\n ...: foo.select().\\\n ...: order_by(func.random()).\\\n ...: limit(select([func.round(func.count() * 0.01)]).\n ...: select_from(foo).\n ...: as_scalar()).\\\n ...: execute().\\\n ...: fetchall()\n ...: \n307 ms ± 5.72 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nIn [25]: %timeit foo.tablesample(1).select().execute().fetchall()\n6.36 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [26]: %timeit foo.tablesample(func.bernoulli(1)).select().execute().fetchall()\n19.8 ms ± 381 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n SYSTEM from sqlalchemy.ext.compiler import compiles\nfrom sqlalchemy.sql import TableSample\n\n@compiles(TableSample)\ndef visit_tablesample(tablesample, self, asfrom=False, **kw):\n \"\"\" Compile `TableSample` with values inlined.\n \"\"\"\n kw_literal_binds = {**kw, \"literal_binds\": True}\n text = \"%s TABLESAMPLE %s\" % (\n self.visit_alias(tablesample, asfrom=True, **kw),\n tablesample._get_method()._compiler_dispatch(self, **kw_literal_binds),\n )\n\n if tablesample.seed is not None:\n text += \" REPEATABLE (%s)\" % (\n tablesample.seed._compiler_dispatch(self, **kw_literal_binds)\n )\n\n return text\n\nfrom sqlalchemy import table, literal, text\n\n# Static percentage\nprint(table(\"tbl\").tablesample(text(\"5 PERCENT\")))\n# Compiler inlined values\nprint(table(\"tbl\").tablesample(5, seed=literal(42)))\n" }, { "answer_id": 62321734, "author": "Anas", "author_id": 12861001, "author_profile": "https://Stackoverflow.com/users/12861001", "pm_score": -1, "selected": false, "text": "#first import the random module\nimport random\n\n#then choose what ever Model you want inside random.choise() method\nget_questions = random.choice(Question.query.all())\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
60,825
<p>I am working on a web application, where I transfer data from the server to the browser in XML.</p> <p>Since I'm danish, I quickly run into problems with the characters <code>æøå</code>.</p> <p>I know that in html, I use the <code>"&amp;amp;aelig;&amp;amp;oslash;&amp;amp;aring;"</code> for <code>æøå</code>.</p> <p>however, as soon as the chars pass through JavaScript, I get black boxes with <code>"?"</code> in them when using <code>æøå</code>, and <code>"&amp;aelig;&amp;oslash;&amp;aring;"</code> is printed as is.</p> <p>I've made sure to set it to utf-8, but that isn't helping much.</p> <p>Ideally, I want it to work with any special characters (naturally).</p> <p>The example that isn't working is included below:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8"&gt; alert("&amp;aelig;&amp;oslash;&amp;aring;"); alert("æøå"); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What am I doing wrong?</p> <hr> <p>Ok, thanks to Grapefrukts answer, I got it working.</p> <p>I actually needed it for data coming from an MySQL server. Since the saving of the files in UTF-8 encoding only solves the problem for static content, I figure I'd include the solution for strings from a MySQL server, pulled out using PHP:</p> <p><code>utf8_encode($MyStringHere)</code></p>
[ { "answer_id": 60832, "author": "chryss", "author_id": 5169, "author_profile": "https://Stackoverflow.com/users/5169", "pm_score": 0, "selected": false, "text": "alert(\"&aelig;&oslash;&aring;\");\n alert(\"æøå\");\n AddCharset utf-8 .js\n" }, { "answer_id": 67289, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 3, "selected": false, "text": "String.fromCharCode() String.fromCharCode( 8226 )" }, { "answer_id": 144878, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 5, "selected": false, "text": "\\u alert(\"\\u00e6\\u00f8\\u00e5\")\n" }, { "answer_id": 17870496, "author": "Kayun Chantarasathaporn", "author_id": 2620771, "author_profile": "https://Stackoverflow.com/users/2620771", "pm_score": 1, "selected": false, "text": "$message echo(\"<html><head><meta charset='utf-8'></head><body><script type='text/javascript'>alert('\" . $message . \"');</script></body></html>\");\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090/" ]
60,830
<p>While it would be very convenient to use inline functions at some situations,</p> <p>Are there any drawbacks with inline functions?</p> <p><strong>Conclusion</strong>:</p> <p>Apparently, There is nothing wrong with using inline functions.</p> <p>But it is worth noting the following points!</p> <ul> <li><p>Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Inline_Functions" rel="noreferrer">- Google Guidelines</a></p></li> <li><p>The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost <a href="http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html" rel="noreferrer">- Source</a></p></li> <li><p>There are few situations where an inline function may not work:</p> <ul> <li>For a function returning values; if a return statement exists.</li> <li>For a function not returning any values; if a loop, switch or goto statement exists. </li> <li>If a function is recursive. <a href="http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html" rel="noreferrer">-Source</a></li> </ul></li> <li><p>The <code>__inline</code> keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not <code>__inline</code> is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the <code>__inline</code> keyword to be ignored. <a href="http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/clug/zcoptinl.htm" rel="noreferrer">-Source</a></p></li> </ul>
[ { "answer_id": 60854, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "__forceinline" }, { "answer_id": 60941, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 2, "selected": false, "text": "class OtherObject;\n\nclass Object {\npublic:\n void someFunc(OtherObject& otherObj) {\n otherObj.doIt(); // Yikes requires OtherObj declaration!\n }\n};\n" }, { "answer_id": 38563033, "author": "Tom Tanner", "author_id": 1182921, "author_profile": "https://Stackoverflow.com/users/1182921", "pm_score": 0, "selected": false, "text": "#include" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ]
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
[ { "answer_id": 60862, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 7, "selected": true, "text": "dict collections.OrderedDict" }, { "answer_id": 61031, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "class ordered_dict(dict):\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n self._order = self.keys()\n\n def __setitem__(self, key, value):\n dict.__setitem__(self, key, value)\n if key in self._order:\n self._order.remove(key)\n self._order.append(key)\n\n def __delitem__(self, key):\n dict.__delitem__(self, key)\n self._order.remove(key)\n\n def order(self):\n return self._order[:]\n\n def ordered_items(self):\n return [(key,self[key]) for key in self._order]\n\n\nod = ordered_dict()\nod[\"hello\"] = \"world\"\nod[\"goodbye\"] = \"cruel world\"\nprint od.order() # prints ['hello', 'goodbye']\n\ndel od[\"hello\"]\nod[\"monty\"] = \"python\"\nprint od.order() # prints ['goodbye', 'monty']\n\nod[\"hello\"] = \"kitty\"\nprint od.order() # prints ['goodbye', 'monty', 'hello']\n\nprint od.ordered_items()\n# prints [('goodbye','cruel world'), ('monty','python'), ('hello','kitty')]\n" }, { "answer_id": 659817, "author": "Davide", "author_id": 25891, "author_profile": "https://Stackoverflow.com/users/25891", "pm_score": 1, "selected": false, "text": "my_dict={}\nmy_dict[\"foo\"]=\"bar\"\n my_dict=odict.odict()\nmy_dict[\"foo\"]=\"bar\"\n" }, { "answer_id": 24028185, "author": "A.J. Uppal", "author_id": 3113477, "author_profile": "https://Stackoverflow.com/users/3113477", "pm_score": -1, "selected": false, "text": "sorted() >>> obj = {}\n>>> obj[1] = 'Bob'\n>>> obj[2] = 'Sally'\n>>> obj[3] = 'Joe'\n>>> for k, v in sorted(obj.items()):\n... print v\n... \nBob\nSally\nJoe\n>>> \n" }, { "answer_id": 26637218, "author": "rewgoes", "author_id": 2848021, "author_profile": "https://Stackoverflow.com/users/2848021", "pm_score": 4, "selected": false, "text": "from collections import OrderedDict\na = {}\nb = OrderedDict()\nc = OrderedDict()\n\na['key1'] = 'value1'\na['key2'] = 'value2'\n\nb['key1'] = 'value1'\nb['key2'] = 'value2'\n\nc['key2'] = 'value2'\nc['key1'] = 'value1'\n\nprint a == b # True\nprint a == c # True\nprint b == c # False\n" }, { "answer_id": 51777540, "author": "Brian McCutchon", "author_id": 2093695, "author_profile": "https://Stackoverflow.com/users/2093695", "pm_score": 4, "selected": false, "text": "popitem()" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
60,874
<p>I know a few advanced ways, to change directories. <code>pushd</code> and <code>popd</code> (directory stack) or <code>cd -</code> (change to last directory).</p> <p>But I am looking for quick way to achieve the following:</p> <p>Say, I am in a rather deep dir:</p> <pre><code>/this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names </code></pre> <p>and I want to switch to </p> <pre><code>/this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names </code></pre> <p>Is there a cool/quick/geeky way to do it (without the mouse)?</p>
[ { "answer_id": 60887, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 4, "selected": true, "text": "cd ${PWD/a/another}\n $PWD ${var/foo/bar} $var" }, { "answer_id": 60936, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "CDPATH" }, { "answer_id": 66331, "author": "slipset", "author_id": 9422, "author_profile": "https://Stackoverflow.com/users/9422", "pm_score": 1, "selected": false, "text": "cd ^/a/^/another/\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ]
60,877
<p>I have a query where I wish to retrieve the oldest X records. At present my query is something like the following:</p> <pre><code>SELECT Id, Title, Comments, CreatedDate FROM MyTable WHERE CreatedDate &gt; @OlderThanDate ORDER BY CreatedDate DESC </code></pre> <p>I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first.</p> <p>So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first. I should also add that my database exists on SQL Server 2005.</p>
[ { "answer_id": 60882, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 6, "selected": true, "text": "SELECT T1.* \nFROM\n(SELECT TOP X Id, Title, Comments, CreatedDate\nFROM MyTable\nWHERE CreatedDate > @OlderThanDate\nORDER BY CreatedDate) T1\nORDER BY CreatedDate DESC\n" }, { "answer_id": 60883, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 1, "selected": false, "text": "select * \nfrom \n(\n SELECT top X Id, Title, Comments, CreatedDate\n FROM MyTable\n WHERE CreatedDate > @OlderThanDate\n ORDER BY CreatedDate \n) a\norder by createddate desc \n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5086/" ]
60,904
<p>How can I open a cmd window in a specific location without having to navigate all the way to the directory I want?</p>
[ { "answer_id": 60907, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 9, "selected": false, "text": "cmd /K \"cd C:\\Windows\\\"\n cd /d C:\\Windows\\System32\\cmd.exe /K \"cd /d H:\\Python\\\"\n" }, { "answer_id": 215534, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "system32 \\ C:\\WINDOWS\\System32\\cmd.exe.\n C:\\temp\\mp3" }, { "answer_id": 215558, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 3, "selected": false, "text": "Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Folder\\shell\\Command_Prompt_Here...]\n@=\"Command Prompt Here...\"\n\n[HKEY_CLASSES_ROOT\\Folder\\shell\\Command_Prompt_Here...\\command]\n@=\"cmd.exe \\\"%1\\\"\"\n Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Directory\\shell\\cmd]\n@=\"@shell32.dll,-8506\"\n\"Extended\"=\"\"\n\"NoWorkingDirectory\"=\"\"\n\"ShowBasedOnVelocityId\"=dword:00639bc8\n\n[HKEY_CLASSES_ROOT\\Directory\\shell\\cmd\\command]\n@=\"cmd.exe /s /k pushd \\\"%V\\\"\"\n ShowBasedOnVelocityId" }, { "answer_id": 1220972, "author": "crowdy", "author_id": 123706, "author_profile": "https://Stackoverflow.com/users/123706", "pm_score": 2, "selected": false, "text": "[HKEY_CLASSES_ROOT\\Directory\\shell\\cmd]\n@=\"command prompt here\"\n[HKEY_CLASSES_ROOT\\Directory\\shell\\cmd\\command]\n@=\"cmd.exe /c start \\\"%1\\\" cmd.exe /k cd /d %1\"\n[HKEY_CLASSES_ROOT\\Drive\\shell\\cmd]\n@=\"command prompt here\"\n[HKEY_CLASSES_ROOT\\Drive\\shell\\cmd\\command]\n@=\"cmd.exe /c start \\\"%1\\\" cmd.exe /k cd /d %1\"\n ShowBasedOnVelocityId" }, { "answer_id": 5342262, "author": "Codism", "author_id": 155253, "author_profile": "https://Stackoverflow.com/users/155253", "pm_score": 4, "selected": false, "text": "; Get working folder\nGetWorkingFolder() {\n if WinActive(\"ahk_class ExploreWClass\") or WinActive(\"ahk_class CabinetWClass\") {\n ControlGetText, path, Edit1\n return %path%\n } else if WinActive(\"FreeCommander\") {\n Send, {CTRLDOWN}{ALTDOWN}{INS}{ALTUP}{CTRLUP}\n Sleep, 100\n return clipboard\n } else {\n return \"C:\\\"\n }\n}\n\n#IfWinActive,\n\n#c::\n path := GetWorkingFolder()\n Run, %ComSpec%, %path%\n return\n\n; PowerShell\n#+C::\n path := GetWorkingFolder()\n Run, %SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe, %path%\n return\n\n#^c::\n Run, %ComSpec%, %temp%\n return\n\n#!c::\n path := GetWorkingFolder()\n Run, %comspec% /k \"%VS90COMNTOOLS%vsvars32.bat\", %path%\n return\n\n; irb\n#!b::\n path := GetWorkingFolder()\n Run, c:\\cygwin\\bin\\ruby /usr/bin/irb, %path%\n return\n\n; Bash\n#b::\n path := GetWorkingFolder()\n Run, bash --login, %path%\n return\n\n; Paste in console\n+INS::\n if WinActive(\"ahk_class ConsoleWindowClass\") {\n WinGetPos, x, y, w, h, A\n MouseGetPos, mx, my\n ;MsgBox x=%x% y=%y% w=%w% h=%h% mx=%mx% my=%my%\n if (mx < 10)\n mx = 10\n else if (mx > w - 30)\n mx := w - 30\n\n if (my < 40)\n my = 40\n else if (my > h)\n my := h - 10\n\n MouseClick, right, mx, my\n }\n return\n" }, { "answer_id": 28795485, "author": "TiagoLr", "author_id": 4052701, "author_profile": "https://Stackoverflow.com/users/4052701", "pm_score": 4, "selected": false, "text": "Alt + D cmd" }, { "answer_id": 33021825, "author": "Edward Gavilán", "author_id": 5420048, "author_profile": "https://Stackoverflow.com/users/5420048", "pm_score": 2, "selected": false, "text": "START cd C:\\Users\n" }, { "answer_id": 34534874, "author": "Forest Jackdaw", "author_id": 5731710, "author_profile": "https://Stackoverflow.com/users/5731710", "pm_score": 2, "selected": false, "text": "cmd.exe Send to cmd.exe Open command window here shell:sendto Send to Command Prompt .lnk %windir%\\system32\\cmd.exe /k cd /d Send to cmd cmd Command Prompt (cd) Send to" }, { "answer_id": 35293994, "author": "ofir_aghai", "author_id": 2591785, "author_profile": "https://Stackoverflow.com/users/2591785", "pm_score": 3, "selected": false, "text": "Shift right click press and hold folder drive click/tap Open Command Prompt Here" }, { "answer_id": 37605054, "author": "Syed. A", "author_id": 1913743, "author_profile": "https://Stackoverflow.com/users/1913743", "pm_score": 4, "selected": false, "text": "cmd" }, { "answer_id": 41578578, "author": "Guillermo", "author_id": 686777, "author_profile": "https://Stackoverflow.com/users/686777", "pm_score": 5, "selected": false, "text": "cmd" }, { "answer_id": 43426901, "author": "cagcak", "author_id": 2153187, "author_profile": "https://Stackoverflow.com/users/2153187", "pm_score": 0, "selected": false, "text": "path_of_the_cmder /START target_path_wish_to_run TARGET C:\\Users\\<username>i\\AppData\\Roaming\\cmder\\Cmder.exe /START C:\\SOURCE\\" }, { "answer_id": 44212019, "author": "Niraj Shakya", "author_id": 5383415, "author_profile": "https://Stackoverflow.com/users/5383415", "pm_score": 1, "selected": false, "text": "\"shift + mouse right click \" cmd" }, { "answer_id": 45469822, "author": "FocusedWolf", "author_id": 490748, "author_profile": "https://Stackoverflow.com/users/490748", "pm_score": 3, "selected": false, "text": "Right-click a folder icon (or the empty background area inside an already open folder)\nand click either \"Open in Terminal\" or \"Open in Terminal (Admin)\".\n\nYou can also right click files to execute them with a command window.\nWhen the file is done running you are left with a command window that is navigated to the files directory.\n Windows Registry Editor Version 5.00\n\n; Admin versions.\n\n; Right click on a folder in a directory.\n[HKEY_CLASSES_ROOT\\Directory\\shell\\OpenCommandWindowHereAsAdministrator]\n@=\"Open in Terminal (Admin)\"\n\"Icon\"=\"cmd.exe\"\n\"HasLUAShield\"=\"\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\Directory\\shell\\OpenCommandWindowHereAsAdministrator\\command]\n@=\"cmd.exe /c powershell.exe -Command \\\"Start-Process cmd -Verb runas -ArgumentList '/k pushd \\\"%1\\\"'\\\"\"\n\n; Right click on nothing in a directory, i.e. the \"background\" of the directory.\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\OpenCommandWindowHereAsAdministrator]\n@=\"Open in Terminal (Admin)\"\n\"Icon\"=\"cmd.exe\"\n\"HasLUAShield\"=\"\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\OpenCommandWindowHereAsAdministrator\\command]\n@=\"cmd.exe /c powershell.exe -Command \\\"Start-Process cmd -Verb runas -ArgumentList '/k pushd \\\"%V\\\"'\\\"\"\n\n; Right click on nothing in a library directory, i.e. the \"background\" of the library directory.\n[HKEY_CLASSES_ROOT\\LibraryFolder\\Background\\shell\\OpenCommandWindowHereAsAdministrator]\n@=\"Open in Terminal (Admin)\"\n\"Icon\"=\"cmd.exe\"\n\"HasLUAShield\"=\"\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\LibraryFolder\\Background\\shell\\OpenCommandWindowHereAsAdministrator\\command]\n@=\"cmd.exe /c powershell.exe -Command \\\"Start-Process cmd -Verb runas -ArgumentList '/k pushd \\\"%V\\\"'\\\"\"\n\n; Right click on a file in a directory.\n[HKEY_CLASSES_ROOT\\*\\shell\\OpenWithCommandWindowAsAdministrator]\n@=\"Open in Terminal (Admin)\"\n\"Icon\"=\"cmd.exe\"\n\"HasLUAShield\"=\"\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\*\\shell\\OpenWithCommandWindowAsAdministrator\\command]\n@=\"cmd.exe /c powershell.exe -Command \\\"Start-Process cmd -Verb runas -ArgumentList '/k pushd \\\\\\\"%W \\\\\\\" && \\\\\\\"%1\\\\\\\"'\\\"\"\n\n; Non-Admin versions.\n\n; Right click on a folder in a directory.\n[HKEY_CLASSES_ROOT\\Directory\\shell\\OpenCommandWindowHere]\n@=\"Open in Terminal\"\n\"Icon\"=\"cmd.exe\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\Directory\\shell\\OpenCommandWindowHere\\command]\n@=\"cmd.exe /k pushd \\\"%1\\\"\"\n\n; Right click on nothing in a directory, i.e. the \"background\" of the directory.\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\OpenCommandWindowHere]\n@=\"Open in Terminal\"\n\"Icon\"=\"cmd.exe\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\OpenCommandWindowHere\\command]\n@=\"cmd.exe /k pushd \\\"%V\\\"\"\n\n; Right click on nothing in a library directory, i.e. the \"background\" of the library directory.\n[HKEY_CLASSES_ROOT\\LibraryFolder\\Background\\shell\\OpenCommandWindowHere]\n@=\"Open in Terminal\"\n\"Icon\"=\"cmd.exe\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\LibraryFolder\\Background\\shell\\OpenCommandWindowHere\\command]\n@=\"cmd.exe /k pushd \\\"%V\\\"\"\n\n; Right click on a file in a directory.\n[HKEY_CLASSES_ROOT\\*\\shell\\OpenWithCommandWindow]\n@=\"Open in Terminal\"\n\"Icon\"=\"cmd.exe\"\n\"Position\"=\"middle\"\n[HKEY_CLASSES_ROOT\\*\\shell\\OpenWithCommandWindow\\command]\n@=\"cmd.exe /k pushd \\\"%W\\\" && \\\"%1\\\"\"\n Windows Registry Editor Version 5.00\n\n[-HKEY_CLASSES_ROOT\\Directory\\shell\\OpenCommandWindowHereAsAdministrator]\n[-HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\OpenCommandWindowHereAsAdministrator]\n[-HKEY_CLASSES_ROOT\\LibraryFolder\\Background\\shell\\OpenCommandWindowHereAsAdministrator]\n[-HKEY_CLASSES_ROOT\\*\\shell\\OpenWithCommandWindowAsAdministrator]\n[-HKEY_CLASSES_ROOT\\Directory\\shell\\OpenCommandWindowHere]\n[-HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\OpenCommandWindowHere]\n[-HKEY_CLASSES_ROOT\\LibraryFolder\\Background\\shell\\OpenCommandWindowHere]\n[-HKEY_CLASSES_ROOT\\*\\shell\\OpenWithCommandWindow]\n" }, { "answer_id": 45563746, "author": "Mendi Barel", "author_id": 2840531, "author_profile": "https://Stackoverflow.com/users/2840531", "pm_score": 3, "selected": false, "text": "cmd /k \"pushd D:\\Music\"\n" }, { "answer_id": 50422879, "author": "curiousBoy", "author_id": 2166856, "author_profile": "https://Stackoverflow.com/users/2166856", "pm_score": 2, "selected": false, "text": "@ECHO OFF \ncd C:\\YourProjectPath\\FolderPath\\ goto-myProjectName" }, { "answer_id": 52266173, "author": "Alex T", "author_id": 2658643, "author_profile": "https://Stackoverflow.com/users/2658643", "pm_score": 2, "selected": false, "text": " start cd c:\\MyTargetFolder\n" }, { "answer_id": 56254760, "author": "Gerold Broser", "author_id": 1744774, "author_profile": "https://Stackoverflow.com/users/1744774", "pm_score": 2, "selected": false, "text": "HKCR\\Directory\\shell Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Folder\\shell\\cmd]\n@=\"Open CMD here...\"\n\n[HKEY_CLASSES_ROOT\\Folder\\shell\\cmd\\command]\n@=\"C:\\\\Windows\\\\system32\\\\cmd.exe /k pushd \\\"%1\\\"\"\n" }, { "answer_id": 56489448, "author": "U.A", "author_id": 11000016, "author_profile": "https://Stackoverflow.com/users/11000016", "pm_score": 1, "selected": false, "text": "start .\n" }, { "answer_id": 68227863, "author": "Julien Jm", "author_id": 12814623, "author_profile": "https://Stackoverflow.com/users/12814623", "pm_score": 3, "selected": false, "text": "Alt A cmd Enter Alt f s a" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
60,910
<p>I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change. </p>
[ { "answer_id": 60948, "author": "Natalie Weizenbaum", "author_id": 2518, "author_profile": "https://Stackoverflow.com/users/2518", "pm_score": 4, "selected": true, "text": "(set-default-font \"-apple-bitstream vera sans mono-medium-r-normal--0-0-0-0-m-0-mac-roman\")\n (x-list-fonts \"searchterm\") *scratch* C-j" }, { "answer_id": 2424197, "author": "fikovnik", "author_id": 219584, "author_profile": "https://Stackoverflow.com/users/219584", "pm_score": 2, "selected": false, "text": " -apple-DejaVu_Sans_Mono-medium-normal-normal-*-12-*-*-*-m-0-iso10646-1\n (set-default-font \"-apple-DejaVu_Sans_Mono-medium-normal-normal-*-12-*-*-*-m-0-iso10646-1\")\n" }, { "answer_id": 58135994, "author": "chrisinmtown", "author_id": 1630244, "author_profile": "https://Stackoverflow.com/users/1630244", "pm_score": 1, "selected": false, "text": "(when window-system\n (setq initial-frame-alist nil) ;; Undo Aquamacs forced defaults\n (setq default-frame-alist nil) ;; Undo Aquamacs forced defaults\n (aquamacs-autoface-mode -1) ;; Use one face (font) everywhere\n (set-frame-font \"Menlo-12\") ;; Set the default font to Menlo size 12\n ;;(set-default-font \"Menlo-12\") ;; This would do the same.\n)\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
60,918
<p>I'm trying to do 'Attach to Process' for debugging in Visual Studio 2008 and I can't figure out what process to attach to. Help.</p>
[ { "answer_id": 6362634, "author": "Robin Minto", "author_id": 1456, "author_profile": "https://Stackoverflow.com/users/1456", "pm_score": 4, "selected": false, "text": "cscript iisapp.vbs appcmd list wp" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
60,919
<p>Can I use this approach efficiently?</p> <pre><code>using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString)) { cmd.Connection.Open(); // set up parameters and CommandType to StoredProcedure etc. etc. cmd.ExecuteNonQuery(); } </code></pre> <p>My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?</p>
[ { "answer_id": 60934, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 8, "selected": true, "text": "SqlCommand SqlConnection using (SqlConnection conn = new SqlConnection(connstring))\n{\n conn.Open();\n using (SqlCommand cmd = new SqlCommand(cmdstring, conn))\n {\n cmd.ExecuteNonQuery();\n }\n}\n SqlConnection conn = new SqlConnection(connstring);\nconn.Open();\n\nusing (SqlCommand cmd = new SqlCommand(\"select field from table where fieldid = 1\", conn))\n{\n Console.WriteLine(cmd.ExecuteScalar().ToString());\n}\n\nusing (SqlCommand cmd = new SqlCommand(\"select field from table where fieldid = 2\", conn))\n{\n Console.WriteLine(cmd.ExecuteScalar().ToString());\n}\n\nconn.Dispose(); \n" }, { "answer_id": 5654064, "author": "Chuck Bevitt", "author_id": 704658, "author_profile": "https://Stackoverflow.com/users/704658", "pm_score": -1, "selected": false, "text": "private void DisposeCommand(SqlCommand cmd)\n{\n try\n {\n if (cmd != null)\n {\n if (cmd.Connection != null)\n {\n cmd.Connection.Close();\n cmd.Connection.Dispose();\n }\n cmd.Dispose();\n }\n }\n catch { } //don't blow up\n}\n finally\n {\n DisposeCommand(cmd);\n }\n" }, { "answer_id": 59635946, "author": "Keith Patrick", "author_id": 12670837, "author_profile": "https://Stackoverflow.com/users/12670837", "pm_score": 1, "selected": false, "text": "var provider = DbProviderFactories.GetFactory(\"System.Data.SqlClient\");// Or MS.Data.SqlClient\nusing (var connection = provider.CreateConnection())\n{\n connection.ConnectionString = \"...\";\n using (var command = connection.CreateCommand())\n {\n command.CommandText = \"...\";\n connection.Open();\n\n using (var reader = command.ExecuteReader())\n {\n...\n }\n }\n}\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
60,942
<p>I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3:</p> <pre><code> proc2 -&gt; stdout / proc1 \ proc3 -&gt; stdout </code></pre> <p>I tried</p> <pre><code> proc1 | (proc2 &amp; proc3) </code></pre> <p>but it doesn't seem to work, i.e.</p> <pre><code> echo 123 | (tr 1 a &amp; tr 1 b) </code></pre> <p>writes</p> <pre><code> b23 </code></pre> <p>to stdout instead of </p> <pre><code> a23 b23 </code></pre>
[ { "answer_id": 60955, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": true, "text": ">(…) bash ksh zsh echo 123 | tee >(tr 1 a) | tr 1 b zsh >(…) tee $ echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null\nb23\na23\n tee $ proc1 | tee >(proc2) ... >(procN-1) >(procN) >/dev/null\n tee" }, { "answer_id": 61716, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "PS > \"123\" | % { \n $_.Replace( \"1\", \"a\"), \n $_.Replace( \"2\", \"b\" ) \n}\n\na23\n1b3\n" }, { "answer_id": 190777, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": false, "text": "bash >(…) <(…) $(…) $(…) …" }, { "answer_id": 16541914, "author": "munish", "author_id": 730858, "author_profile": "https://Stackoverflow.com/users/730858", "pm_score": -1, "selected": false, "text": " eval `echo '&& echo 123 |'{'tr 1 a','tr 1 b'} | sed -n 's/^&&//gp'`\n a23\nb23\n" }, { "answer_id": 43906764, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 4, "selected": false, "text": "bash ksh zsh tee >(...) dash /bin/sh /bin/sh echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null\n >(...) bash ksh zsh bash ksh >(...) tee zsh 2> >(...) ksh 93u+ wait bash v4.4+ wait $! wait bash ksh | cat ksh ksh 93u+ 2> >(...) zsh | cat 2> >(...) bash ksh AFTER printf 'line %s\\n' {1..30} | tee >(cat -n) >(cat -n) >/dev/null; echo AFTER\n bash ksh zsh zsh ksh wait bash while IFS= read -r line; do \n tr 1 a <<<\"$line\"\n tr 1 b <<<\"$line\"\ndone < <(echo '123')\n parallel $ echo '123' | parallel --pipe --tee {} ::: 'tr 1 a' 'tr 1 b'\na23\nb23\n parallel man parallel parallel parallel --version bash bash bash bash fanout PATH $ echo 123 | fanout 'tr 1 a' 'tr 1 b'\n# tr 1 a\na23\n# tr 1 b\nb23\n fanout #!/usr/bin/env bash\n\n# The commands to pipe to, passed as a single string each.\naCmds=( \"$@\" )\n\n# Create a temp. directory to hold all FIFOs and captured output.\ntmpDir=\"${TMPDIR:-/tmp}/$kTHIS_NAME-$$-$(date +%s)-$RANDOM\"\nmkdir \"$tmpDir\" || exit\n# Set up a trap that automatically removes the temp dir. when this script\n# exits.\ntrap 'rm -rf \"$tmpDir\"' EXIT \n\n# Determine the number padding for the sequential FIFO / output-capture names, \n# so that *alphabetic* sorting, as done by *globbing* is equivalent to\n# *numerical* sorting.\nmaxNdx=$(( $# - 1 ))\nfmtString=\"%0${#maxNdx}d\"\n\n# Create the FIFO and output-capture filename arrays\naFifos=() aOutFiles=()\nfor (( i = 0; i <= maxNdx; ++i )); do\n printf -v suffix \"$fmtString\" $i\n aFifos[i]=\"$tmpDir/fifo-$suffix\"\n aOutFiles[i]=\"$tmpDir/out-$suffix\"\ndone\n\n# Create the FIFOs.\nmkfifo \"${aFifos[@]}\" || exit\n\n# Start all commands in the background, each reading from a dedicated FIFO.\nfor (( i = 0; i <= maxNdx; ++i )); do\n fifo=${aFifos[i]}\n outFile=${aOutFiles[i]}\n cmd=${aCmds[i]}\n printf '# %s\\n' \"$cmd\" > \"$outFile\"\n eval \"$cmd\" < \"$fifo\" >> \"$outFile\" &\ndone\n\n# Now tee stdin to all FIFOs.\ntee \"${aFifos[@]}\" >/dev/null || exit\n\n# Wait for all background processes to finish.\nwait\n\n# Print all captured stdout output, grouped by target command, in sequences.\ncat \"${aOutFiles[@]}\"\n" }, { "answer_id": 62188317, "author": "exic", "author_id": 332451, "author_profile": "https://Stackoverflow.com/users/332451", "pm_score": 1, "selected": false, "text": "out=$(proc1); echo \"$out\" | proc2; echo \"$out\" | proc3\n proc1 proc1 out=$(proc1); echo $(echo \"$out\" | proc2) / $(echo \"$out\" | proc3) | bc\n | tee >(proc2) >(proc3) >/dev/null" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4085/" ]
60,950
<p>I find working on the command line in Windows frustrating, primarily because the console window is wretched to use compared to terminal applications on linux and OS X such as "rxvt", "xterm", or "Terminal". Major complaints:</p> <ol> <li><p>No standard copy/paste. You have to turn on "mark" mode and it's only available from a multi-level popup triggered by the (small) left hand corner button. Then copy and paste need to be invoked from the same menu</p></li> <li><p>You can't arbitrarily resize the window by dragging, you need to set a preference (back to the multi-level popup) each time you want to resize a window</p></li> <li><p>You can only make the window so big before horizontal scroll bars enter the picture. Horizontal scroll bars suck.</p></li> <li><p>With the cmd.exe shell, you can't navigate to folders with \\netpath notation (UNC?), you need to map a network drive. This sucks when working on multiple machines that are going to have different drives mapped</p></li> </ol> <p>Are there any tricks or applications, (paid or otherwise), that address these issue?</p>
[ { "answer_id": 60956, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 5, "selected": false, "text": "xterm" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
60,977
<p>Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time.</p> <p>Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the future. Each subsequent recompile has the same problem.</p> <p>Solution that I know are:</p> <p>a) Find the file that has the future time and re-save it. This method is not ideal because the project is very big and it takes time even for windows advanced search to find the files that are changed.</p> <p>b) Delete the whole project and re-check it out from svn.</p> <p>Does anyone know how I can get around this problem?</p> <p>Is there perhaps a setting in visual studio that will allow me to tell the compiler to use the archive bit instead of the last modification date to detect source file changes?</p> <p>Or perhaps there is a recursive modification date reset tool that can be used in this situation?</p>
[ { "answer_id": 61015, "author": "Nathan Jones", "author_id": 5848, "author_profile": "https://Stackoverflow.com/users/5848", "pm_score": 1, "selected": false, "text": "touch temp\nfind . -newer temp -exec touch {} ;\nrm temp\n" }, { "answer_id": 61105, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": true, "text": "Get-ChildItem -r . | \n ? { $_.LastWriteTime -gt ([DateTime]::Now) } | \n Set-ItemProperty -Name \"LastWriteTime\" -Value ([DateTime]::Now)\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
61,000
<p>I am wondering what directory structure are commonly used in development projects. I mean with the idea of facilitating builds, deploys release, and etc.</p> <p>I recently used a <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="nofollow noreferrer">Maven structure</a> for a java project, but I am not sure it's the best structure for a non-maven driven project.</p> <p>So, I have two questions: When you guys start new projects, what structure you use? And: What if you need to integrate two different languages, like for example java classes into a PHP application; PHP files are source files, web files, you you use a /src, /classes, webapps/php ? What are your choices in such scenarios. </p> <p>As a note: I am wondering also what are you choices for directories names. I like the 3-letters names (src, lib, bin, web, img, css, xml, cfg) but what are your opinions about descriptive names like libraris, sources or htdocs/public_html ?</p>
[ { "answer_id": 4540307, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 4, "selected": true, "text": "/project_name (everything goes here)\n /web (htdocs)\n /img\n /css\n /app (usually some framework or sensitive code)\n /lib (externa libs)\n /vendor_1\n /vendor_2\n /tmp\n /cache\n /sql (sql scripts usually with maybe diagrams)\n /scripts\n /doc (usually an empty directory)\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
61,002
<p>I'd like to script, preferably in rake, the following actions into a single command:</p> <ol> <li>Get the version of my local git repository.</li> <li>Git pull the latest code.</li> <li>Git diff from the version I extracted in step #1 to what is now in my local repository.</li> </ol> <p>In other words, I want to get the latest code form the central repository and immediately generate a diff of what's changed since the last time I pulled.</p>
[ { "answer_id": 61004, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "git fetch\ngit diff ...origin\n git pull" }, { "answer_id": 61477, "author": "Greg", "author_id": 108, "author_profile": "https://Stackoverflow.com/users/108", "pm_score": 4, "selected": false, "text": "git config remote.origin.url <url>\n @ECHO off\n\n:: Retrieve the changes, but don't merge them.\ngit fetch\n\n:: Look at the new changes\ngit diff ...origin\n\n:: Ask if you want to merge the new changes into HEAD\nset /p PULL=Do you wish to pull the changes? (Y/N)\nIF /I %PULL%==Y git pull\n" }, { "answer_id": 62303, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 8, "selected": true, "text": "git pull origin\ngit diff @{1}..\n current=`git rev-parse HEAD`\ngit pull origin\ngit diff $current..\n git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..\n" }, { "answer_id": 2831146, "author": "Clintm", "author_id": 3384609, "author_profile": "https://Stackoverflow.com/users/3384609", "pm_score": 2, "selected": false, "text": "function parse_git_branch {\n git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \\(.*\\)/\\1/'\n}\nfunction gd2 { \n echo branch \\($1\\) has these commits and \\($2\\) does not \n git log $2..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local\n}\nfunction grin {\n git fetch origin master\n gd2 FETCH_HEAD $(parse_git_branch)\n}\nfunction grout {\n git fetch origin master\n gd2 $(parse_git_branch) FETCH_HEAD\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061/" ]
61,005
<p>What are the best file permission settings for PHP scripts? Any suggestions on ways to figure out the minimum required permissions?</p>
[ { "answer_id": 61004, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "git fetch\ngit diff ...origin\n git pull" }, { "answer_id": 61477, "author": "Greg", "author_id": 108, "author_profile": "https://Stackoverflow.com/users/108", "pm_score": 4, "selected": false, "text": "git config remote.origin.url <url>\n @ECHO off\n\n:: Retrieve the changes, but don't merge them.\ngit fetch\n\n:: Look at the new changes\ngit diff ...origin\n\n:: Ask if you want to merge the new changes into HEAD\nset /p PULL=Do you wish to pull the changes? (Y/N)\nIF /I %PULL%==Y git pull\n" }, { "answer_id": 62303, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 8, "selected": true, "text": "git pull origin\ngit diff @{1}..\n current=`git rev-parse HEAD`\ngit pull origin\ngit diff $current..\n git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..\n" }, { "answer_id": 2831146, "author": "Clintm", "author_id": 3384609, "author_profile": "https://Stackoverflow.com/users/3384609", "pm_score": 2, "selected": false, "text": "function parse_git_branch {\n git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \\(.*\\)/\\1/'\n}\nfunction gd2 { \n echo branch \\($1\\) has these commits and \\($2\\) does not \n git log $2..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local\n}\nfunction grin {\n git fetch origin master\n gd2 FETCH_HEAD $(parse_git_branch)\n}\nfunction grout {\n git fetch origin master\n gd2 $(parse_git_branch) FETCH_HEAD\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
61,033
<p>I've got a table of URLs and I don't want any duplicate URLs. How do I check to see if a given URL is already in the table using PHP/MySQL?</p>
[ { "answer_id": 61035, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": -1, "selected": false, "text": "SELECT url FROM urls WHERE url = 'http://asdf.com' LIMIT 1\n" }, { "answer_id": 61036, "author": "roman m", "author_id": 3661, "author_profile": "https://Stackoverflow.com/users/3661", "pm_score": 2, "selected": false, "text": "IF NOT EXISTS (SELECT 1 FROM YOURTABLE WHERE URL = 'URL')\nINSERT INTO YOURTABLE (...) VALUES (...)\n" }, { "answer_id": 61045, "author": "Joe Mahoney", "author_id": 575, "author_profile": "https://Stackoverflow.com/users/575", "pm_score": 4, "selected": false, "text": "alter table urls add constraint unique_url unique (url);\n" }, { "answer_id": 62307, "author": "Jean Paul Galea", "author_id": 6618, "author_profile": "https://Stackoverflow.com/users/6618", "pm_score": 1, "selected": false, "text": "urls" }, { "answer_id": 7085163, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 0, "selected": false, "text": "$url = \"http://www.scroogle.com\";\n\n$query = \"SELECT `id` FROM `urls` WHERE `url` = '$url' \";\n$resultdb = mysql_query($query) or die(mysql_error()); \nlist($idtemp) = mysql_fetch_array($resultdb) ;\n\nif(empty($idtemp)) // if $idtemp is empty the url doesn't exist and we go ahead and insert it into the db.\n{ \n mysql_query(\"INSERT INTO urls (`url` ) VALUES('$url') \") or die (mysql_error());\n}else{\n //do something else if the url already exists in the DB\n}\n" }, { "answer_id": 7087626, "author": "Steve Buzonas", "author_id": 816584, "author_profile": "https://Stackoverflow.com/users/816584", "pm_score": 3, "selected": false, "text": "SELECT COUNT(*) AS UrlResults FROM websites WHERE url='http://www.domain.com'\n ALTER TABLE websites ADD UNIQUE (url)\n REPLACE INTO websites (url, data) VALUES ('http://www.domain.com', 'random data')\n INSERT INTO websites (url, data) VALUES ('http://www.domain.com', 'random data')\nON DUPLICATE KEY UPDATE data='random data'\n" }, { "answer_id": 7093198, "author": "Mike Sherrill 'Cat Recall'", "author_id": 562459, "author_profile": "https://Stackoverflow.com/users/562459", "pm_score": 4, "selected": false, "text": "UNIQUE (url, resource_locator)" }, { "answer_id": 7122583, "author": "Matt", "author_id": 61256, "author_profile": "https://Stackoverflow.com/users/61256", "pm_score": 0, "selected": false, "text": "primary key" }, { "answer_id": 7128282, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 5, "selected": false, "text": "http://www.example.com/ links SELECT * FROM links WHERE url = 'http://www.example.com/';\n $conn = mysql_connect('localhost', 'username', 'password');\nif (!$conn)\n{\n die('Could not connect to database');\n}\nif(!mysql_select_db('mydb', $conn))\n{\n die('Could not select database mydb');\n}\n\n$result = mysql_query(\"SELECT * FROM links WHERE url = 'http://www.example.com/'\", $conn);\n\nif (!$result)\n{\n die('There was a problem executing the query');\n}\n\n$number_of_rows = mysql_num_rows($result);\n\nif ($number_of_rows > 0)\n{\n die('This URL already exists in the database');\n}\n $conn mysql_query mysql_connect mysql_select_db CREATE TABLE links\n(\n url VARCHAR(255) NOT NULL,\n last_visited TIMESTAMP\n)\n CREATE TABLE links\n(\n url VARCHAR(255) NOT NULL,\n last_visited TIMESTAMP,\n PRIMARY KEY (url)\n)\n $result = mysql_query(\"INSERT INTO links (url, last_visited) VALUES ('http://www.example.com/', NOW()\", $conn);\n\nif (!$result)\n{\n die('Could not Insert Row 1');\n}\n\n$result2 = mysql_query(\"INSERT INTO links (url, last_visited) VALUES ('http://www.example.com/', NOW()\", $conn);\n\nif (!$result2)\n{\n die('Could not Insert Row 2');\n}\n Could not Insert Row 2 Could not Insert Row 1 CREATE TABLE users (\n username VARCHAR(255) NOT NULL,\n password VARCHAR(40) NOT NULL,\n PRIMARY KEY (username)\n)\n CREATE TABLE users (\n user_id INT(10) NOT NULL AUTO_INCREMENT,\n username VARCHAR(255) NOT NULL,\n password VARCHAR(40) NOT NULL,\n PRIMARY KEY (`user_id`)\n)\n INSERT INTO users (username, password) VALUES('Mez', 'd3571ce95af4dc281f142add33384abc5e574671');\n INSERT INTO users (username, password) VALUES('User', '988881adc9fc3655077dc2d4d757d480b5ea0e11');\n mysql> SELECT * FROM users;\n+---------+----------+------------------------------------------+\n| user_id | username | password |\n+---------+----------+------------------------------------------+\n| 1 | Mez | d3571ce95af4dc281f142add33384abc5e574671 |\n| 2 | User | 988881adc9fc3655077dc2d4d757d480b5ea0e11 |\n+---------+----------+------------------------------------------+\n2 rows in set (0.00 sec)\n mysql> SELECT * FROM users;\n+---------+----------+------------------------------------------+\n| user_id | username | password |\n+---------+----------+------------------------------------------+\n| 1 | Mez | d3571ce95af4dc281f142add33384abc5e574671 |\n| 2 | User | 988881adc9fc3655077dc2d4d757d480b5ea0e11 |\n| 3 | Mez | d3571ce95af4dc281f142add33384abc5e574671 |\n+---------+----------+------------------------------------------+\n3 rows in set (0.00 sec)\n CREATE TABLE users (\n user_id INT(10) NOT NULL AUTO_INCREMENT,\n username VARCHAR(255) NOT NULL,\n password VARCHAR(40) NOT NULL,\n PRIMARY KEY (user_id),\n UNIQUE KEY (username)\n)\n mysql> INSERT INTO users (username, password) VALUES('Mez', 'd3571ce95af4dc281f142add33384abc5e574671');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO users (username, password) VALUES('Mez', 'd3571ce95af4dc281f142add33384abc5e574671');\nERROR 1062 (23000): Duplicate entry 'Mez' for key 'username'\n CREATE TABLE links\n(\n link_id INT(10) NOT NULL AUTO_INCREMENT,\n url VARCHAR(255) NOT NULL,\n last_visited TIMESTAMP,\n PRIMARY KEY (link_id),\n UNIQUE KEY (url)\n)\n INSERT INTO links (url, last_visited) VALUES ('http://www.example.com/', NOW());\n ERROR 1062 (23000): Duplicate entry 'http://www.example.com/' for key 'url'\n $result = mysql_query(\"SELECT * FROM links WHERE url = 'http://www.example.com/'\", $conn);\n\nif (!$result)\n{\n die('There was a problem executing the query');\n}\n\n$number_of_rows = mysql_num_rows($result);\n\nif ($number_of_rows > 0)\n{\n $result = mysql_query(\"UPDATE links SET last_visited = NOW() WHERE url = 'http://www.example.com/'\", $conn);\n\n if (!$result)\n {\n die('There was a problem updating the links table');\n }\n}\n if (!$result)\n{\n die('There was a problem executing the query');\n}\n\n$number_of_rows = mysql_num_rows($result);\n\nif ($number_of_rows > 0)\n{\n $row = mysql_fetch_assoc($result);\n\n $result = mysql_query('UPDATE links SET last_visited = NOW() WHERE link_id = ' . intval($row['link_id'], $conn);\n\n if (!$result)\n {\n die('There was a problem updating the links table');\n }\n}\n REPLACE INTO mysql> SELECT * FROM links;\n+---------+-------------------------+---------------------+\n| link_id | url | last_visited |\n+---------+-------------------------+---------------------+\n| 1 | http://www.example.com/ | 2011-08-19 23:48:03 |\n+---------+-------------------------+---------------------+\n1 row in set (0.00 sec)\n\nmysql> INSERT INTO links (url, last_visited) VALUES ('http://www.example.com/', NOW());\nERROR 1062 (23000): Duplicate entry 'http://www.example.com/' for key 'url'\nmysql> REPLACE INTO links (url, last_visited) VALUES ('http://www.example.com/', NOW());\nQuery OK, 2 rows affected (0.00 sec)\n\nmysql> SELECT * FROM links;\n+---------+-------------------------+---------------------+\n| link_id | url | last_visited |\n+---------+-------------------------+---------------------+\n| 2 | http://www.example.com/ | 2011-08-19 23:55:55 |\n+---------+-------------------------+---------------------+\n1 row in set (0.00 sec)\n REPLACE INTO REPLACE INTO mysql> REPLACE INTO links (url, last_visited) VALUES ('http://www.stackoverflow.com/', NOW());\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> SELECT * FROM links;\n+---------+-------------------------------+---------------------+\n| link_id | url | last_visited |\n+---------+-------------------------------+---------------------+\n| 2 | http://www.example.com/ | 2011-08-20 00:00:07 |\n| 3 | http://www.stackoverflow.com/ | 2011-08-20 00:01:22 |\n+---------+-------------------------------+---------------------+\n2 rows in set (0.00 sec)\n" }, { "answer_id": 7128408, "author": "Matthew", "author_id": 369775, "author_profile": "https://Stackoverflow.com/users/369775", "pm_score": 0, "selected": false, "text": "SELECT\n *\nFROM\n yourTable a\nJOIN\n yourTable b -- Join the same table\n ON b.[URL] = a.[URL] -- where the URL's match\n AND b.[PK] <> b.[PK] -- but the PK's are different\n WHERE\n a.[PK] NOT IN (\n SELECT \n TOP 1 c.[PK] -- Only grabbing the original!\n FROM\n yourTable c\n WHERE\n c.[URL] = a.[URL] -- has the same URL\n ORDER BY\n c.[PK] ASC) -- sort it by whatever your criterion is for \"original\"\n DELETE IN INSERT SELECT \n 1\nWHERE\n EXISTS (SELECT * FROM yourTable WHERE [URL] = 'testValue')\n" }, { "answer_id": 7128781, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 1, "selected": false, "text": "CREATE TABLE MyURLTable(\nID INTEGER NOT NULL AUTO_INCREMENT\n,URL VARCHAR(512)\n,PRIMARY KEY(ID)\n,UNIQUE INDEX IDX_URL(URL)\n);\n CREATE TABLE MyURLTable(\nID INTEGER NOT NULL AUTO_INCREMENT\n,URL VARCHAR(512)\n,PRIMARY KEY(ID)\n,CONSTRAINT UNIQUE UNIQUE_URL(URL)\n);\n ALTER TABLE MyURLTable\nADD UNIQUE INDEX IDX_URL(URL);\n\nALTER TABLE MyURLTable\nADD CONSTRAINT UNIQUE UNIQUE_URL(URL);\n SELECT URL,COUNT(*),MIN(ID) \nFROM MyURLTable\nGROUP BY URL\nHAVING COUNT(*) > 1;\n DELETE RemoveRecords\nFROM MyURLTable As RemoveRecords\nLEFT JOIN \n(\nSELECT MIN(ID) AS ID\nFROM MyURLTable\nGROUP BY URL\nHAVING COUNT(*) > 1\nUNION\nSELECT ID\nFROM MyURLTable\nGROUP BY URL\nHAVING COUNT(*) = 1\n) AS KeepRecords\nON RemoveRecords.ID = KeepRecords.ID\nWHERE KeepRecords.ID IS NULL;\n INSERT IGNORE INTO MyURLTable(URL)\nVALUES('http://www.example.com');\n INSERT INTO MyURLTable(URL,Visits) \nVALUES('http://www.example.com',1)\nON DUPLICATE KEY UPDATE Visits=Visits+1;\n" }, { "answer_id": 7138051, "author": "Daniel Trebbien", "author_id": 196844, "author_profile": "https://Stackoverflow.com/users/196844", "pm_score": 2, "selected": false, "text": "%C3%84 %CC%88 www. Host www. &utm_source=... CREATE TABLE `urls1` (\n `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,\n `scheme` VARCHAR(20) NOT NULL,\n `canonical_login` VARCHAR(100) DEFAULT NULL COLLATE 'utf8mb4_bin',\n `canonical_host` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci', /* the \"ci\" stands for case-insensitive. Also, we want 'utf8mb4_unicode_ci'\nrather than 'utf8mb4_general_ci' because 'utf8mb4_general_ci' treats accented characters as equivalent. */\n `port` INT UNSIGNED,\n `canonical_path` VARCHAR(4096) NOT NULL COLLATE 'utf8mb4_bin',\n\n PRIMARY KEY (`id`),\n INDEX (`canonical_host`(10), `scheme`)\n) ENGINE = 'InnoDB';\n\n\nCREATE TABLE `urls2` (\n `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,\n `canonical_scheme` VARCHAR(20) NOT NULL,\n `canonical_login` VARCHAR(100) DEFAULT NULL COLLATE 'utf8mb4_bin',\n `canonical_host` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',\n `port` INT UNSIGNED,\n `canonical_path` VARCHAR(4096) NOT NULL COLLATE 'utf8mb4_bin',\n\n `orig_scheme` VARCHAR(20) NOT NULL, \n `orig_login` VARCHAR(100) DEFAULT NULL COLLATE 'utf8mb4_bin',\n `orig_host` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',\n `orig_path` VARCHAR(4096) NOT NULL COLLATE 'utf8mb4_bin',\n\n PRIMARY KEY (`id`),\n INDEX (`canonical_host`(10), `canonical_scheme`),\n INDEX (`orig_host`(10), `orig_scheme`)\n) ENGINE = 'InnoDB';\n UNIQUE" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ]
61,051
<p>You can use more than one css class in an HTML tag in current web browsers, e.g.:</p> <pre><code>&lt;div class="style1 style2 style3"&gt;foo bar&lt;/div&gt; </code></pre> <p>This hasn't always worked; with which versions did the major browsers begin correctly supporting this feature?</p>
[ { "answer_id": 61414, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 4, "selected": true, "text": "<div class=\"bold italic\">content</div>\n\n.bold {\n font-weight: 800;\n}\n\n.italic {\n font-style: italic;\n{\n .bold.italic {\n color: purple;\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3283/" ]
61,052
<p>I need to know the application's ProductCode in the Installer.OnCommitted callback. There doesn't seem to be an obvious way of determining this.</p>
[ { "answer_id": 61298, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "string productCode = (string)Context.Parameters[\"productcode\"];\n" }, { "answer_id": 67385558, "author": "aolszowka", "author_id": 433069, "author_profile": "https://Stackoverflow.com/users/433069", "pm_score": 0, "selected": false, "text": " public static string GetProductCode(string fileName)\n {\n IntPtr hInstall = IntPtr.Zero;\n try\n {\n uint num = MsiOpenPackage(fileName, ref hInstall);\n if ((ulong)num != 0)\n {\n throw new Exception(\"Cannot open database: \" + num);\n }\n\n int pcchValueBuf = 255;\n StringBuilder szValueBuf = new StringBuilder(pcchValueBuf);\n num = MsiGetProperty(hInstall, \"ProductCode\", szValueBuf, ref pcchValueBuf);\n if ((ulong)num != 0)\n {\n throw new Exception(\"Failed to Get Property ProductCode: \" + num);\n }\n return szValueBuf.ToString();\n }\n finally\n {\n if (hInstall != IntPtr.Zero)\n {\n MsiCloseHandle(hInstall);\n }\n }\n }\n\n [DllImport(\"msi.dll\", CharSet = CharSet.Unicode, EntryPoint = \"MsiGetPropertyW\", ExactSpelling = true, SetLastError = true)]\n private static extern uint MsiGetProperty(IntPtr hInstall, string szName, [Out] StringBuilder szValueBuf, ref int pchValueBuf);\n [DllImport(\"msi.dll\", CharSet = CharSet.Unicode, EntryPoint = \"MsiOpenPackageW\", ExactSpelling = true, SetLastError = true)]\n private static extern uint MsiOpenPackage(string szDatabasePath, ref IntPtr hProduct);\n [DllImport(\"msi.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]\n private static extern int MsiCloseHandle(IntPtr hAny);\n\n Function Description\nMsiGetProperty Supports a limited set of properties when used with deferred execution custom actions:\n the CustomActionData property, ProductCode property, and UserSID property.Commit custom\n actions cannot use the MsiGetProperty function to obtain the ProductCode property.\n Commit custom actions can use the CustomActionData property to obtain the product code.\n cannot use the MsiGetProperty function to obtain the ProductCode property" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
61,084
<p>I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g.</p> <pre><code>XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement("url", new XElement("loc", "http://www.example.com/page"), new XElement("lastmod", "2008-09-14")))); </code></pre> <p>The result is ...</p> <pre><code>&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"&gt; &lt;url xmlns=""&gt; &lt;loc&gt;http://www.example.com/page&lt;/loc&gt; &lt;lastmod&gt;2008-09-14&lt;/lastmod&gt; &lt;/url&gt; &lt;/urlset&gt; </code></pre> <p>I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?</p>
[ { "answer_id": 61141, "author": "Micah", "author_id": 6209, "author_profile": "https://Stackoverflow.com/users/6209", "pm_score": 6, "selected": true, "text": "XDocument xdoc = new XDocument(new XDeclaration(\"1.0\", \"utf-8\", \"true\"),\nnew XElement(ns + \"urlset\",\nnew XElement(ns + \"url\",\n new XElement(ns + \"loc\", \"http://www.example.com/page\"),\n new XElement(ns + \"lastmod\", \"2008-09-14\"))));\n <urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <url>\n <loc>http://www.example.com/page</loc>\n <lastmod>2008-09-14</lastmod>\n </url>\n</urlset>\n" }, { "answer_id": 777327, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "Imports <xmlns:ns=\"x-schema:tsSchema.xml\">\n Dim output As XDocument = <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <XML ID=\"Microsoft Search Thesaurus\">\n <thesaurus xmlns=\"x-schema:tsSchema.xml\">\n <diacritics_sensitive>0</diacritics_sensitive>\n <%= From tg In termGroups _\n Select <ns:expansion>\n <%= From t In tg _\n Select <ns:sub><%= t %></ns:sub> %>\n </ns:expansion> %>\n </thesaurus>\n </XML>\n\n output.Save(\"C:\\thesaurus.xml\")\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4449/" ]
61,085
<p>I've been trying to use SQLite with the PDO wrapper in PHP with mixed success. I can read from the database fine, but none of my updates are being committed to the database when I view the page in the browser. Curiously, running the script from my shell does update the database. I suspected file permissions as the culprit, but even with the database providing full access (chmod 777) the problem persists. Should I try changing the file owner? If so, what to?</p> <p>By the way, my machine is the standard Mac OS X Leopard install with PHP activated.</p> <p>@Tom Martin</p> <p>Thank you for your reply. I just ran your code and it looks like PHP runs as user _www. I then tried chowning the database to be owned by _www, but that didn't work either.</p> <p>I should also note that PDO's errorInfo function doesn't indicate an error took place. Could this be a setting with PDO somehow opening the database for read-only? I've heard that SQLite performs write locks on the entire file. Is it possible that the database is locked by something else preventing the write?</p> <p>I've decided to include the code in question. This is going to be more or less a port of <a href="https://stackoverflow.com/questions/6936/using-what-ive-learned-from-stackoverflow-html-scraper">Grant's script</a> to PHP. So far it's just the Questions section:</p> <pre><code>&lt;?php $db = new PDO('sqlite:test.db'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com/users/658/kyle"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIE, "shhsecret=1293706652"); $page = curl_exec($ch); preg_match('/summarycount"&gt;.*?([,\d]+)&lt;\/div&gt;.*?Reputation/s', $page, $rep); $rep = preg_replace("/,/", "", $rep[1]); preg_match('/iv class="summarycount".{10,60} (\d+)&lt;\/d.{10,140}Badges/s', $page, $badge); $badge = $badge[1]; $qreg = '/question-summary narrow.*?vote-count-post"&gt;&lt;strong.*?&gt;(-?\d*).*?\/questions\/(\d*).*?&gt;(.*?)&lt;\/a&gt;/s'; preg_match_all($qreg, $page, $questions, PREG_SET_ORDER); $areg = '/(answer-summary"&gt;&lt;a href="\/questions\/(\d*).*?votes.*?&gt;(-?\d+).*?href.*?&gt;(.*?)&lt;.a)/s'; preg_match_all($areg, $page, $answers, PREG_SET_ORDER); echo "&lt;h3&gt;Questions:&lt;/h3&gt;\n"; echo "&lt;table cellpadding=\"3\"&gt;\n"; foreach ($questions as $q) { $query = 'SELECT count(id), votes FROM Questions WHERE id = '.$q[2].' AND type=0;'; $dbitem = $db-&gt;query($query)-&gt;fetch(PDO::FETCH_ASSOC); if ($dbitem['count(id)'] &gt; 0) { $lastQ = $q[1] - $dbitem['votes']; if ($lastQ == 0) { $lastQ = ""; } $query = "UPDATE Questions SET votes = '$q[1]' WHERE id = '$q[2]'"; $db-&gt;exec($query); } else { $query = "INSERT INTO Questions VALUES('$q[3]', '$q[1]', 0, '$q[2]')"; echo "$query\n"; $db-&gt;exec($query); $lastQ = "(NEW)"; } echo "&lt;tr&gt;&lt;td&gt;$lastQ&lt;/td&gt;&lt;td align=\"right\"&gt;$q[1]&lt;/td&gt;&lt;td&gt;$q[3]&lt;/td&gt;&lt;/tr&gt;\n"; } echo "&lt;/table&gt;"; ?&gt; </code></pre>
[ { "answer_id": 61102, "author": "Tom Martin", "author_id": 5303, "author_profile": "https://Stackoverflow.com/users/5303", "pm_score": 1, "selected": false, "text": "echo exec('whoami');" }, { "answer_id": 3470364, "author": "paolo_O", "author_id": 418707, "author_profile": "https://Stackoverflow.com/users/418707", "pm_score": 0, "selected": false, "text": "try...catch" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
61,088
<p><strong>What "Hidden Features" of JavaScript do you think every programmer should know?</strong></p> <p>After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.</p> <ul> <li><a href="https://stackoverflow.com/questions/954327/">Hidden Features of HTML</a></li> <li><a href="https://stackoverflow.com/questions/628407">Hidden Features of CSS</a></li> <li><a href="https://stackoverflow.com/questions/61401/">Hidden Features of PHP</a></li> <li><a href="https://stackoverflow.com/questions/54929/">Hidden Features of ASP.NET</a></li> <li><a href="https://stackoverflow.com/questions/9033/">Hidden Features of C#</a></li> <li><a href="https://stackoverflow.com/questions/15496/">Hidden Features of Java</a></li> <li><a href="https://stackoverflow.com/questions/101268/">Hidden Features of Python</a></li> </ul> <p>Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.</p>
[ { "answer_id": 61094, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 8, "selected": false, "text": "var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z); };\n\nvar sum = function(x,y,z) {\n return x+y+z;\n};\n\nalert( passFunAndApply(sum,3,4,5) ); // 12\n [1, 2, -1].filter(function(element, index, array) { return element > 0 });\n// -> [1,2]\n function PrintName() {\n var privateFunction = function() { return \"Steve\"; };\n return privateFunction();\n}\n" }, { "answer_id": 61097, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 7, "selected": false, "text": "function Person(firstName, lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n\n // A private method only visible from within this constructor\n function calcFullName() {\n return firstName + \" \" + lastName; \n }\n\n // A public method available to everyone\n this.sayHello = function () {\n alert(calcFullName());\n }\n}\n\n//Usage:\nvar person1 = new Person(\"Bob\", \"Loblaw\");\nperson1.sayHello();\n\n// This fails since the method is not visible from this scope\nalert(person1.calcFullName());\n" }, { "answer_id": 61118, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 6, "selected": false, "text": "with var user = \n{\n fname: 'Rocket', \n mname: 'Aloysus',\n lname: 'Squirrel', \n city: 'Fresno', \n state: 'California'\n};\n\n// ...\n\nwith (user)\n{\n mname = 'J';\n city = 'Frostbite Falls';\n state = 'Minnesota';\n}\n var user = \n{\n fname: \"John\",\n// mname definition skipped - no middle name\n lname: \"Doe\"\n};\n\nwith (user)\n{\n mname = \"Q\"; // creates / modifies global variable \"mname\"\n}\n with" }, { "answer_id": 61125, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 7, "selected": false, "text": "[] . obj = {a:\"test\"};\nvar propname = \"a\";\nvar b = obj[propname]; // \"test\"\n obj[\"class\"] = \"test\"; // class is a reserved word; obj.class would be illegal.\nobj[\"two words\"] = \"test2\"; // using dot operator not possible with the space.\n var propname = \"a\";\nvar a = eval(\"obj.\" + propname);\n" }, { "answer_id": 61129, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 6, "selected": false, "text": "Array.prototype.contains = function(value) { \n for (var i = 0; i < this.length; i++) { \n if (this[i] == value) return true; \n } \n return false; \n}\n contains Array var stringArray = [\"foo\", \"bar\", \"foobar\"];\nstringArray.contains(\"foobar\");\n" }, { "answer_id": 61158, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 7, "selected": false, "text": "|| var a = b || c;\n a c b null false undefined 0 empty string NaN a b function example(arg1) {\n arg1 || (arg1 = 'default value');\n}\n function onClick(e) {\n e || (e = window.event);\n}\n debugger // ...\ndebugger;\n// ...\n var str = \"This is a \\\nreally, really \\\nlong line!\";\n \\ \\ SyntaxError" }, { "answer_id": 61173, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 7, "selected": false, "text": "var x = 1;\n{\n var x = 2;\n}\nalert(x); // outputs 2\n" }, { "answer_id": 61193, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 5, "selected": false, "text": "//Takes a function that filters numbers and calls the function on \n//it to build up a list of numbers that satisfy the function.\nfunction filter(filterFunction, numbers)\n{\n var filteredNumbers = [];\n\n for (var index = 0; index < numbers.length; index++)\n {\n if (filterFunction(numbers[index]) == true)\n {\n filteredNumbers.push(numbers[index]);\n }\n }\n return filteredNumbers;\n}\n\n//Creates a function (closure) that will remember the value \"lowerBound\" \n//that gets passed in and keep a copy of it.\nfunction buildGreaterThanFunction(lowerBound)\n{\n return function (numberToCheck) {\n return (numberToCheck > lowerBound) ? true : false;\n };\n}\n\nvar numbers = [1, 15, 20, 4, 11, 9, 77, 102, 6];\n\nvar greaterThan7 = buildGreaterThanFunction(7);\nvar greaterThan15 = buildGreaterThanFunction(15);\n\nnumbers = filter(greaterThan7, numbers);\nalert('Greater Than 7: ' + numbers);\n\nnumbers = filter(greaterThan15, numbers);\nalert('Greater Than 15: ' + numbers);\n" }, { "answer_id": 61196, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 5, "selected": false, "text": "// Defines a Pet class constructor \nfunction Pet(name) \n{\n this.getName = function() { return name; };\n this.setName = function(newName) { name = newName; };\n}\n\n// Adds the Pet.toString() function for all Pet objects\nPet.prototype.toString = function() \n{\n return 'This pets name is: ' + this.getName();\n};\n// end of class Pet\n\n// Define Dog class constructor (Dog : Pet) \nfunction Dog(name, breed) \n{\n // think Dog : base(name) \n Pet.call(this, name);\n this.getBreed = function() { return breed; };\n}\n\n// this makes Dog.prototype inherit from Pet.prototype\nDog.prototype = new Pet();\n\n// Currently Pet.prototype.constructor\n// points to Pet. We want our Dog instances'\n// constructor to point to Dog.\nDog.prototype.constructor = Dog;\n\n// Now we override Pet.prototype.toString\nDog.prototype.toString = function() \n{\n return 'This dogs name is: ' + this.getName() + \n ', and its breed is: ' + this.getBreed();\n};\n// end of class Dog\n\nvar parrotty = new Pet('Parrotty the Parrot');\nvar dog = new Dog('Buddy', 'Great Dane');\n// test the new toString()\nalert(parrotty);\nalert(dog);\n\n// Testing instanceof (similar to the `is` operator)\nalert('Is dog instance of Dog? ' + (dog instanceof Dog)); //true\nalert('Is dog instance of Pet? ' + (dog instanceof Pet)); //true\nalert('Is dog instance of Object? ' + (dog instanceof Object)); //true\n" }, { "answer_id": 61545, "author": "Martin Clarke", "author_id": 2422, "author_profile": "https://Stackoverflow.com/users/2422", "pm_score": 8, "selected": false, "text": "=== !== == != alert('' == '0'); //false\nalert(0 == ''); // true\nalert(0 =='0'); // true\n == ===" }, { "answer_id": 61584, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "function someFunction(){\n var Static = arguments.callee;\n Static.someStaticVariable = (Static.someStaticVariable || 0) + 1;\n alert(Static.someStaticVariable);\n}\nsomeFunction() //Alerts 1\nsomeFunction() //Alerts 2\nsomeFunction() //Alerts 3\n function Obj(){\n this.Static = arguments.callee;\n}\na = new Obj();\na.Static.name = \"a\";\nb = new Obj();\nalert(b.Static.name); //Alerts b\n" }, { "answer_id": 64404, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 3, "selected": false, "text": "undefined if (obj.field === undefined) /* ... */\n" }, { "answer_id": 64912, "author": "Vitaly Sharovatov", "author_id": 6647, "author_profile": "https://Stackoverflow.com/users/6647", "pm_score": 2, "selected": false, "text": "var singleton = function(){ \n\n if (typeof arguments.callee.__instance__ == 'undefined') { \n\n arguments.callee.__instance__ = new function(){\n\n //this creates a random private variable.\n //this could be a complicated calculation or DOM traversing that takes long\n //or anything that needs to be \"cached\"\n var rnd = Math.random();\n\n //just a \"public\" function showing the private variable value\n this.smth = function(){ alert('it is an object with a rand num=' + rnd); };\n\n };\n\n }\n\n return arguments.callee.__instance__;\n\n};\n\n\nvar a = new singleton;\nvar b = new singleton;\n\na.smth(); \nb.smth();\n" }, { "answer_id": 64950, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 4, "selected": false, "text": "function isLeapYear(year) {\n return (new Date(year, 1, 29, 0, 0).getMonth() != 2);\n}\n" }, { "answer_id": 65002, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "//e.g., createAddFunction(\"a\",\"b\") returns function(a,b) { return a+b; }\nfunction createAddFunction(paramName1, paramName2)\n { return new Function( paramName1, paramName2\n ,\"return \"+ paramName1 +\" + \"+ paramName2 +\";\");\n }\n" }, { "answer_id": 65028, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 9, "selected": false, "text": "arguments function sum() {\n var retval = 0;\n for (var i = 0, len = arguments.length; i < len; ++i) {\n retval += arguments[i];\n }\n return retval;\n}\n\nsum(1, 2, 3) // returns 6\n" }, { "answer_id": 65064, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": false, "text": "var x = {a: 0};\nx[\"a\"]; //returns 0\n\nx[\"b\"] = 1;\nx.b; //returns 1\n\nfor (p in x) document.write(p+\";\"); //writes \"a;b;\"\n" }, { "answer_id": 65124, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": false, "text": "var x = 1;\nvar y = 3;\nvar list = {0:0, 1:0, 2:0};\nx in list; //true\ny in list; //false\n1 in list; //true\ny in {3:0, 4:0, 5:0}; //true\n function list()\n { var x = {};\n for(var i=0; i < arguments.length; ++i) x[arguments[i]] = 0;\n return x\n }\n\n 5 in list(1,2,3,4,5) //true\n" }, { "answer_id": 65415, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 4, "selected": false, "text": "var x = { intValue: 5, strValue: \"foo\" };\n String.prototype.doubleLength = function() {\n return this.length * 2;\n}\n\nalert(\"foo\".doubleLength());\n /* \"Constructor\" */\nfunction foo() {\n this.intValue = 5;\n}\n\n/* Create the prototype that includes everything\n * common to all objects created be the foo function.\n */\nfoo.prototype = {\n method: function() {\n alert(this.intValue);\n }\n}\n\nvar f = new foo();\nf.method();\n" }, { "answer_id": 68961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "function getObjectType( obj ) { \n return obj.constructor.name; \n} \n\nwindow.onload = function() { \n alert( getObjectType( \"Hello World!\" ) ); \n function Cat() { \n // some code here... \n } \n alert( getObjectType( new Cat() ) ); \n}\n function myFunction( message, iteration ) { \n if ( arguments.length == 2 ) { \n for ( i = 0; i < iteration; i++ ) { \n alert( message ); \n } \n } else { \n alert( message ); \n } \n} \n\nwindow.onload = function() { \n myFunction( \"Hello World!\", 3 ); \n}\n var a, b, c, d;\nb = a;\nc = b;\nd = c;\n var a, b, c, d;\nd = c = b = a;\n" }, { "answer_id": 75844, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 3, "selected": false, "text": "var o1 = { foo: 1, bar: 'abc' };\nfunction f() {}\nf.prototype = o1;\no2 = new f();\nassert( o2.foo === 1 );\nassert( o2.bar === 'abc' );\no2.foo = 2;\no2.baz = true;\nassert( o2.foo === 2 );\n// o1 is unchanged by assignment to o2\nassert( o1.foo === 1 );\nassert( o2.baz );\n" }, { "answer_id": 78155, "author": "user14079", "author_id": 14079, "author_profile": "https://Stackoverflow.com/users/14079", "pm_score": 4, "selected": false, "text": "// Usual Way\nvar d = new Date();\ntimestamp = d.getTime();\n\n// Shorter Way\ntimestamp = (new Date()).getTime();\n\n// Shortest Way\ntimestamp = +new Date();\n" }, { "answer_id": 78290, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": false, "text": "function x() {\n alert(\"Hello World\");\n}\neval (\"x = \" + (x + \"\").replace(\n 'Hello World',\n 'STACK OVERFLOW BWAHAHA\"); x(\"'));\nx();\n" }, { "answer_id": 104424, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 5, "selected": false, "text": "var test = function () {\n //private members\n var x = 1;\n var y = function () {\n return x * 2;\n };\n //public interface\n return {\n setx : function (newx) {\n x = newx;\n },\n gety : function () {\n return y();\n }\n }\n}();\n\nassert(undefined == test.x);\nassert(undefined == test.y);\nassert(2 == test.gety());\ntest.setx(5);\nassert(10 == test.gety());\n" }, { "answer_id": 105603, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 6, "selected": false, "text": "var listNodes = document.getElementsByTagName('a');\nlistNodes.sort(function(a, b){ ... });\n listNodes Array Array.prototype.sort.apply(listNodes, [function(a, b){ ... }]);\n listNodes sort()" }, { "answer_id": 109360, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 5, "selected": false, "text": "// convert to base 2\n(5).toString(2) // returns \"101\"\n\n// provide built in iteration\nNumber.prototype.times = function(funct){\n if(typeof funct === 'function') {\n for(var i = 0;i < Math.floor(this);i++) {\n funct(i);\n }\n }\n return this;\n}\n\n\n(5).times(function(i){\n string += i+\" \";\n});\n// string now equals \"0 1 2 3 4 \"\n\nvar x = 1000;\n\nx.times(function(i){\n document.body.innerHTML += '<p>paragraph #'+i+'</p>';\n});\n// adds 1000 parapraphs to the document\n" }, { "answer_id": 110337, "author": "user19745", "author_id": 19745, "author_profile": "https://Stackoverflow.com/users/19745", "pm_score": 3, "selected": false, "text": "var z = ( x = \"can you do crazy things with parenthesis\", ( y = x.split(\" \"), [ y[1], y[0] ].concat( y.slice(2) ) ).join(\" \") )\n\nalert(x + \"\\n\" + y + \"\\n\" + z)\n can you do crazy things with parenthesis\ncan,you,do,crazy,things,with,parenthesis\nyou can do crazy things with parenthesis\n" }, { "answer_id": 114695, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "function(){\n arguments.push('foo') // This errors, arguments is not a proper array and has no push method\n Array.prototype.push.apply(arguments, ['foo']) // Works!\n}\n" }, { "answer_id": 115587, "author": "jrockway", "author_id": 8457, "author_profile": "https://Stackoverflow.com/users/8457", "pm_score": 2, "selected": false, "text": "// Create a class called Point\nClass(\"Point\", {\n has: {\n x: {\n is: \"rw\",\n init: 0\n },\n y: {\n is: \"rw\",\n init: 0\n }\n },\n methods: {\n clear: function () {\n this.setX(0);\n this.setY(0);\n }\n }\n})\n\n// Use the class\nvar point = new Point();\npoint.setX(10)\npoint.setY(20);\npoint.clear();\n" }, { "answer_id": 116790, "author": "Andrey Fedorov", "author_id": 10728, "author_profile": "https://Stackoverflow.com/users/10728", "pm_score": 5, "selected": false, "text": "aWizz = wizz || \"default\";\n// same as: if (wizz) { aWizz = wizz; } else { aWizz = \"default\"; }\n (cond (predicate (action ...))\n (predicate2 (action2 ...))\n (#t default ))\n predicate ? action( ... ) :\npredicate2 ? action2( ... ) :\n default;\n if (predicate) {\n foo = \"one\";\n} else if (predicate2) {\n foo = \"two\";\n} else {\n foo = \"default\";\n}\n foo = predicate ? \"one\" :\n predicate2 ? \"two\" :\n \"default\";\n" }, { "answer_id": 117022, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 5, "selected": false, "text": "var recurse = function() {\n if (condition) arguments.callee(); //calls recurse() again\n}\n //do something to all array items within an array recursively\nmyArray.forEach(function(item) {\n if (item instanceof Array) item.forEach(arguments.callee)\n else {/*...*/}\n})\n //these are normal object members\nvar obj = {\n a : function() {},\n b : function() {}\n}\n//but we can do this too\nvar rules = {\n \".layout .widget\" : function(element) {},\n \"a[href]\" : function(element) {}\n}\n/* \nthis snippet searches the page for elements that\nmatch the CSS selectors and applies the respective function to them:\n*/\nfor (var item in rules) {\n var elements = document.querySelectorAll(rules[item]);\n for (var e, i = 0; e = elements[i++];) rules[item](e);\n}\n \"hello world with spaces\".split(/\\s+/g);\n//returns an array: [\"hello\", \"world\", \"with\", \"spaces\"]\n var i = 1;\n\"foo bar baz \".replace(/\\s+/g, function() {return i++});\n//returns \"foo1bar2baz3\"\n" }, { "answer_id": 117922, "author": "treat your mods well", "author_id": 20772, "author_profile": "https://Stackoverflow.com/users/20772", "pm_score": 1, "selected": false, "text": "Array undefined" }, { "answer_id": 117951, "author": "David Leonard", "author_id": 19502, "author_profile": "https://Stackoverflow.com/users/19502", "pm_score": 6, "selected": false, "text": "NaN NaN == < > NaN Array.sort $0 $1 $2 null undefined undefined typeof null == \"object\" this var with break continue undefined if (new Boolean(false)) {...} {...}" }, { "answer_id": 118150, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "parseInt() parseInt('010') parseInt('010') // returns 8! (in FF3)\nparseInt('010', 10); // returns 10 because we've informed it which base to work with.\n" }, { "answer_id": 118556, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "for (i in a) for (i in a)" }, { "answer_id": 123136, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": false, "text": "var a = []; // equivalent to new Array()\nvar o = {}; // equivalent to new Object()\n" }, { "answer_id": 128867, "author": "ScottKoon", "author_id": 1538, "author_profile": "https://Stackoverflow.com/users/1538", "pm_score": 7, "selected": false, "text": "(function() { alert(\"hi there\");})();\n (function() {\n var myvar = 2;\n alert(myvar);\n})();\n myvar" }, { "answer_id": 143666, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ">>> 1 == true\ntrue\n>>> 0 == false\ntrue\n>>> 2 == true\nfalse\n" }, { "answer_id": 152545, "author": "Rob", "author_id": 11715, "author_profile": "https://Stackoverflow.com/users/11715", "pm_score": 4, "selected": false, "text": "function log(message) {\n (console || { log: function(s) { alert(s); }).log(message);\n}\n" }, { "answer_id": 155730, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": false, "text": "let let function varTest() {\n var x = 31;\n if (true) {\n var x = 71; // same variable!\n alert(x); // 71\n }\n alert(x); // 71\n }\n\n function letTest() {\n let x = 31;\n if (true) {\n let x = 71; // different variable\n alert(x); // 71\n }\n alert(x); // 31\n }\n" }, { "answer_id": 155761, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": false, "text": "function fib() {\n var i = 0, j = 1;\n while (true) {\n yield i;\n var t = i;\n i = j;\n j += t;\n }\n}\n\nvar g = fib();\nfor (var i = 0; i < 10; i++) {\n document.write(g.next() + \"<br>\\n\");\n}\n yield next() yield yield next() yield for...in for each...in var objectWithIterator = getObjectSomehow();\n\nfor (var i in objectWithIterator)\n{\n document.write(objectWithIterator[i] + \"<br>\\n\");\n}\n" }, { "answer_id": 155805, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 6, "selected": false, "text": "var obj = { prop1: 42, prop2: 43 };\n\nobj.prop2 = undefined;\n\nfor (var key in obj) {\n ...\n delete obj.prop2;\n" }, { "answer_id": 158462, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": false, "text": "eval() eval(\"{ \\\"foo\\\": 42 }\"); // syntax error: invalid label\neval(\"({ \\\"foo\\\": 42 })\"); // OK\n" }, { "answer_id": 179154, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "3.14 >> 0 3.14 | 0 3.14 & -1 3.14 ^ 0 ~~3.14" }, { "answer_id": 182493, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "var $links = $(\"a\");\n\n$links.hide();\n $(\"a\")\n.hide()\n.fadeIn()\n.fadeOut()\n.hide();\n function test()\n{\n // scope of test()\n\n (function()\n {\n // scope inside the scope of test()\n }());\n\n // scope of test()\n}\n" }, { "answer_id": 224227, "author": "Justin Love", "author_id": 30203, "author_profile": "https://Stackoverflow.com/users/30203", "pm_score": 3, "selected": false, "text": "function blarg(a) {return a;} // statement\nbleep = function(b) {return b;} //expression\n with with" }, { "answer_id": 238770, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 5, "selected": false, "text": "Object.beget = (function(Function){\n return function(Object){\n Function.prototype = Object;\n return new Function;\n }\n})(function(){});\n var A = {\n foo : 'greetings'\n}; \nvar B = Object.beget(A);\n\nalert(B.foo); // 'greetings'\n\n// changes and additionns to A are reflected in B\nA.foo = 'hello';\nalert(B.foo); // 'hello'\n\nA.bar = 'world';\nalert(B.bar); // 'world'\n\n\n// ...but not the other way around\nB.foo = 'wazzap';\nalert(A.foo); // 'hello'\n\nB.bar = 'universe';\nalert(A.bar); // 'world'\n" }, { "answer_id": 302545, "author": "bbrown", "author_id": 20595, "author_profile": "https://Stackoverflow.com/users/20595", "pm_score": 3, "selected": false, "text": "window.name document.getElementById(\"your frame's ID\").contentWindow.name" }, { "answer_id": 347540, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 5, "selected": false, "text": "for (p in anObject) {\n if (anObject.hasOwnProperty(p)) {\n //Do stuff with p here\n }\n}\n" }, { "answer_id": 347552, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 4, "selected": false, "text": "var numbers = [1,2,3,4,5];\ndelete numbers[3];\n//numbers is now [1,2,3,undefined,5]\n var numbers = [1,2,3,4,5];\nnumbers.splice(3,1);\n//numbers is now [1,2,3,5]\n" }, { "answer_id": 414508, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 3, "selected": false, "text": "AJAXCall('http://www.abcd.com/')\n\nfunction AJAXCall(url) {\n var client = new XMLHttpRequest();\n client.onreadystatechange = handlerFunc;\n client.open(\"GET\", url);\n client.send();\n}\n\nfunction handlerFunc() {\n if(this.readyState == 4 && this.status == 200) {\n if(this.responseXML != null)\n document.write(this.responseXML)\n }\n}\n" }, { "answer_id": 460884, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 2, "selected": false, "text": "while var i, len = 100000;\n\nfor (var i = 0; i < len; i++) {\n // do stuff\n}\n i = len;\nwhile (i--) {\n // do stuff\n}\n" }, { "answer_id": 476923, "author": "Paweł Witkowski Photography", "author_id": 58260, "author_profile": "https://Stackoverflow.com/users/58260", "pm_score": 2, "selected": false, "text": "var a;\na=alert(5),7;\nalert(a); // alerts undefined\na=7,alert(5);\nalert(a); // alerts 7\n\na=(3,6);\nalert(a); // alerts 6\n" }, { "answer_id": 490143, "author": "Breton", "author_id": 51101, "author_profile": "https://Stackoverflow.com/users/51101", "pm_score": 5, "selected": false, "text": "function getInnerText(o){\n return o === null? null : {\n string: o,\n array: o.map(getInnerText).join(\"\"),\n object:getInnerText(o[\"childNodes\"])\n }[typeis(o)];\n}\n function getInnerText(o){\n return o === null? null : {\n string: function() { return o;},\n array: function() { return o.map(getInnerText).join(\"\"); },\n object: function () { return getInnerText(o[\"childNodes\"]; ) }\n }[typeis(o)]();\n}\n let getInnerText = o -> ({\n string: o -> o,\n array: o -> o.map(getInnerText).join(\"\"),\n object: o -> getInnerText(o[\"childNodes\"])\n}[ typeis o ] || (->null) )(o);\n" }, { "answer_id": 490169, "author": "Ionuț G. Stan", "author_id": 58808, "author_profile": "https://Stackoverflow.com/users/58808", "pm_score": 5, "selected": false, "text": "try {\n myroutine(); // may throw three exceptions\n} catch (e if e instanceof TypeError) {\n // statements to handle TypeError exceptions\n} catch (e if e instanceof RangeError) {\n // statements to handle RangeError exceptions\n} catch (e if e instanceof EvalError) {\n // statements to handle EvalError exceptions\n} catch (e) {\n // statements to handle any unspecified exceptions\n logMyErrors(e); // pass exception object to error handler\n}\n" }, { "answer_id": 490546, "author": "Breton", "author_id": 51101, "author_profile": "https://Stackoverflow.com/users/51101", "pm_score": 3, "selected": false, "text": "Array.prototype.slice.call({\"0\":\"foo\", \"1\":\"bar\", 2:\"baz\", \"length\":3 }) \n" }, { "answer_id": 625580, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "var i;\n\nfor (i = 0; i < 10; i++) (function ()\n{\n // do something with i\n}());\n var i;\n\nfor (i = 0; i < 10; i++) (function (j)\n{\n // do something with j\n}(i));\n" }, { "answer_id": 628728, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "arguments[-2] arguments.length arguments[-3] arguments.callee" }, { "answer_id": 645331, "author": "nickytonline", "author_id": 77814, "author_profile": "https://Stackoverflow.com/users/77814", "pm_score": 2, "selected": false, "text": "var a = [0, 1, 2];\n\n// code that might clear the array.\n\nif (a.length > 0) {\n // do something\n}\n var a = [0, 1, 2];\n\n// code that might clear the array.\n\nif (a.length) { // if length is not equal to 0, this will be true\n // do something\n}\n function (someArgument) {\n someArgument || (someArgument = \"This is the deault value\");\n}\n" }, { "answer_id": 692380, "author": "Lucent", "author_id": 6385, "author_profile": "https://Stackoverflow.com/users/6385", "pm_score": 4, "selected": false, "text": "eval() spec_grapes, spec_apples eval(\"spec_\" + var) window[] window[\"spec_\" + var]" }, { "answer_id": 731342, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": "// creating an object (the short way, to use it like a hashmap)\nvar diner = {\n\"fruit\":\"apple\"\n\"veggetable\"=\"bean\"\n}\n\n// looping over its properties\nfor (meal_name in diner ) {\n document.write(meal_name+\"<br \\n>\");\n}\n fruit\nveggetable\n // looping over its properties and values\nfor (meal_name in diner ) {\n document.write(meal_name+\" : \"+diner[meal_name]+\"<br \\n>\");\n}\n fruit : apple\nveggetable : bean\n var my_array = ['a', 'b', 'c'];\nfor (index in my_array ) {\n document.write(index+\" : \"+my_array[index]+\"<br \\n>\");\n}\n 0 : a\n1 : b\n3 : c\n var arr = ['a', 'b', 'c', 'd'];\nvar pos = arr.indexOf('c');\npos > -1 && arr.splice( pos, 1 );\n arr.sort(function() Math.random() - 0.5);" }, { "answer_id": 731411, "author": "David", "author_id": 21909, "author_profile": "https://Stackoverflow.com/users/21909", "pm_score": 3, "selected": false, "text": "function Animal () {\n\n}\n\nvar animal = new Animal();\nvar animal = new Animal;\n" }, { "answer_id": 841201, "author": "username", "author_id": 4939, "author_profile": "https://Stackoverflow.com/users/4939", "pm_score": 4, "selected": false, "text": "function fn(){\n var cat = \"meow\";\n var dog = \"woof\";\n return [cat,dog];\n};\n\nvar [cat,dog] = fn(); // Handy!\n\nalert(cat);\nalert(dog);\n" }, { "answer_id": 865753, "author": "Sebastian Schuth", "author_id": 107339, "author_profile": "https://Stackoverflow.com/users/107339", "pm_score": 2, "selected": false, "text": "function called(){\n alert(\"Go called by:\\n\"+arguments.callee.caller.toString());\n}\n\nfunction iDoTheCall(){\n called();\n}\n\niDoTheCall();\n iDoTheCall" }, { "answer_id": 955784, "author": "pawelsto", "author_id": 109208, "author_profile": "https://Stackoverflow.com/users/109208", "pm_score": 1, "selected": false, "text": "<div id=\"jsTest\">Klick Me</div>\n<script type=\"text/javascript\">\n var someVariable = 'I was klicked';\n var divElement = document.getElementById('jsTest');\n // binding function/object or anything as attribute\n divElement.controller = function() { someVariable += '*'; alert('You can change instance data:\\n' + someVariable ); };\n var onclickFunct = new Function( 'this.controller();' ); // Works in Firefox and Internet Explorer.\n divElement.onclick = onclickFunct;\n</script>\n" }, { "answer_id": 1024826, "author": "Metal", "author_id": 75025, "author_profile": "https://Stackoverflow.com/users/75025", "pm_score": 3, "selected": false, "text": "o.constructor.constructor(\"alert('hi')\")() var Z=\"constructor\";\nZ[Z][Z](\"alert('hi')\")();\n" }, { "answer_id": 1025127, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "var names = new Array(1024), i = names.length;\nwhile(i--)\n names[i] = \"John\" + i;\n var birds = new Array(1024); \nfor(var i = 0, j = birds.length; i < j; i++)\n birds[i].fly();\n var largeString = new Array(1024), i = largeString.length;\nwhile(i--) {\n // It's faster than for() loop with largeString.push(), obviously :)\n largeString[i] = i.toString(16);\n}\n\nlargeString = largeString.join(\"\");\n largeString += \"something\"" }, { "answer_id": 1025990, "author": "Justin Johnson", "author_id": 126562, "author_profile": "https://Stackoverflow.com/users/126562", "pm_score": 1, "selected": false, "text": "a || b || c || \"default\"; var getInstance = function(objectName) {\n if ( !getInstance.instances ) {\n getInstance.instances = {};\n }\n\n if ( !getInstance.instances[objectName] ) {\n getInstance.instances[objectName] = new window[objectName];\n }\n\n return getInstance.instances[objectName];\n};\n new window[objectName]; hasOwnProperty in hasOwnProperty var x = [1,2,3];\nfor ( i in x ) {\n if ( !x.hasOwnProperty(i) ) { continue; }\n console.log(i, x[i]);\n}\n with" }, { "answer_id": 1043658, "author": "Blixt", "author_id": 119081, "author_profile": "https://Stackoverflow.com/users/119081", "pm_score": 1, "selected": false, "text": "prototype var MyClass = (function () {\n // private static\n var nextId = 1;\n\n // constructor\n var cls = function () {\n // private\n var id = nextId++;\n var name = 'Unknown';\n\n // public (this instance only)\n this.get_id = function () { return id; };\n\n this.get_name = function () { return name; };\n this.set_name = function (value) {\n if (typeof value != 'string')\n throw 'Name must be a string';\n if (value.length < 2 || value.length > 20)\n throw 'Name must be 2-20 characters long.';\n name = value;\n };\n };\n\n // public static\n cls.get_nextId = function () {\n return nextId;\n };\n\n // public (shared across instances)\n cls.prototype = {\n announce: function () {\n alert('Hi there! My id is ' + this.get_id() + ' and my name is \"' + this.get_name() + '\"!\\r\\n' +\n 'The next fellow\\'s id will be ' + MyClass.get_nextId() + '!');\n }\n };\n\n return cls;\n})();\n var mc1 = new MyClass();\nmc1.set_name('Bob');\n\nvar mc2 = new MyClass();\nmc2.set_name('Anne');\n\nmc1.announce();\nmc2.announce();\n MyClass.call(this); MyClass.prototype MyClass announce MyClass.announce MyClass.prototype.announce.call(this);" }, { "answer_id": 1131595, "author": "RaYell", "author_id": 137467, "author_profile": "https://Stackoverflow.com/users/137467", "pm_score": 2, "selected": false, "text": "typeof object function typeOf (value) {\n var type = typeof value;\n if (type === 'object') {\n if (value === null) {\n type = 'null';\n } else if (typeof value.length === 'number' && \n typeof value.splice === 'function' && \n !value.propertyIsEnumerable('length')) {\n type = 'array';\n }\n }\n return type;\n}\n" }, { "answer_id": 1162208, "author": "gotch4", "author_id": 138606, "author_profile": "https://Stackoverflow.com/users/138606", "pm_score": 1, "selected": false, "text": "function myClass(){\n this.fun = function(){\n do something;\n };\n}\n var a = new myClass();\nvar b = new myClass();\n\nmyClass.fun.apply(b); //this will be like b.fun();\n" }, { "answer_id": 1176498, "author": "outis", "author_id": 90527, "author_profile": "https://Stackoverflow.com/users/90527", "pm_score": 1, "selected": false, "text": "function Circle(r) {\n this.setR(r);\n}\n\nCircle.prototype = {\n recalcArea: function() {\n this.area=function() {\n area = this.r * this.r * Math.PI;\n this.area = function() {return area;}\n return area;\n }\n },\n setR: function (r) {\n this.r = r;\n this.invalidateR();\n },\n invalidateR: function() {\n this.recalcArea();\n }\n}\n Object.prototype.cacheResult = function(name, _get) {\n this[name] = function() {\n var result = _get.apply(this, arguments);\n this[name] = function() {\n return result;\n }\n return result;\n };\n};\n\nfunction Circle(r) {\n this.setR(r);\n}\n\nCircle.prototype = {\n recalcArea: function() {\n this.cacheResult('area', function() { return this.r * this.r * Math.PI; });\n },\n setR: function (r) {\n this.r = r;\n this.invalidateR();\n },\n invalidateR: function() {\n this.recalcArea();\n }\n}\n Object.prototype.memoize = function(name, implementation) {\n this[name] = function() {\n var argStr = Array.toString.call(arguments);\n if (typeof(this[name].memo[argStr]) == 'undefined') {\n this[name].memo[argStr] = implementation.apply(this, arguments);\n }\n return this[name].memo[argStr];\n }\n};\n Object.prototype.defineCacher = function(name, _get) {\n this.__defineGetter__(name, function() {\n var result = _get.call(this);\n this.__defineGetter__(name, function() { return result; });\n return result;\n })\n};\n\nfunction Circle(r) {\n this.r = r;\n}\n\nCircle.prototype = {\n invalidateR: function() {\n this.recalcArea();\n },\n recalcArea: function() {\n this.defineCacher('area', function() {return this.r * this.r * Math.PI; });\n },\n get r() { return this._r; }\n set r(r) { this._r = r; this.invalidateR(); }\n}\n\nvar unit = new Circle(1);\nunit.area;\n Object.prototype.defineRecalcer = function(name, _get) {\n var recalcFunc;\n this[recalcFunc='recalc'+name.toCapitalized()] = function() {\n this.defineCacher(name, _get);\n };\n this[recalcFunc]();\n this.__defineSetter__(name, function(value) {\n _set.call(this, value);\n this.__defineGetter__(name, function() {return value; });\n });\n};\n\nfunction Circle(r) {\n this.defineRecalcer('area',\n function() {return this.r * this.r * Math.PI;},\n function(area) {this._r = Math.sqrt(area / Math.PI);},\n );\n this.r = r;\n}\n\nCircle.prototype = {\n invalidateR: function() {\n this.recalcArea();\n },\n get r() { return this._r; }\n set r(r) { this._r = r; this.invalidateR(); }\n}\n" }, { "answer_id": 1211874, "author": "Fabian Jakobs", "author_id": 129322, "author_profile": "https://Stackoverflow.com/users/129322", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\n(function() {\n\nfunction init() {\n // ...\n}\n\nwindow.onload = init;\n})();\n</script>\n var window window.GLOBAL_VAR = 12;\nwindow.global_function = function() {};\n" }, { "answer_id": 1211921, "author": "Fabian Jakobs", "author_id": 129322, "author_profile": "https://Stackoverflow.com/users/129322", "pm_score": 3, "selected": false, "text": "ns foo if (!window.ns) {\n window.ns = {};\n}\n\nwindow.ns.foo = function() {};\n ns/button.js if (!window.ns) {\n window.ns = {};\n}\nif (!window.ns.button) {\n window.ns.button = {};\n}\n\n// attach methods to the ns.button namespace\nwindow.ns.button.create = function() {};\n" }, { "answer_id": 1318068, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\n function DriveIn()\n {\n this.car = 'Honda';\n alert(this.food); //'food' is the attribute of a future object \n //and DriveIn does not define it.\n }\n\n var A = {food:'chili', q:DriveIn}; //create object A whose q attribute \n //is the function DriveIn;\n\n alert(A.car); //displays 'undefined' \n A.q(); //displays 'chili' but also defines this.car.\n alert(A.car); //displays 'Honda' \n\n \n function Insect ()\n {\n this.bug = \"bee\";\n this.bugFood = function()\n {\n alert(\"nectar\");\n }\n }\n\n var B = new Insect();\n alert(B.constructor); //displays \"Insect\"; By \"The Rule of This\" any\n //ocurrence of 'this' inside Insect now refers \n //to B. \n \n var C = {constructor:Insect}; //Assign the constructor attribute of C, \n //the value Insect.\n C.constructor(); //Call Insect through the attribute. \n //C is now an Insect instance as though it \n //were created with operator new. [*]\n alert(C.bug); //Displays \"bee.\" \n C.bugFood(); //Displays \"nectar.\" \n\n" }, { "answer_id": 1365822, "author": "pramodc84", "author_id": 40614, "author_profile": "https://Stackoverflow.com/users/40614", "pm_score": 6, "selected": false, "text": "function add_nums(num1, num2, num3 ){\n return num1 + num2 + num3;\n}\nadd_nums.length // 3 is the number of parameters expected.\n function add_many_nums(){\n return arguments.length;\n} \nadd_many_nums(2,1,122,12,21,89); //returns 6\n" }, { "answer_id": 1394655, "author": "vsync", "author_id": 104380, "author_profile": "https://Stackoverflow.com/users/104380", "pm_score": -1, "selected": false, "text": "alert(prompt('',something.innerHTML ));\n" }, { "answer_id": 1416391, "author": "Kris Kowal", "author_id": 42586, "author_profile": "https://Stackoverflow.com/users/42586", "pm_score": 2, "selected": false, "text": "+anything\nNumber(anything)\n anything >>> 0\n '' + anything\nString(anything)\n !!anything\nBoolean(anything)\n" }, { "answer_id": 1462261, "author": "Seth", "author_id": 65295, "author_profile": "https://Stackoverflow.com/users/65295", "pm_score": 4, "selected": false, "text": "apply function MakeCallback(obj, method) {\n return function() {\n method.apply(obj, arguments);\n };\n}\n\nvar SomeClass = function() { \n this.a = 1;\n};\nSomeClass.prototype.addXToA = function(x) {\n this.a = this.a + x;\n};\n\nvar myObj = new SomeClass();\n\nbrokenCallback = myObj.addXToA;\nbrokenCallback(1); // Won't work, wrong \"this\" variable\nalert(myObj.a); // 1\n\n\nvar myCallback = MakeCallback(myObj, myObj.addXToA);\nmyCallback(1); // Works as expected because of apply\nalert(myObj.a); // 2\n" }, { "answer_id": 1682820, "author": "Lyubomyr Shaydariv", "author_id": 166589, "author_profile": "https://Stackoverflow.com/users/166589", "pm_score": 2, "selected": false, "text": "// forget the debug alerts\nvar alertToFirebugConsole = function() {\n if ( window.console && window.console.log ) {\n window.alert = console.log;\n }\n}\n" }, { "answer_id": 1712004, "author": "Kenneth J", "author_id": 195456, "author_profile": "https://Stackoverflow.com/users/195456", "pm_score": 1, "selected": false, "text": "var fn = (function() {\n var ready = true;\n function fnX() {\n ready = false;\n // AJAX return function\n function Success() {\n ready = true;\n }\n Success();\n return \"this is a test\";\n }\n\n fnX.IsReady = function() {\n return ready;\n }\n return fnX;\n })();\n\n if (fn.IsReady()) {\n fn();\n }\n" }, { "answer_id": 2042069, "author": "Anil Namde", "author_id": 237743, "author_profile": "https://Stackoverflow.com/users/237743", "pm_score": 2, "selected": false, "text": "\nfunction divPopup(str)\n{\n //code to show the divPopup\n}\nwindow.alert = divPopup;\n" }, { "answer_id": 2047391, "author": "slebetman", "author_id": 167735, "author_profile": "https://Stackoverflow.com/users/167735", "pm_score": 4, "selected": false, "text": "// Say you want three functions to share a single variable:\n\n// Use a self-calling function to create scope:\n(function(){\n\n var counter = 0; // this is the variable we want to share;\n\n // Declare global functions using function expressions:\n increment = function(){\n return ++counter;\n }\n decrement = function(){\n return --counter;\n }\n value = function(){\n return counter;\n }\n})()\n increment decrement value counter counter increment();\nincrement();\ndecrement();\nalert(value()); // will output 1\n for (var i=1;i<=10;i++) {\n document.getElementById('span'+i).onclick = function () {\n alert('this is span number '+i);\n }\n}\n// ALL spans will generate alert: this span is span number 10\n i i function makeClickHandler (j) {\n return function () {alert('this is span number '+j)};\n}\n\nfor (var i=1;i<=10;i++) {\n document.getElementById('span'+i).onclick = makeClickHandler(i);\n}\n// this works because i is passed by reference \n// (or value in this case, since it is a number)\n// instead of being captured by a closure\n" }, { "answer_id": 2243631, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 6, "selected": false, "text": "+ // Quick hex to dec conversion:\n+\"0xFF\"; // -> 255\n\n// Get a timestamp for now, the equivalent of `new Date().getTime()`:\n+new Date();\n\n// Safer parsing than parseFloat()/parseInt()\nparseInt(\"1,000\"); // -> 1, not 1000\n+\"1,000\"; // -> NaN, much better for testing user input\nparseInt(\"010\"); // -> 8, because of the octal literal prefix\n+\"010\"; // -> 10, `Number()` doesn't parse octal literals \n\n// A use case for this would be rare, but still useful in cases\n// for shortening something like if (someVar === null) someVar = 0;\n+null; // -> 0;\n\n// Boolean to integer\n+true; // -> 1;\n+false; // -> 0;\n\n// Other useful tidbits:\n+\"1e10\"; // -> 10000000000\n+\"1e-4\"; // -> 0.0001\n+\"-12\"; // -> -12\n Number() + valueOf() NaN valueOf() var rnd = {\n \"valueOf\": function () { return Math.floor(Math.random()*1000); }\n};\n+rnd; // -> 442;\n+rnd; // -> 727;\n+rnd; // -> 718;\n" }, { "answer_id": 2303653, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "window.alert jQuery.altAlert = function (options) \n{ \n var defaults = { \n title: \"Alert\", \n buttons: { \n \"Ok\": function() \n { \n jQuery(this).dialog(\"close\"); \n } \n } \n }; \n\n jQuery.extend(defaults, options); \n\n delete defaults.autoOpen; \n\n window.alert = function () \n { \n jQuery(\"<div />\", {\n html: arguments[0].replace(/\\n/, \"<br />\")\n }).dialog(defaults); \n }; \n};\n" }, { "answer_id": 2479026, "author": "adamJLev", "author_id": 26192, "author_profile": "https://Stackoverflow.com/users/26192", "pm_score": 1, "selected": false, "text": "function isRunningLocally(){\n var runningLocally = ....; // Might be an expensive check, check whatever needs to be checked.\n\n return (isRunningLocally = function(){\n return runningLocally;\n })();\n},\n" }, { "answer_id": 2709783, "author": "Harmen", "author_id": 176603, "author_profile": "https://Stackoverflow.com/users/176603", "pm_score": 4, "selected": false, "text": "function showSomething(a){\n alert(a);\n return arguments.callee;\n}\n\n// Alerts: 'a', 'b', 'c'\nshowSomething('a')('b')('c');\n\n// Or what about this:\n(function (a){\n alert(a);\n return arguments.callee;\n}​)('a')('b')('c');​​​​\n var count = function(counter){\n alert(counter);\n if(counter < 10){\n return arguments.callee(counter+1);\n }\n return arguments.callee;\n};\n\ncount(5)(9); // Will alert 5, 6, 7, 8, 9, 10 and 9, 10\n" }, { "answer_id": 2920211, "author": "wnrph", "author_id": 345520, "author_profile": "https://Stackoverflow.com/users/345520", "pm_score": 1, "selected": false, "text": "function f() { \n var a; \n function closureGet(){ return a; }\n function closureSet(val){ a=val;}\n return [closureGet,closureSet];\n}\n\n[closureGet,closureSet]=f(); \nclosureSet(5);\nalert(closureGet()); // gives 5\n\nclosureSet(15);\nalert(closureGet()); // gives 15\n [c,d] = [1,3] c=1; d=3; a a" }, { "answer_id": 2921079, "author": "Tgr", "author_id": 323407, "author_profile": "https://Stackoverflow.com/users/323407", "pm_score": 3, "selected": false, "text": ":something $.extend($.expr[':'], {\n foo: function(node, index, args, stack) {\n // decide if selectors matches node, return true or false\n }\n});\n :foo $('div.block:foo(\"bar,baz\") span') foo node index args args[0] :foo(\"bar, baz\") args[1] foo args[2] \" :foo(\"bar, baz\") :foo(bar, baz) args[3] \"bar, baz\" stack true false $.extend($.expr[':'], {\n matches: function(node, index, args, stack) {\n if (!args.re) { // args is a good place for caching\n var re = args[3];\n if (args[2]) { // get rid of quotes\n re = re.slice(1,-1);\n }\n var separator = re[0];\n var pos = re.lastIndexOf(separator);\n var modifiers = re.substr(pos+1);\n var code = re.substr(1, pos-1);\n args.re = new RegExp(code, modifiers);\n }\n return $(node).text().match(args.re);\n }\n});\n\n// find the answers on this page which contain /**/-style comments\n$('.answer .post-text code:matches(!/\\\\*[\\\\s\\\\S]*\\\\*/!)');\n" }, { "answer_id": 3110886, "author": "Edgar Klerks", "author_id": 375367, "author_profile": "https://Stackoverflow.com/users/375367", "pm_score": 1, "selected": false, "text": "callback: function(){\n stuff(arg1,arg2);\n}\n callback: _(stuff, arg1, arg2) \n function _(){\n var func;\n var args = new Array();\n for(var i = 0; i < arguments.length; i++){\n if( i == 0){\n func = arguments[i];\n } else {\n args.push(arguments[i]);\n }\n }\n return function(){\n return func.apply(func, args);\n }\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
61,092
<p>Having read the threads <a href="https://stackoverflow.com/questions/60919/is-sqlcommanddispose-enough">Is SqlCommand.Dispose enough?</a> and <a href="https://stackoverflow.com/questions/23867/closing-and-disposing-a-wcf-service">Closing and Disposing a WCF Service</a> I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?</p>
[ { "answer_id": 61096, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 4, "selected": false, "text": "SqlConnection Dispose() Close() Stream.Dispose()" }, { "answer_id": 61131, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": false, "text": "IDisposable SqlClient using (SqlConnection conn = /* Create new instance using your favorite method */)\n{\n conn.Open();\n using (SqlCommand command = /* Create new instance using your favorite method */)\n {\n // Do work\n }\n conn.Close(); // Optional\n}\n Dispose Close Dispose Close using Dispose Close Dispose Close SqlClient Close" }, { "answer_id": 61133, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 3, "selected": false, "text": "Dispose() StreamWriter.Close() TextWriter.Close() Close() Dispose() Close() Dispose() Close() Dispose() Dispose() Close() MyResource r = new MyResource();\n\ntry {\n r.Write(new Whatever());\n\n r.Close()\nfinally {\n r.Dispose();\n}\n Close() finally Close()" }, { "answer_id": 61171, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 9, "selected": true, "text": "Close Close() Dispose() Close Dispose Close Dispose Close Dispose SqlConnectionObject Close Dispose SqlConnection SqlConnection Dispose using Close" }, { "answer_id": 44633468, "author": "Deep Jadia", "author_id": 7437225, "author_profile": "https://Stackoverflow.com/users/7437225", "pm_score": 1, "selected": false, "text": "private void CloseConnection(Client client)\n {\n if (client != null && client.State == CommunicationState.Opened)\n {\n client.Close();\n }\n else\n {\n client.Abort();\n }\n }\n" }, { "answer_id": 73442564, "author": "Alexander Kozachenko", "author_id": 3423333, "author_profile": "https://Stackoverflow.com/users/3423333", "pm_score": 0, "selected": false, "text": "TransactionScope This platform does not support distributed transactions Close Dispose Close Close Dispose" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5086/" ]
61,109
<p>I have been learning C++ for a while now, I find it very powerful. But, the problem is the the level of abstraction is not much and I have to do memory management myself. What are the languages that I can use which uses a higher level of abstraction.</p>
[ { "answer_id": 12147944, "author": "mikera", "author_id": 214010, "author_profile": "https://Stackoverflow.com/users/214010", "pm_score": 1, "selected": false, "text": ";; treat a vector as a sequence and reverse it\n(reverse [1 2 3 4 5])\n=> (5 4 3 2 1)\n\n;; Take 10 items from a infinite sequence\n(take 10 (range))\n=> (0 1 2 3 4 5 6 7 8 9)\n\n;; Treat a String as a sequence of characters, calculate the frequencies\n(frequencies \"abracadabra\")\n=> {\\a 5, \\b 2, \\r 2, \\c 1, \\d 1}\n\n;; Define an infinite lazy sequence of fibonacci numbers, take the first 10\n(def fibs (concat [0 1] (lazy-seq (map + fibs (rest fibs)))))\n(take 10 fibs)\n=> (0 1 1 2 3 5 8 13 21 34)\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323/" ]
61,110
<p>I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution.</p> <p>The workaround I use while I don't find a cleaner approach is to subclass <code>TextWriter</code> overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this:</p> <pre><code>public class DirtyWorkaround { private class DirtyWriter : TextWriter { private TextWriter stdoutWriter; private StreamWriter fileWriter; public DirtyWriter(string path, TextWriter stdoutWriter) { this.stdoutWriter = stdoutWriter; this.fileWriter = new StreamWriter(path); } override public void Write(string s) { stdoutWriter.Write(s); fileWriter.Write(s); fileWriter.Flush(); } // Same as above for WriteLine() and WriteLine(string), // plus whatever methods I need to override to inherit // from TextWriter (Encoding.Get I guess). } public static void Main(string[] args) { using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) { Console.SetOut(dw); // Teh codez } } } </code></pre> <p>See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer.</p> <p>Also, excuse inaccuracies with the above code (had to write it <em>ad hoc</em>, sorry ;).</p>
[ { "answer_id": 61119, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "MultiWriter TextWriter" }, { "answer_id": 61123, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "tee" }, { "answer_id": 61164, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "Console.WriteLine" }, { "answer_id": 369254, "author": "Rob Parker", "author_id": 181460, "author_profile": "https://Stackoverflow.com/users/181460", "pm_score": 0, "selected": false, "text": "stdoutWriter fileWriter stdoutWriter fileWriter Console.Out fileWriter stdoutWriter fileWriter" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4850/" ]
61,143
<p>Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#. </p>
[ { "answer_id": 61149, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": " public void HandleTreeItems(Action<TreeItem> item, TreeItem parent)\n {\n if (parent.Children.Count > 0)\n {\n foreach (TreeItem ti in parent.Children)\n {\n HandleTreeItems(item, ti);\n }\n }\n\n item(parent);\n }\n HandleTreeItems(item => { Console.WriteLine(item.Name); }, TreeItemRoot);\n" }, { "answer_id": 61206, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "Func<int, int> fact = null;\nfact = x => (x == 0) ? 1 : x * fact(x - 1);\n TreeNode IEnumerable<TreeNode> Action<TreeNode, Action<TreeNode>> preorderTraverse = null;\npreorderTraverse = (node, action) => {\n action(node);\n foreach (var child in node) preorderTraverse(child, action);\n};\n" }, { "answer_id": 61244, "author": "Tom Lokhorst", "author_id": 2597, "author_profile": "https://Stackoverflow.com/users/2597", "pm_score": 4, "selected": false, "text": "Func<int, int> fact = null;\nfact = x => (x == 0) ? 1 : x * fact(x - 1);\n Func<int, int> fact = null;\nfact = x => (x == 0) ? 1 : x * fact(x - 1);\n\n// Make a new reference to the factorial function\nFunc<int, int> myFact = fact;\n\n// Use the new reference to calculate the factorial of 4\nmyFact(4); // returns 24\n\n// Modify the old reference\nfact = x => x;\n\n// Again, use the new reference to calculate\nmyFact(4); // returns 12\n" }, { "answer_id": 61257, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 7, "selected": true, "text": "class TreeNode\n{\n public string Value { get; set;}\n public List<TreeNode> Nodes { get; set;}\n\n\n public TreeNode()\n {\n Nodes = new List<TreeNode>();\n }\n}\n\nAction<TreeNode> traverse = null;\n\ntraverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);};\n\nvar root = new TreeNode { Value = \"Root\" };\nroot.Nodes.Add(new TreeNode { Value = \"ChildA\"} );\nroot.Nodes[0].Nodes.Add(new TreeNode { Value = \"ChildA1\" });\nroot.Nodes[0].Nodes.Add(new TreeNode { Value = \"ChildA2\" });\nroot.Nodes.Add(new TreeNode { Value = \"ChildB\"} );\nroot.Nodes[1].Nodes.Add(new TreeNode { Value = \"ChildB1\" });\nroot.Nodes[1].Nodes.Add(new TreeNode { Value = \"ChildB2\" });\n\ntraverse(root);\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5360/" ]
61,150
<p>My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. </p> <p>So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it <code>staticInit</code>. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock <code>staticInit</code> with <a href="https://jmockit.github.io/" rel="noreferrer">JMockit</a> to not do anything. Let's see this in example.</p> <pre><code>public class ClassWithStaticInit { static { System.out.println("static initializer."); } } </code></pre> <p>Will be changed to</p> <pre><code>public class ClassWithStaticInit { static { staticInit(); } private static void staticInit() { System.out.println("static initialized."); } } </code></pre> <p>So that we can do the following in a <a href="https://junit.org/junit5/" rel="noreferrer">JUnit</a>.</p> <pre><code>public class DependentClassTest { public static class MockClassWithStaticInit { public static void staticInit() { } } @BeforeClass public static void setUpBeforeClass() { Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class); } } </code></pre> <p>However this solution also comes with its own problems. You can't run <code>DependentClassTest</code> and <code>ClassWithStaticInitTest</code> on the same JVM since you actually want the static block to run for <code>ClassWithStaticInitTest</code>.</p> <p>What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner?</p>
[ { "answer_id": 61153, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 3, "selected": false, "text": "staticInit()" }, { "answer_id": 61190, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 2, "selected": false, "text": "Math.metaClass.'static'.max = { int a, int b -> \n a + b\n}\n\nMath.max 1, 2\n" }, { "answer_id": 61389, "author": "martinatime", "author_id": 1353, "author_profile": "https://Stackoverflow.com/users/1353", "pm_score": 1, "selected": false, "text": "public static class MockClassWithEmptyStaticInit {\n public static void staticInit() {\n }\n}\n public static class MockClassWithStaticInit {\n public static void staticInit() {\n System.out.println(\"static initialized.\");\n }\n}\n @BeforeClass\npublic static void setUpBeforeClass() {\n Mockit.redefineMethods(ClassWithStaticInit.class, \n MockClassWithEmptyStaticInit.class);\n}\n @BeforeClass\npublic static void setUpBeforeClass() {\n Mockit.redefineMethods(ClassWithStaticInit.class, \n MockClassWithStaticInit.class);\n}\n" }, { "answer_id": 144876, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 4, "selected": false, "text": "public void $clinit() public class ClassWithStaticInit {\n static {\n staticInit();\n }\n\n private static void staticInit() {\n System.out.println(\"static initialized.\");\n }\n}\n ClassWithStaticInit MockClassWithStaticInit public static class MockClassWithStaticInit {\n public void $clinit() {\n }\n}\n" }, { "answer_id": 489018, "author": "Jan Kronquist", "author_id": 43935, "author_profile": "https://Stackoverflow.com/users/43935", "pm_score": 6, "selected": false, "text": "@RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor(\"some.package.ClassWithStaticInit\")\n" }, { "answer_id": 7242341, "author": "matsev", "author_id": 303598, "author_profile": "https://Stackoverflow.com/users/303598", "pm_score": 4, "selected": false, "text": "@SuppressStaticInitializationFor @RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor(\"com.example.ClassWithStaticInit\")\npublic class ClassWithStaticInitTest {\n\n ClassWithStaticInit tested;\n\n @Before\n public void setUp() {\n tested = new ClassWithStaticInit();\n }\n\n @Test\n public void testSuppressStaticInitializer() {\n asserNotNull(tested);\n }\n\n // more tests...\n}\n" }, { "answer_id": 33737521, "author": "KidCrippler", "author_id": 223365, "author_profile": "https://Stackoverflow.com/users/223365", "pm_score": 0, "selected": false, "text": "Mockit.redefineMethods Mockit.redefineMethods(ClassWithStaticInit.class, ClassWithStaticInit.class);\n @AfterClass ClassWithStaticInitTest" }, { "answer_id": 64216523, "author": "Sebastian Luna", "author_id": 7845889, "author_profile": "https://Stackoverflow.com/users/7845889", "pm_score": 0, "selected": false, "text": "ClassWithStaticInit staticInitClass = new ClassWithStaticInit()\nWhitebox.invokeMethod(staticInitClass, \"staticInit\");\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3087/" ]
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
[ { "answer_id": 61169, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 6, "selected": false, "text": "parent_dir/\n foo.py\n tests/\n" }, { "answer_id": 61531, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "tests/ from .. import foo\n MyApp.foo" }, { "answer_id": 61820, "author": "George V. Reilly", "author_id": 6364, "author_profile": "https://Stackoverflow.com/users/6364", "pm_score": 1, "selected": false, "text": "if __name__ == \"__main__\"" }, { "answer_id": 62527, "author": "user6868", "author_id": 6868, "author_profile": "https://Stackoverflow.com/users/6868", "pm_score": 8, "selected": false, "text": "module.py test_module.py test_module.py module.py ../tests/test_module.py tests/test_module.py test_ unittest test*.py" }, { "answer_id": 77145, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": ">>> import module\n>>> module.method('test')\n'testresult'\n ../tests/test_module.py tests/test_module.py" }, { "answer_id": 103610, "author": "Thomas Andrews", "author_id": 7061, "author_profile": "https://Stackoverflow.com/users/7061", "pm_score": 5, "selected": false, "text": "if __name__ == '__main__':\n do tests...\n if __name__ == '__main__':\n import tests.thisModule\n tests.thisModule.runtests\n" }, { "answer_id": 128616, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 2, "selected": false, "text": "app/src/code.py\napp/testing/code_test.py \napp/docs/..\n ../src/ sys.path" }, { "answer_id": 382596, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "test_suite='tests.runalltests.suite' setup() python setup.py test PYTHONPATH=. python tests/runalltests.py" }, { "answer_id": 2363162, "author": "Dale Reidy", "author_id": 50746, "author_profile": "https://Stackoverflow.com/users/50746", "pm_score": 3, "selected": false, "text": "project/\n src/\n code.py\n tests/\n setup.py\n setup.py develop\n setup.py tests\n" }, { "answer_id": 22704148, "author": "Rahul Biswas", "author_id": 2726038, "author_profile": "https://Stackoverflow.com/users/2726038", "pm_score": 4, "selected": false, "text": " <Main Package>\n / \\\n / \\\n lib tests\n / \\\n [module1.py, module2.py, [ut_module1.py, ut_module2.py,\n module3.py module4.py, ut_module3.py, ut_module.py]\n __init__.py]\n" }, { "answer_id": 23386287, "author": "Steely Wing", "author_id": 1877620, "author_profile": "https://Stackoverflow.com/users/1877620", "pm_score": 7, "selected": false, "text": "module/\n lib/\n __init__.py\n module.py\n test.py\n python test.py\n tests module/\n lib/\n __init__.py\n module.py\n tests/\n test_module.py\n test_module_function.py\n # test_module.py\n\nimport unittest\nfrom lib import module\n\nclass TestModule(unittest.TestCase):\n def test_module(self):\n pass\n\nif __name__ == '__main__':\n unittest.main()\n # In top-level /module/ folder\npython -m tests.test_module\npython -m tests.test_module_function\n unittest discovery unittest discovery __init__.py tests/ module/\n lib/\n __init__.py\n module.py\n tests/\n __init__.py\n test_module.py\n test_module_function.py\n # In top-level /module/ folder\n\n# -s, --start-directory (default current directory)\n# -p, --pattern (default test*.py)\n\npython -m unittest discover\n pytest unittest" }, { "answer_id": 37122327, "author": "Arash", "author_id": 832304, "author_profile": "https://Stackoverflow.com/users/832304", "pm_score": 4, "selected": false, "text": "myPackage/\n myapp/\n moduleA/\n __init__.py\n module_A.py\n moduleB/\n __init__.py\n module_B.py\nsetup.py\n myPackage/\n myapp/\n moduleA/\n __init__.py\n module_A.py\n moduleB/\n __init__.py\n module_B.py\ntest/\n unit/\n myapp/\n moduleA/\n module_A_test.py\n moduleB/\n module_B_test.py\n integration/\n myapp/\n moduleA/\n module_A_test.py\n moduleB/\n module_B_test.py\nsetup.py\n" }, { "answer_id": 39740835, "author": "Janusz Skonieczny", "author_id": 260480, "author_profile": "https://Stackoverflow.com/users/260480", "pm_score": 5, "selected": false, "text": "find_packages(\"src\", exclude=[\"*.tests\", \"*.tests.*\", \"tests.*\", \"tests\"]) \n" }, { "answer_id": 53740627, "author": "cjs", "author_id": 107294, "author_profile": "https://Stackoverflow.com/users/107294", "pm_score": 2, "selected": false, "text": "foo.py foo.pt vi foo.* foo_ut.py vi foo* foobar.py foobar_ut.py" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
61,155
<p>I'm trying to place this menu on the left hand side of the page:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="left-menu" style="left: 123px; top: 355px"&gt; &lt;ul&gt; &lt;li&gt; Categories &lt;/li&gt; &lt;li&gt; Weapons &lt;/li&gt; &lt;li&gt; Armor &lt;/li&gt; &lt;li&gt; Manuals &lt;/li&gt; &lt;li&gt; Sustenance &lt;/li&gt; &lt;li&gt; Test &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The problem is that if I use absolute or fixed values, different screen sizes will render the navigation bar differently. I also have a second <code>div</code> that contains all the main content which also needs to be moved to the right, so far I'm using relative values which seems to work no matter the screen size.</p>
[ { "answer_id": 61200, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "float px em % <div style=\"width: 10em; float: left;\">Left</div>\n<div>Right, spanning<br/> multiple lines</div>\n margin-left <div style=\"width: 10em; float: left;\">Left</div>\n<div style=\"margin-left: 10em;\">Right, spanning<br/> multiple lines</div>\n padding-left float" }, { "answer_id": 61438, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 2, "selected": false, "text": "<div> width margin padding <div> <ul> <p> float absolute relative float" }, { "answer_id": 15769430, "author": "Eng Maisa", "author_id": 2214827, "author_profile": "https://Stackoverflow.com/users/2214827", "pm_score": 0, "selected": false, "text": "<div class=\"left-menu\">\n<ul>\n<li> Categories </li>\n<li> Weapons </li>\n<li> Armor </li>\n<li> Manuals </li>\n<li> Sustenance </li>\n<li> Test </li>\n</ul>\n</div>\n .left-menu{float:left;width:200px;}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
61,176
<p>I want to access messages in Gmail from a Java application using <a href="http://www.ing.iac.es/~docs/external/java/javamail/javadocs/index.html" rel="nofollow noreferrer">JavaMail</a> and <a href="https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol" rel="nofollow noreferrer">IMAP</a>. Why am I getting a <em><a href="https://docs.oracle.com/javase/7/docs/api/java/net/SocketTimeoutException.html" rel="nofollow noreferrer">SocketTimeoutException</a></em> ?</p> <p>Here is my code:</p> <pre><code>Properties props = System.getProperties(); props.setProperty("mail.imap.host", "imap.gmail.com"); props.setProperty("mail.imap.port", "993"); props.setProperty("mail.imap.connectiontimeout", "5000"); props.setProperty("mail.imap.timeout", "5000"); try { Session session = Session.getDefaultInstance(props, new MyAuthenticator()); URLName urlName = new URLName("imap://[email protected]:[email protected]"); Store store = session.getStore(urlName); if (!store.isConnected()) { store.connect(); } } catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(1); } catch (MessagingException e) { e.printStackTrace(); System.exit(2); } </code></pre> <p>I have set the timeout values so that it wouldn't take "forever" to timeout. Also, <em>MyAuthenticator</em> also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for <a href="https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol" rel="nofollow noreferrer">IMAP</a>.)</p>
[ { "answer_id": 61185, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "imaps SSLNOTES.txt imaps://username%[email protected]/INBOX smtps smtps://username%[email protected]/ SSLNOTES.txt" }, { "answer_id": 61469, "author": "Dave", "author_id": 2512222, "author_profile": "https://Stackoverflow.com/users/2512222", "pm_score": 6, "selected": false, "text": "Properties props = System.getProperties();\nprops.setProperty(\"mail.store.protocol\", \"imaps\");\ntry {\n Session session = Session.getDefaultInstance(props, null);\n Store store = session.getStore(\"imaps\");\n store.connect(\"imap.gmail.com\", \"<username>@gmail.com\", \"<password>\");\n ...\n} catch (NoSuchProviderException e) {\n e.printStackTrace();\n System.exit(1);\n} catch (MessagingException e) {\n e.printStackTrace();\n System.exit(2);\n}\n" }, { "answer_id": 260650, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "URLName server = new URLName(\"imaps://<gmail-user-name>:<gmail-pass>@imap.gmail.com/INBOX\");\n" }, { "answer_id": 2385657, "author": "Fu Cheng", "author_id": 221847, "author_profile": "https://Stackoverflow.com/users/221847", "pm_score": 1, "selected": false, "text": "\"mail.imaps.host\" : \"imap.gmail.com\" \n\"mail.store.protocol\" : \"imaps\" \n\"mail.imaps.port\" : \"993\"\n" }, { "answer_id": 9888150, "author": "WhyNotHugo", "author_id": 107510, "author_profile": "https://Stackoverflow.com/users/107510", "pm_score": 3, "selected": false, "text": "props.setProperty(\"mail.imaps.host\", \"imap.gmail.com\");\nprops.setProperty(\"mail.imaps.port\", \"993\");\nprops.setProperty(\"mail.imaps.connectiontimeout\", \"5000\");\nprops.setProperty(\"mail.imaps.timeout\", \"5000\");\n" }, { "answer_id": 31214560, "author": "lboix", "author_id": 2920131, "author_profile": "https://Stackoverflow.com/users/2920131", "pm_score": 2, "selected": false, "text": " final Properties properties = new Properties();\n properties.put(\"mail.imap.ssl.enable\", \"true\");\n\n imapSession = Session.getInstance(properties, null);\n imapSession.setDebug(false);\n imapStore = imapSession.getStore(\"imap\");\n\n imapStore.connect(\"imap.gmail.com\", USERNAME, \"password\");\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2512222/" ]
61,212
<p>How do I delete untracked local files from the current working tree?</p>
[ { "answer_id": 61214, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 9, "selected": false, "text": "git-clean" }, { "answer_id": 64966, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 14, "selected": true, "text": "git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <path>…​\n -x <path>... -n # Print out the list of files and directories which will be removed (dry run)\ngit clean -n -d\n # Delete the files from the repository\ngit clean -f\n git clean -f -d git clean -fd git clean -f -X git clean -fX git clean -f -x git clean -fx X clean.requireForce -f git-clean -f --force -f -n -i -x $GIT_DIR/info/exclude -e -X -n --dry-run -d -f" }, { "answer_id": 912737, "author": "robert.berger", "author_id": 108743, "author_profile": "https://Stackoverflow.com/users/108743", "pm_score": 10, "selected": false, "text": "git clean -f -d git clean -n\n git clean --dry-run\n -f git clean -fd\n git status" }, { "answer_id": 14521765, "author": "Michał Szajbe", "author_id": 369894, "author_profile": "https://Stackoverflow.com/users/369894", "pm_score": 8, "selected": false, "text": "-f git clean -d -f -f" }, { "answer_id": 18974433, "author": "Vijay C", "author_id": 255721, "author_profile": "https://Stackoverflow.com/users/255721", "pm_score": 7, "selected": false, "text": "git clean -f {dir_path}\n git clean -fxd {dir_path}\n git status" }, { "answer_id": 20195320, "author": "Oscar Fraxedas", "author_id": 1074245, "author_profile": "https://Stackoverflow.com/users/1074245", "pm_score": 7, "selected": false, "text": "git clean -fdx\n" }, { "answer_id": 20846779, "author": "SystematicFrank", "author_id": 253098, "author_profile": "https://Stackoverflow.com/users/253098", "pm_score": 9, "selected": false, "text": "git clean -i\n --dry-run -d git iclean\n git clean -fd" }, { "answer_id": 21057032, "author": "hiroshi", "author_id": 338986, "author_profile": "https://Stackoverflow.com/users/338986", "pm_score": 7, "selected": false, "text": "git stash push -u git stash pop git show stash@{0}^3 git stash save push" }, { "answer_id": 28082580, "author": "Pooja", "author_id": 3446107, "author_profile": "https://Stackoverflow.com/users/3446107", "pm_score": 6, "selected": false, "text": "git clean -fd git clean -fX git clean -fx git clean -fdXx" }, { "answer_id": 29667299, "author": "Chhabilal", "author_id": 2554162, "author_profile": "https://Stackoverflow.com/users/2554162", "pm_score": 5, "selected": false, "text": "git clean -d -x -f\n (-d) git (-x) -f -n dry-run -i" }, { "answer_id": 34049725, "author": "Nikita Leonov", "author_id": 723050, "author_profile": "https://Stackoverflow.com/users/723050", "pm_score": 5, "selected": false, "text": "git clean -f -d -x $(git rev-parse --show-cdup) -f -d -x -d\n Remove untracked directories in addition to untracked files. If an\n untracked directory is managed by a different Git repository, it is\n not removed by default. Use -f option twice if you really want to\n remove such a directory.\n\n-f, --force\n If the Git configuration variable clean.requireForce is not set to\n false, git clean will refuse to delete files or directories unless\n given -f, -n or -i. Git will refuse to delete directories with .git\n sub directory or file unless a second -f is given. This affects\n also git submodules where the storage area of the removed submodule\n under .git/modules/ is not removed until -f is given twice.\n\n-x\n Don't use the standard ignore rules read from .gitignore (per\n directory) and $GIT_DIR/info/exclude, but do still use the ignore\n rules given with -e options. This allows removing all untracked\n files, including build products. This can be used (possibly in\n conjunction with git reset) to create a pristine working directory\n to test a clean build.\n git clean --help" }, { "answer_id": 35427633, "author": "Omar Mowafi", "author_id": 1350159, "author_profile": "https://Stackoverflow.com/users/1350159", "pm_score": 4, "selected": false, "text": "git clean -d -n git clean -d -f" }, { "answer_id": 35539401, "author": "thybzi", "author_id": 3027390, "author_profile": "https://Stackoverflow.com/users/3027390", "pm_score": 5, "selected": false, "text": "git add .\ngit reset --hard HEAD\n" }, { "answer_id": 35737150, "author": "JD Brennan", "author_id": 304712, "author_profile": "https://Stackoverflow.com/users/304712", "pm_score": 4, "selected": false, "text": "git stash save -u\ngit stash drop \"stash@{0}\"\n" }, { "answer_id": 37614185, "author": "Thanga", "author_id": 5678086, "author_profile": "https://Stackoverflow.com/users/5678086", "pm_score": 9, "selected": false, "text": "git add --all\ngit reset --hard HEAD\n" }, { "answer_id": 38978877, "author": "rahul286", "author_id": 156336, "author_profile": "https://Stackoverflow.com/users/156336", "pm_score": 5, "selected": false, "text": "git clean -ffdx\n" }, { "answer_id": 39968630, "author": "kujiy", "author_id": 5815086, "author_profile": "https://Stackoverflow.com/users/5815086", "pm_score": 4, "selected": false, "text": "git clean git version 2.9.0.windows.1 $ git clean -fdx # doesn't remove untracked files\n$ git clean -fdx * # Append star then it works!\n" }, { "answer_id": 40235858, "author": "Gaurav", "author_id": 3809978, "author_profile": "https://Stackoverflow.com/users/3809978", "pm_score": 4, "selected": false, "text": "git clean -fdn\n git clean -fd\n" }, { "answer_id": 41187216, "author": "Gnanasekar S", "author_id": 6859356, "author_profile": "https://Stackoverflow.com/users/6859356", "pm_score": 2, "selected": false, "text": "-i $ git clean -i $ git clean -d -i -d c" }, { "answer_id": 42185640, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 7, "selected": false, "text": "git clean -ffdx\n git clean -fdx\n git clean -fd\n git clean -fdX\n git clean\n" }, { "answer_id": 42269293, "author": "Vaisakh VM", "author_id": 1905008, "author_profile": "https://Stackoverflow.com/users/1905008", "pm_score": 4, "selected": false, "text": "git clean -f to remove untracked files from working directory." }, { "answer_id": 42564993, "author": "bit_cracker007", "author_id": 1098479, "author_profile": "https://Stackoverflow.com/users/1098479", "pm_score": 5, "selected": false, "text": "git clean -i -fd\n\nRemove .classpath [y/N]? N\nRemove .gitignore [y/N]? N\nRemove .project [y/N]? N\nRemove .settings/ [y/N]? N\nRemove src/com/arsdumpgenerator/inspector/ [y/N]? y\nRemove src/com/arsdumpgenerator/manifest/ [y/N]? y\nRemove src/com/arsdumpgenerator/s3/ [y/N]? y\nRemove tst/com/arsdumpgenerator/manifest/ [y/N]? y\nRemove tst/com/arsdumpgenerator/s3/ [y/N]? y\n" }, { "answer_id": 45220636, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 6, "selected": false, "text": "git git clean -fd\n -f -d -f git clean -f\n git clean -fd\n -x -i -n -q -f" }, { "answer_id": 45558196, "author": "Vivek", "author_id": 4199462, "author_profile": "https://Stackoverflow.com/users/4199462", "pm_score": 0, "selected": false, "text": "git reset HEAD <file>" }, { "answer_id": 45994347, "author": "Mohideen bin Mohammed", "author_id": 4453737, "author_profile": "https://Stackoverflow.com/users/4453737", "pm_score": 4, "selected": false, "text": "git clean -i git clean \n -d -f -i -n -q -e -x -X (can use either)\n" }, { "answer_id": 46409906, "author": "Sergey", "author_id": 739731, "author_profile": "https://Stackoverflow.com/users/739731", "pm_score": 3, "selected": false, "text": "(git clean -d -x -f && git submodule foreach --recursive git clean -d -x -f)\n" }, { "answer_id": 46868431, "author": "DevWL", "author_id": 2179965, "author_profile": "https://Stackoverflow.com/users/2179965", "pm_score": 7, "selected": false, "text": "-n -n -d -f --force git clean -n -d \ngit clean -n -d -f\n -n git clean -d -f\n git clean -x git clean -f -d -x\n -i git clean -x -i\n git stash --all\n stash --all --all git stash push --keep-index\n git stash git stash push git stash push -m \"name your stash\" // before git stash save (deprecated)\n git stash drop // or clean\n" }, { "answer_id": 47070614, "author": "Jämes", "author_id": 2780334, "author_profile": "https://Stackoverflow.com/users/2780334", "pm_score": 3, "selected": false, "text": "gclean='git clean -fd' gpristine='git reset --hard && git clean -dfx' gclean gpristine" }, { "answer_id": 47627685, "author": "Elangovan", "author_id": 2614459, "author_profile": "https://Stackoverflow.com/users/2614459", "pm_score": 3, "selected": false, "text": "git reset [--soft | --mixed [-N] | --hard | --merge | --keep] [-q] [<commit>]\n git reset --hard HEAD\n" }, { "answer_id": 50404741, "author": "Sudhir Vishwakarma", "author_id": 493356, "author_profile": "https://Stackoverflow.com/users/493356", "pm_score": 3, "selected": false, "text": "git clean -f\n git clean -fd\n" }, { "answer_id": 53244015, "author": "Zia", "author_id": 2931121, "author_profile": "https://Stackoverflow.com/users/2931121", "pm_score": 2, "selected": false, "text": "git stash git clean" }, { "answer_id": 55831043, "author": "victorm1710", "author_id": 680032, "author_profile": "https://Stackoverflow.com/users/680032", "pm_score": 1, "selected": false, "text": "git add -A && git commit -m temp && git reset --hard HEAD^" }, { "answer_id": 56520858, "author": "Thirdy", "author_id": 5118429, "author_profile": "https://Stackoverflow.com/users/5118429", "pm_score": -1, "selected": false, "text": "git status rm <path of file> git clean" }, { "answer_id": 59435746, "author": "ideasman42", "author_id": 432509, "author_profile": "https://Stackoverflow.com/users/432509", "pm_score": 0, "selected": false, "text": "#!/bin/bash\nreadarray -t -d '' FILES < <(git ls-files -z --other --directory)\nif [ \"$FILES\" = \"\" ]; then\n echo \"Nothing to clean!\"\n exit 0\nfi\necho -e \"Dirty files:\\n\"\nprintf ' %s\\n' \"${FILES[@]}\"\nDO_REMOVE=0\nwhile true; do\n echo \"\"\n read -p \"Remove ${#FILES[@]} files? [y/n]: \" choice\n case \"$choice\" in\n y|Y )\n DO_REMOVE=1\n break ;;\n n|N )\n echo \"Exiting!\"\n break ;;\n * ) echo \"Invalid input, expected [Y/y/N/n]\"\n continue ;;\n esac\ndone\n\nif [ \"$DO_REMOVE\" -eq 1 ];then\n echo \"Removing!\"\n for f in \"${FILES[@]}\"; do\n rm -rfv -- \"$f\"\n done\nfi\n" }, { "answer_id": 61917678, "author": "Rajeev Shetty", "author_id": 3932147, "author_profile": "https://Stackoverflow.com/users/3932147", "pm_score": 5, "selected": false, "text": "git add .\ngit reset --hard HEAD\n" }, { "answer_id": 63590924, "author": "Samir Kape", "author_id": 8312897, "author_profile": "https://Stackoverflow.com/users/8312897", "pm_score": 1, "selected": false, "text": "-q, --quiet do not print names of files removed\n-n, --dry-run dry run\n-f, --force force\n-i, --interactive interactive cleaning\n-d remove whole directories\n-e, --exclude <pattern>\n add <pattern> to ignore rules\n-x remove ignored files, too\n-X remove only ignored files\n" }, { "answer_id": 64769771, "author": "KARTHIKEYAN.A", "author_id": 4652706, "author_profile": "https://Stackoverflow.com/users/4652706", "pm_score": 3, "selected": false, "text": "$ git clean -f -d\nRemoving client/app/helpers/base64.js\nRemoving files/\nRemoving package.json.bak\n\nwhere \n-f is force \n-d is a directory \n" }, { "answer_id": 67098568, "author": "jenny", "author_id": 6409591, "author_profile": "https://Stackoverflow.com/users/6409591", "pm_score": 4, "selected": false, "text": "git add --all git stash git stash drop" }, { "answer_id": 68547440, "author": "Ahmet Emrebas", "author_id": 12603032, "author_profile": "https://Stackoverflow.com/users/12603032", "pm_score": 3, "selected": false, "text": "git add .\ngit stash \n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
61,217
<p>This question is a follow up to my <a href="https://stackoverflow.com/questions/56279/export-aspx-to-html">previous question</a> about getting the HTML from an ASPX page. I decided to try using the webclient object, but the problem is that I get the login page's HTML because login is required. I tried "logging in" using the webclient object:</p> <pre><code>WebClient ww = new WebClient(); ww.DownloadString("Login.aspx?UserName=&amp;Password="); string html = ww.DownloadString("Internal.aspx"); </code></pre> <p>But I still get the login page all the time. I know that the username info is not stored in a cookie. I must be doing something wrong or leaving out an important part. Does anyone know what it could be?</p>
[ { "answer_id": 61231, "author": "NakedBrunch", "author_id": 3742, "author_profile": "https://Stackoverflow.com/users/3742", "pm_score": 2, "selected": false, "text": "WebClient ww = new WebClient();\nww.Credentials = CredentialCache.DefaultCredentials;\nww.DownloadString(\"Login.aspx?UserName=&Password=\");\nstring html = ww.DownloadString(\"Internal.aspx\");\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278/" ]
61,219
<p>I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...).</p> <p>He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.:</p> <pre><code>Debug.Assert(i &gt; 3, "i &gt; 3", "This means I got a bad parameter"); </code></pre> <p>Now, personally, it seems crazy to me that he so loves restating his test without an actual sensible 'business logic' comment, perhaps "i &lt;= 3 must never happen because of the flobittyjam widgitification process".</p> <p>So, I think I get Asserts as a kind-of low-level "Let's protect my assumptions" kind of thing... assuming that one feels this is a test one only needs to do in debug - i.e. you are protecting yourself against colleague and future programmers, and hoping that they actually test things.</p> <p>But what I don't get is, he then goes on to say that you should use assertions in addition to normal error handling; now what I envisage is something like this:</p> <pre><code>Debug.Assert(i &gt; 3, "i must be greater than 3 because of the flibbity widgit status"); if (i &lt;= 3) { throw new ArgumentOutOfRangeException("i", "i must be &gt; 3 because... i=" + i.ToString()); } </code></pre> <p>What have I gained by the Debug.Assert repetition of the error condition test? I think I'd get it if we were talking about debug-only double-checking of a very important calculation...</p> <pre><code>double interestAmount = loan.GetInterest(); Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc"); </code></pre> <p>...but I don't get it for parameter tests which are surely worth checking (in both DEBUG and Release builds)... or not. What am I missing?</p>
[ { "answer_id": 61225, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": true, "text": "ArgumentOutOfRangeException" }, { "answer_id": 61266, "author": "hwiechers", "author_id": 5883, "author_profile": "https://Stackoverflow.com/users/5883", "pm_score": 4, "selected": false, "text": "public string ToString()\n{\n Debug.Assert(Name != null);\n return Name;\n}\n public string ToString()\n{\n if ( Name == null )\n {\n throw new InvalidOperationException(\"Name is null\");\n }\n\n return Name;\n}\n public string ToString()\n{\n Debug.Assert(Name != null);\n if ( Name == null )\n {\n throw new InvalidOperationException(\"Name is null\");\n }\n\n return Name;\n}\n" }, { "answer_id": 5964259, "author": "Tim Abell", "author_id": 10245, "author_profile": "https://Stackoverflow.com/users/10245", "pm_score": 1, "selected": false, "text": "Debug.Assert(flibbles.count() < 1000000, \"too many flibbles\"); // indicate something is awry\nlog.warning(\"flibble count reached \" + flibbles.count()); // log in production as early warning\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6004/" ]
61,227
<p>If I have: </p> <pre><code>signed char * p; </code></pre> <p>and I do a comparison:</p> <pre><code>if ( *p == 0xFF ) break; </code></pre> <p>it will never catch 0XFF, but if I replace it with -1 it will:</p> <pre><code>if ( *p == (signed char)0xFF ) break; </code></pre> <p>How can this happen? Is it something with the sign flag? I though that <code>0xFF == -1 == 255</code>.</p>
[ { "answer_id": 61229, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "0xFF *p int if( -1 == 255 ) break;\n (signed char)0xFF if( -1 == -1 ) break;\n int signed char" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2566/" ]
61,233
<p>What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:</p> <pre><code>INSERT INTO some_table (column1, column2, column3) SELECT Rows.n.value('(@column1)[1]', 'varchar(20)'), Rows.n.value('(@column2)[1]', 'nvarchar(100)'), Rows.n.value('(@column3)[1]', 'int'), FROM @xml.nodes('//Rows') Rows(n) </code></pre> <p>However I find that this is getting very slow for even moderate size xml data.</p>
[ { "answer_id": 61246, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "INSERT INTO Test\nSELECT Id, Data \nFROM OPENXML (@XmlDocument, '/Root/blah',2)\nWITH (Id int '@ID',\n Data varchar(10) '@DATA')\n" }, { "answer_id": 631578, "author": "DannykPowell", "author_id": 67617, "author_profile": "https://Stackoverflow.com/users/67617", "pm_score": 1, "selected": false, "text": "INSERT INTO some_table (column1, column2, column3)\nSELECT\nRows.n.value('(@column1)[1]', 'varchar(20)'),\nRows.n.value('(@column2)[1]', 'nvarchar(100)'),\nRows.n.value('(@column3)[1]', 'int'),\nFROM @xml.nodes('//Rows') Rows(n)\n" }, { "answer_id": 4671129, "author": "Dan", "author_id": 572994, "author_profile": "https://Stackoverflow.com/users/572994", "pm_score": 7, "selected": true, "text": "IF EXISTS ( SELECT * FROM sys.xml_schema_collections where [name] = 'MyXmlSchema')\nDROP XML SCHEMA COLLECTION [MyXmlSchema]\nGO\n\nDECLARE @MySchema XML\nSET @MySchema = \n(\n SELECT * FROM OPENROWSET\n (\n BULK 'C:\\Path\\To\\Schema\\MySchema.xsd', SINGLE_CLOB \n ) AS xmlData\n)\n\nCREATE XML SCHEMA COLLECTION [MyXmlSchema] AS @MySchema \nGO\n CREATE TABLE [dbo].[XmlFiles] (\n [Id] [uniqueidentifier] NOT NULL,\n\n -- Data from CV element \n [Data] xml(CONTENT dbo.[MyXmlSchema]) NOT NULL,\n\nCONSTRAINT [PK_XmlFiles] PRIMARY KEY NONCLUSTERED \n(\n [Id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n CREATE PRIMARY XML INDEX PXML_Data\nON [dbo].[XmlFiles] (Data)\n XQuery [dbo.XmlFiles.Data.value()]: Cannot implicitly atomize or apply 'fn:data()' to complex content elements, found type 'xs:anyType' within inferred type 'element({http://www.mynamespace.fake/schemas}:SequenceNumber,xs:anyType) ?'.\n SELECT\n ,C.value('CVElementId[1]', 'INT') AS [CVElementId]\n ,C.value('../SequenceNumber[1]', 'INT') AS [Level]\nFROM \n [dbo].[XmlFiles]\nCROSS APPLY\n [Data].nodes('/CVSet/Level/CVElement') AS T(C)\n SELECT\n ,C.value('CVElementId[1]', 'INT') AS [CVElementId]\n ,B.value('SequenceNumber[1]', 'INT') AS [Level]\nFROM \n [dbo].[XmlFiles]\nCROSS APPLY\n [Data].nodes('/CVSet/Level') AS T(B)\nOUTER APPLY\n B.nodes ('CVElement') AS S(C)\n" }, { "answer_id": 9794641, "author": "edhubbell", "author_id": 1054938, "author_profile": "https://Stackoverflow.com/users/1054938", "pm_score": 2, "selected": false, "text": "INSERT INTO some_table (column1, column2, column3)\n SELECT \n Rows.n.value(N'(@column1/text())[1]', 'varchar(20)'), \n Rows.n.value(N'(@column2/text())[1]', 'nvarchar(100)'), \n Rows.n.value(N'(@column3/text())[1]', 'int')\n FROM @xml.nodes('//Rows') Rows(n) \n" }, { "answer_id": 18264248, "author": "jccprj", "author_id": 2687849, "author_profile": "https://Stackoverflow.com/users/2687849", "pm_score": 3, "selected": false, "text": "INSERT INTO @tbl (Tbl_ID, Name, Value, ParamData)\nSELECT 1,\n tbl.cols.value('name[1]', 'nvarchar(255)'),\n tbl.cols.value('value[1]', 'nvarchar(255)'),\n tbl.cols.query('./paramdata[1]')\nFROM @xml.nodes('//root') as tbl(cols) OPTION ( OPTIMIZE FOR ( @xml = NULL ) )\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ]
61,262
<p>Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file.<br> Now you want to create a class or use a symbol which is defined in multiple namespaces, e.g. <code>System.Windows.Controls.Image</code> &amp; <code>System.Drawing.Image</code></p> <p>Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here?</p> <p><em>(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)</em></p>
[ { "answer_id": 61264, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": true, "text": "using System.Windows.Controls;\nusing Drawing = System.Drawing;\n\n...\n\nImage img = ... //System.Windows.Controls.Image\nDrawing.Image img2 = ... //System.Drawing.Image\n" }, { "answer_id": 61265, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "using ControlImage = System.Windows.Controls.Image;\nusing System.Drawing.Image;\n\nControlImage.Image myImage = new ControlImage.Image();\nmyImage.Width = 200;\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
61,278
<p>What method do you use when you want to get performance data about specific code paths?</p>
[ { "answer_id": 61279, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": true, "text": "#pragma once\n#include <tchar.h>\n#include <windows.h>\n#include <sstream>\n#include <boost/noncopyable.hpp>\n\nnamespace scope_timer {\n class time_collector : boost::noncopyable {\n __int64 total;\n LARGE_INTEGER start;\n size_t times;\n const TCHAR* name;\n\n double cpu_frequency()\n { // cache the CPU frequency, which doesn't change.\n static double ret = 0; // store as double so devision later on is floating point and not truncating\n if (ret == 0) {\n LARGE_INTEGER freq;\n QueryPerformanceFrequency(&freq);\n ret = static_cast<double>(freq.QuadPart);\n }\n return ret;\n }\n bool in_use;\n\n public:\n time_collector(const TCHAR* n)\n : times(0)\n , name(n)\n , total(0)\n , start(LARGE_INTEGER())\n , in_use(false)\n {\n }\n\n ~time_collector()\n {\n std::basic_ostringstream<TCHAR> msg;\n msg << _T(\"scope_timer> \") << name << _T(\" called: \");\n\n double seconds = total / cpu_frequency();\n double average = seconds / times;\n\n msg << times << _T(\" times total time: \") << seconds << _T(\" seconds \")\n << _T(\" (avg \") << average <<_T(\")\\n\");\n OutputDebugString(msg.str().c_str());\n }\n\n void add_time(__int64 ticks)\n {\n total += ticks;\n ++times;\n in_use = false;\n }\n\n bool aquire()\n {\n if (in_use)\n return false;\n in_use = true;\n return true;\n }\n };\n\n class one_time : boost::noncopyable {\n LARGE_INTEGER start;\n time_collector* collector;\n public:\n one_time(time_collector& tc)\n {\n if (tc.aquire()) {\n collector = &tc;\n QueryPerformanceCounter(&start);\n }\n else\n collector = 0;\n }\n\n ~one_time()\n {\n if (collector) {\n LARGE_INTEGER end;\n QueryPerformanceCounter(&end);\n collector->add_time(end.QuadPart - start.QuadPart);\n }\n }\n };\n}\n\n// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)\n#define TIME_THIS_SCOPE(name) \\\n static scope_timer::time_collector st_time_collector_##name(_T(#name)); \\\n scope_timer::one_time st_one_time_##name(st_time_collector_##name)\n" }, { "answer_id": 61281, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "Timer timer = new Timer\ntimer.Start\n timer.Stop\nshow elapsed time\n" }, { "answer_id": 61303, "author": "MrValdez", "author_id": 1599, "author_profile": "https://Stackoverflow.com/users/1599", "pm_score": 2, "selected": false, "text": "cProfile cProfileManager cProfileManager cProfile cProfile cProfile cProfile cProfileManager cProfileManager cProfile cProfile cProfileManager class cProfile\n{\n cProfile()\n {\n TimeStart = GetTime();\n };\n\n ~cProfile()\n {\n ProfileManager->AddProfile (GetTime() - TimeStart);\n }\n\n float TimeStart;\n}\n cProfile int main()\n{\n printf(\"Start test\");\n {\n cProfile Profile;\n Calculate();\n }\n ProfileManager->OutputData();\n}\n void foobar()\n{\n cProfile ProfileFoobar;\n\n foo();\n {\n cProfile ProfileBarCheck;\n while (bar())\n {\n cProfile ProfileSpam;\n spam();\n }\n }\n}\n cProfile cProfile cProfileManager" }, { "answer_id": 231590, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "dumpResults()" }, { "answer_id": 231614, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 2, "selected": false, "text": "int CInsertBuffer::Read(char* pBuf)\n{\n // TIMER NOTES: Avg Execution Time = ~1 ms\n Timer timer(\"BufferRead\");\n : :\n return -1;\n}\n Timer Precision = 418.0095 ps\n\n=== Item Trials Ttl Time Avg Time Mean Time StdDev ===\n AddTrade 500 7 ms 14 us 12 us 24 us\n BufferRead 511 1:19.25 0.16 s 621 ns 2.48 s\n BufferWrite 516 511 us 991 ns 482 ns 11 us\n ImportPos Loop 1002 18.62 s 19 ms 77 us 0.51 s\n ImportPosition 2 18.75 s 9.38 s 16.17 s 13.59 s\n Insert 515 4.26 s 8 ms 5 ms 27 ms\n recv 101 18.54 s 0.18 s 2603 ns 1.63 s\n #include <map>\n#include \"x:\\utils\\stlext\\stringext.h\"\n#include <iterator>\n#include <set>\n#include <vector>\n#include <numeric>\n#include \"x:\\utils\\stlext\\algorithmext.h\"\n#include <math.h>\n\n class Timer\n {\n public:\n Timer(const char* name)\n {\n label = std::safe_string(name);\n QueryPerformanceCounter(&startTime);\n }\n\n virtual ~Timer()\n {\n QueryPerformanceCounter(&stopTime);\n __int64 clocks = stopTime.QuadPart-startTime.QuadPart;\n double elapsed = (double)clocks/(double)TimerFreq();\n TimeMap().insert(std::make_pair(label,elapsed));\n };\n\n static std::string Dump(bool ClipboardAlso=true)\n {\n static const std::string loc = \"Timer::Dump\";\n\n if( TimeMap().empty() )\n {\n return \"No trials\\r\\n\";\n }\n\n std::string ret = std::formatstr(\"\\r\\n\\r\\nTimer Precision = %s\\r\\n\\r\\n\", format_elapsed(1.0/(double)TimerFreq()).c_str());\n\n // get a list of keys\n typedef std::set<std::string> keyset;\n keyset keys;\n std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());\n\n size_t maxrows = 0;\n\n typedef std::vector<std::string> strings;\n strings lines;\n\n static const size_t tabWidth = 9;\n\n std::string head = std::formatstr(\"=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===\", tabWidth*2, tabWidth*2, \"Item\", tabWidth, tabWidth, \"Trials\", tabWidth, tabWidth, \"Ttl Time\", tabWidth, tabWidth, \"Avg Time\", tabWidth, tabWidth, \"Mean Time\", tabWidth, tabWidth, \"StdDev\");\n ret += std::formatstr(\"\\r\\n%s\\r\\n\", head.c_str());\n if( ClipboardAlso ) \n lines.push_back(\"Item\\tTrials\\tTtl Time\\tAvg Time\\tMean Time\\tStdDev\\r\\n\");\n // dump the values for each key\n {for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )\n {\n time_type ttl = 0;\n ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));\n size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));\n if( num > maxrows ) \n maxrows = num;\n time_type avg = ttl / num;\n\n // compute mean\n std::vector<time_type> sortedTimes;\n std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));\n std::sort(sortedTimes.begin(), sortedTimes.end());\n size_t mid = (size_t)floor((double)num/2.0);\n double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];\n // compute variance\n double sum = 0.0;\n if( num > 1 )\n {\n for( std::vector<time_type>::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )\n sum += pow(*timeIt-mean,2.0);\n }\n // compute std dev\n double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;\n\n ret += std::formatstr(\" %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\\r\\n\", tabWidth*2, tabWidth*2, key->c_str(), tabWidth, tabWidth, std::formatstr(\"%d\",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str()); \n if( ClipboardAlso )\n lines.push_back(std::formatstr(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\r\\n\", key->c_str(), std::formatstr(\"%d\",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str())); \n\n }\n }\n ret += std::formatstr(\"%s\\r\\n\", std::string(head.length(),'=').c_str());\n\n if( ClipboardAlso )\n {\n // dump header row of data block\n lines.push_back(\"\");\n {\n std::string s;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n s.append(\"\\t\");\n s.append(*key);\n }\n s.append(\"\\r\\n\");\n lines.push_back(s);\n }\n\n // blow out the flat map of time values to a seperate vector of times for each key\n typedef std::map<std::string, std::vector<time_type> > nodematrix;\n nodematrix nodes;\n for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )\n nodes[time->first].push_back(time->second);\n\n // dump each data point\n for( size_t row = 0; row < maxrows; ++row )\n {\n std::string rowDump;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n rowDump.append(\"\\t\");\n if( nodes[*key].size() > row )\n rowDump.append(std::formatstr(\"%f\", nodes[*key][row]));\n }\n rowDump.append(\"\\r\\n\");\n lines.push_back(rowDump);\n }\n\n // dump to the clipboard\n std::string dump;\n for( strings::iterator s = lines.begin(); s != lines.end(); ++s )\n {\n dump.append(*s);\n }\n\n OpenClipboard(0);\n EmptyClipboard();\n HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);\n if( hg != 0 )\n {\n char* buf = (char*)GlobalLock(hg);\n if( buf != 0 )\n {\n std::copy(dump.begin(), dump.end(), buf);\n buf[dump.length()] = 0;\n GlobalUnlock(hg);\n SetClipboardData(CF_TEXT, hg);\n }\n }\n CloseClipboard();\n }\n\n return ret;\n }\n\n static void Reset()\n {\n TimeMap().clear();\n }\n\n static std::string format_elapsed(double d) \n {\n if( d < 0.00000001 )\n {\n // show in ps with 4 digits\n return std::formatstr(\"%0.4f ps\", d * 1000000000000.0);\n }\n if( d < 0.00001 )\n {\n // show in ns\n return std::formatstr(\"%0.0f ns\", d * 1000000000.0);\n }\n if( d < 0.001 )\n {\n // show in us\n return std::formatstr(\"%0.0f us\", d * 1000000.0);\n }\n if( d < 0.1 )\n {\n // show in ms\n return std::formatstr(\"%0.0f ms\", d * 1000.0);\n }\n if( d <= 60.0 )\n {\n // show in seconds\n return std::formatstr(\"%0.2f s\", d);\n }\n if( d < 3600.0 )\n {\n // show in min:sec\n return std::formatstr(\"%01.0f:%02.2f\", floor(d/60.0), fmod(d,60.0));\n }\n // show in h:min:sec\n return std::formatstr(\"%01.0f:%02.0f:%02.2f\", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));\n }\n\n private:\n static __int64 TimerFreq()\n {\n static __int64 freq = 0;\n static bool init = false;\n if( !init )\n {\n LARGE_INTEGER li;\n QueryPerformanceFrequency(&li);\n freq = li.QuadPart;\n init = true;\n }\n return freq;\n }\n LARGE_INTEGER startTime, stopTime;\n std::string label;\n\n typedef std::string key_type;\n typedef double time_type;\n typedef std::multimap<key_type, time_type> Times;\n// static Times times;\n static Times& TimeMap()\n {\n static Times times_;\n return times_;\n }\n\n struct extract_key : public std::unary_function<Times::value_type, key_type>\n {\n std::string operator()(Times::value_type const & r) const\n {\n return r.first;\n }\n };\n\n struct extract_val : public std::unary_function<Times::value_type, time_type>\n {\n time_type operator()(Times::value_type const & r) const\n {\n return r.second;\n }\n };\n struct match_key : public std::unary_function<Times::value_type, bool>\n {\n match_key(key_type const & key_) : key(key_) {};\n bool operator()(Times::value_type const & rhs) const\n {\n return key == rhs.first;\n }\n private:\n match_key& operator=(match_key&) { return * this; }\n const key_type key;\n };\n\n struct accum_key : public std::binary_function<time_type, Times::value_type, time_type>\n {\n accum_key(key_type const & key_) : key(key_), n(0) {};\n time_type operator()(time_type const & v, Times::value_type const & rhs) const\n {\n if( key == rhs.first )\n {\n ++n;\n return rhs.second + v;\n }\n return v;\n }\n private:\n accum_key& operator=(accum_key&) { return * this; }\n const Times::key_type key;\n mutable size_t n;\n };\n };\n namespace std\n{\n /* ---\n\n Formatted Print\n\n template<class C>\n int strprintf(basic_string<C>* pString, const C* pFmt, ...);\n\n template<class C>\n int vstrprintf(basic_string<C>* pString, const C* pFmt, va_list args);\n\n Returns :\n\n # characters printed to output\n\n\n Effects :\n\n Writes formatted data to a string. strprintf() works exactly the same as sprintf(); see your\n documentation for sprintf() for details of peration. vstrprintf() also works the same as sprintf(), \n but instead of accepting a variable paramater list it accepts a va_list argument.\n\n Requires :\n\n pString is a pointer to a basic_string<>\n\n --- */\n\n template<class char_type> int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);\n\n template<> inline int vprintf_generic<char>(char* buffer, size_t bufferSize, const char* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template<> inline int vprintf_generic<wchar_t>(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnwprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template<class Type, class Traits>\n inline int vstringprintf(basic_string<Type,Traits> & outStr, const Type* format, va_list args)\n {\n // prologue\n static const size_t ChunkSize = 1024;\n size_t curBufSize = 0;\n outStr.erase(); \n\n if( !format )\n {\n return 0;\n }\n\n // keep trying to write the string to an ever-increasing buffer until\n // either we get the string written or we run out of memory\n while( bool cont = true )\n {\n // allocate a local buffer\n curBufSize += ChunkSize;\n std::ref_ptr<Type> localBuffer = new Type[curBufSize];\n if( localBuffer.get() == 0 )\n {\n // we ran out of memory -- nice goin'!\n return -1;\n }\n // format output to local buffer\n int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);\n if( -1 == i )\n {\n // the buffer wasn't big enough -- try again\n continue;\n }\n else if( i < 0 )\n {\n // something wierd happened -- bail\n return i;\n }\n // if we get to this point the string was written completely -- stop looping\n outStr.assign(localBuffer.get(),i);\n return i;\n }\n // unreachable code\n return -1;\n };\n\n // provided for backward-compatibility\n template<class Type, class Traits>\n inline int vstrprintf(basic_string<Type,Traits> * outStr, const Type* format, va_list args)\n {\n return vstringprintf(*outStr, format, args);\n }\n\n template<class Char, class Traits>\n inline int stringprintf(std::basic_string<Char, Traits> & outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(outString, format, args);\n va_end(args);\n return retval;\n }\n\n // old function provided for backward-compatibility\n template<class Char, class Traits>\n inline int strprintf(std::basic_string<Char, Traits> * outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(*outString, format, args);\n va_end(args);\n return retval;\n }\n\n /* ---\n\n Inline Formatted Print\n\n string strprintf(const char* Format, ...);\n\n Returns :\n\n Formatted string\n\n\n Effects :\n\n Writes formatted data to a string. formatstr() works the same as sprintf(); see your\n documentation for sprintf() for details of operation. \n\n --- */\n\n template<class Char>\n inline std::basic_string<Char> formatstr(const Char * format, ...)\n {\n std::string outString;\n\n va_list args;\n va_start(args, format);\n vstringprintf(outString, format, args);\n va_end(args);\n return outString;\n }\n};\n /* ---\n\nTransform\n25.2.3\n\n template<class InputIterator, class OutputIterator, class UnaryOperation, class Predicate>\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)\n\n template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)\n\nRequires: \n\n T is of type EqualityComparable (20.1.1) \n op and binary_op have no side effects\n\nEffects :\n\n Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:\n 1: op( *(first1 + (i - result)) \n 2: binary_op( *(first1 + (i - result), *(first2 + (i - result))\n\nReturns :\n\n result + (last1 - first1)\n\nComplexity :\n\n At most last1 - first1 applications of op or binary_op\n\n--- */\n\ntemplate<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>\nOutputIterator transform_if(InputIterator first, \n InputIterator last, \n OutputIterator result, \n UnaryFunction f, \n Predicate pred)\n{\n for (; first != last; ++first)\n {\n if( pred(*first) )\n *result++ = f(*first);\n }\n return result; \n}\n\ntemplate<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>\nOutputIterator transform_if(InputIterator1 first1, \n InputIterator1 last1, \n InputIterator2 first2, \n OutputIterator result, \n BinaryOperation binary_op, \n Predicate pred)\n{\n for (; first1 != last1 ; ++first1, ++first2)\n {\n if( pred(*first1) )\n *result++ = binary_op(*first1,*first2);\n }\n return result;\n}\n" }, { "answer_id": 44489926, "author": "metamorphosis", "author_id": 3454889, "author_profile": "https://Stackoverflow.com/users/3454889", "pm_score": 0, "selected": false, "text": "plf::timer t;\ntimer.start();\n\n// stuff\n\ndouble elapsed = t.get_elapsed_ns(); // Get nanoseconds\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
61,307
<p>I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?</p>
[ { "answer_id": 61279, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": true, "text": "#pragma once\n#include <tchar.h>\n#include <windows.h>\n#include <sstream>\n#include <boost/noncopyable.hpp>\n\nnamespace scope_timer {\n class time_collector : boost::noncopyable {\n __int64 total;\n LARGE_INTEGER start;\n size_t times;\n const TCHAR* name;\n\n double cpu_frequency()\n { // cache the CPU frequency, which doesn't change.\n static double ret = 0; // store as double so devision later on is floating point and not truncating\n if (ret == 0) {\n LARGE_INTEGER freq;\n QueryPerformanceFrequency(&freq);\n ret = static_cast<double>(freq.QuadPart);\n }\n return ret;\n }\n bool in_use;\n\n public:\n time_collector(const TCHAR* n)\n : times(0)\n , name(n)\n , total(0)\n , start(LARGE_INTEGER())\n , in_use(false)\n {\n }\n\n ~time_collector()\n {\n std::basic_ostringstream<TCHAR> msg;\n msg << _T(\"scope_timer> \") << name << _T(\" called: \");\n\n double seconds = total / cpu_frequency();\n double average = seconds / times;\n\n msg << times << _T(\" times total time: \") << seconds << _T(\" seconds \")\n << _T(\" (avg \") << average <<_T(\")\\n\");\n OutputDebugString(msg.str().c_str());\n }\n\n void add_time(__int64 ticks)\n {\n total += ticks;\n ++times;\n in_use = false;\n }\n\n bool aquire()\n {\n if (in_use)\n return false;\n in_use = true;\n return true;\n }\n };\n\n class one_time : boost::noncopyable {\n LARGE_INTEGER start;\n time_collector* collector;\n public:\n one_time(time_collector& tc)\n {\n if (tc.aquire()) {\n collector = &tc;\n QueryPerformanceCounter(&start);\n }\n else\n collector = 0;\n }\n\n ~one_time()\n {\n if (collector) {\n LARGE_INTEGER end;\n QueryPerformanceCounter(&end);\n collector->add_time(end.QuadPart - start.QuadPart);\n }\n }\n };\n}\n\n// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)\n#define TIME_THIS_SCOPE(name) \\\n static scope_timer::time_collector st_time_collector_##name(_T(#name)); \\\n scope_timer::one_time st_one_time_##name(st_time_collector_##name)\n" }, { "answer_id": 61281, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "Timer timer = new Timer\ntimer.Start\n timer.Stop\nshow elapsed time\n" }, { "answer_id": 61303, "author": "MrValdez", "author_id": 1599, "author_profile": "https://Stackoverflow.com/users/1599", "pm_score": 2, "selected": false, "text": "cProfile cProfileManager cProfileManager cProfile cProfile cProfile cProfile cProfileManager cProfileManager cProfile cProfile cProfileManager class cProfile\n{\n cProfile()\n {\n TimeStart = GetTime();\n };\n\n ~cProfile()\n {\n ProfileManager->AddProfile (GetTime() - TimeStart);\n }\n\n float TimeStart;\n}\n cProfile int main()\n{\n printf(\"Start test\");\n {\n cProfile Profile;\n Calculate();\n }\n ProfileManager->OutputData();\n}\n void foobar()\n{\n cProfile ProfileFoobar;\n\n foo();\n {\n cProfile ProfileBarCheck;\n while (bar())\n {\n cProfile ProfileSpam;\n spam();\n }\n }\n}\n cProfile cProfile cProfileManager" }, { "answer_id": 231590, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "dumpResults()" }, { "answer_id": 231614, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 2, "selected": false, "text": "int CInsertBuffer::Read(char* pBuf)\n{\n // TIMER NOTES: Avg Execution Time = ~1 ms\n Timer timer(\"BufferRead\");\n : :\n return -1;\n}\n Timer Precision = 418.0095 ps\n\n=== Item Trials Ttl Time Avg Time Mean Time StdDev ===\n AddTrade 500 7 ms 14 us 12 us 24 us\n BufferRead 511 1:19.25 0.16 s 621 ns 2.48 s\n BufferWrite 516 511 us 991 ns 482 ns 11 us\n ImportPos Loop 1002 18.62 s 19 ms 77 us 0.51 s\n ImportPosition 2 18.75 s 9.38 s 16.17 s 13.59 s\n Insert 515 4.26 s 8 ms 5 ms 27 ms\n recv 101 18.54 s 0.18 s 2603 ns 1.63 s\n #include <map>\n#include \"x:\\utils\\stlext\\stringext.h\"\n#include <iterator>\n#include <set>\n#include <vector>\n#include <numeric>\n#include \"x:\\utils\\stlext\\algorithmext.h\"\n#include <math.h>\n\n class Timer\n {\n public:\n Timer(const char* name)\n {\n label = std::safe_string(name);\n QueryPerformanceCounter(&startTime);\n }\n\n virtual ~Timer()\n {\n QueryPerformanceCounter(&stopTime);\n __int64 clocks = stopTime.QuadPart-startTime.QuadPart;\n double elapsed = (double)clocks/(double)TimerFreq();\n TimeMap().insert(std::make_pair(label,elapsed));\n };\n\n static std::string Dump(bool ClipboardAlso=true)\n {\n static const std::string loc = \"Timer::Dump\";\n\n if( TimeMap().empty() )\n {\n return \"No trials\\r\\n\";\n }\n\n std::string ret = std::formatstr(\"\\r\\n\\r\\nTimer Precision = %s\\r\\n\\r\\n\", format_elapsed(1.0/(double)TimerFreq()).c_str());\n\n // get a list of keys\n typedef std::set<std::string> keyset;\n keyset keys;\n std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());\n\n size_t maxrows = 0;\n\n typedef std::vector<std::string> strings;\n strings lines;\n\n static const size_t tabWidth = 9;\n\n std::string head = std::formatstr(\"=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===\", tabWidth*2, tabWidth*2, \"Item\", tabWidth, tabWidth, \"Trials\", tabWidth, tabWidth, \"Ttl Time\", tabWidth, tabWidth, \"Avg Time\", tabWidth, tabWidth, \"Mean Time\", tabWidth, tabWidth, \"StdDev\");\n ret += std::formatstr(\"\\r\\n%s\\r\\n\", head.c_str());\n if( ClipboardAlso ) \n lines.push_back(\"Item\\tTrials\\tTtl Time\\tAvg Time\\tMean Time\\tStdDev\\r\\n\");\n // dump the values for each key\n {for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )\n {\n time_type ttl = 0;\n ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));\n size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));\n if( num > maxrows ) \n maxrows = num;\n time_type avg = ttl / num;\n\n // compute mean\n std::vector<time_type> sortedTimes;\n std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));\n std::sort(sortedTimes.begin(), sortedTimes.end());\n size_t mid = (size_t)floor((double)num/2.0);\n double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];\n // compute variance\n double sum = 0.0;\n if( num > 1 )\n {\n for( std::vector<time_type>::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )\n sum += pow(*timeIt-mean,2.0);\n }\n // compute std dev\n double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;\n\n ret += std::formatstr(\" %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\\r\\n\", tabWidth*2, tabWidth*2, key->c_str(), tabWidth, tabWidth, std::formatstr(\"%d\",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str()); \n if( ClipboardAlso )\n lines.push_back(std::formatstr(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\r\\n\", key->c_str(), std::formatstr(\"%d\",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str())); \n\n }\n }\n ret += std::formatstr(\"%s\\r\\n\", std::string(head.length(),'=').c_str());\n\n if( ClipboardAlso )\n {\n // dump header row of data block\n lines.push_back(\"\");\n {\n std::string s;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n s.append(\"\\t\");\n s.append(*key);\n }\n s.append(\"\\r\\n\");\n lines.push_back(s);\n }\n\n // blow out the flat map of time values to a seperate vector of times for each key\n typedef std::map<std::string, std::vector<time_type> > nodematrix;\n nodematrix nodes;\n for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )\n nodes[time->first].push_back(time->second);\n\n // dump each data point\n for( size_t row = 0; row < maxrows; ++row )\n {\n std::string rowDump;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n rowDump.append(\"\\t\");\n if( nodes[*key].size() > row )\n rowDump.append(std::formatstr(\"%f\", nodes[*key][row]));\n }\n rowDump.append(\"\\r\\n\");\n lines.push_back(rowDump);\n }\n\n // dump to the clipboard\n std::string dump;\n for( strings::iterator s = lines.begin(); s != lines.end(); ++s )\n {\n dump.append(*s);\n }\n\n OpenClipboard(0);\n EmptyClipboard();\n HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);\n if( hg != 0 )\n {\n char* buf = (char*)GlobalLock(hg);\n if( buf != 0 )\n {\n std::copy(dump.begin(), dump.end(), buf);\n buf[dump.length()] = 0;\n GlobalUnlock(hg);\n SetClipboardData(CF_TEXT, hg);\n }\n }\n CloseClipboard();\n }\n\n return ret;\n }\n\n static void Reset()\n {\n TimeMap().clear();\n }\n\n static std::string format_elapsed(double d) \n {\n if( d < 0.00000001 )\n {\n // show in ps with 4 digits\n return std::formatstr(\"%0.4f ps\", d * 1000000000000.0);\n }\n if( d < 0.00001 )\n {\n // show in ns\n return std::formatstr(\"%0.0f ns\", d * 1000000000.0);\n }\n if( d < 0.001 )\n {\n // show in us\n return std::formatstr(\"%0.0f us\", d * 1000000.0);\n }\n if( d < 0.1 )\n {\n // show in ms\n return std::formatstr(\"%0.0f ms\", d * 1000.0);\n }\n if( d <= 60.0 )\n {\n // show in seconds\n return std::formatstr(\"%0.2f s\", d);\n }\n if( d < 3600.0 )\n {\n // show in min:sec\n return std::formatstr(\"%01.0f:%02.2f\", floor(d/60.0), fmod(d,60.0));\n }\n // show in h:min:sec\n return std::formatstr(\"%01.0f:%02.0f:%02.2f\", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));\n }\n\n private:\n static __int64 TimerFreq()\n {\n static __int64 freq = 0;\n static bool init = false;\n if( !init )\n {\n LARGE_INTEGER li;\n QueryPerformanceFrequency(&li);\n freq = li.QuadPart;\n init = true;\n }\n return freq;\n }\n LARGE_INTEGER startTime, stopTime;\n std::string label;\n\n typedef std::string key_type;\n typedef double time_type;\n typedef std::multimap<key_type, time_type> Times;\n// static Times times;\n static Times& TimeMap()\n {\n static Times times_;\n return times_;\n }\n\n struct extract_key : public std::unary_function<Times::value_type, key_type>\n {\n std::string operator()(Times::value_type const & r) const\n {\n return r.first;\n }\n };\n\n struct extract_val : public std::unary_function<Times::value_type, time_type>\n {\n time_type operator()(Times::value_type const & r) const\n {\n return r.second;\n }\n };\n struct match_key : public std::unary_function<Times::value_type, bool>\n {\n match_key(key_type const & key_) : key(key_) {};\n bool operator()(Times::value_type const & rhs) const\n {\n return key == rhs.first;\n }\n private:\n match_key& operator=(match_key&) { return * this; }\n const key_type key;\n };\n\n struct accum_key : public std::binary_function<time_type, Times::value_type, time_type>\n {\n accum_key(key_type const & key_) : key(key_), n(0) {};\n time_type operator()(time_type const & v, Times::value_type const & rhs) const\n {\n if( key == rhs.first )\n {\n ++n;\n return rhs.second + v;\n }\n return v;\n }\n private:\n accum_key& operator=(accum_key&) { return * this; }\n const Times::key_type key;\n mutable size_t n;\n };\n };\n namespace std\n{\n /* ---\n\n Formatted Print\n\n template<class C>\n int strprintf(basic_string<C>* pString, const C* pFmt, ...);\n\n template<class C>\n int vstrprintf(basic_string<C>* pString, const C* pFmt, va_list args);\n\n Returns :\n\n # characters printed to output\n\n\n Effects :\n\n Writes formatted data to a string. strprintf() works exactly the same as sprintf(); see your\n documentation for sprintf() for details of peration. vstrprintf() also works the same as sprintf(), \n but instead of accepting a variable paramater list it accepts a va_list argument.\n\n Requires :\n\n pString is a pointer to a basic_string<>\n\n --- */\n\n template<class char_type> int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);\n\n template<> inline int vprintf_generic<char>(char* buffer, size_t bufferSize, const char* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template<> inline int vprintf_generic<wchar_t>(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnwprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template<class Type, class Traits>\n inline int vstringprintf(basic_string<Type,Traits> & outStr, const Type* format, va_list args)\n {\n // prologue\n static const size_t ChunkSize = 1024;\n size_t curBufSize = 0;\n outStr.erase(); \n\n if( !format )\n {\n return 0;\n }\n\n // keep trying to write the string to an ever-increasing buffer until\n // either we get the string written or we run out of memory\n while( bool cont = true )\n {\n // allocate a local buffer\n curBufSize += ChunkSize;\n std::ref_ptr<Type> localBuffer = new Type[curBufSize];\n if( localBuffer.get() == 0 )\n {\n // we ran out of memory -- nice goin'!\n return -1;\n }\n // format output to local buffer\n int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);\n if( -1 == i )\n {\n // the buffer wasn't big enough -- try again\n continue;\n }\n else if( i < 0 )\n {\n // something wierd happened -- bail\n return i;\n }\n // if we get to this point the string was written completely -- stop looping\n outStr.assign(localBuffer.get(),i);\n return i;\n }\n // unreachable code\n return -1;\n };\n\n // provided for backward-compatibility\n template<class Type, class Traits>\n inline int vstrprintf(basic_string<Type,Traits> * outStr, const Type* format, va_list args)\n {\n return vstringprintf(*outStr, format, args);\n }\n\n template<class Char, class Traits>\n inline int stringprintf(std::basic_string<Char, Traits> & outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(outString, format, args);\n va_end(args);\n return retval;\n }\n\n // old function provided for backward-compatibility\n template<class Char, class Traits>\n inline int strprintf(std::basic_string<Char, Traits> * outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(*outString, format, args);\n va_end(args);\n return retval;\n }\n\n /* ---\n\n Inline Formatted Print\n\n string strprintf(const char* Format, ...);\n\n Returns :\n\n Formatted string\n\n\n Effects :\n\n Writes formatted data to a string. formatstr() works the same as sprintf(); see your\n documentation for sprintf() for details of operation. \n\n --- */\n\n template<class Char>\n inline std::basic_string<Char> formatstr(const Char * format, ...)\n {\n std::string outString;\n\n va_list args;\n va_start(args, format);\n vstringprintf(outString, format, args);\n va_end(args);\n return outString;\n }\n};\n /* ---\n\nTransform\n25.2.3\n\n template<class InputIterator, class OutputIterator, class UnaryOperation, class Predicate>\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)\n\n template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)\n\nRequires: \n\n T is of type EqualityComparable (20.1.1) \n op and binary_op have no side effects\n\nEffects :\n\n Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:\n 1: op( *(first1 + (i - result)) \n 2: binary_op( *(first1 + (i - result), *(first2 + (i - result))\n\nReturns :\n\n result + (last1 - first1)\n\nComplexity :\n\n At most last1 - first1 applications of op or binary_op\n\n--- */\n\ntemplate<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>\nOutputIterator transform_if(InputIterator first, \n InputIterator last, \n OutputIterator result, \n UnaryFunction f, \n Predicate pred)\n{\n for (; first != last; ++first)\n {\n if( pred(*first) )\n *result++ = f(*first);\n }\n return result; \n}\n\ntemplate<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>\nOutputIterator transform_if(InputIterator1 first1, \n InputIterator1 last1, \n InputIterator2 first2, \n OutputIterator result, \n BinaryOperation binary_op, \n Predicate pred)\n{\n for (; first1 != last1 ; ++first1, ++first2)\n {\n if( pred(*first1) )\n *result++ = binary_op(*first1,*first2);\n }\n return result;\n}\n" }, { "answer_id": 44489926, "author": "metamorphosis", "author_id": 3454889, "author_profile": "https://Stackoverflow.com/users/3454889", "pm_score": 0, "selected": false, "text": "plf::timer t;\ntimer.start();\n\n// stuff\n\ndouble elapsed = t.get_elapsed_ns(); // Get nanoseconds\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665/" ]
61,320
<p>SVN in Eclipse is spread into two camps. The SVN people have developed a plugin called <a href="http://subclipse.tigris.org/" rel="noreferrer">Subclipse</a>. The Eclipse people have a plugin called <a href="http://www.eclipse.org/subversive/" rel="noreferrer">Subversive</a>. Broadly speaking they both do the same things. What are the advantages and disadvantages of each?</p>
[ { "answer_id": 4215210, "author": "Rahel Lüthy", "author_id": 57448, "author_profile": "https://Stackoverflow.com/users/57448", "pm_score": 2, "selected": false, "text": "bugtraq bugtraq:label BUGID bugtraq:url" }, { "answer_id": 8433757, "author": "Yinch", "author_id": 1088090, "author_profile": "https://Stackoverflow.com/users/1088090", "pm_score": 2, "selected": false, "text": "Subversive" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3408/" ]
61,339
<p>I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how?</p>
[ { "answer_id": 61452, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public override void ItemAdded(SPItemEventProperties properties)\n{\n // Get list item on which the event occurred.\n SPListItem item = properties.ListItem;\n\n // Set the Author Image field to the user's PictureURL if it exists.\n using (SPWeb web = properties.OpenWeb())\n {\n // Author: {C32DB804-FF2D-4656-A38A-B0394BA5C931}\n SPFieldUserValue authorValue = new SPFieldUserValue(properties.OpenWeb(), item[new Guid(\"{C32DB804-FF2D-4656-A38A-B0394BA5C931}\")].ToString());\n\n UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(web.Site));\n UserProfile profile = profileManager.GetUserProfile(authorValue.LookupId);\n UserProfileValueCollection values = profile[PropertyConstants.PictureUrl];\n\n if (values.Count > 0)\n {\n // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}\n SPFieldUrlValue urlValue = new SPFieldUrlValue(values.Value.ToString());\n item[new Guid(\"{37A5CA4C-7621-44d7-BF3B-583F742CE52F}\")] = urlValue.Url;\n }\n }\n\n item.Update();\n\n // News Text: {7F55A8F0-4555-46BC-B24C-222240B862AF}\n //\n\n // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}\n // \n\n // Publish Date: {45E84B8B-E161-46C6-AD51-27A42E4992B5}\n //\n}\n" }, { "answer_id": 61468, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": true, "text": " //get current profile manager\n UserProfileManager objUserProfileManager = new UserProfileManager(PortalContext.Current);\n //get current users profile\n UserProfile profile = objUserProfileManager.GetUserProfile(true);\n //get user image URL\n string imageUrl = (string)profile[PropertyConstants.PictureUrl];\n\n //do something here with imageUrl\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
61,341
<p>I remember back in the day with the old borland DOS compiler you could do something like this:</p> <pre><code>asm { mov ax,ex etc etc... } </code></pre> <p>Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me.</p>
[ { "answer_id": 61344, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n\n\nint main() {\n /* Add 10 and 20 and store result into register %eax */\n __asm__ ( \"movl $10, %eax;\"\n \"movl $20, %ebx;\"\n \"addl %ebx, %eax;\"\n );\n\n /* Subtract 20 from 10 and store result into register %eax */\n __asm__ ( \"movl $10, %eax;\"\n \"movl $20, %ebx;\"\n \"subl %ebx, %eax;\"\n );\n\n /* Multiply 10 and 20 and store result into register %eax */\n __asm__ ( \"movl $10, %eax;\"\n \"movl $20, %ebx;\"\n \"imull %ebx, %eax;\"\n );\n\n return 0 ;\n}\n" }, { "answer_id": 61350, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 7, "selected": true, "text": "__asm__(\"movl %edx, %eax\\n\\t\"\n \"addl $2, %eax\\n\\t\");\n __asm {\n mov eax, edx\n add eax, 2\n}\n" }, { "answer_id": 61745, "author": "Martin Del Vecchio", "author_id": 5397, "author_profile": "https://Stackoverflow.com/users/5397", "pm_score": 4, "selected": false, "text": " asm (\"lock; xaddl %0,%2\" : \"=r\" (result) : \"0\" (1), \"m\" (*atom) : \"memory\");\n" }, { "answer_id": 66843327, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "asm __asm__ fortran asm(\"syscall\");\nfortran(\"Print *,\"J\");\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6062/" ]
61,354
<p>I was just working on fixing up exception handling in a .NET 2.0 app, and I stumbled onto some weird issue with <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx" rel="nofollow noreferrer">Application.ThreadException</a>.</p> <p>What I want is to be able to catch all exceptions from events behind GUI elements (e.g. button_Click, etc.). I then want to filter these exceptions on 'fatality', e.g. with some types of Exceptions the application should keep running and with others it should exit.</p> <p>In another .NET 2.0 app I learned that, by default, only in debug mode the exceptions actually leave an Application.Run or Application.DoEvents call. In release mode this does not happen, and the exceptions have to be 'caught' using the Application.ThreadException event.</p> <p>Now, however, I noticed that <strong>the exception object passed in the ThreadExceptionEventArgs of the Application.ThreadException event is always the innermost exception in the exception chain</strong>. For logging/debugging/design purposes I really want the entire chain of exceptions though. It isn't easy to determine what external system failed for example when you just get to handle a SocketException: when it's wrapped as e.g. a NpgsqlException, then at least you know it's a database problem.</p> <p><strong>So, how to get to the entire chain of exceptions from this event?</strong> Is it even possible or do I need to design my excepion handling in another way?</p> <p>Note that I do -sort of- have a <a href="https://stackoverflow.com/questions/61366/rolling-your-own-message-loop-any-pitfalls">workaround</a> using <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.setunhandledexceptionmode.aspx" rel="nofollow noreferrer">Application.SetUnhandledExceptionMode</a>, but this is far from ideal because I'd have to roll my own message loop.</p> <p>EDIT: to prevent more mistakes, <strong>the GetBaseException() method does NOT do what I want</strong>: it just returns the innermost exception, while the only thing I already have is the innermost exception. I want to get at the outermost exception!</p>
[ { "answer_id": 61647, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": -1, "selected": false, "text": " Public Overridable Function GetBaseException() As Exception\n Dim innerException As Exception = Me.InnerException\n Dim exception2 As Exception = Me\n Do While (Not innerException Is Nothing)\n exception2 = innerException\n innerException = innerException.InnerException\n Loop\n Return exception2\n End Function\n Public Sub LogExceptionChain(ByVal CurrentException As Exception)\n\n Dim innerException As Exception = CurrentException.InnerException\n Dim exception2 As Exception = CurrentException\n\n Debug.Print(exception2.Message) 'Log the Exception\n\n Do While (Not innerException Is Nothing)\n\n exception2 = innerException\n Debug.Print(exception2.Message) 'Log the Exception\n\n 'Move to the next exception\n innerException = innerException.InnerException\n Loop\n\nEnd Sub\n" }, { "answer_id": 308388, "author": "Vincent Van Den Berghe", "author_id": 39259, "author_profile": "https://Stackoverflow.com/users/39259", "pm_score": 1, "selected": false, "text": " Private Shared Sub Test1()\n Try\n Test2()\n Catch ex As Exception\n Application.OnThreadException(New ApplicationException(\"test1\", ex))\n End Try\n End Sub\n\n Private Shared Sub Test2()\n Try\n Test3()\n Catch ex As Exception\n Throw New ApplicationException(\"test2\", ex)\n End Try\n End Sub\n\n Private Shared Sub Test3()\n Throw New ApplicationException(\"blabla\")\n End Sub\n\nPrivate Shared Sub HandleAppException(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)\n...\nEnd Sub\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
61,357
<p>Should I still be using tables anyway?</p> <p>The table code I'd be replacing is:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;Name&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt; &lt;/tr&gt; ... &lt;/table&gt; </code></pre> <p>From what I've been reading I should have something like</p> <pre><code>&lt;label class="name"&gt;Name&lt;/label&gt;&lt;label class="value"&gt;Value&lt;/value&gt;&lt;br /&gt; ... </code></pre> <p>Ideas and links to online samples greatly appreciated. I'm a developer way out of my design depth.</p> <p>EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form.</p>
[ { "answer_id": 61360, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<dl> and <dt> <td>" }, { "answer_id": 61362, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 7, "selected": true, "text": "<dl>\n <dt>Name</dt>\n <dd>Value</dd>\n</dl>\n" }, { "answer_id": 61364, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": -1, "selected": false, "text": ".left {\n float:left;\n padding-right:20px\n}\n <div class=\"left\">\n Name<br/>\n AnotherName\n</div>\n<div>\n Value<br />\n AnotherValue\n</div>\n" }, { "answer_id": 61381, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "<form ... class=\"editing\">\n <div class=\"field\">\n <label>Label</label>\n <span class=\"edit\"><input type=\"text\" value=\"Value\" ... /></span>\n <span class=\"view\">Value</span>\n </div>\n ...\n</form>\n .editing .view, .viewing .edit { display: none }\n.editing .edit, .editing .view { display: inline }\n" }, { "answer_id": 39487947, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 3, "selected": false, "text": "<dl class=\"dl-horizontal\">\n <dt>ID</dt>\n <dd>25</dd>\n <dt>Username</dt>\n <dd>Bob</dd>\n</dl>\n dl-horizontal <dl class=\"row\">\n <dt class=\"col\">ID</dt>\n <dd class=\"col\">25</dd>\n</dl>\n<dl class=\"row\">\n <dt class=\"col\">Username</dt>\n <dd class=\"col\">Bob</dd>\n</dl>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122/" ]
61,366
<p>This question is slightly related to <a href="https://stackoverflow.com/questions/61354/how-to-get-entire-chain-of-exceptions-in-applicationthreadexception-event-handl">this question about exception handling</a>. The workaround I found there consists of rolling my own message loop.</p> <p>So my Main method now looks basically like this:</p> <pre><code>[STAThread] static void Main() { // this is needed so there'll actually an exception be thrown by // Application.Run/Application.DoEvents, instead of the ThreadException // event being raised. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form form = new MainForm(); form.Show(); // the loop is here to keep app running if non-fatal exception is caught. do { try { Application.DoEvents(); Thread.Sleep(100); } catch (Exception ex) { ExceptionHandler.ConsumeException(ex); } } while (!form.IsDisposed); } </code></pre> <p>What I'm wondering though, <strong>is this a safe/decent way to replace the more typical 'Application.Run(new MainForm());'</strong>, whether it's used for exception handling or for whatever else, or should I always stick to using Application.Run?</p> <p>On another app that's in testing now a similar approach is used for both loading (splashscreen) and exception handling, and I don't think it has caused any troubles (yet :-))</p>
[ { "answer_id": 61393, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 2, "selected": false, "text": "Thread.Sleep(100);\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
61,372
<p>I want to write an <code>onClick</code> event which submits a form several times, iterating through selected items in a multi-select field, submitting once for each. </p> <p><strong>How do I code the loop?</strong></p> <p>I'm working in Ruby on Rails and using <code>remote_function()</code> to generate the JavaScript for the ajax call.</p>
[ { "answer_id": 61651, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<%= javascript_include_tag 'prototype' %>\n\n<form id=\"my-form\">\n <input type=\"text\" name=\"username\" />\n\n <select multiple=\"true\" id=\"select-box\">\n <option value=\"1\">First</option>\n <option value=\"2\">Second</option>\n <option value=\"3\">Third</option>\n <option value=\"4\">Fourth</option>\n </select>\n</form>\n\n<script type=\"text/javascript\" language=\"javascript\">\nsubmitFormMultipleTimes = function() {\n $F('select-box').each(function(selectedItemValue){\n new Ajax.Request('/somewhere?val='+selectedItemValue, \n {method: 'POST', postBody: Form.serialize('my-form')});\n });\n}\n</script>\n\n<a href=\"#\" onclick=\"submitFormMultipleTimes(); return false;\">Clicky Clicky</a>\n $F() Ajax.Request POST Form.serialize" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
61,383
<p>My current project is in Rails. Coming from a Symfony (PHP) and Django (Python) background, they both have excellent admin generators. Seems like this is missing in Rails.</p> <p>For those who aren't familiar with Symfony or Django, they both allow you to specify some metadata around your models to automatically (dynamically) generate an admin interface to do the common CRUD operations. You can create an entire Intranet with only a few commands or lines of code. They have a good appearance and are extensible enough for 99% of your admin needs.</p> <p>I've looked for something similar for Rails, but all of the projects either have no activity or they died long ago. Is there anything to generate an intranet/admin site for a rails app other than scaffolding?</p>
[ { "answer_id": 62410, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "./script/generate scaffold_resource MyModel property:type property2:type2\n" }, { "answer_id": 17062194, "author": "Rajarshi Das", "author_id": 2463570, "author_profile": "https://Stackoverflow.com/users/2463570", "pm_score": 0, "selected": false, "text": "active_admin" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884/" ]
61,400
<p>I'm sure most of you are writing lots of automated tests and that you also have run into some common pitfalls when unit testing. </p> <p>My question is do you follow any rules of conduct for writing tests in order to avoid problems in the future? To be more specific: What are the <strong>properties of good unit tests</strong> or how do you write your tests?</p> <p>Language agnostic suggestions are encouraged.</p>
[ { "answer_id": 61441, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "[TestFixture]\npublic class StackTests\n{\n [TestFixture]\n public class EmptyTests\n {\n Stack<int> _stack;\n\n [TestSetup]\n public void TestSetup()\n {\n _stack = new Stack<int>();\n }\n\n [TestMethod]\n [ExpectedException (typeof(Exception))]\n public void PopFails()\n {\n _stack.Pop();\n }\n\n [TestMethod]\n public void IsEmpty()\n {\n Assert(_stack.IsEmpty());\n }\n }\n\n [TestFixture]\n public class PushedOneTests\n {\n Stack<int> _stack;\n\n [TestSetup]\n public void TestSetup()\n {\n _stack = new Stack<int>();\n _stack.Push(7);\n }\n\n // Tests for one item on the stack...\n }\n}\n" }, { "answer_id": 831542, "author": "womp", "author_id": 63756, "author_profile": "https://Stackoverflow.com/users/63756", "pm_score": 5, "selected": false, "text": " - Map_DefaultConstructorShouldCreateEmptyGisMap()\n - ShouldAlwaysDelegateXMLCorrectlyToTheCustomHandlers()\n - Dog_Object_Should_Eat_Homework_Object_When_Hungry()\n Assert.That(x == 2 && y == 2, \"An incorrect number of begin/end element \nprocessing events was raised by the XElementSerializer\");\n /// A layer cannot be constructed with a null gisLayer, as every function \n /// in the Layer class assumes that a valid gisLayer is present.\n [Test]\n public void ShouldNotAllowConstructionWithANullGisLayer()\n {\n }\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
61,401
<p>I know this sounds like a point-whoring question but let me explain where I'm coming from.</p> <p>Out of college I got a job at a PHP shop. I worked there for a year and a half and thought that I had learned all there was to learn about programming.</p> <p>Then I got a job as a one-man internal development shop at a sizable corporation where all the work was in C#. In my commitment to the position I started reading a ton of blogs and books and quickly realized how wrong I was to think I knew everything. I learned about unit testing, dependency injection and decorator patterns, the design principle of loose coupling, the composition over inheritance debate, and so on and on and on - I am still very much absorbing it all. Needless to say my programming style has changed entirely in the last year.</p> <p>Now I find myself picking up a php project doing some coding for a friend's start-up and I feel completely constrained as opposed to programming in C#. It really bothers me that all variables at a class scope have to be referred to by appending '$this->' . It annoys me that none of the IDEs that I've tried have very good intellisense and that my SimpleTest unit tests methods have to start with the word 'test'. It drives me crazy that dynamic typing keeps me from specifying implicitly which parameter type a method expects, and that you have to write a switch statement to do method overloads. I can't stand that you can't have nested namespaces and have to use the :: operator to call the base class's constructor.</p> <p>Now I have no intention of starting a PHP vs C# debate, rather what I mean to say is that I'm sure there are some PHP features that I either don't know about or know about yet fail to use properly. I am set in my C# universe and having trouble seeing outside the glass bowl.</p> <p>So I'm asking, what are your favorite features of PHP? What are things you can do in it that you can't or are more difficult in the .Net languages?</p>
[ { "answer_id": 61403, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 4, "selected": false, "text": "function MyMethod($VarICareAbout, $VarIDontCareAbout = 'yippie') { }\n" }, { "answer_id": 61482, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 7, "selected": false, "text": "interface AllMagicMethods {\n // accessing undefined or invisible (e.g. private) properties\n public function __get($fieldName);\n public function __set($fieldName, $value);\n public function __isset($fieldName);\n public function __unset($fieldName);\n\n // calling undefined or invisible (e.g. private) methods\n public function __call($funcName, $args);\n public static function __callStatic($funcName, $args); // as of PHP 5.3\n\n // on serialize() / unserialize()\n public function __sleep();\n public function __wakeup();\n\n // conversion to string (e.g. with (string) $obj, echo $obj, strlen($obj), ...)\n public function __toString();\n\n // calling the object like a function (e.g. $obj($arg, $arg2))\n public function __invoke($arguments, $...);\n\n // called on var_export()\n public static function __set_state($array);\n}\n () (string) [] foreach count" }, { "answer_id": 61489, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 7, "selected": false, "text": "$fp = fopen(\"xlsfile://tmp/test.xls\", \"wb\");\nif (!is_resource($fp)) { \n die(\"Cannot open excel file\");\n}\n\n$data= array(\n array(\"Name\" => \"Bob Loblaw\", \"Age\" => 50), \n array(\"Name\" => \"Popo Jijo\", \"Age\" => 75), \n array(\"Name\" => \"Tiny Tim\", \"Age\" => 90)\n); \n\nfwrite($fp, serialize($data));\nfclose($fp);\n" }, { "answer_id": 61574, "author": "Jan Gorman", "author_id": 3196, "author_profile": "https://Stackoverflow.com/users/3196", "pm_score": 4, "selected": false, "text": "function foo ( array $param0, stdClass $param1 );\n" }, { "answer_id": 62525, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 6, "selected": false, "text": "$foo = 'bar';\n$bar = 'foobar';\necho $$foo; //This outputs foobar\n\nfunction bar() {\n echo 'Hello world!';\n}\n\nfunction foobar() {\n echo 'What a wonderful world!';\n}\n$foo(); //This outputs Hello world!\n$$foo(); //This outputs What a wonderful world!\n" }, { "answer_id": 62645, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 2, "selected": false, "text": "class Bar\n{\n public function __construct(array $Parameters, Bar $AnotherBar){}\n}\n" }, { "answer_id": 114001, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 6, "selected": false, "text": "extract() function render_template($template_name, $context, $as_string=false)\n{\n extract($context);\n if ($as_string)\n ob_start();\n include TEMPLATE_DIR . '/' . $template_name;\n if ($as_string)\n return ob_get_clean();\n}\n render_template('index.html', array('foo' => 'bar')) $foo \"bar\"" }, { "answer_id": 163857, "author": "Willem", "author_id": 15447, "author_profile": "https://Stackoverflow.com/users/15447", "pm_score": 6, "selected": false, "text": "__autoload() set_include_path() set_include_path(get_include_path() . PATH_SEPARATOR . '../libs/');`\n __autoload() function __autoload($classname) {\n // every class is stored in a file \"libs/classname.class.php\"\n\n // note: temporary alter error_reporting to prevent WARNINGS\n // Do not suppress errors with a @ - syntax errors will fail silently!\n\n include_once($classname . '.class.php');\n}\n" }, { "answer_id": 173907, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 5, "selected": false, "text": "<?php $flag and print \"Blah\" ?>\n" }, { "answer_id": 255623, "author": "Dean Rather", "author_id": 14966, "author_profile": "https://Stackoverflow.com/users/14966", "pm_score": 7, "selected": false, "text": "$person = array();\n$person['name'] = 'bob';\n$person['age'] = 5;\n $person = new stdClass();\n$person->name = 'bob';\n$person->age = 5;\n $string = $person['name'] . ' is ' . $person['age'] . ' years old.';\n// vs\n$string = \"$person->name is $person->age years old.\";\n" }, { "answer_id": 526917, "author": "Michał Tatarynowicz", "author_id": 49564, "author_profile": "https://Stackoverflow.com/users/49564", "pm_score": 6, "selected": false, "text": "or = $page = (int) @$_GET['page'] \n or $page = 1;\n true $record = get_record($id) \n or throw new Exception(\"...\");\n" }, { "answer_id": 551988, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 4, "selected": false, "text": "if (preg_match(\"/cat/\",\"one cat\")) {\n // do something\n}\n import java.util.regex.*;\nPattern p = Pattern.compile(\"cat\");\nMatcher m = p.matcher(\"one cat\")\nif (m.find()) {\n // do something\n}\n" }, { "answer_id": 665660, "author": "Jamol", "author_id": 66611, "author_profile": "https://Stackoverflow.com/users/66611", "pm_score": 5, "selected": false, "text": "function myFunc($param1, $param2 = MY_CONST)\n{\n//code...\n}\n $str = 'hell o World';\necho $str; //outputs: \"hell o World\"\n\n$str[0] = 'H';\necho $str; //outputs: \"Hell o World\"\n\n$str[4] = null;\necho $str; //outputs: \"Hello World\"\n" }, { "answer_id": 794461, "author": "Luc M", "author_id": 14673, "author_profile": "https://Stackoverflow.com/users/14673", "pm_score": 3, "selected": false, "text": "$my_array = array();\n$my_array[] = 'first element';\n$my_array[] = 'second element';\n" }, { "answer_id": 810635, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "class style\n{\n ....\n function set_bg_colour($c)\n {\n $this->{'background-color'} = $c;\n }\n}\n" }, { "answer_id": 886384, "author": "zombat", "author_id": 81205, "author_profile": "https://Stackoverflow.com/users/81205", "pm_score": 6, "selected": false, "text": "$fp = fopen('http://example.com');\n $str = file_get_contents('http://example.com/file');\n $imageInfo = getimagesize('ftp://user:[email protected]/image/name.jpg');\n include() require()" }, { "answer_id": 1023029, "author": "Sam152", "author_id": 59730, "author_profile": "https://Stackoverflow.com/users/59730", "pm_score": 5, "selected": false, "text": "/*\n die('You shall not pass!');\n//*/\n\n\n//*\n die('You shall not pass!');\n//*/\n" }, { "answer_id": 1024891, "author": "dcousineau", "author_id": 20265, "author_profile": "https://Stackoverflow.com/users/20265", "pm_score": 5, "selected": false, "text": "static <?php\nfunction foo($arg1)\n{\n static $cache;\n\n if( !isset($cache[md5($arg1)]) )\n {\n // Do the work here\n $cache[md5($arg1)] = $results;\n }\n\n return $cache[md5($arg1)];\n}\n?>\n static get_all_books_by_id(...) get_all_categories(...) md5(...) sprintf('%u', crc32(...)) spl_object_hash(...)" }, { "answer_id": 1024914, "author": "MSpreij", "author_id": 126584, "author_profile": "https://Stackoverflow.com/users/126584", "pm_score": 5, "selected": false, "text": "// swap values. any number of vars works, obviously \nlist($a, $b) = array($b, $a);\n\n// nested list() calls \"fill\" variables from multidim arrays: \n$arr = array( \n array('aaaa', 'bbb'), \n array('cc', 'd') \n); \nlist(list($a, $b), list($c, $d)) = $arr; \necho \"$a $b $c $d\"; // -> aaaa bbb cc d \n\n// list() values to arrays \nwhile (list($arr1[], $arr2[], $arr3[]) = mysql_fetch_row($res)) { .. } \n// or get columns from a matrix \nforeach($data as $row) list($col_1[], $col_2[], $col_3[]) = $row;\n\n// abusing the ternary operator to set other variables as a side effect: \n$foo = $condition ? 'Yes' . (($bar = 'right') && false) : 'No' . (($bar = 'left') && false); \n// boolean False cast to string for concatenation becomes an empty string ''. \n// you can also use list() but that's so boring ;-) \nlist($foo, $bar) = $condition ? array('Yes', 'right') : array('No', 'left');\n // the strings' \"Complex syntax\" allows for *weird* stuff. \n// given $i = 3, if $custom is true, set $foo to $P['size3'], else to $C['size3']: \n$foo = ${$custom?'P':'C'}['size'.$i]; \n$foo = $custom?$P['size'.$i]:$C['size'.$i]; // does the same, but it's too long ;-) \n// similarly, splitting an array $all_rows into two arrays $data0 and $data1 based \n// on some field 'active' in the sub-arrays: \nforeach ($all_rows as $row) ${'data'.($row['active']?1:0)}[] = $row;\n\n// slight adaption from another answer here, I had to try out what else you could \n// abuse as variable names.. turns out, way too much... \n$string = 'f.> <!-? o+'; \n${$string} = 'asdfasf'; \necho ${$string}; // -> 'asdfasf' \necho $GLOBALS['f.> <!-? o+']; // -> 'asdfasf' \n// (don't do this. srsly.)\n\n${''} = 456; \necho ${''}; // -> 456 \necho $GLOBALS['']; // -> 456 \n// I have no idea. \n // just discovered you can comment the hell out of php:\n$q/* snarf */=/* quux */$_GET/* foo */[/* bar */'q'/* bazz */]/* yadda */;\n class foo {\n function __call($func, $args) {\n eval ($func);\n }\n}\n\n$x = new foo;\n$x->{'foreach(range(1, 10) as $i) {echo $i.\"\\n\";}'}();\n $foo = 'abcde';\n$strlen = 'strlen';\necho \"$foo is {$strlen($foo)} characters long.\"; // \"abcde is 5 characters long.\"\n" }, { "answer_id": 1025143, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 5, "selected": false, "text": "array_merge() // Set the normal defaults.\n$control_defaults = array( 'type' => 'text', 'size' => 30 );\n\n// ... many lines later ...\n\n$control_5 = $control_defaults + array( 'name' => 'surname', 'size' => 40 );\n// This is the same as:\n// $control_5 = array( 'type' => 'text', 'name' => 'surname', 'size' => 40 );\n" }, { "answer_id": 1025183, "author": "noripcord", "author_id": 84824, "author_profile": "https://Stackoverflow.com/users/84824", "pm_score": 0, "selected": false, "text": "//file page_specific_funcs.inc\n\nfunction doOtherThing(){\n\n}\n\nclass MyClass{\n\n}\n\n//end file\n\n//file.php\n\nfunction doSomething(){\n include(\"page_specific_funcs.inc\");\n\n $var = new MyClass(); \n\n}\n//end of file.php\n" }, { "answer_id": 1025634, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "$var = ($_POST['my_checkbox']=='checked') ? TRUE : FALSE;\n $var = !!($_POST['my_checkbox']=='checked');\n" }, { "answer_id": 1026758, "author": "Darren Newton", "author_id": 12799, "author_profile": "https://Stackoverflow.com/users/12799", "pm_score": 6, "selected": false, "text": "for ($i=0; $i < $x; $i++) { \n // code...\n}\n foreach (range(0, 12) as $number) {\n // ...\n}\n foreach (range(date(\"Y\"), date(\"Y\")+20) as $i)\n{\nprint \"\\t<option value=\\\"{$i}\\\">{$i}</option>\\n\";\n}\n" }, { "answer_id": 1027553, "author": "aviv", "author_id": 112601, "author_profile": "https://Stackoverflow.com/users/112601", "pm_score": -1, "selected": false, "text": "function getInt(int $v)\n{\n echo $v;\n}\n\ngetInt(5); // will work\ngetInt('hello'); // will fail\n" }, { "answer_id": 1027577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Class Connection {\n private $dsn;\n private $connection;\n ...\n public __wakeup() {\n $this->connection = ADONewConnection();\n }\n}\n" }, { "answer_id": 1027828, "author": "Eric", "author_id": 119301, "author_profile": "https://Stackoverflow.com/users/119301", "pm_score": 4, "selected": false, "text": "serialize unserialize json_encode json_decode get_class call_user_func_array method_exists func_num_arg func_get_arg set_error_handler set_exception_handler" }, { "answer_id": 1029100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "echo <<<EOM\n <div id=\"someblock\">\n <img src=\"{$file}\" />\n </div>\nEOM;\n" }, { "answer_id": 1029114, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$foo = 'Bob';\necho 'My name is {$foo}'; // Doesn't swap the variable\necho \"My name is {$foo}\"; // Swaps the variable\n" }, { "answer_id": 1029599, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$obj = new ArrayObject(array(\"name\"=>\"bob\", \"email\"=>\"[email protected]\"),2);\n$obj->fullname = \"Bob Example\";\necho $obj[\"fullname\"];\n$obj[\"fullname\"]=\"Bobby Example\";\necho $obj->fullname;\n" }, { "answer_id": 1061640, "author": "Shane H", "author_id": 60247, "author_profile": "https://Stackoverflow.com/users/60247", "pm_score": 4, "selected": false, "text": "function twiterize($text) {\n // Replace @somename with the full twitter handle\n return preg_replace(\"(\\s+)@(\\w)+(\\s+)\", \"http://www.twitter.com/${2}\", $text);\n}\n\nob_start(twiterize);\n ob_start(parseTemplate);\n // ... \n ob_start(twiterize);\n // ...\n ob_end_flush();\n // ... \nob_end_flush();\n" }, { "answer_id": 1092743, "author": "Daan", "author_id": 7922, "author_profile": "https://Stackoverflow.com/users/7922", "pm_score": 2, "selected": false, "text": "if foreach <?= $myVar ?>" }, { "answer_id": 1103508, "author": "TheBrain", "author_id": 130341, "author_profile": "https://Stackoverflow.com/users/130341", "pm_score": 6, "selected": false, "text": "func_get_args() <?php\n\nfunction test() {\n\n $args = func_get_args();\n echo $args[2]; // will print 'd'\n echo $args[1]; // will print 3\n}\n\ntest(1,3,'d',4);\n\n?>\n" }, { "answer_id": 1141481, "author": "RaYell", "author_id": 137467, "author_profile": "https://Stackoverflow.com/users/137467", "pm_score": 3, "selected": false, "text": "$newVar = $ar['foo']['bar'];\necho \"Array value is $newVar\";\n\n$newVar = $obj->foo->bar;\necho \"Object value is $newVar\";\n echo \"Array value is {$ar['foo']['bar']}\";\necho \"Object value is {$obj->foo->bar}\";\n" }, { "answer_id": 1173586, "author": "dburke", "author_id": 72656, "author_profile": "https://Stackoverflow.com/users/72656", "pm_score": 2, "selected": false, "text": "php -a <?php" }, { "answer_id": 1241052, "author": "Philippe Gerber", "author_id": 117260, "author_profile": "https://Stackoverflow.com/users/117260", "pm_score": 7, "selected": false, "text": "// config.php\nreturn array(\n 'db' => array(\n 'host' => 'example.org',\n 'user' => 'usr',\n // ...\n ),\n // ...\n);\n\n// index.php\n$config = include 'config.php';\necho $config['db']['host']; // example.org\n" }, { "answer_id": 1416447, "author": "Kzqai", "author_id": 69993, "author_profile": "https://Stackoverflow.com/users/69993", "pm_score": 1, "selected": false, "text": "function render_title($title){\n return \"<title>$title</title\";\n}\n" }, { "answer_id": 1548737, "author": "Alex L", "author_id": 114446, "author_profile": "https://Stackoverflow.com/users/114446", "pm_score": 3, "selected": false, "text": "$classInfo = new ReflectionClass ('MyClass');\nif ($classInfo->hasMethod($methodName)) \n{\n $cm = $classInfo->getMethod($name); \n $methodResult = $cm->invoke(null);\n}\n" }, { "answer_id": 1697712, "author": "Frank Koehl", "author_id": 38358, "author_profile": "https://Stackoverflow.com/users/38358", "pm_score": 3, "selected": false, "text": "#!/usr/bin/php5\n<?php\n// start coding here\n" }, { "answer_id": 2032550, "author": "Axel Gneiting", "author_id": 5876, "author_profile": "https://Stackoverflow.com/users/5876", "pm_score": 2, "selected": false, "text": "ArrayAccess Iterator __call updateByName(\"foo\")" }, { "answer_id": 2161431, "author": "Talvi Watia", "author_id": 215170, "author_profile": "https://Stackoverflow.com/users/215170", "pm_score": 1, "selected": false, "text": "<?\n// file unit1.php\n$this_code='does something.';\n?>\n\n<?\n// file unit2.php\n$this_code='does something else. it could be a PHP class object!';\n?>\n\n<?\n// file unit3.php\n$this_code='does something else. it could be your master include file';\nrequire_once('unit2.php');\ninclude('unit1.php');\n?>\n\n<?\n// file main.php\ninclude('unit1.php');\nrequire_once('unit2.php');\nrequire_once('unit3.php');\n?>\n" }, { "answer_id": 3089775, "author": "bob-the-destroyer", "author_id": 352583, "author_profile": "https://Stackoverflow.com/users/352583", "pm_score": 3, "selected": false, "text": "included include" }, { "answer_id": 3111088, "author": "manixrock", "author_id": 93691, "author_profile": "https://Stackoverflow.com/users/93691", "pm_score": 4, "selected": false, "text": "break N; goto for (int i=0; i<100; i++) {\n foreach ($myarr as $item) {\n if ($item['name'] == 'abort')\n break 2;\n }\n}\n" }, { "answer_id": 3135918, "author": "fixo2020 ", "author_id": 347194, "author_profile": "https://Stackoverflow.com/users/347194", "pm_score": -1, "selected": false, "text": "$check = \"HELLO\";\n\nswitch ($check) {\n case (eregi('HI', $check)):\n echo \"Write HI!\";\n case (eregi('HELLO', $check)):\n echo \"Write HELLO!\";\n case (eregi('OTHER', $check)):\n echo \"Write OTHER!\";\n}\n" }, { "answer_id": 3136088, "author": "Codler", "author_id": 304894, "author_profile": "https://Stackoverflow.com/users/304894", "pm_score": 2, "selected": false, "text": "function sort_by_field($field, & $data) {\n $sort_func = create_function('$a,$b', 'if ($a[\"' . $field . '\"] == $b[\"' . $field . '\"]) {return 0;} \n return ($a[\"' . $field . '\"] < $b[\"' . $field . '\"]) ? -1 : 1;');\n\n uasort($data, $sort_func);\n}\n" }, { "answer_id": 3136831, "author": "Xeoncross", "author_id": 99923, "author_profile": "https://Stackoverflow.com/users/99923", "pm_score": 3, "selected": false, "text": "<?php\n\nTRUE AND print 'Hello';\nFALSE OR print 'World';\n\n// Prints \"Hello World\";\n\n// Complex example...\nUser::logged_in() or die('Not allowed');\nUser::is_admin() AND print 'Admin Area';\n <?php defined('YOURCONSTANT') or die('Not allowed');\n\n///rest of your code\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
61,405
<p>I'm about to start on a large Qt application, which is made up of smaller components (groups of classes that work together). For example, there might be a dialog that is used in the project, but should be developed on its own before being integrated into the project. Instead of working on it in another folder somewhere and then copying it into the main project folder, can I create a sub-folder which is dedicated to that dialog, and then somehow incorporate it into the main project?</p>
[ { "answer_id": 62009, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 6, "selected": true, "text": "/MyWholeApp\n /MyWholeApp/DummyDlg/\n # Input\nFORMS += dummydlg.ui\nHEADERS += dummydlg.h\nSOURCES += dummydlg.cpp\n TEMPLATE = app\nDEPENDPATH += .\nINCLUDEPATH += .\n\ninclude(DummyDlg.pri)\n\n# Input\nSOURCES += main.cpp\n #include <QApplication>\n#include \"dummydlg.h\"\n\nint main(int argc, char* argv[])\n{\n QApplication MyApp(argc, argv);\n\n DummyDlg MyDlg;\n MyDlg.show();\n return MyApp.exec();\n}\n TEMPLATE = app\nDEPENDPATH += . DummyDlg\nINCLUDEPATH += . DummyDlg\n\ninclude(DummyDlg/DummyDlg.pri)\n\n# Input\nFORMS += OtherDlg.ui\nHEADERS += OtherDlg.h\nSOURCES += OtherDlg.cpp WholeApp.cpp\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
61,418
<p>I have a function that gives me the following warning:</p> <blockquote> <p>[DCC Warning] filename.pas(6939): W1035 Return value of function 'function' might be undefined</p> </blockquote> <p>The function, however, is clean, small, and does have a known, expected, return value. The first statement in the function is:</p> <pre><code>Result := ''; </code></pre> <p>and there is no local variable or parameter called <code>Result</code> either.</p> <p>Is there any kind of pragma-like directive I can surround this method with to remove this warning? This is Delphi 2007.</p> <p>Unfortunately, the help system on this Delphi installation is not working, therefore i can't pop up the help for that warning right now.</p> <p>Anyone know off the top of their head what i can do?</p>
[ { "answer_id": 61426, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "{$WARN NO_RETVAL OFF}\nfunction func(...): string;\nbegin\n ...\nend;\n{$WARN NO_RETVAL ON}\n" }, { "answer_id": 2906623, "author": "Abelevich", "author_id": 11391, "author_profile": "https://Stackoverflow.com/users/11391", "pm_score": 1, "selected": false, "text": "program TestCompilerProblems;\n\nprocedure Proc;\nvar\n a01, a02, a03, a04, a05, a06, a07, a08, a09, a10,\n a11, a12, a13, a14, a15, a16, a17, a18, a19, a20,\n a21, a22, a23, a24, a25, a26, a27, a28, a29, a30,\n a31, a32, a33, a34, a35, a36, a37, a38, a39, a40: Integer;\nbegin\nend;\n\nbegin\n Proc;\nend.\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
61,421
<p>I'm making an example for someone who hasn't yet realized that controls like <code>ListBox</code> don't have to contain strings; he had been storing formatted strings and jumping through complicated parsing hoops to get the data back out of the <code>ListBox</code> and I'd like to show him there's a better way.</p> <p>I noticed that if I have an object stored in the <code>ListBox</code> then update a value that affects <code>ToString</code>, the <code>ListBox</code> does not update itself. I've tried calling <code>Refresh</code> and <code>Update</code> on the control, but neither works. Here's the code of the example I'm using, it requires you to drag a listbox and a button onto the form:</p> <pre><code>Public Class Form1 Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) MyBase.OnLoad(e) For i As Integer = 1 To 3 Dim tempInfo As New NumberInfo() tempInfo.Count = i tempInfo.Number = i * 100 ListBox1.Items.Add(tempInfo) Next End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click For Each objItem As Object In ListBox1.Items Dim info As NumberInfo = DirectCast(objItem, NumberInfo) info.Count += 1 Next End Sub End Class Public Class NumberInfo Public Count As Integer Public Number As Integer Public Overrides Function ToString() As String Return String.Format("{0}, {1}", Count, Number) End Function End Class</code></pre> <p>I thought that perhaps the problem was using fields and tried implementing <em>INotifyPropertyChanged</em>, but this had no effect. (The reason I'm using fields is because it's an example and I don't feel like adding a few dozen lines that have nothing to do with the topic I'm demonstrating.)</p> <p>Honestly I've never tried updating items in place like this before; in the past I've always been adding/removing items, not editing them. So I've never noticed that I don't know how to make this work.</p> <p>So what am I missing?</p>
[ { "answer_id": 61425, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "Public Class Form1\n\n Private datasource As New List(Of NumberInfo)\n Private bindingSource As New BindingSource\n\n Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)\n MyBase.OnLoad(e)\n\n For i As Integer = 1 To 3\n Dim tempInfo As New NumberInfo()\n tempInfo.Count = i\n tempInfo.Number = i * 100\n datasource.Add(tempInfo)\n Next\n bindingSource.DataSource = datasource\n ListBox1.DataSource = bindingSource\n End Sub\n\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n For Each objItem As Object In datasource\n Dim info As NumberInfo = DirectCast(objItem, NumberInfo)\n info.Count += 1\n Next\n bindingSource.ResetBindings(False)\n End Sub\nEnd Class\n\nPublic Class NumberInfo\n\n Public Count As Integer\n Public Number As Integer\n\n Public Overrides Function ToString() As String\n Return String.Format(\"{0}, {1}\", Count, Number)\n End Function\nEnd Class\n" }, { "answer_id": 61463, "author": "zeemz", "author_id": 6351, "author_profile": "https://Stackoverflow.com/users/6351", "pm_score": -1, "selected": false, "text": "listbox.bind()" }, { "answer_id": 61711, "author": "Ant", "author_id": 3709, "author_profile": "https://Stackoverflow.com/users/3709", "pm_score": 2, "selected": false, "text": "public class ListBox2 : ListBox {\n public void RefreshItem2(int index) {\n RefreshItem(index);\n }\n}\n" }, { "answer_id": 61719, "author": "Brad Bruce", "author_id": 5008, "author_profile": "https://Stackoverflow.com/users/5008", "pm_score": 5, "selected": false, "text": "public class RefreshingListBox : ListBox\n{\n public new void RefreshItem(int index)\n {\n base.RefreshItem(index);\n }\n\n public new void RefreshItems()\n {\n base.RefreshItems();\n }\n}\n" }, { "answer_id": 930356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if (objLstTypes.SelectedItem != null)\n{\n PublisherTypeDescriptor objType = (PublisherTypeDescriptor)objLstTypes.SelectedItem;\n objLstTypes.Items.Remove(objType);\n objLstTypes.Items.Add(objType);\n objLstTypes.SelectedItem = objType;\n}\n" }, { "answer_id": 2135255, "author": "geno", "author_id": 258739, "author_profile": "https://Stackoverflow.com/users/258739", "pm_score": 6, "selected": true, "text": "using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace TestBindingList\n{\n public class Employee\n {\n public string Name { get; set; }\n public int Id { get; set; }\n }\n\n public partial class Form1 : Form\n {\n private BindingList<Employee> _employees;\n\n private ListBox lstEmployees;\n private TextBox txtId;\n private TextBox txtName;\n private Button btnRemove;\n\n public Form1()\n {\n InitializeComponent();\n\n FlowLayoutPanel layout = new FlowLayoutPanel();\n layout.Dock = DockStyle.Fill;\n Controls.Add(layout);\n\n lstEmployees = new ListBox();\n layout.Controls.Add(lstEmployees);\n\n txtId = new TextBox();\n layout.Controls.Add(txtId);\n\n txtName = new TextBox();\n layout.Controls.Add(txtName);\n\n btnRemove = new Button();\n btnRemove.Click += btnRemove_Click;\n btnRemove.Text = \"Remove\";\n layout.Controls.Add(btnRemove);\n\n Load+=new EventHandler(Form1_Load);\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n _employees = new BindingList<Employee>();\n for (int i = 0; i < 10; i++)\n {\n _employees.Add(new Employee() { Id = i, Name = \"Employee \" + i.ToString() }); \n }\n\n lstEmployees.DisplayMember = \"Name\";\n lstEmployees.DataSource = _employees;\n\n txtId.DataBindings.Add(\"Text\", _employees, \"Id\");\n txtName.DataBindings.Add(\"Text\", _employees, \"Name\");\n }\n\n private void btnRemove_Click(object sender, EventArgs e)\n {\n Employee selectedEmployee = (Employee)lstEmployees.SelectedItem;\n if (selectedEmployee != null)\n {\n _employees.Remove(selectedEmployee);\n }\n }\n }\n}\n" }, { "answer_id": 4285934, "author": "Elton M", "author_id": 521450, "author_profile": "https://Stackoverflow.com/users/521450", "pm_score": 5, "selected": false, "text": "lstBox.Items[lstBox.SelectedIndex] = lstBox.SelectedItem;\n" }, { "answer_id": 4631419, "author": "Jon", "author_id": 567625, "author_profile": "https://Stackoverflow.com/users/567625", "pm_score": 4, "selected": false, "text": "typeof(ListBox).InvokeMember(\"RefreshItems\", \n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,\n null, myListBox, new object[] { });\n" }, { "answer_id": 29008084, "author": "JTIM", "author_id": 2076775, "author_profile": "https://Stackoverflow.com/users/2076775", "pm_score": 0, "selected": false, "text": "private void listBox1_DrawItem(object sender, DrawItemEventArgs e)\n{\n e.DrawBackground();\n e.DrawFocusRectangle();\n\n Sensor toBeDrawn = (listBox1.Items[e.Index] as Sensor);\n e.Graphics.FillRectangle(new SolidBrush(toBeDrawn.ItemColor), e.Bounds);\n e.Graphics.DrawString(toBeDrawn.sensorName, new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold), new SolidBrush(Color.White),e.Bounds);\n}\n Color int temp = listBoxName.SelectedIndex;\nlistBoxName.SelectedIndex = -1;\nlistBoxName.SelectedIndex = temp;\n Color" }, { "answer_id": 71672910, "author": "Daniel Lidström", "author_id": 286406, "author_profile": "https://Stackoverflow.com/users/286406", "pm_score": 0, "selected": false, "text": "private void CheckBox_Click(object sender, EventArgs e)\n{\n // some kind of hack to make the ListBox refresh\n int currentPosition = bindingSource.Position;\n bindingSource.Position += 1;\n bindingSource.Position -= 1;\n bindingSource.Position = currentPosition;\n}\n" }, { "answer_id": 71919054, "author": "John G", "author_id": 12492467, "author_profile": "https://Stackoverflow.com/users/12492467", "pm_score": 0, "selected": false, "text": "Dim i = LstBox.SelectedIndex\nLstBox.Items(i) = anObject\nLstBox.Sorted = True\n" }, { "answer_id": 72072608, "author": "purple_2022", "author_id": 13008103, "author_profile": "https://Stackoverflow.com/users/13008103", "pm_score": 0, "selected": false, "text": "Public Class Form1\n\nDim tempInfo As New NumberInfo()\n\nPrivate Sub Form1_Load() Handles Me.Load\n For i As Integer = 1 To 3\n tempInfo.Count = i\n tempInfo.Number = i * 100\n ListBox1.Items.Add(tempInfo)\n Next\nEnd Sub\n\nPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n Dim info As NumberInfo = tempInfo\n Dim obj As New Object\n info.Count += 1\n info.Number = info.Count * 100\n obj = info\n ListBox1.Items.Add(obj)\n ListBox1.Items.RemoveAt(0)\nEnd Sub\nEnd Class\n\nPublic Class NumberInfo\nPublic Count As Integer\nPublic Number As Integer\n Public Overrides Function ToString() As String\n Return String.Format(\"{0}, {1}\", Count, Number)\n End Function\nEnd Class\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
61,443
<p>I have a counter in hardware that I can observe for timing considerations. It counts miliseconds and is stored in a 16 bit unsigned value. How do I safely check if a timer value has passed a certain time and safely handle the inevitable rollover:</p> <pre><code>//this is a bit contrived, but it illustrates what I'm trying to do const uint16_t print_interval = 5000; // milliseconds static uint16_t last_print_time; if(ms_timer() - last_print_time &gt; print_interval) { printf("Fault!\n"); last_print_time = ms_timer(); } </code></pre> <p>This code will fail when ms_timer overflows to 0.</p>
[ { "answer_id": 61461, "author": "ReaperUnreal", "author_id": 4218, "author_profile": "https://Stackoverflow.com/users/4218", "pm_score": 1, "selected": false, "text": "const int32 print_interval = 5000;\nstatic int32 last_print_time; // I'm assuming this gets initialized elsewhere\n\nint32 delta = ((int32)ms_timer()) - last_print_time; //allow a negative interval\nwhile(delta < 0) delta += 65536; // move the difference back into range\nif(delta < print_interval)\n{\n printf(\"Fault!\\n\");\n last_print_time = ms_timer();\n}\n" }, { "answer_id": 61466, "author": "JeffV", "author_id": 445087, "author_profile": "https://Stackoverflow.com/users/445087", "pm_score": 1, "selected": false, "text": "const uint16_t print_interval = 5000; // milliseconds\nstatic uint16_t last_print_time; \n\nint next_print_time = (last_print_time + print_interval);\n\nif((int16_t) (x - next_print_time) >= 0)\n{\n printf(\"Fault!\\n\");\n last_print_time = x;\n}\n" }, { "answer_id": 61572, "author": "smh", "author_id": 1077, "author_profile": "https://Stackoverflow.com/users/1077", "pm_score": 4, "selected": false, "text": "ms_timer() uint16_t t1 = 0xFFF0;\nuint16_t t2 = 0x0010;\nuint16_t dt = t2 - t1;\n dt 0x20" }, { "answer_id": 164182, "author": "Steve Karg", "author_id": 9016, "author_profile": "https://Stackoverflow.com/users/9016", "pm_score": 0, "selected": false, "text": "void timer_milliseconds_reset(unsigned index);\nbool timer_milliseconds_elapsed(unsigned index, unsigned long value);\n #define TIMER_PRINT 0\n#define TIMER_LED 1\n#define MAX_MILLISECOND_TIMERS 2\n /* variable counts interrupts */\nstatic volatile unsigned long Millisecond_Counter[MAX_MILLISECOND_TIMERS];\nbool timer_milliseconds_elapsed(\n unsigned index,\n unsigned long value)\n{\n if (index < MAX_MILLISECOND_TIMERS) {\n return (Millisecond_Counter[index] >= value);\n }\n return false;\n}\n\nvoid timer_milliseconds_reset(\n unsigned index)\n{\n if (index < MAX_MILLISECOND_TIMERS) {\n Millisecond_Counter[index] = 0;\n }\n}\n //this is a bit contrived, but it illustrates what I'm trying to do\nconst uint16_t print_interval = 5000; // milliseconds\n\nif (timer_milliseconds_elapsed(TIMER_PRINT, print_interval)) \n{\n printf(\"Fault!\\n\");\n timer_milliseconds_reset(TIMER_PRINT);\n}\n" }, { "answer_id": 2976575, "author": "bobc", "author_id": 358705, "author_profile": "https://Stackoverflow.com/users/358705", "pm_score": 2, "selected": false, "text": "/* ========================================================================== */\n/* timers.c */\n/* */\n/* Description: Demonstrate unsigned vs signed timers */\n/* ========================================================================== */\n\n#include <stdio.h>\n#include <limits.h>\n\nint timer;\n\nint HW_DIGCTL_MICROSECONDS_RD()\n{\n printf (\"timer %x\\n\", timer);\n return timer++;\n}\n\n// delay up to UINT_MAX\n// this fails when start near UINT_MAX\nvoid delay_us (unsigned int us)\n{\n unsigned int start = HW_DIGCTL_MICROSECONDS_RD();\n\n while (start + us > HW_DIGCTL_MICROSECONDS_RD()) \n ;\n}\n\n// works correctly for delay from 0 to INT_MAX\nvoid sdelay_us (int us)\n{\n int start = HW_DIGCTL_MICROSECONDS_RD();\n\n while (HW_DIGCTL_MICROSECONDS_RD() - start < us) \n ;\n}\n\nint main()\n{\n printf (\"UINT_MAX = %x\\n\", UINT_MAX);\n printf (\"INT_MAX = %x\\n\\n\", INT_MAX);\n\n printf (\"unsigned, no wrap\\n\\n\");\n timer = 0;\n delay_us (10);\n\n printf (\"\\nunsigned, wrap\\n\\n\");\n timer = UINT_MAX - 8;\n delay_us (10);\n\n printf (\"\\nsigned, no wrap\\n\\n\");\n timer = 0;\n sdelay_us (10);\n\n printf (\"\\nsigned, wrap\\n\\n\");\n timer = INT_MAX - 8;\n sdelay_us (10);\n\n}\n bob@hedgehog:~/work2/test$ ./timers|more\nUINT_MAX = ffffffff\nINT_MAX = 7fffffff\n\nunsigned, no wrap\n\ntimer 0\ntimer 1\ntimer 2\ntimer 3\ntimer 4\ntimer 5\ntimer 6\ntimer 7\ntimer 8\ntimer 9\ntimer a\n\nunsigned, wrap\n\ntimer fffffff7\ntimer fffffff8\n\nsigned, no wrap\n\ntimer 0\ntimer 1\ntimer 2\ntimer 3\ntimer 4\ntimer 5\ntimer 6\ntimer 7\ntimer 8\ntimer 9\ntimer a\n\nsigned, wrap\n\ntimer 7ffffff7\ntimer 7ffffff8\ntimer 7ffffff9\ntimer 7ffffffa\ntimer 7ffffffb\ntimer 7ffffffc\ntimer 7ffffffd\ntimer 7ffffffe\ntimer 7fffffff\ntimer 80000000\ntimer 80000001\nbob@hedgehog:~/work2/test$ \n" }, { "answer_id": 11911902, "author": "Jeff", "author_id": 877375, "author_profile": "https://Stackoverflow.com/users/877375", "pm_score": -1, "selected": false, "text": "#define LIMIT 10 // Any value less then ULONG_MAX\nulong t1 = tick of last event;\nulong t2 = current tick;\n\n// This code needs to execute every tick\nif ( t1 > t2 ){\n if ((ULONG_MAX-t1+t2+1)>=LIMIT){\n do something\n }\n} else {\nif ( t2 - t1 >= LIMT ){\n do something\n}\n" }, { "answer_id": 45852411, "author": "Hill", "author_id": 3239341, "author_profile": "https://Stackoverflow.com/users/3239341", "pm_score": 2, "selected": false, "text": "uint32_t uint16_t 0xFFFFFFFF 0xFFFF uint16_t get_diff_tick(uint16_t test_tick, uint16_t prev_tick)\n{\n if (test_tick < prev_tick)\n {\n // time rollover(overflow)\n return (0xFFFF - prev_tick) + 1 + test_tick;\n }\n else\n {\n return test_tick - prev_tick;\n }\n}\n\n/* your code will be.. */\nuint16_t cur_tick = ms_timer();\nif(get_diff_tick(cur_tick, last_print_time) > print_interval)\n{\n printf(\"Fault!\\n\");\n last_print_time = cur_tick;\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
61,446
<p>Particularly, what is the best snippets package out there?</p> <p>Features:</p> <ul> <li>easy to define new snippets (plain text, custom input with defaults)</li> <li>simple navigation between predefined positions in the snippet</li> <li>multiple insertion of the same custom input</li> <li>accepts currently selected text as a custom input</li> <li><em>cross-platform</em> (Windows, Linux)</li> <li>dynamically evaluated expressions (embedded code) written in a concise programming language (Perl, Python, Ruby are preferred)</li> <li>nicely coexists with others packages in Emacs</li> </ul> <p>Example of code template, a simple <code>for</code> loop in C:</p> <pre><code>for (int i = 0; i &lt; %N%; ++i) { _ } </code></pre> <p>It is a lot of typing for such common code. I want to invoke a code template or snippet which inserts that boilerplate code for me. Additionally it stops (on TAB or other keystroke) at <code>%N%</code> (my input replaces it) and final position of the cursor is <code>_</code>. </p>
[ { "answer_id": 61447, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": true, "text": "hippie-expand .emacs YASnippet" }, { "answer_id": 18829042, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 2, "selected": false, "text": "Semantic CEDET" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
61,449
<p>I've just created a new Windows XP VM on my Mac using VMware Fusion. The VM is using NAT to share the host's internet connection.</p> <p>How do I access a Rails application, which is accessible on the Mac itself using <code>http://localhost:3000</code>?</p>
[ { "answer_id": 61455, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 8, "selected": true, "text": "ipconfig" }, { "answer_id": 191707, "author": "Richard Poirier", "author_id": 26842, "author_profile": "https://Stackoverflow.com/users/26842", "pm_score": 3, "selected": false, "text": "<gateway-ip <gateway-ip" }, { "answer_id": 2094910, "author": "J. Perkins", "author_id": 93921, "author_profile": "https://Stackoverflow.com/users/93921", "pm_score": 4, "selected": false, "text": "192.168.78.1 myrubyapp\n" }, { "answer_id": 6688618, "author": "Jess Telford", "author_id": 473961, "author_profile": "https://Stackoverflow.com/users/473961", "pm_score": 3, "selected": false, "text": "[default-gateway-IP] www.example.com\n[default-gateway-IP] example.com\n http://www.example.com http://example.com" }, { "answer_id": 9828343, "author": "Dennis Plucinik", "author_id": 184302, "author_profile": "https://Stackoverflow.com/users/184302", "pm_score": 3, "selected": false, "text": "<gateway-ip> yourserver.local 127.0.0.1 yourserver.local" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ]
61,451
<p>Does Django have any template tags to generate common HTML markup? For example, I know that I can get a url using</p> <pre><code>{% url mapper.views.foo %} </code></pre> <p>But that only gives me the URL and not the HTML code to create the link. Does Django have anything similar to Rails' link_to helper? I found <a href="http://code.google.com/p/django-helpers/" rel="noreferrer">django-helpers</a> but since this is a common thing I thought Django would have something built-in.</p>
[ { "answer_id": 71598, "author": "Ali", "author_id": 11895, "author_profile": "https://Stackoverflow.com/users/11895", "pm_score": -1, "selected": false, "text": "<a href=\"{% url mapper.views.foo %}\">foo</a>" }, { "answer_id": 82175, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 0, "selected": false, "text": "p img a div span" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
61,456
<p>After trying to avoid JavaScript for years, Iv started using Query for <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="nofollow noreferrer">validation</a> in MVC asp.net, as there does not seem to be an official way of doing validation, Iv been surprised how good jQuery is. </p> <p>Firstly is there a way to get intellisense working for jQuery and its validation plugin, so that i don have to learn the api?</p> <p>Secondly how do I create a validation summary for this, it currently appends the error to the right of the text box.:</p> <pre><code>&lt;script type="text/javascript"&gt; $().ready(function() { $("#CreateLog").validate({ rules: { UserName: { required: true, minLength: 2, } }, messages: { UserName: { required: "Please enter a username", minLength: "Your username must consist of at least 2 characters", } } }); }); &lt;/script&gt; &lt;form id="CreateLog" action="Create" method="post" /&gt; &lt;label&gt;UserName&lt;/label&gt;&lt;br /&gt; &lt;%=Html.TextBox("UserName")%&gt; &lt;br /&gt; &lt;div class="error"&gt; &lt;/div&gt; &lt;input type=submit value=Save /&gt; &lt;/form&gt; </code></pre> <p>I tried adding this to the script:</p> <pre><code> errorLabelContainer: $("#CreateLog div.error") </code></pre> <p>and this to the html:</p> <pre><code> &lt;div class="error"&gt; &lt;/div&gt; </code></pre> <p>But this didn't work.</p>
[ { "answer_id": 66527, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 5, "selected": true, "text": "display:none; $().ready(function() {\n $(\"#CreateLog\").validate({\n errorLabelContainer: $(\"ul\", $('div.error-container')),\n wrapper: 'li',\n rules: { \n UserName: {\n required: true,\n minLength: 2,\n\n }\n },\n messages: {\n UserName: {\n required: \"Please enter a username\",\n minLength: \"Your username must consist of at least 2 characters\"\n }\n }\n });\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"error-container\">\n <ul></ul>\n</div>\n\n<form id=\"CreateLog\" action=\"Create\" method=\"post\" /> \n <label>UserName</label><br />\n <%=Html.TextBox(\"UserName\")%> \n <br /> \n <input type=submit value=Save />\n</form>" }, { "answer_id": 298664, "author": "Tomas Aschan", "author_id": 38055, "author_profile": "https://Stackoverflow.com/users/38055", "pm_score": 1, "selected": false, "text": "/// <reference path=\"[insert path to script file here]\" />\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
61,480
<p>In the past we declared properties like this:</p> <pre><code>public class MyClass { private int _age; public int Age { get{ return _age; } set{ _age = value; } } } </code></pre> <p>Now we can do:</p> <pre><code>public class MyClass { public int Age {get; set;} } </code></pre> <p>My question is, how can I access the private variable that is created automatically using this notation? </p> <p>I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?</p>
[ { "answer_id": 61493, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": false, "text": "[CompilerGenerated]\nprivate int <Age>k_BackingField;\n\npublic int Age\n{\n [CompilerGenerated]\n get\n {\n return this.<Age>k_BackingField;\n }\n [CompilerGenerated]\n set\n {\n this.<Age>k_BackingField = value;\n }\n" }, { "answer_id": 61494, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 5, "selected": false, "text": "private int _age public class TempMessage {\n public int FromID { get; set; }\n public int ToID { get; set; }\n public string Message { get; set; }\n}\n" }, { "answer_id": 61503, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 7, "selected": false, "text": "public class MyClass\n{\n public int Age {get; private set;} \n}" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
61,486
<p>I need to figure out what div is visible out of four possible divs using jQuery. Only one of those div's will be visible at any given time.</p> <p>This is what I have that works so far:</p> <pre><code>$("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id"); </code></pre> <p>Is there a way to refactor this? Is there an easier way to figure this out?</p>
[ { "answer_id": 61500, "author": "Gilean", "author_id": 6305, "author_profile": "https://Stackoverflow.com/users/6305", "pm_score": 5, "selected": true, "text": "$(\"div.myClass:visible\").attr(\"id\");\n" }, { "answer_id": 64390, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<div> id=\"foo\" $(\"#foo > div:visible\").attr(\"id\")" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ]
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p>
[ { "answer_id": 61522, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 6, "selected": false, "text": "dir __str__ __dict__ >>> class Foo(object):\n... bar = 'hello'\n... baz = 'world'\n...\n>>> f = Foo()\n>>> [name for name in dir(f) if not name.startswith('__')]\n[ 'bar', 'baz' ]\n>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__')) \n{ 'bar': 'hello', 'baz': 'world' }\n props import inspect\n\ndef props(obj):\n pr = {}\n for name in dir(obj):\n value = getattr(obj, name)\n if not name.startswith('__') and not inspect.ismethod(value):\n pr[name] = value\n return pr\n" }, { "answer_id": 61551, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 5, "selected": false, "text": "dict((key, value) for key, value in f.__dict__.iteritems() \n if not callable(value) and not key.startswith('__'))\n" }, { "answer_id": 62680, "author": "user6868", "author_id": 6868, "author_profile": "https://Stackoverflow.com/users/6868", "pm_score": 10, "selected": true, "text": "class Foo(object):\n ...\n __dict__ __dict__ >>> class A(object):\n... def __init__(self):\n... self.b = 1\n... self.c = 2\n... def do_nothing(self):\n... pass\n...\n>>> a = A()\n>>> a.__dict__\n{'c': 2, 'b': 1}\n vars >>> vars(a)\n{'c': 2, 'b': 1}\n dict getattr setattr class Foo(dict):\n def __init__(self):\n pass\n def __getattr__(self, attr):\n return self[attr]\n\n # etc...\n" }, { "answer_id": 63635, "author": "indentation", "author_id": 7706, "author_profile": "https://Stackoverflow.com/users/7706", "pm_score": 4, "selected": false, "text": "__dict__ class c(object):\n x = 3\na = c()\n" }, { "answer_id": 17470565, "author": "Score_Under", "author_id": 1091693, "author_profile": "https://Stackoverflow.com/users/1091693", "pm_score": 3, "selected": false, "text": "def props(x):\n return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))\n" }, { "answer_id": 23937693, "author": "radtek", "author_id": 2023392, "author_profile": "https://Stackoverflow.com/users/2023392", "pm_score": 3, "selected": false, "text": "class A(object):\n def __init__(self):\n self.b = 1\n self.c = 2\n def __getitem__(self, item):\n return self.__dict__[item]\n\n# Usage: \na = A()\na.__getitem__('b') # Outputs 1\na.__dict__ # Outputs {'c': 2, 'b': 1}\nvars(a) # Outputs {'c': 2, 'b': 1}\n" }, { "answer_id": 29333136, "author": "Seaux", "author_id": 263175, "author_profile": "https://Stackoverflow.com/users/263175", "pm_score": 5, "selected": false, "text": "dict(obj) class A(object):\n d = '4'\n e = '5'\n f = '6'\n\n def __init__(self):\n self.a = '1'\n self.b = '2'\n self.c = '3'\n\n def __iter__(self):\n # first start by grabbing the Class items\n iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__')\n\n # then update the class items with the instance items\n iters.update(self.__dict__)\n\n # now 'yield' through the items\n for x,y in iters.items():\n yield x,y\n\na = A()\nprint(dict(a)) \n# prints \"{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}\"\n __iter__ dict update __dict__ @iterable def iterable(cls):\n def iterfn(self):\n iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != '__')\n iters.update(self.__dict__)\n\n for x,y in iters.items():\n yield x,y\n\n cls.__iter__ = iterfn\n return cls\n\n@iterable\nclass B(object):\n d = 'd'\n e = 'e'\n f = 'f'\n\n def __init__(self):\n self.a = 'a'\n self.b = 'b'\n self.c = 'c'\n\nb = B()\nprint(dict(b))\n" }, { "answer_id": 31770231, "author": "Berislav Lopac", "author_id": 122033, "author_profile": "https://Stackoverflow.com/users/122033", "pm_score": 8, "selected": false, "text": "x.__dict__ vars(x)" }, { "answer_id": 34662287, "author": "coanor", "author_id": 342348, "author_profile": "https://Stackoverflow.com/users/342348", "pm_score": 1, "selected": false, "text": "__dict__ def __dict__(self):\n d = {\n 'attr_1' : self.attr_1,\n ...\n }\n return d\n\n# Call __dict__\nd = instance.__dict__()\n instance d" }, { "answer_id": 48696573, "author": "spattanaik75", "author_id": 3094089, "author_profile": "https://Stackoverflow.com/users/3094089", "pm_score": 0, "selected": false, "text": "class DateTimeDecoder(json.JSONDecoder):\n\n def __init__(self, *args, **kargs):\n JSONDecoder.__init__(self, object_hook=self.dict_to_object,\n *args, **kargs)\n\n def dict_to_object(self, d):\n if '__type__' not in d:\n return d\n\n type = d.pop('__type__')\n try:\n dateobj = datetime(**d)\n return dateobj\n except:\n d['__type__'] = type\n return d\n\ndef json_default_format(value):\n try:\n if isinstance(value, datetime):\n return {\n '__type__': 'datetime',\n 'year': value.year,\n 'month': value.month,\n 'day': value.day,\n 'hour': value.hour,\n 'minute': value.minute,\n 'second': value.second,\n 'microsecond': value.microsecond,\n }\n if isinstance(value, decimal.Decimal):\n return float(value)\n if isinstance(value, Enum):\n return value.name\n else:\n return vars(value)\n except Exception as e:\n raise ValueError\n class Foo():\n def toJSON(self):\n return json.loads(\n json.dumps(self, sort_keys=True, indent=4, separators=(',', ': '), default=json_default_format), cls=DateTimeDecoder)\n\n\nFoo().toJSON() \n" }, { "answer_id": 53823839, "author": "R H", "author_id": 2169290, "author_profile": "https://Stackoverflow.com/users/2169290", "pm_score": 4, "selected": false, "text": "__dict__ jsons >>> import jsons\n>>> jsons.dump(f)\n{'bar': 'hello', 'baz': 'world'}\n" }, { "answer_id": 61531302, "author": "Ricky Levi", "author_id": 281965, "author_profile": "https://Stackoverflow.com/users/281965", "pm_score": 3, "selected": false, "text": "vars() def to_dict(self):\n return json.loads(json.dumps(self, default=lambda o: o.__dict__))\n" }, { "answer_id": 65469063, "author": "Anakhand", "author_id": 6117426, "author_profile": "https://Stackoverflow.com/users/6117426", "pm_score": 2, "selected": false, "text": "vars __slots__ __dict__ str int __dict__ __slots__ def instance_attributes(obj: Any) -> Dict[str, Any]:\n \"\"\"Get a name-to-value dictionary of instance attributes of an arbitrary object.\"\"\"\n try:\n return vars(obj)\n except TypeError:\n pass\n\n # object doesn't have __dict__, try with __slots__\n try:\n slots = obj.__slots__\n except AttributeError:\n # doesn't have __dict__ nor __slots__, probably a builtin like str or int\n return {}\n # collect all slots attributes (some might not be present)\n attrs = {}\n for name in slots:\n try:\n attrs[name] = getattr(obj, name)\n except AttributeError:\n continue\n return attrs\n class Foo:\n class_var = \"spam\"\n\n\nclass Bar:\n class_var = \"eggs\"\n \n __slots__ = [\"a\", \"b\"]\n >>> foo = Foo()\n>>> foo.a = 1\n>>> foo.b = 2\n>>> instance_attributes(foo)\n{'a': 1, 'b': 2}\n\n>>> bar = Bar()\n>>> bar.a = 3\n>>> instance_attributes(bar)\n{'a': 3}\n\n>>> instance_attributes(\"baz\") \n{}\n\n vars" }, { "answer_id": 66727687, "author": "Reed Sandberg", "author_id": 1287091, "author_profile": "https://Stackoverflow.com/users/1287091", "pm_score": 3, "selected": false, "text": ">>> class Foo(BaseModel):\n... count: int\n... size: float = None\n... \n>>> \n>>> class Bar(BaseModel):\n... apple = 'x'\n... banana = 'y'\n... \n>>> \n>>> class Spam(BaseModel):\n... foo: Foo\n... bars: List[Bar]\n... \n>>> \n>>> m = Spam(foo={'count': 4}, bars=[{'apple': 'x1'}, {'apple': 'x2'}])\n >>> print(m.dict())\n{'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y'}]}\n >>> print(m.json())\n{\"foo\": {\"count\": 4, \"size\": null}, \"bars\": [{\"apple\": \"x1\", \"banana\": \"y\"}, {\"apple\": \"x2\", \"banana\": \"y\"}]}\n >>> spam = Spam.parse_obj({'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y2'}]})\n>>> spam\nSpam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y2')])\n >>> spam = Spam.parse_raw('{\"foo\": {\"count\": 4, \"size\": null}, \"bars\": [{\"apple\": \"x1\", \"banana\": \"y\"}, {\"apple\": \"x2\", \"banana\": \"y\"}]}')\n>>> spam\nSpam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y')])\n" }, { "answer_id": 68982164, "author": "thetaprime", "author_id": 1968839, "author_profile": "https://Stackoverflow.com/users/1968839", "pm_score": 0, "selected": false, "text": "from pprint import pformat\na_dict = eval(pformat(an_obj))\n" }, { "answer_id": 69088860, "author": "hizbul25", "author_id": 1534638, "author_profile": "https://Stackoverflow.com/users/1534638", "pm_score": 3, "selected": false, "text": "return dict((key, value) for key, value in f.__dict__.items() if not callable(value) and not key.startswith('__'))\n" }, { "answer_id": 73388990, "author": "Surya Teja", "author_id": 5692181, "author_profile": "https://Stackoverflow.com/users/5692181", "pm_score": 2, "selected": false, "text": "@dataclass\nclass Point:\n x: int\n y: int\n\np = Point(10, 20)\nasdict(p) # it returns {'x': 10, 'y': 20}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148/" ]
61,535
<p>I get a URL from a user. I need to know:<br/> a) is the URL a valid RSS feed?<br/> b) if not is there a valid feed associated with that URL</p> <p>using PHP/Javascript or something similar</p> <p>(Ex. <a href="http://techcrunch.com" rel="nofollow noreferrer">http://techcrunch.com</a> fails a), but b) would return their RSS feed)</p>
[ { "answer_id": 61537, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "text/html <link>" }, { "answer_id": 61538, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<link rel=\"alternate\" title=\"RSS Feed\" \n href=\"http://www.example.com/rss-feed.xml\" type=\"application/rss+xml\" />\n" }, { "answer_id": 61539, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" }, { "answer_id": 62237, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "$feedArray = Zend_Feed::findFeeds('http://www.example.com/news.html');\n" }, { "answer_id": 71816, "author": "Corion", "author_id": 11253, "author_profile": "https://Stackoverflow.com/users/11253", "pm_score": 2, "selected": false, "text": "use Feed::Find;\nmy @feeds = Feed::Find->find('http://example.com/');\n link a .rss" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ]
61,552
<p><a href="http://www.stackoverflow.com/questions/61088/hidden-features-of-javascript#61118">Alan Storm's comments</a> in response to my answer regarding the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with" rel="noreferrer"><code>with</code> statement</a> got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of <code>with</code>, while avoiding its pitfalls.</p> <p>Where have you found the <code>with</code> statement useful?</p>
[ { "answer_id": 61566, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": false, "text": "With someObject.Foo = ''\nsomeObject.Bar = ''\nsomeObject.Baz = ''\n With someObject\n .Foo = ''\n .Bar = ''\n .Baz = ''\nEnd With\n . With someObject\n .Foo = ''\nEnd With\n With someObject\n Foo = ''\nEnd With\n someObject.Foo Foo someObject with" }, { "answer_id": 61577, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "(with-slots (foo bar) objectname\n \"some code that accesses foo and bar\"\n \"some code that accesses (slot-value objectname 'foo) and (slot-value objectname 'bar)\"\"\n" }, { "answer_id": 61586, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": false, "text": "with var with_ = function (obj, func) { func (obj); };\n\nwith_ (object_name_here, function (_)\n{\n _.a = \"foo\";\n _.b = \"bar\";\n});\n" }, { "answer_id": 61676, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 6, "selected": false, "text": "with user = {};\nsomeFunctionThatDoesStuffToUser(user);\nsomeOtherFunction(user);\n\nwith(user){\n name = 'Bob';\n age = 20;\n}\n user.name Bob name Bob user name with" }, { "answer_id": 61737, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 5, "selected": false, "text": "var o = incrediblyLongObjectNameThatNoOneWouldUse;\no.name = \"Bob\";\no.age = \"50\";\n" }, { "answer_id": 176406, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 2, "selected": false, "text": "with var sHeader = object.data.header.toString();\nvar sContent = object.data.content.toString();\nvar sFooter = object.data.footer.toString();\n with var sHeader = null, sContent = null, sFooter = null;\nwith(object.data) {\n sHeader = header.toString();\n sContent = content.toString();\n sFooter = content.toString();\n}\n with with" }, { "answer_id": 185283, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 9, "selected": false, "text": "var name = \"Joe\";\nif ( true )\n{\n var name = \"Jack\";\n}\n// name now contains \"Jack\"\n for (var i=0; i<3; ++i)\n{\n var num = i;\n setTimeout(function() { alert(num); }, 10);\n}\n num 2 let with let // variables introduced in this statement \n// are scoped to each iteration of the loop\nfor (let i=0; i<3; ++i)\n{\n setTimeout(function() { alert(i); }, 10);\n}\n for (var i=0; i<3; ++i)\n{\n // variables introduced in this statement \n // are scoped to the block containing it.\n let num = i;\n setTimeout(function() { alert(num); }, 10);\n}\n with for (var i=0; i<3; ++i)\n{\n // object members introduced in this statement \n // are scoped to the block following it.\n with ({num: i})\n {\n setTimeout(function() { alert(num); }, 10);\n }\n}\n let" }, { "answer_id": 1028684, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "with (document.getElementById(\"blah\").style) {\n background = \"black\";\n color = \"blue\";\n border = \"1px solid green\";\n}\n var element = document.createElement(\"div\"),\n elementStyle = element.style;\n\nelementStyle.fontWeight = \"bold\";\nelementStyle.fontSize = \"1.5em\";\nelementStyle.color = \"#55d\";\nelementStyle.marginLeft = \"2px\";\n" }, { "answer_id": 1462102, "author": "airportyh", "author_id": 5304, "author_profile": "https://Stackoverflow.com/users/5304", "pm_score": 7, "selected": false, "text": "markupbuilder.div(\n markupbuilder.p('Hi! I am a paragraph!',\n markupbuilder.span('I am a span inside a paragraph')\n )\n)\n with(markupbuilder){\n div(\n p('Hi! I am a paragraph!',\n span('I am a span inside a paragraph')\n )\n )\n}\n" }, { "answer_id": 1463937, "author": "kangax", "author_id": 130652, "author_profile": "https://Stackoverflow.com/users/130652", "pm_score": 4, "selected": false, "text": "with with with" }, { "answer_id": 2207355, "author": "alex", "author_id": 267082, "author_profile": "https://Stackoverflow.com/users/267082", "pm_score": 2, "selected": false, "text": "// demo class framework\nvar Class= function(name, o) {\n var c=function(){};\n if( o.hasOwnProperty(\"constructor\") ) {\n c= o.constructor;\n }\n delete o[\"constructor\"];\n delete o[\"prototype\"];\n c.prototype= {};\n for( var k in o ) c.prototype[k]= o[k];\n c.scope= Class.scope;\n c.scope.Class= c;\n c.Name= name;\n return c;\n}\nClass.newScope= function() {\n Class.scope= {};\n Class.scope.Scope= Class.scope;\n return Class.scope;\n}\n\n// create a new class\nwith( Class.newScope() ) {\n window.Foo= Class(\"Foo\",{\n test: function() {\n alert( Class.Name );\n }\n });\n}\n(new Foo()).test();\n var o={x: 5},r, fnRAW= function(a,b){ return a*b; }, fnScoped, s, e, i;\nwith( o ) {\n fnScoped= function(a,b){ return a*b; };\n}\n\ns= Date.now();\nr= 0;\nfor( i=0; i < 1000000; i++ ) {\n r+= fnRAW(i,i);\n}\ne= Date.now();\nconsole.log( (e-s)+\"ms\" );\n\ns= Date.now();\nr= 0;\nfor( i=0; i < 1000000; i++ ) {\n r+= fnScoped(i,i);\n}\ne= Date.now();\nconsole.log( (e-s)+\"ms\" );\n" }, { "answer_id": 2602245, "author": "Fire Crow", "author_id": 80479, "author_profile": "https://Stackoverflow.com/users/80479", "pm_score": 2, "selected": false, "text": "for(var i = nodes.length; i--;)\n{\n // info is namespaced in a closure the click handler can access!\n (function(info)\n { \n nodes[i].onclick = function(){ showStuff(info) };\n })(data[i]);\n}\n for(var i = nodes.length; i--;)\n{\n // info is namespaced in a closure the click handler can access!\n with({info: data[i]})\n { \n nodes[i].onclick = function(){ showStuff(info) };\n } \n}\n" }, { "answer_id": 3122593, "author": "Jonah", "author_id": 376785, "author_profile": "https://Stackoverflow.com/users/376785", "pm_score": 3, "selected": false, "text": "var photo = document.getElementById('photo');\nphoto.style.position = 'absolute';\nphoto.style.left = '10px';\nphoto.style.top = '10px';\n with(document.getElementById('photo').style) {\n position = 'absolute';\n left = '10px';\n top = '10px';\n}\n" }, { "answer_id": 3471239, "author": "palswim", "author_id": 393280, "author_profile": "https://Stackoverflow.com/users/393280", "pm_score": 2, "selected": false, "text": "with if (typeof Object.merge !== 'function') {\n Object.merge = function (o1, o2) { // Function to merge all of the properties from one object into another\n for(var i in o2) { o1[i] = o2[i]; }\n return o1;\n };\n}\n with var eDiv = document.createElement(\"div\");\nvar eHeader = Object.merge(eDiv.cloneNode(false), {className: \"header\", onclick: function(){ alert(\"Click!\"); }});\nfunction NewObj() {\n Object.merge(this, {size: 4096, initDate: new Date()});\n}\n" }, { "answer_id": 3637640, "author": "Jordão", "author_id": 31158, "author_profile": "https://Stackoverflow.com/users/31158", "pm_score": 3, "selected": false, "text": "with" }, { "answer_id": 3666255, "author": "Elvis Salaris", "author_id": 442248, "author_profile": "https://Stackoverflow.com/users/442248", "pm_score": 1, "selected": false, "text": "function validate_required(field)\n{\nwith (field)\n {\n if (value==null||value==\"\")\n {\n alert('All fields are mandtory');return false;\n }\n else\n {\n return true;\n }\n }\n}\n\nfunction validate_form(thisform)\n{\nwith (thisform)\n {\n for(fiie in elements){\n if (validate_required(elements[fiie])==false){\n elements[fiie].focus();\n elements[fiie].style.border='1px solid red';\n return false;\n } else {elements[fiie].style.border='1px solid #7F9DB9';}\n }\n\n }\n return false;\n}\n" }, { "answer_id": 3976785, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 6, "selected": false, "text": "with with (consoleCommands) {\n with (window) {\n eval(expression); \n }\n}\n with InjectedScript._evaluateOn = function(evalFunction, object, expression) {\n InjectedScript._ensureCommandLineAPIInstalled();\n // Surround the expression in with statements to inject our command line API so that\n // the window object properties still take more precedent than our API functions.\n expression = \"with (window._inspectorCommandLineAPI) { with (window) { \" + expression + \" } }\";\n return evalFunction.call(object, expression);\n}\n const evalScript = \"with (__win__.__scope__.vars) { with (__win__.__scope__.api) { with (__win__.__scope__.userVars) { with (__win__) {\" +\n \"try {\" +\n \"__win__.__scope__.callback(eval(__win__.__scope__.expr));\" +\n \"} catch (exc) {\" +\n \"__win__.__scope__.callback(exc, true);\" +\n \"}\" +\n\"}}}}\";\n" }, { "answer_id": 6360857, "author": "Trevor Burnham", "author_id": 66226, "author_profile": "https://Stackoverflow.com/users/66226", "pm_score": 1, "selected": false, "text": "with this @ with long.object.reference\n @a = 'foo'\n bar = @b\n" }, { "answer_id": 10077345, "author": "rplantiko", "author_id": 1092785, "author_profile": "https://Stackoverflow.com/users/1092785", "pm_score": 2, "selected": false, "text": "sin cos AngularDegree AngularDegree = new function() {\nthis.CONV = Math.PI / 180;\nthis.sin = function(x) { return Math.sin( x * this.CONV ) };\nthis.cos = function(x) { return Math.cos( x * this.CONV ) };\nthis.tan = function(x) { return Math.tan( x * this.CONV ) };\nthis.asin = function(x) { return Math.asin( x ) / this.CONV };\nthis.acos = function(x) { return Math.acos( x ) / this.CONV };\nthis.atan = function(x) { return Math.atan( x ) / this.CONV };\nthis.atan2 = function(x,y) { return Math.atan2(x,y) / this.CONV };\n};\n with function getAzimut(pol,pos) {\n ...\n var d = pos.lon - pol.lon;\n with(AngularDegree) {\n var z = atan2( sin(d), cos(pol.lat)*tan(pos.lat) - sin(pol.lat)*cos(d) );\n return z;\n }\n }\n" }, { "answer_id": 14428133, "author": "avanderveen", "author_id": 1472460, "author_profile": "https://Stackoverflow.com/users/1472460", "pm_score": 0, "selected": false, "text": "with types.tbr with Tile.types = (function(t,l,b,r) {\n function j(a) { return a.join(' '); }\n // all possible types\n var types = { \n br: j( [b,r]),\n lbr: j([l,b,r]),\n lb: j([l,b] ), \n tbr: j([t,b,r]),\n tbl: j([t,b,l]),\n tlr: j([t,l,r]),\n tr: j([t,r] ), \n tl: j([t,l] ), \n locked: []\n }; \n // store starting (base/locked) tiles in types.locked\n with( types ) { locked = [ \n br, lbr, lbr, lb, \n tbr, tbr, lbr, tbl,\n tbr, tlr, tbl, tbl,\n tr, tlr, tlr, tl\n ] } \n return types;\n})(\"top\",\"left\",\"bottom\",\"right\");\n" }, { "answer_id": 19012662, "author": "Dexygen", "author_id": 34806, "author_profile": "https://Stackoverflow.com/users/34806", "pm_score": 0, "selected": false, "text": "with var modules = requirejs.declare([{\n 'App' : 'app/app'\n}]);\n\nrequire(modules.paths(), function() { with (modules.resolve(arguments)) {\n App.run();\n}});\n requirejs.declare = function(dependencyPairs) {\n var pair;\n var dependencyKeys = [];\n var dependencyValues = [];\n\n for (var i=0, n=dependencyPairs.length; i<n; i++) {\n pair = dependencyPairs[i];\n for (var key in dependencyPairs[i]) {\n dependencyKeys.push(key);\n dependencyValues.push(pair[key]);\n break;\n }\n };\n\n return {\n paths : function() {\n return dependencyValues;\n },\n \n resolve : function(args) {\n var modules = {};\n for (var i=0, n=args.length; i<n; i++) {\n modules[dependencyKeys[i]] = args[i];\n }\n return modules;\n }\n } \n}\n" }, { "answer_id": 23285657, "author": "Jackson", "author_id": 1468130, "author_profile": "https://Stackoverflow.com/users/1468130", "pm_score": 0, "selected": false, "text": "with for (var i = 0; i < 3; i++) {\n function toString() {\n return 'a';\n }\n with ({num: i}) {\n setTimeout(function() { console.log(num); }, 10);\n console.log(toString()); // prints \"[object Object]\"\n }\n}\n with function scope(o) {\n var ret = Object.create(null);\n if (typeof o !== 'object') return ret;\n Object.keys(o).forEach(function (key) {\n ret[key] = o[key];\n });\n return ret;\n}\n\nfor (var i = 0; i < 3; i++) {\n function toString() {\n return 'a';\n }\n with (scope({num: i})) {\n setTimeout(function() { console.log(num); }, 10);\n console.log(toString()); // prints \"a\"\n }\n}\n with" }, { "answer_id": 26707742, "author": "kevin.groat", "author_id": 2939688, "author_profile": "https://Stackoverflow.com/users/2939688", "pm_score": 0, "selected": false, "text": "with // this code is only executed once\nvar localScope = {\n build: undefined,\n\n // this is where all of the values I want to hide go; the list is rather long\n window: undefined,\n console: undefined,\n ...\n};\nwith(localScope) {\n build = function(userCode) {\n eval('var builtFunction = function(options) {' + userCode + '}');\n return builtFunction;\n }\n}\nvar build = localScope.build;\ndelete localScope.build;\n\n// this is how I use the build method\nvar userCode = 'return \"Hello, World!\";';\nvar userFunction = build(userCode);\n window window test = function() {\n return this.window\n};\nreturn test();\n" }, { "answer_id": 29690322, "author": "user2782001", "author_id": 2782001, "author_profile": "https://Stackoverflow.com/users/2782001", "pm_score": -1, "selected": false, "text": " //utility function\n function _with(context){\n var ctx=context;\n this.set=function(obj){\n for(x in obj){\n //should add hasOwnProperty(x) here\n ctx[x]=obj[x];\n }\n } \n\n return this.set; \n }\n\n //how calling it would look in code...\n\n _with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)({\n\n a:\"letter a\",\n b:\"letter b\",\n c:\"letter c\",\n d:\"letter a\",\n e:\"letter b\",\n f:\"letter c\",\n // continue through whole alphabet...\n\n });//look how readable I am!!!!\n //imagine a deeply nested object \n//Hemisphere.Continent.Nation.Language.Dialect.Alphabet\n(function(){\n with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet){ \n this.a=\"letter a\";\n this.b=\"letter b\";\n this.c=\"letter c\";\n this.d=\"letter a\";\n this.e=\"letter b\";\n this.f=\"letter c\";\n // continue through whole alphabet...\n }\n}).call(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)\n //imagine a deeply nested object Hemisphere.Continent.Nation.Language.Dialect.Alphabet\n var ltr=Hemisphere.Continent.Nation.Language.Dialect.Alphabet \n ltr.a=\"letter a\";\n ltr.b=\"letter b\";\n ltr.c=\"letter c\";\n ltr.d=\"letter a\";\n ltr.e=\"letter b\";\n ltr.f=\"letter c\";\n // continue through whole alphabet...\n" }, { "answer_id": 37640530, "author": "Little Alien", "author_id": 6267925, "author_profile": "https://Stackoverflow.com/users/6267925", "pm_score": 1, "selected": false, "text": "switch(e.type) {\n case gapi.drive.realtime.ErrorType.TOKEN_REFRESH_REQUIRED: blah\n case gapi.drive.realtime.ErrorType.CLIENT_ERROR: blah\n case gapi.drive.realtime.ErrorType.NOT_FOUND: blah\n}\n with(gapi.drive.realtime.ErrorType) {switch(e.type) {\n case TOKEN_REFRESH_REQUIRED: blah\n case CLIENT_ERROR: blah\n case NOT_FOUND: blah\n}}\n" }, { "answer_id": 65077825, "author": "shabaany", "author_id": 12220097, "author_profile": "https://Stackoverflow.com/users/12220097", "pm_score": 1, "selected": false, "text": "module require const runInContext = function(code, context) {\n context.global = context;\n const proxyOfContext = new Proxy(context, { has: () => true });\n let run = new Function(\n \"proxyOfContext\",\n `\n with(proxyOfContext){\n with(global){\n ${code}\n }\n }\n `\n );\n return run(proxyOfContext);\n};\n undefined code var let const vm.runInContext" }, { "answer_id": 73360501, "author": "nzn", "author_id": 932256, "author_profile": "https://Stackoverflow.com/users/932256", "pm_score": 0, "selected": false, "text": "with var a = {id: 123, name: 'abc', attr1: 'efg', attr2: 'zxvc', attr3: '4321'};\n var b = {\n id: a.id,\n name: a.name\n metadata: {name: a.name, attr1: a.attr1}\n extrastuff: {attr2: a.attr2, attr3: a.attr3}\n}\n with (a) {\n var b = {\n id,\n name,\n metadata: {name, attr1}\n extrastuff: {attr2, attr3}\n }\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811/" ]
61,604
<p>Do you often see in API documentation (as in 'javadoc of public functions' for example) the description of "value limits" as well as the classic documentation ?</p> <p><strong>Note:</strong> I am not talking about <a href="https://stackoverflow.com/questions/20922/do-you-comment-your-code">comments within the code</a></p> <p>By "value limits", I mean:</p> <ul> <li>does a parameter can support a null value (or an empty String, or...) ?</li> <li>does a 'return value' can be null or is guaranteed to never be null (or can be "empty", or...) ?</li> </ul> <p><strong>Sample:</strong></p> <p>What I often see (without having access to source code) is:</p> <pre><code>/** * Get all readers name for this current Report. &lt;br /&gt; * &lt;b&gt;Warning&lt;/b&gt;The Report must have been published first. * @param aReaderNameRegexp filter in order to return only reader matching the regexp * @return array of reader names */ String[] getReaderNames(final String aReaderNameRegexp); </code></pre> <p>What I <em>like to see</em> would be:</p> <pre><code>/** * Get all readers name for this current Report. &lt;br /&gt; * &lt;b&gt;Warning&lt;/b&gt;The Report must have been published first. * @param aReaderNameRegexp filter in order to return only reader matching the regexp * (can be null or empty) * @return array of reader names * (null if Report has not yet been published, * empty array if no reader match criteria, * reader names array matching regexp, or all readers if regexp is null or empty) */ String[] getReaderNames(final String aReaderNameRegexp); </code></pre> <p><strong>My point is:</strong></p> <p>When I use a library with a getReaderNames() function in it, I often do not even need to read the API documentation to guess what it does. But I need to be sure <em>how to use it</em>.</p> <p>My only concern when I want to use this function is: what should I expect in term of parameters and return values ? That is all I need to know to safely setup my parameters and safely test the return value, yet I almost never see that kind of information in API documentation...</p> <p><strong>Edit:</strong> </p> <p>This can influence the usage or not for <em><a href="https://stackoverflow.com/questions/27578#73355">checked or unchecked exceptions</a></em>.</p> <p>What do you think ? value limits and API, do they belong together or not ?</p>
[ { "answer_id": 61608, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "//File:\n// Should be a path to the teexture file to load, if it is not a full path (eg \"c:\\example.png\") it will attempt to find the file usign the paths provided by the DataSearchPath list\n//Return: The pointer to a Texture instance is returned, in the event of an error, an exception is thrown. When you are finished with the texture you chould call the Free() method.\n//Exceptions:\n//except::FileNotFound\n//except::InvalidFile\n//except::InvalidParams\n//except::CreationFailed\nTexture *GetTexture(const std::string &File);\n" }, { "answer_id": 24224149, "author": "taringamberini", "author_id": 1972317, "author_profile": "https://Stackoverflow.com/users/1972317", "pm_score": 2, "selected": false, "text": "RuntimeException RuntimeException @param aReaderNameRegexp filter in order to ... (can be null or empty) iContract JcontractS Execption IllegalArgumentException IllegalStateException" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
[ { "answer_id": 61629, "author": "Jason Etheridge", "author_id": 2193, "author_profile": "https://Stackoverflow.com/users/2193", "pm_score": 5, "selected": false, "text": "q, r = divide(22, 7)\n" }, { "answer_id": 61636, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 8, "selected": true, "text": "divmod() q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x\n zip enumerate dict.items for i, e in enumerate([1, 3, 3]):\n print \"index=%d, element=%s\" % (i, e)\n\n# reverse keys and values in a dictionary\nd = dict((v, k) for k, v in adict.items()) # or \nd = dict(zip(adict.values(), adict.keys()))\n (x, y) Point(x, y) >>> import collections\n>>> Point = collections.namedtuple('Point', 'x y')\n>>> x, y = Point(0, 1)\n>>> p = Point(x, y)\n>>> x, y, p\n(0, 1, Point(x=0, y=1))\n>>> p.x, p.y, p[0], p[1]\n(0, 1, 0, 1)\n>>> for i in p:\n... print(i)\n...\n0\n1\n" }, { "answer_id": 61637, "author": "Nathan Jones", "author_id": 5848, "author_profile": "https://Stackoverflow.com/users/5848", "pm_score": 4, "selected": false, "text": "divmod seconds = 1234\nminutes, seconds = divmod(seconds, 60)\nhours, minutes = divmod(minutes, 60)\n\nseconds = 1234\nminutes = seconds / 60\nseconds = seconds % 60\nhours = minutes / 60\nminutes = minutes % 60\n" }, { "answer_id": 63528, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 0, "selected": false, "text": "divmod" }, { "answer_id": 64110, "author": "zweiterlinde", "author_id": 6592, "author_profile": "https://Stackoverflow.com/users/6592", "pm_score": 2, "selected": false, "text": "// C++\nvoid test(int& arg)\n{\n arg = 1;\n}\n\nint foo = 0;\ntest(foo); // foo is now 1!\n # Python\ndef test(arg):\n arg = 1\n\nfoo = 0\ntest(foo) # foo is still 0\n" }, { "answer_id": 66967, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 0, "selected": false, "text": "def divide(x, y):\n return {'quotient': x/y, 'remainder':x%y }\n\nanswer = divide(22, 7)\nprint answer['quotient']\nprint answer['remainder']\n" }, { "answer_id": 640632, "author": "NevilleDNZ", "author_id": 77431, "author_profile": "https://Stackoverflow.com/users/77431", "pm_score": 1, "selected": false, "text": "INT quotient:=355, remainder;\nremainder := (quotient /:= 113);\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
61,615
<p>C# and Java allow almost any character in class names, method names, local variables, etc.. Is it bad practice to use non-ASCII characters, testing the boundaries of poor editors and analysis tools and making it difficult for some people to read, or is American arrogance the only argument against?</p>
[ { "answer_id": 61619, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": false, "text": "if toString()" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4926/" ]
61,634
<p>I'm trying to create a dialog box using C++ and the windows API, but I don't want the dialog defined in a resource file. I can't find anything good on this on the web, and none of the examples I've read seem to define the dialog programmatically.</p> <p>How can I do this?</p> <p>A simple example is fine. I'm not doing anything complicated with it yet.</p>
[ { "answer_id": 48009861, "author": "jrh", "author_id": 4975230, "author_profile": "https://Stackoverflow.com/users/4975230", "pm_score": 3, "selected": false, "text": "CreateWindow CreateWindowEx Control TextBox UNICODE _UNICODE UNICODE _UNICODE char* char* SendMessageA // This sample will work either with or without UNICODE, it looks like\n// it's recommended now to use UNICODE for all new code, but I left\n// the ANSI option in there just to get the absolute maximum amount\n// of compatibility.\n//\n// Note that UNICODE and _UNICODE go together, unfortunately part\n// of the Windows API uses _UNICODE, and part of it uses UNICODE.\n//\n// tchar.h, for example, makes heavy use of _UNICODE, and windows.h\n// makes heavy use of UNICODE.\n#define UNICODE\n#define _UNICODE\n//#undef UNICODE\n//#undef _UNICODE\n\n#include <windows.h>\n#include <tchar.h>\n\n// I made this struct to more conveniently store the\n// positions / size of each window in the dialog\ntypedef struct SizeAndPos_s\n{\n int x, y, width, height;\n} SizeAndPos_t;\n\n// Typically these would be #defines, but there\n// is no reason to not make them constants\nconst WORD ID_btnHELLO = 1;\nconst WORD ID_btnQUIT = 2;\nconst WORD ID_CheckBox = 3;\nconst WORD ID_txtEdit = 4;\nconst WORD ID_btnShow = 5;\n\n// x, y, width, height\nconst SizeAndPos_t mainWindow = { 150, 150, 300, 300 };\n\nconst SizeAndPos_t btnHello = { 20, 50, 80, 25 };\nconst SizeAndPos_t btnQuit = { 120, 50, 80, 25 };\nconst SizeAndPos_t chkCheck = { 20, 90, 185, 35 };\n\nconst SizeAndPos_t txtEdit = { 20, 150, 150, 20 };\nconst SizeAndPos_t btnShow = { 180, 150, 80, 25 };\n\nHWND txtEditHandle = NULL;\n\n// hwnd: All window processes are passed the handle of the window\n// that they belong to in hwnd.\n// msg: Current message (e.g., WM_*) from the OS.\n// wParam: First message parameter, note that these are more or less\n// integers, but they are really just \"data chunks\" that\n// you are expected to memcpy as raw data to float, etc.\n// lParam: Second message parameter, same deal as above.\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n\n switch (msg)\n {\n\n case WM_CREATE:\n // Create the buttons\n //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n // Note that the \"parent window\" is the dialog itself. Since we are\n // in the dialog's WndProc, the dialog's handle is passed into hwnd.\n //\n //CreateWindow( lpClassName, lpWindowName, dwStyle, x, y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam\n //CreateWindow( windowClassName, initial text, style (flags), xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);\n CreateWindow( TEXT(\"Button\"), TEXT(\"Hello\"), WS_VISIBLE | WS_CHILD, btnHello.x, btnHello.y, btnHello.width, btnHello.height, hwnd, (HMENU)ID_btnHELLO, NULL, NULL);\n\n CreateWindow( TEXT(\"Button\"), TEXT(\"Quit\"), WS_VISIBLE | WS_CHILD, btnQuit.x, btnQuit.y, btnQuit.width, btnQuit.height, hwnd, (HMENU)ID_btnQUIT, NULL, NULL);\n\n // Create a checkbox\n //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CreateWindow( TEXT(\"button\"), TEXT(\"CheckBox\"), WS_VISIBLE | WS_CHILD | BS_CHECKBOX, chkCheck.x, chkCheck.y, chkCheck.width, chkCheck.height, hwnd, (HMENU)ID_CheckBox, NULL, NULL);\n\n // Create an edit box (single line text editing), and a button to show the text\n //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n //Handle = CreateWindow(windowClassName, windowName, style, xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);\n txtEditHandle = CreateWindow(TEXT(\"Edit\"), TEXT(\"Initial Text\"), WS_CHILD | WS_VISIBLE | WS_BORDER, txtEdit.x, txtEdit.y, txtEdit.width, txtEdit.height, hwnd, (HMENU)ID_txtEdit, NULL, NULL);\n\n //CreateWindow( windowClassName, windowName, style, xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);\n CreateWindow( TEXT(\"Button\"), TEXT(\"Show\"), WS_VISIBLE | WS_CHILD, btnShow.x, btnShow.y, btnShow.width, btnShow.height, hwnd, (HMENU)ID_btnShow, NULL, NULL);\n\n // Create an Updown control. Note that this control will allow you to type in non-number characters, but it will not affect the state of the control\n\n break;\n\n // For more information about WM_COMMAND, see\n // https://msdn.microsoft.com/en-us/library/windows/desktop/ms647591(v=vs.85).aspx\n case WM_COMMAND:\n\n // The LOWORD of wParam identifies which control sent\n // the WM_COMMAND message. The WM_COMMAND message is\n // sent when the button has been clicked.\n if (LOWORD(wParam) == ID_btnHELLO)\n {\n MessageBox(hwnd, TEXT(\"Hello!\"), TEXT(\"Hello\"), MB_OK);\n }\n else if (LOWORD(wParam) == ID_btnQUIT)\n {\n PostQuitMessage(0);\n }\n else if (LOWORD(wParam) == ID_CheckBox)\n {\n UINT checked = IsDlgButtonChecked(hwnd, ID_CheckBox);\n\n if (checked)\n {\n CheckDlgButton(hwnd, ID_CheckBox, BST_UNCHECKED);\n MessageBox(hwnd, TEXT(\"The checkbox has been unchecked.\"), TEXT(\"CheckBox Event\"), MB_OK);\n }\n else\n {\n CheckDlgButton(hwnd, ID_CheckBox, BST_CHECKED);\n MessageBox(hwnd, TEXT(\"The checkbox has been checked.\"), TEXT(\"CheckBox Event\"), MB_OK);\n }\n }\n else if (LOWORD(wParam) == ID_btnShow)\n {\n int textLength_WithNUL = GetWindowTextLength(txtEditHandle) + 1;\n // WARNING: If you are compiling this for C, please remember to remove the (TCHAR*) cast.\n TCHAR* textBoxText = (TCHAR*) malloc(sizeof(TCHAR) * textLength_WithNUL);\n\n GetWindowText(txtEditHandle, textBoxText, textLength_WithNUL);\n\n MessageBox(hwnd, textBoxText, TEXT(\"Here's what you typed\"), MB_OK);\n\n free(textBoxText);\n }\n break;\n\n case WM_DESTROY:\n\n PostQuitMessage(0);\n break;\n }\n\n return DefWindowProc(hwnd, msg, wParam, lParam);\n}\n\n\n// hInstance: This handle refers to the running executable\n// hPrevInstance: Not used. See https://blogs.msdn.microsoft.com/oldnewthing/20040615-00/?p=38873\n// lpCmdLine: Command line arguments.\n// nCmdShow: a flag that says whether the main application window\n// will be minimized, maximized, or shown normally.\n//\n// Note that it's necessary to use _tWinMain to make it\n// so that command line arguments will work, both\n// with and without UNICODE / _UNICODE defined.\nint APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)\n{\n MSG msg;\n WNDCLASS mainWindowClass = { 0 };\n\n // You can set the main window name to anything, but\n // typically you should prefix custom window classes\n // with something that makes it unique.\n mainWindowClass.lpszClassName = TEXT(\"JRH.MainWindow\");\n\n mainWindowClass.hInstance = hInstance;\n mainWindowClass.hbrBackground = GetSysColorBrush(COLOR_3DFACE);\n mainWindowClass.lpfnWndProc = WndProc;\n mainWindowClass.hCursor = LoadCursor(0, IDC_ARROW);\n\n RegisterClass(&mainWindowClass);\n\n // Notes:\n // - The classname identifies the TYPE of the window. Not a C type.\n // This is a (TCHAR*) ID that Windows uses internally.\n // - The window name is really just the window text, this is\n // commonly used for captions, including the title\n // bar of the window itself.\n // - parentHandle is considered the \"owner\" of this\n // window. MessageBoxes can use HWND_MESSAGE to\n // free them of any window.\n // - menuHandle: hMenu specifies the child-window identifier,\n // an integer value used by a dialog box\n // control to notify its parent about events.\n // The application determines the child-window\n // identifier; it must be unique for all\n // child windows with the same parent window.\n\n //CreateWindow( windowClassName, windowName, style, xPos, yPos, width, height, parentHandle, menuHandle, instanceHandle, param);\n CreateWindow( mainWindowClass.lpszClassName, TEXT(\"Main Window\"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, mainWindow.x, mainWindow.y, mainWindow.width, mainWindow.height, NULL, 0, hInstance, NULL);\n\n while (GetMessage(&msg, NULL, 0, 0))\n {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n return (int)msg.wParam;\n}\n\n// This code is based roughly on tutorial code present at http://zetcode.com/gui/winapi/\n Control" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467/" ]
61,669
<p>How do I use the profiler in Visual Studio 2008?</p> <p>I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Profile to bring up the profile dialog box, yet in 2008 there is no such menu item).</p> <p>Is this because Visual Studio 2008 does not include a profiler, and if it does where is it and where is the documentation for it?</p>
[ { "answer_id": 11205196, "author": "Michelle", "author_id": 1482301, "author_profile": "https://Stackoverflow.com/users/1482301", "pm_score": 0, "selected": false, "text": ".vsp .vsp" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
61,675
<p>I'm reading lines of input on a TCP socket, similar to this:</p> <pre><code>class Bla def getcmd @sock.gets unless @sock.closed? end def start srv = TCPServer.new(5000) @sock = srv.accept while ! @sock.closed? ans = getcmd end end end </code></pre> <p>If the endpoint terminates the connection while getline() is running then gets() hangs. </p> <p>How can I work around this? Is it necessary to do non-blocking or timed I/O?</p>
[ { "answer_id": 61732, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": -1, "selected": false, "text": "gets recvfrom gets" }, { "answer_id": 64313, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 3, "selected": false, "text": "require 'socket'\n\nhost, port = 'localhost', 7000\n\nTCPServer.open(host, port) do |server|\n while client = server.accept\n readfds = true\n got = nil\n begin\n readfds, writefds, exceptfds = select([client], nil, nil, 0.1)\n p :r => readfds, :w => writefds, :e => exceptfds\n\n if readfds\n got = client.gets \n p got\n end\n end while got\n end\nend\n require 'socket'\n\nhost, port = 'localhost', 7000\n\nTCPSocket.open(host, port) do |socket|\n socket.puts \"Hey there\"\n socket.write 'he'\n socket.flush\n socket.close\nend\n" }, { "answer_id": 6005803, "author": "Ben Flynn", "author_id": 449161, "author_profile": "https://Stackoverflow.com/users/449161", "pm_score": 0, "selected": false, "text": "while true\n sockets_ready = select(@sockets, nil, nil, nil)\n if sockets_ready != nil\n sockets_ready[0].each do |socket|\n begin\n if (socket == @server_socket)\n # puts \"Connection accepted!\"\n @sockets << @server_socket.accept\n else\n # Received something on a client socket\n if socket.eof?\n # puts \"Disconnect!\"\n socket.close\n @sockets.delete(socket)\n else\n data = \"\"\n recv_length = 256\n while (tmp = socket.readpartial(recv_length))\n data += tmp\n break if (!socket.ready?)\n end\n listen socket, data\n end\n end\n rescue Exception => exception\n case exception\n when Errno::ECONNRESET,Errno::ECONNABORTED,Errno::ETIMEDOUT\n # puts \"Socket: #{exception.class}\"\n @sockets.delete(socket)\n else\n raise exception\n end\n end\n end\n end\n end\n @server_socket = TCPServer.open(port)\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3796/" ]
61,677
<p>Suppose I have a COM object which users can access via a call such as:</p> <pre><code>Set s = CreateObject("Server") </code></pre> <p>What I'd like to be able to do is allow the user to specify an event handler for the object, like so:</p> <pre><code>Function ServerEvent MsgBox "Event handled" End Function s.OnDoSomething = ServerEvent </code></pre> <p>Is this possible and, if so, how do I expose this in my type library in C++ (specifically BCB 2007)?</p>
[ { "answer_id": 61723, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "IProvideClassInfo ConnectObject" }, { "answer_id": 61762, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 3, "selected": false, "text": "[\n object,\n uuid(6EDA5438-0915-4183-841D-D3F0AEDFA466),\n nonextensible,\n oleautomation,\n pointer_default(unique)\n]\ninterface IServerEvents : IDispatch\n{\n [id(1)]\n HRESULT OnServerEvent();\n}\n\n//...\n\n[\n uuid(FA8F24B3-1751-4D44-8258-D649B6529494),\n]\ncoclass ServerEvents\n{\n [default] interface IServerEvents;\n [default, source] dispinterface IServerEvents;\n};\n class ATL_NO_VTABLE CServerEvents :\n public CComObjectRootEx<CComSingleThreadModel>,\n public CComCoClass<CServerEvents, &CLSID_ServerEvents>,\n public IDispatchImpl<IServerEvents, &IID_IServerEvents , &LIBID_YourLibrary, -1, -1>,\n public IConnectionPointContainerImpl<CServerEvents>,\n public IConnectionPointImpl<CServerEvents,&__uuidof(IServerEvents)>\n{\npublic:\n CServerEvents()\n {\n }\n\n // ...\n\nBEGIN_COM_MAP(CServerEvents)\n COM_INTERFACE_ENTRY(IServerEvents)\n COM_INTERFACE_ENTRY(IDispatch)\n COM_INTERFACE_ENTRY(IConnectionPointContainer)\nEND_COM_MAP()\n\nBEGIN_CONNECTION_POINT_MAP(CServerEvents)\n CONNECTION_POINT_ENTRY(__uuidof(IServerEvents))\nEND_CONNECTION_POINT_MAP()\n\n // ..\n\n // IServerEvents\n STDMETHOD(OnServerEvent)();\n\nprivate:\n CRITICAL_SECTION m_csLock; \n};\n STDMETHODIMP CServerEvents::OnServerEvent()\n{\n ::EnterCriticalSection( &m_csLock );\n\n IUnknown* pUnknown;\n\n for ( unsigned i = 0; ( pUnknown = m_vec.GetAt( i ) ) != NULL; ++i )\n { \n CComPtr<IDispatch> spDisp;\n pUnknown->QueryInterface( &spDisp );\n\n if ( spDisp )\n {\n spDisp.Invoke0( CComBSTR( L\"OnServerEvent\" ) );\n }\n }\n\n ::LeaveCriticalSection( &m_csLock );\n\n return S_OK;\n}\n STDMETHOD(DoSomethingAsynchronous)( IServerEvents *pCallback );\n m_pCallback->OnServerEvent();\n Private m_server As Server\nPrivate WithEvents m_serverEvents As ServerEvents\n\nPrivate Sub MainMethod()\n Set s = CreateObject(\"Server\")\n Set m_serverEvents = New ServerEvents\n\n Call m_searchService.DoSomethingAsynchronous(m_serverEvents)\nEnd Sub\n\nPrivate Sub m_serverEvents_OnServerEvent()\n MsgBox \"Event handled\"\nEnd Sub\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5449/" ]
61,680
<p>I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).</p> <p>I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?</p> <p>Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800).</p> <p>Thanks!</p>
[ { "answer_id": 61684, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 5, "selected": true, "text": "int *array = new int[800*800];\n delete[]" }, { "answer_id": 61685, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 2, "selected": false, "text": "const int width = 800;\nconst int height = 800;\nunsigned int* z_buffer = new unsigned int[width*height];\n unsigned int z = z_buffer[y*width+x];\n" }, { "answer_id": 61689, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "int *ary=new int[800*800];\n class _2DArray\n{\n public:\n int *operator[](const size_t &idx)\n {\n return &ary[idx*800];\n }\n const int *operator[](const size_t &idx) const\n {\n return &ary[idx*800];\n }\n};\n" }, { "answer_id": 61690, "author": "Free Wildebeest", "author_id": 1849, "author_profile": "https://Stackoverflow.com/users/1849", "pm_score": 1, "selected": false, "text": "const int xwidth = 800;\nconst int ywidth = 800;\nint* array = (int*) new int[xwidth * ywidth];\n// Check array is not NULL here and handle the allocation error if it is\n// Then do stuff with the array, such as zero initialize it\nfor(int x = 0; x < xwidth; ++x)\n{\n for(int y = 0; y < ywidth; ++y)\n {\n array[y * xwidth + x] = 0;\n }\n}\n// Just use array[y * xwidth + x] when you want to access your class.\n\n// When you're done with it, free the memory you allocated with\ndelete[] array;\n y * xwidth + x []" }, { "answer_id": 61693, "author": "ReaperUnreal", "author_id": 4218, "author_profile": "https://Stackoverflow.com/users/4218", "pm_score": -1, "selected": false, "text": "800 = 512 + 256 + 32 = 2^5 + 2^8 + 2^9\n int index = y << 9 + y << 8 + y << 5 + x;\n class ZBuffer\n{\npublic:\n const int width = 800;\n const int height = 800;\n\n ZBuffer()\n {\n for(unsigned int i = 0, *pBuff = zbuff; i < width * height; i++, pBuff++)\n *pBuff = 0;\n }\n\n inline unsigned int getZAt(unsigned int x, unsigned int y)\n {\n return *(zbuff + y << 9 + y << 8 + y << 5 + x);\n }\n\n inline unsigned int setZAt(unsigned int x, unsigned int y, unsigned int z)\n {\n *(zbuff + y << 9 + y << 8 + y << 5 + x) = z;\n }\nprivate:\n unsigned int zbuff[width * height];\n};\n" }, { "answer_id": 61936, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 3, "selected": false, "text": "template <class T, size_t W, size_t H>\nclass Array2D\n{\npublic:\n const int width = W;\n const int height = H;\n typedef typename T type;\n\n Array2D()\n : buffer(width*height)\n {\n }\n\n inline type& at(unsigned int x, unsigned int y)\n {\n return buffer[y*width + x];\n }\n\n inline const type& at(unsigned int x, unsigned int y) const\n {\n return buffer[y*width + x];\n }\n\nprivate:\n std::vector<T> buffer;\n};\n void foo()\n{\n Array2D<int, 800, 800> zbuffer;\n\n // Do something with zbuffer...\n}\n Array2D::buffer" }, { "answer_id": 61946, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 1, "selected": false, "text": "vector vectors vector vector int std::vector<std::vector<int> > arr(800, std::vector<int>(800));\n > >" }, { "answer_id": 61960, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 2, "selected": false, "text": "std::vector<T> buffer[width * height];\n std::vector<T> buffer;\n const T &operator()(int x, int y) const\n{\n return buffer[y * width + x];\n}\n T &operator()(int x, int y)\n{\n return buffer[y * width + x];\n}\n int main()\n{\n Array2D<int, 800, 800> a;\n a(10, 10) = 50;\n std::cout << \"A(10, 10)=\" << a(10, 10) << std::endl;\n return 0;\n}\n" }, { "answer_id": 61980, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 1, "selected": false, "text": "boost::shared_array<int> zbuffer(new int[width*height]);\n ++zbuffer[0];\n" }, { "answer_id": 62611, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "static int array[800][800];\n\nvoid fn()\n{\n static int array[800][800];\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ]
61,688
<p>My current project is to write a web application that is an equivalent of an existing desktop application. </p> <p>In the desktop app at certain points in the workflow the user might click on a button and then be shown a form to fill in. Even if it takes a little time for the app to display the form, expert users know what the form will be and will start typing, knowing that the app will "catch up with them".</p> <p>In a web application this doesn't happen: when the user clicks a link their keystrokes are then lost until the form on the following page is dispayed. Does anyone have any tricks for preventing this? Do I have to move away from using separate pages and use AJAX to embed the form in the page using something like <a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">GWT</a>, or will that still have the problem of lost keystrokes?</p>
[ { "answer_id": 61708, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 0, "selected": false, "text": "<html><head>\n<script language=javascript>\nIE=document.all;\nNN=document.layers;\nkys=\"\";\nif (NN){document.captureEvents(Event.KEYPRESS)}\ndocument.onkeypress=katch\nfunction katch(e){\nif (NN){kys+=e.which}\nif (IE){kys+=event.keyCode}\ndocument.forms[0].elements[0].value=kys\n}\n</script>\n</head>\n<body>\n<form><input></form>\n</body>\n</html>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2649/" ]
61,691
<p>The .NET Setup project seems to have a lot of options, but I don't see an "Uninstall" option. </p> <p>I'd prefer if people could "uninstall" from the standard "start menu" folder rather than send them to the control panel to uninstall my app, so can someone please tell me how to do this?</p> <p>Also, I am aware of non Microsoft installers that have this feature, but if possible I'd like to stay with the Microsoft toolkit.</p>
[ { "answer_id": 61697, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 4, "selected": true, "text": "msiexec /uninstall [path to msi or product code]\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050/" ]
61,692
<p>I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.</p> <p>I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?</p>
[ { "answer_id": 61697, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 4, "selected": true, "text": "msiexec /uninstall [path to msi or product code]\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849/" ]
61,699
<p>Until recently we were using Inno Setup for our installations, something I would like to continue doing, unless we can get an <a href="https://stackoverflow.com/questions/61691/how-to-add-uninstall-option-in-net-setup-project">uninstall option in the start menu</a> (thanks Giovanni Galbo), however we now need to GAC some external libraries, something I suspect is only doable (or at least only supported) though the .NET Setup Project.</p> <p>Is it possible to call a GAC'ing library from another setup application?</p>
[ { "answer_id": 1476781, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "* Added new [Files] section flag: gacinstall.\n* Added new [Files] section parameter: StrongAssemblyName.\n* Added new constants: {regasmexe}, {regasmexe32}, {regasmexe64}.\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
61,718
<p>When you are doing integration tests with either just your data access layer or the majority of the application stack. What is the best way prevent multiple tests from clashing with each other if they are run on the same database?</p>
[ { "answer_id": 61721, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "Load all fixture data.\n\nFor each test:\n\n BEGIN TRANSACTION\n\n # Yield control to user code\n\n ROLLBACK TRANSACTION\n\nEnd for each\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6369/" ]
61,733
<p>Which of the following is better code in c# and why?</p> <pre><code>((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString() </code></pre> <p>or</p> <pre><code>DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString() </code></pre> <p>Ultimately, is it better to cast or to parse?</p>
[ { "answer_id": 62619, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 1, "selected": false, "text": "DateTime.TryParse() ToShortDateString() private DateTime ParseDateTime(object data)\n{\n if (data is DateTime)\n {\n // already a date-time.\n return (DateTime)data;\n }\n else if (data is string)\n {\n // it's a local-format string.\n string dateString = (string)data;\n DateTime parseResult;\n if (DateTime.TryParse(dateString, CultureInfo.CurrentCulture,\n DateTimeStyles.AssumeLocal, out parseResult))\n {\n return parseResult;\n }\n else\n {\n throw new ArgumentOutOfRangeException(\"data\", \n \"could not parse this datetime:\" + data);\n }\n }\n else\n {\n // it's neither a DateTime or a string; that's a problem.\n throw new ArgumentOutOfRangeException(\"data\", \n \"could not understand data of this type\");\n }\n}\n ParseDateTime(g[0][\"MyUntypedDateField\").ToShortDateString();\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4246/" ]
61,735
<p>What is the best method for including a CSS or Javascript file for a specific node in Drupal 6.</p> <p>I want to create a page on my site that has a little javascript application running, so the CSS and javascript is specific to that page and would not want to be included in other page loads at all.</p>
[ { "answer_id": 61798, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {\n // the node ID of the node you want to modify\n $node_to_modify = 6;\n\n // do it!\n if($op == 'view' && $node->nid == $node_to_modify) {\n drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');\n drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css');\n }\n}\n" }, { "answer_id": 67901, "author": "Inferis", "author_id": 6251, "author_profile": "https://Stackoverflow.com/users/6251", "pm_score": 4, "selected": false, "text": "hook_nodeapi hook_nodeapi function mymodule_preprocess_node(&$variables) {\n $node = $variables['node'];\n if (!empty($node) && $node->nid == $the_specific_node_id) {\n drupal_add_js(drupal_get_path('module', 'mymodule') . \"/file.js\", \"module\");\n drupal_add_css(drupal_get_path('module', 'mymodule') . \"/file.css\", \"module\");\n }\n}\n function mytheme_preprocess_node(&$variables) {\n $node = $variables['node'];\n if (!empty($node) && $node->nid == $the_specific_node_id) {\n drupal_add_js(path_to_theme() . \"/file.js\", \"theme\");\n drupal_add_css(path_to_theme(). \"/file.css\", \"theme\");\n }\n}\n" }, { "answer_id": 628706, "author": "canen", "author_id": 43785, "author_profile": "https://Stackoverflow.com/users/43785", "pm_score": 3, "selected": false, "text": "$variables['styles'] drupal_get_css drupal_add_css drupal_add_js $variables['styles'] function mytheme_preprocess_node(&$variables) {\n $node = $variables['node'];\n if (!empty($node) && $node->nid == $the_specific_node_id) {\n drupal_add_js(path_to_theme() . \"/file.js\", \"theme\");\n drupal_add_css(path_to_theme(). \"/file.css\", \"theme\");\n $variables['styles'] = drupal_get_css();\n $variables['script'] = drupal_get_js();\n }\n}\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6277/" ]
61,739
<p>I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl:</p> <pre><code>DrawFrameControl(dc, &amp;rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO); </code></pre> <p>I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button.</p> <p>DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen.</p> <p>Anyone know how to do this? </p>
[ { "answer_id": 124770, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": false, "text": "GetSystemMetrics" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3655/" ]
61,747
<p>How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all.</p>
[ { "answer_id": 1286153, "author": "hbw", "author_id": 90155, "author_profile": "https://Stackoverflow.com/users/90155", "pm_score": 6, "selected": true, "text": "$ pecl download pdo_pgsql\n$ tar xzf PDO_PGSQL-1.0.2.tgz\n pecl sudo pecl $ cd PDO_PGSQL-1.0.2\n$ phpize\n$ ./configure --with-pdo-pgsql=/path/to/your/PostgreSQL/installation\n$ make && sudo make install\n pdo_pgsql.so /usr/lib/php/extensions/no-debug-non-zts-20060613/ php.ini extension=pdo_pgsql.so\n php.ini extension_dir pdo_pgsql.so extension_dir extension_dir = \"/usr/lib/php/extensions/no-debug-non-zts-20060613\"\n /System/Library/LaunchDaemons/org.apache.httpd.plist <key>ProgramArguments</key>\n<array>\n <string>arch</string>\n<string>-arch</string>\n<string>i386</string>\n" }, { "answer_id": 35874398, "author": "Mark Horgan", "author_id": 628709, "author_profile": "https://Stackoverflow.com/users/628709", "pm_score": 0, "selected": false, "text": "brew install php55-pdo-pgsql\n brew uninstall postgres\n LoadModule php5_module /usr/local/Cellar/php55/5.5.32/libexec/apache2/libphp5.so\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6371/" ]
61,750
<p>Task: implement paging of database records suitable for different RDBMS. Method should work for mainstream engines - MSSQL2000+, Oracle, MySql, etc.</p> <p>Please don't post RDBMS specific solutions, I know how to implement this for most of the modern database engines. I'm looking for the universal solution. Only temporary tables based solutions come to my mind at the moment.</p> <p><strong>EDIT:</strong><br> I'm looking for SQL solution, not 3rd party library.</p>
[ { "answer_id": 61757, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 0, "selected": false, "text": "Query q = ...;\nq.setFirstResult (0);\nq.setMaxResults (10);\n" }, { "answer_id": 61985, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "N - upper bound\nM - lower bound\n\ncreate #temp (Id int identity, originalId int)\n\ninsert into #temp(originalId)\nselect top N KeyColumn from MyTable\nwhere ...\n\nselect MyTable.* from MyTable\njoin #temp t on t.originalId = MyTable.KeyColumn\nwhere Id between M and M\norder by Id asc\n\ndrop #temp\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
61,805
<p>I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so:</p> <pre><code>public partial class Home : ViewMasterPage </code></pre> <p>On Home.Master there is a display statement like this:</p> <pre><code>&lt;%= ((GenericViewData)ViewData["Generic"]).Skin %&gt; </code></pre> <p>However, a developer on the team just changed the assembly references to Preview 4.</p> <p>Following this, the code will no longer populate ViewData with indexed values like the above.</p> <p>Instead, ViewData["Generic"] is null.</p> <p>As per <a href="https://stackoverflow.com/questions/18787/aspnet-mvc-user-control-viewdata">this question</a>, ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly.</p> <p>However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff).</p> <p>I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem.</p> <p>I have other solutions using the same technique that continue to work.</p> <p>Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)?</p>
[ { "answer_id": 61835, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 0, "selected": false, "text": "ViewData[\"CategoryName\"] = a.Name;\n <%= ViewData[\"CategoryName\"] %>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
61,817
<p>I am wondering what the best way to obtain the current domain is in ASP.NET?</p> <p>For instance:</p> <p><a href="http://www.domainname.com/subdir/" rel="noreferrer">http://www.domainname.com/subdir/</a> should yield <a href="http://www.domainname.com" rel="noreferrer">http://www.domainname.com</a> <a href="http://www.sub.domainname.com/subdir/" rel="noreferrer">http://www.sub.domainname.com/subdir/</a> should yield <a href="http://sub.domainname.com" rel="noreferrer">http://sub.domainname.com</a></p> <p>As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.</p>
[ { "answer_id": 61819, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 5, "selected": false, "text": "Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host \n int defaultPort = Request.IsSecureConnection ? 443 : 80;\nRequest.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host \n + (Request.Url.Port != defaultPort ? \":\" + Request.Url.Port : \"\");\n IsDefaultPort" }, { "answer_id": 61822, "author": "jwalkerjr", "author_id": 689, "author_profile": "https://Stackoverflow.com/users/689", "pm_score": -1, "selected": false, "text": "String domain = \"http://\" + Request.Url.Host\n" }, { "answer_id": 64045, "author": "derek lawless", "author_id": 400464, "author_profile": "https://Stackoverflow.com/users/400464", "pm_score": 1, "selected": false, "text": "NameValueCollection vars = HttpContext.Current.Request.ServerVariables;\nstring protocol = vars[\"SERVER_PORT_SECURE\"] == \"1\" ? \"https://\" : \"http://\";\nstring domain = vars[\"SERVER_NAME\"];\nstring port = vars[\"SERVER_PORT\"];\n" }, { "answer_id": 2326934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\nstring domain;\nUri url = HttpContext.Current.Request.Url;\ndomain= url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);\n" }, { "answer_id": 2878350, "author": "Carlos Muñoz", "author_id": 186133, "author_profile": "https://Stackoverflow.com/users/186133", "pm_score": 9, "selected": true, "text": "Request.Url.Authority $\"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}\"\n" }, { "answer_id": 6727511, "author": "Korayem", "author_id": 80434, "author_profile": "https://Stackoverflow.com/users/80434", "pm_score": 4, "selected": false, "text": "Request.Url.Authority" }, { "answer_id": 8686506, "author": "izlence", "author_id": 1123996, "author_profile": "https://Stackoverflow.com/users/1123996", "pm_score": 5, "selected": false, "text": "Request.Url.GetLeftPart(UriPartial.Authority)\n" }, { "answer_id": 29385136, "author": "Darren", "author_id": 329367, "author_profile": "https://Stackoverflow.com/users/329367", "pm_score": 0, "selected": false, "text": " var relativePath = \"\"; // or whatever-path-you-want\n var uriBuilder = new UriBuilder\n {\n Host = Request.Url.Host,\n Path = relativePath,\n Scheme = Request.Url.Scheme\n };\n\n if (!Request.Url.IsDefaultPort)\n uriBuilder.Port = Request.Url.Port;\n\n var fullPathToUse = uriBuilder.ToString();\n" }, { "answer_id": 45777954, "author": "Ramin Bateni", "author_id": 1474613, "author_profile": "https://Stackoverflow.com/users/1474613", "pm_score": 2, "selected": false, "text": "Request.GetFullDomain() // Add this class to your project\npublic static class HttpRequestExtensions{\n public static string GetFullDomain(this HttpRequestBase request)\n {\n var uri= request?.UrlReferrer;\n if (uri== null)\n return string.Empty;\n return uri.Scheme + Uri.SchemeDelimiter + uri.Authority;\n }\n}\n\n// Now Use it like this:\nRequest.GetFullDomain();\n// Example output: https://example.com:5031\n// Example output: http://example.com:5031\n" }, { "answer_id": 63976140, "author": "Dastan Alybaev", "author_id": 10049738, "author_profile": "https://Stackoverflow.com/users/10049738", "pm_score": 1, "selected": false, "text": "private readonly IHttpContextAccessor _contextAccessor;\n public SomeClass(IHttpContextAccessor contextAccessor)\n{\n _contextAccessor = contextAccessor;\n}\n private string GenerateFullDomain()\n{\n string domain = _contextAccessor.HttpContext.Request.Host.Value;\n string scheme = _contextAccessor.HttpContext.Request.Scheme;\n string delimiter = System.Uri.SchemeDelimiter;\n string fullDomainToUse = scheme + delimiter + domain;\n return fullDomainToUse;\n}\n//Examples of usage GenerateFullDomain() method:\n//https://example.com:5031\n//http://example.com:5031\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
61,838
<p>If I have something like a UILabel linked to a xib file, do I need to release it on dealloc of my view? The reason I ask is because I don't alloc it, which makes me think I don't need to release it either? eg (in the header):</p> <pre><code>IBOutlet UILabel *lblExample; </code></pre> <p>in the implementation:</p> <pre><code>.... [lblExample setText:@"whatever"]; .... -(void)dealloc{ [lblExample release];//????????? } </code></pre>
[ { "answer_id": 61867, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 0, "selected": false, "text": "@property (nonatomic, retain) UILabel *lblExample;\n" }, { "answer_id": 191935, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": true, "text": "@interface MyController : MySuperclass {\n Control *uiElement;\n}\n@property (nonatomic, retain) IBOutlet Control *uiElement;\n@end\n\n\n@implementation MyController\n\n@synthesize uiElement;\n\n- (void)dealloc {\n [uiElement release];\n [super dealloc];\n}\n@end\n setView: - (void)setView:(UIView *)newView {\n if (newView == nil) {\n self.uiElement = nil;\n }\n [super setView:aView];\n}\n dealloc setView: self.anOutlet = nil dealloc dealloc nil dealloc - (void)dealloc {\n // release outlets and set variables to nil\n [anOutlet release], anOutlet = nil;\n [super dealloc];\n}\n" }, { "answer_id": 567962, "author": "Wil Shipley", "author_id": 30602, "author_profile": "https://Stackoverflow.com/users/30602", "pm_score": 2, "selected": false, "text": "[anOutlet release], anOutlet = nil;\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
61,861
<p>I would like to make my web control more readable in design mode, basically I want the tag declaration to look like:</p> <pre><code>&lt;cc1:Ctrl ID="Value1" runat="server"&gt; &lt;Values&gt;string value 1&lt;/Value&gt; &lt;Values&gt;string value 2&lt;/Value&gt; &lt;/cc1:Ctrl&gt; </code></pre> <p>Lets say I have a private variable in the code behind:</p> <pre><code>List&lt;string&gt; values = new List&lt;string&gt;(); </code></pre> <p>So how can I make my user control fill out the private variable with the values that are declared in the markup?</p> <hr> <p>Sorry I should have been more explicit. Basically I like the functionality that the ITemplate provides (<a href="http://msdn.microsoft.com/en-us/library/aa719834.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa719834.aspx</a>)</p> <p>But in this case you need to know at runtime how many templates can be instansitated, i.e.</p> <pre><code>void Page_Init() { if (messageTemplate != null) { for (int i=0; i&lt;5; i++) { MessageContainer container = new MessageContainer(i); messageTemplate.InstantiateIn(container); msgholder.Controls.Add(container); } } </code></pre> <p>}</p> <p>In the given example the markup looks like:</p> <pre><code>&lt;acme:test runat=server&gt; &lt;MessageTemplate&gt; Hello #&lt;%# Container.Index %&gt;.&lt;br&gt; &lt;/MessageTemplate&gt; &lt;/acme:test&gt; </code></pre> <p>Which is nice and clean, it does not have any tag prefixes etc. I really want the nice clean tags.</p> <p>I'm probably being silly in wanting the markup to be clean, I'm just wondering if there is something simple that I'm missing.</p>
[ { "answer_id": 61925, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 0, "selected": false, "text": " <asp:ListBox ID=\"ListBox1\" runat=\"server\">\n <asp:ListItem>String 1</asp:ListItem>\n <asp:ListItem>String 2</asp:ListItem>\n <asp:ListItem>String 3</asp:ListItem>\n </asp:ListBox><br />\n List<String> values = new List<String>();\n\n foreach (ListItem item in ListBox1.Items)\n {\n values.Add(item.Value.ToString());\n }\n" }, { "answer_id": 62589, "author": "Luca Molteni", "author_id": 4206, "author_profile": "https://Stackoverflow.com/users/4206", "pm_score": 3, "selected": true, "text": "[PersistenceMode(PersistenceMode.InnerProperty)]\n <%@ Register Namespace=\"MyNamespace\" TagPrefix=\"Pref\" %>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2758/" ]
61,872
<p>We are rewriting our legacy <a href="https://en.wikipedia.org/wiki/Accounting_information_system" rel="nofollow noreferrer">accounting system</a> in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal.</p> <p>What is your recommendation?</p> <p>Should the float or decimal data type be used for dollar amounts?</p> <p>What are some of the pros and cons for either?</p> <p>One <em>con</em> mentioned in our <a href="https://en.wikipedia.org/wiki/Scrum_%28software_development%29#Daily_scrum" rel="nofollow noreferrer">daily scrum</a> was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions.</p> <p>Another <em>con</em> is all displays and printed amounts have to have a <em>format statement</em> that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct. (i.e. 10.2 or 10.2546)</p> <p>A <em>pro</em> is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2).</p>
[ { "answer_id": 62071, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "money" }, { "answer_id": 62493, "author": "David T. Macknet", "author_id": 6850, "author_profile": "https://Stackoverflow.com/users/6850", "pm_score": 0, "selected": false, "text": "FORMAT() floor ceiling money smallmoney" }, { "answer_id": 66678, "author": "TSK", "author_id": 9959, "author_profile": "https://Stackoverflow.com/users/9959", "pm_score": 8, "selected": true, "text": "m/2^n m n m/(2^n*5^n) factor 5 0.3 = 3/(2^1 * 5^1) = 0.3\n\n0.3 = [0.25/0.5] [0.25/0.375] [0.25/3.125] [0.2825/3.125]\n\n 1/4 1/8 1/16 1/32\n 0.049999999999 0.0500000000 0.4999 0.5000" }, { "answer_id": 70868, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 2, "selected": false, "text": "100 1.00 int cents = num % 100;\nint dollars = (num - cents) / 100;\nprintf(\"%d.%02d\", dollars, cents);\n" }, { "answer_id": 3991553, "author": "Lars Bohl", "author_id": 438960, "author_profile": "https://Stackoverflow.com/users/438960", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\nint main()\n{\n printf(\"Mapping 100 numbers between 0 and 1 \");\n printf(\"to their hexadecimal exponential form (HEF).\\n\");\n printf(\"Most of them do not equal their HEFs. That means \");\n printf(\"that their representations as floats \");\n printf(\"differ from their actual values.\\n\");\n double f = 0.01;\n int i;\n for (i = 0; i < 100; i++) {\n printf(\"%1.2f -> %a\\n\",f*i,f*i);\n }\n printf(\"Printing 128 'float-compatible' numbers \");\n printf(\"together with their HEFs for comparison.\\n\");\n f = 0x1p-7; // ==0.0071825\n for (i = 0; i < 0x80; i++) {\n printf(\"%1.7f -> %a\\n\",f*i,f*i);\n }\n return 0;\n}\n" }, { "answer_id": 4002088, "author": "BrokeMyLegBiking", "author_id": 97686, "author_profile": "https://Stackoverflow.com/users/97686", "pm_score": 0, "selected": false, "text": " DECLARE @Float1 float, @Float2 float, @Float3 float, @Float4 float; \n SET @Float1 = 54; \n SET @Float2 = 3.1; \n SET @Float3 = 0 + @Float1 + @Float2; \n SELECT @Float3 - @Float1 - @Float2 AS \"Should be 0\";\n\nShould be 0 \n---------------------- \n1.13797860024079E-15\n DECLARE @Fixed1 decimal(8,4), @Fixed2 decimal(8,4), @Fixed3 decimal(8,4); \nSET @Fixed1 = 54; \nSET @Fixed2 = 0.03; \nSET @Fixed3 = 1 * @Fixed1 / @Fixed2; \nSELECT @Fixed3 / @Fixed1 * @Fixed2 AS \"Should be 1\";\n\nShould be 1 \n--------------------------------------- \n0.99999999999999900\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4964/" ]
61,882
<p>In a typical handheld/portable embedded system device Battery life is a major concern in design of H/W, S/W and the features the device can support. From the Software programming perspective, one is aware of MIPS, Memory(Data and Program) optimized code. I am aware of the H/W Deep sleep mode, Standby mode that are used to clock the hardware at lower Cycles or turn of the clock entirel to some unused circutis to save power, but i am looking for some ideas from that point of view:</p> <p>Wherein my code is running and it needs to keep executing, given this how can I write the code "power" efficiently so as to consume minimum watts?</p> <p>Are there any special programming constructs, data structures, control structures which i should look at to achieve minimum power consumption for a given functionality.</p> <p>Are there any s/w high level design considerations which one should keep in mind at time of code structure design, or during low level design to make the code as power efficient(Least power consuming) as possible? </p>
[ { "answer_id": 61912, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 5, "selected": false, "text": "1800 INFORMATION" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
61,888
<p>Is it possible to use <a href="http://subversion.apache.org/" rel="noreferrer">Apache Subversion</a> (SVN) as general purpose backup tool? (As a kind of <a href="http://en.wikipedia.org/wiki/Rsync" rel="noreferrer">rsync</a> alternative.)</p>
[ { "answer_id": 15548768, "author": "user2195264", "author_id": 2195264, "author_profile": "https://Stackoverflow.com/users/2195264", "pm_score": 1, "selected": false, "text": "cd svnauto #!/bin/sh\nexport LANG=en_US.UTF-8 && cd /my/directory && echo Starting backup $(date) > /root/backup_log.txt && /root/svnauto >> /root/backup_log.txt 2>&1 && echo Finished backup. >> /root/backup_log.txt && cat /root/backup_log.txt\n /my/directory svnauto /root export" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897/" ]