qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
242,182
<p>I have a page with a "Print" link that takes the user to a printer-friendly page. The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page. How can I do this with javascript?</p>
[ { "answer_id": 242190, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 9, "selected": true, "text": "<pre><code>window.print(); \n</code></pre>\n\n<p>unless you mean a custom looking popup.</p>\n" }, { "answer_id": 242192, "author": "mmiika", "author_id": 6846, "author_profile": "https://Stackoverflow.com/users/6846", "pm_score": 6, "selected": false, "text": "<p>You could do</p>\n\n<pre><code>&lt;body onload=\"window.print()\"&gt;\n...\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 242200, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 3, "selected": false, "text": "<p>I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.</p>\n\n<pre><code>&lt;a href=\"javascript:alert('Please be sure to set your printer to Landscape.');window.print();\"&gt;Print Me...&lt;/a&gt;\n</code></pre>\n\n<p>or </p>\n\n<pre><code>&lt;body onload=\"alert('Please be sure to set your printer to Landscape.');window.print();\"&gt;\netc.\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 17352555, "author": "Daryl H", "author_id": 2088442, "author_profile": "https://Stackoverflow.com/users/2088442", "pm_score": 5, "selected": false, "text": "<p>I like this, so that you can add whatever fields you want and print it that way.</p>\n\n<pre><code>function printPage() {\n var w = window.open();\n\n var headers = $(\"#headers\").html();\n var field= $(\"#field1\").html();\n var field2= $(\"#field2\").html();\n\n var html = \"&lt;!DOCTYPE HTML&gt;\";\n html += '&lt;html lang=\"en-us\"&gt;';\n html += '&lt;head&gt;&lt;style&gt;&lt;/style&gt;&lt;/head&gt;';\n html += \"&lt;body&gt;\";\n\n //check to see if they are null so \"undefined\" doesnt print on the page. &lt;br&gt;s optional, just to give space\n if(headers != null) html += headers + \"&lt;br/&gt;&lt;br/&gt;\";\n if(field != null) html += field + \"&lt;br/&gt;&lt;br/&gt;\";\n if(field2 != null) html += field2 + \"&lt;br/&gt;&lt;br/&gt;\";\n\n html += \"&lt;/body&gt;\";\n w.document.write(html);\n w.window.print();\n w.document.close();\n};\n</code></pre>\n" }, { "answer_id": 38635307, "author": "Limitless isa", "author_id": 1256632, "author_profile": "https://Stackoverflow.com/users/1256632", "pm_score": -1, "selected": false, "text": "<p>if problem:</p>\n\n<pre><code> mywindow.print();\n</code></pre>\n\n<p>altenative using: </p>\n\n<pre><code>'&lt;scr'+'ipt&gt;print()&lt;/scr'+'ipt&gt;'\n</code></pre>\n\n<p>Full:</p>\n\n<pre><code> $('.print-ticket').click(function(){\n\n var body = $('body').html();\n var ticket_area = '&lt;aside class=\"widget tickets\"&gt;' + $('.widget.tickets').html() + '&lt;/aside&gt;';\n\n $('body').html(ticket_area);\n var print_html = '&lt;html lang=\"tr\"&gt;' + $('html').html() + '&lt;scr'+'ipt&gt;print()&lt;/scr'+'ipt&gt;' + '&lt;/html&gt;'; \n $('body').html(body);\n\n var mywindow = window.open('', 'my div', 'height=600,width=800');\n mywindow.document.write(print_html);\n mywindow.document.close(); // necessary for IE &gt;= 10'&lt;/html&gt;'\n mywindow.focus(); // necessary for IE &gt;= 10\n //mywindow.print();\n mywindow.close();\n\n return true;\n });\n</code></pre>\n" }, { "answer_id": 47117332, "author": "thestar", "author_id": 2418867, "author_profile": "https://Stackoverflow.com/users/2418867", "pm_score": 2, "selected": false, "text": "<p>You can tie it to button or on load of the page.</p>\n\n<pre><code>window.print();\n</code></pre>\n" }, { "answer_id": 56296607, "author": "Dan Sinclair", "author_id": 1304050, "author_profile": "https://Stackoverflow.com/users/1304050", "pm_score": 3, "selected": false, "text": "<p>If you just have a link without a click event handler:</p>\n\n<pre><code>&lt;a href=\"javascript:window.print();\"&gt;Print Page&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 58851876, "author": "James Heffer", "author_id": 3656152, "author_profile": "https://Stackoverflow.com/users/3656152", "pm_score": 2, "selected": false, "text": "<p>I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor)...</p>\n\n<p>You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)</p>\n\n<p>IN YOUR RAZOR PAGE: </p>\n\n<pre><code>@inject IJSRuntime JSRuntime\n</code></pre>\n\n<p>Once you have that injected, create a button with a click event that calls a C# method: </p>\n\n<pre><code>&lt;MatFAB Icon=\"@MatIconNames.Print\" OnClick=\"@(async () =&gt; await print())\"&gt;&lt;/MatFAB&gt;\n</code></pre>\n\n<p>(or something more simple if you don't use MatBlazor)</p>\n\n<pre><code>&lt;button @onclick=\"@(async () =&gt; await print())\"&gt;PRINT&lt;/button&gt;\n</code></pre>\n\n<p>For the C# method: </p>\n\n<pre><code>public async Task print()\n{\n await JSRuntime.InvokeVoidAsync(\"printDocument\");\n}\n</code></pre>\n\n<p>NOW IN YOUR index.html: </p>\n\n<pre><code>&lt;script&gt;\n function printDocument() {\n window.print();\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it's calls such as InvokeVoidAsync </p>\n\n<p>PS: If you wanted to message box in asp net core for instance: </p>\n\n<pre><code>await JSRuntime.InvokeAsync&lt;string&gt;(\"alert\", \"Hello user, this is the message box\");\n</code></pre>\n\n<p>To have a confirm message box: </p>\n\n<pre><code>bool question = await JSRuntime.InvokeAsync&lt;bool&gt;(\"confirm\", \"Are you sure you want to do this?\");\n if(question == true)\n {\n //user clicked yes\n }\n else\n {\n //user clicked no\n }\n</code></pre>\n\n<p>Hope this helps :) </p>\n" }, { "answer_id": 70298748, "author": "John Nico Novero", "author_id": 9923490, "author_profile": "https://Stackoverflow.com/users/9923490", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;script&gt;\n const _print = () =&gt; {\n window.print();\n }\n&lt;/script&gt;\n</code></pre>\n<p>or</p>\n<pre><code>&lt;body onload=&quot;window.print();&quot;&gt;&lt;/body&gt;\n</code></pre>\n<p>see the documentation here : <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/print\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Window/print</a></p>\n" }, { "answer_id": 73668592, "author": "dvicemuse", "author_id": 1155184, "author_profile": "https://Stackoverflow.com/users/1155184", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question, but after fighting with this similar issue, I figured out a way to open a print screen and <strong>NOT</strong> have to open a new tab, and <strong>not</strong> have to enable popups.</p>\n<p>Hopefully, this helps someone else.</p>\n<pre><code>/*\n Example:\n &lt;a href=&quot;//example.com&quot; class=&quot;print-url&quot;&gt;Print&lt;/a&gt;\n*/\n\n//LISTEN FOR PRINT URL ITEMS TO BE CLICKED\n$(document).off('click.PrintUrl').on('click.PrintUrl', '.print-url', function(e){\n\n //PREVENT OTHER CLICK EVENTS FROM PROPAGATING\n e.preventDefault();\n\n //TRY TO ASK THE URL TO TRIGGER A PRINT DIALOGUE BOX\n printUrl($(this).attr('href'));\n});\n\n//TRIGGER A PRINT DIALOGE BOX FROM A URL\nfunction printUrl(url) { \n\n //CREATE A HIDDEN IFRAME AND APPEND IT TO THE BODY THEN WAIT FOR IT TO LOAD\n $('&lt;iframe src=&quot;'+url+'&quot;&gt;&lt;/iframe&gt;').hide().appendTo('body').on('load', function(){\n \n var oldTitle = $(document).attr('title'); //GET THE ORIGINAL DOCUMENT TITLE\n var that = $(this); //STORE THIS IFRAME AS A VARIABLE \n var title = $(that).contents().find('title').text(); //GET THE IFRAME TITLE\n $(that).focus(); //CALL THE IFRAME INTO FOCUS (FOR OLDER BROWSERS) \n\n //SET THE DOCUMENT TITLE FROM THE IFRAME (THIS NAMES THE DOWNLOADED FILE)\n if(title &amp;&amp; title.length) $(document).attr('title', title);\n \n //TRIGGER THE IFRAME TO CALL THE PRINT\n $(that)[0].contentWindow.print();\n\n //LISTEN FOR THE PRINT DIALOGUE BOX TO CLOSE\n $(window).off('focus.PrintUrl').on('focus.PrintUrl', function(e){\n e.stopPropagation(); //PREVENT OTHER WINDOW FOCUS EVENTS FROM RUNNING \n $(that).remove(); //GET RID OF THE IFRAME\n if(title &amp;&amp; title.length) $(document).attr('title', oldTitle); //RESET THE PAGE TITLE\n $(window).off('focus.PrintUrl'); //STOP LISTENING FOR WINDOW FOCUS\n });\n }); \n};\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I have a page with a "Print" link that takes the user to a printer-friendly page. The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page. How can I do this with javascript?
``` window.print(); ``` unless you mean a custom looking popup.
242,255
<p>If I have class names such as "left", "right", "clear" and xhtml like</p> <pre><code>&lt;a href="index.php" class="right continueLink"&gt;Continue&lt;/a&gt; </code></pre> <p>With CSS like</p> <pre><code>.right { float: right; } </code></pre> <p>I know it's not a semantic name, but it does make things much easier sometimes.</p> <p>Anyway, what are your thoughts?</p>
[ { "answer_id": 242259, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>It might be advisable to avoid names that are the same as values in the CSS specs to avoid confusion. Especially in situations where multiple developers work on the same application.</p>\n\n<p>Other than that I see no problem. I would qualify the right or left name like this: menuleft, menuright etc.</p>\n" }, { "answer_id": 242277, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": true, "text": "<p>I don't think that's a very good idea. Now when you (or a future maintainer) go to change your website layout, you'll either have to change <code>.right</code> to <code>{float:left;}</code> (obviously a bad idea) or go through all your HTML files and change <code>right</code> to <code>left</code>.</p>\n\n<p>Why do you want that particular link to be floated right, and the other <code>.continueLink</code>'s not to? Use the answer to that question to choose a more descriptive class name for that link.</p>\n" }, { "answer_id": 242299, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "<p>css is about presentation of the <strong><em>structure</em></strong> of your html page.</p>\n\n<p>Meaning its classes should represent the structure of the document ('article', 'extra-links', 'glossary', 'introduction', 'conclusion', ...). </p>\n\n<p>You should avoid any class linked to a <em>physical</em> representation ('left', 'right', 'footnotes', 'sidenotes', ...), because, as the <a href=\"http://www.csszengarden.com/\" rel=\"noreferrer\">Zen Garden</a> so clearly illustrates, you can decide to place any div in very different and various ways.</p>\n" }, { "answer_id": 242325, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>The purists will say don't do it, and the pragmatists will say it's fine. But would the purists define <code>.right</code> as <code>float: left</code>?</p>\n" }, { "answer_id": 242501, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 1, "selected": false, "text": "<p>Being a purist, I say no don't do it. For reasons mentioned earlier.</p>\n\n<p>Being a pragmatist, I just wanted to say that never have I seen website rework that involved pure html changes without css, or pure css without html, simply because both parts are being developed with the other in mind. So, in reality, if somebody else would EVER need to change the page, I bet my salary they will change both html and css.</p>\n\n<p>The above is something that collegue purists around often tend to ignore, even though it's reality. But bottom line; no, avoid using a className such as \"right\". :-)</p>\n" }, { "answer_id": 242705, "author": "Hauge", "author_id": 17368, "author_profile": "https://Stackoverflow.com/users/17368", "pm_score": 0, "selected": false, "text": "<p>.right and other classes like that, certainly makes it quick to write create a tag with a <code>float:right</code> rule attached to it, but I think this method has more disadvantages than advantages:</p>\n\n<p>Often a class-style with a single <code>float:right;</code> in it will lack something, your example wil only float right if the other class rule contains a <code>display:block</code> in it, since an \"a\" tag is not a block level element. Also floating elements more often than not needs to have width an height attached. This means that the code in your example needs additional code to do what it says, and you have to search in two places when you have to change your css.</p>\n\n<p>I tend to style my html by dividing the page into different div-tags with unique id's, and then styling elements in these div by inheritance like this.</p>\n\n<pre><code>div#sidebar { float:right; width:200px; }\ndiv#sidebar ul { list-style-type:none; }\n</code></pre>\n\n<p>This makes it possible to partition my css files, so that it is easy to find the css-code that styles a particular tag, but if you introduce .right and other classes you are starting to disperse the rules into different areas of the css file, making the site more difficult to maintain.</p>\n\n<p>I think the idea of having a very generic classes is born from the wish of making it possible to change the entire layout of the site by changing a couple of rules in a stylesheet, but I must say that in my 8 years of website development with 30+, different sites under my belt i haven't once changed the layout of a website and reused the HTML. </p>\n\n<p>What I have done countless times is making small adjustments to regions of pages, either due to small changes in the design or to the introduction of new browsers. So I'm all for keeping my css divided into neat chunks that makes it easy to find the rules I am looking for, and not putting the code in different places to achieve a shorter stylesheet.</p>\n\n<p>Regards \nJesper Hauge</p>\n" }, { "answer_id": 242739, "author": "Samuel Cotterall", "author_id": 15935, "author_profile": "https://Stackoverflow.com/users/15935", "pm_score": 0, "selected": false, "text": "<p>Yeah, semantically speaking it is wrong, but, for example, there are times when I'm positioning images within a block of body copy and I'll give them the class \"right\".</p>\n\n<p>Maybe \"alt\" is a more suitable class name.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
If I have class names such as "left", "right", "clear" and xhtml like ``` <a href="index.php" class="right continueLink">Continue</a> ``` With CSS like ``` .right { float: right; } ``` I know it's not a semantic name, but it does make things much easier sometimes. Anyway, what are your thoughts?
I don't think that's a very good idea. Now when you (or a future maintainer) go to change your website layout, you'll either have to change `.right` to `{float:left;}` (obviously a bad idea) or go through all your HTML files and change `right` to `left`. Why do you want that particular link to be floated right, and the other `.continueLink`'s not to? Use the answer to that question to choose a more descriptive class name for that link.
242,264
<p>I am digging into LINQ--trying to understand basic models (it seems pretty cool to me). The code below is the code to perform before committing an update. </p> <pre><code> Linq01.Account acc = context.Accounts.Single( pc =&gt; pc.AccountID == AccountID ); acc.Name = textboxAccountNameRead.Text.Trim(); context.SubmitChanges(); </code></pre> <p>So far, so good. But what do you do if the Single() method failed--if the account ID wasn't found? </p> <p>Thank you!</p>
[ { "answer_id": 242266, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 4, "selected": true, "text": "<p>You should use <code>SingleOrDefault</code>, if the query does not return a value you can check it against null:</p>\n\n<pre><code>var acc = context.Accounts.SingleOrDefault(pc =&gt; pc.AccountId == AccountId);\nif(acc != null)\n{\n acc.Name = textboxAccountNameRead.Text.Trim();\n context.SubmitChanges();\n}\n</code></pre>\n" }, { "answer_id": 242394, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>To add to Slace's answer, if you call Single and then account ID wasn't found, it will throw an exception. In <em>some</em> cases that's more appropriate than returning null and explicitly handling it.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536/" ]
I am digging into LINQ--trying to understand basic models (it seems pretty cool to me). The code below is the code to perform before committing an update. ``` Linq01.Account acc = context.Accounts.Single( pc => pc.AccountID == AccountID ); acc.Name = textboxAccountNameRead.Text.Trim(); context.SubmitChanges(); ``` So far, so good. But what do you do if the Single() method failed--if the account ID wasn't found? Thank you!
You should use `SingleOrDefault`, if the query does not return a value you can check it against null: ``` var acc = context.Accounts.SingleOrDefault(pc => pc.AccountId == AccountId); if(acc != null) { acc.Name = textboxAccountNameRead.Text.Trim(); context.SubmitChanges(); } ```
242,284
<p>While surfing, I came to know that somebody has done Tower of Hanoi using vim. WOW!!!</p> <p>Can you people share what all cool things you have been doing in vim.</p> <p>Edit: Not sure about the Tower of Hanoi solution using vim being all that useful. But I think this question should be re-opened to allow people to comment on any useful things that they've done using vim. For me? See my answer below. (-:</p>
[ { "answer_id": 245320, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<p>I was working on a system that had massive log files. We're talking 30,000 10MB logs.</p>\n\n<p>Per day!</p>\n\n<p>Distinguishing between log messages that were coming from the middleware (same company but custom rolled) and our application was getting tedious.</p>\n\n<p>That is until I wrote some custom vim syntax parsing so that anything vim displayed in green was from the middleware (done by the guys in Sophia Antipolis near Cannes) as opposed to anything vim displayed in blue that was from our application software that sat over the top of the SA code.</p>\n\n<p>I also added highlighting to really make exceptions stand out with white lettering on a read background!</p>\n\n<p>Made life so much easier! And it wasn't that hard to do!</p>\n\n<p>Thanks vim!</p>\n" }, { "answer_id": 245329, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 3, "selected": false, "text": "<p>I'm using vim to syntax-color code in my <a href=\"http://www.spinellis.gr/blog\" rel=\"noreferrer\">blog</a> and <a href=\"http://www.dmst.aueb.gr/dds/enotes.html\" rel=\"noreferrer\">lecture notes</a>. A single Perl line</p>\n\n<pre><code>system \"$vimrt\\\\gvim.exe\", qq{ \n -c \"edit /tmp/tmpcode.$ext \" \n -c \"source $vimrt/syntax/2html.vim\" \n -c \"write! /tmp/tmpcode.html\" \n -c \"qa!\"};\n</code></pre>\n\n<p>converts the code into nicely-colored HTML. I know there are stand-alone tools for doing this, but vim is already installed on my system, so this is one less tool to install.</p>\n" }, { "answer_id": 245341, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 2, "selected": false, "text": "<p>I couple of months ago I wrote a vim script to <a href=\"http://www.spinellis.gr/blog/20080825/\" rel=\"nofollow noreferrer\">save a complete history of all my edits</a>, so I could inspect and measure my programming performance.</p>\n" }, { "answer_id": 245527, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "<p>I'm using vim a lot recently to edit XML files. I got the <a href=\"http://www.vim.org/scripts/script.php?script_id=301\" rel=\"nofollow noreferrer\">xmledit</a> plugin for vim working. Now vim creates closing tags for me, I can enclose highlighted text in an XML tag, and jump to balancing XML tags. It saves a lot of repetitive typing, reduces mistakes, and increases my productivity.</p>\n" }, { "answer_id": 245971, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "<p><code>vim</code> has a set of commands that integrate with development tools such as <code>make</code>, <code>gcc</code>, and <code>ctags</code>. You can build your project, navigate to warnings and errors, and jump to function/variable definitions without leaving the editor:</p>\n\n<ul>\n<li><code>:make</code> builds the project. </li>\n<li><code>:cl</code> lists warnings and errors.</li>\n<li><code>:cc</code> takes you to the to line in the source code that generated the current error.</li>\n<li><code>:cn</code> navigates to the next error.</li>\n<li><code>:cp</code> navigates to the previous error.</li>\n<li><code>:tag name</code> navigates to the definition of the token <code>name</code>. (See <code>man ctags</code> to generate an index of tokens; sometimes <code>make tags</code> will do this automatically.)</li>\n<li>Pressing <code>Ctrl+]</code> navigates to the definition of the token under the cursor.</li>\n</ul>\n" }, { "answer_id": 516320, "author": "Joe Holloway", "author_id": 48837, "author_profile": "https://Stackoverflow.com/users/48837", "pm_score": 3, "selected": false, "text": "<p>I found myself struggling to be more efficient in vim compared to other non-modal text editors until I learned about \"text-objects\". Understanding this concept really improved my productivity and also gave me a new way of looking at text which in turn made it easier to deeply understand other vim concepts that I had only understood ephemerally before.</p>\n\n<p>:help text-objects</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29405/" ]
While surfing, I came to know that somebody has done Tower of Hanoi using vim. WOW!!! Can you people share what all cool things you have been doing in vim. Edit: Not sure about the Tower of Hanoi solution using vim being all that useful. But I think this question should be re-opened to allow people to comment on any useful things that they've done using vim. For me? See my answer below. (-:
I'm using vim to syntax-color code in my [blog](http://www.spinellis.gr/blog) and [lecture notes](http://www.dmst.aueb.gr/dds/enotes.html). A single Perl line ``` system "$vimrt\\gvim.exe", qq{ -c "edit /tmp/tmpcode.$ext " -c "source $vimrt/syntax/2html.vim" -c "write! /tmp/tmpcode.html" -c "qa!"}; ``` converts the code into nicely-colored HTML. I know there are stand-alone tools for doing this, but vim is already installed on my system, so this is one less tool to install.
242,295
<blockquote> <p><strong>EDIT</strong>: This question duplicates <a href="https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number#111173">How to access the current Subversion build number?</a> (Thanks for the heads up, Charles!)</p> </blockquote> <p>Hi there,</p> <p>This question is similar to <a href="https://stackoverflow.com/questions/16248/getting-the-subversion-repository-number-into-code">Getting the subversion repository number into code</a></p> <p>The differences being:</p> <ol> <li><p>I would like to add the revision number to Python</p></li> <li><p>I want the revision of the repository (not the checked out file)</p></li> </ol> <p>I.e. I would like to extract the Revision number from the return from 'svn info', likeso:</p> <p>$ svn info</p> <pre><code>Path: . URL: svn://localhost/B/trunk Repository Root: svn://localhost/B Revision: 375 Node Kind: directory Schedule: normal Last Changed Author: bmh Last Changed Rev: 375 Last Changed Date: 2008-10-27 12:09:00 -0400 (Mon, 27 Oct 2008) </code></pre> <p>I want a variable with 375 (the Revision). It's easy enough with put $Rev$ into a variable to keep track of changes on a file. However, I would like to keep track of the repository's version, and I understand (and it seems based on my tests) that $Rev$ only updates when the file changes.</p> <p>My initial thoughts turn to using the svn/libsvn module built in to Python, though I can't find any documentation on or examples of how to use them.</p> <p>Alternatively, I've thought calling 'svn info' and regex'ing the code out, though that seems rather brutal. :)</p> <p>Help would be most appreciated.</p> <p>Thanks &amp; Cheers.</p>
[ { "answer_id": 242327, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 1, "selected": false, "text": "<p>I use a technique very similar to this in order to show the current subversion revision number in my shell:</p>\n\n<pre><code>svnRev=$(echo \"$(svn info)\" | grep \"^Revision\" | awk -F\": \" '{print $2};')\necho $svnRev\n</code></pre>\n\n<p>It works very well for me.</p>\n\n<p>Why do you want the python files to change every time the version number of the entire repository is incremented? This will make doing things like doing a diff between two files annoying if one is from the repo, and the other is from a tarball..</p>\n" }, { "answer_id": 242508, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>Python has direct bindings to libsvn, so you don't need to invoke the command line client at all. See <a href=\"http://jtauber.com/python_subversion_binding/\" rel=\"nofollow noreferrer\">this blog post</a> for more details.</p>\n\n<p>EDIT: You can basically do something like this:</p>\n\n<pre><code>from svn import fs, repos, core\nrepository = repos.open(root_path)\nfs_ptr = repos.fs(repository)\nyoungest_revision_number = fs.youngest_rev(fs_ptr)\n</code></pre>\n" }, { "answer_id": 242515, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 3, "selected": true, "text": "<p>There is a command called <code>svnversion</code> which comes with subversion and is meant to solve exactly that kind of problem.</p>\n" }, { "answer_id": 242634, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 1, "selected": false, "text": "<p>If you want to have a variable in one source file that can be set to the current working copy revision, and does not replay on subversion and a working copy being actually available at the time you run your program, then <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html\" rel=\"nofollow noreferrer\">SubWCRev</a> my be your solution.</p>\n\n<p>There also seems to be a linux port called <a href=\"http://svnwcrev.tigris.org/\" rel=\"nofollow noreferrer\">SVNWCRev</a></p>\n\n<p>Both perform substitution of $WCREV$ with the highest commit level of the working copy. Other information may also be provided.</p>\n" }, { "answer_id": 243088, "author": "pobk", "author_id": 7829, "author_profile": "https://Stackoverflow.com/users/7829", "pm_score": 2, "selected": false, "text": "<p>Stolen directly from django:</p>\n\n<pre><code>def get_svn_revision(path=None):\n rev = None\n if path is None:\n path = MODULE.__path__[0]\n entries_path = '%s/.svn/entries' % path\n\n if os.path.exists(entries_path):\n entries = open(entries_path, 'r').read()\n # Versions &gt;= 7 of the entries file are flat text. The first line is\n # the version number. The next set of digits after 'dir' is the revision.\n if re.match('(\\d+)', entries):\n rev_match = re.search('\\d+\\s+dir\\s+(\\d+)', entries)\n if rev_match:\n rev = rev_match.groups()[0]\n # Older XML versions of the file specify revision as an attribute of\n # the first entries node.\n else:\n from xml.dom import minidom\n dom = minidom.parse(entries_path)\n rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')\n\n if rev:\n return u'SVN-%s' % rev\n return u'SVN-unknown'\n</code></pre>\n\n<p>Adapt as appropriate. YOu might want to change MODULE for the name of one of your codemodules.</p>\n\n<p>This code has the advantage of working even if the destination system does not have subversion installed.</p>\n" }, { "answer_id": 245505, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 0, "selected": false, "text": "<p>Based on CesarB's response and the link Charles provided, I've done the following:</p>\n\n<pre><code>try:\n from subprocess import Popen, PIPE\n _p = Popen([\"svnversion\", \".\"], stdout=PIPE)\n REVISION= _p.communicate()[0]\n _p = None # otherwise we get a wild exception when Django auto-reloads\nexcept Exception, e:\n print \"Could not get revision number: \", e\n REVISION=\"Unknown\"\n</code></pre>\n\n<p>Golly Python is cool. :)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
> > **EDIT**: This question duplicates [How to access the current Subversion build number?](https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number#111173) (Thanks for the heads up, Charles!) > > > Hi there, This question is similar to [Getting the subversion repository number into code](https://stackoverflow.com/questions/16248/getting-the-subversion-repository-number-into-code) The differences being: 1. I would like to add the revision number to Python 2. I want the revision of the repository (not the checked out file) I.e. I would like to extract the Revision number from the return from 'svn info', likeso: $ svn info ``` Path: . URL: svn://localhost/B/trunk Repository Root: svn://localhost/B Revision: 375 Node Kind: directory Schedule: normal Last Changed Author: bmh Last Changed Rev: 375 Last Changed Date: 2008-10-27 12:09:00 -0400 (Mon, 27 Oct 2008) ``` I want a variable with 375 (the Revision). It's easy enough with put $Rev$ into a variable to keep track of changes on a file. However, I would like to keep track of the repository's version, and I understand (and it seems based on my tests) that $Rev$ only updates when the file changes. My initial thoughts turn to using the svn/libsvn module built in to Python, though I can't find any documentation on or examples of how to use them. Alternatively, I've thought calling 'svn info' and regex'ing the code out, though that seems rather brutal. :) Help would be most appreciated. Thanks & Cheers.
There is a command called `svnversion` which comes with subversion and is meant to solve exactly that kind of problem.
242,307
<p>This is the XML I am creating in JavaScript:</p> <pre><code>&lt;root&gt; &lt;GradeValueSet&gt; &lt;GradeValueSetMaster SetId="0" SetName="wrwr" SetComments="werwrwr" mode="add"/&gt; &lt;DetailInfo&gt; &lt;ChildInfo Name="This sfsf" Weightage="24"/&gt; &lt;ChildInfo Name="45654" Weightage="67"/&gt; &lt;/DetailInfo&gt; &lt;/GradeValueSet&gt; &lt;/root&gt; </code></pre> <p>I am sending this to a .aspx page and doing the following things:</p> <pre><code> XmlDocument objXmlDoc = new XmlDocument(); Request.InputStream.Position = 0; objXmlDoc.Load(Request.InputStream); objXmlDoc.Save("MyXML.xml"); </code></pre> <p>It is showing an exception "root elemenet missing"</p> <p>Is my XML not well formed? I think I have a valid root element.</p>
[ { "answer_id": 242309, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Sorry forgot to add the sending XML in previous post</p>\n\n<p>&lt;root&gt;\n&lt;GradeValueSet&gt;\n&lt;GradeValueSetMaster SetId=\"0\" SetName=\"wrwr\" SetComments=\"werwrwr\" mode=\"add\"/&gt;\n&lt;DetailInfo&gt;\n &lt;ChildInfo Name=\"This sfsf\" Weightage=\"24\"/&gt;\n &lt;ChildInfo Name=\"45654\" Weightage=\"67\"/&gt;\n&lt;/DetailInfo&gt;\n&lt;/GradeValueSet&gt;\n&lt;/root&gt;</p>\n" }, { "answer_id": 242334, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 1, "selected": false, "text": "<p>you might want to try saving the data as plain text from the aspx page to ensure the ONLY the xml is coming through.</p>\n\n<p>Depending on how you are sending the data to the page, there could be extra information which is not part of the xml. Saving the data as plain text just to test this will show exactly what data you are getting.</p>\n\n<p>Also, in the XML you do not actually need an element called \"root\", it's just referring to the top level element in your structure.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is the XML I am creating in JavaScript: ``` <root> <GradeValueSet> <GradeValueSetMaster SetId="0" SetName="wrwr" SetComments="werwrwr" mode="add"/> <DetailInfo> <ChildInfo Name="This sfsf" Weightage="24"/> <ChildInfo Name="45654" Weightage="67"/> </DetailInfo> </GradeValueSet> </root> ``` I am sending this to a .aspx page and doing the following things: ``` XmlDocument objXmlDoc = new XmlDocument(); Request.InputStream.Position = 0; objXmlDoc.Load(Request.InputStream); objXmlDoc.Save("MyXML.xml"); ``` It is showing an exception "root elemenet missing" Is my XML not well formed? I think I have a valid root element.
you might want to try saving the data as plain text from the aspx page to ensure the ONLY the xml is coming through. Depending on how you are sending the data to the page, there could be extra information which is not part of the xml. Saving the data as plain text just to test this will show exactly what data you are getting. Also, in the XML you do not actually need an element called "root", it's just referring to the top level element in your structure.
242,314
<p>Using gnuplot 4.2, is it possible to obtain the value of a specific column/row and use that value somehow?</p> <p>For example, let's say my datafile contains the following</p> <pre><code>#1 2 7 13 5 11 23 17 53 12 </code></pre> <p>For a simple plot where column 1 is the x axis and column 2 is the y axis I would:-</p> <pre><code>plot 'datafile' using 1:2 </code></pre> <p>What I'm trying to do is to normalize the all data in column 2 by the first element in that column (13). Is there a way to do this in gnuplot itself (i.e., without resorting to a scripting language or something to preprocess the data first)?</p> <p>Cheers</p>
[ { "answer_id": 460520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>ad a new column full of 13, then use:</p>\n\n<p>plot 'datafile' using 1:($2/$3)</p>\n" }, { "answer_id": 1450661, "author": "otto.poellath", "author_id": 11678, "author_profile": "https://Stackoverflow.com/users/11678", "pm_score": 1, "selected": false, "text": "<p>If your base value (e.g. 13) is in the first row of your data set, you should be able to do what you want using the CVS version of gnuplot.</p>\n\n<p>Have a look at the <a href=\"http://gnuplot.sourceforge.net/demo_4.3/data_feedback.html\" rel=\"nofollow noreferrer\">running averages demo</a>. Along those lines, you could write a custom function that stores the base value in a custom variable when called for the first time, and returns that variable on subsequent calls.</p>\n\n<p>(Since that demo is listed for the CVS version only, I assume the required functionality is not available in the current release version.)</p>\n" }, { "answer_id": 28361017, "author": "Jonatan Lindén", "author_id": 167319, "author_profile": "https://Stackoverflow.com/users/167319", "pm_score": 3, "selected": false, "text": "<p>Using the running averages demo, I managed to achieve a plot normalized to the first value of the second column.</p>\n\n<p>The <code>base</code> variable is used to store the reference value, and the <code>first</code> function initializes <code>base</code> on the first row.</p>\n\n<pre><code>first(x) = ($0 &gt; 0 ? base : base = x)\nplot file.dat u 1:(first($2), base/$2)\n</code></pre>\n\n<p>It should be mentioned that this was not done using gnuplot 4.2.</p>\n\n<p><strong>Edit:</strong> Updated using Christoph's advice.</p>\n" }, { "answer_id": 71218187, "author": "Vikram Govindarajan", "author_id": 10584300, "author_profile": "https://Stackoverflow.com/users/10584300", "pm_score": 1, "selected": false, "text": "<p>You can use the <code>stats</code> command to get the first value of the second column and store it in the <code>reference</code> variable as shown below,</p>\n<pre><code>stats 'datafile' using (reference=$2) every ::0::0 nooutput\n</code></pre>\n<p>You can replace <code>$2</code> with any other column you want. The zeros in <code>every ::0::0</code> implies the first entry of the column and you can also use <code>every ::n::n</code> to get the nth entry of the column. <code>nooutput</code> is used to avoid the cluttered console.</p>\n<p>You can then get normalized plot using,</p>\n<pre><code>plot 'datafile' using 1:($2/reference)\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11688/" ]
Using gnuplot 4.2, is it possible to obtain the value of a specific column/row and use that value somehow? For example, let's say my datafile contains the following ``` #1 2 7 13 5 11 23 17 53 12 ``` For a simple plot where column 1 is the x axis and column 2 is the y axis I would:- ``` plot 'datafile' using 1:2 ``` What I'm trying to do is to normalize the all data in column 2 by the first element in that column (13). Is there a way to do this in gnuplot itself (i.e., without resorting to a scripting language or something to preprocess the data first)? Cheers
Using the running averages demo, I managed to achieve a plot normalized to the first value of the second column. The `base` variable is used to store the reference value, and the `first` function initializes `base` on the first row. ``` first(x) = ($0 > 0 ? base : base = x) plot file.dat u 1:(first($2), base/$2) ``` It should be mentioned that this was not done using gnuplot 4.2. **Edit:** Updated using Christoph's advice.
242,320
<p>Is there a way to bind a Generic List to a multicolumn listbox, yes listbox...I know but this is what I am stuck with and can't add a grid or listview.</p> <p>Thanks</p>
[ { "answer_id": 242408, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 3, "selected": true, "text": "<p>You could bind a list to a listbox like this:</p>\n\n<pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 2, 4, 8, 16 };\nlistBox1.DataSource = list;\n</code></pre>\n\n<p>As for multicolumn listbox documentation says <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.multicolumn.aspx\" rel=\"nofollow noreferrer\">ListBox.MultiColumn</a> only places items into as many columns as are needed to make vertical scrolling unnecessary. </p>\n\n<p>If you want to show several columns of information for which an entire row will get selected you could use <a href=\"http://www.codeproject.com/KB/combobox/multicolumnlistbox.aspx\" rel=\"nofollow noreferrer\">Multi Column List Box</a> by Chris Rickard.</p>\n" }, { "answer_id": 1372200, "author": "AMissico", "author_id": 163921, "author_profile": "https://Stackoverflow.com/users/163921", "pm_score": 1, "selected": false, "text": "<p>For .NET 2.0 you can use the <code>UseCustomTabOffsets</code> and <code>CustomTabOffsets</code>, if you need multi-column support in your <code>ListBox</code>. See <a href=\"https://stackoverflow.com/questions/1365973/how-to-make-more-than-2-columns-in-listbox-using-c/1372212#1372212\">how to make more than 2 column&#39;s in ListBox using C#?</a> for an example of use.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
Is there a way to bind a Generic List to a multicolumn listbox, yes listbox...I know but this is what I am stuck with and can't add a grid or listview. Thanks
You could bind a list to a listbox like this: ``` List<int> list = new List<int> { 1, 2, 4, 8, 16 }; listBox1.DataSource = list; ``` As for multicolumn listbox documentation says [ListBox.MultiColumn](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.multicolumn.aspx) only places items into as many columns as are needed to make vertical scrolling unnecessary. If you want to show several columns of information for which an entire row will get selected you could use [Multi Column List Box](http://www.codeproject.com/KB/combobox/multicolumnlistbox.aspx) by Chris Rickard.
242,341
<p>I'm writing a utility to export evernote notes into Outlook on a schedule. The Outlook API's need plain text, and Evernote outputs a XHTML doc version of the plain text note. What I need is to strip out all the Tags and unescape the source XHTML doc embedded in the Evernote export file.</p> <p>Basically I need to turn;</p> <pre><code>&lt;note&gt; &lt;title&gt;Test Sync Note 1&lt;/title&gt; &lt;content&gt; &lt;![CDATA[ &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd"&gt; &lt;en-note bgcolor="#FFFFFF"&gt; &lt;div&gt;Test Sync Note 1&lt;/div&gt; &lt;div&gt;This i has some text in it&lt;/div&gt; &lt;div&gt;&amp;nbsp;&lt;/div&gt; &lt;div&gt;&amp;nbsp;&lt;/div&gt; &lt;div&gt;and a second line&lt;/div&gt; &lt;/en-note&gt; ]]&gt; &lt;/content&gt; &lt;created&gt;20081028T045727Z&lt;/created&gt; &lt;updated&gt;20081028T051346Z&lt;/updated&gt; &lt;tag&gt;Test&lt;/tag&gt; &lt;/note&gt; </code></pre> <p>Into </p> <pre> Test Sync Note 1 This i has some text in it and a second line </pre> <p>I can easily parse out the CDATA section and get just the 4 lines of text, but I need a reliable way to strip the div's, unescape and deal with any extra HTML that might have snuck in there.</p> <p>I'm assuming that there's some MS API combo that will do the job, but I don't know it.</p>
[ { "answer_id": 242351, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 0, "selected": false, "text": "<p>As far as I know there isn't anything to do that specific job but you might want to look at using XSLT or walking through an IXPathNavigable.</p>\n" }, { "answer_id": 242379, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<pre><code> string xml = @\"&lt;note&gt;\n &lt;title&gt;Test Sync Note 1&lt;/title&gt; \n &lt;content&gt;\n &lt;![CDATA[ &lt;?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\"?&gt;\n &lt;!DOCTYPE en-note SYSTEM \"\"http://xml.evernote.com/pub/enml.dtd\"\"&gt;\n\n &lt;en-note bgcolor=\"\"#FFFFFF\"\"&gt;\n &lt;div&gt;Test Sync Note 1&lt;/div&gt;\n &lt;div&gt;This i has some text in it&lt;/div&gt;\n &lt;div&gt; &lt;/div&gt;\n &lt;div&gt; &lt;/div&gt;\n &lt;div&gt;and a second line&lt;/div&gt;\n &lt;/en-note&gt;\n\n ]]&gt; \n &lt;/content&gt;\n &lt;created&gt;20081028T045727Z&lt;/created&gt; \n &lt;updated&gt;20081028T051346Z&lt;/updated&gt; \n &lt;tag&gt;Test&lt;/tag&gt; \n &lt;/note&gt;\n \";\n XPathDocument doc = new XPathDocument(new StringReader(xml));\n XPathNavigator nav = doc.CreateNavigator();\n\n // Compile a standard XPath expression\n\n XPathExpression expr;\n expr = nav.Compile(\"/note/content\");\n XPathNodeIterator iterator = nav.Select(expr);\n\n // Iterate on the node set\n\n try\n {\n while (iterator.MoveNext())\n {\n //Get the XML in the CDATA\n XPathNavigator nav2 = iterator.Current.Clone();\n XPathDocument doc2 = new XPathDocument(new StringReader(nav2.Value.Trim()));\n\n //Parse the XML in the CDATA\n XPathNavigator nav3 = doc2.CreateNavigator();\n expr = nav3.Compile(\"/en-note\");\n XPathNodeIterator iterator2 = nav3.Select(expr);\n iterator2.MoveNext();\n XPathNavigator nav4 = iterator2.Current.Clone();\n\n //Output the value directly, does not preserve the formatting\n Console.WriteLine(\"Direct Try:\");\n Console.WriteLine(nav4.Value);\n\n //This works, but is ugly\n Console.WriteLine(\"Ugly Try:\");\n Console.WriteLine(nav4.InnerXml.Replace(\"&lt;div&gt;\",\"\").Replace(\"&lt;/div&gt;\",Environment.NewLine));\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n</code></pre>\n" }, { "answer_id": 242451, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 1, "selected": false, "text": "<p>I would use a regular expression to strip out all the HTML tags, this one is pretty basic, I am sure if you may be able to tweak it if it doesn't work as you exactly want.</p>\n\n<p><code>Regex.Replace(\"&lt;div&gt;your html in here&lt;/div&gt;\",@\"&lt;(.|\\n)*?&gt;\",string.Empty)</code>;</p>\n" }, { "answer_id": 242496, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "<p>You can also use an xslt transformation to convert the xml into a text document.</p>\n" }, { "answer_id": 243764, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">HTML Agility Pack</a>.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing a utility to export evernote notes into Outlook on a schedule. The Outlook API's need plain text, and Evernote outputs a XHTML doc version of the plain text note. What I need is to strip out all the Tags and unescape the source XHTML doc embedded in the Evernote export file. Basically I need to turn; ``` <note> <title>Test Sync Note 1</title> <content> <![CDATA[ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd"> <en-note bgcolor="#FFFFFF"> <div>Test Sync Note 1</div> <div>This i has some text in it</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>and a second line</div> </en-note> ]]> </content> <created>20081028T045727Z</created> <updated>20081028T051346Z</updated> <tag>Test</tag> </note> ``` Into ``` Test Sync Note 1 This i has some text in it and a second line ``` I can easily parse out the CDATA section and get just the 4 lines of text, but I need a reliable way to strip the div's, unescape and deal with any extra HTML that might have snuck in there. I'm assuming that there's some MS API combo that will do the job, but I don't know it.
I would use a regular expression to strip out all the HTML tags, this one is pretty basic, I am sure if you may be able to tweak it if it doesn't work as you exactly want. `Regex.Replace("<div>your html in here</div>",@"<(.|\n)*?>",string.Empty)`;
242,344
<p>I want this page to return 200 whilst still sending the redirect...</p> <pre><code>&lt;script&gt; sub page_load 'Get the parameters dim content As String content = request.querystring("text") response.redirect ("http://100.200.100.10/test1/Default.aspx?CommandParm=" + content) end sub &lt;/script&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form runat="server"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 242358, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>No way with <code>Response.Redirect()</code>. I... think. Maybe setting <code>Response.Status = \"200 OK\"</code> after calling <code>Redirect()</code> works, I've never tried.</p>\n\n<p>You could fake it by setting the \"Location\" header manually in an otherwise empty response. Not sure what that is good for, though. ;-)</p>\n\n<pre><code>Response.AddHeader(\"Location\", \"http://100.200.100.10/test1/Default.aspx?CommandParm=\" + content)\nResponse.End()\n</code></pre>\n\n<p><em>(And, for the record: You would be producing an invalid HTTP header constellation. Should not break anything, but still.)</em></p>\n" }, { "answer_id": 242370, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "<p>You could get this page to be redirected by javascript</p>\n\n<p>Firstly, create the dynamic javascript by making the following string</p>\n\n<pre><code>&lt;script type\"text/javascript\"&gt;\n&lt;!--\nfunction redirect()\n{\n window.location = \"http://100.200.100.10/test1/Default.aspx?CommandParm=\" + content\n}\n//--&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>Secondly, add the javascript to the header of the current page.</p>\n\n<p>Then, add javascript to body</p>\n\n<pre><code>mybody.Attributes.Add(\"onload\", \"redirect()\");\n</code></pre>\n\n<p>When you browse the current page, it will return you HTTP 200, and after onload event fires the browser will call redirect() and your browse will be in the target page.</p>\n\n<p>Just curious why do you need this?!</p>\n" }, { "answer_id": 242719, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>@eyelidlessness@</p>\n\n<p>I agree it seems like a poor usability choice, but I'm hoping it's a workaround for a problem that can't be fixed directly.</p>\n\n<p>Given that, try a <a href=\"http://en.wikipedia.org/wiki/Meta_refresh\" rel=\"nofollow noreferrer\">META refresh</a>, e.g.,</p>\n\n<pre><code>&lt;meta http-equiv=\"refresh\" content=\"5;url=http://example.com/\"/&gt;\n</code></pre>\n\n<p>and embed a message explaining what is going on to the unlucky user who lands on this page.</p>\n\n<blockquote>\n <p>I probably didn't explain myself when posting question. This is actually a B2B transaction. There is no end-user with a browser. A third party sends the HTTP GET. All we want to do is forward it as ligitimate transaction.</p>\n</blockquote>\n\n<p>Then you should send a 301 or 302 - that's the exact purpose they were designed to handle.</p>\n" }, { "answer_id": 259774, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 1, "selected": false, "text": "<p>You can't have it both: Redirect and Status 200.</p>\n\n<p><a href=\"http://www.greenbytes.de/tech/webdav/rfc2616.html\" rel=\"nofollow noreferrer\">RFC2616</a> says about <a href=\"http://www.greenbytes.de/tech/webdav/rfc2616.html#status.200\" rel=\"nofollow noreferrer\">status code 200</a>:</p>\n\n<blockquote>\n <p><strong>10.2.1 200 OK</strong></p>\n \n <p>The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:</p>\n \n <ul>\n <li><strong>GET</strong>: an entity corresponding to the requested resource is sent in the response;</li>\n <li><strong>HEAD</strong>: the entity-header fields corresponding to the requested resource are sent in the response without any message-body;</li>\n <li><strong>POST</strong>: an entity describing or containing the result of the action;</li>\n <li><strong>TRACE</strong>: an entity containing the request message as received by the end server.</li>\n </ul>\n</blockquote>\n\n<p>So there's no room for redirecting other than sending some content that is interpreted by the user agent, e.g. JavaScript to a browser.</p>\n\n<p>And <a href=\"http://www.greenbytes.de/tech/webdav/rfc2616.html#status.3xx\" rel=\"nofollow noreferrer\">this is the part</a> in the spec that tells about redirection using status codes 301, 302 or 303:</p>\n\n<blockquote>\n <p><strong>10.3.2 301 Moved Permanently</strong></p>\n \n <p>The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.</p>\n \n <p>The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</p>\n \n <p>If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.</p>\n \n <p>Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.</p>\n \n <p><strong>10.3.3 302 Found</strong></p>\n \n <p>The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.</p>\n \n <p>The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</p>\n \n <p>If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.</p>\n \n <p>Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.</p>\n \n <p><strong>10.3.4 303 See Other</strong></p>\n \n <p>The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.</p>\n \n <p>The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</p>\n \n <p>Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.</p>\n</blockquote>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want this page to return 200 whilst still sending the redirect... ``` <script> sub page_load 'Get the parameters dim content As String content = request.querystring("text") response.redirect ("http://100.200.100.10/test1/Default.aspx?CommandParm=" + content) end sub </script> <html> <head> </head> <body> <form runat="server"> </form> </body> </html> ```
@eyelidlessness@ I agree it seems like a poor usability choice, but I'm hoping it's a workaround for a problem that can't be fixed directly. Given that, try a [META refresh](http://en.wikipedia.org/wiki/Meta_refresh), e.g., ``` <meta http-equiv="refresh" content="5;url=http://example.com/"/> ``` and embed a message explaining what is going on to the unlucky user who lands on this page. > > I probably didn't explain myself when posting question. This is actually a B2B transaction. There is no end-user with a browser. A third party sends the HTTP GET. All we want to do is forward it as ligitimate transaction. > > > Then you should send a 301 or 302 - that's the exact purpose they were designed to handle.
242,363
<p>I want create a drop shadow around the canvas component in flex. Technically speaking it will not be a shadow, as I want it to wrap around the component giving the component a floating look. I may be able to do it with glow, but can anyone drop an line or two who has already done it?</p> <p>Thanks in advance.</p>
[ { "answer_id": 242373, "author": "Mozammel", "author_id": 20165, "author_profile": "https://Stackoverflow.com/users/20165", "pm_score": 3, "selected": true, "text": "<p>I actually solved it by doing this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:Canvas xmlns:mx=\"http://www.adobe.com/2006/mxml\" \n width=\"780\" height=\"100%\" borderStyle=\"solid\" borderColor=\"gray\"\n creationComplete=\"init();\" backgroundColor=\"white\"&gt;\n\n &lt;mx:Script&gt;\n &lt;![CDATA[\n import mx.styles.StyleManager;\n\n\n private function init():void {\n var glow:GlowFilter = new GlowFilter();\n glow.color = StyleManager.getColorName(\"gray\");\n glow.alpha = 0.8;\n glow.blurX = 4;\n glow.blurY = 4;\n glow.strength = 6;\n glow.quality = BitmapFilterQuality.HIGH;\n\n this.filters = [glow];\n }\n ]]&gt;\n &lt;/mx:Script&gt;\n\n\n\n&lt;/mx:Canvas&gt;\n</code></pre>\n" }, { "answer_id": 242392, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>You can use <code>DropShadowFilter</code> but it looks to be more or less the same thing:</p>\n\n<pre><code>&lt;mx:Canvas xmlns:mx=\"http://www.adobe.com/2006/mxml\" \n width=\"780\" height=\"100%\" borderStyle=\"solid\" borderColor=\"gray\"\n creationComplete=\"init();\" backgroundColor=\"white\" dropShadowEnabled=\"true\"&gt;\n &lt;mx:filters&gt;\n &lt;mx:DropShadowFilter\n quality=\"1\"\n color=\"gray\"\n alpha=\"0.8\"\n distance=\"0\"\n blurX=\"4\"\n blurY=\"4\"\n strength=\"6\"\n /&gt;\n &lt;/mx:filters&gt;\n&lt;/mx:Canvas&gt;\n</code></pre>\n" }, { "answer_id": 251623, "author": "Ben Throop", "author_id": 27899, "author_profile": "https://Stackoverflow.com/users/27899", "pm_score": 0, "selected": false, "text": "<p>If you want to define it outside of the canvas, you can do this:</p>\n\n<pre><code>&lt;mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" \n width=\"780\" height=\"100%\"&gt;\n\n &lt;mx:Canvas filters=\"[dropShadow]\" width=\"200\" height=\"200\" backgroundColor=\"white\"/&gt;\n &lt;mx:DropShadowFilter id=\"dropShadow\" distance=\"0\"/&gt;\n\n&lt;/mx:Application&gt;\n</code></pre>\n" }, { "answer_id": 267360, "author": "Glenn", "author_id": 11814, "author_profile": "https://Stackoverflow.com/users/11814", "pm_score": 0, "selected": false, "text": "<p>You might be able to do it with <a href=\"http://www.degrafa.com/\" rel=\"nofollow noreferrer\">degrafa</a> and skinning. Their docs are limited but you can watch one of the tutorial videos for how to create skins. Or look at their sample code. Just assign a degrafa programmatic skin to the border of your canvas and you can add all sorts of funky gradients, paths, shapes, whatever. </p>\n" }, { "answer_id": 4318662, "author": "Willtriv", "author_id": 525735, "author_profile": "https://Stackoverflow.com/users/525735", "pm_score": 2, "selected": false, "text": "<p>In flex 4 I'm using the following. I just wanted to post this because filters property should look like below in the image. (yes I know I'm using a spark filter on an mx object)</p>\n\n<pre><code> &lt;fx:Declarations&gt;\n &lt;s:GlowFilter\n id=\"glowBlack\"\n alpha=\".6\"\n color=\"0x000000\"\n inner=\"false\"\n blurX=\"10\"\n blurY=\"10\"\n quality = \"2\"\n\n /&gt;\n</code></pre>\n\n<p></p>\n\n<pre><code> &lt;mx:Image id=\"rssIcon\"\n height=\"70\"\n filters=\"{[glowBlack]}\"\n source=\"assets/rss/icon_rss.png\"\n styleName=\"rssIconStyle\"\n width=\"70\"\n scaleContent=\"true\"\n click=\"openRssSite(event)\"\n \"/&gt;\n</code></pre>\n" }, { "answer_id": 8784430, "author": "Scott Evernden", "author_id": 11397, "author_profile": "https://Stackoverflow.com/users/11397", "pm_score": 0, "selected": false, "text": "<p>Depending on your needs you might be able to get away with:</p>\n\n<pre><code>&lt;mx:Canvas ... dropShadowEnabled=\"true\" shadowDirection=\"right\"&gt;\n</code></pre>\n\n<p>There are caveats .. outlined <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=styles_11.html\" rel=\"nofollow\">here</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165/" ]
I want create a drop shadow around the canvas component in flex. Technically speaking it will not be a shadow, as I want it to wrap around the component giving the component a floating look. I may be able to do it with glow, but can anyone drop an line or two who has already done it? Thanks in advance.
I actually solved it by doing this: ``` <?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="780" height="100%" borderStyle="solid" borderColor="gray" creationComplete="init();" backgroundColor="white"> <mx:Script> <![CDATA[ import mx.styles.StyleManager; private function init():void { var glow:GlowFilter = new GlowFilter(); glow.color = StyleManager.getColorName("gray"); glow.alpha = 0.8; glow.blurX = 4; glow.blurY = 4; glow.strength = 6; glow.quality = BitmapFilterQuality.HIGH; this.filters = [glow]; } ]]> </mx:Script> </mx:Canvas> ```
242,383
<p>I want to autowire a bean partially - that is, I want some args to be autowired but other to be explicitly set. For example:</p> <p>public MyClient(Service svc, boolean b)</p> <p>In the case of this constructor, I would like to specify in my xml the value for b, but have svc autowired. Is that possible?</p> <p>Thanks, Lowell</p>
[ { "answer_id": 242443, "author": "NR.", "author_id": 11701, "author_profile": "https://Stackoverflow.com/users/11701", "pm_score": 2, "selected": false, "text": "<p>I don't think it is possible with constructors, but with explicit setters it certainly is. Just annotate the ones you want autowired with @Autowired, and set the others in your config-file </p>\n\n<p>Something like:</p>\n\n<pre><code>public MyClient() {}\n\n@Autowired\npublic setService (Service svc) {...}\n\npublic setBoolean (boolean b) {...}\n</code></pre>\n\n<p>and then in your config</p>\n\n<pre><code>&lt;context:annotation-config /&gt;\n\n&lt;bean id=\"service\"&gt;...&lt;/bean&gt;\n\n&lt;bean id=\"yourbean\" class=\"MyClient\"&gt;\n &lt;property name=\"b\" value=\"true\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n" }, { "answer_id": 245347, "author": "lowellk", "author_id": 22063, "author_profile": "https://Stackoverflow.com/users/22063", "pm_score": 2, "selected": false, "text": "<p>I figured it out on my own, hooray!</p>\n\n<p>The way I did it was to put something like the following in my xml:</p>\n\n<pre><code>&lt;bean class=\"MyClient\" autowire=\"constructor\"&gt;\n &lt;constructor-arg index=\"1\"&gt;...&lt;/constructor-arg&gt;\n&lt;bean&gt;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ]
I want to autowire a bean partially - that is, I want some args to be autowired but other to be explicitly set. For example: public MyClient(Service svc, boolean b) In the case of this constructor, I would like to specify in my xml the value for b, but have svc autowired. Is that possible? Thanks, Lowell
I don't think it is possible with constructors, but with explicit setters it certainly is. Just annotate the ones you want autowired with @Autowired, and set the others in your config-file Something like: ``` public MyClient() {} @Autowired public setService (Service svc) {...} public setBoolean (boolean b) {...} ``` and then in your config ``` <context:annotation-config /> <bean id="service">...</bean> <bean id="yourbean" class="MyClient"> <property name="b" value="true"/> </bean> ```
242,391
<p>Here's the core problem: I have a .NET application that is using <a href="http://en.wikipedia.org/wiki/COM_Interop" rel="noreferrer">COM interop</a> in a separate AppDomain. The COM stuff seems to be loading assemblies back into the default domain, rather than the AppDomain from which the COM stuff is being called.</p> <p>What I want to know is: is this expected behaviour, or am I doing something wrong to cause these COM related assemblies to be loaded in the wrong AppDomain? Please see a more detailed description of the situation below...</p> <p>The application consists of 3 assemblies: - the main EXE, the entry point of the application. - common.dll, containing just an interface IController (in the IPlugin style) - controller.dll, containing a Controller class that implements IController and MarshalByRefObject. This class does all the work and uses COM interop to interact with another application.</p> <p>The relevant part of the main EXE looks like this:</p> <pre><code>AppDomain controller_domain = AppDomain.CreateDomain("Controller Domain"); IController c = (IController)controller_domain.CreateInstanceFromAndUnwrap("controller.dll", "MyNamespace.Controller"); result = c.Run(); AppDomain.Unload(controller_domain); </code></pre> <p>The common.dll only contains these 2 things:</p> <pre><code>public enum ControllerRunResult{FatalError, Finished, NonFatalError, NotRun} public interface IController { ControllerRunResult Run(); } </code></pre> <p>And the controller.dll contains this class (which also calls the COM interop stuff):</p> <pre><code>public class Controller: IController, MarshalByRefObject </code></pre> <p>When first running the application, Assembly.GetAssemblies() looks as expected, with common.dll being loaded in both AppDomains, and controller.dll only being loaded into the controller domain. After calling c.Run() however I see that assemblies related to the COM interop stuff have been loaded into the default AppDomain, and NOT in the AppDomain from which the COM interop is taking place.</p> <p>Why might this be occurring?</p> <p>And if you're interested, here's a bit of background:</p> <p>Originally this was a 1 AppDomain application. The COM stuff it interfaces with is a server API which is not stable over long periods of use. When a COMException (with no useful diagnostic information as to its cause) occurs from the COM stuff, the entire application has to restarted before the COM connection will work again. Simply reconnecting to the COM app server results in immediate COM exceptions again. To cope with this I have tried to move the COM interop stuff into a seperate AppDomain so that when the mystery COMExceptions occur I can unload the AppDomain in which it occurs, create a new one and start again, all without having to manually restart the application. That was the theory anyway...</p>
[ { "answer_id": 243817, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>Don't make your Controller MBR. Create a small proxy, which loads the Controller in the second domain and starts it. That way Controller dll will not be loaded in the first domain.</p>\n" }, { "answer_id": 1685461, "author": "Shaun Wilson", "author_id": 131420, "author_profile": "https://Stackoverflow.com/users/131420", "pm_score": 5, "selected": true, "text": "<p>Unfortunately, A COM component is loaded within Process Space and not within the context of an AppDomain. Thus, you will need to manually tear-down (Release and Unload) your Native DLLs (applies to both COM and P/Invoke). Simply destroying an appdomain will do you no good, but respawning the whole process shouldn't be necessary to reset COM state (simply recreating the COM object(s) should also normally work, this sounds like a bug within the component providers code, perhaps they can address it?)</p>\n\n<p><strong>References</strong></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/kt21t9h7(v=vs.100).aspx\" rel=\"noreferrer\">(TechNet) Process Address Space</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/2bh4z9hs(v=vs.110).aspx\" rel=\"noreferrer\">(MSDN) Application Domains</a></p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms189334(v=sql.105).aspx\" rel=\"noreferrer\">(MSDN) Boundaries: Processes and AppDomains</a></p>\n" }, { "answer_id": 14283464, "author": "Jeffrey Knight", "author_id": 83418, "author_profile": "https://Stackoverflow.com/users/83418", "pm_score": 2, "selected": false, "text": "<p>Here's the proof that Shaun Wilson's answer is correct</p>\n\n<p><img src=\"https://i.stack.imgur.com/BbYrE.png\" alt=\"Com App Domain\"></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31967/" ]
Here's the core problem: I have a .NET application that is using [COM interop](http://en.wikipedia.org/wiki/COM_Interop) in a separate AppDomain. The COM stuff seems to be loading assemblies back into the default domain, rather than the AppDomain from which the COM stuff is being called. What I want to know is: is this expected behaviour, or am I doing something wrong to cause these COM related assemblies to be loaded in the wrong AppDomain? Please see a more detailed description of the situation below... The application consists of 3 assemblies: - the main EXE, the entry point of the application. - common.dll, containing just an interface IController (in the IPlugin style) - controller.dll, containing a Controller class that implements IController and MarshalByRefObject. This class does all the work and uses COM interop to interact with another application. The relevant part of the main EXE looks like this: ``` AppDomain controller_domain = AppDomain.CreateDomain("Controller Domain"); IController c = (IController)controller_domain.CreateInstanceFromAndUnwrap("controller.dll", "MyNamespace.Controller"); result = c.Run(); AppDomain.Unload(controller_domain); ``` The common.dll only contains these 2 things: ``` public enum ControllerRunResult{FatalError, Finished, NonFatalError, NotRun} public interface IController { ControllerRunResult Run(); } ``` And the controller.dll contains this class (which also calls the COM interop stuff): ``` public class Controller: IController, MarshalByRefObject ``` When first running the application, Assembly.GetAssemblies() looks as expected, with common.dll being loaded in both AppDomains, and controller.dll only being loaded into the controller domain. After calling c.Run() however I see that assemblies related to the COM interop stuff have been loaded into the default AppDomain, and NOT in the AppDomain from which the COM interop is taking place. Why might this be occurring? And if you're interested, here's a bit of background: Originally this was a 1 AppDomain application. The COM stuff it interfaces with is a server API which is not stable over long periods of use. When a COMException (with no useful diagnostic information as to its cause) occurs from the COM stuff, the entire application has to restarted before the COM connection will work again. Simply reconnecting to the COM app server results in immediate COM exceptions again. To cope with this I have tried to move the COM interop stuff into a seperate AppDomain so that when the mystery COMExceptions occur I can unload the AppDomain in which it occurs, create a new one and start again, all without having to manually restart the application. That was the theory anyway...
Unfortunately, A COM component is loaded within Process Space and not within the context of an AppDomain. Thus, you will need to manually tear-down (Release and Unload) your Native DLLs (applies to both COM and P/Invoke). Simply destroying an appdomain will do you no good, but respawning the whole process shouldn't be necessary to reset COM state (simply recreating the COM object(s) should also normally work, this sounds like a bug within the component providers code, perhaps they can address it?) **References** [(TechNet) Process Address Space](http://msdn.microsoft.com/en-us/library/vstudio/kt21t9h7(v=vs.100).aspx) [(MSDN) Application Domains](http://msdn.microsoft.com/en-us/library/2bh4z9hs(v=vs.110).aspx) [(MSDN) Boundaries: Processes and AppDomains](http://technet.microsoft.com/en-us/library/ms189334(v=sql.105).aspx)
242,393
<p>I have the following classes</p> <pre><code>public interface InterfaceBase { } public class ImplementA:InterfaceBase { } public class ImplementB:InterfaceBase { } public void TestImplementType&lt;T&gt;(T obj) where T: InterfaceBase { } </code></pre> <p>How to infer what the T is whether ImplementA or ImplementB? I tried to use </p> <pre><code>typeof(T) is ImplementA </code></pre> <p>but this expression is always evaluated to false. </p> <p>Edit: And how am I going to cast obj to ImplementA or ImplementB?</p>
[ { "answer_id": 242395, "author": "Toby", "author_id": 291137, "author_profile": "https://Stackoverflow.com/users/291137", "pm_score": 3, "selected": true, "text": "<p><code>obj is ImplementA</code></p>\n" }, { "answer_id": 242396, "author": "Andrew Stapleton", "author_id": 28506, "author_profile": "https://Stackoverflow.com/users/28506", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<pre><code> if(obj.GetType().Equals(typeof(ImplementA)))\n {\n // ...\n }\n</code></pre>\n" }, { "answer_id": 242397, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p><code>typeof(T)</code> returns the <code>Type</code> of <code>T</code> - and <code>System.Type</code> doesn't implement <code>ImplementA</code>. What you want is:</p>\n\n<pre><code>if (typeof(ImplementA).IsAssignableFrom(typeof(T))\n{\n}\n</code></pre>\n" }, { "answer_id": 242402, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>Strictly, you should avoid too much specialization within generics. It would be cleaner to put any specialized logic in a member on the interface, so that any implementation can do it differently. However, there are a number of ways:</p>\n\n<p>You can test \"obj\" (assuming it is non-null)</p>\n\n<pre><code> bool testObj = obj is ImplementA;\n</code></pre>\n\n<p>You can test T for being typeof(ImplementA):</p>\n\n<pre><code> bool testEq = typeof(T) == typeof(ImplementA);\n</code></pre>\n\n<p>Likewise you can test it for being ImplementA or a subclass:</p>\n\n<pre><code> bool testAssign = typeof(ImplementA).IsAssignableFrom(typeof(T));\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I have the following classes ``` public interface InterfaceBase { } public class ImplementA:InterfaceBase { } public class ImplementB:InterfaceBase { } public void TestImplementType<T>(T obj) where T: InterfaceBase { } ``` How to infer what the T is whether ImplementA or ImplementB? I tried to use ``` typeof(T) is ImplementA ``` but this expression is always evaluated to false. Edit: And how am I going to cast obj to ImplementA or ImplementB?
`obj is ImplementA`
242,404
<p>Four 2D points in an array. I need to sort them in clockwise order. I think it can be done with just one swap operation but I have not been able to put this down formally.</p> <p><strike>Edit: The four points are a convex polygon in my case.</strike></p> <p>Edit: The four points are the vertices of a convex polygon. They need not be in order.</p>
[ { "answer_id": 242414, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>I believe you're right that a single swap can ensure that a polygon represented by four points in the plane is convex. The questions that remain to be answered are:</p>\n\n<ul>\n<li>Is this set of four points a convex polygon?</li>\n<li>If no, then which two points need to be swapped?</li>\n<li>Which direction is clockwise?</li>\n</ul>\n\n<p>Upon further reflection, I think that the only answer to the second question above is \"the middle two\".</p>\n" }, { "answer_id": 242469, "author": "Agnel Kurian", "author_id": 45603, "author_profile": "https://Stackoverflow.com/users/45603", "pm_score": 0, "selected": false, "text": "<p>How about this?</p>\n\n<pre><code>// Take signed area of ABC.\n// If negative,\n// Swap B and C.\n// Otherwise,\n// Take signed area of ACD.\n// If negative, swap C and D.\n</code></pre>\n\n<p>Ideas?</p>\n" }, { "answer_id": 242473, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 1, "selected": false, "text": "<p>Work it out the long way then optimize it.</p>\n\n<p>A more specific problem would be to sort the coordinates by decreasing angle relative to the positive x axis. This angle, in radians, will be given by this function:</p>\n\n<pre><code>x&gt;0\n AND y &gt;= 0\n angle = arctan(y/x)\n AND y &lt; 0\n angle = arctan(y/x) + 2*pi\nx==0\n AND y &gt;= 0\n angle = 0\n AND y &lt; 0\n angle = 3*pi/2\nx&lt;0\n angle = arctan(y/x) + pi\n</code></pre>\n\n<p>Then, of course, it's just a matter of sorting the coordinates by angle. Note that arctan(w) > arctan(z) if and only if x > z, so you can optimize a function which compares angles to each other pretty easily.</p>\n\n<p>Sorting such that the angle is monotonically decreasing over a window (or such that it increases at most once) is a bit different.</p>\n\n<p>In lieu of a an extensive proof I'll mention that I verified that a single swap operation will sort 4 2D points in clockwise order. Determining which swap operation is necessary is the trick, of course.</p>\n" }, { "answer_id": 242509, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 3, "selected": false, "text": "<p>A couple of thoughts worth considering here;</p>\n\n<ul>\n<li><p>Clockwise is only meaningful with respect to an origin. I would tend to think of the origin as the centre of gravity of a set of points. e.g. Clockwise relative to a point at the mean position of the four points, rather than the possibly very distant origin.</p></li>\n<li><p>If you have four points, a,b,c,d, there exists multiple clockwise orderings of those points around your origin. For example, if (a,b,c,d) formed a clockwise ordering, so would (b,c,d,a), (c,d,a,b) and (d,a,b,c)</p></li>\n<li><p>Do your four points already form a polygon? If so, it is a matter of checking and reversing the winding rather than sorting the points, e.g. a,b,c,d becomes d,c,b,a. If not, I would sort based on the join bearing between each point and the origin, as per Wedges response.</p></li>\n</ul>\n\n<p><strong>Edit:</strong> regarding your comments on which points to swap;</p>\n\n<p>In the case of a triangle (a,b,c), we can say that it is clockwise if the third point <strong>c</strong>, is on the right hand side of the line <strong>ab</strong>. I use the following side function to determine this based on the point's coordinates;</p>\n\n<pre><code>int side(double x1,double y1,double x2,double y2,double px,double py)\n{\n double dx1,dx2,dy1,dy2;\n double o;\n\n dx1 = x2 - x1;\n dy1 = y2 - y1;\n dx2 = px - x1;\n dy2 = py - y1;\n o = (dx1*dy2)-(dy1*dx2);\n if (o &gt; 0.0) return(LEFT_SIDE);\n if (o &lt; 0.0) return(RIGHT_SIDE);\n return(COLINEAR);\n}\n</code></pre>\n\n<p>If I have a four point convex polygon, (a,b,c,d), I can consider this as two triangles, (a,b,c) and (c,d,a). If (a,b,c) is counter clockwise, I change the winding (a,b,c,d) to (a,d,c,b) to change the winding of the polygon as a whole to clockwise.</p>\n\n<p>I strongly suggest drawing this with a few sample points, to see what I'm talking about. Note you have a lot of exceptional cases to deal with, such as concave polygons, colinear points, coincident points, etc...</p>\n" }, { "answer_id": 242526, "author": "vmarquez", "author_id": 10740, "author_profile": "https://Stackoverflow.com/users/10740", "pm_score": -1, "selected": false, "text": "<p>Wedge’s Answer is correct.</p>\n\n<p>To implement it easily, I think the same way as smacl: you need to find the boundary’s center and translate your points to that center.</p>\n\n<p>Like this:</p>\n\n<pre><code>centerPonintX = Min(x) + ( (Max(x) – Min(x)) / 2 )\ncenterPonintY = Min(y) + ( (Max(y) – Min(y)) / 2 )\n</code></pre>\n\n<p>Then, decrease centerPointX and centerPointY from each poin in order to translate it to boundary’s origin.</p>\n\n<p>Finally, apply Wedge’s solution with just one twist: Get the Absolute value of arctan(x/y) for every instance (worked for me that way).</p>\n" }, { "answer_id": 242710, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": -1, "selected": false, "text": "<pre><code>if( (p2.x-p1.x)*(p3.y-p1.y) &gt; (p3.x-p1.x)*(p2.y-p1.y) )\n swap( &amp;p1, &amp;p3 );\n</code></pre>\n\n<p>The '>' might be facing the wrong way, but you get the idea.</p>\n" }, { "answer_id": 242740, "author": "Pablo Retyk", "author_id": 30729, "author_profile": "https://Stackoverflow.com/users/30729", "pm_score": 0, "selected": false, "text": "<p>if we assume that point x is bigger than point y if the angle it has with the point (0,0) is bigger then we can implement this this way in c#</p>\n\n<pre><code> class Point : IComparable&lt;Point&gt;\n {\n public int X { set; get; }\n public int Y { set; get; }\n\n public double Angle\n {\n get\n {\n return Math.Atan2(X, Y);\n }\n }\n\n #region IComparable&lt;Point&gt; Members\n\n public int CompareTo(Point other)\n {\n return this.Angle.CompareTo(other.Angle);\n }\n\n #endregion\n\n public static List&lt;Point&gt; Sort(List&lt;Point&gt; points)\n {\n return points.Sort();\n }\n}\n</code></pre>\n" }, { "answer_id": 245079, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 5, "selected": true, "text": "<p>If you want to take a more mathematical perspective, we can consider the permutations of 4 points</p>\n\n<p>In our case there are 4 permutations that are in clockwise order</p>\n\n<pre><code>A B C D\nB C D A\nC D A B\nD A B C\n</code></pre>\n\n<p>All other possible permutations can be converted to one of these forms with 0 or 1 swaps. (I will only consider permutations starting with A, as it is symmetrical)</p>\n\n<ol>\n<li>A B C D - done</li>\n<li>A B D C - swap C and D</li>\n<li>A C B D - swap B and C</li>\n<li>A C D B - swap A and B</li>\n<li>A D B C - swap A and D</li>\n<li>A D C B - swap B and D</li>\n</ol>\n\n<p>Thus only one swap is ever needed - but it may take some work to identify which.</p>\n\n<p>By looking at the first three points, and checking the sign of the signed area of ABC, we can determine whether they are clockwise or not. If they are clockwise then we are in case 1 2 or 5</p>\n\n<p>to distinguish between these cases we have to check two more triangles - if ACD is clockwise then we can narrow this down to case 1, otherwise we must be in case 2 or 5.</p>\n\n<p>To pick between cases 2 and 5, we can test ABD</p>\n\n<p>We can check for the case of ABC anti-clockwise similarly.</p>\n\n<p>In the worst case we have to test 3 triangles.</p>\n\n<p>If your points are not convex, you would find the inside point, sort the rest and then add it in any edge. Note that if the quad is convex then 4 points no longer uniquely determine the quad, there are 3 equally valid quads.</p>\n" }, { "answer_id": 245659, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 0, "selected": false, "text": "<pre><code>if AB crosses CD\n swap B,C\nelif AD crosses BC\n swap C,D\n\nif area (ABC) &gt; 0\n swap B,D\n\n(I mean area(ABC) > 0 when A->B->C is counter-clockwise).\nLet p*x + q*y + r = 0 be the straight line that joins A and B.\nThen AB crosses CD if p*Cx + q*Cy + r and p*Dx + q*Dy + r\nhave different sign, i.e. their product is negative.\n</code></pre>\n\n<p>The first 'if/elif' brings the four points in clockwise <em>or</em> counterclockwise order.\n(Since your polygon is convex, the only other 'crossing' alternative is 'AC crosses BD', which means that the four points are already sorted.) \nThe last 'if' inverts orientation whenever it is counter-clockwise.</p>\n" }, { "answer_id": 245694, "author": "Julien Grenier", "author_id": 23051, "author_profile": "https://Stackoverflow.com/users/23051", "pm_score": 0, "selected": false, "text": "<p>You should take a look at the Graham's Scan.\nOf course you will need to adapt it since it finds to points counter-clockwise.</p>\n\n<p>p.s: This might be overkill for 4 points but if the number of points increase it could be interesting </p>\n" }, { "answer_id": 246063, "author": "Agnel Kurian", "author_id": 45603, "author_profile": "https://Stackoverflow.com/users/45603", "pm_score": 2, "selected": false, "text": "<p>Oliver is right. This code (community wikified) generates and sorts all possible combinations of an array of 4 points.</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;algorithm&gt;\n\nstruct PointF {\n float x;\n float y;\n};\n\n// Returns the z-component of the cross product of a and b\ninline double CrossProductZ(const PointF &amp;a, const PointF &amp;b) {\n return a.x * b.y - a.y * b.x;\n}\n\n// Orientation is positive if abc is counterclockwise, negative if clockwise.\n// (It is actually twice the area of triangle abc, calculated using the\n// Shoelace formula: http://en.wikipedia.org/wiki/Shoelace_formula .)\ninline double Orientation(const PointF &amp;a, const PointF &amp;b, const PointF &amp;c) {\n return CrossProductZ(a, b) + CrossProductZ(b, c) + CrossProductZ(c, a);\n}\n\nvoid Sort4PointsClockwise(PointF points[4]){\n PointF&amp; a = points[0];\n PointF&amp; b = points[1];\n PointF&amp; c = points[2];\n PointF&amp; d = points[3];\n\n if (Orientation(a, b, c) &lt; 0.0) {\n // Triangle abc is already clockwise. Where does d fit?\n if (Orientation(a, c, d) &lt; 0.0) {\n return; // Cool!\n } else if (Orientation(a, b, d) &lt; 0.0) {\n std::swap(d, c);\n } else {\n std::swap(a, d);\n }\n } else if (Orientation(a, c, d) &lt; 0.0) {\n // Triangle abc is counterclockwise, i.e. acb is clockwise.\n // Also, acd is clockwise.\n if (Orientation(a, b, d) &lt; 0.0) {\n std::swap(b, c);\n } else {\n std::swap(a, b);\n }\n } else {\n // Triangle abc is counterclockwise, and acd is counterclockwise.\n // Therefore, abcd is counterclockwise.\n std::swap(a, c);\n }\n}\n\nvoid PrintPoints(const char *caption, const PointF points[4]){\n printf(\"%s: (%f,%f),(%f,%f),(%f,%f),(%f,%f)\\n\", caption,\n points[0].x, points[0].y, points[1].x, points[1].y,\n points[2].x, points[2].y, points[3].x, points[3].y);\n}\n\nint main(){\n PointF points[] = {\n {5.0f, 20.0f},\n {5.0f, 5.0f},\n {20.0f, 20.0f},\n {20.0f, 5.0f}\n };\n\n for(int i = 0; i &lt; 4; i++){\n for(int j = 0; j &lt; 4; j++){\n if(j == i) continue;\n for(int k = 0; k &lt; 4; k++){\n if(j == k || i == k) continue;\n for(int l = 0; l &lt; 4; l++){\n if(j == l || i == l || k == l) continue;\n PointF sample[4];\n sample[0] = points[i];\n sample[1] = points[j];\n sample[2] = points[k];\n sample[3] = points[l];\n\n PrintPoints(\"input: \", sample);\n Sort4PointsClockwise(sample);\n PrintPoints(\"output: \", sample);\n printf(\"\\n\");\n }\n }\n }\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 251787, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 1, "selected": false, "text": "<p>I have one further improvement to add to my previous answer </p>\n\n<p>remember - these are the cases we can be in.</p>\n\n<ol>\n<li>A B C D</li>\n<li>A B D C</li>\n<li>A C B D</li>\n<li>A C D B</li>\n<li>A D B C</li>\n<li>A D C B</li>\n</ol>\n\n<p>If ABC is anticlockwise (has negative signed area) then we are in cases 3, 4, 6. If we swap B &amp; C in this case, then we are left with the following possibilities:</p>\n\n<ol>\n<li>A B C D</li>\n<li>A B D C</li>\n<li>A B C D</li>\n<li>A B D C</li>\n<li>A D B C</li>\n<li>A D B C</li>\n</ol>\n\n<p>Next we can check for ABD and swap B &amp; D if it is anticlockwise (cases 5, 6)</p>\n\n<ol>\n<li>A B C D</li>\n<li>A B D C</li>\n<li>A B C D</li>\n<li>A B D C</li>\n<li>A B D C</li>\n<li>A B D C</li>\n</ol>\n\n<p>Finally we need to check ACD and swap C &amp; D if ACD is anticlockwise. Now we know our points are all in order.</p>\n\n<p>This method is not as efficient as my previous method - this requires 3 checks every time, and more than one swap; but the code would be a lot simpler.</p>\n" }, { "answer_id": 10110480, "author": "Rui Marques", "author_id": 1085483, "author_profile": "https://Stackoverflow.com/users/1085483", "pm_score": 3, "selected": false, "text": "<p>If someone is interested, here is my quick and dirty solution to a similar problem.</p>\n<p>My problem was to have my rectangle corners ordered in the following order:</p>\n<blockquote>\n<p>top-left &gt; top-right &gt; bottom-right &gt; bottom-left</p>\n</blockquote>\n<p>Basically it is clockwise order starting from the top-left corner.</p>\n<p>The idea for the algorithm is:</p>\n<p><strong>Order the corners by rows and then order corner-pairs by cols.</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> // top-left = 0; top-right = 1; \n // right-bottom = 2; left-bottom = 3;\n List&lt;Point&gt; orderRectCorners(List&lt;Point&gt; corners) { \n if(corners.size() == 4) { \n ordCorners = orderPointsByRows(corners);\n \n if(ordCorners.get(0).x &gt; ordCorners.get(1).x) { // swap points\n Point tmp = ordCorners.get(0);\n ordCorners.set(0, ordCorners.get(1));\n ordCorners.set(1, tmp);\n }\n \n if(ordCorners.get(2).x &lt; ordCorners.get(3).x) { // swap points\n Point tmp = ordCorners.get(2);\n ordCorners.set(2, ordCorners.get(3));\n ordCorners.set(3, tmp);\n } \n return ordCorners;\n } \n return empty list or something;\n }\n\n List&lt;Point&gt; orderPointsByRows(List&lt;Point&gt; points) {\n Collections.sort(points, new Comparator&lt;Point&gt;() {\n public int compare(Point p1, Point p2) {\n if (p1.y &lt; p2.y) return -1;\n if (p1.y &gt; p2.y) return 1;\n return 0;\n }\n });\n return points;\n }\n</code></pre>\n" }, { "answer_id": 12141521, "author": "Shekhar", "author_id": 825822, "author_profile": "https://Stackoverflow.com/users/825822", "pm_score": 1, "selected": false, "text": "<pre><code>var arr = [{x:3,y:3},{x:4,y:1},{x:0,y:2},{x:5,y:2},{x:1,y:1}];\nvar reference = {x:2,y:2};\narr.sort(function(a,b) {\n var aTanA = Math.atan2((a.y - reference.y),(a.x - reference.x));\n var aTanB = Math.atan2((b.y - reference.y),(b.x - reference.x));\n if (aTanA &lt; aTanB) return -1;\n else if (aTanB &lt; aTanA) return 1;\n return 0;\n});\nconsole.log(arr);\n</code></pre>\n\n<p>Where reference point lies inside the polygon.</p>\n\n<p>More info at this <a href=\"http://social.msdn.microsoft.com/Forums/en/csharplanguage/thread/c4c0ce02-bbd0-46e7-aaa0-df85a3408c61\" rel=\"nofollow\">site</a></p>\n" }, { "answer_id": 13971319, "author": "Jean-Pat", "author_id": 601314, "author_profile": "https://Stackoverflow.com/users/601314", "pm_score": 2, "selected": false, "text": "<p>Calculate the area from the coordinates with the shoelace formula (devoided of the absolute value such that the area can be positive or negative) for every points permutations.\nThe maximal area values seems to correspond to direct simple quadrilaterals:<a href=\"http://dip4fish.blogspot.fr/2012/12/simple-direct-quadrilaterals-found-with.html\" rel=\"nofollow noreferrer\">Simple direct quadrilaterals found with the shoelace formula </a> </p>\n\n<p><img src=\"https://i.stack.imgur.com/cohEb.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 43973648, "author": "Eisneim", "author_id": 3177057, "author_profile": "https://Stackoverflow.com/users/3177057", "pm_score": 1, "selected": false, "text": "<p>if you just need to deal with 4 points then there is a most easy way of doing that</p>\n\n<ol>\n<li><p>sort by y value</p></li>\n<li><p>top row is the first two points, bottom row is the rest 2 points</p></li>\n<li><p>for top and bottom row, sort them by x value</p></li>\n</ol>\n\n<p>.</p>\n\n<pre><code>corners.sort(key=lambda ii: ii[1], reverse=True)\ntopRow = corners[0:2]\nbottomRow = corners[2:]\n\ntopRow.sort(key=lambda ii: ii[0])\nbottomRow.sort(key=lambda ii: ii[0])\n# clockwise\nreturn [topRow[0], topRow[1], bottomRow[1], bottomRow[0]]\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
Four 2D points in an array. I need to sort them in clockwise order. I think it can be done with just one swap operation but I have not been able to put this down formally. Edit: The four points are a convex polygon in my case. Edit: The four points are the vertices of a convex polygon. They need not be in order.
If you want to take a more mathematical perspective, we can consider the permutations of 4 points In our case there are 4 permutations that are in clockwise order ``` A B C D B C D A C D A B D A B C ``` All other possible permutations can be converted to one of these forms with 0 or 1 swaps. (I will only consider permutations starting with A, as it is symmetrical) 1. A B C D - done 2. A B D C - swap C and D 3. A C B D - swap B and C 4. A C D B - swap A and B 5. A D B C - swap A and D 6. A D C B - swap B and D Thus only one swap is ever needed - but it may take some work to identify which. By looking at the first three points, and checking the sign of the signed area of ABC, we can determine whether they are clockwise or not. If they are clockwise then we are in case 1 2 or 5 to distinguish between these cases we have to check two more triangles - if ACD is clockwise then we can narrow this down to case 1, otherwise we must be in case 2 or 5. To pick between cases 2 and 5, we can test ABD We can check for the case of ABC anti-clockwise similarly. In the worst case we have to test 3 triangles. If your points are not convex, you would find the inside point, sort the rest and then add it in any edge. Note that if the quad is convex then 4 points no longer uniquely determine the quad, there are 3 equally valid quads.
242,406
<p>So I have action_mailer_optional_tls (<a href="http://svn.douglasfshearer.com/rails/plugins/action_mailer_optional_tls" rel="nofollow noreferrer">http://svn.douglasfshearer.com/rails/plugins/action_mailer_optional_tls</a>) and this in my enviroment.rb</p> <pre><code>ActionMailer::Base.server_settings = { :tls =&gt; true, :address =&gt; "smtp.gmail.com", :port =&gt; "587", :domain =&gt; "www.somedomain.com", :authentication =&gt; :plain, :user_name =&gt; "someusername", :password =&gt; "somepassword" } </code></pre> <p>But now what If I want to send emails from different email accounts? How do I override the user_name and password fields on the fly?</p> <p>What Im looking for is a solution which allows dynamic switching between accounts. Example the following scenario: 10 "Admins" can send out notices to our customers. Each has their own gmail account, when they fill out a form on the site rails connects using their account and sends the mail.</p> <p>Thanks in advance!</p> <p>Ali</p>
[ { "answer_id": 242576, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 0, "selected": false, "text": "<p>If you want to use a different email address for the replies from the target receivers, \nyou could specify Reply-To: [email protected] for the SMTP protocol and still using the existing account of google smtp service.</p>\n\n<p>However you need to go to Gmail settings to add [email protected] to the list of \"send email as\", that also requires you to confirm [email protected] is yours by sending a link to that inbox.</p>\n" }, { "answer_id": 244343, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 1, "selected": false, "text": "<p>I can't verify that this works right now, but you should try just modifying these settings on the fly. i.e. set the username / password from the users account right before sending an email. You could even setup a before filter on your controller to load that info.</p>\n\n<pre><code>before_filter :load_email_settings\n\ndef load_email_settings\n ActionMailer::Base.server_settings.merge!(:user_name =&gt; current_user.email, :password =&gt; current_user.email_password)\nend\n\ndef current_user\n @current_user ||= User.find(session[:user_id])\nend\n</code></pre>\n\n<p>Note that storing the users email password as plaintext is pretty dangerous, I don't know if there is any way to do what you want using Googles Account's <a href=\"http://code.google.com/apis/accounts/docs/AuthForWebApps.html\" rel=\"nofollow noreferrer\">third party authentication</a> scheme but you might want to check that out.</p>\n" }, { "answer_id": 1564683, "author": "uv.", "author_id": 109216, "author_profile": "https://Stackoverflow.com/users/109216", "pm_score": 0, "selected": false, "text": "<p>As of Rails 2.3, the <code>action_mailer_optional_tls</code> plugin is not required. Instead, you should put the following in your <code>environment.rb</code>:</p>\n\n<pre><code>config.action_mailer.delivery_method = :smtp \nconfig.action_mailer.smtp_settings = { \n :enable_starttls_auto =&gt; :true, \n :address =&gt; \"smtp.gmail.com\", \n :port =&gt; 587, \n :domain =&gt; \"mydomain.example.com\", \n :authentication =&gt; :plain, \n :user_name =&gt; \"[email protected]\", \n :password =&gt; \"xxxxxxx\", \n :tls =&gt; :true \n} \nconfig.action_mailer.perform_deliveries = :true \nconfig.action_mailer.raise_delivery_errors = :true \nconfig.action_mailer.default_charset = \"utf-8\"\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31975/" ]
So I have action\_mailer\_optional\_tls (<http://svn.douglasfshearer.com/rails/plugins/action_mailer_optional_tls>) and this in my enviroment.rb ``` ActionMailer::Base.server_settings = { :tls => true, :address => "smtp.gmail.com", :port => "587", :domain => "www.somedomain.com", :authentication => :plain, :user_name => "someusername", :password => "somepassword" } ``` But now what If I want to send emails from different email accounts? How do I override the user\_name and password fields on the fly? What Im looking for is a solution which allows dynamic switching between accounts. Example the following scenario: 10 "Admins" can send out notices to our customers. Each has their own gmail account, when they fill out a form on the site rails connects using their account and sends the mail. Thanks in advance! Ali
I can't verify that this works right now, but you should try just modifying these settings on the fly. i.e. set the username / password from the users account right before sending an email. You could even setup a before filter on your controller to load that info. ``` before_filter :load_email_settings def load_email_settings ActionMailer::Base.server_settings.merge!(:user_name => current_user.email, :password => current_user.email_password) end def current_user @current_user ||= User.find(session[:user_id]) end ``` Note that storing the users email password as plaintext is pretty dangerous, I don't know if there is any way to do what you want using Googles Account's [third party authentication](http://code.google.com/apis/accounts/docs/AuthForWebApps.html) scheme but you might want to check that out.
242,415
<p>I have a problem of playing FLV file which id embed in my swf when i place it on server, swf plays correctly but not FLV</p> <p>any solution will be highly appreciated.</p> <hr> <p>thanks for all replys, its works in All browesers other than IE 6 now , </p> <p>i will paste the code here for the flv to chk .</p> <pre><code>var videopath:String; var flvtime:String; var vidPlaying:Boolean = false; var audio_sound:Sound = new Sound(vflvPlayback); videopath = "/public/ANS/test/flash/Price_video.flv"; flvtime = ":00/:17"; time_txt.text = flvtime; endClip_mc.moreabout_btn.enabled = false; endClip_mc.send_btn.enabled = false; endClip_mc.replay_btn.enabled = false; import mx.video.*; vflvPlayback.contentPath = videopath; vflvPlayback.stopButton = my_stopbttn; vflvPlayback.playPauseButton = my_playbttn; vflvPlayback.seekBar = my_scrubber; vflvPlayback.playheadUpdateInterval = 17; var vid_time:Number; var listenerObject:Object = new Object(); listenerObject.playheadUpdate = function(eventObject:Object):Void { if (eventObject.playheadTime == undefined || vflvPlayback.totalTime == undefined || vflvPlayback.totalTime == 0) { return; } vid_time = Math.floor(eventObject.playheadTime); vid_mins = Math.floor(vid_time/60); vid_secs = Math.floor(vid_time%60); if (vid_secs&lt;10) { vid_secs = "0"+vid_secs; } if (vid_mins&lt;10) { vid_mins = "0"+vid_mins; } time_txt.text = ":"+vid_secs+"/:17"; var percentPlayed:Number = eventObject.playheadTime/vflvPlayback.totalTime*100; if (percentPlayed&gt;=2) { this.placeHolder._visible = false; } vflvPlayback.complete = function(eventObject:Object):Void { vidComplete(); }; bar_mc._xscale = (vflvPlayback.totalTime == undefined || isNaN(percentPlayed)) ? 0 : percentPlayed; }; vflvPlayback.addEventListener("playheadUpdate",listenerObject); function vidComplete():Void { this.attachMovie("gfxFlash","flashFade",1000,{_x:-2, _y:10.5}); } </code></pre>
[ { "answer_id": 242429, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 0, "selected": false, "text": "<p><em>\"Apache 5.5\"</em>? Apache httpd only goes to 2.x, so can we assume you mean Apache Tomcat 5.5? Or??? <strong>More information is required.</strong> Maybe even a link if you can. Flash players are really good about playing valid FLV video files via HTTP, even with bad mime type headers.</p>\n" }, { "answer_id": 242616, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>In IIS you need to add the .flv extension to the known mime types otherwise files will be blocked. Perhaps Tomcat needs something similar.</p>\n\n<p>FLV mime = 'video/x-flv'</p>\n" }, { "answer_id": 245002, "author": "Luke", "author_id": 21406, "author_profile": "https://Stackoverflow.com/users/21406", "pm_score": 1, "selected": false, "text": "<p>As said before check the mime type on the server.</p>\n\n<p>If the FLV is playing in some browsers and not in others there is probably an issue with the Flash Player. First in all browsers go the URL where the FLV lives on the server so see if you actually access the file from a browser. Then check for each browser separately what Flash player version installed. E.g. If you're trying to play H264 video on Flash Player 8 it's not going to work.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a problem of playing FLV file which id embed in my swf when i place it on server, swf plays correctly but not FLV any solution will be highly appreciated. --- thanks for all replys, its works in All browesers other than IE 6 now , i will paste the code here for the flv to chk . ``` var videopath:String; var flvtime:String; var vidPlaying:Boolean = false; var audio_sound:Sound = new Sound(vflvPlayback); videopath = "/public/ANS/test/flash/Price_video.flv"; flvtime = ":00/:17"; time_txt.text = flvtime; endClip_mc.moreabout_btn.enabled = false; endClip_mc.send_btn.enabled = false; endClip_mc.replay_btn.enabled = false; import mx.video.*; vflvPlayback.contentPath = videopath; vflvPlayback.stopButton = my_stopbttn; vflvPlayback.playPauseButton = my_playbttn; vflvPlayback.seekBar = my_scrubber; vflvPlayback.playheadUpdateInterval = 17; var vid_time:Number; var listenerObject:Object = new Object(); listenerObject.playheadUpdate = function(eventObject:Object):Void { if (eventObject.playheadTime == undefined || vflvPlayback.totalTime == undefined || vflvPlayback.totalTime == 0) { return; } vid_time = Math.floor(eventObject.playheadTime); vid_mins = Math.floor(vid_time/60); vid_secs = Math.floor(vid_time%60); if (vid_secs<10) { vid_secs = "0"+vid_secs; } if (vid_mins<10) { vid_mins = "0"+vid_mins; } time_txt.text = ":"+vid_secs+"/:17"; var percentPlayed:Number = eventObject.playheadTime/vflvPlayback.totalTime*100; if (percentPlayed>=2) { this.placeHolder._visible = false; } vflvPlayback.complete = function(eventObject:Object):Void { vidComplete(); }; bar_mc._xscale = (vflvPlayback.totalTime == undefined || isNaN(percentPlayed)) ? 0 : percentPlayed; }; vflvPlayback.addEventListener("playheadUpdate",listenerObject); function vidComplete():Void { this.attachMovie("gfxFlash","flashFade",1000,{_x:-2, _y:10.5}); } ```
As said before check the mime type on the server. If the FLV is playing in some browsers and not in others there is probably an issue with the Flash Player. First in all browsers go the URL where the FLV lives on the server so see if you actually access the file from a browser. Then check for each browser separately what Flash player version installed. E.g. If you're trying to play H264 video on Flash Player 8 it's not going to work.
242,417
<p>I have two lists that are of the same length, is it possible to loop through these two lists at once?</p> <p>I am looking for the correct syntax to do the below</p> <pre><code>foreach itemA, itemB in ListA, ListB { Console.WriteLine(itemA.ToString()+","+itemB.ToString()); } </code></pre> <p>do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?</p>
[ { "answer_id": 242420, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "<p>[edit]: to clarify; this is useful in the generic LINQ / <code>IEnumerable&lt;T&gt;</code> context, where you <strong>can't use</strong> an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes, I do realise that LINQ and lambdas are not quite the same thing).</p>\n\n<p>It sounds like you need the missing <code>Zip</code> operator; you can spoof it:</p>\n\n<pre><code>static void Main()\n{\n int[] left = { 1, 2, 3, 4, 5 };\n string[] right = { \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\" };\n\n // using KeyValuePair&lt;,&gt; approach\n foreach (var item in left.Zip(right))\n {\n Console.WriteLine(\"{0}/{1}\", item.Key, item.Value);\n }\n\n // using projection approach\n foreach (string item in left.Zip(right,\n (x,y) =&gt; string.Format(\"{0}/{1}\", x, y)))\n {\n Console.WriteLine(item);\n }\n}\n\n// library code; written once and stuffed away in a util assembly...\n\n// returns each pais as a KeyValuePair&lt;,&gt;\nstatic IEnumerable&lt;KeyValuePair&lt;TLeft,TRight&gt;&gt; Zip&lt;TLeft, TRight&gt;(\n this IEnumerable&lt;TLeft&gt; left, IEnumerable&lt;TRight&gt; right)\n{\n return Zip(left, right, (x, y) =&gt; new KeyValuePair&lt;TLeft, TRight&gt;(x, y));\n}\n\n// accepts a projection from the caller for each pair\nstatic IEnumerable&lt;TResult&gt; Zip&lt;TLeft, TRight, TResult&gt;(\n this IEnumerable&lt;TLeft&gt; left, IEnumerable&lt;TRight&gt; right,\n Func&lt;TLeft, TRight, TResult&gt; selector)\n{\n using(IEnumerator&lt;TLeft&gt; leftE = left.GetEnumerator())\n using (IEnumerator&lt;TRight&gt; rightE = right.GetEnumerator())\n {\n while (leftE.MoveNext() &amp;&amp; rightE.MoveNext())\n {\n yield return selector(leftE.Current, rightE.Current);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 242422, "author": "jcelgin", "author_id": 26582, "author_profile": "https://Stackoverflow.com/users/26582", "pm_score": 4, "selected": false, "text": "<p>It'll be much simpler to just do it in a plain old for loop instead...</p>\n\n<pre><code>for(int i=0; i&lt;ListA.Length; i++)\n{\n Console.WriteLine(ListA[i].ToString() + \", \" + ListB[i].ToString());\n}\n</code></pre>\n" }, { "answer_id": 242433, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can do it explicit.</p>\n\n<pre><code>IEnumerator ListAEnum = ListA.GetEnumerator();\nIEnumerator ListBEnum = ListB.GetEnumerator();\n\nListBEnum.MoveNext();\nwhile(ListAEnum.MoveNext()==true)\n{\n itemA=ListAEnum.getCurrent();\n itemB=ListBEnum.getCurrent();\n Console.WriteLine(itemA.ToString()+\",\"+itemB.ToString());\n}\n</code></pre>\n\n<p>At least this (or something like this) is what the compiler does for a foreach-loop. I haven't tested it though and I guess some template parameters are missing for the enumerators.</p>\n\n<p>Just look up GetEnumerator() from List and the IEnumerator-Interface.</p>\n" }, { "answer_id": 242489, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://msmvps.com/blogs/senthil/default.aspx\" rel=\"nofollow noreferrer\">Senthil Kumar's tech blog</a>, has a series covering implementations of <strong>(Python) Itertools for C#</strong>, including <a href=\"http://docs.python.org/library/itertools.html#itertools.izip\" rel=\"nofollow noreferrer\"><code>itertools.izip</code></a>.</p>\n\n<p>From <a href=\"http://msmvps.com/blogs/senthil/archive/2008/04/26/itertools-for-c-cycle-and-zip.aspx\" rel=\"nofollow noreferrer\">Itertools for C# - Cycle and Zip</a>, you have a solution for any number of <em>iterables</em> (not only <em>List&LT;T&GT;</em>). Note that <code>Zip</code> yields an <code>Array</code> on each iteration:</p>\n\n<pre><code>public static IEnumerable&lt;T[]&gt; Zip&lt;T&gt;(params IEnumerable&lt;T&gt;[] iterables)\n{\nIEnumerator&lt;T&gt;[] enumerators = Array.ConvertAll(iterables, (iterable) =&gt; iterable.GetEnumerator());\n\nwhile (true)\n{\n int index = 0;\n T[] values = new T[enumerators.Length];\n\n foreach (IEnumerator&lt;T&gt; enumerator in enumerators)\n {\n if (!enumerator.MoveNext())\n yield break;\n\n values[index++] = enumerator.Current;\n }\n\n yield return values;\n}\n</code></pre>\n\n<p>}</p>\n\n<blockquote>\n <p>The code gets enumerators for all the iterables, moves all enumerators forward, accumulates their current values into an array and yields the array. It does this until any one of the enumerators runs out of elements.</p>\n</blockquote>\n" }, { "answer_id": 242564, "author": "PiRX", "author_id": 25718, "author_profile": "https://Stackoverflow.com/users/25718", "pm_score": 2, "selected": false, "text": "<p>I recommend using plain old for loop, but you should consider different array lengths.\nSo </p>\n\n<pre><code>for(int i=0; i&lt;ListA.Length; i++)\n{\n Console.WriteLine(ListA[i].ToString() + \", \" + ListB[i].ToString());\n}\n</code></pre>\n\n<p>can turn into </p>\n\n<pre><code>for(int i = 0; i &lt; Math.Min(ListA.Length, ListB.Lenght); i++)\n{\n Console.WriteLine(ListA[i].ToString() + \", \" + ListB[i].ToString());\n}\n</code></pre>\n\n<p>or even into</p>\n\n<pre><code> for(int i = 0; i &lt; Math.Max(ListA.Length, ListB.Lenght); i++)\n {\n string valueA = i &lt; ListA.Length ? listA[i].ToString() : \"\";\n string valueB = i &lt; ListB.Length ? listB[i].ToString() : \"\";\n\n Console.WriteLine(valueA+ \", \" + valueB);\n }\n</code></pre>\n" }, { "answer_id": 9931679, "author": "sonjz", "author_id": 740575, "author_profile": "https://Stackoverflow.com/users/740575", "pm_score": 1, "selected": false, "text": "<p>I had this same problem but using lists of objects with lists inside of them.. for what its worth, this might help someone with the same issue.</p>\n\n<p>The running time of this isn't very good since IndexOf is O(n), but at the time, I'm dealing with a lot more inner-foreach loops than in this example, so I didn't want to deal with handling iterator variables.</p>\n\n<p>At times like this I very much miss PHPs foreach($arrayList as $key => $value) notation... maybe I'm missing something in C#, there's got to be a way to get the index in O(c) time!\n(sadly this post says no: <a href=\"https://stackoverflow.com/questions/60032/getting-the-array-key-in-a-foreach-loop\">Getting the array key in a &#39;foreach&#39; loop</a>)</p>\n\n<pre><code>class Stock {\n string symbol;\n List&lt;decimal&gt; hourlyPrice; // provides a list of 24 decimals\n}\n\n// get hourly prices from yesterday and today\nList&lt;Stock&gt; stockMondays = Stocks.GetStock(\"GOOGL,IBM,AAPL\", DateTime.Now.AddDay(-1));\nList&lt;Stock&gt; stockTuesdays = Stocks.GetStock(\"GOOGL,IBM,AAPL\", DateTime.Now);\n\ntry {\n foreach(Stock sMonday in stockMondays) {\n Stock sTuesday = stockTuesday[stockMondays.IndexOf(sMonday)];\n\n foreach(decimal mondayPrice in sMonday.prices) {\n decimal tuesdayPrice = sTuesday.prices[sMonday.prices.IndexOf(mondayPrice)];\n // do something now\n }\n\n }\n} catch (Exception ex) { // some reason why list counts aren't matching? }\n</code></pre>\n" }, { "answer_id": 41531092, "author": "Joy Fernandes", "author_id": 4519455, "author_profile": "https://Stackoverflow.com/users/4519455", "pm_score": 0, "selected": false, "text": "<p>I have this small function which helps me to iterate through this two list objects. schema is of type SqlData, which is a class that hold three properties. And data is a list that holds values of dynamic type. First I'm iterating through the schema collection and than using the index of item to iterate through the data object.</p>\n\n<pre><code>public List&lt;SqlData&gt; SqlDataBinding(List&lt;SqlData&gt; schema, List&lt;dynamic&gt; data)\n{\n foreach (SqlData item in schema)\n {\n item.Values = data[schema.IndexOf(item)];\n }\n return schema\n}\n</code></pre>\n" }, { "answer_id": 68089024, "author": "MarredCheese", "author_id": 5405967, "author_profile": "https://Stackoverflow.com/users/5405967", "pm_score": 4, "selected": true, "text": "<h1>Modern Answer</h1>\n<p>LINQ now has a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip\" rel=\"nofollow noreferrer\">built-in Zip method</a>, so you don't need to create your own. The resulting sequence is as long as the shortest input. Zip currently (as of .NET Core 3.0) has 2 overloads. The simpler one returns a sequence of tuples. It lets us produce some very terse code that's close to the original request:</p>\n<pre><code>int[] numbers = { 1, 2, 3, 4 };\nstring[] words = { &quot;one&quot;, &quot;two&quot;, &quot;three&quot; };\n\nforeach (var (number, word) in numbers.Zip(words))\n Console.WriteLine($&quot;{number}, {word}&quot;);\n\n// 1, one\n// 2, two\n// 3, three\n</code></pre>\n<p>Or, the same thing but without tuple unpacking:</p>\n<pre><code>foreach (var item in numbers.Zip(words))\n Console.WriteLine($&quot;{item.First}, {item.Second}&quot;);\n</code></pre>\n<p>The other overload (which appeared earlier than Core 3.0) takes a mapping function, giving you more control over the result. This example returns a sequence of strings, but you could return a sequence of whatever (e.g. some custom class).</p>\n<pre><code>var numbersAndWords = numbers.Zip(words, (number, word) =&gt; $&quot;{number}, {word}&quot;);\n\nforeach (string item in numbersAndWords)\n Console.WriteLine(item);\n</code></pre>\n<p>If you are using LINQ on regular objects (as opposed to using it to generate SQL), you can also check out <a href=\"https://github.com/morelinq/MoreLINQ\" rel=\"nofollow noreferrer\">MoreLINQ</a>, which provides several zipping methods. Each of those methods takes up to 4 input sequences, not just 2:</p>\n<ul>\n<li><p><code>EquiZip</code> - An exception is thrown if the input sequences are of different lengths.</p>\n</li>\n<li><p><code>ZipLongest</code> - The resulting sequence will always be as long as the longest of input sequences where the default value of each of the shorter sequence element types is used for padding.</p>\n</li>\n<li><p><code>ZipShortest</code> - The resulting sequence is as short as the shortest input sequence.</p>\n</li>\n</ul>\n<p>See their <a href=\"https://github.com/morelinq/examples\" rel=\"nofollow noreferrer\">examples</a> and/or <a href=\"https://github.com/morelinq/MoreLINQ/tree/master/MoreLinq.Test\" rel=\"nofollow noreferrer\">tests</a> for usage. It seems MoreLINQ's zipping came before regular LINQ's, so if you're stuck with an old version of .NET, it might be a good option.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I have two lists that are of the same length, is it possible to loop through these two lists at once? I am looking for the correct syntax to do the below ``` foreach itemA, itemB in ListA, ListB { Console.WriteLine(itemA.ToString()+","+itemB.ToString()); } ``` do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?
Modern Answer ============= LINQ now has a [built-in Zip method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip), so you don't need to create your own. The resulting sequence is as long as the shortest input. Zip currently (as of .NET Core 3.0) has 2 overloads. The simpler one returns a sequence of tuples. It lets us produce some very terse code that's close to the original request: ``` int[] numbers = { 1, 2, 3, 4 }; string[] words = { "one", "two", "three" }; foreach (var (number, word) in numbers.Zip(words)) Console.WriteLine($"{number}, {word}"); // 1, one // 2, two // 3, three ``` Or, the same thing but without tuple unpacking: ``` foreach (var item in numbers.Zip(words)) Console.WriteLine($"{item.First}, {item.Second}"); ``` The other overload (which appeared earlier than Core 3.0) takes a mapping function, giving you more control over the result. This example returns a sequence of strings, but you could return a sequence of whatever (e.g. some custom class). ``` var numbersAndWords = numbers.Zip(words, (number, word) => $"{number}, {word}"); foreach (string item in numbersAndWords) Console.WriteLine(item); ``` If you are using LINQ on regular objects (as opposed to using it to generate SQL), you can also check out [MoreLINQ](https://github.com/morelinq/MoreLINQ), which provides several zipping methods. Each of those methods takes up to 4 input sequences, not just 2: * `EquiZip` - An exception is thrown if the input sequences are of different lengths. * `ZipLongest` - The resulting sequence will always be as long as the longest of input sequences where the default value of each of the shorter sequence element types is used for padding. * `ZipShortest` - The resulting sequence is as short as the shortest input sequence. See their [examples](https://github.com/morelinq/examples) and/or [tests](https://github.com/morelinq/MoreLINQ/tree/master/MoreLinq.Test) for usage. It seems MoreLINQ's zipping came before regular LINQ's, so if you're stuck with an old version of .NET, it might be a good option.
242,421
<p>I am trying to execute this SQL query prior to restoring a .BAK file in SQL Express. Initially, I had the file on the Desktop of my user account. I am logged in as Administrator.</p> <p>When I try to access the .BAK file on the desktop like this</p> <pre><code>RESTORE FILELISTONLY FROM DISK= 'C:\Documents and Settings\Administrator\Desktop\file.bak' </code></pre> <p>I get an error.</p> <pre>Msg 3201, Level 16, State 2, Line 1 Cannot open backup device 'C:\Documents and Settings\Administrator\Desktop\file.bak'. Operating system error 5(Access is denied.). Msg 3013, Level 16, State 1, Line 1 RESTORE FILELIST is terminating abnormally.</pre> <p>However, when I move the .BAK file to <code>C:\temp</code>, and execute this </p> <pre><code>RESTORE FILELISTONLY FROM DISK= 'C:\temp\file.bak' </code></pre> <p>It works just fine.</p> <p>I cant figure out what is going on. Is there a way to access files on Desktop using Windows Authentication with SQL Express?</p>
[ { "answer_id": 242430, "author": "rwired", "author_id": 17492, "author_profile": "https://Stackoverflow.com/users/17492", "pm_score": 4, "selected": true, "text": "<p>Try granting read permission to <strong>Users</strong> or <strong>LOCAL SERVICE</strong> to the folder C:\\Documents and Settings\\Administrator\\Desktop\\ in your Policy Editor (right click the folder and in the Security tab click Add... then Advanced...|Find Now</p>\n" }, { "answer_id": 242825, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 0, "selected": false, "text": "<p>When you are running the restore script, it is executing under the context of the service account that the SQL Express is running under. Go to the Services Management Console ( or run Services.msc) and find the SQL Express service and look at what account it is configured to run under and then look at the permissions of the file on your desktop and make sure that account has read access.</p>\n" }, { "answer_id": 53519678, "author": "Marcello Miorelli", "author_id": 1501497, "author_profile": "https://Stackoverflow.com/users/1501497", "pm_score": 0, "selected": false, "text": "<p>after SQL Server 2008R2 SP1 you don't need to Go to the Services Management Console ( or run Services.msc) to find out the account under which the sql server service is running.</p>\n\n<p>simply use the code below:</p>\n\n<pre><code>select * from\nsys.dm_server_services\n\nSELECT DSS.servicename,\n DSS.startup_type_desc,\n DSS.status_desc,\n DSS.last_startup_time,\n DSS.service_account,\n DSS.is_clustered,\n DSS.cluster_nodename,\n DSS.filename,\n DSS.startup_type,\n DSS.status,\n DSS.process_id\nFROM sys.dm_server_services AS DSS;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31979/" ]
I am trying to execute this SQL query prior to restoring a .BAK file in SQL Express. Initially, I had the file on the Desktop of my user account. I am logged in as Administrator. When I try to access the .BAK file on the desktop like this ``` RESTORE FILELISTONLY FROM DISK= 'C:\Documents and Settings\Administrator\Desktop\file.bak' ``` I get an error. ``` Msg 3201, Level 16, State 2, Line 1 Cannot open backup device 'C:\Documents and Settings\Administrator\Desktop\file.bak'. Operating system error 5(Access is denied.). Msg 3013, Level 16, State 1, Line 1 RESTORE FILELIST is terminating abnormally. ``` However, when I move the .BAK file to `C:\temp`, and execute this ``` RESTORE FILELISTONLY FROM DISK= 'C:\temp\file.bak' ``` It works just fine. I cant figure out what is going on. Is there a way to access files on Desktop using Windows Authentication with SQL Express?
Try granting read permission to **Users** or **LOCAL SERVICE** to the folder C:\Documents and Settings\Administrator\Desktop\ in your Policy Editor (right click the folder and in the Security tab click Add... then Advanced...|Find Now
242,424
<p>I know how to move a layer based on touch. But I would also like to be able to rotate the image. </p> <p>Is there any sample code that shows how to do this? Or can anyone give me some advice?</p> <p>Thanks!</p>
[ { "answer_id": 242619, "author": "Jesús A. Álvarez", "author_id": 13186, "author_profile": "https://Stackoverflow.com/users/13186", "pm_score": 1, "selected": false, "text": "<p>You would use the view's transform property.\nThere's some example code for rotating the view in the iPhone OS Programming Guide, under <a href=\"https://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationEnvironment/chapter_3_section_6.html#//apple_ref/doc/uid/TP40007072-CH7-SW18\" rel=\"nofollow noreferrer\" title=\"Launching in Landscape Mode\">Launching in Landscape Mode</a></p>\n" }, { "answer_id": 242661, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 0, "selected": false, "text": "<p>You should look at Apple's <a href=\"https://developer.apple.com/iphone/library/samplecode/MoveMe/index.html\" rel=\"nofollow noreferrer\">MoveMe</a> example for how to move around a layer based on touch. It also applies some scaling transforms as you do it, so that should serve as a reasonable example of to apply rotation transforms.</p>\n" }, { "answer_id": 242858, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 5, "selected": true, "text": "<p>The simplest way to do this is using the layer's transform property:</p>\n\n<pre><code>float angle = M_PI; //rotate 180°, or 1 π radians\nlayer.transform = CATransform3DMakeRotation(angle, 0, 0.0, 1.0);\n</code></pre>\n\n<p>The first argument to the CATransform3DMakeRotation function is the amount to rotate, in radians. The next three describe the vector around which to rotate. This is describing a vector in the z-axis, so effectively perpendicular to the screen. This will rotate the layer so it's upside down. </p>\n" }, { "answer_id": 244749, "author": "rksprst", "author_id": 23695, "author_profile": "https://Stackoverflow.com/users/23695", "pm_score": 4, "selected": false, "text": "<p>I ended up doing it like this:</p>\n\n<pre><code>CGAffineTransform transform = CGAffineTransformMakeRotation(angle);\n[[self viewWithTag:999] setTransform:transform];\n</code></pre>\n\n<p>Note that the angle is in radians.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
I know how to move a layer based on touch. But I would also like to be able to rotate the image. Is there any sample code that shows how to do this? Or can anyone give me some advice? Thanks!
The simplest way to do this is using the layer's transform property: ``` float angle = M_PI; //rotate 180°, or 1 π radians layer.transform = CATransform3DMakeRotation(angle, 0, 0.0, 1.0); ``` The first argument to the CATransform3DMakeRotation function is the amount to rotate, in radians. The next three describe the vector around which to rotate. This is describing a vector in the z-axis, so effectively perpendicular to the screen. This will rotate the layer so it's upside down.
242,438
<p>I've a performance related question regarding use of StringBuilder. In a very long loop I'm manipulating a <code>StringBuilder</code> and passing it to another method like this:</p> <pre><code>for (loop condition) { StringBuilder sb = new StringBuilder(); sb.append("some string"); . . . sb.append(anotherString); . . . passToMethod(sb.toString()); } </code></pre> <p>Is instantiating <code>StringBuilder</code> at every loop cycle is a good solution? And is calling a delete instead better, like the following?</p> <pre><code>StringBuilder sb = new StringBuilder(); for (loop condition) { sb.delete(0, sb.length); sb.append("some string"); . . . sb.append(anotherString); . . . passToMethod(sb.toString()); } </code></pre>
[ { "answer_id": 242442, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 3, "selected": false, "text": "<p>The modern JVM is really smart about stuff like this. I would not second guess it and do something hacky that is less maintainable/readable...unless you do proper bench marks with production data that validate a non-trivial performance improvement (and document it ;) </p>\n" }, { "answer_id": 242449, "author": "Peter", "author_id": 26483, "author_profile": "https://Stackoverflow.com/users/26483", "pm_score": 5, "selected": false, "text": "<p>In the philosophy of writing solid code its always better to put your StringBuilder inside your loop. This way it doesnt go outside the code its intended for.</p>\n\n<p>Secondly the biggest improvment in StringBuilder comes from giving it an initial size to avoid it growing bigger while the loop runs</p>\n\n<pre><code>for (loop condition) {\n StringBuilder sb = new StringBuilder(4096);\n}\n</code></pre>\n" }, { "answer_id": 242454, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>Based on my experience with developing software on Windows I would say clearing the StringBuilder out during your loop has better performance than instantiating a StringBuilder with each iteration. Clearing it frees that memory to be overwritten immediately with no additional allocation required. I'm not familiar enough with the Java garbage collector, but I would think that freeing and no reallocation (unless your next string grows the StringBuilder) is more beneficial than instantiation.</p>\n\n<p>(My opinion is contrary to what everyone else is suggesting. Hmm. Time to benchmark it.)</p>\n" }, { "answer_id": 242455, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 6, "selected": false, "text": "<p>The second one is about 25% faster in my mini-benchmark.</p>\n\n<pre><code>public class ScratchPad {\n\n static String a;\n\n public static void main( String[] args ) throws Exception {\n long time = System.currentTimeMillis();\n for( int i = 0; i &lt; 10000000; i++ ) {\n StringBuilder sb = new StringBuilder();\n sb.append( \"someString\" );\n sb.append( \"someString2\"+i );\n sb.append( \"someStrin4g\"+i );\n sb.append( \"someStr5ing\"+i );\n sb.append( \"someSt7ring\"+i );\n a = sb.toString();\n }\n System.out.println( System.currentTimeMillis()-time );\n time = System.currentTimeMillis();\n StringBuilder sb = new StringBuilder();\n for( int i = 0; i &lt; 10000000; i++ ) {\n sb.delete( 0, sb.length() );\n sb.append( \"someString\" );\n sb.append( \"someString2\"+i );\n sb.append( \"someStrin4g\"+i );\n sb.append( \"someStr5ing\"+i );\n sb.append( \"someSt7ring\"+i );\n a = sb.toString();\n }\n System.out.println( System.currentTimeMillis()-time );\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>25265\n17969\n</code></pre>\n\n<p>Note that this is with JRE 1.6.0_07.</p>\n\n<hr>\n\n<p>Based on Jon Skeet's ideas in the edit, here's version 2. Same results though.</p>\n\n<pre><code>public class ScratchPad {\n\n static String a;\n\n public static void main( String[] args ) throws Exception {\n long time = System.currentTimeMillis();\n StringBuilder sb = new StringBuilder();\n for( int i = 0; i &lt; 10000000; i++ ) {\n sb.delete( 0, sb.length() );\n sb.append( \"someString\" );\n sb.append( \"someString2\" );\n sb.append( \"someStrin4g\" );\n sb.append( \"someStr5ing\" );\n sb.append( \"someSt7ring\" );\n a = sb.toString();\n }\n System.out.println( System.currentTimeMillis()-time );\n time = System.currentTimeMillis();\n for( int i = 0; i &lt; 10000000; i++ ) {\n StringBuilder sb2 = new StringBuilder();\n sb2.append( \"someString\" );\n sb2.append( \"someString2\" );\n sb2.append( \"someStrin4g\" );\n sb2.append( \"someStr5ing\" );\n sb2.append( \"someSt7ring\" );\n a = sb2.toString();\n }\n System.out.println( System.currentTimeMillis()-time );\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>5016\n7516\n</code></pre>\n" }, { "answer_id": 242536, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>Okay, I now understand what's going on, and it does make sense.</p>\n\n<p>I was under the impression that <code>toString</code> just passed the underlying <code>char[]</code> into a String constructor which <em>didn't</em> take a copy. A copy would then be made on the next \"write\" operation (e.g. <code>delete</code>). I believe this <em>was</em> the case with <code>StringBuffer</code> in some previous version. (It isn't now.) But no - <code>toString</code> just passes the array (and index and length) to the public <code>String</code> constructor which takes a copy.</p>\n\n<p>So in the \"reuse the <code>StringBuilder</code>\" case we genuinely create one copy of the data per string, using the same char array in the buffer the whole time. Obviously creating a new <code>StringBuilder</code> each time creates a new underlying buffer - and then that buffer is copied (somewhat pointlessly, in our particular case, but done for safety reasons) when creating a new string.</p>\n\n<p>All this leads to the second version definitely being more efficient - but at the same time I'd still say it's uglier code.</p>\n" }, { "answer_id": 243392, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Declare once, and assign each time. It is a more pragmatic and reusable concept than an optimization.</p>\n" }, { "answer_id": 248919, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 0, "selected": false, "text": "<p>The first is better for humans. If the second is a bit faster on some versions of some JVMs, so what?</p>\n\n<p>If performance is that critical, bypass StringBuilder and write your own. If you're a good programmer, and take into account how your app is using this function, you should be able to make it even faster. Worthwhile? Probably not.</p>\n\n<p>Why is this question stared as \"favorite question\"? Because performance optimization is so much fun, no matter whether it is practical or not.</p>\n" }, { "answer_id": 250110, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 3, "selected": false, "text": "<p>Since I don't think it's been pointed out yet, because of optimizations built into the Sun Java compiler, which automatically creates StringBuilders (StringBuffers pre-J2SE 5.0) when it sees String concatenations, the first example in the question is equivalent to:</p>\n\n<pre><code>for (loop condition) {\n String s = \"some string\";\n . . .\n s += anotherString;\n . . .\n passToMethod(s);\n}\n</code></pre>\n\n<p>Which is more readable, IMO, the better approach. Your attempts to optimize may result in gains in some platform, but potentially losses others.</p>\n\n<p>But if you really are running into issues with performance, then sure, optimize away. I'd start with explicitly specifying the buffer size of the StringBuilder though, per Jon Skeet.</p>\n" }, { "answer_id": 1025697, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 5, "selected": false, "text": "<p>Faster still:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ScratchPad {\n\n private static String a;\n\n public static void main( String[] args ) throws Exception {\n final long time = System.currentTimeMillis();\n\n // Pre-allocate enough space to store all appended strings.\n // StringBuilder, ultimately, uses an array of characters.\n final StringBuilder sb = new StringBuilder( 128 );\n\n for( int i = 0; i &lt; 10000000; i++ ) {\n // Resetting the string is faster than creating a new object.\n // Since this is a critical loop, every instruction counts.\n sb.setLength( 0 );\n sb.append( &quot;someString&quot; );\n sb.append( &quot;someString2&quot; );\n sb.append( &quot;someStrin4g&quot; );\n sb.append( &quot;someStr5ing&quot; );\n sb.append( &quot;someSt7ring&quot; );\n setA( sb.toString() );\n }\n\n System.out.println( System.currentTimeMillis() - time );\n }\n\n private static void setA( final String aString ) {\n a = aString;\n }\n}\n</code></pre>\n<p>In the philosophy of writing solid code, the inner workings of the method are hidden from the client objects. Thus it makes no difference from the system's perspective whether you re-declare the <code>StringBuilder</code> within the loop or outside of the loop. Since declaring it outside of the loop is faster, and it does not make the code significantly more complicated, reuse the object.</p>\n<p>Even if it was much more complicated, and you knew for certain that object instantiation was the bottleneck, comment it.</p>\n<p>Three runs with this answer:</p>\n<pre><code>$ java ScratchPad\n1567\n$ java ScratchPad\n1569\n$ java ScratchPad\n1570\n</code></pre>\n<p>Three runs with the other answer:</p>\n<pre><code>$ java ScratchPad2\n1663\n2231\n$ java ScratchPad2\n1656\n2233\n$ java ScratchPad2\n1658\n2242\n</code></pre>\n<p>Although not significant, setting the <code>StringBuilder</code>'s initial buffer size, to prevent memory re-allocations, will give a small performance gain.</p>\n" }, { "answer_id": 1134977, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 1, "selected": false, "text": "<p>The reason why doing a 'setLength' or 'delete' improves the performance is mostly the code 'learning' the right size of the buffer, and less to do the memory allocation. Generally, <a href=\"http://www.theeggeadventure.com/wikimedia/index.php/String_Concatenation_optimization\" rel=\"nofollow noreferrer\">I recommend letting the compiler do the string optimizations</a>. However, if the performance is critical, I'll often pre-calculate the expected size of the buffer. The default StringBuilder size is 16 characters. If you grow beyond that, then it has to resize. Resizing is where the performance is getting lost. Here's another mini-benchmark which illustrates this:</p>\n\n<pre><code>private void clear() throws Exception {\n long time = System.currentTimeMillis();\n int maxLength = 0;\n StringBuilder sb = new StringBuilder();\n\n for( int i = 0; i &lt; 10000000; i++ ) {\n // Resetting the string is faster than creating a new object.\n // Since this is a critical loop, every instruction counts.\n //\n sb.setLength( 0 );\n sb.append( \"someString\" );\n sb.append( \"someString2\" ).append( i );\n sb.append( \"someStrin4g\" ).append( i );\n sb.append( \"someStr5ing\" ).append( i );\n sb.append( \"someSt7ring\" ).append( i );\n maxLength = Math.max(maxLength, sb.toString().length());\n }\n\n System.out.println(maxLength);\n System.out.println(\"Clear buffer: \" + (System.currentTimeMillis()-time) );\n}\n\nprivate void preAllocate() throws Exception {\n long time = System.currentTimeMillis();\n int maxLength = 0;\n\n for( int i = 0; i &lt; 10000000; i++ ) {\n StringBuilder sb = new StringBuilder(82);\n sb.append( \"someString\" );\n sb.append( \"someString2\" ).append( i );\n sb.append( \"someStrin4g\" ).append( i );\n sb.append( \"someStr5ing\" ).append( i );\n sb.append( \"someSt7ring\" ).append( i );\n maxLength = Math.max(maxLength, sb.toString().length());\n }\n\n System.out.println(maxLength);\n System.out.println(\"Pre allocate: \" + (System.currentTimeMillis()-time) );\n}\n\npublic void testBoth() throws Exception {\n for(int i = 0; i &lt; 5; i++) {\n clear();\n preAllocate();\n }\n}\n</code></pre>\n\n<p>The results show reusing the object is about 10% faster than creating a buffer of the expected size.</p>\n" }, { "answer_id": 4467844, "author": "Ting Choo Chiaw", "author_id": 545669, "author_profile": "https://Stackoverflow.com/users/545669", "pm_score": 1, "selected": false, "text": "<p>LOL, first time i ever seen people compared the performance by combining string in StringBuilder. For that purpose, if you use \"+\", it could be even faster ;D. The purpose of using StringBuilder to speed up for retrieval of the whole string as the concept of \"locality\". </p>\n\n<p>In the scenario that you retrieve a String value frequently that does not need frequent change, Stringbuilder allows higher performance of string retrieval. And that is the purpose of using Stringbuilder.. please do not MIS-Test the core purpose of that..</p>\n\n<p>Some people said, Plane flies faster. Therefore, i test it with my bike, and found that the plane move slower. Do you know how i set the experiment settings ;D</p>\n" }, { "answer_id": 16941816, "author": "johnmartel", "author_id": 1270280, "author_profile": "https://Stackoverflow.com/users/1270280", "pm_score": 1, "selected": false, "text": "<p>Not significantly faster, but from my tests it shows on average to be a couple millis faster using 1.6.0_45 64 bits:\nuse StringBuilder.setLength(0) instead of StringBuilder.delete():</p>\n\n<pre><code>time = System.currentTimeMillis();\nStringBuilder sb2 = new StringBuilder();\nfor (int i = 0; i &lt; 10000000; i++) {\n sb2.append( \"someString\" );\n sb2.append( \"someString2\"+i );\n sb2.append( \"someStrin4g\"+i );\n sb2.append( \"someStr5ing\"+i );\n sb2.append( \"someSt7ring\"+i );\n a = sb2.toString();\n sb2.setLength(0);\n}\nSystem.out.println( System.currentTimeMillis()-time );\n</code></pre>\n" }, { "answer_id": 19075395, "author": "Shen liang", "author_id": 1765981, "author_profile": "https://Stackoverflow.com/users/1765981", "pm_score": 1, "selected": false, "text": "<p>The fastest way is to use \"setLength\". It won't involve the copying operation. <strong>The way to create a new StringBuilder should be completely out</strong>. The slow for the StringBuilder.delete(int start, int end) is because it will copy the array again for the resizing part. </p>\n\n<pre><code> System.arraycopy(value, start+len, value, start, count-end);\n</code></pre>\n\n<p>After that, the StringBuilder.delete() will update the StringBuilder.count to the new size. While the StringBuilder.setLength() just simplify update the <em>StringBuilder.count</em> to the new size. </p>\n" }, { "answer_id": 58503489, "author": "Ulrich K.", "author_id": 12257130, "author_profile": "https://Stackoverflow.com/users/12257130", "pm_score": 0, "selected": false, "text": "<p>I don't think that it make sence to try to optimize performance like that.\nToday (2019) the both statments are running about 11sec for 100.000.000 loops on my I5 Laptop:</p>\n\n<pre><code> String a;\n StringBuilder sb = new StringBuilder();\n long time = 0;\n\n System.gc();\n time = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000000; i++) {\n StringBuilder sb3 = new StringBuilder();\n sb3.append(\"someString\");\n sb3.append(\"someString2\");\n sb3.append(\"someStrin4g\");\n sb3.append(\"someStr5ing\");\n sb3.append(\"someSt7ring\");\n a = sb3.toString();\n }\n System.out.println(System.currentTimeMillis() - time);\n\n System.gc();\n time = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000000; i++) {\n sb.setLength(0);\n sb.delete(0, sb.length());\n sb.append(\"someString\");\n sb.append(\"someString2\");\n sb.append(\"someStrin4g\");\n sb.append(\"someStr5ing\");\n sb.append(\"someSt7ring\");\n a = sb.toString();\n }\n System.out.println(System.currentTimeMillis() - time);\n</code></pre>\n\n<p>==> 11000 msec(declaration inside loop) and 8236 msec(declaration outside loop)</p>\n\n<p>Even if I'am running programms for address dedublication with some billion loops \na difference of 2 sec. for 100 million loops does not make any difference because that programs are running for hours.\nAlso be aware that things are different if you only have one append statement:</p>\n\n<pre><code> System.gc();\n time = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000000; i++) {\n StringBuilder sb3 = new StringBuilder();\n sb3.append(\"someString\");\n a = sb3.toString();\n }\n System.out.println(System.currentTimeMillis() - time);\n\n System.gc();\n time = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000000; i++) {\n sb.setLength(0);\n sb.delete(0, sb.length());\n sb.append(\"someString\");\n a = sb.toString();\n }\n System.out.println(System.currentTimeMillis() - time);\n</code></pre>\n\n<p>==> 3416 msec(inside loop), 3555 msec(outside loop)\nThe first statement which is creating the StringBuilder within the loop is faster in that case.\nAnd, if you change the order of execution it is much more faster:</p>\n\n<pre><code> System.gc();\n time = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000000; i++) {\n sb.setLength(0);\n sb.delete(0, sb.length());\n sb.append(\"someString\");\n a = sb.toString();\n }\n System.out.println(System.currentTimeMillis() - time);\n\n System.gc();\n time = System.currentTimeMillis();\n for (int i = 0; i &lt; 100000000; i++) {\n StringBuilder sb3 = new StringBuilder();\n sb3.append(\"someString\");\n a = sb3.toString();\n }\n System.out.println(System.currentTimeMillis() - time);\n</code></pre>\n\n<p>==> 3638 msec(outside loop), 2908 msec(inside loop)</p>\n\n<p>Regards,\nUlrich</p>\n" }, { "answer_id": 72210343, "author": "Volksman", "author_id": 257364, "author_profile": "https://Stackoverflow.com/users/257364", "pm_score": 0, "selected": false, "text": "<p>The practice of not recreating so many new objects in a tight loop, where easily avoidable, definitely has a clear and obvious benefit as shown by the performance benchmarks.</p>\n<p>However it also has a more subtle benefit that no one has mentioned.</p>\n<p>This secondary benefit is related to an application freeze I saw in a large app processing the persistent objects produced after parsing CSV files with millions of lines/records and each record having about 140 fields.</p>\n<p>Creating a new object here and there doesn't normally affect the garbage collector's workload.</p>\n<p>Creating two new objects in a tight loop that iterates through each of the 140 fields in each of the millions of records in the aforementioned app incurs more than just mere wasted CPU cycles. It places a massive burden on the GC.</p>\n<p>For the objects created by parsing a CSV file with 10 million lines the GC was being asked to allocate then clean up 2 x 140 x 10,000,000 = 2.8 billion objects!!!</p>\n<p>If at any stage of the amount of free memory gets scarce e.g. the app has been asked to process multiple large files simultaneously, then you run the risk that the app ends up doing way more GC'ing than actual real work. When the GC effort takes up more than 98% of the CPU time then BANG! You get one of these dreaded exceptions:</p>\n<p><strong>GC Overhead Limit Exceeded</strong></p>\n<p><a href=\"https://www.baeldung.com/java-gc-overhead-limit-exceeded\" rel=\"nofollow noreferrer\">https://www.baeldung.com/java-gc-overhead-limit-exceeded</a></p>\n<p>In that case rewriting the code to reuse objects like the StringBuilder instead of instantiating a new one at each iteration can really avoid a lot of GC activity (by not instantiating an extra 2.8 billion objects unnecessarily), reduce the chance of it throwing a &quot;GC Overhead Limit Exceeded&quot; exception and drastically improve the app's general performance even when it is not yet tight on memory.</p>\n<p>Clearly, &quot;leaving to the JVM to optimize&quot; can not be a &quot;rule of thumb&quot; applicable to all scenarios.</p>\n<p>With the sort of metrics associated with known large input files nobody who writes code to avoid the unnecessary creation of 2.8 billion objects should ever be accused by the &quot;puritanicals&quot; of &quot;Pre-Optimizing&quot; ;)</p>\n<p>Any dev with half a brain and the slightest amount of foresight could see that this type of optimization for the expected input file size was warranted from day one.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27789/" ]
I've a performance related question regarding use of StringBuilder. In a very long loop I'm manipulating a `StringBuilder` and passing it to another method like this: ``` for (loop condition) { StringBuilder sb = new StringBuilder(); sb.append("some string"); . . . sb.append(anotherString); . . . passToMethod(sb.toString()); } ``` Is instantiating `StringBuilder` at every loop cycle is a good solution? And is calling a delete instead better, like the following? ``` StringBuilder sb = new StringBuilder(); for (loop condition) { sb.delete(0, sb.length); sb.append("some string"); . . . sb.append(anotherString); . . . passToMethod(sb.toString()); } ```
The second one is about 25% faster in my mini-benchmark. ``` public class ScratchPad { static String a; public static void main( String[] args ) throws Exception { long time = System.currentTimeMillis(); for( int i = 0; i < 10000000; i++ ) { StringBuilder sb = new StringBuilder(); sb.append( "someString" ); sb.append( "someString2"+i ); sb.append( "someStrin4g"+i ); sb.append( "someStr5ing"+i ); sb.append( "someSt7ring"+i ); a = sb.toString(); } System.out.println( System.currentTimeMillis()-time ); time = System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); for( int i = 0; i < 10000000; i++ ) { sb.delete( 0, sb.length() ); sb.append( "someString" ); sb.append( "someString2"+i ); sb.append( "someStrin4g"+i ); sb.append( "someStr5ing"+i ); sb.append( "someSt7ring"+i ); a = sb.toString(); } System.out.println( System.currentTimeMillis()-time ); } } ``` Results: ``` 25265 17969 ``` Note that this is with JRE 1.6.0\_07. --- Based on Jon Skeet's ideas in the edit, here's version 2. Same results though. ``` public class ScratchPad { static String a; public static void main( String[] args ) throws Exception { long time = System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); for( int i = 0; i < 10000000; i++ ) { sb.delete( 0, sb.length() ); sb.append( "someString" ); sb.append( "someString2" ); sb.append( "someStrin4g" ); sb.append( "someStr5ing" ); sb.append( "someSt7ring" ); a = sb.toString(); } System.out.println( System.currentTimeMillis()-time ); time = System.currentTimeMillis(); for( int i = 0; i < 10000000; i++ ) { StringBuilder sb2 = new StringBuilder(); sb2.append( "someString" ); sb2.append( "someString2" ); sb2.append( "someStrin4g" ); sb2.append( "someStr5ing" ); sb2.append( "someSt7ring" ); a = sb2.toString(); } System.out.println( System.currentTimeMillis()-time ); } } ``` Results: ``` 5016 7516 ```
242,444
<p>I have a little pet web app project I'd like to show someone who doesn't have an application server themselves (and who has no clue about application servers).</p> <p>What is the easiest and quickest way for them to get my WAR file running with zero configuration, preferably something I could send along with or bundle with the WAR file? Is there a slimmed down version of Jetty, for example? Something else?</p>
[ { "answer_id": 242459, "author": "tunaranch", "author_id": 27708, "author_profile": "https://Stackoverflow.com/users/27708", "pm_score": 2, "selected": false, "text": "<p>If you're using maven, there's a jetty maven plugin that can deploy your war to an embedded instance of jetty.</p>\n\n<p>But even otherwise, depending on what sort of stuff your app needs, jetty or even tomcat will do.</p>\n" }, { "answer_id": 242476, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>You can create the slimmed down version yourself easily.</p>\n\n<p><a href=\"http://docs.codehaus.org/display/JETTY/Embedding+Jetty\" rel=\"nofollow noreferrer\">http://docs.codehaus.org/display/JETTY/Embedding+Jetty</a></p>\n\n<p><a href=\"http://jetty.mortbay.org/xref/org/mortbay/jetty/example/LikeJettyXml.html\" rel=\"nofollow noreferrer\">http://jetty.mortbay.org/xref/org/mortbay/jetty/example/LikeJettyXml.html</a></p>\n\n<p>To run embedded Jetty you need only the following jars on the classpath:</p>\n\n<pre><code>* servlet-api-2.5-6.x.jar\n* jetty-util-6.x.jar\n* jetty-6.x.jar\n\n\n/usr/local/jetty-6.1.4/lib&gt; ls -la servlet-api-2.5-6.1.4.jar jetty-*\n-rw-rw-r-- 1 wwwrun admin 476213 2007-06-15 08:42 jetty-6.1.4.jar\n-rw-rw-r-- 1 wwwrun admin 128026 2007-06-15 08:40 jetty-util-6.1.4.jar\n-rw-rw-r-- 1 wwwrun admin 131977 2007-06-15 08:40 servlet-api-2.5-6.1.4.jar\n</code></pre>\n\n<p>Very light... </p>\n\n<p>Alternatively, the Maven <a href=\"http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin\" rel=\"nofollow noreferrer\">plugin</a> can work as well.</p>\n" }, { "answer_id": 242479, "author": "Russell Leggett", "author_id": 2828, "author_profile": "https://Stackoverflow.com/users/2828", "pm_score": 0, "selected": false, "text": "<p>I would definitely just create an executable jar that embeds jetty and uses your war. The maven thing might be ok, but it's pretty easy to just write the single main function yourself.</p>\n" }, { "answer_id": 274244, "author": "Randin", "author_id": 3932, "author_profile": "https://Stackoverflow.com/users/3932", "pm_score": 2, "selected": false, "text": "<p>If you don't know or do not want to mess with maven you could try Jetty-runner</p>\n\n<p><a href=\"https://svn.codehaus.org/jetty-contrib/trunk/jetty-runner\" rel=\"nofollow noreferrer\">https://svn.codehaus.org/jetty-contrib/trunk/jetty-runner</a></p>\n\n<p>jetty-runner.jar is one jar file that you can run from command line like so:</p>\n\n<p>java -jar jetty-runner.jar my.war</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have a little pet web app project I'd like to show someone who doesn't have an application server themselves (and who has no clue about application servers). What is the easiest and quickest way for them to get my WAR file running with zero configuration, preferably something I could send along with or bundle with the WAR file? Is there a slimmed down version of Jetty, for example? Something else?
You can create the slimmed down version yourself easily. <http://docs.codehaus.org/display/JETTY/Embedding+Jetty> <http://jetty.mortbay.org/xref/org/mortbay/jetty/example/LikeJettyXml.html> To run embedded Jetty you need only the following jars on the classpath: ``` * servlet-api-2.5-6.x.jar * jetty-util-6.x.jar * jetty-6.x.jar /usr/local/jetty-6.1.4/lib> ls -la servlet-api-2.5-6.1.4.jar jetty-* -rw-rw-r-- 1 wwwrun admin 476213 2007-06-15 08:42 jetty-6.1.4.jar -rw-rw-r-- 1 wwwrun admin 128026 2007-06-15 08:40 jetty-util-6.1.4.jar -rw-rw-r-- 1 wwwrun admin 131977 2007-06-15 08:40 servlet-api-2.5-6.1.4.jar ``` Very light... Alternatively, the Maven [plugin](http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin) can work as well.
242,468
<p>In my ASP.NET application I have a web.config file. In the web.config file I have a connection string...</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="HRDb" connectionString="xxxxx" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>Yet, when I retrieve this value using <code>ConfigurationManager.ConnectionStringsp["HRDb"]</code>, I get the my old connection string, not the new one.</p> <p>Where else (apart from web.config) does the <code>ConfigurationManager</code> read connection string values from?</p> <p>I'm running the application from VS.NET (not deployed to IIS).</p>
[ { "answer_id": 242481, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 0, "selected": false, "text": "<p>Where was the 'old' value stored? Is it in a different config file? The config manager should only pull from the config files, but there can be multiple files for an application. Is part of your build process copying in an old file?</p>\n" }, { "answer_id": 242490, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "<p>It is also possible, although unlikely, that you have a connection string defined in a \"parent\" web.config in a folder above your current folder or even in machine.config. \nTry to add a <code>&lt;clear /&gt;</code> element before the <code>&lt;add&gt;</code> element.</p>\n" }, { "answer_id": 242499, "author": "willem", "author_id": 22702, "author_profile": "https://Stackoverflow.com/users/22702", "pm_score": 3, "selected": true, "text": "<p>I figured out what was going wrong.</p>\n\n<p>So to answer my own question... ConfigurationManager only reads from web.config.</p>\n\n<p>My problem was that the project was configured to use an IIS web server when running the project instead of using the Visual Studio Development server. So I was in fact running an old version of my application. Silly.</p>\n" }, { "answer_id": 3516737, "author": "jeroentrappers", "author_id": 424549, "author_profile": "https://Stackoverflow.com/users/424549", "pm_score": 0, "selected": false, "text": "<p>I've had a similar problem, where the solution was that I was holding the wrong web.config, one that was generated by visual studio when adding a file or so.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22702/" ]
In my ASP.NET application I have a web.config file. In the web.config file I have a connection string... ``` <connectionStrings> <add name="HRDb" connectionString="xxxxx" providerName="System.Data.SqlClient" /> </connectionStrings> ``` Yet, when I retrieve this value using `ConfigurationManager.ConnectionStringsp["HRDb"]`, I get the my old connection string, not the new one. Where else (apart from web.config) does the `ConfigurationManager` read connection string values from? I'm running the application from VS.NET (not deployed to IIS).
I figured out what was going wrong. So to answer my own question... ConfigurationManager only reads from web.config. My problem was that the project was configured to use an IIS web server when running the project instead of using the Visual Studio Development server. So I was in fact running an old version of my application. Silly.
242,485
<p>This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I am not against having an extra import statement at the top of the file, nor a few extra lines of code.</p>
[ { "answer_id": 242506, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 5, "selected": false, "text": "<p>This isn't the debugger, but probably just as useful(?)</p>\n\n<p>I know I heard Guido mention this in a speech somewhere.</p>\n\n<p>I just checked python -?, and if you use the -i command you can interact where your script stopped.</p>\n\n<p>So given this script:</p>\n\n<pre><code>testlist = [1,2,3,4,5, 0]\n\nprev_i = None\nfor i in testlist:\n if not prev_i:\n prev_i = i\n else:\n result = prev_i/i\n</code></pre>\n\n<p>You can get this output!</p>\n\n<pre><code>PS D:\\&gt; python -i debugtest.py\nTraceback (most recent call last):\n File \"debugtest.py\", line 10, in &lt;module&gt;\n result = prev_i/i\nZeroDivisionError: integer division or modulo by zero\n&gt;&gt;&gt;\n&gt;&gt;&gt;\n&gt;&gt;&gt; prev_i\n1\n&gt;&gt;&gt; i\n0\n&gt;&gt;&gt;\n</code></pre>\n\n<p>To be honest I haven't used this, but I should be, seems very useful.</p>\n" }, { "answer_id": 242514, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 8, "selected": true, "text": "<p>You can use <a href=\"http://docs.python.org/library/traceback.html#traceback.print_exc\" rel=\"noreferrer\">traceback.print_exc</a> to print the exceptions traceback. Then use <a href=\"http://docs.python.org/library/sys#sys.exc_info\" rel=\"noreferrer\">sys.exc_info</a> to extract the traceback and finally call <a href=\"http://docs.python.org/library/pdb#pdb.post_mortem\" rel=\"noreferrer\">pdb.post_mortem</a> with that traceback</p>\n<pre><code>import pdb, traceback, sys\n\ndef bombs():\n a = []\n print a[0]\n\nif __name__ == '__main__':\n try:\n bombs()\n except:\n extype, value, tb = sys.exc_info()\n traceback.print_exc()\n pdb.post_mortem(tb)\n</code></pre>\n<p>If you want to start an interactive command line with <a href=\"http://docs.python.org/library/code#code.interact\" rel=\"noreferrer\">code.interact</a> using the locals of the frame where the exception originated you can do</p>\n<pre><code>import traceback, sys, code\n\ndef bombs():\n a = []\n print a[0]\n\nif __name__ == '__main__':\n try:\n bombs()\n except:\n type, value, tb = sys.exc_info()\n traceback.print_exc()\n last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb\n frame = last_frame().tb_frame\n ns = dict(frame.f_globals)\n ns.update(frame.f_locals)\n code.interact(local=ns)\n</code></pre>\n" }, { "answer_id": 242531, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": false, "text": "<p>Use the following module:</p>\n\n<pre><code>import sys\n\ndef info(type, value, tb):\n if hasattr(sys, 'ps1') or not sys.stderr.isatty():\n # we are in interactive mode or we don't have a tty-like\n # device, so we call the default hook\n sys.__excepthook__(type, value, tb)\n else:\n import traceback, pdb\n # we are NOT in interactive mode, print the exception...\n traceback.print_exception(type, value, tb)\n print\n # ...then start the debugger in post-mortem mode.\n # pdb.pm() # deprecated\n pdb.post_mortem(tb) # more \"modern\"\n\nsys.excepthook = info\n</code></pre>\n\n<p>Name it <code>debug</code> (or whatever you like) and put it somewhere in your python path.</p>\n\n<p>Now, at the start of your script, just add an <code>import debug</code>.</p>\n" }, { "answer_id": 2438834, "author": "Catherine Devlin", "author_id": 86209, "author_profile": "https://Stackoverflow.com/users/86209", "pm_score": 9, "selected": false, "text": "<pre><code>python -m pdb -c continue myscript.py\n</code></pre>\n\n<p>If you don't provide the <code>-c continue</code> flag then you'll need to enter 'c' (for Continue) when execution begins. Then it will run to the error point and give you control there. As <a href=\"https://stackoverflow.com/questions/242485/starting-python-debugger-automatically-on-error#comment73725114_2438834\">mentioned by eqzx</a>, this flag is a new addition in python 3.2 so entering 'c' is required for earlier Python versions (see <a href=\"https://docs.python.org/3/library/pdb.html\" rel=\"noreferrer\">https://docs.python.org/3/library/pdb.html</a>).</p>\n" }, { "answer_id": 4873570, "author": "Amandasaurus", "author_id": 161922, "author_profile": "https://Stackoverflow.com/users/161922", "pm_score": 2, "selected": false, "text": "<p>You can put this line in your code:</p>\n\n<pre><code>import pdb ; pdb.set_trace()\n</code></pre>\n\n<p>More info: <a href=\"http://www.technomancy.org/python/debugger-start-line/\" rel=\"nofollow noreferrer\">Start the python debugger at any line</a></p>\n" }, { "answer_id": 13003378, "author": "Latanius", "author_id": 391376, "author_profile": "https://Stackoverflow.com/users/391376", "pm_score": 6, "selected": false, "text": "<p><strong>Ipython</strong> has a command for toggling this behavior: <strong>%pdb</strong>. It does exactly what you described, maybe even a bit more (giving you more informative backtraces with syntax highlighting and code completion). It's definitely worth a try!</p>\n" }, { "answer_id": 23113690, "author": "vlad-ardelean", "author_id": 1037251, "author_profile": "https://Stackoverflow.com/users/1037251", "pm_score": -1, "selected": false, "text": "<p>Put a breakpoint inside the constructor of topmost exception class in the hierarchy, and most of the times you will see where the error was raised.</p>\n\n<p>Putting a breakpoint means whatever you want it to mean : you can use an IDE, or <code>pdb.set_trace</code>, or whatever</p>\n" }, { "answer_id": 34733850, "author": "Zlatko Karakaš", "author_id": 4447387, "author_profile": "https://Stackoverflow.com/users/4447387", "pm_score": 2, "selected": false, "text": "<p>To have it run without having to type c at the beginning use:</p>\n\n<pre><code>python -m pdb -c c &lt;script name&gt;\n</code></pre>\n\n<p>Pdb has its own command line arguments: -c c will execute c(ontinue) command at start of execution and the program will run uninterrupted until the error.</p>\n" }, { "answer_id": 35039165, "author": "wodow", "author_id": 167806, "author_profile": "https://Stackoverflow.com/users/167806", "pm_score": 5, "selected": false, "text": "<p>IPython makes this simple on the command line:</p>\n\n<pre><code>python myscript.py arg1 arg2\n</code></pre>\n\n<p>can be rewritten to</p>\n\n<pre><code>ipython --pdb myscript.py -- arg1 arg2\n</code></pre>\n\n<p>Or, similarly, if calling a module:</p>\n\n<pre><code>python -m mymodule arg1 arg2\n</code></pre>\n\n<p>can be rewritten to</p>\n\n<pre><code>ipython --pdb -m mymodule -- arg1 arg2\n</code></pre>\n\n<p>Note the <code>--</code> to stop IPython from reading the script's arguments as its own.</p>\n\n<p>This also has the advantage of invoking the enhanced IPython debugger (ipdb) instead of pdb.</p>\n" }, { "answer_id": 35489235, "author": "blueFast", "author_id": 647991, "author_profile": "https://Stackoverflow.com/users/647991", "pm_score": 2, "selected": false, "text": "<p>If you are running a module:</p>\n\n<pre><code>python -m mymodule\n</code></pre>\n\n<p>And now you want to enter <code>pdb</code> when an exception occurs, do this:</p>\n\n<pre><code>PYTHONPATH=\".\" python -m pdb -c c mymodule/__main__.py\n</code></pre>\n\n<p>(or <em>extend</em> your <code>PYTHONPATH</code>). The <code>PYTHONPATH</code> is needed so that the module is found in the path, since you are running the <code>pdb</code> module now.</p>\n" }, { "answer_id": 41656242, "author": "Jehandad", "author_id": 3840400, "author_profile": "https://Stackoverflow.com/users/3840400", "pm_score": 3, "selected": false, "text": "<p>If you are using the IPython environment, you can just use the %debug and the shell will take you back to the offending line with the ipdb environment for inspections etc. Another option as pointed above is to use the iPython magic %pdb which effectively does the same.</p>\n" }, { "answer_id": 44708864, "author": "Hannah", "author_id": 7815769, "author_profile": "https://Stackoverflow.com/users/7815769", "pm_score": 2, "selected": false, "text": "<p>python -m pdb script.py in python2.7 press continue to start and it will run to the error and break there for debug.</p>\n" }, { "answer_id": 51050899, "author": "Willemoes", "author_id": 2047185, "author_profile": "https://Stackoverflow.com/users/2047185", "pm_score": 4, "selected": false, "text": "<p>If you are using <code>ipython</code>, after launching type <code>%pdb</code></p>\n\n<pre><code>In [1]: %pdb\nAutomatic pdb calling has been turned ON\n</code></pre>\n" }, { "answer_id": 65653479, "author": "dlukes", "author_id": 1826241, "author_profile": "https://Stackoverflow.com/users/1826241", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://pypi.org/project/ipdb/\" rel=\"nofollow noreferrer\"><code>ipdb</code></a> has a nice context manager to achieve this behavior which makes the intent semantically clearer:</p>\n<pre><code>from ipdb import launch_ipdb_on_exception\n\nwith launch_ipdb_on_exception():\n ...\n</code></pre>\n" }, { "answer_id": 71375486, "author": "Jonathan Dauwe", "author_id": 17229877, "author_profile": "https://Stackoverflow.com/users/17229877", "pm_score": 0, "selected": false, "text": "<p>Since 3.7, you can use the keyword <strong>breakpoint</strong> directly in your code (without any import), just like this:</p>\n<pre><code>try:\n ... # The line that raises an error\nexcept:\n breakpoint()\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24530/" ]
This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I am not against having an extra import statement at the top of the file, nor a few extra lines of code.
You can use [traceback.print\_exc](http://docs.python.org/library/traceback.html#traceback.print_exc) to print the exceptions traceback. Then use [sys.exc\_info](http://docs.python.org/library/sys#sys.exc_info) to extract the traceback and finally call [pdb.post\_mortem](http://docs.python.org/library/pdb#pdb.post_mortem) with that traceback ``` import pdb, traceback, sys def bombs(): a = [] print a[0] if __name__ == '__main__': try: bombs() except: extype, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb) ``` If you want to start an interactive command line with [code.interact](http://docs.python.org/library/code#code.interact) using the locals of the frame where the exception originated you can do ``` import traceback, sys, code def bombs(): a = [] print a[0] if __name__ == '__main__': try: bombs() except: type, value, tb = sys.exc_info() traceback.print_exc() last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb frame = last_frame().tb_frame ns = dict(frame.f_globals) ns.update(frame.f_locals) code.interact(local=ns) ```
242,504
<p>How can I generate a report in access with the data from a recordset (instead of a query or table). I have updates to the recordset that also must be shown in the report.</p>
[ { "answer_id": 242605, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": -1, "selected": false, "text": "<p>Please explain in more detail. For example, do you wish to show what the field was and what it is now? If so, you will need an audit trail. Here is an example from Microsoft: <a href=\"http://support.microsoft.com/kb/q197592/\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/q197592/</a></p>\n\n<p>What do you mean by report? If you mean a printed paper document, Access has a good report builder. If you mean you wish to view the data, you can use a form. If you are unfamilar with building reports and forms, there are wizards. </p>\n\n<p>It is always wise to study the Northwind sample database that ships with every version of Access.</p>\n" }, { "answer_id": 243544, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 3, "selected": true, "text": "<p>From <a href=\"http://www.mvps.org/access/reports/rpt0014.htm\" rel=\"nofollow noreferrer\">Access Web</a> you can use the \"name\" property of a recordset. You resulting code would look something like this:</p>\n\n<p><em>In the report</em> </p>\n\n<pre><code>Private Sub Report_Open(Cancel As Integer)\n Me.RecordSource = gMyRecordSet.Name\nEnd Sub\n</code></pre>\n\n<p><em>In the calling object (module, form, etc.)</em> </p>\n\n<pre><code>Public gMyRecordSet As Recordset\n'...\nPublic Sub callMyReport()\n '...\n Set gMyRecordSet = CurrentDb.OpenRecordset(\"Select * \" &amp; _\n \"from foo \" &amp; _\n \"where bar='yaddah'\")\n DoCmd.OpenReport \"myReport\", acViewPreview \n '...\n gMyRecordSet.Close \n Set gMyRecordSet = Nothing\n '...\nEnd Sub\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31132/" ]
How can I generate a report in access with the data from a recordset (instead of a query or table). I have updates to the recordset that also must be shown in the report.
From [Access Web](http://www.mvps.org/access/reports/rpt0014.htm) you can use the "name" property of a recordset. You resulting code would look something like this: *In the report* ``` Private Sub Report_Open(Cancel As Integer) Me.RecordSource = gMyRecordSet.Name End Sub ``` *In the calling object (module, form, etc.)* ``` Public gMyRecordSet As Recordset '... Public Sub callMyReport() '... Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _ "from foo " & _ "where bar='yaddah'") DoCmd.OpenReport "myReport", acViewPreview '... gMyRecordSet.Close Set gMyRecordSet = Nothing '... End Sub ```
242,517
<p>I have a certain application which feeds information into an object, after comparing the new information to the old information. It goes something like</p> <pre><code>set { oldval=_value; _value=value; if (some comparison logic) raiseEvent(); } </code></pre> <p>This all happens on a background thread, in an infinite loop, which intermittently sleeps for 100ms. The really odd part is that it works the first time, the comparison logic turns up true, and the event is raised. After that, the information keeps flowing, it keep entering the object, I know this because I set MessageBoxes to display the old and new values all the time, but its as if it somehow bypasses the set clause! I set a messagebox in the beginning of the clause, an it just doesn't pop up! This is really wierd, since I am sure that the value keeps updating.</p> <p>Any Thoughts?</p> <hr> <p>Yeah, I know, but unfortunately theres not much more I can show... Let me try to explain the overall structure again: I have a separate background thread running an infinite loop. This loop continuously pulls data from a Data object, which is updated by a whole other set of threads. All of this is of course under synchronization with Monitor.Enter and Exit. The data pulled from the Data object is then inputted into the Comparer object.</p> <pre><code>while(true) { Thread.Sleep(100); Monitor.Enter(Data); Comparer.Value = Data.Value; Monitor.Exit(Data); } </code></pre> <p>The Comparer.Value is the property I mentioned in the first post. Its really quite weird since I set up a MessageBox in the end of the loop:</p> <pre><code>MessageBox.Show(Comparer.Value + " - " + Data.Value); </code></pre> <p>and the values DO actually update, it just somehow seems to bypass the set clause, which is impossible... This is truly weird.</p> <p>And Rob, the loop doesn't do any of the checking, it just simulates a stream of information into Comparer.Value; It's set clause contains the comparison logic.</p> <p>bh213, I'm pretty that it is, but I can't tell because the comparison stops before any meaningful checking is done.</p> <hr> <p>Alright, I've solved the problem, apparently my question was wrong, the problem was in a whole other place. Thanks for all the help, the question may be closed.</p>
[ { "answer_id": 242519, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>You really need to give more information. All we've got here is some pseudocode. Try to come up with a <a href=\"http://pobox.com/~skeet/csharp/complete.html\" rel=\"nofollow noreferrer\">short but complete program</a> that demonstrates the problem.</p>\n" }, { "answer_id": 242521, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>Without some meaningful code, we can only guess. In particular, if adding a MessageBox to the start of the Set doesn't appear, then it is likely that the problem is at the calling code (not this).</p>\n\n<p>Some thoughts, though - especially since you have multiple threads:</p>\n\n<ul>\n<li>is there a thread race somewhere? should some of the code be synchronized?</li>\n<li>has the worker got a stale copy of a non-volatile value?</li>\n<li><strong>thread affinity</strong>: is something involving the worker and the UI borking things?</li>\n<li>are you sure you have the right instance (i.e. is it possible that the object firing the event isn't the same object you were listening for)?</li>\n</ul>\n\n<p>It could be none of these; without some example code we can't really help.</p>\n\n<p>I've marked <strong>thread affinity</strong> in bold, as this is a very likely problem if your worker is making changes that (via an event) the UI is listening for; the UI event-handler <em>must</em> switch to the UI thread to update the UI:</p>\n\n<pre><code>void SomeHandler(object sender, EventArgs args)\n{\n this.Invoke((MethodInvoker)delegate {\n this.Text = \"Something happened\";\n });\n}\n</code></pre>\n" }, { "answer_id": 242533, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>Previous answers are totally right in that you need to provide more information.</p>\n\n<p>But can I ask <em>why</em> you are doing it like this? Surely your business model would just raise an event when the value is set, why is there a background thread running to intermittently check?</p>\n\n<p>Maybe I am just missing something, but it just seems that there is likely a design flaw here that is causing the <em>real</em> issue.</p>\n" }, { "answer_id": 242537, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 0, "selected": false, "text": "<p>Since event is being raised on background thread all your event handlers are being run on that (background) thread. Is your code handling this correctly?</p>\n" }, { "answer_id": 242559, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 0, "selected": false, "text": "<p>As others said, you really need to create a small working example to show the problem.</p>\n\n<p>Probably you will even notice the source of your problem yourself while you create this sample app.</p>\n" }, { "answer_id": 242575, "author": "Marco M.", "author_id": 28375, "author_profile": "https://Stackoverflow.com/users/28375", "pm_score": 2, "selected": false, "text": "<p>Spam System.Diagnostic.Debug.WriteLine around instead of messageboxes.\nThese do not (or at least they do only to a minimum) change the instruction flow and have no threading issues (apart possible bad output).</p>\n\n<p>Also, from the description, it seems a simple debug session with some carefully placed breakpoint might help.</p>\n\n<p>Third, what is the \"(some comparison logic)\" ?</p>\n\n<p>If it is a simple (oldval != _value) rewrite it as </p>\n\n<pre><code>set\n{\n if (_value != value)\n {\n _value=value;\n RaiseSomeEvent();\n }\n}\n</code></pre>\n\n<p>it's cleaner and you have no chance of _value changing without the event being raised (apart no subscribed handlers..).</p>\n\n<p>Otherwise the \"(some comparison logic)\" expression is likely the bugged location.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30884/" ]
I have a certain application which feeds information into an object, after comparing the new information to the old information. It goes something like ``` set { oldval=_value; _value=value; if (some comparison logic) raiseEvent(); } ``` This all happens on a background thread, in an infinite loop, which intermittently sleeps for 100ms. The really odd part is that it works the first time, the comparison logic turns up true, and the event is raised. After that, the information keeps flowing, it keep entering the object, I know this because I set MessageBoxes to display the old and new values all the time, but its as if it somehow bypasses the set clause! I set a messagebox in the beginning of the clause, an it just doesn't pop up! This is really wierd, since I am sure that the value keeps updating. Any Thoughts? --- Yeah, I know, but unfortunately theres not much more I can show... Let me try to explain the overall structure again: I have a separate background thread running an infinite loop. This loop continuously pulls data from a Data object, which is updated by a whole other set of threads. All of this is of course under synchronization with Monitor.Enter and Exit. The data pulled from the Data object is then inputted into the Comparer object. ``` while(true) { Thread.Sleep(100); Monitor.Enter(Data); Comparer.Value = Data.Value; Monitor.Exit(Data); } ``` The Comparer.Value is the property I mentioned in the first post. Its really quite weird since I set up a MessageBox in the end of the loop: ``` MessageBox.Show(Comparer.Value + " - " + Data.Value); ``` and the values DO actually update, it just somehow seems to bypass the set clause, which is impossible... This is truly weird. And Rob, the loop doesn't do any of the checking, it just simulates a stream of information into Comparer.Value; It's set clause contains the comparison logic. bh213, I'm pretty that it is, but I can't tell because the comparison stops before any meaningful checking is done. --- Alright, I've solved the problem, apparently my question was wrong, the problem was in a whole other place. Thanks for all the help, the question may be closed.
Without some meaningful code, we can only guess. In particular, if adding a MessageBox to the start of the Set doesn't appear, then it is likely that the problem is at the calling code (not this). Some thoughts, though - especially since you have multiple threads: * is there a thread race somewhere? should some of the code be synchronized? * has the worker got a stale copy of a non-volatile value? * **thread affinity**: is something involving the worker and the UI borking things? * are you sure you have the right instance (i.e. is it possible that the object firing the event isn't the same object you were listening for)? It could be none of these; without some example code we can't really help. I've marked **thread affinity** in bold, as this is a very likely problem if your worker is making changes that (via an event) the UI is listening for; the UI event-handler *must* switch to the UI thread to update the UI: ``` void SomeHandler(object sender, EventArgs args) { this.Invoke((MethodInvoker)delegate { this.Text = "Something happened"; }); } ```
242,534
<pre><code>private const int THE_ANSWER = 42; </code></pre> <p>or</p> <pre><code>private const int theAnswer = 42; </code></pre> <p>Personally I think with modern IDEs we should go with camelCase as ALL_CAPS looks strange. What do you think?</p>
[ { "answer_id": 242539, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 4, "selected": false, "text": "<p>Leave Hungarian to the Hungarians.</p>\n\n<p>In the example I'd even leave out the definitive article and just go with </p>\n\n<pre><code>private const int Answer = 42;\n</code></pre>\n\n<p>Is that answer or is that the answer?</p>\n\n<p>*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to <a href=\"http://en.wikipedia.org/wiki/Life,_the_Universe_and_Everything\" rel=\"noreferrer\">life, the universe and everything</a>.</p>\n" }, { "answer_id": 242540, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 3, "selected": false, "text": "<p>The ALL_CAPS is taken from the C and C++ way of working I believe. This article <a href=\"http://blogs.msdn.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx\" rel=\"noreferrer\">here</a> explains how the style differences came about.</p>\n\n<p>In the new IDE's such as Visual Studio it is easy to identify the types, scope and if they are constant so it is not strictly necessary. </p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/FxCop\" rel=\"noreferrer\">FxCop</a> and Microsoft <a href=\"http://en.wikipedia.org/wiki/StyleCop\" rel=\"noreferrer\">StyleCop</a> software will help give you guidelines and check your code so everyone works the same way.</p>\n" }, { "answer_id": 242541, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 5, "selected": false, "text": "<p>I still go with the uppercase for const values, but this is more out of habit than for any particular reason. </p>\n\n<p>Of course it makes it easy to see immediately that something is a const. The question to me is: Do we really need this information? Does it help us in any way to avoid errors? If I assign a value to the const, the compiler will tell me I did something dumb. </p>\n\n<p>My conclusion: Go with the camel casing. Maybe I will change my style too ;-)</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>That something <em>smells</em> hungarian is not really a valid argument, IMO. The question should always be: Does it help, or does it hurt?</p>\n\n<p>There are cases when hungarian helps. Not that many nowadays, but they still exist. </p>\n" }, { "answer_id": 242545, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 6, "selected": false, "text": "<p>Actually, it is </p>\n\n<pre><code>private const int TheAnswer = 42;\n</code></pre>\n\n<p>At least if you look at the .NET library, which IMO is the best way to decide naming conventions - so your code doesn't look out of place.</p>\n" }, { "answer_id": 242549, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 10, "selected": true, "text": "<p>The recommended naming and capitalization convention is to use <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"noreferrer\"><strong>P</strong>ascal<strong>C</strong>asing</a> for constants (Microsoft has a tool named <a href=\"https://github.com/StyleCop\" rel=\"noreferrer\">StyleCop</a> that documents all the preferred conventions and can check your source for compliance - though it is a little bit <em>too</em> anally retentive for many people's tastes). e.g.</p>\n\n<pre><code>private const int TheAnswer = 42;\n</code></pre>\n\n<p>The Pascal capitalization convention is also documented in Microsoft's <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"noreferrer\">Framework Design Guidelines</a>.</p>\n" }, { "answer_id": 242554, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>I actually tend to prefer PascalCase here - but out of habit, I'm guilty of UPPER_CASE...</p>\n" }, { "answer_id": 242824, "author": "user31939", "author_id": 31939, "author_profile": "https://Stackoverflow.com/users/31939", "pm_score": 4, "selected": false, "text": "<p>First, Hungarian Notation is the practice of using a prefix to display a parameter's data type or intended use.\nMicrosoft's naming conventions for says no to Hungarian Notation\n<a href=\"http://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Hungarian_notation</a>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms229045.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms229045.aspx</a></p>\n\n<p>Using UPPERCASE is not encouraged as stated here:\nPascal Case is the acceptable convention and SCREAMING CAPS.\n<a href=\"http://en.wikibooks.org/wiki/C_Sharp_Programming/Naming\" rel=\"noreferrer\">http://en.wikibooks.org/wiki/C_Sharp_Programming/Naming</a> </p>\n\n<p>Microsoft also states here that UPPERCASE can be used if it is done to match the the existed scheme.\n<a href=\"http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx</a></p>\n\n<p>This pretty much sums it up. </p>\n" }, { "answer_id": 20890557, "author": "DavidRR", "author_id": 1497596, "author_profile": "https://Stackoverflow.com/users/1497596", "pm_score": 4, "selected": false, "text": "<p>In its article <a href=\"http://msdn.microsoft.com/en-us/library/ms173119.aspx\" rel=\"noreferrer\">Constants (C# Programming Guide)</a>, Microsoft gives the following example:</p>\n\n<pre><code>class Calendar3\n{\n const int months = 12;\n const int weeks = 52;\n const int days = 365;\n\n const double daysPerWeek = (double) days / (double) weeks;\n const double daysPerMonth = (double) days / (double) months;\n}\n</code></pre>\n\n<p>So, for constants, it <em>appears</em> that Microsoft is recommending the use of <a href=\"http://msdn.microsoft.com/en-us/library/ms229043.aspx\" rel=\"noreferrer\"><code>camelCasing</code></a>. But note that these constants are defined <strong>locally</strong>.</p>\n\n<p>Arguably, the naming of externally-visible constants is of greater interest. In practice, Microsoft documents its <strong>public constants</strong> in the .NET class library as <strong>fields</strong>. Here are some examples:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.int32.maxvalue%28v=vs.110%29.aspx\" rel=\"noreferrer\">Int32.MaxValue</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.string.empty%28v=vs.110%29.aspx\" rel=\"noreferrer\">String.Empty</a> <em>(actually,</em> <code>static readonly</code><em>)</em></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.math.pi%28v=vs.110%29.aspx\" rel=\"noreferrer\">Math.PI</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.math.e%28v=vs.110%29.aspx\" rel=\"noreferrer\">Math.E</a></li>\n</ul>\n\n<p>The first two are examples of <a href=\"http://msdn.microsoft.com/en-us/library/ms229043.aspx\" rel=\"noreferrer\"><code>PascalCasing</code></a>. The third appears to follow Microsoft's <a href=\"http://msdn.microsoft.com/en-us/library/ms229043.aspx\" rel=\"noreferrer\">Capitalization Conventions</a> for a two-letter acronym (although <a href=\"http://en.wikipedia.org/wiki/Pi\" rel=\"noreferrer\">pi</a> is not an acryonym). And the fourth one seems to suggest that the rule for a two-letter acryonym extends to a single letter acronym or identifier such as <code>E</code> (which represents the mathematical constant <a href=\"https://en.wikipedia.org/wiki/E_(mathematical_constant)\" rel=\"noreferrer\"><em>e</em></a>).</p>\n\n<p>Furthermore, in its Capitalization Conventions document, Microsoft very directly states that field identifiers should be named via <code>PascalCasing</code> and gives the following examples for <a href=\"http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.infinitetimeout%28v=vs.110%29.aspx\" rel=\"noreferrer\">MessageQueue.InfiniteTimeout</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.int32.minvalue%28v=vs.110%29.aspx\" rel=\"noreferrer\">UInt32.Min</a>:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class MessageQueue\n{\n public static readonly TimeSpan InfiniteTimeout;\n}\n\npublic struct UInt32\n{\n public const Min = 0;\n}\n</code></pre>\n\n<p><strong>Conclusion: Use <code>PascalCasing</code> for public constants</strong> (which are documented as <code>const</code> or <code>static readonly</code> fields).</p>\n\n<p>Finally, as far as I know, Microsoft does not advocate specific naming or capitalization conventions for <strong>private</strong> identifiers as shown in the examples presented in the question.</p>\n" }, { "answer_id": 23787775, "author": "usefulBee", "author_id": 2093880, "author_profile": "https://Stackoverflow.com/users/2093880", "pm_score": 7, "selected": false, "text": "<p>Visually, Upper Case is the way to go. It is so recognizable that way.\nFor the sake of uniqueness and leaving no chance for guessing, I vote for UPPER_CASE!</p>\n\n<pre><code>const int THE_ANSWER = 42;\n</code></pre>\n\n<p><strong>Note</strong>: The Upper Case will be useful when constants are to be used within the same file at the top of the page and for intellisense purposes; however, if they were to be moved to an independent class, using Upper Case would not make much difference, as an example: </p>\n\n<pre><code>public static class Constant\n{\n public static readonly int Cons1 = 1;\n public static readonly int coNs2 = 2;\n public static readonly int cOns3 = 3;\n public static readonly int CONS4 = 4;\n}\n\n// Call constants from anywhere\n// Since the class has a unique and recognizable name, Upper Case might lose its charm\nprivate void DoSomething(){\nvar getCons1 = Constant.Cons1;\nvar getCons2 = Constant.coNs2;\nvar getCons3 = Constant.cOns3;\nvar getCons4 = Constant.CONS4;\n }\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6846/" ]
``` private const int THE_ANSWER = 42; ``` or ``` private const int theAnswer = 42; ``` Personally I think with modern IDEs we should go with camelCase as ALL\_CAPS looks strange. What do you think?
The recommended naming and capitalization convention is to use [**P**ascal**C**asing](https://en.wikipedia.org/wiki/Camel_case) for constants (Microsoft has a tool named [StyleCop](https://github.com/StyleCop) that documents all the preferred conventions and can check your source for compliance - though it is a little bit *too* anally retentive for many people's tastes). e.g. ``` private const int TheAnswer = 42; ``` The Pascal capitalization convention is also documented in Microsoft's [Framework Design Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions).
242,538
<p>Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script file resides?</p>
[ { "answer_id": 242550, "author": "TheMarko", "author_id": 31099, "author_profile": "https://Stackoverflow.com/users/31099", "pm_score": 10, "selected": true, "text": "<p>In Bash, you should get what you need like this:</p>\n\n<pre><code>#!/usr/bin/env bash\n\nBASEDIR=$(dirname \"$0\")\necho \"$BASEDIR\"\n</code></pre>\n" }, { "answer_id": 242557, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 6, "selected": false, "text": "<p>Assuming you're using bash</p>\n<pre><code>#!/bin/bash\n\ncurrent_dir=$(pwd)\nscript_dir=$(dirname &quot;$0&quot;)\n\necho $current_dir\necho $script_dir\n</code></pre>\n<p>This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from <code>/</code> with the script in <code>/home/mez/</code>, it outputs</p>\n<pre><code>/\n/home/mez\n</code></pre>\n<p>Remember, when assigning variables from the output of a command, wrap the command in <code>$(</code> and <code>)</code> - or you won't get the desired output.</p>\n" }, { "answer_id": 444349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>That should do the trick:</p>\n\n<pre><code>echo `pwd`/`dirname $0`\n</code></pre>\n\n<p>It might look ugly depending on how it was invoked and the cwd but should get you where you need to go (or you can tweak the string if you care how it looks).</p>\n" }, { "answer_id": 1638397, "author": "al.", "author_id": 198265, "author_profile": "https://Stackoverflow.com/users/198265", "pm_score": 9, "selected": false, "text": "<p>The original post contains the solution (ignore the responses, they don't add anything useful). The interesting work is done by the mentioned unix command <code>readlink</code> with option <code>-f</code>. Works when the script is called by an absolute as well as by a relative path.</p>\n\n<p>For bash, sh, ksh:</p>\n\n<pre><code>#!/bin/bash \n# Absolute path to this script, e.g. /home/user/bin/foo.sh\nSCRIPT=$(readlink -f \"$0\")\n# Absolute path this script is in, thus /home/user/bin\nSCRIPTPATH=$(dirname \"$SCRIPT\")\necho $SCRIPTPATH\n</code></pre>\n\n<p>For tcsh, csh:</p>\n\n<pre><code>#!/bin/tcsh\n# Absolute path to this script, e.g. /home/user/bin/foo.csh\nset SCRIPT=`readlink -f \"$0\"`\n# Absolute path this script is in, thus /home/user/bin\nset SCRIPTPATH=`dirname \"$SCRIPT\"`\necho $SCRIPTPATH\n</code></pre>\n\n<p>See also: <a href=\"https://stackoverflow.com/a/246128/59087\">https://stackoverflow.com/a/246128/59087</a></p>\n" }, { "answer_id": 2473033, "author": "docwhat", "author_id": 108857, "author_profile": "https://Stackoverflow.com/users/108857", "pm_score": 5, "selected": false, "text": "<p>If you're using bash....</p>\n\n<pre><code>#!/bin/bash\n\npushd $(dirname \"${0}\") &gt; /dev/null\nbasedir=$(pwd -L)\n# Use \"pwd -P\" for the path without links. man bash for more info.\npopd &gt; /dev/null\n\necho \"${basedir}\"\n</code></pre>\n" }, { "answer_id": 4693587, "author": "blueyed", "author_id": 15690, "author_profile": "https://Stackoverflow.com/users/15690", "pm_score": 4, "selected": false, "text": "<pre><code>cd $(dirname $(readlink -f $0))\n</code></pre>\n" }, { "answer_id": 6255065, "author": "ranamalo", "author_id": 756470, "author_profile": "https://Stackoverflow.com/users/756470", "pm_score": 5, "selected": false, "text": "<p>As theMarko suggests:</p>\n\n<pre><code>BASEDIR=$(dirname $0)\necho $BASEDIR\n</code></pre>\n\n<p>This works unless you execute the script from the same directory where the script resides, in which case you get a value of '.'</p>\n\n<p>To get around that issue use:</p>\n\n<pre><code>current_dir=$(pwd)\nscript_dir=$(dirname $0)\n\nif [ $script_dir = '.' ]\nthen\nscript_dir=\"$current_dir\"\nfi\n</code></pre>\n\n<p>You can now use the variable current_dir throughout your script to refer to the script directory. However this may still have the symlink issue. </p>\n" }, { "answer_id": 13958777, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 1, "selected": false, "text": "<p>Inspired by <a href=\"https://stackoverflow.com/a/4693587\"><strong>blueyed’s answer</strong></a></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>read &lt; &lt;(readlink -f $0 | xargs dirname)\ncd $REPLY\n</code></pre>\n" }, { "answer_id": 15824974, "author": "Daniel", "author_id": 124704, "author_profile": "https://Stackoverflow.com/users/124704", "pm_score": 6, "selected": false, "text": "<p>An earlier comment on an answer said it, but it is easy to miss among all the other answers.</p>\n\n<p>When using bash:</p>\n\n<pre><code>echo this file: \"$BASH_SOURCE\"\necho this dir: \"$(dirname \"$BASH_SOURCE\")\"\n</code></pre>\n\n<p><a href=\"http://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html\" rel=\"noreferrer\">Bash Reference Manual, 5.2 Bash Variables</a></p>\n" }, { "answer_id": 43919044, "author": "Ján Sáreník", "author_id": 1255163, "author_profile": "https://Stackoverflow.com/users/1255163", "pm_score": 4, "selected": false, "text": "<p>Let's make it a POSIX oneliner:</p>\n<pre><code>a=&quot;/$0&quot;; a=&quot;${a%/*}&quot;; a=&quot;${a:-.}&quot;; a=&quot;${a##/}/&quot;; BINDIR=$(cd &quot;$a&quot;; pwd)\n</code></pre>\n<p>Tested on many Bourne-compatible shells including the BSD ones.</p>\n<p>As far as I know I am the author and I put it into public domain. For more info see:\n<a href=\"https://www.bublina.eu.org/posts/2017-05-11-posix_shell_dirname_replacement/\" rel=\"nofollow noreferrer\">https://www.bublina.eu.org/posts/2017-05-11-posix_shell_dirname_replacement/</a></p>\n" }, { "answer_id": 44644933, "author": "Alexandro de Oliveira", "author_id": 1781470, "author_profile": "https://Stackoverflow.com/users/1781470", "pm_score": 5, "selected": false, "text": "<p>The best answer for this question was answered here:<br>\n<a href=\"https://stackoverflow.com/a/246128/1781470\">Getting the source directory of a Bash script from within</a></p>\n\n<p>And it is:</p>\n\n<pre><code>DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &amp;&amp; pwd )\"\n</code></pre>\n\n<p>One-liner which will give you the full directory name of the script no matter where it is being called from.</p>\n\n<p>To understand how it works you can execute the following script:</p>\n\n<pre><code>#!/bin/bash\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n TARGET=\"$(readlink \"$SOURCE\")\"\n if [[ $TARGET == /* ]]; then\n echo \"SOURCE '$SOURCE' is an absolute symlink to '$TARGET'\"\n SOURCE=\"$TARGET\"\n else\n DIR=\"$( dirname \"$SOURCE\" )\"\n echo \"SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')\"\n SOURCE=\"$DIR/$TARGET\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\n fi\ndone\necho \"SOURCE is '$SOURCE'\"\nRDIR=\"$( dirname \"$SOURCE\" )\"\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" &amp;&amp; pwd )\"\nif [ \"$DIR\" != \"$RDIR\" ]; then\n echo \"DIR '$RDIR' resolves to '$DIR'\"\nfi\necho \"DIR is '$DIR'\"\n</code></pre>\n" }, { "answer_id": 45392962, "author": "michael", "author_id": 127971, "author_profile": "https://Stackoverflow.com/users/127971", "pm_score": 2, "selected": false, "text": "<p>So many answers, all plausible, each with pro's and con's &amp; slightly differeing objectives (which should probably be stated for each). Here's another solution that meets a primary objective of both being clear and working across all systems, on all bash (no assumptions about bash versions, or <code>readlink</code> or <code>pwd</code> options), and reasonably does what you'd expect to happen (eg, resolving symlinks is an interesting problem, but isn't usually what you actually want), handle edge cases like spaces in paths, etc., ignores any errors and uses a sane default if there are any issues.</p>\n\n<p>Each component is stored in a separate variable that you can use individually:</p>\n\n<pre><code># script path, filename, directory\nPROG_PATH=${BASH_SOURCE[0]} # this script's name\nPROG_NAME=${PROG_PATH##*/} # basename of script (strip path)\nPROG_DIR=\"$(cd \"$(dirname \"${PROG_PATH:-$PWD}\")\" 2&gt;/dev/null 1&gt;&amp;2 &amp;&amp; pwd)\"\n</code></pre>\n" }, { "answer_id": 49964642, "author": "thebunnyrules", "author_id": 1059127, "author_profile": "https://Stackoverflow.com/users/1059127", "pm_score": 3, "selected": false, "text": "<p><strong>INTRODUCTION</strong></p>\n\n<p>This answer <strong><em>corrects</em></strong> the very broken but shockingly top voted answer of this thread (written by TheMarko):</p>\n\n<pre><code>#!/usr/bin/env bash\n\nBASEDIR=$(dirname \"$0\")\necho \"$BASEDIR\"\n</code></pre>\n\n<p><strong>WHY DOES USING dirname \"$0\" ON IT'S OWN NOT WORK?</strong></p>\n\n<p><strong><em>dirname $0</em></strong> will only work if user launches script in a very specific way. I was able to find several situations where this answer fails and crashes the script. </p>\n\n<p>First of all, let's understand how this answer works. He's getting the script directory by doing </p>\n\n<pre><code>dirname \"$0\"\n</code></pre>\n\n<p><strong>$0</strong> represents the first part of the command calling the script (it's basically the inputted command without the arguments: </p>\n\n<pre><code>/some/path/./script argument1 argument2\n</code></pre>\n\n<p>$0=\"/some/path/./script\"</p>\n\n<p>dirname basically finds the last / in a string and truncates it there. So if you do:</p>\n\n<pre><code> dirname /usr/bin/sha256sum\n</code></pre>\n\n<p>you'll get: /usr/bin </p>\n\n<p>This example works well because /usr/bin/sha256sum is a properly formatted path but </p>\n\n<pre><code> dirname \"/some/path/./script\"\n</code></pre>\n\n<p>wouldn't work well and would give you:</p>\n\n<pre><code> BASENAME=\"/some/path/.\" #which would crash your script if you try to use it as a path\n</code></pre>\n\n<p>Say you're in the same dir as your script and you launch it with this command</p>\n\n<pre><code>./script \n</code></pre>\n\n<p>$0 in this situation will be ./script and dirname $0 will give:</p>\n\n<pre><code>. #or BASEDIR=\".\", again this will crash your script\n</code></pre>\n\n<p>Using:</p>\n\n<pre><code>sh script\n</code></pre>\n\n<p>Without inputting the full path will also give a BASEDIR=\".\"</p>\n\n<p>Using relative directories:</p>\n\n<pre><code> ../some/path/./script\n</code></pre>\n\n<p>Gives a dirname $0 of:</p>\n\n<pre><code> ../some/path/.\n</code></pre>\n\n<p>If you're in the /some directory and you call the script in this manner (note the absence of / in the beginning, again a relative path):</p>\n\n<pre><code> path/./script.sh\n</code></pre>\n\n<p>You'll get this value for dirname $0:</p>\n\n<pre><code> path/. \n</code></pre>\n\n<p>and ./path/./script (another form of the relative path) gives:</p>\n\n<pre><code> ./path/.\n</code></pre>\n\n<p>The only two situations where <strong><em>basedir $0</em></strong> will work is if the user use sh or touch to launch a script because both will result in $0:</p>\n\n<pre><code> $0=/some/path/script\n</code></pre>\n\n<p>which will give you a path you can use with dirname.</p>\n\n<p><strong>THE SOLUTION</strong></p>\n\n<p>You'd have account for and detect every one of the above mentioned situations and apply a fix for it if it arises: </p>\n\n<pre><code>#!/bin/bash\n#this script will only work in bash, make sure it's installed on your system.\n\n#set to false to not see all the echos\ndebug=true\n\nif [ \"$debug\" = true ]; then echo \"\\$0=$0\";fi\n\n\n#The line below detect script's parent directory. $0 is the part of the launch command that doesn't contain the arguments\nBASEDIR=$(dirname \"$0\") #3 situations will cause dirname $0 to fail: #situation1: user launches script while in script dir ( $0=./script)\n #situation2: different dir but ./ is used to launch script (ex. $0=/path_to/./script)\n #situation3: different dir but relative path used to launch script\nif [ \"$debug\" = true ]; then echo 'BASEDIR=$(dirname \"$0\") gives: '\"$BASEDIR\";fi \n\nif [ \"$BASEDIR\" = \".\" ]; then BASEDIR=\"$(pwd)\";fi # fix for situation1\n\n_B2=${BASEDIR:$((${#BASEDIR}-2))}; B_=${BASEDIR::1}; B_2=${BASEDIR::2}; B_3=${BASEDIR::3} # &lt;- bash only\nif [ \"$_B2\" = \"/.\" ]; then BASEDIR=${BASEDIR::$((${#BASEDIR}-1))};fi #fix for situation2 # &lt;- bash only\nif [ \"$B_\" != \"/\" ]; then #fix for situation3 #&lt;- bash only\n if [ \"$B_2\" = \"./\" ]; then\n #covers ./relative_path/(./)script\n if [ \"$(pwd)\" != \"/\" ]; then BASEDIR=\"$(pwd)/${BASEDIR:2}\"; else BASEDIR=\"/${BASEDIR:2}\";fi\n else\n #covers relative_path/(./)script and ../relative_path/(./)script, using ../relative_path fails if current path is a symbolic link\n if [ \"$(pwd)\" != \"/\" ]; then BASEDIR=\"$(pwd)/$BASEDIR\"; else BASEDIR=\"/$BASEDIR\";fi\n fi\nfi\n\nif [ \"$debug\" = true ]; then echo \"fixed BASEDIR=$BASEDIR\";fi\n</code></pre>\n" }, { "answer_id": 50772450, "author": "Richard Gomes", "author_id": 62131, "author_profile": "https://Stackoverflow.com/users/62131", "pm_score": 3, "selected": false, "text": "<p>This one-liner tells where the shell script is, <em>does not matter if you ran it or if you sourced it</em>. Also, it resolves any symbolic links involved, if that is the case:</p>\n\n<pre><code>dir=$(dirname $(test -L \"$BASH_SOURCE\" &amp;&amp; readlink -f \"$BASH_SOURCE\" || echo \"$BASH_SOURCE\"))\n</code></pre>\n\n<p>By the way, I suppose you are using <em>/bin/bash</em>.</p>\n" }, { "answer_id": 52293841, "author": "searchrome", "author_id": 2342649, "author_profile": "https://Stackoverflow.com/users/2342649", "pm_score": 4, "selected": false, "text": "<pre><code>BASE_DIR=\"$(cd \"$(dirname \"$0\")\"; pwd)\";\necho \"BASE_DIR =&gt; $BASE_DIR\"\n</code></pre>\n" }, { "answer_id": 55472432, "author": "Rohith", "author_id": 1771949, "author_profile": "https://Stackoverflow.com/users/1771949", "pm_score": 5, "selected": false, "text": "<p>If you want to get the actual script directory (irrespective of whether you are invoking the script using a symlink or directly), try:</p>\n\n<pre><code>BASEDIR=$(dirname $(realpath \"$0\"))\necho \"$BASEDIR\"\n</code></pre>\n\n<p>This works on both linux and macOS. I couldn't see anyone here mention about <code>realpath</code>. Not sure whether there are any drawbacks in this approach.</p>\n\n<p>on macOS, you need to install <code>coreutils</code> to use <code>realpath</code>. Eg: <code>brew install coreutils</code>.</p>\n" }, { "answer_id": 66962790, "author": "Leslie Krause", "author_id": 9216142, "author_profile": "https://Stackoverflow.com/users/9216142", "pm_score": 0, "selected": false, "text": "<p>With tcsh, you can use the <code>:h</code> variable modifier to retrieve the path.</p>\n<p>One caveat is that if the script is executed as <code>tcsh myscript.csh</code>, then you will only get the script name. A workaround is to validate the path as shown below.</p>\n<pre><code>#!/bin/tcsh\n\nset SCRIPT_PATH = $0:h\nif ( $SCRIPT_PATH == $0 ) then\n set SCRIPT_PATH = &quot;.&quot;\nendif\n\n$SCRIPT_PATH/compile.csh &gt; $SCRIPT_PATH/results.txt\n</code></pre>\n<p>More information about variable modifiers can be found at <a href=\"https://learnxinyminutes.com/docs/tcsh/\" rel=\"nofollow noreferrer\">https://learnxinyminutes.com/docs/tcsh/</a></p>\n" }, { "answer_id": 70174488, "author": "anton_rh", "author_id": 5447906, "author_profile": "https://Stackoverflow.com/users/5447906", "pm_score": 1, "selected": false, "text": "<p>Basic version:</p>\n<pre><code>dir=$(dirname $0)\n</code></pre>\n<p>If the script might be called via <code>$PATH</code>, then:</p>\n<pre><code>dir=$(dirname $(which $0))\n</code></pre>\n<p>If the script might be called like this: <code>bash script.sh</code>, then:</p>\n<pre><code>dir=$(dirname $(which $0 2&gt;/dev/null || realpath ./$0))\n</code></pre>\n<p>If you feel insanely unsafe, then:</p>\n<pre><code>dir=&quot;$(dirname -- &quot;$(which -- &quot;$0&quot; 2&gt;/dev/null || realpath -- &quot;./$0&quot;)&quot;)&quot;\n</code></pre>\n" }, { "answer_id": 71603179, "author": "johansenj", "author_id": 897289, "author_profile": "https://Stackoverflow.com/users/897289", "pm_score": 0, "selected": false, "text": "<p>one of the most robust ways i've found is</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\nrelative_dir=`perl -e 'use Cwd &quot;realpath&quot;;$pwd = realpath(shift); $pwd =~ s/\\/[^\\/]*$//; print $pwd' $0`\ncd $relative_dir\n</code></pre>\n<p>works with symlinks and has worked for many of my coworkers no matter their choice of shell type</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371/" ]
Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script file resides?
In Bash, you should get what you need like this: ``` #!/usr/bin/env bash BASEDIR=$(dirname "$0") echo "$BASEDIR" ```
242,565
<p>I have MainViewController calling WebViewController (From UICatalog sample application) In WebViewController I make some function setValue(){...} to set some value passed as parameter to the variable (NSString *value) from WebViewController.h but when I try from MainViewController something like WebViewController targetViewController... targetViewController.setValue(value), it says: "<strong>error: request for member 'setValue' in something not s structure or union</strong>"...</p>
[ { "answer_id": 242638, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 1, "selected": false, "text": "<p>If you have a property named \"value\", and use @sythesize to create a method for you, in which case you call using that \".\" notation:</p>\n\n<pre><code>targetViewController.value = whatever;\n</code></pre>\n\n<p>Or you can call the setter outright regardless of you or the @synthesize writing the method:</p>\n\n<pre><code>[targetViewController setValue:whatever];\n</code></pre>\n\n<p>The property syntax (class.property = whatever) is really just a shortcut of calling a \"setValue:\" method, and in return the @property and @synthesize mechanisms of properties are just writing a helpful bit of code for you.</p>\n\n<p>Edit: I had said before if you just wrote a \"setValue:\" method you could call it using the \"class.value = newValue\" notation, but that was incorrect - you have to define an @property to use \".\" notation.</p>\n" }, { "answer_id": 242839, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 1, "selected": false, "text": "<p>I believe that </p>\n\n<pre><code>targetViewController.value = whatever;\n</code></pre>\n\n<p>will only work if you already have the @property declared; if not, you'll need to use the full method calling syntax:</p>\n\n<pre><code>[targetViewController setValue: whatever];\n</code></pre>\n\n<p>Otherwise, Kendall is correct about using setters and @synthesize.</p>\n\n<p>Also your syntax is written using procedural C</p>\n\n<pre><code>targetViewController.setValue(value);\n</code></pre>\n\n<p>which <em>definitely</em> won't work. </p>\n" }, { "answer_id": 250223, "author": "drewh", "author_id": 1967, "author_profile": "https://Stackoverflow.com/users/1967", "pm_score": 0, "selected": false, "text": "<p>You also need to be sure to #import your targetViewController.h file.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16066/" ]
I have MainViewController calling WebViewController (From UICatalog sample application) In WebViewController I make some function setValue(){...} to set some value passed as parameter to the variable (NSString \*value) from WebViewController.h but when I try from MainViewController something like WebViewController targetViewController... targetViewController.setValue(value), it says: "**error: request for member 'setValue' in something not s structure or union**"...
If you have a property named "value", and use @sythesize to create a method for you, in which case you call using that "." notation: ``` targetViewController.value = whatever; ``` Or you can call the setter outright regardless of you or the @synthesize writing the method: ``` [targetViewController setValue:whatever]; ``` The property syntax (class.property = whatever) is really just a shortcut of calling a "setValue:" method, and in return the @property and @synthesize mechanisms of properties are just writing a helpful bit of code for you. Edit: I had said before if you just wrote a "setValue:" method you could call it using the "class.value = newValue" notation, but that was incorrect - you have to define an @property to use "." notation.
242,568
<p>By default, .NET application's configuration file is named after "exe file name".config. I'm wondering whether it is possible to have one application's configuration specified dynamically.</p> <p>For example, the built application is "foo.exe". At runtime, the config file is "foo.exe.config". Is it possible to have it accept command line arguments to use other config file. So, the application can use other configuration like below.</p> <blockquote> <p>foo.exe /config:bar.config</p> </blockquote> <p>bar.config is used as config file insteand of foo.exe.config.</p>
[ { "answer_id": 242591, "author": "Will Dieterich", "author_id": 31233, "author_profile": "https://Stackoverflow.com/users/31233", "pm_score": 0, "selected": false, "text": "<p>Yes you will need use ExeConfigurationFileMap</p>\n" }, { "answer_id": 242612, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 2, "selected": false, "text": "<p>Code from MSDN</p>\n\n<pre><code>static void DisplayMappedExeConfigurationFileSections()\n{\n // Get the application configuration file path.\n string exeFilePath = System.IO.Path.Combine(\n Environment.CurrentDirectory, \"ConfigurationManager.exe.config\");\n // HERE !!! \n // Map to the application configuration file.\n ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();\n configFile.ExeConfigFilename = exeFilePath;\n\n Configuration config =\n ConfigurationManager.OpenMappedExeConfiguration(configFile,\n ConfigurationUserLevel.None);\n\n // Display the configuration file sections.\n ConfigurationSectionCollection sections = config.Sections;\n\n Console.WriteLine();\n Console.WriteLine(\"Sections in machine.config:\");\n\n // Loop to get the sections machine.config.\n foreach (ConfigurationSection section in sections)\n {\n string name = section.SectionInformation.Name;\n Console.WriteLine(\"Name: {0}\", name);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 242613, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 2, "selected": false, "text": "<p>Gotten from <a href=\"http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/ec237df4-f05e-4711-a230-fb089c395c73/\" rel=\"nofollow noreferrer\">How to use Configuration.GetSection() and ConfigurationManager.OpenMappedExeConfiguration()</a></p>\n\n<pre><code>ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();\nfileMap.ExeConfigFilename = @\"C:\\Inetpub\\Test\\Config\\Dev.config\";\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);\nAppSettingsSection section = (AppSettingsSection)config.GetSection(\"appSettings\");\nstring ConfigVersion = section.Settings[\"ConfigVersion\"].Value;\n</code></pre>\n" }, { "answer_id": 305711, "author": "Slav", "author_id": 22680, "author_profile": "https://Stackoverflow.com/users/22680", "pm_score": 4, "selected": false, "text": "<p>All of the above work well if you need to replace only AppSettings section. </p>\n\n<p>In case you have to run with different config files (all sections) you might want to consider launching application using a host, that creates app domain for your main application and sets different config file depending on parameters you passed in.</p>\n\n<p>Here's the code that worked for me:</p>\n\n<pre><code> AppDomainSetup setup = new AppDomainSetup();\n setup.ApplicationBase = \"file://\" + System.Environment.CurrentDirectory;\n setup.DisallowBindingRedirects = true;\n setup.DisallowCodeDownload = true;\n\n if (args.Length != 0 &amp;&amp; args[0].Equals(\"-test\"))\n {\n setup.ConfigurationFile = \"PATH_TO_YOUR_TEST_CONFIG_FILE\";\n }\n else {\n setup.ConfigurationFile = \"PATH_TO_YOUR_LIVE_CONFIG_FILE\";\n }\n\n AppDomain domain = AppDomain.CreateDomain(\"FRIENDLY_NAME\", null, setup);\n domain.ExecuteAssembly(\"YourMainApp.exe\");\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
By default, .NET application's configuration file is named after "exe file name".config. I'm wondering whether it is possible to have one application's configuration specified dynamically. For example, the built application is "foo.exe". At runtime, the config file is "foo.exe.config". Is it possible to have it accept command line arguments to use other config file. So, the application can use other configuration like below. > > foo.exe /config:bar.config > > > bar.config is used as config file insteand of foo.exe.config.
All of the above work well if you need to replace only AppSettings section. In case you have to run with different config files (all sections) you might want to consider launching application using a host, that creates app domain for your main application and sets different config file depending on parameters you passed in. Here's the code that worked for me: ``` AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = "file://" + System.Environment.CurrentDirectory; setup.DisallowBindingRedirects = true; setup.DisallowCodeDownload = true; if (args.Length != 0 && args[0].Equals("-test")) { setup.ConfigurationFile = "PATH_TO_YOUR_TEST_CONFIG_FILE"; } else { setup.ConfigurationFile = "PATH_TO_YOUR_LIVE_CONFIG_FILE"; } AppDomain domain = AppDomain.CreateDomain("FRIENDLY_NAME", null, setup); domain.ExecuteAssembly("YourMainApp.exe"); ```
242,570
<p>I need to copy the content of a window (BitBlt) which is hidden, to another window. The problem is that once I hide the source window, the device context I got isn't painted anymore.</p>
[ { "answer_id": 242581, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 0, "selected": false, "text": "<p>Maybe you can trigger a redraw operation on the window with InvalidateRect?</p>\n" }, { "answer_id": 242611, "author": "slashmais", "author_id": 15161, "author_profile": "https://Stackoverflow.com/users/15161", "pm_score": 1, "selected": false, "text": "<p>Copy the source bitmap to a memory bitmap before closing/hiding the window.</p>\n" }, { "answer_id": 242809, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 1, "selected": false, "text": "<p>You could try sending a <code>WM_PRINT</code> message to the window. For many windows (including all standard windows and common controls) this will cause it to paint into the supplied DC.</p>\n\n<p>Also, if you pass an HDC as the wparam of a WM_PAINT message, many windows (such as the common controls) will paint into that DC rather than onto the screen.</p>\n" }, { "answer_id": 242826, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, I think you're going to have real problems getting this to work reliably. You don't say exactly what you're doing, but I assume that, given the window handle, you're grabbing the device context associated with the window by calling GetWindowDC(), and then using the resulting device context.</p>\n\n<p>This will work okay on XP when the window is visible. However, on Vista, if desktop compositing is enabled, it won't even work properly then: you'll get 0 back from GetWindowDC(). Fundamentally, grabbing window device contexts isn't going to work reliably.</p>\n\n<p>If the window you're trying to copy from is part of your own application, I'd suggest modifying your code to support the WM___PRINT message: this acts like WM_PAINT, but allows you to supply a device context to draw into. </p>\n\n<p>If the window isn't from your application, you're basically out of luck: if the window is hidden, the image of what it would show if it were visible doesn't exist anywhere.</p>\n" }, { "answer_id": 242837, "author": "elifiner", "author_id": 15109, "author_profile": "https://Stackoverflow.com/users/15109", "pm_score": 3, "selected": false, "text": "<p>What you need is the <a href=\"http://msdn.microsoft.com/en-us/library/ms535695.aspx\" rel=\"noreferrer\">PrintWindow</a> function that's available in Win32 API since Windows XP. If you need it to work with older versions of Windows, you can try <a href=\"http://msdn.microsoft.com/en-us/library/ms534856(VS.85).aspx\" rel=\"noreferrer\">WM_PRINT</a>, although I've never been able to make it work.</p>\n\n<p>There's a nice article <a href=\"http://msdn.microsoft.com/en-us/library/ms997649.aspx\" rel=\"noreferrer\">here</a> that shows how to use PrintWindow, and here's the relevant code snippet from that article:</p>\n\n<pre><code>// Takes a snapshot of the window hwnd, stored in the memory device context hdcMem\nHDC hdc = GetWindowDC(hwnd);\nif (hdc)\n{\n HDC hdcMem = CreateCompatibleDC(hdc);\n if (hdcMem)\n {\n RECT rc;\n GetWindowRect(hwnd, &amp;rc);\n\n HBITMAP hbitmap = CreateCompatibleBitmap(hdc, RECTWIDTH(rc), RECTHEIGHT(rc));\n if (hbitmap)\n {\n SelectObject(hdcMem, hbitmap);\n\n PrintWindow(hwnd, hdcMem, 0);\n\n DeleteObject(hbitmap);\n }\n DeleteObject(hdcMem);\n }\n ReleaseDC(hwnd, hdc);\n}\n</code></pre>\n\n<p>I should have some Python code that uses wxPython to achieve the same thing. Drop me a note if you want it.</p>\n" }, { "answer_id": 242979, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The PrintWindow function doesn't seem to work on a hidden window, only on visible ones.</p>\n" }, { "answer_id": 245204, "author": "Jon Bright", "author_id": 1813, "author_profile": "https://Stackoverflow.com/users/1813", "pm_score": 0, "selected": false, "text": "<p>Approaching things from a different perspective, are you sure that's really what you want to be doing? You don't, for example, want to be using CreateCompatibleDC and CreateCompatibleBitmap to create your invisible drawing surface, drawing on that and then using BitBlt?</p>\n\n<p>Some more information about the background to what you're up to might enable someone to come up with either a solution or some lateral thinking...</p>\n" }, { "answer_id": 7492799, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/dd144909.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/dd144909.aspx</a> (getPixel) might help...</p>\n" }, { "answer_id": 8728689, "author": "Orwellophile", "author_id": 912236, "author_profile": "https://Stackoverflow.com/users/912236", "pm_score": 0, "selected": false, "text": "<p>I just tested this in Windows 7, should work fine from XP up.</p>\n\n<p>It brings the window to the foreground without giving it focus, before capturing it. It's not perfection, but it's the best you're going to do if you can't get PrintWindow() to work.</p>\n\n<p>It's a static method, so you just can simply call it like so:</p>\n\n<pre><code>Orwellophile.TakeScreenShotOfWindow(\"window.jpg\", Form.Handle);\n</code></pre>\n\n<p>No mess, no fuss. It's from a larger class, so hopefully nothing is missing. The originals are:</p>\n\n<p><a href=\"http://sfinktah.trac.cvsdude.com/vhddirector/browser/main/VHD%20Director/UnhandledExceptionManager.cs\" rel=\"nofollow\">http://sfinktah.trac.cvsdude.com/vhddirector/browser/main/VHD%20Director/UnhandledExceptionManager.cs</a>\nand <a href=\"http://sfinktah.trac.cvsdude.com/vhddirector/browser/main/CSharp.cc/Win32Messaging.cs\" rel=\"nofollow\">http://sfinktah.trac.cvsdude.com/vhddirector/browser/main/CSharp.cc/Win32Messaging.cs</a> although they're nowhere as neat as the example I've pasted below.</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Threading;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\npublic class Orwellophile {\n public static void TakeScreenshotOfWindow(String strFilename, IntPtr hTargetWindow)\n {\n Rectangle objRectangle;\n RECT r;\n IntPtr hForegroundWindow = GetForegroundWindow();\n\n GetWindowRect(hTargetWindow, out r);\n objRectangle = r.ToRectangle();\n\n if (hTargetWindow != hForegroundWindow)\n {\n ShowWindow(hTargetWindow, SW_SHOWNOACTIVATE);\n SetWindowPos(hTargetWindow.ToInt32(), HWND_TOPMOST, r.X, r.Y, r.Width, r.Height, SWP_NOACTIVATE);\n Thread.Sleep(500);\n }\n\n TakeScreenshotPrivate(strFilename, objRectangle);\n }\n\n private static void TakeScreenshotPrivate(string strFilename, Rectangle objRectangle)\n {\n Bitmap objBitmap = new Bitmap(objRectangle.Width, objRectangle.Height);\n Graphics objGraphics = default(Graphics);\n IntPtr hdcDest = default(IntPtr);\n int hdcSrc = 0;\n\n objGraphics = Graphics.FromImage(objBitmap);\n\n\n hdcSrc = GetDC(0); // Get a device context to the windows desktop and our destination bitmaps\n hdcDest = objGraphics.GetHdc(); // Copy what is on the desktop to the bitmap\n BitBlt(hdcDest.ToInt32(), 0, 0, objRectangle.Width, objRectangle.Height, hdcSrc, objRectangle.X, objRectangle.Y, SRCCOPY);\n objGraphics.ReleaseHdc(hdcDest); // Release DC\n ReleaseDC(0, hdcSrc);\n\n objBitmap.Save(strFilename);\n }\n\n\n [DllImport(\"gdi32.dll\", SetLastError = true)]\n static extern IntPtr CreateCompatibleDC(IntPtr hdc);\n [DllImport(\"user32.dll\")]\n static extern IntPtr GetWindowDC(IntPtr hWnd);\n [DllImport(\"gdi32.dll\")]\n static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);\n [DllImport(\"gdi32.dll\", ExactSpelling = true, PreserveSig = true, SetLastError = true)]\n static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); // To capture only the client area of window, use PW_CLIENTONLY = 0x1 as nFlags\n [DllImport(\"gdi32.dll\")]\n static extern bool DeleteObject(IntPtr hObject);\n [DllImport(\"user32.dll\")]\n static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowPos\")]\n static extern bool SetWindowPos(\n int hWnd, // window handle\n int hWndInsertAfter, // placement-order handle\n int X, // horizontal position\n int Y, // vertical position\n int cx, // width\n int cy, // height\n uint uFlags); // window positioning flags\n [DllImport(\"user32.dll\")]\n static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, ExactSpelling = true)]\n static public extern IntPtr GetForegroundWindow();\n private const int SW_SHOWNOACTIVATE = 4;\n private const int HWND_TOPMOST = -1;\n private const uint SWP_NOACTIVATE = 0x0010;\n private const int SRCCOPY = 0xcc0020;\n}\n</code></pre>\n\n<p>Note that you can implement your own light-weight RECT class/struct, but this is the one I use. I've attached it separately due to it's size</p>\n\n<pre><code>[StructLayout(LayoutKind.Sequential)]\npublic struct RECT\n{\n private int _Left;\n private int _Top;\n private int _Right;\n private int _Bottom;\n\n public RECT(System.Drawing.Rectangle Rectangle)\n : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)\n {\n }\n public RECT(int Left, int Top, int Right, int Bottom)\n {\n _Left = Left;\n _Top = Top;\n _Right = Right;\n _Bottom = Bottom;\n }\n\n public int X\n {\n get { return _Left; }\n set { _Left = value; }\n }\n public int Y\n {\n get { return _Top; }\n set { _Top = value; }\n }\n public int Left\n {\n get { return _Left; }\n set { _Left = value; }\n }\n public int Top\n {\n get { return _Top; }\n set { _Top = value; }\n }\n public int Right\n {\n get { return _Right; }\n set { _Right = value; }\n }\n public int Bottom\n {\n get { return _Bottom; }\n set { _Bottom = value; }\n }\n public int Height\n {\n get { return _Bottom - _Top; }\n set { _Bottom = value - _Top; }\n }\n public int Width\n {\n get { return _Right - _Left; }\n set { _Right = value + _Left; }\n }\n public Point Location\n {\n get { return new Point(Left, Top); }\n set\n {\n _Left = value.X;\n _Top = value.Y;\n }\n }\n public Size Size\n {\n get { return new Size(Width, Height); }\n set\n {\n _Right = value.Height + _Left;\n _Bottom = value.Height + _Top;\n }\n }\n\n public Rectangle ToRectangle()\n {\n return new Rectangle(this.Left, this.Top, this.Width, this.Height);\n }\n static public Rectangle ToRectangle(RECT Rectangle)\n {\n return Rectangle.ToRectangle();\n }\n static public RECT FromRectangle(Rectangle Rectangle)\n {\n return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom);\n }\n\n static public implicit operator Rectangle(RECT Rectangle)\n {\n return Rectangle.ToRectangle();\n }\n static public implicit operator RECT(Rectangle Rectangle)\n {\n return new RECT(Rectangle);\n }\n static public bool operator ==(RECT Rectangle1, RECT Rectangle2)\n {\n return Rectangle1.Equals(Rectangle2);\n }\n static public bool operator !=(RECT Rectangle1, RECT Rectangle2)\n {\n return !Rectangle1.Equals(Rectangle2);\n }\n\n public override string ToString()\n {\n return \"{Left: \" + _Left + \"; \" + \"Top: \" + _Top + \"; Right: \" + _Right + \"; Bottom: \" + _Bottom + \"}\";\n }\n\n public bool Equals(RECT Rectangle)\n {\n return Rectangle.Left == _Left &amp;&amp; Rectangle.Top == _Top &amp;&amp; Rectangle.Right == _Right &amp;&amp; Rectangle.Bottom == _Bottom;\n }\n public override bool Equals(object Object)\n {\n if (Object is RECT)\n {\n return Equals((RECT)Object);\n }\n else if (Object is Rectangle)\n {\n return Equals(new RECT((Rectangle)Object));\n }\n\n return false;\n }\n\n public override int GetHashCode()\n {\n return Left.GetHashCode() ^ Right.GetHashCode() ^ Top.GetHashCode() ^ Bottom.GetHashCode();\n }\n}\n</code></pre>\n" }, { "answer_id": 10212007, "author": "ckg", "author_id": 292533, "author_profile": "https://Stackoverflow.com/users/292533", "pm_score": 0, "selected": false, "text": "<p>For a window that is hidden behind another window you can set it to be transparent (with a high alpha so that it doesn't look transparent). It should then be possible to capture the whole window with BitBlt.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to copy the content of a window (BitBlt) which is hidden, to another window. The problem is that once I hide the source window, the device context I got isn't painted anymore.
What you need is the [PrintWindow](http://msdn.microsoft.com/en-us/library/ms535695.aspx) function that's available in Win32 API since Windows XP. If you need it to work with older versions of Windows, you can try [WM\_PRINT](http://msdn.microsoft.com/en-us/library/ms534856(VS.85).aspx), although I've never been able to make it work. There's a nice article [here](http://msdn.microsoft.com/en-us/library/ms997649.aspx) that shows how to use PrintWindow, and here's the relevant code snippet from that article: ``` // Takes a snapshot of the window hwnd, stored in the memory device context hdcMem HDC hdc = GetWindowDC(hwnd); if (hdc) { HDC hdcMem = CreateCompatibleDC(hdc); if (hdcMem) { RECT rc; GetWindowRect(hwnd, &rc); HBITMAP hbitmap = CreateCompatibleBitmap(hdc, RECTWIDTH(rc), RECTHEIGHT(rc)); if (hbitmap) { SelectObject(hdcMem, hbitmap); PrintWindow(hwnd, hdcMem, 0); DeleteObject(hbitmap); } DeleteObject(hdcMem); } ReleaseDC(hwnd, hdc); } ``` I should have some Python code that uses wxPython to achieve the same thing. Drop me a note if you want it.
242,572
<p>I'm trying to use a .NET assembly from VB6 via interop without placing it in the GAC and without using the /codebase argument for regasm.exe.</p> <p>From what I understand, when I run regasm.exe on a .NET class library, it creates a registry entry for each class in the class library telling the COM clients they should load mscoree.dll that serves as a proxy wrapping .NET objects for COM use. Mscoree.dll uses the InprocServer32/Assembly key in the registry for the class to determine which class library contains the implementation of the class.</p> <p>If I use /codebase with regasm.exe or put my class library in the GAC, everything works OK; but as far as I can figure out from the scattered documentation, mscoree.dll should look for the assembly in the current directory and in the path if /codebase hasn't been used (and therefore there is no CodeBase entry in the registry for the class) and it can't find it in the GAC.</p> <p>The C# code is as simple as can be:</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace myinterop { [Guid("B1D6B9FE-A4C7-11DD-B06B-E93056D89593")] [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class MyServer { public int Add(int a, int b) { return a + b; } } } </code></pre> <p>And the problem reproduces with a VBScript one liner that I put in the same directory as the compiled DLL:</p> <pre><code>object = CreateObject("myinterop.MyServer") </code></pre> <p>What am I missing here? Is there a definitive description of the way mscoree.dll looks up the assemblies somewhere?</p> <p>BTW, I'm using .NET 2.0 and yes, I know I should put my assemblies in the GAC, I'm just wondering why this doesn't work as advertised.</p>
[ { "answer_id": 242601, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 3, "selected": true, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/tzat5yw6(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p><strong>/Codebase</strong> : Creates a Codebase entry in the\n registry. The Codebase entry specifies\n the file path for an assembly that is\n not installed in the global assembly\n cache. You should not specify this\n option if you will subsequently\n install the assembly that you are\n registering into the global assembly\n cache. The assemblyFile argument that\n you specify with the /codebase option\n must be a strong-named assembly.</p>\n</blockquote>\n\n<p>It appears that it does work as advertised. If you don't put your assembly in the GAC, then you need to use /codebase so that the filepath is accessible.</p>\n" }, { "answer_id": 242630, "author": "jkchong", "author_id": 32004, "author_profile": "https://Stackoverflow.com/users/32004", "pm_score": 2, "selected": false, "text": "<p>To achieve what you want, I think you need to create .manifest files for both your .NET assembly and your VB6_App.EXE (referencing the .NET assembly). Check Google for registration-free COM.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15109/" ]
I'm trying to use a .NET assembly from VB6 via interop without placing it in the GAC and without using the /codebase argument for regasm.exe. From what I understand, when I run regasm.exe on a .NET class library, it creates a registry entry for each class in the class library telling the COM clients they should load mscoree.dll that serves as a proxy wrapping .NET objects for COM use. Mscoree.dll uses the InprocServer32/Assembly key in the registry for the class to determine which class library contains the implementation of the class. If I use /codebase with regasm.exe or put my class library in the GAC, everything works OK; but as far as I can figure out from the scattered documentation, mscoree.dll should look for the assembly in the current directory and in the path if /codebase hasn't been used (and therefore there is no CodeBase entry in the registry for the class) and it can't find it in the GAC. The C# code is as simple as can be: ``` using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace myinterop { [Guid("B1D6B9FE-A4C7-11DD-B06B-E93056D89593")] [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class MyServer { public int Add(int a, int b) { return a + b; } } } ``` And the problem reproduces with a VBScript one liner that I put in the same directory as the compiled DLL: ``` object = CreateObject("myinterop.MyServer") ``` What am I missing here? Is there a definitive description of the way mscoree.dll looks up the assemblies somewhere? BTW, I'm using .NET 2.0 and yes, I know I should put my assemblies in the GAC, I'm just wondering why this doesn't work as advertised.
From [MSDN](http://msdn.microsoft.com/en-us/library/tzat5yw6(VS.80).aspx): > > **/Codebase** : Creates a Codebase entry in the > registry. The Codebase entry specifies > the file path for an assembly that is > not installed in the global assembly > cache. You should not specify this > option if you will subsequently > install the assembly that you are > registering into the global assembly > cache. The assemblyFile argument that > you specify with the /codebase option > must be a strong-named assembly. > > > It appears that it does work as advertised. If you don't put your assembly in the GAC, then you need to use /codebase so that the filepath is accessible.
242,579
<p>I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using</p> <pre><code>Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url) </code></pre> <p>For short URLs like "<a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a>" this works fine. But for long URLs (say, 2000 characters), this simply does absolutely nothing at all: no exception or anything of the sort, it is simply ignored.</p> <p>Is there a character limit a) for a Runtime.exec command or b) for the rundll32 url.dll command? If so, what is the limit?</p>
[ { "answer_id": 242674, "author": "David Harrison", "author_id": 2966, "author_profile": "https://Stackoverflow.com/users/2966", "pm_score": 3, "selected": true, "text": "<p>You will be running up against <a href=\"https://web.archive.org/web/20190902193246/https://boutell.com/newfaq/misc/urllength.html\" rel=\"nofollow noreferrer\">this (archived)</a> operating system/browser specific maximum URL length problem:</p>\n\n<p>For \"rundll32 url.dll\" (i.e. Microsoft IE) you will be limited to 2,083 characters (including http://).</p>\n\n<p>From where I sit you have two alternatives:</p>\n\n<ol>\n<li><p>Build (or use) a TinyURL-style service\nthat turns your long-urls into\nshort, redirected ones. However even\nhere you are going to run into the\nsame URL length issue, just within\nthe browser itself rather than your\nRuntime() statement. e.g. The browser window would open, go to the short-URL which would perform the redirect to the long-URL and fail. </p></li>\n<li><p>Use a POST request and bury some or\nall of your URL parameters within\nit. Rather than using a GET call you\ncan supply very long parameters\nwithin the body of an HTTP POST request. This\nwould not be as simple as your example code. In fact this maybe quite tricky (or impossible) with the rundll32 url.dll combination (I am not familiar with it)...</p></li>\n</ol>\n" }, { "answer_id": 244342, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 0, "selected": false, "text": "<p>It will also depend on the version of windows, because you may be exceeding the operating system's <code>MAX_PATH</code> length on the command line?</p>\n" }, { "answer_id": 248384, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 0, "selected": false, "text": "<p>You could also try the Runtime.exec(String []) version, which you may have better luck with. Just take all your space seperated arguments and pass them in as seperate strings:</p>\n\n<p><code>Runtime.getRuntime().exec(new String [] {\"rundll32\", \"url.dll,FileProtocolHandler\", \"urlarg1\", \"urlarg2\"});</code></p>\n" }, { "answer_id": 301710, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 2, "selected": false, "text": "<p>As an aside, I would suggest using the cross platform <code>Desktop.open()</code> or <code>Desktop.browse()</code> instead of Windows only <code>rundll32</code>. This will give you an IOException if it can't open the write application.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using ``` Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url) ``` For short URLs like "<http://www.google.com>" this works fine. But for long URLs (say, 2000 characters), this simply does absolutely nothing at all: no exception or anything of the sort, it is simply ignored. Is there a character limit a) for a Runtime.exec command or b) for the rundll32 url.dll command? If so, what is the limit?
You will be running up against [this (archived)](https://web.archive.org/web/20190902193246/https://boutell.com/newfaq/misc/urllength.html) operating system/browser specific maximum URL length problem: For "rundll32 url.dll" (i.e. Microsoft IE) you will be limited to 2,083 characters (including http://). From where I sit you have two alternatives: 1. Build (or use) a TinyURL-style service that turns your long-urls into short, redirected ones. However even here you are going to run into the same URL length issue, just within the browser itself rather than your Runtime() statement. e.g. The browser window would open, go to the short-URL which would perform the redirect to the long-URL and fail. 2. Use a POST request and bury some or all of your URL parameters within it. Rather than using a GET call you can supply very long parameters within the body of an HTTP POST request. This would not be as simple as your example code. In fact this maybe quite tricky (or impossible) with the rundll32 url.dll combination (I am not familiar with it)...
242,608
<p>Is it possible to disable the browsers vertical and horizontal scrollbars using jQuery or javascript?</p>
[ { "answer_id": 242615, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 6, "selected": false, "text": "<p>Try CSS</p>\n\n<pre><code>&lt;body style=\"overflow: hidden\"&gt;\n</code></pre>\n" }, { "answer_id": 242684, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 7, "selected": false, "text": "<p>In case you need possibility to hide and show scrollbars dynamically you could use</p>\n\n<pre><code>$(\"body\").css(\"overflow\", \"hidden\");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$(\"body\").css(\"overflow\", \"auto\");\n</code></pre>\n\n<p>somewhere in your code.</p>\n" }, { "answer_id": 242805, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 5, "selected": false, "text": "<p>So far we have overflow:hidden on the body. However IE doesn't always honor that and you need to put scroll=\"no\" on the body element as well and/or place overflow:hidden on the html element as well.</p>\n\n<p>You can take this further when you need to 'take control' of the view port you can do this:-</p>\n\n<pre><code>&lt;style&gt;\n body {width:100%; height:100%; overflow:hidden; margin:0; }\n html {width:100%; height:100%; overflow:hidden; }\n&lt;/style&gt;\n</code></pre>\n\n<p>An element granted height 100% in the body has the full height of the window viewport, and element positioned absolutely using bottom:nnPX will be set nn pixels above the bottom edge of the window, etc.</p>\n" }, { "answer_id": 3418851, "author": "Gawin", "author_id": 351659, "author_profile": "https://Stackoverflow.com/users/351659", "pm_score": 3, "selected": false, "text": "<p>In case you also need support for Internet Explorer 6, just overflow the <strong>html</strong></p>\n\n<pre><code>$(\"html\").css(\"overflow\", \"hidden\");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$(\"html\").css(\"overflow\", \"auto\");\n</code></pre>\n" }, { "answer_id": 8504771, "author": "shafraz", "author_id": 1097822, "author_profile": "https://Stackoverflow.com/users/1097822", "pm_score": 4, "selected": false, "text": "<p>Try CSS.</p>\n\n<p>If you want to remove Horizontal</p>\n\n<pre><code>overflow-x: hidden;\n</code></pre>\n\n<p>And if you want to remove Vertical</p>\n\n<pre><code>overflow-y: hidden;\n</code></pre>\n" }, { "answer_id": 10811680, "author": "Lyncee", "author_id": 1425405, "author_profile": "https://Stackoverflow.com/users/1425405", "pm_score": 7, "selected": false, "text": "<pre><code>function reloadScrollBars() {\n document.documentElement.style.overflow = 'auto'; // firefox, chrome\n document.body.scroll = \"yes\"; // ie only\n}\n\nfunction unloadScrollBars() {\n document.documentElement.style.overflow = 'hidden'; // firefox, chrome\n document.body.scroll = \"no\"; // ie only\n}\n</code></pre>\n" }, { "answer_id": 16081832, "author": "Zeeshan Ali", "author_id": 1133785, "author_profile": "https://Stackoverflow.com/users/1133785", "pm_score": 3, "selected": false, "text": "<p>IE has some bug with the scrollbars. So if you want either of the two, you must include the following to hide the horizontal scrollbar:</p>\n\n<p><code>overflow-x: hidden;</code><br>\n<code>overflow-y:scroll;</code></p>\n\n<p>and to hide vertical:</p>\n\n<p><code>overflow-y: hidden;</code><br>\n<code>overflow-x: scroll;</code></p>\n" }, { "answer_id": 16226821, "author": "Qvcool", "author_id": 2016624, "author_profile": "https://Stackoverflow.com/users/2016624", "pm_score": 2, "selected": false, "text": "<p>Because Firefox has an arrow key short cut, you probably want to put a <code>&lt;div&gt;</code> around it with CSS style: <code>overflow:hidden;</code>.</p>\n" }, { "answer_id": 20801125, "author": "Lg102", "author_id": 775265, "author_profile": "https://Stackoverflow.com/users/775265", "pm_score": 3, "selected": false, "text": "<p>In modern versions of IE (IE10 and above), scrollbars can be hidden using the <a href=\"http://msdn.microsoft.com/en-us/library/ie/hh771902(v=vs.85).aspx\" rel=\"noreferrer\"><code>-ms-overflow-style</code> property</a>.</p>\n\n<pre><code>html {\n -ms-overflow-style: none;\n}\n</code></pre>\n\n<p>In Chrome, scrollbars can be styled:</p>\n\n<pre><code>::-webkit-scrollbar {\n display: none;\n}\n</code></pre>\n\n<p>This is very useful if you want to use the 'default' body scrolling in a web application, which is considerably faster than <code>overflow-y: scroll</code>.</p>\n" }, { "answer_id": 32781413, "author": "Erasmus Cedernaes", "author_id": 4713758, "author_profile": "https://Stackoverflow.com/users/4713758", "pm_score": 2, "selected": false, "text": "<p>(I can't comment yet, but wanted to share this):</p>\n\n<p>Lyncee's code worked for me in desktop browser. However, on iPad (Chrome, iOS 9), it crashed the application. To fix it, I changed </p>\n\n<pre><code>document.documentElement.style.overflow = ...\n</code></pre>\n\n<p>to</p>\n\n<pre><code>document.body.style.overflow = ...\n</code></pre>\n\n<p>which solved my problem.</p>\n" }, { "answer_id": 37098825, "author": "gtzinos", "author_id": 4669968, "author_profile": "https://Stackoverflow.com/users/4669968", "pm_score": 2, "selected": false, "text": "<p>Using JQuery you can disable scrolling bar with this code : </p>\n\n<pre><code>$('body').on({\n 'mousewheel': function(e) {\n if (e.target.id == 'el') return;\n e.preventDefault();\n e.stopPropagation();\n }\n});\n</code></pre>\n\n<p>Also you can enable it again with this code :</p>\n\n<pre><code> $('body').unbind('mousewheel');\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
Is it possible to disable the browsers vertical and horizontal scrollbars using jQuery or javascript?
In case you need possibility to hide and show scrollbars dynamically you could use ``` $("body").css("overflow", "hidden"); ``` and ``` $("body").css("overflow", "auto"); ``` somewhere in your code.
242,614
<p>A classic ASP.NET app - AppSrv + MS SQL DB. Both servers are heavy-lifters 8 cores, 20 GB of RAM. When load testing, the throughput goes somewhere to 400 VirtualUsers (according to LoadRunner) with CPU being approximately 30% utilized an DB server primarily idling - response times go dramatically up, to the point of unresponsive.</p> <p>The usual suspects, such as Max Pool being exhausted and conn limit on ASP.NET set are not at fault: Max Pool is set to 200 and about 80 conns are used; conn limit is set to 0. </p> <p>I ran with ANTS profiler the code and it showed that Thread blocking did not contribute significantly. </p> <p>Ideas very very welcome!</p>
[ { "answer_id": 242631, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": true, "text": "<p>Does the host utilize App Pool?</p>\n\n<p>Did you try increase the number to 5 to 10 in </p>\n\n<pre><code>An Application Pool -&gt; Performance -&gt; \nWeb Garden -&gt; Max Number of worker processes\n</code></pre>\n" }, { "answer_id": 242649, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 1, "selected": false, "text": "<p>When no CPUs are hosed and pages tend to become unresponsive, my first hunch is database locking. One thread can hold up the rest when not releasing a lock on a table, which results in non responsive pages while idling your db server.</p>\n\n<p>Can you use a sql monitoring tool to verify proper usege on the database machine and see if all users get their data properly?</p>\n\n<p>One other thing; what info can you give on memory use?</p>\n" }, { "answer_id": 242657, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Add logging to your app with some appropriate unique request ID so you can effectively trace how long each operation within a page load takes. For instance, logging before and after every database call will show whether the database calls are taking a long time or not.</p>\n\n<p>As others have suggested, adding logging/profiling on the database side will show whether that's deadlocked (or similar).</p>\n" }, { "answer_id": 242855, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 0, "selected": false, "text": "<p>Also check for network saturation. Make sure you aren't maxing out the network connection between your load test machine and the web server. Also, if you are returning alot of heavy text/binary data between your web and database server monitor that network connection. </p>\n" }, { "answer_id": 242997, "author": "Dave Anderson", "author_id": 371, "author_profile": "https://Stackoverflow.com/users/371", "pm_score": 1, "selected": false, "text": "<p>We recently tuned our web application using the following <a href=\"http://technet.microsoft.com/en-us/magazine/cc160755.aspx\" rel=\"nofollow noreferrer\">IIS performance settings</a> guide which proved very succesfull.</p>\n\n<p>There were two server specific settings we changed;</p>\n\n<p><strong>Working Set Memory Usage</strong> - Servers running Windows Server™ 2003 are configured by default to give preference to the file system cache over the working set when allocating memory. Microsoft does this because Windows benefits from having a large file system cache. Being that IIS rides on top of the Windows operating system, it also benefits from having a large file system cache. If your server is a dedicated IIS Server, though, you might see better performance if you shift priority to the working set instead. The reason behind this is if preference is given to the file system cache, the pageable code is often written to virtual memory. The next time this information is needed, something else must be paged to virtual memory and the previously paged information must be read into physical memory before it can be used. This results in very slow processing. </p>\n\n<p><strong>Network Throughput</strong> - By default, servers running Windows Server 2003 are configured to give preference to the file system cache over the working sets of processes when allocating memory (through the server property Maximize data throughput for file sharing). Although IIS 6.0–based servers benefit from a large file system cache, giving the file system cache preference often causes the IIS 6.0 pageable code to be written to disk, which results in lengthy processing delays. To avoid these processing delays, set server properties to maximize data throughput for network applications. </p>\n\n<p>The following services are not required on a dedicated Web server:</p>\n\n<ul>\n<li>Alerter </li>\n<li>ClipBook</li>\n<li>Computer Browser </li>\n<li>DHCP Client </li>\n<li>DHCP Server </li>\n<li>Fax Service </li>\n<li>File Replication </li>\n<li>Infrared Monitor </li>\n<li>Internet Connection Sharing </li>\n<li>Messenger </li>\n<li>NetMeeting Remote Desktop Sharing </li>\n<li>Network DDE </li>\n<li>Network DDE DSDM </li>\n<li>NWLink NetBIOS </li>\n<li>NWLink IPX/SPX </li>\n<li>Print Spooler </li>\n<li>TCP/IP NetBIOS Helper Service </li>\n<li>Telephony </li>\n<li>Telnet </li>\n<li>Uninterruptible Power Supply</li>\n</ul>\n" }, { "answer_id": 243279, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 0, "selected": false, "text": "<p>It may be a long shot, but you can try running your code through the <a href=\"http://www.codeplex.com/PracticesChecker\" rel=\"nofollow noreferrer\">Patterns and Practices Checker</a> to see if it finds any low hanging fruit.</p>\n" }, { "answer_id": 243460, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 1, "selected": false, "text": "<p>Problem is probably in your <code>machine.config</code> file. </p>\n\n<p>You should check following configuration parameters:</p>\n\n<ul>\n<li><code>maxconnection</code></li>\n<li><code>maxIoThreads</code></li>\n<li><code>maxWorkerThreads</code></li>\n<li><code>minFreeThreads</code></li>\n<li><code>minLocalRequestFreeThreads</code> </li>\n</ul>\n\n<p>For short description check: <a href=\"http://www.eggheadcafe.com/articles/20050613.asp\" rel=\"nofollow noreferrer\">IIS 6.0 Tuning for Performance </a></p>\n\n<p>There are some differences between ASP.NET 1.1 and ASP.NET 2.0</p>\n\n<p><strong>ASP.NET 1.1</strong></p>\n\n<p>Guidelines about some practical values you can find in:</p>\n\n<ul>\n<li><a href=\"http://support.microsoft.com/?id=821268\" rel=\"nofollow noreferrer\">Microsoft Kb article 821268</a></li>\n<li>MSDN Article <a href=\"http://msdn.microsoft.com/en-us/library/ms998549.aspx#scalenetchapt06_topic8\" rel=\"nofollow noreferrer\" title=\"Threading Explained chapter\">\"Chapter 6 — Improving ASP.NET Performance - Threading Explained\"</a></li>\n</ul>\n\n<p>Default values are way to low for any practical use and should be corrected according to suggestions in linked articles.</p>\n\n<p><strong>ASP.NET 2.0</strong></p>\n\n<p>Parameters are moved to <code>processModel</code> section and parameters are auto configured.\nBesides auto configuration, you can manually set parameter values, so you should check if:</p>\n\n<ul>\n<li><code>processModel</code> is enabled</li>\n<li><code>autoConfig</code> is set to <code>true</code>\n<br>or</li>\n<li>parameters are set to correct values</li>\n</ul>\n\n<p>For detailed description check: <a href=\"http://msdn.microsoft.com/en-us/library/7w2sway1.aspx\" rel=\"nofollow noreferrer\">ASP.Net 2.0 processModel</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29573/" ]
A classic ASP.NET app - AppSrv + MS SQL DB. Both servers are heavy-lifters 8 cores, 20 GB of RAM. When load testing, the throughput goes somewhere to 400 VirtualUsers (according to LoadRunner) with CPU being approximately 30% utilized an DB server primarily idling - response times go dramatically up, to the point of unresponsive. The usual suspects, such as Max Pool being exhausted and conn limit on ASP.NET set are not at fault: Max Pool is set to 200 and about 80 conns are used; conn limit is set to 0. I ran with ANTS profiler the code and it showed that Thread blocking did not contribute significantly. Ideas very very welcome!
Does the host utilize App Pool? Did you try increase the number to 5 to 10 in ``` An Application Pool -> Performance -> Web Garden -> Max Number of worker processes ```
242,617
<p>Posting a stack overflow question on stackoverflow.com, how amusing :-)</p> <p>I'm running some recursive Ruby code and I get the: <code>"Stack level too deep (SystemStackError)"</code></p> <p>(I'm quite sure the code works, that I'm not in an infinite recursive death spiral, but that is not the point anyway)</p> <p>Is there anyway to change the allowed stack depth/size for my Ruby app?</p> <p>I don't quite get it if this is a restriction in Ruby, since the error says "Stack level", which gives me the impression that Ruby somehow counts 'levels' of stack, or if it simply means that the stack is full.</p> <p>I have tried running this program under both Vista and Ubuntu with same result. Under Ubuntu i tried changing the stack size with 'ulimit -s' from 8192 to 16000, but that didn't change anything.</p> <p>Edit: Thanks for the feedback.<br> I do realize that using a recursive function perhaps isn't the most robust way to go. But that isn't the point either. I simply wonder if there is a way to increase the stack size.. period. And as I mentioned i did try running ulimit -s 16000 before running the ruby script.. with no improvement.. Am I using it wrong?</p> <p>Edit2: I was in fact having an infinite recursion in an edge case of the code. <br>The truncated ruby stack trace when you get the <code>"Stack level too deep"</code> error is a bit misleading. <br>When having a recursive behavior involving several functions, you get the impression that the numbers of recursions is much lower than it actually is. In this example one might thing that it crashes after little bit more than 190 calls, but it is actually around 15000 calls</p> <pre><code>tst.rb:8:in `p': stack level too deep (SystemStackError) from tst.rb:8:in `bar' from tst.rb:12:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' ... 190 levels... from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:22 </code></pre> <p>-Andreas</p>
[ { "answer_id": 242659, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 3, "selected": false, "text": "<p>Yukihiro Matsumoto writes <a href=\"http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/d4d50fb6127933ec?pli=1\" rel=\"nofollow noreferrer\">here</a></p>\n\n<blockquote>\n <p>Ruby uses C stack, so that you need to\n use ulimit to specify a limit on\n stack depth.</p>\n</blockquote>\n" }, { "answer_id": 242667, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 4, "selected": true, "text": "<p>Ruby uses the C stack so your options include using ulimit or compiling Ruby with some compiler/linker stack size flag. Tail recursion is yet to be implemented and Ruby's current support for recursion isn't so great. As cool and elegant recursion is, you might want to consider coping with the language's limitations and writing your code in a different way.</p>\n" }, { "answer_id": 243005, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 2, "selected": false, "text": "<p>Think about what is going on with the code. As other posters have mentioned it is possible to hack the C code of the interpreter. However. the result will be that you are using more RAM and have no guarantee that you won't blow the stack again.</p>\n\n<p>The really good solution would be to come up with an iterative algorithm for what you are trying to do. Sometimes memoisation can help and sometimes you find you are not using the stuff you are pushing on the stack in which case you can replace recursive calls with mutable state. </p>\n\n<p>If you are new to this sort of stuff have a look at SICP <a href=\"http://mitpress.mit.edu/sicp/\" rel=\"nofollow noreferrer\">here</a> for some ideas...</p>\n" }, { "answer_id": 244348, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 4, "selected": false, "text": "<p>If you are sure that you do not have an Infinite recursion situation then your algorythm is pobably not suited for Ruby to execute it in a recirsive manner. Converting an algorythm from recursion to different kind of stack is pretty easy and I suggest you try that. Here is how you can do it.</p>\n\n<pre><code>def recursive(params)\n if some_conditions(params)\n recursive(update_params(params))\n end\nend\n\nrecursive(starting_params)\n</code></pre>\n\n<p>will transform into</p>\n\n<pre><code>stack = [starting_params]\nwhile !stack.empty?\n current_params = stack.delete_at(0)\n if some_conditions(current_params)\n stack &lt;&lt; update_params(current_params)\n end\nend\n</code></pre>\n" }, { "answer_id": 8119686, "author": "Folke", "author_id": 230291, "author_profile": "https://Stackoverflow.com/users/230291", "pm_score": 2, "selected": false, "text": "<p>Just had the same issue and it is very easy to fix on Linux or on Mac. As said in the other answers, Ruby uses the system stack setting. You can easily change this on Mac and Linux by setting the stack size. Fox example:</p>\n\n<pre><code>ulimit -s 20000\n</code></pre>\n" }, { "answer_id": 27510458, "author": "gregspurrier", "author_id": 601798, "author_profile": "https://Stackoverflow.com/users/601798", "pm_score": 5, "selected": false, "text": "<p>This question and its answers appear to date back to Ruby 1.8.x, which used the C stack. Ruby 1.9.x and later use a VM that has its own stack. In Ruby 2.0.0 and later, the size of the VM stack can be controlled via the <code>RUBY_THREAD_VM_STACK_SIZE</code> environment variable.</p>\n" }, { "answer_id": 43838159, "author": "Kathryn", "author_id": 7948068, "author_profile": "https://Stackoverflow.com/users/7948068", "pm_score": 1, "selected": false, "text": "<p>As of <a href=\"http://blog.tdg5.com/tail-call-optimization-in-ruby-background/\" rel=\"nofollow noreferrer\">Ruby 1.9.2</a> you can turn on tail-call optimization with something like:</p>\n\n<pre><code>RubyVM::InstructionSequence.compile_option = {\n tailcall_optimization: true,\n trace_instruction: false\n}\n\nRubyVM::InstructionSequence.new(&lt;&lt;-EOF).eval\n def me_myself_and_i\n me_myself_and_i\n end\nEOF\nme_myself_and_i # Infinite loop, not stack overflow\n</code></pre>\n\n<p>That will avoid the <code>SystemStackError</code> error if the recursive call is at the end of the method and <em>only the method</em>. Of course, this example will result in an infinite loop instead. Probably best to debug using shallow recursion (and no optimization) before going after deep recursion.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28625/" ]
Posting a stack overflow question on stackoverflow.com, how amusing :-) I'm running some recursive Ruby code and I get the: `"Stack level too deep (SystemStackError)"` (I'm quite sure the code works, that I'm not in an infinite recursive death spiral, but that is not the point anyway) Is there anyway to change the allowed stack depth/size for my Ruby app? I don't quite get it if this is a restriction in Ruby, since the error says "Stack level", which gives me the impression that Ruby somehow counts 'levels' of stack, or if it simply means that the stack is full. I have tried running this program under both Vista and Ubuntu with same result. Under Ubuntu i tried changing the stack size with 'ulimit -s' from 8192 to 16000, but that didn't change anything. Edit: Thanks for the feedback. I do realize that using a recursive function perhaps isn't the most robust way to go. But that isn't the point either. I simply wonder if there is a way to increase the stack size.. period. And as I mentioned i did try running ulimit -s 16000 before running the ruby script.. with no improvement.. Am I using it wrong? Edit2: I was in fact having an infinite recursion in an edge case of the code. The truncated ruby stack trace when you get the `"Stack level too deep"` error is a bit misleading. When having a recursive behavior involving several functions, you get the impression that the numbers of recursions is much lower than it actually is. In this example one might thing that it crashes after little bit more than 190 calls, but it is actually around 15000 calls ``` tst.rb:8:in `p': stack level too deep (SystemStackError) from tst.rb:8:in `bar' from tst.rb:12:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' ... 190 levels... from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:22 ``` -Andreas
Ruby uses the C stack so your options include using ulimit or compiling Ruby with some compiler/linker stack size flag. Tail recursion is yet to be implemented and Ruby's current support for recursion isn't so great. As cool and elegant recursion is, you might want to consider coping with the language's limitations and writing your code in a different way.
242,621
<p>I'm having trouble running a complex query against our company LDAP server. I'm using the following Perl script:</p> <pre><code>use Data::Dumper; use Net::LDAP; die "Can't connect to LDAP-Server: $@\n" unless $ldap = Net::LDAP-&gt;new( 'xLDAPx' ); foreach my $filter ( 'ou=Personal', 'ou=BAR', 'ou=Personal,ou=BAR', 'ou=Personal,ou=FOO,o=FOO,dc=foo,dc=com' ) { $mesg = $ldap-&gt;search( base =&gt; "o=FOO,dc=foo,dc=com", filter =&gt; $filter ); print Dumper($mesg), "\n\n"; } </code></pre> <p>While the first two filters work (as in returning the expected values) the last and complex one doesn't. It returns an empty array. What really puzzles me is that exactly the same query string works when I use it with a tool like the Softerra LDAP Browser. </p> <p>I have also tried the same query using PHP's <code>ldap_search</code> &amp; co, no avail.</p> <p>Can somebody shed some light on this?</p> <p>Thanks for reading</p> <p>holli</p> <p>Edit: This is the structure of the server:</p> <pre><code>Server ou=FOO ou=... ou=Personal uid=something </code></pre> <p>I need a list of uids.</p>
[ { "answer_id": 242656, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>The reason is that you are not providing syntactically correct filter strings, but parts of a DN. I can't imagine this works in Ldap Browser - I just tried myself without success.</p>\n\n<p>The first two are correct filter strings. They filter on a single object attribute in a \"({attribute}={value})\" fashion. The first (\"ou=Personal\") would return any OU named \"Personal\" within your search base.</p>\n\n<p>If you explain in more detail what you are trying to find I can probably tell you what filter expression you need.</p>\n" }, { "answer_id": 242779, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": true, "text": "<p>I think you want it to be more like <code>(&amp;(ou=Personal)(ou=FOO)(o=FOO)(dc=foo)(dc=com))</code>.\nBut you are not clear at all on what you want exactly, so I can't make a filter for you.</p>\n\n<p>Edited to add: I'm guessing this is what you want to do: <code>(|(ou=Personal)(ou=FOO))</code></p>\n" }, { "answer_id": 242952, "author": "Peter Scott", "author_id": 28086, "author_profile": "https://Stackoverflow.com/users/28086", "pm_score": 2, "selected": false, "text": "<p>Write a filter that conforms to <a href=\"http://www.faqs.org/rfcs/rfc2254.html\" rel=\"nofollow noreferrer\">RFC 2254</a>\n and then see what happens. You don't need a complex query, you want one attribute for every entry under one branch. Look at the attrs argument for the search method.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18606/" ]
I'm having trouble running a complex query against our company LDAP server. I'm using the following Perl script: ``` use Data::Dumper; use Net::LDAP; die "Can't connect to LDAP-Server: $@\n" unless $ldap = Net::LDAP->new( 'xLDAPx' ); foreach my $filter ( 'ou=Personal', 'ou=BAR', 'ou=Personal,ou=BAR', 'ou=Personal,ou=FOO,o=FOO,dc=foo,dc=com' ) { $mesg = $ldap->search( base => "o=FOO,dc=foo,dc=com", filter => $filter ); print Dumper($mesg), "\n\n"; } ``` While the first two filters work (as in returning the expected values) the last and complex one doesn't. It returns an empty array. What really puzzles me is that exactly the same query string works when I use it with a tool like the Softerra LDAP Browser. I have also tried the same query using PHP's `ldap_search` & co, no avail. Can somebody shed some light on this? Thanks for reading holli Edit: This is the structure of the server: ``` Server ou=FOO ou=... ou=Personal uid=something ``` I need a list of uids.
I think you want it to be more like `(&(ou=Personal)(ou=FOO)(o=FOO)(dc=foo)(dc=com))`. But you are not clear at all on what you want exactly, so I can't make a filter for you. Edited to add: I'm guessing this is what you want to do: `(|(ou=Personal)(ou=FOO))`
242,627
<pre><code>today1 = new Date(); today2 = Date.parse("2008-28-10"); </code></pre> <p>To compare the time (millisecond) values of these I have to do the following, because today2 is just a number.</p> <pre><code>if (today1.getTime() == today2) </code></pre> <p>Why is this?</p>
[ { "answer_id": 242632, "author": "Yuval Adam", "author_id": 24545, "author_profile": "https://Stackoverflow.com/users/24545", "pm_score": 2, "selected": false, "text": "<p>If I remember correctly, Date gives you a value down to the millisecond you created the Date object. So unless this code runs exactly on 2008-28-10 at 00:00:00:000, they won't be the same.</p>\n\n<p>Just an addition: Date.parse() by definition returns a long value representing the millisecond value of the Date, and not the Date object itself. If you want to hold the Date object itself, just build it like so:</p>\n\n<pre><code>var newDate = new Date();\nnewDate.setFullYear(2008,9,28);\n</code></pre>\n\n<p>For more reference check out: <a href=\"http://www.w3schools.com/jsref/jsref_obj_date.asp\" rel=\"nofollow noreferrer\">the Date class reference</a></p>\n" }, { "answer_id": 242679, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": true, "text": "<p>To answer the question in the title: Because they decided so when creating the JavaScript language. Probably because Java's <code>java.util.Date</code> parse function was doing the same thing, and they wanted to mimic its behavior to make the language feel more familiar.</p>\n\n<p>To answer the question in the text... Use this construct to get two date objects:</p>\n\n<pre><code>var today2 = new Date(Date.parse(\"2008-10-28\"));\n</code></pre>\n\n<hr>\n\n<p>EDIT: A simple</p>\n\n<pre><code>var today2 = new Date(\"2008-10-28\");\n</code></pre>\n\n<p>also works. </p>\n\n<hr>\n\n<p>Note: Old Internet Explorer versions (anything before 9) does not understand dashes in the date string. It works with slashes, though:</p>\n\n<pre><code>var today2 = new Date(\"2008/10/28\");\n</code></pre>\n\n<p>Slashes seem to be universally understood by browsers both old and new.</p>\n" }, { "answer_id": 242681, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 1, "selected": false, "text": "<p>What Data.parse is returning is a NaN. Which fundementally is an indefinite number. This is what most implementations return when its unable to convert the string to a date. Some implementations do not cope with anything but an <a href=\"https://www.rfc-editor.org/rfc/rfc1123\" rel=\"nofollow noreferrer\">RFC 1123</a> compliant date strings (which is all that the spec requires).</p>\n<p><strong>Edit</strong>: A comment to this answer states that Date.parse does not return NaN. However the spec says that parse should return a number. What number should it return when given a string that it can't parse as a date? It can't use 0 or -1 or some other such 'rogue' value because these a valid millisecond offsets from Jan 1, 1970. Mozilla and IE both return NaN which is a perfectly sensible thing to do.</p>\n<p>Whilst the spec doesn't preclude the parsing of a string such as &quot;2008-28-10&quot; to a valid date it doesn't require it. I haven't come across any implementations that do anything more than required in the spec. Hence &quot;Oct 10, 2008&quot; is the closest you're gonna get to the string above that will parse properly.</p>\n" }, { "answer_id": 242785, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>I can't answer in place of the language designers, but you can use the result of Date.parse or Date.UTC in the Date constructor to get such object.</p>\n\n<p>Note that your code sample is incorrect: it is not a valid date format, not ISO (yyyy-mm-dd) nor IETF (Mon, 25 Dec 1995 13:30:00 GMT+0430 ). So you will get a NaN. Date.parse only understand IETF format, from what I have read on <a href=\"https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Date/Parse\" rel=\"nofollow noreferrer\" title=\"Mozilla Devloper Center\">MDC</a>.</p>\n\n<p>If you need to compare two dates, you might compare the results of .getFullYear(), .getMonth() and .getDay(), or just compare the string representations at the wanted level.</p>\n\n<pre><code>var d1 = new Date();\nvar n = Date.parse(\"28 Oct 2008\");\nvar d2 = new Date(n);\nvar d3 = new Date(\"28 october 2008\");\n\nalert(d1.toDateString() == d2.toDateString());\nalert(d2.toDateString() == d3.toDateString());\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
``` today1 = new Date(); today2 = Date.parse("2008-28-10"); ``` To compare the time (millisecond) values of these I have to do the following, because today2 is just a number. ``` if (today1.getTime() == today2) ``` Why is this?
To answer the question in the title: Because they decided so when creating the JavaScript language. Probably because Java's `java.util.Date` parse function was doing the same thing, and they wanted to mimic its behavior to make the language feel more familiar. To answer the question in the text... Use this construct to get two date objects: ``` var today2 = new Date(Date.parse("2008-10-28")); ``` --- EDIT: A simple ``` var today2 = new Date("2008-10-28"); ``` also works. --- Note: Old Internet Explorer versions (anything before 9) does not understand dashes in the date string. It works with slashes, though: ``` var today2 = new Date("2008/10/28"); ``` Slashes seem to be universally understood by browsers both old and new.
242,640
<p>I wanna see if there is an approach to pack a few plugins together as a meta plugin that install everything together automatically, works like a project template.</p> <p>Why not a script? Because I want to put it in github so I don't have to worry about it when I am not with my own PC :) but of coz a script based solution is welcomed too.</p>
[ { "answer_id": 243330, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 1, "selected": false, "text": "<p>My solution (ruby script):</p>\n\n<pre><code>plugins = %w{\n http://url_to_plugin_1\n http://url_to_plugin_2\n http://url_to_plugin_3\n http://url_to_plugin_4\n http://url_to_plugin_5\n}\nplugins.each do | p |\n `ruby script/plugin install -x #{p}`\nend\n</code></pre>\n\n<p>run from project root directory</p>\n" }, { "answer_id": 550841, "author": "pjb3", "author_id": 41984, "author_profile": "https://Stackoverflow.com/users/41984", "pm_score": 0, "selected": false, "text": "<p>If what you really want is a project template, you might give <a href=\"http://m.onkey.org/2008/12/4/rails-templates\" rel=\"nofollow noreferrer\">templates</a> a try, which is a feature new to 2.3</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371/" ]
I wanna see if there is an approach to pack a few plugins together as a meta plugin that install everything together automatically, works like a project template. Why not a script? Because I want to put it in github so I don't have to worry about it when I am not with my own PC :) but of coz a script based solution is welcomed too.
My solution (ruby script): ``` plugins = %w{ http://url_to_plugin_1 http://url_to_plugin_2 http://url_to_plugin_3 http://url_to_plugin_4 http://url_to_plugin_5 } plugins.each do | p | `ruby script/plugin install -x #{p}` end ``` run from project root directory
242,646
<p>How can I use vimdiff to view the differences described in a diff file?</p>
[ { "answer_id": 242680, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>Make a copy of the original file, apply the diff and then</p>\n\n<pre><code>vimdiff original_file patched_file\n</code></pre>\n\n<p>You could also look at <a href=\"http://www.vim.org/scripts/script.php?script_id=2090\" rel=\"nofollow noreferrer\">vim.org scripts</a> which have been written to deal with svn diff output. If you are generating your diff from a version control system then take a look at the <a href=\"http://www.vim.org/scripts/script.php?script_id=90\" rel=\"nofollow noreferrer\">vcscommand.vim : CVS/SVN/SVK/git integration plugin</a>.</p>\n" }, { "answer_id": 244766, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 6, "selected": false, "text": "<p>Instead of using <code>/usr/bin/vimdiff</code> command, try this:</p>\n\n<pre>$ vim file\n:vertical diffpatch path/to/diff</pre>\n\n<p>(<code>:vert diffpa</code> for short.)<br>\nThis is equivalent to calling <code>vimdiff</code> on the original file and the subsequently patched file, but <code>vim</code> calls <code>patch</code> on a temporary file for you.</p>\n\n<h2>Edit</h2>\n\n<p>If you want <code>vim</code>'s diff-mode to be entered automatically, use this:</p>\n\n<pre>$ vim file +'vert diffpa path/to/diff'</pre>\n\n<p>where <code>+command</code> asks <code>vim</code> to execute \"command\". (<code>+123</code> jumps to line 123, <code>+/abc</code> jumps to the first match for \"abc\", it's all documented.)</p>\n\n<p>Regarding Ken's query: if the diff file includes hunks applying to files other than the file you're currently editing, no worries; <code>vim</code> calls the <code>patch</code> executable underneath, which will ask for the locations of these mysteriously missing files, and you can tell <code>patch</code> to just skip those hunks.</p>\n" }, { "answer_id": 247514, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 2, "selected": false, "text": "<p>Coming from the other direction. I wrote a Vim plugin that shows the changes that have been made to a file since the last save in either vimdiff or unified diff format.</p>\n\n<p>Get it here: <a href=\"http://www.vim.org/scripts/script.php?script_id=2158\" rel=\"nofollow noreferrer\">diffchanges.vim</a></p>\n" }, { "answer_id": 4169689, "author": "Adam Monsen", "author_id": 156060, "author_profile": "https://Stackoverflow.com/users/156060", "pm_score": 1, "selected": false, "text": "<p>Would you say more about why you want to use vimdiff for this?</p>\n\n<p>For instance, do you want to <a href=\"https://stackoverflow.com/questions/3231759/how-can-i-visualize-per-character-differences-in-a-unified-diff-file\">visualize per-character differences in a (unified) diff file?</a>. If so, someone answered <a href=\"https://stackoverflow.com/questions/3231759/how-can-i-visualize-per-character-differences-in-a-unified-diff-file\">my question about same</a> with <a href=\"https://stackoverflow.com/questions/3231759/how-can-i-visualize-per-character-differences-in-a-unified-diff-file/3509992#3509992\">a suggestion</a> to basically just fire up emacs on the diff and hit <code>ALT-n</code> to cycle through hunks, nicely highlighting per-word or per-characters changes along the way (similar to vimdiff). It works well, but it's a bummer to fire up emacs just to do this. I only know enough emacs to do that then exit without mucking up the patch. :)</p>\n\n<p>Anyway, the emacs answer gave me some ideas. I'm sure Vim can be cajoled into providing better highlighting for diff files, maybe something more like ediff. I looked into this a while back, and someone on the vim user list had the excellent suggestion to <a href=\"http://thread.gmane.org/gmane.editors.vim/89542/focus=91342\" rel=\"nofollow noreferrer\">incorporate google-diff-match-patch</a>. The Python interface could be used from a Python Vim ftplugin, for instance.</p>\n\n<p>Sorry about using an \"answer\" to reply when this may not be a great answer, the formatting for \"add comment\" was too limited for what I wanted to say.</p>\n\n<p>For posterity, <a href=\"https://stackoverflow.com/questions/704707/viewing-unified-diff-with-meld-vimdiff-other-tools\">here's a reference to another similar question</a> (which already links here as well).</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14437/" ]
How can I use vimdiff to view the differences described in a diff file?
Instead of using `/usr/bin/vimdiff` command, try this: ``` $ vim file :vertical diffpatch path/to/diff ``` (`:vert diffpa` for short.) This is equivalent to calling `vimdiff` on the original file and the subsequently patched file, but `vim` calls `patch` on a temporary file for you. Edit ---- If you want `vim`'s diff-mode to be entered automatically, use this: ``` $ vim file +'vert diffpa path/to/diff' ``` where `+command` asks `vim` to execute "command". (`+123` jumps to line 123, `+/abc` jumps to the first match for "abc", it's all documented.) Regarding Ken's query: if the diff file includes hunks applying to files other than the file you're currently editing, no worries; `vim` calls the `patch` executable underneath, which will ask for the locations of these mysteriously missing files, and you can tell `patch` to just skip those hunks.
242,647
<p>I have one aspx page with some controls. Also i have one DIV which is dynamically populated from AJAX call. This AJAX call return couple of controls, for example HtmlInputText1 and HtmlInputText2.</p> <p>When page is submitted, I can get values from this controls through Request.Form. If possible access to the attributes of this control on pege code behind (for example HtmlInputText1.Height, etc). </p> <p>I think that is impossible, but I am not sure. I can use hidden field. Is any other way?</p>
[ { "answer_id": 242692, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 2, "selected": true, "text": "<p>The data you want the server to know can be set by the javascript within the form.\nThen You can process postback data for the target values manually.</p>\n\n<p>You can write some javascript which modify the value of the server control within browser.</p>\n\n<pre><code>&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\nfunction changeValue() {\n var txtControlClient = document.getElementById('&lt;%= txtControl.ClientID %&gt;');\n txtControlClient.value = \"modified text\";\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>In the expected event, you call changeValue() function before the postback, then you can just use server control object txtControl to obtain the value or property you have altered.</p>\n" }, { "answer_id": 243421, "author": "SelvirK", "author_id": 17465, "author_profile": "https://Stackoverflow.com/users/17465", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>The data you want the server to know\n can be set by the javascript within\n the form. Then You can process\n postback data for the target values\n manually.</p>\n</blockquote>\n\n<p>How to make this?</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
I have one aspx page with some controls. Also i have one DIV which is dynamically populated from AJAX call. This AJAX call return couple of controls, for example HtmlInputText1 and HtmlInputText2. When page is submitted, I can get values from this controls through Request.Form. If possible access to the attributes of this control on pege code behind (for example HtmlInputText1.Height, etc). I think that is impossible, but I am not sure. I can use hidden field. Is any other way?
The data you want the server to know can be set by the javascript within the form. Then You can process postback data for the target values manually. You can write some javascript which modify the value of the server control within browser. ``` <script language="javascript" type="text/javascript"> function changeValue() { var txtControlClient = document.getElementById('<%= txtControl.ClientID %>'); txtControlClient.value = "modified text"; } </script> ``` In the expected event, you call changeValue() function before the postback, then you can just use server control object txtControl to obtain the value or property you have altered.
242,665
<p>I'm trying to set up a basic test of HMAC-SHA-256 hashing but I'm having problems with the engine setup. Ideally I would like to set up only the HMAC-SHA-algorithm but so far I haven't even gotten the general case where load all the algorithms to work. Currently I'm getting segfaults on the row where I try to set the default digests.</p> <p>Also, I'm regularly a Java guy, so don't hesitate to point out any mistakes in the code.</p> <pre><code>#include &lt;openssl/hmac.h&gt; #include &lt;openssl/evp.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; int main() { unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"; unsigned char* data = (unsigned char*) "4869205468657265"; unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; unsigned char* result; HMAC_CTX* ctx; ENGINE* e; ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); ENGINE_set_default_digests(e); HMAC_CTX_init(ctx); HMAC_Init_ex(ctx, key, 40, EVP_sha256(), e); result = HMAC(NULL, NULL, 40, data, 16, NULL, NULL); HMAC_CTX_cleanup(ctx); ENGINE_finish(e); ENGINE_free(e); if (strcmp((char*) result, (char*) expected) == 0) { printf("Test ok\n"); } else { printf("Got %s instead of %s\n", result, expected); } } </code></pre> <p>EDIT: The program has now evolved to the following, but I'm still segfaulting at <code>HMAC_Init_ex</code>:</p> <pre><code>unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"; unsigned char* data = (unsigned char*) "4869205468657265"; unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; unsigned char* result; unsigned int result_len = 64; HMAC_CTX ctx; ENGINE* e; result = (unsigned char*) malloc(sizeof(char) * result_len); e = (ENGINE*) ENGINE_new(); ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); ENGINE_set_default_digests(e); HMAC_CTX_init(&amp;ctx); HMAC_Init_ex(&amp;ctx, key, 16, EVP_sha256(), e); HMAC_Update(&amp;ctx, data, 40); HMAC_Final(&amp;ctx, result, &amp;result_len); HMAC_CTX_cleanup(&amp;ctx); ENGINE_finish(e); ENGINE_free(e); </code></pre>
[ { "answer_id": 242687, "author": "Martin Kenny", "author_id": 6111, "author_profile": "https://Stackoverflow.com/users/6111", "pm_score": 0, "selected": false, "text": "<p>It looks as though nothing is allocating an engine, so the first use of <code>e</code> is segfaulting. I think you need to call <code>ENGINE *ENGINE_new(void)</code> first.</p>\n\n<p>(Note that I've used OpenSSL, but I haven't used the <code>ENGINE</code> functions before.)</p>\n\n<p><strong>Update</strong>: I'm not really happy with my own answer (I had to dash off to tea, before). So my further notes are:</p>\n\n<ol>\n<li><p>I've had a bit of a look at the (long) <a href=\"http://www.manpagez.com/man/3/engine/\" rel=\"nofollow noreferrer\">man page</a> for the <code>ENGINE</code> functions, and I'm not quite sure that calling <code>ENGINE_new</code> is sufficient.</p></li>\n<li><p>I didn't notice that the calls to the <code>HMAC_CTX_*</code> functions were taking an uninitialized pointer, rather than a pointer to an allocated structure. <code>HMAC_CTX_init</code> will try to write to the memory pointed to by its <code>ctx</code> parameter, which will segfault. You need to declare and use <code>ctx</code> like this:</p>\n\n<pre><code>HMAC_CTX ctx;\nHMAC_CTX_init(&amp;ctx);\nHMAC_Init_ex(&amp;ctx, key, 40, EVP_sha256(), e);\n...\n</code></pre>\n\n<p>That way you're allocating the structure on the stack, and then passing a pointer to it.</p></li>\n<li><p>The <code>HMAC</code> function doesn't take a pointer to a <code>CTX</code> at all, so apart from global or thread-local storage, I'm not sure what it's connection to the <code>CTX</code> is. I think you can bypass that by calling <code>HMAC_Update</code> one-or-more times, followed by <code>HMAC_Final</code> to get the result. You'd need to allocate space for that result, so something like the following would work for that:</p>\n\n<pre><code>unsigned int len;\nHMAC_Final(&amp;ctx, result, &amp;len);\n</code></pre></li>\n</ol>\n" }, { "answer_id": 244310, "author": "Fylke", "author_id": 30059, "author_profile": "https://Stackoverflow.com/users/30059", "pm_score": 2, "selected": false, "text": "<p>Okay, turns out that you don't have to use an engine but I'd misunderstood exactly how not to use an explicit engine. I also misunderstood how to properly format the test vectors. In the end I looked at hmactest.c which pretty much does all I want to do, I just didn't understand the code.</p>\n\n<p>The final solution to what I was trying to do looks like this:</p>\n\n<pre><code>int main() {\n unsigned char* key = (unsigned char*) \"Jefe\";\n unsigned char* data = (unsigned char*) \"what do ya want for nothing?\";\n unsigned char* expected = (unsigned char*) \"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843\";\n unsigned char* result;\n unsigned int result_len = 32;\n int i;\n static char res_hexstring[32];\n\n result = HMAC(EVP_sha256(), key, 4, data, 28, NULL, NULL);\n for (i = 0; i &lt; result_len; i++) {\n sprintf(&amp;(res_hexstring[i * 2]), \"%02x\", result[i]);\n }\n\n if (strcmp((char*) res_hexstring, (char*) expected) == 0) {\n printf(\"Test ok, result length %d\\n\", result_len);\n } else {\n printf(\"Got %s instead of %s\\n\", res_hexstring, expected);\n }\n}\n</code></pre>\n\n<p>But since I was asking about something entirely different, I'm unsure about what to do with the original question. Suggestions?</p>\n" }, { "answer_id": 245335, "author": "Jon Bright", "author_id": 1813, "author_profile": "https://Stackoverflow.com/users/1813", "pm_score": 5, "selected": true, "text": "<p>The problem with your original suggestion is, as Martin said, that you need to initialise the ENGINE. The problem with your edited code was that you were doing ENGINE_new, which is getting you a completely new ENGINE of your own, which you then need to provide with cipher methods, digest methods, etc. In fact, for what you want (and what almost everybody wants), just completely ignoring all of the ENGINE stuff is the right choice. </p>\n\n<p>Some subsidiary problems: </p>\n\n<ul>\n<li>your strings were hex, but you needed a \\x per character to actually get that hex byte at that position in the string, which I suspect was what you wanted.</li>\n<li>you were trying to hash 40 bytes from \"data\", which wasn't that long (actual effect: you'd end up partly hashing your result string)</li>\n<li>your expected result was (as far as I can tell) incorrect</li>\n<li>you would print out random characters to the terminal, since the HMAC function will produce 32 bytes of random binary data, not printable stuff.</li>\n</ul>\n\n<p>The following code compiles, works and passes the test. It's a bit different to the example code you found (since it still uses the individual HMAC_* functions - useful if you want to do your hashing bit by bit using HMAC_Update):</p>\n\n<pre><code>#include &lt;openssl/engine.h&gt;\n#include &lt;openssl/hmac.h&gt;\n#include &lt;openssl/evp.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\n\nint main(void)\n{\n unsigned char* key = (unsigned char*) \"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\";\n unsigned char* data = (unsigned char*) \"\\x48\\x69\\x20\\x54\\x68\\x65\\x72\\x65\";\n unsigned char* expected = (unsigned char*) \"\\x49\\x2c\\xe0\\x20\\xfe\\x25\\x34\\xa5\\x78\\x9d\\xc3\\x84\\x88\\x06\\xc7\\x8f\\x4f\\x67\\x11\\x39\\x7f\\x08\\xe7\\xe7\\xa1\\x2c\\xa5\\xa4\\x48\\x3c\\x8a\\xa6\";\n unsigned char* result;\n unsigned int result_len = 32;\n int i;\n HMAC_CTX ctx;\n\n result = (unsigned char*) malloc(sizeof(char) * result_len);\n\n ENGINE_load_builtin_engines();\n ENGINE_register_all_complete();\n\n HMAC_CTX_init(&amp;ctx);\n HMAC_Init_ex(&amp;ctx, key, 16, EVP_sha256(), NULL);\n HMAC_Update(&amp;ctx, data, 8);\n HMAC_Final(&amp;ctx, result, &amp;result_len);\n HMAC_CTX_cleanup(&amp;ctx);\n\n for (i=0; i!=result_len; i++)\n {\n if (expected[i]!=result[i])\n {\n printf(\"Got %02X instead of %02X at byte %d!\\n\", result[i], expected[i], i);\n break;\n }\n }\n if (i==result_len)\n {\n printf(\"Test ok!\\n\");\n }\n return 0;\n}\n</code></pre>\n\n<p>Of course, it doesn't answer your original question about how to initialise ENGINEs, but there's really no right answer to that without having more context, which context turns out not to be relevant in your situation...</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30059/" ]
I'm trying to set up a basic test of HMAC-SHA-256 hashing but I'm having problems with the engine setup. Ideally I would like to set up only the HMAC-SHA-algorithm but so far I haven't even gotten the general case where load all the algorithms to work. Currently I'm getting segfaults on the row where I try to set the default digests. Also, I'm regularly a Java guy, so don't hesitate to point out any mistakes in the code. ``` #include <openssl/hmac.h> #include <openssl/evp.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"; unsigned char* data = (unsigned char*) "4869205468657265"; unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; unsigned char* result; HMAC_CTX* ctx; ENGINE* e; ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); ENGINE_set_default_digests(e); HMAC_CTX_init(ctx); HMAC_Init_ex(ctx, key, 40, EVP_sha256(), e); result = HMAC(NULL, NULL, 40, data, 16, NULL, NULL); HMAC_CTX_cleanup(ctx); ENGINE_finish(e); ENGINE_free(e); if (strcmp((char*) result, (char*) expected) == 0) { printf("Test ok\n"); } else { printf("Got %s instead of %s\n", result, expected); } } ``` EDIT: The program has now evolved to the following, but I'm still segfaulting at `HMAC_Init_ex`: ``` unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"; unsigned char* data = (unsigned char*) "4869205468657265"; unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; unsigned char* result; unsigned int result_len = 64; HMAC_CTX ctx; ENGINE* e; result = (unsigned char*) malloc(sizeof(char) * result_len); e = (ENGINE*) ENGINE_new(); ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); ENGINE_set_default_digests(e); HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, key, 16, EVP_sha256(), e); HMAC_Update(&ctx, data, 40); HMAC_Final(&ctx, result, &result_len); HMAC_CTX_cleanup(&ctx); ENGINE_finish(e); ENGINE_free(e); ```
The problem with your original suggestion is, as Martin said, that you need to initialise the ENGINE. The problem with your edited code was that you were doing ENGINE\_new, which is getting you a completely new ENGINE of your own, which you then need to provide with cipher methods, digest methods, etc. In fact, for what you want (and what almost everybody wants), just completely ignoring all of the ENGINE stuff is the right choice. Some subsidiary problems: * your strings were hex, but you needed a \x per character to actually get that hex byte at that position in the string, which I suspect was what you wanted. * you were trying to hash 40 bytes from "data", which wasn't that long (actual effect: you'd end up partly hashing your result string) * your expected result was (as far as I can tell) incorrect * you would print out random characters to the terminal, since the HMAC function will produce 32 bytes of random binary data, not printable stuff. The following code compiles, works and passes the test. It's a bit different to the example code you found (since it still uses the individual HMAC\_\* functions - useful if you want to do your hashing bit by bit using HMAC\_Update): ``` #include <openssl/engine.h> #include <openssl/hmac.h> #include <openssl/evp.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { unsigned char* key = (unsigned char*) "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"; unsigned char* data = (unsigned char*) "\x48\x69\x20\x54\x68\x65\x72\x65"; unsigned char* expected = (unsigned char*) "\x49\x2c\xe0\x20\xfe\x25\x34\xa5\x78\x9d\xc3\x84\x88\x06\xc7\x8f\x4f\x67\x11\x39\x7f\x08\xe7\xe7\xa1\x2c\xa5\xa4\x48\x3c\x8a\xa6"; unsigned char* result; unsigned int result_len = 32; int i; HMAC_CTX ctx; result = (unsigned char*) malloc(sizeof(char) * result_len); ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, key, 16, EVP_sha256(), NULL); HMAC_Update(&ctx, data, 8); HMAC_Final(&ctx, result, &result_len); HMAC_CTX_cleanup(&ctx); for (i=0; i!=result_len; i++) { if (expected[i]!=result[i]) { printf("Got %02X instead of %02X at byte %d!\n", result[i], expected[i], i); break; } } if (i==result_len) { printf("Test ok!\n"); } return 0; } ``` Of course, it doesn't answer your original question about how to initialise ENGINEs, but there's really no right answer to that without having more context, which context turns out not to be relevant in your situation...
242,695
<p>I have seen C# code that uses the <code>@</code> to tell the compiler the string has newlines in it and that it should be all in one line. Is there something like that for C/C++?</p> <p>Like if I want to put something like:</p> <p>73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450</p> <p>In a string I don't want to place it all in one line but just put it like that and have the compiler know that that is only one line.</p>
[ { "answer_id": 242702, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>C and C++ didn't have anything like C# verbatim string literals at the time this answer was first written. The closest you could do is:</p>\n\n<pre><code>\"73167176531330624919225119674426574742355349194934\"\n\"96983520312774506326239578318016984801869478851843\" \n\"85861560789112949495459501737958331952853208805511\" \n\"12540698747158523863050715693290963295227443043557\" \n\"66896648950445244523161731856403098711121722383113\" \n\"62229893423380308135336276614282806444486645238749\" \n\"30358907296290491560440772390713810515859307960866\" \n\"70172427121883998797908792274921901699720888093776\" \n\"65727333001053367881220235421809751254540594752243\" \n\"52584907711670556013604839586446706324415722155397\" \n\"53697817977846174064955149290862569321978468622482\" \n\"83972241375657056057490261407972968652414535100474\" \n\"82166370484403199890008895243450658541227588666881\" \n\"16427171479924442928230863465674813919123162824586\" \n\"17866458359124566529476545682848912883142607690042\"\n\"24219022671055626321111109370544217506941658960408\" \n\"07198403850962455444362981230987879927244284909188\" \n\"84580156166097919133875499200524063689912560717606\" \n\"05886116467109405077541002256983155200055935729725\" \n\"71636269561882670428252483600823257530420752963450\"\n</code></pre>\n\n<p>Note however that even in C# it doesn't do what it sounds like you want. If you have:</p>\n\n<pre><code>string foo = @\"x\ny\";\n</code></pre>\n\n<p>in C# then the string will actually contain a linebreak.</p>\n\n<p>In C++11, as per the comment, the <code>R</code> prefix denotes a <em>raw string literal</em>, e.g.</p>\n\n<pre><code>string x = R\"(First line\nsecond line)\";\n</code></pre>\n" }, { "answer_id": 242707, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": false, "text": "<p>In C and C++ you can do this:</p>\n\n<pre><code>const char* str = \"73167176531330624919225119674426574742355349194934\"\n \"96983520312774506326239578318016984801869478851843\";\n</code></pre>\n\n<p>and the compiler will automatically concatenate these into a single string.</p>\n" }, { "answer_id": 242709, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": true, "text": "<p>C and C++ have automatic concatenation of adjacent quoted strings. This means that </p>\n\n<pre><code>const char *a = \"a\" \"b\";\n</code></pre>\n\n<p>and</p>\n\n<pre><code>const char *b = \"ab\";\n</code></pre>\n\n<p>will make <code>a</code> and <code>b</code> point at identical data. You can of course extend this, but it becomes troublesome when the strings contain quotes. Your example seems not to, so it might be practical then.</p>\n" }, { "answer_id": 243020, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>Sure, you can do:</p>\n\n<pre><code>char *x = \"73167176531330624919225119674426574742355349194934\\n\"\n \"96983520312774506326239578318016984801869478851843\\n\"\n &lt;lines removed for brevity&gt;\n \"71636269561882670428252483600823257530420752963450\";\n</code></pre>\n\n<p>and this will emulate the @\"\" behavior exactly (including the line breaks).</p>\n\n<p>If you really want it as one line with no line breaks, don't put the \"\\n\" newline characters in, but that's slightly different to the way the @\"\" stuff works in C#.</p>\n" }, { "answer_id": 243924, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 3, "selected": false, "text": "<p>Another alternative is to end a line with a \\, upon seeing which the preprocessor will delete the following newline:</p>\n\n<pre><code>const char *str = \"Hello,\\\n World!\";\n</code></pre>\n\n<p>It's not as pretty as relying on the automatic concatenation of adjacent string literals as said above; but should be mentioned anyway.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
I have seen C# code that uses the `@` to tell the compiler the string has newlines in it and that it should be all in one line. Is there something like that for C/C++? Like if I want to put something like: 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 In a string I don't want to place it all in one line but just put it like that and have the compiler know that that is only one line.
C and C++ have automatic concatenation of adjacent quoted strings. This means that ``` const char *a = "a" "b"; ``` and ``` const char *b = "ab"; ``` will make `a` and `b` point at identical data. You can of course extend this, but it becomes troublesome when the strings contain quotes. Your example seems not to, so it might be practical then.
242,698
<p>I am trying to write a replacement regular expression to surround all words in quotes except the words AND, OR and NOT. </p> <p>I have tried the following for the match part of the expression:</p> <pre><code>(?i)(?&lt;word&gt;[a-z0-9]+)(?&lt;!and|not|or) </code></pre> <p>and </p> <pre><code>(?i)(?&lt;word&gt;[a-z0-9]+)(?!and|not|or) </code></pre> <p>but neither work. The replacement expression is simple and currently surrounds all words.</p> <pre><code>"${word}" </code></pre> <p>So </p> <blockquote> <p>This and This not That</p> </blockquote> <p>becomes </p> <blockquote> <p>"This" and "This" not "That"</p> </blockquote>
[ { "answer_id": 242716, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "<p>This is a little dirty, but it works:</p>\n\n<pre><code>(?&lt;!\\b(?:and| or|not))\\b(?!(?:and|or|not)\\b)\n</code></pre>\n\n<p>In plain English, this matches any word boundary not preceded by and not followed by \"and\", \"or\", or \"not\". It matches whole words only, e.g. the position after the word \"sand\" would not be a match just because it is preceded by \"and\".</p>\n\n<p>The space in front of the \"or\" in the zero-width look-behind assertion is necessary to make it a fixed length look-behind. Try if that already solves your problem.</p>\n\n<p>EDIT: Applied to the string \"except the words AND, OR and NOT.\" as a global replace with single quotes, this returns:</p>\n\n<pre><code>'except' 'the' 'words' AND, OR and NOT.\n</code></pre>\n" }, { "answer_id": 242730, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Call me crazy, but I'm not a fan of fighting regex; I limit my patterns to simple things I can understand, and often cheat for the rest - for example via a <code>MatchEvaluator</code>:</p>\n\n<pre><code> string[] whitelist = new string[] { \"and\", \"not\", \"or\" };\n string input = \"foo and bar or blop\";\n string result = Regex.Replace(input, @\"([a-z0-9]+)\",\n delegate(Match match) {\n string word = match.Groups[1].Value;\n return Array.IndexOf(whitelist, word) &gt;= 0\n ? word : (\"\\\"\" + word + \"\\\"\");\n });\n</code></pre>\n\n<p>(edited for more terse layout)</p>\n" }, { "answer_id": 243043, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "<p>Based on Tomalaks answer:</p>\n\n<pre><code>(?&lt;!and|or|not)\\b(?!and|or|not)\n</code></pre>\n\n<p>This regex has two problems:</p>\n\n<ol>\n<li><p><code>(?&lt;! )</code> only works for fixed length look-behind</p></li>\n<li><p>The previous regex only looked at end ending/beginning of the surrounding words, not the whole word.</p></li>\n</ol>\n\n<blockquote>\n <p><code>(?&lt;!\\band)(?&lt;!\\bor)(?&lt;!\\bnot)\\b(?!(?:and|or|not)\\b)</code></p>\n</blockquote>\n\n<p>This regex fixes both the above problems. First by splitting the look-behind into three separate ones. Second by adding word-boundaries (<code>\\b</code>) inside the look-arounds.</p>\n" }, { "answer_id": 256742, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 3, "selected": false, "text": "<p>John,</p>\n\n<p>The regex in your question is almost correct. The only problem is that you put the lookahead at the end of the regex instead of at the start. Also, you need to add word boundaries to force the regex to match whole words. Otherwise, it will match \"nd\" in \"and\", \"r\" in \"or\", etc, because \"nd\" and \"r\" are not in your negative lookahead.</p>\n\n<blockquote>\n <p>(?i)\\b(?!and|not|or)(?[a-z0-9]+)\\b</p>\n</blockquote>\n" }, { "answer_id": 748892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>(?!\\bnot\\b|\\band\\b|\\bor\\b|\\b\\\"[^\"]+\\\"\\b)((?&lt;=\\s|\\-|\\(|^)[^\\\"\\s\\()]+(?=\\s|\\*|\\)|$))\n</code></pre>\n\n<p>I use this regex to find all words that are not within double quotes or are the words \"not\" \"and\" or \"or.\"</p>\n" }, { "answer_id": 60678482, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": false, "text": "<p>To match any <em>\"word\" that is a combination of letters, digits or underscores (including any other word chars defined in the <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#word-character-w\" rel=\"nofollow noreferrer\"><code>\\w</code> shorthand character class</a>)</em>, you may use <strong>word boundaries</strong> like in</p>\n\n<pre><code>\\b(?!(?:word1|word2|word3)\\b)\\w+\n</code></pre>\n\n<p>If the <em>\"word\" is a chunk of non-whitespace characters with start/end of string or whitespace on both ends</em> use <strong>whitespace boundaries</strong> like in</p>\n\n<pre><code>(?&lt;!\\S)(?!(?:word1|word2|word3)(?!\\S))\\S+\n</code></pre>\n\n<p>Here, the two expressions will look like</p>\n\n<pre><code>\\b(?!(?:and|not|or)\\b)\\w+\n(?&lt;!\\S)(?!(?:and|not|or)(?!\\S))\\S+\n</code></pre>\n\n<p>See the <a href=\"http://regexstorm.net/tester?p=%5Cb%28%3F!%28%3F%3Aand%7Cnot%7Cor%29%5Cb%29%5Cw%2B&amp;i=This%20and%20This%20not%20That&amp;r=%22%24%26%22\" rel=\"nofollow noreferrer\">regex demo</a> (or, a popular <a href=\"https://regex101.com/r/px5CwO/1\" rel=\"nofollow noreferrer\">regex101 demo</a>, but please note that PCRE <code>\\w</code> meaning is different from the .NET <code>\\w</code> meaning.)</p>\n\n<p><strong>Pattern explanation</strong></p>\n\n<ul>\n<li><code>\\b</code> - <a href=\"https://stackoverflow.com/a/1324784/3832970\">word boundary</a></li>\n<li><code>(?&lt;!\\S)</code> - a negative lookbehind that matches a location that is not immediately preceded with a character other than whitespace, it requires a start of string position or a whitespace char to be right before the current location</li>\n<li><code>(?!(?:word1|word2|word3)\\b)</code> - a negative lookahead that fails the match if, immediately to the right of the current location, there is <code>word1</code>, <code>word2</code> or <code>word3</code> char sequences followed with a word boundary (or, if <code>(?!\\S)</code> whitespace right-hand boundary is used, there must be a whitespace or end of string immediately to the right of the current location)</li>\n<li><code>\\w+</code> - 1+ <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#word-character-w\" rel=\"nofollow noreferrer\">word chars</a></li>\n<li><code>\\S+</code> - 1+ chars other than <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#whitespace-character-s\" rel=\"nofollow noreferrer\">whitespace</a></li>\n</ul>\n\n<p>In C#, and any other programming language, you may build the pattern dynamically, by joining array/list items with a pipe character, <a href=\"https://ideone.com/bVgt2f\" rel=\"nofollow noreferrer\">see the demo</a> below:</p>\n\n<pre><code>var exceptions = new[] { \"and\", \"not\", \"or\" };\nvar result = Regex.Replace(\"This and This not That\", \n $@\"\\b(?!(?:{string.Join(\"|\", exceptions)})\\b)\\w+\",\n \"\\\"$&amp;\\\"\");\nConsole.WriteLine(result); // =&gt; \"This\" and \"This\" not \"That\"\n</code></pre>\n\n<p>If your \"words\" may contain special characters, the whitespace boundaries approach is more suitable, and make sure to escape the \"words\" with, say, <code>exceptions.Select(Regex.Escape)</code>:</p>\n\n<pre><code>var pattern = $@\"(?&lt;!\\S)(?!(?:{string.Join(\"|\", exceptions.Select(Regex.Escape))})(?!\\S))\\S+\";\n</code></pre>\n\n<p><strong>NOTE</strong>: If there are too many words to search for, it might be a better idea to build a <strong>regex trie</strong> out of them.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33/" ]
I am trying to write a replacement regular expression to surround all words in quotes except the words AND, OR and NOT. I have tried the following for the match part of the expression: ``` (?i)(?<word>[a-z0-9]+)(?<!and|not|or) ``` and ``` (?i)(?<word>[a-z0-9]+)(?!and|not|or) ``` but neither work. The replacement expression is simple and currently surrounds all words. ``` "${word}" ``` So > > This and This not That > > > becomes > > "This" and "This" not "That" > > >
This is a little dirty, but it works: ``` (?<!\b(?:and| or|not))\b(?!(?:and|or|not)\b) ``` In plain English, this matches any word boundary not preceded by and not followed by "and", "or", or "not". It matches whole words only, e.g. the position after the word "sand" would not be a match just because it is preceded by "and". The space in front of the "or" in the zero-width look-behind assertion is necessary to make it a fixed length look-behind. Try if that already solves your problem. EDIT: Applied to the string "except the words AND, OR and NOT." as a global replace with single quotes, this returns: ``` 'except' 'the' 'words' AND, OR and NOT. ```
242,701
<p>Which SQL statement is faster?</p> <pre><code>SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM Table1 AS c1, Table2 AS c2, ..... Table49 AS c49, Table50 AS c50 WHERE c1.Date = c2.Date AND c2.Date = c3.Date ..... c49.Date = c50.Date ORDER BY c1.ID DESC OR SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM (Table1 AS c1 INNER JOIN (Table2 AS c2 ........ INNER JOIN (Table49 AS c49 INNER JOIN Table50 AS c50 ON c49.Date = c50.Date) ........ ON c2.FullDate__ = c3.FullDate__) ON c1.FullDate__ = c2.FullDate__) ORDER BY c1.ID DESC"; </code></pre> <p>Basically I need to extract 2 rows from each table to produce a summary periodically. Which statement is faster?</p>
[ { "answer_id": 242706, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 3, "selected": false, "text": "<p>WHERE would usually be better but the best way is <strong>case by case</strong> and throw this into profiler, or simpler yet <strong>display execution plan</strong>. Folk often have very strong opinions on which approach is fastest/best in theory but there is no replacement for actually tuning according to the data you actually deal with as theories applicable change depending on your data load.</p>\n\n<p>If you do not have <strong>real data</strong> in your app yet, try and create some realistic stress data. This will continue to be useful for testing. Then schedule time to tune once the application is live.</p>\n" }, { "answer_id": 242712, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": -1, "selected": false, "text": "<p>Ignore JOINs whenever possible. Performance wise, Join statements are not efficient at all.</p>\n" }, { "answer_id": 242714, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "<p>You will probably find that the SQL optimising engine will generate the same internal query (if the logic is the same), and as a result there will be no difference.</p>\n\n<p>As mentioned by others, run this through a profiler (such as Query analyser) to determine the difference (if there is one).</p>\n" }, { "answer_id": 242720, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 5, "selected": true, "text": "<p>What is faster is not having 50 tables to start with. Joining 50 tables might be ok, but it's a highly counter-intuitive design and probably not the most maintainable solution.</p>\n\n<p>Can you not store your data in rows (or columns) of a single (or fewer) tables rather than 50 tables??!</p>\n" }, { "answer_id": 242732, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 0, "selected": false, "text": "<p>Normally the database optimises both statements, so the difference would not be that big. But you can verify this by compairing the explain plan for both queries.</p>\n\n<p>One thing that could possibly optimize the query with joins (I have not verified this) is to have extra constraints (non join constraints) in the join statement. Although this is not a recommended style since it does not clearly separate the join conditions and other conditions. </p>\n\n<p>For example:</p>\n\n<pre><code>select * \n from A a \n join B b on b.x = a.y \n where b.z = 'ok';\n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>select * \n from A a \n join B b on b.x = a.y and b.z = 'ok';\n</code></pre>\n" }, { "answer_id": 242912, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "<p>If you attach a screen shot of your Query Plans and a Profiler trace I will be happy to let you know which is faster. There really isn't enough information to answer the question otherwise.</p>\n\n<p>My gut feeling is that both have very similar performance in SQL Server and that SQL server optimises both to use the same Query plan, but who knows, its possible the a fifty table join makes the optimiser go a little crazy. </p>\n\n<p>I will in general stick to the JOIN semantics cause I find it easier to read and to maintain. The cross joining is very prone to errors and extremely uncommon. </p>\n" }, { "answer_id": 243128, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks for answers guys.</p>\n\n<p>I do not have access to Query Analyser since I am currently moving that database from\nMS Access, where I was doing a quick prototype, to MySQL. I believe that Query Analyser is\nonly available on SQL Server but I may be wrong, so I can't attach my Profiler trace.</p>\n\n<p>Each table is distinct (i.e. the values in it are unique even though the column names may be the same) and is used separately to generate other objects but I need to occasionally run a summary that collects rows from each table. So, I believe I need 50 tables although I haven't fleshed out the whole scheme of things and will therefore look into it. (p.s. I am new to databases and SQL but not new to programming). I also need to consider the ramifications on memory size if I was to put all info into one table when only small section of it will be used a time.</p>\n\n<p>However, from what I have gathered, the difference should not be that major since the 2 statements will probably be compiled to the same internal query. I asked the question wanting to know if the internals will be different. Will run tests on actual data to find out.</p>\n\n<p>By the way, will the performance on the 2 statements matter if we though into the equation concurrent queries by multiple users?</p>\n" }, { "answer_id": 243205, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 0, "selected": false, "text": "<p>You don't specify the expected volume of your tables, but be aware that if the queries do optimize to different query plans then what is the fastest with 100 rows in your table may not be the same as when you have 100,000 rows or more.</p>\n\n<p>In fact, there is usually little to be gained from obsessively optimizing for queries using tables less than 10,000 records so long as you have reasonably sensibly designed indexes and queries. However, somewhere around 100,000 records performance of badly optimized queries will start to degrade, generally catastrophically. The exact figure depends up the row size and the amount of memory you have in the server but it's not unusual to see performance degrade by an order of magnitude or more for a doubling of table size. </p>\n\n<p>Generally, then the best strategy not to spend time with minor queries on smaller tables, the effort can usually be spent more profitably elsewhere. However aggressively optimize any queries which are running against you main tables if these are expected to grow over 10,000 rows. Usually, this will mean using a QA instance and loading with 10 times the expected volume to check the actual behavior.</p>\n" }, { "answer_id": 245138, "author": "user32012", "author_id": 32012, "author_profile": "https://Stackoverflow.com/users/32012", "pm_score": 1, "selected": false, "text": "<p>All the talk about having fewer tables got me thinking (Thanks MarkR). I have been \ngoing through the MySQL documentation for the past couple of hours and realized \nthat a better solution would be to create a new summary table that would hold the \ninitial results. Thereafter, I would create a trigger that would update the new table\nwhenever an insert happens on one of the tables that is always touched.</p>\n\n<p>Another idea I thought of is creating a view of the query. However it seems that MySQL\nruns the underlying query to a view everytime it is called. Am I right? Is there a way\nto make MySQL store the resultant table of a pre-executed view and then use a trigger\nto tell the view when to update the table? Is there any RDBMS that does this?</p>\n" }, { "answer_id": 245154, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>Optimizing the join order takes exponential time. Each database engine simply picks a small number of possible join orders and estimates the best one out of those.</p>\n\n<p>It seems like you will always want to <code>join ... on c*1*.Date = c*n*.Date</code> for all <code>n</code>.</p>\n\n<p>You will also want to get rid of the extremely odd database schema you have.</p>\n" }, { "answer_id": 245218, "author": "Jason Kester", "author_id": 27214, "author_profile": "https://Stackoverflow.com/users/27214", "pm_score": 0, "selected": false, "text": "<p>What happened when you tried?</p>\n\n<p>I mean seriously, Query Analyzer has a little timer for a reason. Different query structures sometimes give wildly different execution times, often with no intuitive reason behind it. </p>\n\n<p>Write both queries. Test them. Then come back and answer your own question.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32012/" ]
Which SQL statement is faster? ``` SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM Table1 AS c1, Table2 AS c2, ..... Table49 AS c49, Table50 AS c50 WHERE c1.Date = c2.Date AND c2.Date = c3.Date ..... c49.Date = c50.Date ORDER BY c1.ID DESC OR SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM (Table1 AS c1 INNER JOIN (Table2 AS c2 ........ INNER JOIN (Table49 AS c49 INNER JOIN Table50 AS c50 ON c49.Date = c50.Date) ........ ON c2.FullDate__ = c3.FullDate__) ON c1.FullDate__ = c2.FullDate__) ORDER BY c1.ID DESC"; ``` Basically I need to extract 2 rows from each table to produce a summary periodically. Which statement is faster?
What is faster is not having 50 tables to start with. Joining 50 tables might be ok, but it's a highly counter-intuitive design and probably not the most maintainable solution. Can you not store your data in rows (or columns) of a single (or fewer) tables rather than 50 tables??!
242,711
<p>I think this must be simple but I can't get it right...</p> <p>I have an MxM triangular matrix, the coefficients of which are stored in a vector, row by row. For example:</p> <pre><code>M = [ m00 m01 m02 m03 ] [ m11 m12 m13 ] [ m22 m23 ] [ m33 ] </code></pre> <p>is stored as </p> <pre><code>coef[ m00 m01 m02 m03 m11 m12 m13 m22 m23 m33 ] </code></pre> <p>Now I'm looking for a non-recursive algorithm that gives me for matrix size <code>M</code> and coefficient array index <code>i</code></p> <pre><code>unsigned int row_index(i,M) </code></pre> <p>and </p> <pre><code>unsigned int column_index(i,M) </code></pre> <p>of the matrix element that it refers to. So, <code>row_index(9,4) == 3</code>, <code>column_index(7,4) == 2</code> etc. if the index counting is zero-based.</p> <p>EDIT: Several replies using an iteration have been given. Does anyone know of algebraic expressions?</p>
[ { "answer_id": 242919, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 0, "selected": false, "text": "<p>Took me some time to understand what you needed! :)</p>\n\n<pre><code>unsigned int row_index(int i, int m)\n{\n int iCurrentRow = 0;\n int iTotalItems = 0;\n for(int j = m; j &gt; 0; j--)\n {\n iTotalItems += j;\n\n if( (i+1) &lt;= iTotalItems)\n return iCurrentRow;\n\n iCurrentRow ++;\n }\n\n return -1; // Not checking if \"i\" can be in a MxM matrix.\n}\n</code></pre>\n\n<p>Sorry forgot the other function.....</p>\n\n<pre><code>unsigned int column_index(int i, int m)\n{\n int iTotalItems = 0;\n for(int j = m; j &gt; 0; j--)\n {\n iTotalItems += j;\n\n if( (i+1) &lt;= iTotalItems)\n return m - (iTotalItems - i);\n }\n\n return -1; // Not checking if \"i\" can be in a MxM matrix.\n}\n</code></pre>\n" }, { "answer_id": 242921, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 2, "selected": false, "text": "<p>It has to be that </p>\n\n<pre><code>i == col + row*(M-1)-row*(row-1)/2\n</code></pre>\n\n<p>So one way to find col and row is to iterate over possible values of row:</p>\n\n<pre><code>for(row = 0; row &lt; M; row++){\n col = i - row*(M-1)-row*(row-1)/2\n if (row &lt;= col &lt; M) return (row,column);\n}\n</code></pre>\n\n<p>This is at least non-recursive, I don't know if you can do this without iteration.</p>\n\n<p>As can be seen from this and other answers, you pretty much have to calculate row in order to calculate column, so it could be smart to do both in one function.</p>\n" }, { "answer_id": 242924, "author": "Matt Lewis", "author_id": 28987, "author_profile": "https://Stackoverflow.com/users/28987", "pm_score": 2, "selected": false, "text": "<p>There may be a clever one liner for these, but (minus any error checking):</p>\n\n<pre><code>unsigned int row_index( unsigned int i, unsigned int M ){\n unsigned int row = 0;\n unsigned int delta = M - 1;\n for( unsigned int x = delta; x &lt; i; x += delta-- ){\n row++;\n }\n return row;\n}\n\nunsigned int column_index( unsigned int i, unsigned int M ){\n unsigned int row = 0;\n unsigned int delta = M - 1;\n unsigned int x;\n for( x = delta; x &lt; i; x += delta-- ){\n row++;\n }\n return M + i - x - 1;\n}\n</code></pre>\n" }, { "answer_id": 243342, "author": "Matt Lewis", "author_id": 28987, "author_profile": "https://Stackoverflow.com/users/28987", "pm_score": 4, "selected": true, "text": "<p>Here's an algebraic (mostly) solution:</p>\n\n<pre><code>unsigned int row_index( unsigned int i, unsigned int M ){\n double m = M;\n double row = (-2*m - 1 + sqrt( (4*m*(m+1) - 8*(double)i - 7) )) / -2;\n if( row == (double)(int) row ) row -= 1;\n return (unsigned int) row;\n}\n\n\nunsigned int column_index( unsigned int i, unsigned int M ){\n unsigned int row = row_index( i, M);\n return i - M * row + row*(row+1) / 2;\n}\n</code></pre>\n\n<p>EDIT: fixed row_index()</p>\n" }, { "answer_id": 244550, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 4, "selected": false, "text": "<p>One-liners at the end of this reply, explanation follows :-)</p>\n\n<p>The coefficient array has: M elements for the first row (row 0, in your indexing), (M-1) for the second (row 1), and so on, for a total of M+(M-1)+&hellip;+1=M(M+1)/2 elements.</p>\n\n<p>It's slightly easier to work from the end, because the coefficient array <em>always</em> has 1 element for the last row (row M-1), 2 elements for the second-last row (row M-2), 3 elements for row M-3, and so on. The last K rows take up the last K(K+1)/2 positions of the coefficient array.</p>\n\n<p>Now suppose you are given an index i in the coefficient array. There are M(M+1)/2-1-i elements at positions greater than i. Call this number i'; <strong>you want to find the largest k such that k(k+1)/2 &le; i'</strong>. The form of this problem is the very source of your misery -- as far as I can see, you cannot avoid taking square roots :-)</p>\n\n<p>Well let's do it anyway: k(k+1) &le; 2i' means (k+1/2)<sup>2</sup> - 1/4 &le; 2i', or equivalently k &le; (sqrt(8i'+1)-1)/2. Let me call the largest such k as K, then there are K rows that are later (out of a total of M rows), so the row_index(i,M) is M-1-K. As for the column index, K(K+1)/2 elements out of the i' are in later rows, so there are j'=i'-K(K+1)/2 later elements in this row (which has K+1 elements in total), so the column index is K-j'. [Or equivalently, this row starts at (K+1)(K+2)/2 from the end, so we just need to subtract the starting position of this row from i: i-[M(M+1)/2-(K+1)(K+2)/2]. It is heartening that both expressions give the same answer!]</p>\n\n<p>(Pseudo-)Code [using ii instead of i' as some languages don't allow variables with names like i' ;-)]:</p>\n\n<pre><code>row_index(i, M):\n ii = M(M+1)/2-1-i\n K = floor((sqrt(8ii+1)-1)/2)\n return M-1-K\n\ncolumn_index(i, M):\n ii = M(M+1)/2-1-i\n K = floor((sqrt(8ii+1)-1)/2)\n return i - M(M+1)/2 + (K+1)(K+2)/2\n</code></pre>\n\n<p>Of course you can turn them into one-liners by substituting the expressions for ii and K. You may have to be careful about precision errors, but there are ways of finding the integer square root which do not require floating-point computation. Also, to quote Knuth: \"Beware of bugs in the above code; I have only proved it correct, not tried it.\"</p>\n\n<p>If I may venture to make a further remark: simply keeping all the values in an M&times;M array will take at most twice the memory, and depending on your problem, the factor of 2 might be insignificant compared to algorithmic improvements, and might be worth trading the possibly expensive computation of the square root for the simpler expressions you'll have.</p>\n\n<p>[Edit: BTW, you can prove that floor((sqrt(8ii+1)-1)/2) = (isqrt(8ii+1)-1)/2 where isqrt(x)=floor(sqrt(x)) is integer square root, and the division is integer division (truncation; the default in C/C++/Java etc.) -- so if you're worried about precision issues you only need to worry about implementing a correct integer square root.]</p>\n" }, { "answer_id": 3148414, "author": "JuanPi", "author_id": 487993, "author_profile": "https://Stackoverflow.com/users/487993", "pm_score": 1, "selected": false, "text": "<p>I thought a little bit and I got the following result. Note that you get both row and columns on one shot.</p>\n\n<p>Assumptions: Rows start a 0. Columns start at 0. Index start at 0</p>\n\n<p>Notation</p>\n\n<p>N = matrix size (was M in the original problem)</p>\n\n<p>m = Index of the element</p>\n\n<p>The psuedo code is</p>\n\n<pre><code>function ind2subTriu(m,N)\n{\n d = 0;\n i = -1;\n while d &lt; m\n {\n i = i + 1\n d = i*(N-1) - i*(i-1)/2\n }\n i0 = i-1;\n j0 = m - i0*(N-1) + i0*(i0-1)/2 + i0 + 1;\n return i0,j0\n}\n</code></pre>\n\n<p>And some octave/matlab code </p>\n\n<pre><code>function [i0 j0]= ind2subTriu(m,N)\n I = 0:N-2;\n d = I*(N-1)-I.*(I-1)/2;\n i0 = I(find (d &lt; m,1,'last'));\n j0 = m - d(i0+1) + i0 + 1;\n</code></pre>\n\n<p>What do you think?</p>\n\n<p>As of December 2011 really good code to do this was added to GNU/Octave. Potentially they will extend sub2ind and ind2sub. The code can be found for the moment as private functions <a href=\"http://octave.svn.sf.net/viewvc/octave/trunk/octave-forge/main/mechanics/inst/core/private/sub2ind_tril.m?view=log\" rel=\"nofollow noreferrer\">ind2sub_tril</a> and <a href=\"http://octave.svn.sf.net/viewvc/octave/trunk/octave-forge/main/mechanics/inst/core/private/ind2sub_tril.m?view=log\" rel=\"nofollow noreferrer\">sub2ind_tril</a></p>\n" }, { "answer_id": 28116498, "author": "Michael Bauer", "author_id": 2019794, "author_profile": "https://Stackoverflow.com/users/2019794", "pm_score": 2, "selected": false, "text": "<p>The explanation of ShreevatsaR is excellent and helped me solve my problem. However, the explanation and code provided for the column index give a slightly different answer than what the question asks for. </p>\n\n<p>To reiterate, there are j' = i' - K(K+1)/2 elements in the row after i. But the row, like every other row, has M elements. Hence the (zero-based) column index is y = M - 1 - j'.</p>\n\n<p>The corresponding pseudo code is:</p>\n\n<pre><code>column_index(i, M):\n ii = M(M+1)/2-1-i\n K = floor((sqrt(8ii+1)-1)/2)\n jj = ii - K(K+1)/2\n return M-1-jj\n</code></pre>\n\n<p>The answer given by ShreevatsaR, K - j', is the column index when starting to count (with zero) from the diagonal of the matrix. Hence, his calculation gives column_index(7,4) = 0 and not, as specified in the question, column_index(7,4) = 2.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
I think this must be simple but I can't get it right... I have an MxM triangular matrix, the coefficients of which are stored in a vector, row by row. For example: ``` M = [ m00 m01 m02 m03 ] [ m11 m12 m13 ] [ m22 m23 ] [ m33 ] ``` is stored as ``` coef[ m00 m01 m02 m03 m11 m12 m13 m22 m23 m33 ] ``` Now I'm looking for a non-recursive algorithm that gives me for matrix size `M` and coefficient array index `i` ``` unsigned int row_index(i,M) ``` and ``` unsigned int column_index(i,M) ``` of the matrix element that it refers to. So, `row_index(9,4) == 3`, `column_index(7,4) == 2` etc. if the index counting is zero-based. EDIT: Several replies using an iteration have been given. Does anyone know of algebraic expressions?
Here's an algebraic (mostly) solution: ``` unsigned int row_index( unsigned int i, unsigned int M ){ double m = M; double row = (-2*m - 1 + sqrt( (4*m*(m+1) - 8*(double)i - 7) )) / -2; if( row == (double)(int) row ) row -= 1; return (unsigned int) row; } unsigned int column_index( unsigned int i, unsigned int M ){ unsigned int row = row_index( i, M); return i - M * row + row*(row+1) / 2; } ``` EDIT: fixed row\_index()
242,718
<p>How do you split a string?</p> <p>Lets say i have a string "dog, cat, mouse,bird"</p> <p>My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.</p> <p>but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?</p> <p>im using asp c#</p>
[ { "answer_id": 242724, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 4, "selected": true, "text": "<pre><code> string[] tokens = text.Split(',');\n\n for (int i = 0; i &lt; tokens.Length; i++)\n {\n yourListBox.Add(new ListItem(token[i], token[i]));\n }\n</code></pre>\n" }, { "answer_id": 242726, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "<p>It gives you a string array by strVar.Split</p>\n\n<pre><code>\"dog, cat, mouse,bird\".Split(new[] { ',' });\n</code></pre>\n" }, { "answer_id": 242729, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Have you tried <a href=\"http://msdn.microsoft.com/en-us/library/system.string.split.aspx\" rel=\"nofollow noreferrer\">String.Split</a>? You may need some post-processing to remove whitespace if you want \"a, b, c\" to end up as {\"a\", \"b\", \"c\"} but \"a b, c\" to end up as {\"a b\", \"c\"}.</p>\n\n<p>For instance:</p>\n\n<pre><code>private readonly char[] Delimiters = new char[]{','};\n\nprivate static string[] SplitAndTrim(string input)\n{\n string[] tokens = input.Split(Delimiters,\n StringSplitOptions.RemoveEmptyEntries);\n\n // Remove leading and trailing whitespace\n for (int i=0; i &lt; tokens.Length; i++)\n {\n tokens[i] = tokens[i].Trim();\n }\n return tokens;\n}\n</code></pre>\n" }, { "answer_id": 242759, "author": "Gordon Mackie JoanMiro", "author_id": 15778, "author_profile": "https://Stackoverflow.com/users/15778", "pm_score": 2, "selected": false, "text": "<p>Or simply:</p>\n\n<pre><code>targetListBox.Items.AddRange(inputString.Split(','));\n</code></pre>\n\n<p>Or this to ensure the strings are trimmed:</p>\n\n<pre><code>targetListBox.Items.AddRange((from each in inputString.Split(',')\n select each.Trim()).ToArray&lt;string&gt;());\n</code></pre>\n\n<p>Oops! As comments point out, missed that it was ASP.NET, so can't initialise from string array - need to do it like this:</p>\n\n<pre><code>var items = (from each in inputString.Split(',')\n select each.Trim()).ToArray&lt;string&gt;();\n\nforeach (var currentItem in items)\n{\n targetListBox.Items.Add(new ListItem(currentItem));\n}\n</code></pre>\n" }, { "answer_id": 243008, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 2, "selected": false, "text": "<p>Needless Linq version;</p>\n\n<pre><code>from s in str.Split(',')\nwhere !String.IsNullOrEmpty(s.Trim())\nselect s.Trim();\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23491/" ]
How do you split a string? Lets say i have a string "dog, cat, mouse,bird" My actual goal is to insert each of those animals into a listBox, so they would become items in a list box. but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this? im using asp c#
``` string[] tokens = text.Split(','); for (int i = 0; i < tokens.Length; i++) { yourListBox.Add(new ListItem(token[i], token[i])); } ```
242,745
<p>When I add the textBox.TextChanged to watch list I get a message saying <pre>The event 'System.Windows.Forms.Control.TextChanged' can only appear on the left hand side of += or -=</pre></p> <p>Is there any way to check what event's are called on text change?</p>
[ { "answer_id": 242757, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>We use Subversion for document management at work. It works great.</p>\n\n<ul>\n<li>Don't worry about the disk space. Revisions are stored compressed anyway.</li>\n<li>Checking out a project with documentation doesn't take much more time than one without. Unless your documents are absolutely huge, this shouldn't be a problem.</li>\n<li>Training time is a consideration. Fortunately, TortoiseSVN makes this easy.</li>\n</ul>\n\n<p>To manage Word documents so they can only be edited by one person at a time, use the <a href=\"http://svnbook.red-bean.com/en/1.2/svn.advanced.locking.html\" rel=\"nofollow noreferrer\"><code>svn:needs-lock</code></a> property. This will make the files appear as read-only on a normal checkout, and read-write when a developer has locked them for editing. After commit, the file will be unlocked and read-only again.</p>\n\n<p>An additional benefit of TortoiseSVN is that it can do diffs of Word documents and present the differences in Word itself. This alone is a killer feature for me.</p>\n" }, { "answer_id": 242798, "author": "kauppi", "author_id": 964, "author_profile": "https://Stackoverflow.com/users/964", "pm_score": 0, "selected": false, "text": "<p>I think this issue is a bit broader than just the \"how to use SVN\" aspect.</p>\n\n<p>First of all, SVN might be the proper tool for technically oriented people but could be very cumbersome to artistic or management guys. I believe that all project related documentation should be kept in one place that is accessible by all participants.</p>\n\n<p>Moreover, version control is not a substitute to a proper process and good communications. You need to find a way to communicate the changes and new requirements etc to all involved parties.</p>\n\n<p>I think you might need a document management system. <a href=\"http://www.alfresco.com/\" rel=\"nofollow noreferrer\" title=\"Alfresco\">Alfresco</a> or similar might be a good option.</p>\n" }, { "answer_id": 242801, "author": "Ryan McCue", "author_id": 2575, "author_profile": "https://Stackoverflow.com/users/2575", "pm_score": -1, "selected": false, "text": "<p>Subversion <strong>only</strong> stores the difference between revisions, which makes it very efficient. I'm not aware if this is true for binary files (such as Word or Excel files), however I believe it may be. If not, it may be to your advantage to use CSV files if possible instead of .XLS files and RTF files if possible instead of .DOC files.</p>\n" }, { "answer_id": 245247, "author": "Neil Albrock", "author_id": 32124, "author_profile": "https://Stackoverflow.com/users/32124", "pm_score": 0, "selected": false, "text": "<p>Greg and kauppi both raise important issues here. Subversion is a fantastic tool but it's really not for everyone. I have been trying to get my development team to fully adopt it for over a year but still find myself talking them through the basics all too regularly. </p>\n\n<p>If you've taken the time to understand and appreciate version control systems, they are one the tools you will never want to do without. For some people though, the process and dicipline of using them will seem like a hassle.</p>\n\n<p>It comes back to communication and good teamworking. Sometimes these tools can help in that regard but alas, they can't solve all our problems.</p>\n\n<p>Greg's suggestion of using svn:needs-lock as a way to control the editing of binary objects is a good one if your do end up going down this road.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1534/" ]
When I add the textBox.TextChanged to watch list I get a message saying ``` The event 'System.Windows.Forms.Control.TextChanged' can only appear on the left hand side of += or -= ``` Is there any way to check what event's are called on text change?
We use Subversion for document management at work. It works great. * Don't worry about the disk space. Revisions are stored compressed anyway. * Checking out a project with documentation doesn't take much more time than one without. Unless your documents are absolutely huge, this shouldn't be a problem. * Training time is a consideration. Fortunately, TortoiseSVN makes this easy. To manage Word documents so they can only be edited by one person at a time, use the [`svn:needs-lock`](http://svnbook.red-bean.com/en/1.2/svn.advanced.locking.html) property. This will make the files appear as read-only on a normal checkout, and read-write when a developer has locked them for editing. After commit, the file will be unlocked and read-only again. An additional benefit of TortoiseSVN is that it can do diffs of Word documents and present the differences in Word itself. This alone is a killer feature for me.
242,766
<p>Recently I've been seeing a lot of this:</p> <pre><code>&lt;a href='http://widget-site-example.com/example.html'&gt; &lt;img src='http://widget-site-example.com/ross.jpg' alt='Ross&amp;#39;s Widget' /&gt; &lt;/a&gt; </code></pre> <p>Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.</p>
[ { "answer_id": 242775, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": true, "text": "<p>It's certainly valid to use single quotes (<a href=\"http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2\" rel=\"noreferrer\">HTML 4.01, section 3.2.2</a>). I haven't noticed such a trend, but perhaps there's some framework that powers web sites you've visited that happens to quote using single quotes.</p>\n" }, { "answer_id": 242784, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 6, "selected": false, "text": "<p>I find using single quotes is handy when dynamically generating HTML using a programming language that uses double quote string literals.</p>\n\n<p>e.g.</p>\n\n<pre><code>String.Format(\"&lt;a href='{0}'&gt;{1}&lt;/a&gt;\", Url, Desc)\n</code></pre>\n" }, { "answer_id": 242790, "author": "Dean Rather", "author_id": 14966, "author_profile": "https://Stackoverflow.com/users/14966", "pm_score": 4, "selected": false, "text": "<p>When using PHP to generate HTML it can be easier to do something like:</p>\n\n<pre><code>$html = \"&lt;img src='$url' /&gt;\";\n</code></pre>\n\n<p>than concatenating a string with a variable with a string, as PHP parses variables in double-quoted strings.</p>\n" }, { "answer_id": 242800, "author": "Joshi Spawnbrood", "author_id": 15392, "author_profile": "https://Stackoverflow.com/users/15392", "pm_score": 0, "selected": false, "text": "<p>What's against single quotes? </p>\n\n<p>You can have single/double quotes all over your html code without any problem, as long as you keep the same quoting style inside a current tags ( many browser won't complain even about this, and validation just want that if you start with a quote, end with the same, inside the same propriety )</p>\n\n<p>Free support to random quoting styles!!! (yay ;D )</p>\n" }, { "answer_id": 242802, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It's easier when you want to embed double quotes.</p>\n" }, { "answer_id": 242862, "author": "Danko Durbić", "author_id": 19241, "author_profile": "https://Stackoverflow.com/users/19241", "pm_score": 2, "selected": false, "text": "<p>In ASP.NET, it's easier to use single quotes if you're using <a href=\"http://msdn.microsoft.com/en-us/library/ms178366.aspx\" rel=\"nofollow noreferrer\">data-binding expressions</a> in attributes:</p>\n\n<pre><code>&lt;asp:TextBox runat=\"server\" Text='&lt;%# Bind(\"Name\") %&gt;' /&gt;\n</code></pre>\n" }, { "answer_id": 243246, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 2, "selected": false, "text": "<p>Someone may use it in PHP to avoid escaping \" if they're using double quoted string to parse variables within it, or to avoid using string concatenation operator.</p>\n\n<p>Example:</p>\n\n<pre><code>echo \"&lt;input type='text' value='$data'/&gt;\";\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>echo \"&lt;input type=\\\"text\\\" value=\\\"$data\\\" /&gt;\";\n</code></pre>\n\n<p>or </p>\n\n<pre><code>echo '&lt;input type=\"text\" value=\"' . $data . '\" /&gt;';\n</code></pre>\n\n<p>Nowadays I always stick to using double quotes for HTML and single quotes for Javascript.</p>\n" }, { "answer_id": 444197, "author": "Ms2ger", "author_id": 33466, "author_profile": "https://Stackoverflow.com/users/33466", "pm_score": 2, "selected": false, "text": "<p>Single quotes are perfectly legal in (X)HTML. Using a backslash to escape them, on the other hand, isn't. <code>&lt;img src='<a href=\"http://widget-site-example.com/ross.jpg\" rel=\"nofollow noreferrer\">http://widget-site-example.com/ross.jpg</a>' alt='Ross\\'s Widget' /></code> is an image with the alt text \"Ross\\\", and empty <code>s</code> and <code>Widget</code>/<code>Widget'</code> attributes. The correct way of escaping an apostrophe in HTML is <code>&amp;#39;</code>.</p>\n" }, { "answer_id": 3346486, "author": "matv", "author_id": 403718, "author_profile": "https://Stackoverflow.com/users/403718", "pm_score": 2, "selected": false, "text": "<p>In PHP, echo takes multiples parameters. So, if one would like to omit the concatenation operator, they could done something like and still use double quotes :</p>\n\n<pre><code>echo '&lt;input type=\"text\" value=\"', $data, '\" /&gt;';\n</code></pre>\n" }, { "answer_id": 3900374, "author": "Anthony", "author_id": 279090, "author_profile": "https://Stackoverflow.com/users/279090", "pm_score": 1, "selected": false, "text": "<p>Single quotes generate a cleaner page with less clutter. You shouldn't be escaping them in HTML strings and it's your choice which to use... my preference is single quotes normally and if I need to include a single quote in the string (e.g. as delimiters for a string inside the string), I use double quotes for one &amp; single for the other.</p>\n" }, { "answer_id": 14659308, "author": "leftclickben", "author_id": 1007512, "author_profile": "https://Stackoverflow.com/users/1007512", "pm_score": 0, "selected": false, "text": "<p>I know this is an old thread, but still very much relevant. </p>\n\n<p>If you want control over quotes in your generated HTML, you can use the <a href=\"http://php.net/manual/en/function.sprintf.php\" rel=\"nofollow\">sprintf()</a> function in PHP (and similar calls available in many other languages):</p>\n\n<pre><code>$html = sprintf('&lt;a href=\"%s\"&gt;%s&lt;/a&gt;', $url, $text);\n</code></pre>\n\n<p>Using sprintf() allows the format string to be easily modifiable by retrieving it from a database or configuration file, or via translation mechanisms. </p>\n\n<p>It is very readable, and allows either double or single quotes in the generated HTML, with very little change and never any escaping:</p>\n\n<pre><code>$html = sprintf(\"&lt;a href='%s'&gt;%s&lt;/a&gt;\", $url, $text);\n</code></pre>\n" }, { "answer_id": 17930297, "author": "Snuggs", "author_id": 173208, "author_profile": "https://Stackoverflow.com/users/173208", "pm_score": 0, "selected": false, "text": "<p>Why not save pressing the <kbd>SHIFT</kbd> Key. One less keystroke for the same milage. </p>\n" }, { "answer_id": 26431618, "author": "Code Whisperer", "author_id": 2299820, "author_profile": "https://Stackoverflow.com/users/2299820", "pm_score": -1, "selected": false, "text": "<h1>You should avoid quotes altogether.</h1>\n<p>In your example only one quoted attribute actually needed quotes.</p>\n<pre><code>&lt;!-- best form --&gt;\n&lt;a href=http://widget-site-example.com/example.html&gt;\n &lt;img src=http://widget-site-example.com/ross.jpg alt='Ross&amp;#39;s Widget' /&gt;\n&lt;/a&gt;\n</code></pre>\n<p>If you do use quotes, there is no hard and fast rule, but I've seen most commonly single quotes, with double quotes on the inside if necessary.</p>\n<p>Using double quotes won't pass some validators.</p>\n" }, { "answer_id": 33440486, "author": "Eric", "author_id": 473290, "author_profile": "https://Stackoverflow.com/users/473290", "pm_score": 1, "selected": false, "text": "<p>If you want to the <a href=\"/questions/tagged/html\" class=\"post-tag\" title=\"show questions tagged &#39;html&#39;\" rel=\"tag\">html</a> to be valid <a href=\"/questions/tagged/html4\" class=\"post-tag\" title=\"show questions tagged &#39;html4&#39;\" rel=\"tag\">html4</a> or <a href=\"/questions/tagged/xhtml\" class=\"post-tag\" title=\"show questions tagged &#39;xhtml&#39;\" rel=\"tag\">xhtml</a> then both <a href=\"/questions/tagged/single-quotes\" class=\"post-tag\" title=\"show questions tagged &#39;single-quotes&#39;\" rel=\"tag\">single-quotes</a> or <a href=\"/questions/tagged/double-quotes\" class=\"post-tag\" title=\"show questions tagged &#39;double-quotes&#39;\" rel=\"tag\">double-quotes</a> will work for attributes. HTML4 can be validated here: <a href=\"https://validator.w3.org/\" rel=\"nofollow\">https://validator.w3.org/</a></p>\n\n<p>If you are <a href=\"http://html5readiness.com/\" rel=\"nofollow\">supporting only modern browsers</a> (<a href=\"/questions/tagged/ie10\" class=\"post-tag\" title=\"show questions tagged &#39;ie10&#39;\" rel=\"tag\">ie10</a> and higher) then you can use the <a href=\"/questions/tagged/html5\" class=\"post-tag\" title=\"show questions tagged &#39;html5&#39;\" rel=\"tag\">html5</a> syntax which allows single quotes, double quotes, and no quotes (as long as there are no special characters in the attributes' value). HTML5 can be validated here: <a href=\"https://validator.w3.org/nu\" rel=\"nofollow\">https://validator.w3.org/nu</a></p>\n" }, { "answer_id": 40959586, "author": "bryc", "author_id": 815680, "author_profile": "https://Stackoverflow.com/users/815680", "pm_score": 2, "selected": false, "text": "<p>Another case where you may want to use single quotes: Storing JSON data in data attributes:</p>\n\n<pre><code>&lt;tr data-info='{\"test\":true}'&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>JSON object keys must be in double quotes, so the attribute itself cannot.</p>\n" }, { "answer_id": 66673441, "author": "dkellner", "author_id": 1892607, "author_profile": "https://Stackoverflow.com/users/1892607", "pm_score": 0, "selected": false, "text": "<h2>Let's settle this argument for good</h2>\n<hr>\n<ol>\n<li><strong>Double quotes</strong> are OK</li>\n<li><strong>Single quotes</strong> are OK</li>\n<li><strong>No quotes</strong> are OK, as long as you don't have one of these characters:\n<ul>\n<li>space (obviously)</li>\n<li>&quot;&lt;&quot; or &quot;&gt;&quot; (makes sense)</li>\n<li>equal sign (not sure why but ok)</li>\n<li>any kind of quote: double, single, backtick (again, makes sense)</li>\n</ul>\n</li>\n</ol>\n<p>Funny how some people, even today, stick to the &quot;double quote only&quot; standard which was never really a standard but a convention. Also, if your language has apostrophes as a natural element (English, anyone?) it's more convenient, but in my opinion, increasing the complexity of PHP string compositions is way too high a price to pay for this.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
Recently I've been seeing a lot of this: ``` <a href='http://widget-site-example.com/example.html'> <img src='http://widget-site-example.com/ross.jpg' alt='Ross&#39;s Widget' /> </a> ``` Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.
It's certainly valid to use single quotes ([HTML 4.01, section 3.2.2](http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2)). I haven't noticed such a trend, but perhaps there's some framework that powers web sites you've visited that happens to quote using single quotes.
242,771
<p>How can I create an Oracle stored procedure which accepts a variable number of parameter values used to feed a IN clause?</p> <p>This is what I am trying to achieve. I do not know how to declare in PLSQL for passing a variable list of primary keys of the rows I want to update.</p> <pre><code>FUNCTION EXECUTE_UPDATE ( &lt;parameter_list&gt; value IN int) RETURN int IS BEGIN [...other statements...] update table1 set col1 = col1 - value where id in (&lt;parameter_list&gt;) RETURN SQL%ROWCOUNT ; END; </code></pre> <p>Also, I would like to call this procedure from C#, so it must be compatible with .NET capabilities. </p> <p>Thanks, Robert</p>
[ { "answer_id": 242776, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": -1, "selected": false, "text": "<p>I've not done it for Oracle, but with SQL Server you can use a function to convert a CSV string into a table, which can then be used in an IN clause. It should be straight-forward to re-write this for Oracle (I think!)</p>\n\n<pre><code>CREATE Function dbo.CsvToInt ( @Array varchar(1000)) \nreturns @IntTable table \n (IntValue nvarchar(100))\nAS\nbegin\n\n declare @separator char(1)\n set @separator = ','\n\n declare @separator_position int \n declare @array_value varchar(1000) \n\n set @array = @array + ','\n\n while patindex('%,%' , @array) &lt;&gt; 0 \n begin\n\n select @separator_position = patindex('%,%' , @array)\n select @array_value = left(@array, @separator_position - 1)\n\n Insert @IntTable\n Values (Cast(@array_value as nvarchar))\n\n select @array = stuff(@array, 1, @separator_position, '')\n end\n\n return\nend\n</code></pre>\n\n<p>Then you can pass in a CSV string (e.g. '0001,0002,0003') and do something like </p>\n\n<pre><code>UPDATE table1 SET \n col1 = col1 - value \nWHERE id in (SELECT * FROM csvToInt(@myParam)) \n</code></pre>\n" }, { "answer_id": 242960, "author": "Gazmo", "author_id": 31175, "author_profile": "https://Stackoverflow.com/users/31175", "pm_score": -1, "selected": false, "text": "<p>There is an article on the AskTom web site that shows how to create a function to parse the CSV string and use this in your statement in a similar way to the SQL Server example given.</p>\n\n<p>See <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:139812348065\" rel=\"nofollow noreferrer\" title=\"ASkTom\">Asktom</a></p>\n" }, { "answer_id": 242987, "author": "rics", "author_id": 21047, "author_profile": "https://Stackoverflow.com/users/21047", "pm_score": 1, "selected": false, "text": "<p>I think there is no direct way to create procedures with variable number of parameters.\nHowever there are some, at least partial solutions to the problem, described <a href=\"http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_packages.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<ol>\n<li>If there are some typical call types procedure overloading may help.</li>\n<li>If there is an upper limit in the number of parameters (and their type is also known in advance), default values of parameters may help.</li>\n<li>The best option is maybe the usage of cursor variables what are pointers to database cursors.</li>\n</ol>\n\n<p>Unfortunately I have no experience with .NET environments.</p>\n" }, { "answer_id": 243011, "author": "Ashley Mercer", "author_id": 13065, "author_profile": "https://Stackoverflow.com/users/13065", "pm_score": 6, "selected": true, "text": "<p>Using CSV is probably the simplest way, assuming you can be 100% certain that your elements won't themselves contain strings.</p>\n\n<p>An alternative, and probably more robust, way of doing this is to create a custom type as a table of strings. Supposing your strings were never longer than 100 characters, then you could have:</p>\n\n<pre><code>CREATE TYPE string_table AS TABLE OF varchar2(100);\n</code></pre>\n\n<p>You can then pass a variable of this type into your stored procedure and reference it directly. In your case, something like this:</p>\n\n<pre><code>FUNCTION EXECUTE_UPDATE(\n identifierList string_table,\n value int)\nRETURN int\nIS\nBEGIN\n\n [...other stuff...]\n\n update table1 set col1 = col1 - value \n where id in (select column_value from table(identifierList));\n\n RETURN SQL%ROWCOUNT;\n\nEND\n</code></pre>\n\n<p>The <code>table()</code> function turns your custom type into a table with a single column \"COLUMN_VALUE\", which you can then treat like any other table (so do joins or, in this case, subselects).</p>\n\n<p>The beauty of this is that Oracle will create a constructor for you, so when calling your stored procedure you can simply write:</p>\n\n<pre><code>execute_update(string_table('foo','bar','baz'), 32);\n</code></pre>\n\n<p>I'm assuming that you can handle building up this command programatically from C#.</p>\n\n<p>As an aside, at my company we have a number of these custom types defined as standard for lists of strings, doubles, ints and so on. We also make use of <a href=\"http://www.oracle.com/technology/oramag/oracle/04-jan/o14dev_jpublisher.html\" rel=\"noreferrer\">Oracle JPublisher</a> to be able to map directly from these types into corresponding Java objects. I had a quick look around but I couldn't see any direct equivalents for C#. Just thought I'd mention it in case Java devs come across this question.</p>\n" }, { "answer_id": 1234241, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Why not just use a long parameter list and load the values into a table constructor? Here is the SQL/PSM for this trick</p>\n\n<pre><code>UPDATE Foobar\n SET x = 42\n WHERE Foobar.keycol\n IN (SELECT X.parm\n FROM (VALUES (in_p01), (in_p02), .., (in_p99)) X(parm)\n WHERE X.parm IS NOT NULL);\n</code></pre>\n" }, { "answer_id": 1888740, "author": "bowthy", "author_id": 203508, "author_profile": "https://Stackoverflow.com/users/203508", "pm_score": 1, "selected": false, "text": "<p>I found the following article by Mark A. Williams which I thought would be a useful addition to this thread. The article gives a good example of passing arrays from C# to PL/SQL procs using associative arrays (TYPE myType IS TABLE OF mytable.row%TYPE INDEX BY PLS_INTEGER):</p>\n\n<p><a href=\"http://www.oracle.com/technetwork/issue-archive/2007/07-jan/o17odp-093600.html\" rel=\"nofollow noreferrer\">Great article by Mark A. Williams</a></p>\n" }, { "answer_id": 73880698, "author": "Andrea Coppo", "author_id": 20110245, "author_profile": "https://Stackoverflow.com/users/20110245", "pm_score": 0, "selected": false, "text": "<p>just split variable as a comma separed string:</p>\n<pre><code>declare\nschema_n VARCHAR2 (30);\nschema_size number;\nschemas VARCHAR2 (30);\nbegin\nschema_n := 'USER_PROD01,USER_PROD01' ;\n\nselect sum(bytes)/1024/1024 INTO schema_size FROM dba_segments where owner in (\nwith rws as (\n select ''||schema_n||'' str from dual\n)\n select regexp_substr (\n str,\n '[^,]+',\n 1,\n level\n ) value\n from rws\n connect by level &lt;= \n length ( str ) - length ( replace ( str, ',' ) ) + 1\n\n) ;\nDBMS_OUTPUT.PUT_LINE ('PAY ATTENTION : PROD '||schemas||' user size is in total of : '||schema_size||' MBs .');\nend;\n/\n</code></pre>\n<p>PAY ATTENTION : PROD user size is in total of : 18.8125 MBs .</p>\n<p>PL/SQL procedure successfully completed.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970/" ]
How can I create an Oracle stored procedure which accepts a variable number of parameter values used to feed a IN clause? This is what I am trying to achieve. I do not know how to declare in PLSQL for passing a variable list of primary keys of the rows I want to update. ``` FUNCTION EXECUTE_UPDATE ( <parameter_list> value IN int) RETURN int IS BEGIN [...other statements...] update table1 set col1 = col1 - value where id in (<parameter_list>) RETURN SQL%ROWCOUNT ; END; ``` Also, I would like to call this procedure from C#, so it must be compatible with .NET capabilities. Thanks, Robert
Using CSV is probably the simplest way, assuming you can be 100% certain that your elements won't themselves contain strings. An alternative, and probably more robust, way of doing this is to create a custom type as a table of strings. Supposing your strings were never longer than 100 characters, then you could have: ``` CREATE TYPE string_table AS TABLE OF varchar2(100); ``` You can then pass a variable of this type into your stored procedure and reference it directly. In your case, something like this: ``` FUNCTION EXECUTE_UPDATE( identifierList string_table, value int) RETURN int IS BEGIN [...other stuff...] update table1 set col1 = col1 - value where id in (select column_value from table(identifierList)); RETURN SQL%ROWCOUNT; END ``` The `table()` function turns your custom type into a table with a single column "COLUMN\_VALUE", which you can then treat like any other table (so do joins or, in this case, subselects). The beauty of this is that Oracle will create a constructor for you, so when calling your stored procedure you can simply write: ``` execute_update(string_table('foo','bar','baz'), 32); ``` I'm assuming that you can handle building up this command programatically from C#. As an aside, at my company we have a number of these custom types defined as standard for lists of strings, doubles, ints and so on. We also make use of [Oracle JPublisher](http://www.oracle.com/technology/oramag/oracle/04-jan/o14dev_jpublisher.html) to be able to map directly from these types into corresponding Java objects. I had a quick look around but I couldn't see any direct equivalents for C#. Just thought I'd mention it in case Java devs come across this question.
242,792
<p>I need to write a regular expression that finds javascript files that match </p> <pre><code>&lt;anypath&gt;&lt;slash&gt;js&lt;slash&gt;&lt;anything&gt;.js </code></pre> <p>For example, it should work for both :</p> <ul> <li>c:\mysite\js\common.js (Windows)</li> <li>/var/www/mysite/js/common.js (UNIX)</li> </ul> <p>The problem is that the file separator in Windows is not being properly escaped :</p> <pre><code>pattern = Pattern.compile( "^(.+?)" + File.separator + "js" + File.separator + "(.+?).js$" ); </code></pre> <p>Throwing </p> <pre><code>java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence </code></pre> <p>Is there any way to use a common regular expression that works in both Windows and UNIX systems ?</p>
[ { "answer_id": 242803, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "<p>Does <code>Pattern.quote(File.separator)</code> do the trick?</p>\n\n<p>EDIT: This is available as of Java 1.5 or later. For 1.4, you need to simply escape the file separator char:</p>\n\n<pre><code>\"\\\\\" + File.separator\n</code></pre>\n\n<p>Escaping punctuation characters will not break anything, but escaping letters or numbers unconditionally will either change them to their special meaning or lead to a <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/PatternSyntaxException.html\" rel=\"nofollow noreferrer\">PatternSyntaxException</a>. <em>(Thanks <a href=\"https://stackoverflow.com/users/20938/alan-m\">Alan M</a> for pointing this out in the comments!)</em></p>\n" }, { "answer_id": 242806, "author": "heijp06", "author_id": 1793417, "author_profile": "https://Stackoverflow.com/users/1793417", "pm_score": 2, "selected": false, "text": "<p>Can't you just use a backslash to escape the path separator like so:</p>\n\n<pre><code>pattern = Pattern.compile(\n \"^(.+?)\\\\\" + \n File.separator +\n \"js\\\\\" +\n File.separator +\n \"(.+?).js$\" );\n</code></pre>\n" }, { "answer_id": 242814, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "<p>Why don't you escape <code>File.separator</code>:</p>\n\n<pre><code>... +\n\"\\\\\" + File.separator +\n...\n</code></pre>\n\n<p>to fit <code>Pattern.compile</code> requirements?\nI hope \"/\" (unix case) is processed as a single \"/\".</p>\n" }, { "answer_id": 242848, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 1, "selected": false, "text": "<p>I've tested gimel's answer on a Unix system - putting <code>\"\\\\\" + File.separator</code> works fine - the resulting <code>\"\\/\"</code> in the pattern correctly matches a single <code>\"/\"</code></p>\n" }, { "answer_id": 243659, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Is there any way to use a common regular expression that works in both Windows and UNIX systems ?</p>\n</blockquote>\n\n<p>Yes, just use a regex that matches both kinds of separator.</p>\n\n<pre><code>pattern = Pattern.compile(\n \"^(.+?)\" + \n \"[/\\\\\\\\]\" +\n \"js\" +\n \"[/\\\\\\\\]\" +\n \"(.+?)\\\\.js$\" );\n</code></pre>\n\n<p>It's safe because neither Windows nor Unix permits those characters in a file or directory name.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
I need to write a regular expression that finds javascript files that match ``` <anypath><slash>js<slash><anything>.js ``` For example, it should work for both : * c:\mysite\js\common.js (Windows) * /var/www/mysite/js/common.js (UNIX) The problem is that the file separator in Windows is not being properly escaped : ``` pattern = Pattern.compile( "^(.+?)" + File.separator + "js" + File.separator + "(.+?).js$" ); ``` Throwing ``` java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence ``` Is there any way to use a common regular expression that works in both Windows and UNIX systems ?
Does `Pattern.quote(File.separator)` do the trick? EDIT: This is available as of Java 1.5 or later. For 1.4, you need to simply escape the file separator char: ``` "\\" + File.separator ``` Escaping punctuation characters will not break anything, but escaping letters or numbers unconditionally will either change them to their special meaning or lead to a [PatternSyntaxException](http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/PatternSyntaxException.html). *(Thanks [Alan M](https://stackoverflow.com/users/20938/alan-m) for pointing this out in the comments!)*
242,812
<p>I've created a series of radio button controls in C#. <code>(radCompany, radProperty etc.)</code><br> I've set their group name to be the same (282_Type) so they function as a list of radio buttons. </p> <p>How do I retrieve the name <code>(like: ct100$m$dfgadjkfasdghasdkjfg$282_Type)</code> in c# so I can use this in a Javascript method i'm creating?</p> <p>The values output are: </p> <pre><code>Radion Button 1 id="ct223423432243_radCompany" name="ct100$sdfsdf$sdfsdf$282_Type" Radion Button 2 id="ct223423432243_radProperty" name="ct100$sdfsdf$sdfsdf$282_Type" </code></pre>
[ { "answer_id": 242835, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>You need to reference the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx\" rel=\"nofollow noreferrer\">ClientID</a> of the control; this is the id in the final html.</p>\n\n<p>Of course, another approach might be to use some other attribute (such as the css etc), and use <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> to find it; jQuery takes a lot of DOM pain away from javascript. It is interesting that jQuery is now even supported by VS2008 (with intellisense etc).</p>\n\n<p>I'm currently reading <a href=\"http://www.manning.com/bibeault/\" rel=\"nofollow noreferrer\">jQuery in Action</a>, and liking it much. To take an example straight from the book (on the subject of radios):</p>\n\n<pre><code>var x = $('[name=radioGroup]:checked').val();\n</code></pre>\n\n<p>which returns the value of the single checked radio button in the group, or <code>undefined</code> if none is selected.</p>\n\n<p>Re getting the name; it uses the internal <code>UniqueGroupName</code> property, which does a lot of mangling. An option (but not an attractive one) would be to use reflection to read <code>UniqueGroupName</code>. Alternatively, use something simple like a literal control. Gawd I hate the ASP.NET forms model... roll on MVC...</p>\n\n<p>Fianlly - I'm currently looking at the public <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=922b4655-93d0-4476-bda4-94cf5f8d4814&amp;displaylang=en&amp;tm\" rel=\"nofollow noreferrer\">VS2010 CTP</a> image; one of the new additions for ASP.NET is static <code>ClientID</code>s, by setting ClientIdMode = Static on the control. A bit overdue, but not unwelcome.</p>\n" }, { "answer_id": 6702310, "author": "Dallas Morrison", "author_id": 845736, "author_profile": "https://Stackoverflow.com/users/845736", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://reflector.webtropy.com/default.aspx/Net/Net/3@5@50727@3053/DEVDIV/depot/DevDiv/releases/whidbey/netfxsp/ndp/fx/src/xsp/System/Web/UI/WebControls/RadioButton@cs/2/RadioButton@cs\" rel=\"nofollow\">http://reflector.webtropy.com/default.aspx/Net/Net/3@5@50727@3053/DEVDIV/depot/DevDiv/releases/whidbey/netfxsp/ndp/fx/src/xsp/System/Web/UI/WebControls/RadioButton@cs/2/RadioButton@cs</a></p>\n\n<pre><code>internal string UniqueGroupName { \n get { \n if (_uniqueGroupName == null) { \n // For radio buttons, we must make the groupname unique, but can't just use the \n // UniqueID because all buttons in a group must have the same name. So \n // we replace the last part of the UniqueID with the group Name. \n string name = GroupName; \n string uid = UniqueID; \n\n if (uid != null) { \n int lastColon = uid.LastIndexOf(IdSeparator); \n if (lastColon &gt;= 0) { \n if (name.Length &gt; 0) { \n name = uid.Substring(0, lastColon+1) + name; \n } \n else if (NamingContainer is RadioButtonList) { \n // If GroupName is not set we simply use the naming \n // container as the group name \n name = uid.Substring(0, lastColon); \n } \n } \n\n if (name.Length == 0) { \n name = uid; \n } \n } \n\n _uniqueGroupName = name; \n } \n return _uniqueGroupName; \n } \n }\n</code></pre>\n" }, { "answer_id": 6702403, "author": "Alastair", "author_id": 470339, "author_profile": "https://Stackoverflow.com/users/470339", "pm_score": 0, "selected": false, "text": "<p>You want the UniqueID attribute:</p>\n<blockquote>\n<ul>\n<li><p><strong>UniqueID</strong> — The hierarchically-qualified unique identifier assigned to a control by the ASP.NET page framework.</p>\n</li>\n<li><p><strong>ClientID</strong> — A unique identifier assigned to a control by the ASP.NET\npage framework and rendered as the HTML ID attribute on the client.The\nClientID is different from the UniqueID because the UniqueID can\ncontain the colon character (:), which is not valid in the HTML ID\nattribute (and is not allowed in variable names in client-side\nscript).</p>\n</li>\n</ul>\n</blockquote>\n<p>(<a href=\"http://msdn.microsoft.com/en-us/library/aa720435%28v=vs.71%29.aspx\" rel=\"nofollow noreferrer\">from here</a>)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13911/" ]
I've created a series of radio button controls in C#. `(radCompany, radProperty etc.)` I've set their group name to be the same (282\_Type) so they function as a list of radio buttons. How do I retrieve the name `(like: ct100$m$dfgadjkfasdghasdkjfg$282_Type)` in c# so I can use this in a Javascript method i'm creating? The values output are: ``` Radion Button 1 id="ct223423432243_radCompany" name="ct100$sdfsdf$sdfsdf$282_Type" Radion Button 2 id="ct223423432243_radProperty" name="ct100$sdfsdf$sdfsdf$282_Type" ```
You need to reference the [ClientID](http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx) of the control; this is the id in the final html. Of course, another approach might be to use some other attribute (such as the css etc), and use [jQuery](http://jquery.com/) to find it; jQuery takes a lot of DOM pain away from javascript. It is interesting that jQuery is now even supported by VS2008 (with intellisense etc). I'm currently reading [jQuery in Action](http://www.manning.com/bibeault/), and liking it much. To take an example straight from the book (on the subject of radios): ``` var x = $('[name=radioGroup]:checked').val(); ``` which returns the value of the single checked radio button in the group, or `undefined` if none is selected. Re getting the name; it uses the internal `UniqueGroupName` property, which does a lot of mangling. An option (but not an attractive one) would be to use reflection to read `UniqueGroupName`. Alternatively, use something simple like a literal control. Gawd I hate the ASP.NET forms model... roll on MVC... Fianlly - I'm currently looking at the public [VS2010 CTP](http://www.microsoft.com/downloads/details.aspx?familyid=922b4655-93d0-4476-bda4-94cf5f8d4814&displaylang=en&tm) image; one of the new additions for ASP.NET is static `ClientID`s, by setting ClientIdMode = Static on the control. A bit overdue, but not unwelcome.
242,813
<p><code>console.log(&quot;double&quot;);</code> vs. <code>console.log('single');</code></p> <p>I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other?</p> <p>I thought they're pretty much interchangeable.</p>
[ { "answer_id": 242833, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 11, "selected": true, "text": "<p>The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.</p>\n<p>Using the other type of quote as a literal:</p>\n<pre><code>alert('Say &quot;Hello&quot;');\nalert(&quot;Say 'Hello'&quot;);\n</code></pre>\n<p>This can get complicated:</p>\n<pre><code>alert(&quot;It's \\&quot;game\\&quot; time.&quot;);\nalert('It\\'s &quot;game&quot; time.');\n</code></pre>\n<p>Another option, new in ECMAScript 6, is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"noreferrer\">template literals</a> which use the <em>backtick</em> character:</p>\n<pre><code>alert(`Use &quot;double&quot; and 'single' quotes in the same string`);\nalert(`Escape the \\` back-tick character and the \\${ dollar-brace sequence in a string`);\n</code></pre>\n<p>Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.</p>\n<p>Note that <a href=\"https://jsonlint.com/\" rel=\"noreferrer\">JSON</a> is formally specified to use double quotes, which may be worth considering depending on system requirements.</p>\n" }, { "answer_id": 242843, "author": "Michiel Overeem", "author_id": 5043, "author_profile": "https://Stackoverflow.com/users/5043", "pm_score": 3, "selected": false, "text": "<p>There are people that claim to see performance differences: <a href=\"http://lists.evolt.org/pipermail/javascript/2003-November/006168.html\" rel=\"nofollow noreferrer\">old mailing list thread</a>. But I couldn't find any of them to be confirmed.</p>\n<p>The main thing is to look at what kind of quotes (double or single) you are using inside your string. It helps to keep the number of escapes low. For instance, when you are working with HTML content inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.</p>\n" }, { "answer_id": 243148, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "<p>There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JavaScript code itself is in a string), to keep number of escapes low.</p>\n<p>The speed difference legend might come from PHP world, where the two quotes have different behavior.</p>\n" }, { "answer_id": 243687, "author": "Kramii", "author_id": 11514, "author_profile": "https://Stackoverflow.com/users/11514", "pm_score": 5, "selected": false, "text": "<p>Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.</p>\n<p>Here are several factors that could influence your choice:</p>\n<ul>\n<li>House style: Some groups of developers already use one convention or the other.</li>\n<li>Client-side requirements: Will you be using quotes within the strings? (See <a href=\"https://stackoverflow.com/questions/242813/when-should-i-use-double-or-single-quotes-in-javascript/242833#242833\">Ady's answer</a>.)</li>\n<li>Server-side language: VB.NET people might choose to use single quotes for JavaScript so that the scripts can be built server-side (VB.NET uses double-quotes for strings, so the JavaScript strings are easy to distinguished if they use single quotes).</li>\n<li>Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.</li>\n<li>Personal preference: You might think one or other style looks better.</li>\n</ul>\n" }, { "answer_id": 244824, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 2, "selected": false, "text": "<p>The difference is purely stylistic. I used to be a double-quote Nazi. Now I use single quotes in nearly all cases. There's no practical difference beyond how your editor highlights the syntax.</p>\n" }, { "answer_id": 244842, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 7, "selected": false, "text": "<p>Section 7.8.4 of the <a href=\"https://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"noreferrer\">specification</a> describes literal string notation. The only difference is that DoubleStringCharacter is \"SourceCharacter but not double-quote\" and SingleStringCharacter is \"SourceCharacter but not single-quote\". So the <strong>only</strong> difference can be demonstrated thusly:</p>\n\n<pre><code>'A string that\\'s single quoted'\n\n\"A string that's double quoted\"\n</code></pre>\n\n<p>So it depends on how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.</p>\n" }, { "answer_id": 814376, "author": "Mathias Bynens", "author_id": 96656, "author_profile": "https://Stackoverflow.com/users/96656", "pm_score": 6, "selected": false, "text": "<p>I'd like to say the difference is purely stylistic, but I'm really having my doubts. Consider the following example:</p>\n<pre><code>/*\n Add trim() functionality to JavaScript...\n 1. By extending the String prototype\n 2. By creating a 'stand-alone' function\n This is just to demonstrate results are the same in both cases.\n*/\n\n// Extend the String prototype with a trim() method\nString.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, '');\n};\n\n// 'Stand-alone' trim() function\nfunction trim(str) {\n return str.replace(/^\\s+|\\s+$/g, '');\n};\n\ndocument.writeln(String.prototype.trim);\ndocument.writeln(trim);\n</code></pre>\n<p>In Safari, Chrome, Opera, and Internet Explorer (tested in <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_7\" rel=\"nofollow noreferrer\">Internet Explorer 7</a> and <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"nofollow noreferrer\">Internet Explorer 8</a>), this will return the following:</p>\n<pre><code>function () {\n return this.replace(/^\\s+|\\s+$/g, '');\n}\nfunction trim(str) {\n return str.replace(/^\\s+|\\s+$/g, '');\n}\n</code></pre>\n<p>However, Firefox will yield a slightly different result:</p>\n<pre><code>function () {\n return this.replace(/^\\s+|\\s+$/g, &quot;&quot;);\n}\nfunction trim(str) {\n return str.replace(/^\\s+|\\s+$/g, &quot;&quot;);\n}\n</code></pre>\n<p>The single quotes have been replaced by double quotes. (Also note how the indenting space was replaced by four spaces.) This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. <em>One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.</em></p>\n<p>Which, by the way, makes me a very sad panda, since I think single quotes look much nicer in code. Plus, in other programming languages, they're usually faster to use than double quotes, so it would only make sense if the same applied to JavaScript.</p>\n<p><strong>Conclusion:</strong> I think we need to do more research on this.</p>\n<p>This might explain <a href=\"http://lists.evolt.org/pipermail/javascript/2003-November/006155.html\" rel=\"nofollow noreferrer\">Peter-Paul Koch's test results</a> from back in 2003.</p>\n<blockquote>\n<p>It seems that single quotes are <em>sometimes</em> faster in Explorer Windows (roughly 1/3 of my tests did show a faster response time), but if Mozilla shows a difference at all, it handles double quotes slightly faster. I found no difference at all in Opera.</p>\n</blockquote>\n<p><strong>2014:</strong> Modern versions of Firefox/Spidermonkey don’t do this anymore.</p>\n" }, { "answer_id": 814644, "author": "Jozzeh", "author_id": 99816, "author_profile": "https://Stackoverflow.com/users/99816", "pm_score": 1, "selected": false, "text": "<p>I think it's important not to forget that while Internet Explorer might have zero extensions/toolbars installed, Firefox might have some extensions installed (I'm just thinking of <a href=\"https://en.wikipedia.org/wiki/Firebug_%28software%29\" rel=\"nofollow noreferrer\">Firebug</a> for instance). Those extensions will have an influence on the benchmark result.</p>\n<p>Not that it really matters since browser X is faster in getting elementstyles, while browser Y might be faster in rendering a canvas element (hence why a browser &quot;manufacturer&quot; always has the fastest JavaScript engine).</p>\n" }, { "answer_id": 1179473, "author": "Tom Lianza", "author_id": 26624, "author_profile": "https://Stackoverflow.com/users/26624", "pm_score": 5, "selected": false, "text": "<p>If you're doing inline JavaScript (arguably a &quot;bad&quot; thing, but avoiding that discussion) <strong>single</strong> quotes are your only option for string literals, I believe.</p>\n<p>E.g., this works fine:</p>\n<pre><code>&lt;a onclick=&quot;alert('hi');&quot;&gt;hi&lt;/a&gt;\n</code></pre>\n<p>But you can't wrap the &quot;hi&quot; in double quotes, via any escaping method I'm aware of. Even <b><code>&amp;quot;</code></b> which would have been my best guess (since you're escaping quotes in an attribute value of HTML) doesn't work for me in Firefox. <b><code>&quot;</code></b> won't work either because at this point you're escaping for HTML, not JavaScript.</p>\n<p>So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your application, I think single quotes are the winner. Someone please correct me if I'm wrong though.</p>\n" }, { "answer_id": 1179507, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 3, "selected": false, "text": "<p>I would use double quotes when single quotes cannot be used and vice versa:</p>\n\n<pre><code>\"'\" + singleQuotedValue + \"'\"\n'\"' + doubleQuotedValue + '\"'\n</code></pre>\n\n<p>Instead of:</p>\n\n<pre><code>'\\'' + singleQuotedValue + '\\''\n\"\\\"\" + doubleQuotedValue + \"\\\"\"\n</code></pre>\n" }, { "answer_id": 1184251, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>There isn't any difference between single and double quotes in JavaScript.</p>\n<p>The specification is important:</p>\n<p>Maybe there are performance differences, but they are absolutely minimum and can change any day according to browsers' implementation. Further discussion is futile unless your JavaScript application is hundreds of thousands lines long.</p>\n<p>It's like a benchmark if</p>\n<pre><code>a=b;\n</code></pre>\n<p>is faster than</p>\n<pre><code>a = b;\n</code></pre>\n<p>(extra spaces)</p>\n<p>today, in a particular browser and platform, etc.</p>\n" }, { "answer_id": 2738605, "author": "Bastiaan Linders", "author_id": 255657, "author_profile": "https://Stackoverflow.com/users/255657", "pm_score": 3, "selected": false, "text": "<p>I've been running the following about 20 times. And it appears that double quotes are about 20% faster.</p>\n\n<p>The fun part is, if you change part 2 and part 1 around, single quotes are about 20% faster.</p>\n\n<pre><code>//Part1\nvar r='';\nvar iTime3 = new Date().valueOf();\nfor(var j=0; j&lt;1000000; j++) {\n r+='a';\n}\nvar iTime4 = new Date().valueOf();\nalert('With single quote : ' + (iTime4 - iTime3)); \n\n//Part 2 \nvar s=\"\";\nvar iTime1 = new Date().valueOf();\nfor(var i=0; i&lt;1000000; i++) {\n s += \"a\";\n}\nvar iTime2 = new Date().valueOf();\nalert('With double quote: ' + (iTime2 - iTime1));\n</code></pre>\n" }, { "answer_id": 4612914, "author": "Arne", "author_id": 565153, "author_profile": "https://Stackoverflow.com/users/565153", "pm_score": 9, "selected": false, "text": "<p>If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.</p>\n" }, { "answer_id": 7459639, "author": "Mohsen", "author_id": 650722, "author_profile": "https://Stackoverflow.com/users/650722", "pm_score": 3, "selected": false, "text": "<p>After reading all the answers that say it may be be faster or may be have advantages, I would say double quotes are better or may be faster too because the <a href=\"http://closure-compiler.appspot.com/home\" rel=\"nofollow noreferrer\">Google Closure compiler</a> converts single quotes to double quotes.</p>\n" }, { "answer_id": 10116207, "author": "Dodzi Dzakuma", "author_id": 920322, "author_profile": "https://Stackoverflow.com/users/920322", "pm_score": 3, "selected": false, "text": "<p>One more thing that you might want to consider as a reason for the shift from double quotes to single quotes is the increase in popularity of server side scripts. When using PHP you can pass variables and parse JavaScript functions using strings and variables in PHP.</p>\n<p>If you write a string and use double quotes for your PHP you won't have to escape any of the single quotes and PHP will automatically retrieve the value of the variables for you.</p>\n<p>Example:I need to run a JavaScript function using a variable from my server.</p>\n<pre><code>public static function redirectPage( $pageLocation )\n{\n echo &quot;&lt;script type='text/javascript'&gt;window.location = '$pageLocation';&lt;/script&gt;&quot;;\n}\n</code></pre>\n<p>This saves me a lot of hassle in having to deal with joining strings, and I can effectively call a JavaScript from PHP. This is only one example, but this may be one of several reasons why programmers are defaulting to single quotes in JavaScript.</p>\n<p><a href=\"http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double\" rel=\"nofollow noreferrer\">Quote from PHP documents</a>:</p>\n<blockquote>\n<p>The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.</p>\n</blockquote>\n" }, { "answer_id": 10421803, "author": "Mariusz Nowak", "author_id": 96806, "author_profile": "https://Stackoverflow.com/users/96806", "pm_score": 5, "selected": false, "text": "<p>Technically there's no difference. It's only matter of style and convention.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Douglas_Crockford\" rel=\"nofollow noreferrer\">Douglas Crockford</a> recommends using single quotes for internal strings and double quotes for external (by external we mean those to be displayed to user of application, like messages or alerts).</p>\n<p>I personally follow that.</p>\n<p><em>UPDATE: It appears that Mr. Crockford <a href=\"https://plus.google.com/+DouglasCrockfordEsq/posts/EBky2K9erKt\" rel=\"nofollow noreferrer\">changed his mind</a> and now recommends using double quotes throughout :)</em></p>\n" }, { "answer_id": 10472742, "author": "aelgoa", "author_id": 1260792, "author_profile": "https://Stackoverflow.com/users/1260792", "pm_score": -1, "selected": false, "text": "<p>For use of JavaScript code across different languages, I've found single quotes to consistently require less code tweaking.</p>\n\n<p>Double quotes support multi-line strings.</p>\n" }, { "answer_id": 10487870, "author": "mariotti", "author_id": 756130, "author_profile": "https://Stackoverflow.com/users/756130", "pm_score": 4, "selected": false, "text": "<p>I hope I am not adding something obvious, but I have been struggling with <a href=\"http://en.wikipedia.org/wiki/Django_%28web_framework%29\" rel=\"nofollow noreferrer\">Django</a>, <a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow noreferrer\">Ajax</a>, and JSON on this.</p>\n<p>Assuming that in your HTML code you do use double quotes, as normally should be, I highly suggest to use single quotes for the rest in JavaScript.</p>\n<p>So I agree <a href=\"https://stackoverflow.com/questions/242813/when-should-i-use-double-or-single-quotes-in-javascript/242833#242833\">with ady</a>, but with some care.</p>\n<p>My bottom line is:</p>\n<p>In JavaScript it probably doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.</p>\n<p>My simple case was:</p>\n<pre><code>tbox.innerHTML = tbox.innerHTML + '&lt;div class=&quot;thisbox_des&quot; style=&quot;width:210px;&quot; onmouseout=&quot;clear()&quot;&gt;&lt;a href=&quot;/this/thislist/'\n + myThis[i].pk +'&quot;&gt;&lt;img src=&quot;/site_media/'\n + myThis[i].fields.thumbnail +'&quot; height=&quot;80&quot; width=&quot;80&quot; style=&quot;float:left;&quot; onmouseover=&quot;showThis('\n + myThis[i].fields.left +','\n + myThis[i].fields.right +',\\''\n + myThis[i].fields.title +'\\')&quot;&gt;&lt;/a&gt;&lt;p style=&quot;float:left;width:130px;height:80px;&quot;&gt;&lt;b&gt;'\n + myThis[i].fields.title +'&lt;/b&gt; '\n + myThis[i].fields.description +'&lt;/p&gt;&lt;/div&gt;'\n</code></pre>\n<p>You can spot the ' in the third field of showThis.</p>\n<p>The double quote didn't work!</p>\n<p>It is clear why, but it is also clear why we should stick to single quotes... I guess...</p>\n<p>This case is a very simple HTML embedding, and the error was generated by a simple copy/paste from a 'double quoted' JavaScript code.</p>\n<p>So to answer the question:</p>\n<p>Try to use single quotes while within HTML. It might save a couple of debug issues...</p>\n" }, { "answer_id": 10677511, "author": "cavalcade", "author_id": 1264013, "author_profile": "https://Stackoverflow.com/users/1264013", "pm_score": 4, "selected": false, "text": "<p>It's mostly a matter of style and preference. There are some rather interesting and useful technical explorations in the other answers, so perhaps the only thing I might add is to offer a little worldly advice.</p>\n<ul>\n<li><p><em>If</em> you're coding in a company or team, <em>then</em> it's probably a good idea to follow the &quot;house style&quot;.</p>\n</li>\n<li><p><em>If</em> you're alone hacking a few side projects, <em>then</em> look at a few prominent leaders in the community. For example, let's say you getting into <a href=\"https://en.wikipedia.org/wiki/Node.js\" rel=\"nofollow noreferrer\">Node.js</a>. Take a look at core modules, for example, <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"nofollow noreferrer\">Underscore.js</a> or express and see what convention they use, and consider following that.</p>\n</li>\n<li><p><em>If</em> both conventions are equally used, <em>then</em> defer to your personal preference.</p>\n</li>\n<li><p><em>If</em> you don't have any personal preference, <em>then</em> flip a coin.</p>\n</li>\n<li><p><em>If</em> you don't have a coin, <em>then</em> beer is on me ;)</p>\n</li>\n</ul>\n" }, { "answer_id": 11633978, "author": "Frederic", "author_id": 1549163, "author_profile": "https://Stackoverflow.com/users/1549163", "pm_score": 4, "selected": false, "text": "<p>Let's look what a reference does.</p>\n<p>Inside jquery.js, every string is double-quoted.</p>\n<p>So, beginning now, I'll use double-quoted strings. (I was using single!)</p>\n" }, { "answer_id": 12007257, "author": "Jason", "author_id": 1584271, "author_profile": "https://Stackoverflow.com/users/1584271", "pm_score": 2, "selected": false, "text": "<p>For me, if I code in a <a href=\"https://en.wikipedia.org/wiki/Vim_%28text_editor%29\" rel=\"nofollow noreferrer\">Vim</a> editor and if something is enclosed in single quotes, I can double-click to select <em>only</em> the text within the quotes. Double quotes, on the other hand, include the quote marks which I find annoying when I want to do some quick copy and pasting.</p>\n<p>E.g. 'myVar' double-click in the Vim editor copies: &gt;myVar&lt;\n&quot;myVar&quot; literally copies: &gt;&quot;myVar&quot;&lt; and when I paste, I have to delete the quote marks on either side.</p>\n" }, { "answer_id": 12193881, "author": "Eugene Ramirez", "author_id": 180824, "author_profile": "https://Stackoverflow.com/users/180824", "pm_score": -1, "selected": false, "text": "<p>As stated by other replies, they are almost the same. But I will try to add more.</p>\n<ol>\n<li>Some efficient algorithms use character arrays to process strings. Those algorithms (browser compiler, etc.) would see <code>&quot;</code> (#34) first before <code>'</code> (#39) therefore saving several CPU cycles depending on your data structure.</li>\n<li><code>&quot;</code> is escaped by anti-<a href=\"https://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow noreferrer\">XSS</a> engines</li>\n</ol>\n" }, { "answer_id": 13170691, "author": "garysb", "author_id": 1790308, "author_profile": "https://Stackoverflow.com/users/1790308", "pm_score": 4, "selected": false, "text": "<p>I am not sure if this is relevant in today's world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.</p>\n<p>The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched. This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like <code>\\n</code> or <code>\\0</code> (not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in CPU cycles for processing the string).</p>\n" }, { "answer_id": 17769861, "author": "moomoo", "author_id": 2597671, "author_profile": "https://Stackoverflow.com/users/2597671", "pm_score": 3, "selected": false, "text": "<p>If you're jumping back an forth between JavaScript and C#, it's best to train your fingers for the common convention which is double quotes. </p>\n" }, { "answer_id": 18041188, "author": "user1429980", "author_id": 1429980, "author_profile": "https://Stackoverflow.com/users/1429980", "pm_score": 9, "selected": false, "text": "<p><strong>There is no one better solution</strong>; however, I would like to argue that double quotes may be more desirable at times:</p>\n\n<ul>\n<li><strong>Newcomers will already be familiar with double quotes from their language</strong>. In English, we must use double quotes <code>\"</code> to identify a passage of quoted text. If we were to use a single quote <code>'</code>, the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the <code>'</code> indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code.</li>\n<li><strong>Double quotes eliminate the need to escape apostrophes</strong> (as in contractions). Consider the string: <code>\"I'm going to the mall\"</code>, vs. the otherwise escaped version: <code>'I\\'m going to the mall'</code>.</li>\n<li><p><strong>Double quotes mean a string in many other languages</strong>. When you learn a new language like Java or C, double quotes are always used. In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them. </p></li>\n<li><p><strong>JSON notation is written with double quotes.</strong></p></li>\n</ul>\n\n<p>Nonetheless, as others have stated, it is most important to remain consistent.</p>\n" }, { "answer_id": 19054664, "author": "Jules", "author_id": 2824084, "author_profile": "https://Stackoverflow.com/users/2824084", "pm_score": -1, "selected": false, "text": "<p>The best practice is to use double quotes (&quot;&quot;) first and single quotes ('') if needed after. The reason being is that if you ever use server-side scripting you will not be able to pull content from a server (example SQL queries from a database) if you use singles quotes over double.</p>\n" }, { "answer_id": 19988852, "author": "Kat Lim Ruiz", "author_id": 915865, "author_profile": "https://Stackoverflow.com/users/915865", "pm_score": 0, "selected": false, "text": "<p>I think this is all a matter of convenience/preference.</p>\n<p>I prefer double quote because it matches what C# has and this is my environment that I normally work in: C# + JavaScript.</p>\n<p>Also one possible reason for double quotes over single quotes is this (which I have found in my projects code):\nFrench or some other languages use single quotes a lot (like English actually), so if by some reason you end up rendering strings from the server side (which I know is bad practice), then a single quote will render wrongly.</p>\n<p>The probability of using double quotes in a regular language is low, and therefore I think it has a better chance of not breaking something.</p>\n" }, { "answer_id": 20075342, "author": "Juan C. Roldán", "author_id": 1832728, "author_profile": "https://Stackoverflow.com/users/1832728", "pm_score": 4, "selected": false, "text": "<p>Talking about performance, quotes will never be your bottleneck. However, the performance is the same in both cases.</p>\n<p>Talking about coding speed, if you use <code>'</code> for delimiting a string, you will need to escape <code>&quot;</code> quotes. You are more likely to need to use <code>&quot;</code> inside the string. Example:</p>\n<pre><code>// JSON Objects:\nvar jsonObject = '{&quot;foo&quot;:&quot;bar&quot;}';\n\n// HTML attributes:\ndocument.getElementById(&quot;foobar&quot;).innerHTML = '&lt;input type=&quot;text&quot;&gt;';\n</code></pre>\n<p>Then, I prefer to use <code>'</code> for delimiting the string, so I have to escape fewer characters.</p>\n" }, { "answer_id": 20136762, "author": "John Kurlak", "author_id": 55732, "author_profile": "https://Stackoverflow.com/users/55732", "pm_score": 4, "selected": false, "text": "<p>One (silly) reason to use single quotes would be that they don't require you to hit the shift key to type them, whereas a double quote do. (I'm assuming that the average string doesn't require escaping, which is a reasonable assumption.) Now, let's suppose every day I code 200 lines of code. Maybe in those 200 lines I have 30 quotes. Maybe typing a double quote takes 0.1 seconds more time than typing a single quote (because I have to hit the shift key). Then on any given day, I waste 3 seconds. If I code in this manner for 200 days a year for 40 years, then I've wasted 6.7 hours of my life. Food for thought.</p>\n" }, { "answer_id": 22072778, "author": "MetallimaX", "author_id": 2236695, "author_profile": "https://Stackoverflow.com/users/2236695", "pm_score": 4, "selected": false, "text": "<p>If you are using <a href=\"http://www.jshint.com/\" rel=\"nofollow noreferrer\">JSHint</a>, it will raise an error if you use a double quoted string.</p>\n<p>I used it through the Yeoman scafflholding of AngularJS, but maybe there is somehow a manner to configure this.</p>\n<p>By the way, when you handle HTML into JavaScript, it's easier to use single quote:</p>\n<pre><code>var foo = '&lt;div class=&quot;cool-stuff&quot;&gt;Cool content&lt;/div&gt;';\n</code></pre>\n<p>And at least JSON is using double quotes to represent strings.</p>\n<p>There isn't any trivial way to answer to your question.</p>\n" }, { "answer_id": 24053745, "author": "B.F.", "author_id": 817152, "author_profile": "https://Stackoverflow.com/users/817152", "pm_score": 2, "selected": false, "text": "<p>If your JavaScript source is</p>\n<pre><code>elem.innerHTML=&quot;&lt;img src='smily' alt='It\\'s a Smily' style='width:50px'&gt;&quot;;\n</code></pre>\n<p>the HTML source will be:</p>\n<pre><code>&lt;img src=&quot;smiley&quot; alt=&quot;It's a Smiley&quot; style=&quot;width:50px&quot;&gt;\n</code></pre>\n<p>Or for HTML5</p>\n<pre><code>&lt;img src=smiley alt=&quot;It's a Smiley&quot; style=width:50px&gt;\n</code></pre>\n<p>JavaScript allows arrays like that:</p>\n<pre><code>var arr=['this','that'];\n</code></pre>\n<p>But if you stringify it, it will be for compatibility reasons:</p>\n<pre><code>JSON=[&quot;this&quot;,&quot;that&quot;]\n</code></pre>\n<p>I'm sure this takes some time.</p>\n" }, { "answer_id": 24192811, "author": "James Wilkins", "author_id": 1236397, "author_profile": "https://Stackoverflow.com/users/1236397", "pm_score": 2, "selected": false, "text": "<p>Just to add my <a href=\"https://en.wiktionary.org/wiki/two_cents#Noun\" rel=\"nofollow noreferrer\">two cents</a>: In working with both JavaScript and PHP a few years back, I've become accustomed to using single quotes so I can type the escape character ('') without having to escape it as well. I usually used it when typing <a href=\"http://en.wikipedia.org/wiki/String_literal#Raw_strings\" rel=\"nofollow noreferrer\">raw strings</a> with file paths, etc.</p>\n<p>Anyhow, my convention ended up becoming the use of single quotes on identifier-type raw strings, such as <code>if (typeof s == 'string') ...</code> (in which escape characters would never be used - ever), and double quotes for <em>texts</em>, such as &quot;Hey, what's up?&quot;. I also use single quotes in comments as a typographical convention to show identifier names. This is just a rule of thumb, and I break off only when needed, such as when typing HTML strings <code>'&lt;a href=&quot;#&quot;&gt; like so &lt;a&gt;'</code> (though you could reverse the quotes here also). I'm also aware that, in the case of JSON, double quotes are used for the names - but outside that, personally, I prefer the single quotes when escaping is <em>never</em> required for the text between the quotes - like <code>document.createElement('div')</code>.</p>\n<p>The bottom line is, and as some have mentioned/alluded to, to pick a convention, stick with it, and only deviate when necessary.</p>\n" }, { "answer_id": 25771249, "author": "JJTalik", "author_id": 4018784, "author_profile": "https://Stackoverflow.com/users/4018784", "pm_score": 2, "selected": false, "text": "<p>You can use single quotes or double quotes.</p>\n<p>This enables you for example to easily nest JavaScript content inside HTML attributes, without the need to escape the quotes.\nThe same is when you create JavaScript with PHP.</p>\n<p>The general idea is: if it is possible use such quotes that you won't need to escape.</p>\n<p>Less escaping = better code.</p>\n" }, { "answer_id": 28450732, "author": "GijsjanB", "author_id": 997941, "author_profile": "https://Stackoverflow.com/users/997941", "pm_score": 3, "selected": false, "text": "<p>When using <a href=\"https://en.wikipedia.org/wiki/CoffeeScript\" rel=\"nofollow noreferrer\">CoffeeScript</a> I use double quotes. I agree that you should pick either one and stick to it. CoffeeScript gives you interpolation when using the double quotes.</p>\n<pre><code>&quot;This is my #{name}&quot;\n</code></pre>\n<p><a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-_ECMAScript_2015\" rel=\"nofollow noreferrer\">ECMAScript 6</a> is using back ticks (`) for template strings. Which probably has a good reason, but when coding, it can be cumbersome to change the string literals character from quotes or double quotes to backticks in order to get the interpolation feature. CoffeeScript might not be perfect, but using the same string literals character everywhere (double quotes) and always be able to interpolate is a nice feature.</p>\n<pre><code>`This is my ${name}`\n</code></pre>\n" }, { "answer_id": 31883471, "author": "Alec Mev", "author_id": 242684, "author_profile": "https://Stackoverflow.com/users/242684", "pm_score": 7, "selected": false, "text": "<h1>Single Quotes</h1>\n<p>I wish double quotes were the standard, because they <a href=\"https://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript#18041188\">make a little bit more sense</a>, but I keep using single quotes because they dominate the scene.</p>\n<p>Single quotes:</p>\n<ul>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json\" rel=\"noreferrer\">Airbnb</a></li>\n<li><a href=\"https://github.com/facebook/fbjs/blob/8d447780c6f4df0ef92fa3d2987d9c4f96eb0100/packages/eslint-config-fbjs-opensource/index.js#L249\" rel=\"noreferrer\">Facebook</a></li>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/google.json\" rel=\"noreferrer\">Google</a></li>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/grunt.json\" rel=\"noreferrer\">Grunt</a></li>\n<li><a href=\"https://github.com/gulpjs/gulp/blob/master/.jscsrc\" rel=\"noreferrer\">Gulp.js</a></li>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/node.json\" rel=\"noreferrer\">Node.js</a></li>\n<li><a href=\"https://github.com/npm/npm/blob/master/lib/npm.js\" rel=\"noreferrer\">npm</a> (though not defined in <a href=\"https://docs.npmjs.com/misc/coding-style\" rel=\"noreferrer\">the author's guide</a>)</li>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/wikimedia.json\" rel=\"noreferrer\">Wikimedia</a></li>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/wordpress.json\" rel=\"noreferrer\">WordPress</a></li>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/yandex.json\" rel=\"noreferrer\">Yandex</a></li>\n</ul>\n<p>No preference:</p>\n<ul>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/mdcs.json\" rel=\"noreferrer\">Three.js</a></li>\n</ul>\n<p>Double quotes:</p>\n<ul>\n<li><a href=\"https://github.com/microsoft/TypeScript/blob/main/.eslintrc.json\" rel=\"noreferrer\">TypeScript</a></li>\n<li><a href=\"https://plus.google.com/+DouglasCrockfordEsq/posts/EBky2K9erKt\" rel=\"noreferrer\">Douglas Crockford</a></li>\n<li><a href=\"https://github.com/d3/d3-format/blob/master/src/locale.js\" rel=\"noreferrer\">D3.js</a> (though not defined in <a href=\"https://github.com/d3/d3-shape/blob/master/.eslintrc\" rel=\"noreferrer\"><code>.eslintrc</code></a>)</li>\n<li><a href=\"https://github.com/jscs-dev/node-jscs/blob/master/presets/jquery.json\" rel=\"noreferrer\">jQuery</a></li>\n</ul>\n" }, { "answer_id": 32462977, "author": "abhisekp", "author_id": 1262108, "author_profile": "https://Stackoverflow.com/users/1262108", "pm_score": 4, "selected": false, "text": "<p><strong>Just keep consistency in what you use. But don't let down your comfort level.</strong></p>\n<pre><code>&quot;This is my string.&quot;; // :-|\n&quot;I'm invincible.&quot;; // Comfortable :)\n'You can\\'t beat me.'; // Uncomfortable :(\n'Oh! Yes. I can &quot;beat&quot; you.'; // Comfortable :)\n&quot;Do you really think, you can \\&quot;beat\\&quot; me?&quot;; // Uncomfortable :(\n&quot;You're my guest. I can \\&quot;beat\\&quot; you.&quot;; // Sometimes, you've to :P\n'You\\'re my guest too. I can &quot;beat&quot; you too.'; // Sometimes, you've to :P\n</code></pre>\n<p><strong>ECMAScript 6 update</strong></p>\n<p>Using <em>template literal syntax</em>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>`Be &quot;my&quot; guest. You're in complete freedom.`; // Most comfort :D\n</code></pre>\n" }, { "answer_id": 35870563, "author": "Divyesh Kanzariya", "author_id": 5246706, "author_profile": "https://Stackoverflow.com/users/5246706", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>Examining the pros and cons</p>\n</blockquote>\n\n<p><strong>In favor of single quotes</strong></p>\n\n<ul>\n<li>Less visual clutter.</li>\n<li>Generating HTML: HTML attributes are usually delimited by double quotes.</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>elem.innerHTML = '&lt;a href=\"' + url + '\"&gt;Hello&lt;/a&gt;';</code></pre>\r\n</div>\r\n</div>\r\n\nHowever, single quotes are just as legal in HTML.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>elem.innerHTML = \"&lt;a href='\" + url + \"'&gt;Hello&lt;/a&gt;\";</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Furthermore, inline HTML is normally an anti-pattern. Prefer templates.</p>\n\n<ul>\n<li>Generating JSON: Only double quotes are allowed in JSON.</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>myJson = '{ \"hello world\": true }';</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.</p>\n\n<p><strong>In favor of double quotes</strong></p>\n\n<ul>\n<li>Doubles are easier to spot if you don't have color coding. Like in a console log or some kind of view-source setup.</li>\n<li>Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them. C and Java use double quotes for strings and single quotes for characters.</li>\n<li>If you want code to be valid JSON, you need to use double quotes.</li>\n</ul>\n\n<p><strong>In favor of both</strong></p>\n\n<p>There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> \"He said: \\\"Let's go!\\\"\"\r\n 'He said: \"Let\\'s go!\"'\r\n \"He said: \\\"Let\\'s go!\\\"\"\r\n 'He said: \\\"Let\\'s go!\\\"'</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.</p>\n" }, { "answer_id": 40283674, "author": "ovidb", "author_id": 1828653, "author_profile": "https://Stackoverflow.com/users/1828653", "pm_score": 2, "selected": false, "text": "<p>It is just a matter <em>time</em> for me. A few milliseconds lost of my life every time I have to press the <kbd>Shift</kbd> key before every time I'm able to type <code>&quot;</code>.</p>\n<p>I prefer <code>'</code> simply because you don't have to do it!</p>\n<p>Other than that, you can escape a <code>'</code> inside single quotes with backslash <code>\\'</code>.</p>\n<p><code>console.log('Don\\'t lose time'); // &quot;Don't lose time&quot;</code></p>\n" }, { "answer_id": 45612369, "author": "Bruno Jennrich", "author_id": 1557690, "author_profile": "https://Stackoverflow.com/users/1557690", "pm_score": 2, "selected": false, "text": "<p>I use single quotes most of the time, because when developing in PHP, single quoted-string are in no way altered, which is what I want. When I use</p>\n<pre><code>echo &quot;$xyz&quot;;\n</code></pre>\n<p>In PHP, $xyz gets evaluated, which is <em>not</em> what I want. Therefore I always use <code>'</code> instead of <code>&quot;</code> when it comes to web development. So I ensure at least string-consistency when it comes to PHP/JavaScript.</p>\n<p>Unfortunately this can't be done in Java or <a href=\"https://en.wikipedia.org/wiki/Objective-C\" rel=\"nofollow noreferrer\">Objective-C</a>, where <code>''</code> stands for character and <code>&quot;&quot;</code> stands for string. But this is another question.</p>\n" }, { "answer_id": 48703923, "author": "Gordon", "author_id": 4870698, "author_profile": "https://Stackoverflow.com/users/4870698", "pm_score": 1, "selected": false, "text": "<p>If you use PHP to generate JavaScript code you should use the following declaration.</p>\n<pre><code>let value = &quot;&lt;?php echo 'This is my message, &quot;double quoted&quot; - \\'single quoted\\' ?&gt;&quot;;\n</code></pre>\n<p>The output will be:</p>\n<pre><code>This is my message, &quot;double quoted&quot; - 'single quoted'\n</code></pre>\n<p>For some reasons it is recommend to use single quotes rather than double quotes in PHP.</p>\n<p>For the normal behaviour in JavaScript it is recommend to use single quotes.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var value = 'This is my message';\ndocument.getElementById('sample-text').innerHTML = value;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;span id=\"sample-text\"&gt;&lt;/span&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 56860574, "author": "Anthony", "author_id": 3973137, "author_profile": "https://Stackoverflow.com/users/3973137", "pm_score": 0, "selected": false, "text": "<p>Personally I prefer single quotes for the sake of readability. If I'm staring at code all day it's easier to see the words with just single quotes as opposed to double quotes.</p>\n\n<p>Easier to read as demonstrated here:</p>\n\n<p>'easy to read'</p>\n\n<p>\"harder to read\"</p>\n\n<p>\"\"hardest to read\"\"</p>\n" }, { "answer_id": 59709799, "author": "OCDev", "author_id": 508558, "author_profile": "https://Stackoverflow.com/users/508558", "pm_score": 3, "selected": false, "text": "<p>Now that it's 2020, we should consider a third option for JavaScript: The single backtick for everything.</p>\n<p>This can be used everywhere instead of single or double quotes.</p>\n<p>It allows you to do all the things!</p>\n<ol>\n<li><p><strong>Embed single quotes inside of it:</strong> `It's great!`</p>\n</li>\n<li><p><strong>Embed double quotes inside of it:</strong> `It's &quot;really&quot; great!`</p>\n</li>\n<li><p><strong>Use string interpolation:</strong> `It's &quot;${better}&quot; than great!`</p>\n</li>\n<li><p><strong>It allows multiple lines:</strong> `</p>\n<p>This</p>\n<p>Makes</p>\n<p>JavaScript</p>\n<p>Better!</p>\n</li>\n</ol>\n<p>`</p>\n<p>It also doesn't cause any performance loss when replacing the other two:\n<em><a href=\"https://medium.com/javascript-in-plain-english/are-backticks-slower-than-other-strings-in-javascript-ce4abf9b9fa\" rel=\"nofollow noreferrer\">Are backticks (``) slower than other strings in JavaScript?</a></em></p>\n" }, { "answer_id": 59977360, "author": "lolol", "author_id": 941072, "author_profile": "https://Stackoverflow.com/users/941072", "pm_score": 1, "selected": false, "text": "<p>I prefer to use the single quote, <code>'</code>. It is easier to type and looks better.</p>\n<p>Also, let’s remember that straight quotes (single and double) are a mistake in good typography. Curly quotes are preferable, so instead of escaping straight quotes I prefer to use the correct characters.</p>\n<pre><code>const message = 'That\\'s a \\'magic\\' shoe.' // This is wrong\nconst message = 'That’s a ‘magic’ shoe.' // This is correct\n</code></pre>\n<p><a href=\"https://practicaltypography.com/straight-and-curly-quotes.html\" rel=\"nofollow noreferrer\">https://practicaltypography.com/straight-and-curly-quotes.html</a></p>\n<p>Can someone add a smart-quote feature to Visual Studio Code, please?</p>\n" }, { "answer_id": 70415062, "author": "Artfaith", "author_id": 5113030, "author_profile": "https://Stackoverflow.com/users/5113030", "pm_score": 0, "selected": false, "text": "<p>In addition, it seems the specification (currently mentioned at <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\" rel=\"nofollow noreferrer\">MDN</a>) doesn't state any difference between single and double quotes except closing and some unescaped few characters. However, template literal (`) assumes additional parsing/processing.</p>\n<blockquote>\n<p>A string literal is 0 or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. <strong>All code points may appear literally in a string literal except for the closing quote code points</strong>, <code>U+005C (REVERSE SOLIDUS)</code>, <code>U+000D (CARRIAGE RETURN)</code>, and <code>U+000A (LINE FEED)</code>. Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values...</p>\n</blockquote>\n<p>Source: <a href=\"https://tc39.es/ecma262/#sec-literals-string-literals\" rel=\"nofollow noreferrer\">https://tc39.es/ecma262/#sec-literals-string-literals</a></p>\n" }, { "answer_id": 72089570, "author": "Nabi K.A.Z.", "author_id": 1407491, "author_profile": "https://Stackoverflow.com/users/1407491", "pm_score": -1, "selected": false, "text": "<p>Single quotation (<kbd>'</kbd>) uses one keyboard key, but double quotation uses two keys (<kbd>shift</kbd>+<kbd>'</kbd>). So saving the number of keys press is also an advantage! (:</p>\n" }, { "answer_id": 74558082, "author": "Bowiemtl", "author_id": 13088630, "author_profile": "https://Stackoverflow.com/users/13088630", "pm_score": 0, "selected": false, "text": "<p>This answer is going to be pretty much useless but my general guideline is using double quotes for when a string is going to be visible to the user and single quotes for when it's passed down into a function exclusively. Jshint w109 however suggests single quote strings but it's personal preference from my experience mostly</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28150/" ]
`console.log("double");` vs. `console.log('single');` I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other? I thought they're pretty much interchangeable.
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string. Using the other type of quote as a literal: ``` alert('Say "Hello"'); alert("Say 'Hello'"); ``` This can get complicated: ``` alert("It's \"game\" time."); alert('It\'s "game" time.'); ``` Another option, new in ECMAScript 6, is [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) which use the *backtick* character: ``` alert(`Use "double" and 'single' quotes in the same string`); alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`); ``` Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more. Note that [JSON](https://jsonlint.com/) is formally specified to use double quotes, which may be worth considering depending on system requirements.
242,822
<p>Why would someone use <code>WHERE 1=1 AND &lt;conditions&gt;</code> in a SQL clause (Either SQL obtained through concatenated strings, either view definition)</p> <p>I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.</p> <p>If there is injection <code>WHERE 1 = 1 AND injected OR 1=1</code> would have the same result as <code>injected OR 1=1</code>.</p> <p>Later edit: What about the usage in a view definition?</p> <hr> <p>Thank you for your answers.</p> <p>Still, I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure.</p> <p>Take this for example:</p> <pre><code>CREATE VIEW vTest AS SELECT FROM Table WHERE 1=1 AND table.Field=Value </code></pre>
[ { "answer_id": 242831, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 10, "selected": true, "text": "<p>If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:</p>\n\n<pre><code>and &lt;condition&gt;\n</code></pre>\n\n<p>and concatenate them all together. With the <code>1=1</code> at the start, the initial <code>and</code> has something to associate with.</p>\n\n<p>I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I <em>have</em> seen it used as an implementation convenience. The SQL query engine will end up ignoring the <code>1=1</code> so it should have no performance impact.</p>\n" }, { "answer_id": 242832, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 5, "selected": false, "text": "<p>Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.</p>\n" }, { "answer_id": 242834, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "<p>1 = 1 expression is commonly used in generated sql code. This expression can simplify sql generating code reducing number of conditional statements.</p>\n" }, { "answer_id": 242842, "author": "Carl", "author_id": 2136, "author_profile": "https://Stackoverflow.com/users/2136", "pm_score": 5, "selected": false, "text": "<p>I've seen it used when the number of conditions can be variable. </p>\n\n<p>You can concatenate conditions using an \" AND \" string. Then, instead of counting the number of conditions you're passing in, you place a \"WHERE 1=1\" at the end of your stock SQL statement and throw on the concatenated conditions.</p>\n\n<p>Basically, it saves you having to do a test for conditions and then add a \"WHERE\" string before them.</p>\n" }, { "answer_id": 242867, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 7, "selected": false, "text": "<p>Just adding a example code to Greg's answer:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>dim sqlstmt as new StringBuilder\nsqlstmt.add(&quot;SELECT * FROM Products&quot;)\nsqlstmt.add(&quot; WHERE 1=1&quot;) \n\n''// From now on you don't have to worry if you must \n''// append AND or WHERE because you know the WHERE is there\nIf ProductCategoryID &lt;&gt; 0 then\n sqlstmt.AppendFormat(&quot; AND ProductCategoryID = {0}&quot;, trim(ProductCategoryID))\nend if\nIf MinimunPrice &gt; 0 then\n sqlstmt.AppendFormat(&quot; AND Price &gt;= {0}&quot;, trim(MinimunPrice))\nend if\n</code></pre>\n" }, { "answer_id": 243050, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "<p>Actually, I've seen this sort of thing used in BIRT reports. The query passed to the BIRT runtime is of the form:</p>\n\n<pre><code>select a,b,c from t where a = ?\n</code></pre>\n\n<p>and the '?' is replaced at runtime by an actual parameter value selected from a drop-down box. The choices in the drop-down are given by:</p>\n\n<pre><code>select distinct a from t\nunion all\nselect '*' from sysibm.sysdummy1\n</code></pre>\n\n<p>so that you get all possible values plus \"<code>*</code>\". If the user selects \"<code>*</code>\" from the drop down box (meaning all values of a should be selected), the query has to be modified (by Javascript) before being run.</p>\n\n<p>Since the \"?\" is a positional parameter and MUST remain there for other things to work, the Javascript modifies the query to be:</p>\n\n<pre><code>select a,b,c from t where ((a = ?) or (1==1))\n</code></pre>\n\n<p>That basically removes the effect of the where clause while still leaving the positional parameter in place.</p>\n\n<p>I've also seen the AND case used by lazy coders whilst dynamically creating an SQL query.</p>\n\n<p>Say you have to dynamically create a query that starts with <code>select * from t</code> and checks:</p>\n\n<ul>\n<li>the name is Bob; and</li>\n<li>the salary is > $20,000</li>\n</ul>\n\n<p>some people would add the first with a WHERE and subsequent ones with an AND thus:</p>\n\n<pre><code>select * from t where name = 'Bob' and salary &gt; 20000\n</code></pre>\n\n<p>Lazy programmers (and that's not necessarily a <em>bad</em> trait) wouldn't distinguish between the added conditions, they'd start with <code>select * from t where 1=1</code> and just add AND clauses after that.</p>\n\n<pre><code>select * from t where 1=1 and name = 'Bob' and salary &gt; 20000\n</code></pre>\n" }, { "answer_id": 517307, "author": "jackberry", "author_id": 45131, "author_profile": "https://Stackoverflow.com/users/45131", "pm_score": 0, "selected": false, "text": "<p>I first came across this back with ADO and classic asp, the answer i got was: <strong>performance.</strong>\nif you do a straight </p>\n\n<p><code>Select * from tablename</code></p>\n\n<p>and pass that in as an sql command/text you will get a noticeable performance increase with the </p>\n\n<p><code>Where 1=1</code></p>\n\n<p>added, it was a visible difference. something to do with table headers being returned as soon as the first condition is met, or some other craziness, anyway, it did speed things up.</p>\n" }, { "answer_id": 1419843, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>where 1=0, This is done to check if the table exists. Don't know why 1=1 is used.</p>\n" }, { "answer_id": 2021633, "author": "sanbikinoraion", "author_id": 22715, "author_profile": "https://Stackoverflow.com/users/22715", "pm_score": 3, "selected": false, "text": "<p>While I can see that 1=1 would be useful for generated SQL, a technique I use in PHP is to create an array of clauses and then do</p>\n\n<pre><code>implode (\" AND \", $clauses);\n</code></pre>\n\n<p>thus avoiding the problem of having a leading or trailing AND. Obviously this is only useful if you know that you are going to have at least one clause!</p>\n" }, { "answer_id": 8164877, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 3, "selected": false, "text": "<p>Here's a closely related example: using a SQL <code>MERGE</code> statement to update the target tabled using all values from the source table where there is no common attribute on which to join on e.g. </p>\n\n<pre><code>MERGE INTO Circles\n USING \n (\n SELECT pi\n FROM Constants\n ) AS SourceTable\n ON 1 = 1\nWHEN MATCHED THEN \n UPDATE\n SET circumference = 2 * SourceTable.pi * radius;\n</code></pre>\n" }, { "answer_id": 11905143, "author": "Big Al", "author_id": 1399422, "author_profile": "https://Stackoverflow.com/users/1399422", "pm_score": 0, "selected": false, "text": "<p>Using a predicate like <code>1=1</code> is a normal hint sometimes used to force the access plan to use or not use an index scan. The reason why this is used is when you are using a multi-nested joined query with many predicates in the where clause where sometimes even using all of the indexes causes the access plan to read each table - a full table scan. This is just 1 of many hints used by DBAs to trick a dbms into using a more efficient path. Just don't throw one in; you need a dba to analyze the query since it doesn't always work.</p>\n" }, { "answer_id": 14982466, "author": "milso", "author_id": 633865, "author_profile": "https://Stackoverflow.com/users/633865", "pm_score": 5, "selected": false, "text": "<p>Indirectly Relevant: when 1=2 is used:</p>\n\n<pre><code>CREATE TABLE New_table_name \nas \nselect * \nFROM Old_table_name \nWHERE 1 = 2;\n</code></pre>\n\n<p>this will create a new table with same schema as old table. (Very handy if you want to load some data for compares)</p>\n" }, { "answer_id": 22497243, "author": "Zo Has", "author_id": 521201, "author_profile": "https://Stackoverflow.com/users/521201", "pm_score": 1, "selected": false, "text": "<p>I do this usually when I am building dynamic SQL for a report which has many dropdown values a user can select. Since the user may or may not select the values from each dropdown, we end up getting a hard time figuring out which condition was the first where clause. So we pad up the query with a <code>where 1=1</code> in the end and add all where clauses after that.</p>\n\n<p>Something like</p>\n\n<pre><code>select column1, column2 from my table where 1=1 {name} {age};\n</code></pre>\n\n<p>Then we would build the where clause like this and pass it as a parameter value</p>\n\n<pre><code>string name_whereClause= ddlName.SelectedIndex &gt; 0 ? \"AND name ='\"+ ddlName.SelectedValue+ \"'\" : \"\";\n</code></pre>\n\n<p>As the where clause selection are unknown to us at runtime, so this helps us a great deal in finding whether to include an <code>'AND' or 'WHERE'.</code></p>\n" }, { "answer_id": 27622738, "author": "StuartLC", "author_id": 314291, "author_profile": "https://Stackoverflow.com/users/314291", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Why would someone use WHERE 1=1 AND <code>&lt;proper conditions&gt;</code></p>\n</blockquote>\n\n<p>I've <a href=\"https://stackoverflow.com/a/11329871/314291\">seen</a> homespun frameworks do stuff like this (<em>blush</em>), as this allows lazy parsing practices to be applied to both the <code>WHERE</code> and <code>AND</code> Sql keywords.</p>\n\n<p>For example (I'm using C# as an example here), consider the conditional parsing of the following predicates in a Sql query <code>string builder</code>:</p>\n\n<pre><code>var sqlQuery = \"SELECT * FROM FOOS WHERE 1 = 1\"\nif (shouldFilterForBars)\n{\n sqlQuery = sqlQuery + \" AND Bars &gt; 3\";\n}\nif (shouldFilterForBaz)\n{\n sqlQuery = sqlQuery + \" AND Baz &lt; 12\";\n}\n</code></pre>\n\n<p>The \"benefit\" of <code>WHERE 1 = 1</code> means that no special code is needed:</p>\n\n<ul>\n<li>For <strong>AND</strong> - whether zero, one or both predicates (Bars and Baz's) should be applied, which would determine whether the first <code>AND</code> is required. Since we already have at least one predicate with the <code>1 = 1</code>, it means <code>AND</code> is always OK.</li>\n<li>For no predicates at all - In the case where there are ZERO predicates, then the <code>WHERE</code> must be dropped. But again, we can be lazy, because we are again guarantee of at least one predicate.</li>\n</ul>\n\n<p>This is obviously a bad idea and would recommend using an established data access framework or <a href=\"https://stackoverflow.com/a/11330095/314291\">ORM</a> for parsing optional and conditional predicates in this way.</p>\n" }, { "answer_id": 36427261, "author": "Yogesh Umesh Vaity", "author_id": 5925259, "author_profile": "https://Stackoverflow.com/users/5925259", "pm_score": 3, "selected": false, "text": "<p>If you came here searching for <code>WHERE 1</code>, note that <code>WHERE 1</code> and <code>WHERE 1=1</code> are identical. <code>WHERE 1</code> is used rarely because some database systems reject it considering <code>WHERE 1</code> not really being boolean.</p>\n" }, { "answer_id": 37310766, "author": "Carlos Toledo", "author_id": 4146766, "author_profile": "https://Stackoverflow.com/users/4146766", "pm_score": 4, "selected": false, "text": "<p>I found this pattern useful when I'm testing or double checking things on the database, so I can very quickly comment other conditions:</p>\n<pre><code>CREATE VIEW vTest AS\nSELECT FROM Table WHERE 1=1 \nAND Table.Field=Value\nAND Table.IsValid=true\n</code></pre>\n<p>turns into:</p>\n<pre><code>CREATE VIEW vTest AS\nSELECT FROM Table WHERE 1=1 \n--AND Table.Field=Value\n--AND Table.IsValid=true\n</code></pre>\n" }, { "answer_id": 48821888, "author": "Eliseo Jr", "author_id": 8311491, "author_profile": "https://Stackoverflow.com/users/8311491", "pm_score": 2, "selected": false, "text": "<p>This is useful in a case where you have to use dynamic query in which in where \nclause you have to append some filter options. Like if you include options 0 for status is inactive, 1 for active. Based from the options, there is only two available options(0 and 1) but if you want to display All records, it is handy to include in where close 1=1.\nSee below sample:</p>\n\n<pre><code>Declare @SearchValue varchar(8) \nDeclare @SQLQuery varchar(max) = '\nSelect [FirstName]\n ,[LastName]\n ,[MiddleName]\n ,[BirthDate]\n,Case\n when [Status] = 0 then ''Inactive''\n when [Status] = 1 then ''Active''\nend as [Status]'\n\nDeclare @SearchOption nvarchar(100)\nIf (@SearchValue = 'Active')\nBegin\n Set @SearchOption = ' Where a.[Status] = 1'\nEnd\n\nIf (@SearchValue = 'Inactive')\nBegin\n Set @SearchOption = ' Where a.[Status] = 0'\nEnd\n\nIf (@SearchValue = 'All')\nBegin\n Set @SearchOption = ' Where 1=1'\nEnd\n\nSet @SQLQuery = @SQLQuery + @SearchOption\n\nExec(@SQLQuery);\n</code></pre>\n" }, { "answer_id": 49323891, "author": "JonWay", "author_id": 5300021, "author_profile": "https://Stackoverflow.com/users/5300021", "pm_score": 2, "selected": false, "text": "<p>Having review all the answers i decided to perform some experiment like</p>\n\n<pre><code>SELECT\n*\nFROM MyTable\n\nWHERE 1=1\n</code></pre>\n\n<p>Then i checked with other numbers</p>\n\n<pre><code>WHERE 2=2\nWHERE 10=10\nWHERE 99=99\n</code></pre>\n\n<p>ect\nHaving done all the checks, the query run town is the same. even without the where clause. I am not a fan of the syntax </p>\n" }, { "answer_id": 62336566, "author": "SMS", "author_id": 11262056, "author_profile": "https://Stackoverflow.com/users/11262056", "pm_score": 0, "selected": false, "text": "<p>Here is a use case... however I am not too concerned with the technicalities of why I should or not use 1 = 1.\nI am writing a function, using pyodbc to retrieve some data from SQL Server. I was looking for a way to force a filler after the <code>where</code> keyword in my code. This was a great suggestion indeed:</p>\n\n<pre><code>if _where == '': _where = '1=1'\n...\n...\n...\ncur.execute(f'select {predicate} from {table_name} where {_where}')\n</code></pre>\n\n<p>The reason is because I could not implement the keyword 'where' together inside the _where clause variable. So, I think using any dummy condition that evaluates to true would do as a filler.</p>\n" }, { "answer_id": 65370798, "author": "spioter", "author_id": 1279373, "author_profile": "https://Stackoverflow.com/users/1279373", "pm_score": 1, "selected": false, "text": "<p>Making &quot;where 1=1&quot; the standard for all your queries also makes it trivially easy to validate the sql by replacing it with where 1 = 0, handy when you have batches of commands/files.</p>\n<p>Also makes it trivially easy to find the end of the end of the from/join section of any query. Even queries with sub-queries if properly indented.</p>\n" }, { "answer_id": 67129874, "author": "Bora Çolakoğlu", "author_id": 14253710, "author_profile": "https://Stackoverflow.com/users/14253710", "pm_score": 2, "selected": false, "text": "<p>Saw this in production code and asked seniors for help.</p>\n<p>Their answer:</p>\n<p>-We use 1=1 so when we have to add a new condition we can just type</p>\n<pre><code>and &lt;condition&gt;\n</code></pre>\n<p>and get on with it.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23795/" ]
Why would someone use `WHERE 1=1 AND <conditions>` in a SQL clause (Either SQL obtained through concatenated strings, either view definition) I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird. If there is injection `WHERE 1 = 1 AND injected OR 1=1` would have the same result as `injected OR 1=1`. Later edit: What about the usage in a view definition? --- Thank you for your answers. Still, I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure. Take this for example: ``` CREATE VIEW vTest AS SELECT FROM Table WHERE 1=1 AND table.Field=Value ```
If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like: ``` and <condition> ``` and concatenate them all together. With the `1=1` at the start, the initial `and` has something to associate with. I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I *have* seen it used as an implementation convenience. The SQL query engine will end up ignoring the `1=1` so it should have no performance impact.
242,841
<p>Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?</p> <p>Let's say we have an array of associative arrays:</p> <pre><code>var myArray = [{'key': 'value'}, {'key': 'value1'}]; </code></pre> <p>So we can iterate:</p> <pre><code>for (var i = 0; i &lt; myArray.length; i++) </code></pre> <p>And:</p> <pre><code>for (var i in myArray) </code></pre> <p>I don't see a big difference. Are there any performance issues?</p>
[ { "answer_id": 242869, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 2, "selected": false, "text": "<p>With <em>for (var i in myArray)</em> you can loop over objects too, <em>i</em> will contain the key name and you can access the property via <em>myArray[i]</em>. Additionaly, any methods you will have added to the object will be included in the loop, too, i.e., if you use any external framework like jQuery or prototype, or if you add methods to object prototypes directly, at one point <em>i</em> will point to those methods.</p>\n" }, { "answer_id": 242872, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 3, "selected": false, "text": "<p>I'd use the different methods based on how I wanted to reference the items.</p>\n\n<p>Use foreach if you just want the current item.</p>\n\n<p>Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)</p>\n\n<p>I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.</p>\n" }, { "answer_id": 242888, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 10, "selected": true, "text": "<p>The choice should be based on the which idiom is best understood.</p>\n\n<p>An array is iterated using:</p>\n\n<pre><code>for (var i = 0; i &lt; a.length; i++)\n //do stuff with a[i]\n</code></pre>\n\n<p>An object being used as an associative array is iterated using:</p>\n\n<pre><code>for (var key in o)\n //do stuff with o[key]\n</code></pre>\n\n<p>Unless you have earth shattering reasons, stick to the established pattern of usage.</p>\n" }, { "answer_id": 242893, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 5, "selected": false, "text": "<p>there are performance differences depending on what kind of loop you use and on what browser.</p>\n\n<p>For instance:</p>\n\n<pre><code>for (var i = myArray.length-1; i &gt;= 0; i--)\n</code></pre>\n\n<p>is almost twice as fast on some browsers than:</p>\n\n<pre><code>for (var i = 0; i &lt; myArray.length; i++)\n</code></pre>\n\n<p>However unless your arrays are HUGE or you loop them constantly all are fast enough. I seriously doubt that array looping is a bottleneck in your project (or for any other project for that matter)</p>\n" }, { "answer_id": 243694, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 2, "selected": false, "text": "<p>For in loops on Arrays is not compatible with Prototype. If you think you might need to use that library in the future, it would make sense to stick to for loops.</p>\n\n<p><a href=\"http://www.prototypejs.org/api/array\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/array</a></p>\n" }, { "answer_id": 243755, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 4, "selected": false, "text": "<p>I second opinions that you should choose the iteration method according to your need. I would suggest you actually not to <strong>ever</strong> loop through native <code>Array</code> with <code>for in</code> structure. It is way slower <strong>and</strong>, as Chase Seibert pointed at the moment ago, not compatible with Prototype framework.</p>\n\n<p>There is an excellent <a href=\"http://blogs.oracle.com/greimer/entry/best_way_to_code_a\" rel=\"noreferrer\">benchmark on different looping styles that you absolutely should take a look at if you work with JavaScript</a>. Do not do early optimizations, but you should keep that stuff somewhere in the back of your head.</p>\n\n<p>I would use <code>for in</code> to get all properties of an object, which is especially useful when debugging your scripts. For example, I like to have this line handy when I explore unfamiliar object:</p>\n\n<pre><code>l = ''; for (m in obj) { l += m + ' =&gt; ' + obj[m] + '\\n' } console.log(l);\n</code></pre>\n\n<p>It dumps content of the whole object (together with method bodies) to my Firebug log. <strong>Very</strong> handy.</p>\n" }, { "answer_id": 243778, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 7, "selected": false, "text": "<p>Douglas Crockford recommends in <a href=\"http://oreilly.com/catalog/9780596517748/\" rel=\"noreferrer\">JavaScript: The Good Parts</a> (page 24) to avoid using the <code>for in</code> statement. </p>\n\n<p>If you use <code>for in</code> to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.</p>\n\n<p>Everything but the properties can be filtered out with <code>.hasOwnProperty</code>. This code sample does what you probably wanted originally:</p>\n\n<pre><code>for (var name in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, name)) {\n // DO STUFF\n }\n}\n</code></pre>\n" }, { "answer_id": 243796, "author": "Benjamin Lee", "author_id": 29009, "author_profile": "https://Stackoverflow.com/users/29009", "pm_score": 2, "selected": false, "text": "<p>I have seen problems with the \"for each\" using objects and prototype and arrays</p>\n\n<p>my understanding is that the for each is for properties of objects and NOT arrays</p>\n" }, { "answer_id": 1176454, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>here is something i did.</p>\n\n<pre><code>function foreach(o, f) {\n for(var i = 0; i &lt; o.length; i++) { // simple for loop\n f(o[i], i); // execute a function and make the obj, objIndex available\n }\n}\n</code></pre>\n\n<p>this is how you would use it<br />\nthis will work on arrays and objects( such as a list of HTML elements )</p>\n\n<pre><code>foreach(o, function(obj, i) { // for each obj in o\n alert(obj); // obj\n alert(i); // obj index\n /*\n say if you were dealing with an html element may be you have a collection of divs\n */\n if(typeof obj == 'object') { \n obj.style.marginLeft = '20px';\n }\n});\n</code></pre>\n\n<p>I just made this so I'm open to suggestions :)</p>\n" }, { "answer_id": 1229010, "author": "Jason", "author_id": 26860, "author_profile": "https://Stackoverflow.com/users/26860", "pm_score": 6, "selected": false, "text": "<h2>FYI - jQuery Users</h2>\n\n<hr>\n\n<p>jQuery's <code>each(callback)</code> method uses <code>for( ; ; )</code> loop by default, and will use <code>for( in )</code> <em>only</em> if the length is <code>undefined</code>. </p>\n\n<p>Therefore, I would say it is safe to assume the correct order when using this function.</p>\n\n<p><strong>Example</strong>:</p>\n\n<pre><code>$(['a','b','c']).each(function() {\n alert(this);\n});\n//Outputs \"a\" then \"b\" then \"c\"\n</code></pre>\n\n<p>The downside of using this is that if you're doing some non UI logic, your functions will be less portable to other frameworks. The <code>each()</code> function is probably best reserved for use with jQuery selectors and <code>for( ; ; )</code> might be advisable otherwise.</p>\n\n<hr>\n" }, { "answer_id": 3122212, "author": "fabjoa", "author_id": 376741, "author_profile": "https://Stackoverflow.com/users/376741", "pm_score": 2, "selected": false, "text": "<p>If you really want to speed up your code, what about that?</p>\n\n<pre><code>for( var i=0,j=null; j=array[i++]; foo(j) );\n</code></pre>\n\n<p>it's kinda of having the while logic within the for statement and it's less redundant. Also firefox has Array.forEach and Array.filter</p>\n" }, { "answer_id": 6442930, "author": "Sam Dutton", "author_id": 51593, "author_profile": "https://Stackoverflow.com/users/51593", "pm_score": 5, "selected": false, "text": "<p>Note that the native Array.forEach method is now <a href=\"http://kangax.github.com/es5-compat-table/\">widely supported</a>.</p>\n" }, { "answer_id": 6443017, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 4, "selected": false, "text": "<p>The two are not the same when the array is sparse.</p>\n\n<pre><code>var array = [0, 1, 2, , , 5];\n\nfor (var k in array) {\n // Not guaranteed by the language spec to iterate in order.\n alert(k); // Outputs 0, 1, 2, 5.\n // Behavior when loop body adds to the array is unclear.\n}\n\nfor (var i = 0; i &lt; array.length; ++i) {\n // Iterates in order.\n // i is a number, not a string.\n alert(i); // Outputs 0, 1, 2, 3, 4, 5\n // Behavior when loop body modifies array is clearer.\n}\n</code></pre>\n" }, { "answer_id": 8826575, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 5, "selected": false, "text": "<p><strong>Updated answer for 2012</strong> current version of all major browsers - Chrome, Firefox, IE9, Safari and Opera support ES5's native array.forEach.</p>\n\n<p>Unless you have some reason to support IE8 natively (keeping in mind ES5-shim or Chrome frame can be provided to these users, which will provide a proper JS environment), it's cleaner to simply use the language's proper syntax:</p>\n\n<pre><code>myArray.forEach(function(item, index) {\n console.log(item, index);\n});\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow\">Full documentation for array.forEach() is at MDN.</a></p>\n" }, { "answer_id": 9669705, "author": "meloncholy", "author_id": 648802, "author_profile": "https://Stackoverflow.com/users/648802", "pm_score": 4, "selected": false, "text": "<p><strong>Using forEach to skip the prototype chain</strong> </p>\n\n<p>Just a quick addendum to <a href=\"https://stackoverflow.com/a/8826575/648802\">@nailer's answer above</a>, using forEach with Object.keys means you can avoid iterating over the prototype chain without having to use hasOwnProperty. </p>\n\n<pre><code>var Base = function () {\n this.coming = \"hey\";\n};\n\nvar Sub = function () {\n this.leaving = \"bye\";\n};\n\nSub.prototype = new Base();\nvar tst = new Sub();\n\nfor (var i in tst) {\n console.log(tst.hasOwnProperty(i) + i + tst[i]);\n}\n\nObject.keys(tst).forEach(function (val) {\n console.log(val + tst[val]);\n});\n</code></pre>\n" }, { "answer_id": 10364156, "author": "PazoozaTest Pazman", "author_id": 559724, "author_profile": "https://Stackoverflow.com/users/559724", "pm_score": 1, "selected": false, "text": "<p>Use the Array().forEach loop to take advantage of parallelism</p>\n" }, { "answer_id": 10504109, "author": "baptx", "author_id": 1176454, "author_profile": "https://Stackoverflow.com/users/1176454", "pm_score": 2, "selected": false, "text": "<p>Watch out!</p>\n\n<p>If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.</p>\n\n<p><a href=\"https://developer.mozilla.org/en/DOM/HTMLCollection\" rel=\"nofollow\">https://developer.mozilla.org/en/DOM/HTMLCollection</a></p>\n\n<p>If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!</p>\n\n<pre><code>var scriptTags = document.getElementsByTagName(\"script\");\n\nfor(var i = 0; i &lt; scriptTags.length; i++)\nalert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)\n\nfor(var i in scriptTags)\nalert(i); // Will print \"length\", \"item\" and \"namedItem\" in addition to your elements!\n</code></pre>\n\n<p>Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection:\n<a href=\"https://developer.mozilla.org/en/DOM/document.getElementsByTagName\" rel=\"nofollow\">https://developer.mozilla.org/en/DOM/document.getElementsByTagName</a></p>\n" }, { "answer_id": 12806509, "author": "Paulo Cheque", "author_id": 1163081, "author_profile": "https://Stackoverflow.com/users/1163081", "pm_score": 0, "selected": false, "text": "<p>Be careful!!!\nI am using Chrome 22.0 in Mac OS and I am having problem with the for each syntax.</p>\n\n<p>I do not know if this is a browser issue, javascript issue or some error in the code, but it is VERY strange. Outside of the object it works perfectly.</p>\n\n<pre><code>var MyTest = {\n a:string = \"a\",\n b:string = \"b\"\n};\n\nmyfunction = function(dicts) {\n for (var dict in dicts) {\n alert(dict);\n alert(typeof dict); // print 'string' (incorrect)\n }\n\n for (var i = 0; i &lt; dicts.length; i++) {\n alert(dicts[i]);\n alert(typeof dicts[i]); // print 'object' (correct, it must be {abc: \"xyz\"})\n }\n};\n\nMyObj = function() {\n this.aaa = function() {\n myfunction([MyTest]);\n };\n};\nnew MyObj().aaa(); // This does not work\n\nmyfunction([MyTest]); // This works\n</code></pre>\n" }, { "answer_id": 30140279, "author": "bormat", "author_id": 4237897, "author_profile": "https://Stackoverflow.com/users/4237897", "pm_score": 2, "selected": false, "text": "<p>A shorter and best code according to jsperf is</p>\n\n<pre><code>keys = Object.keys(obj);\nfor (var i = keys.length; i--;){\n value = obj[keys[i]];// or other action\n}\n</code></pre>\n" }, { "answer_id": 35293614, "author": "angelito", "author_id": 1823091, "author_profile": "https://Stackoverflow.com/users/1823091", "pm_score": 2, "selected": false, "text": "<p><strong>for(;;)</strong> is for <strong>Arrays</strong> : [20,55,33]</p>\n\n<p><strong>for..in</strong> is for <strong>Objects</strong> : {x:20,y:55:z:33}</p>\n" }, { "answer_id": 40723365, "author": "achecopar", "author_id": 2646253, "author_profile": "https://Stackoverflow.com/users/2646253", "pm_score": 0, "selected": false, "text": "<p>There is an important difference between both. The for-in iterates over the properties of an object, so when the case is an array it will not only iterate over its elements but also over the \"remove\" function it has.</p>\n\n<pre><code>for (var i = 0; i &lt; myArray.length; i++) { \n console.log(i) \n}\n\n//Output\n0\n1\n\nfor (var i in myArray) { \n console.log(i) \n} \n\n// Output\n0 \n1 \nremove\n</code></pre>\n\n<p>You could use the for-in with an <code>if(myArray.hasOwnProperty(i))</code>. Still, when iterating over arrays I always prefer to avoid this and just use the for(;;) statement.</p>\n" }, { "answer_id": 48063455, "author": "Yash Srivastava", "author_id": 5791180, "author_profile": "https://Stackoverflow.com/users/5791180", "pm_score": 0, "selected": false, "text": "<p>Although they both are very much alike there is a minor difference :</p>\n\n<pre><code>var array = [\"a\", \"b\", \"c\"];\narray[\"abc\"] = 123;\nconsole.log(\"Standard for loop:\");\nfor (var index = 0; index &lt; array.length; index++)\n{\n console.log(\" array[\" + index + \"] = \" + array[index]); //Standard for loop\n}\n</code></pre>\n\n<p>in this case the output is :</p>\n\n<p>STANDARD FOR LOOP:</p>\n\n<p>ARRAY[0] = A</p>\n\n<p>ARRAY[1] = B</p>\n\n<p>ARRAY[2] = C</p>\n\n<pre><code>console.log(\"For-in loop:\");\nfor (var key in array)\n{\n console.log(\" array[\" + key + \"] = \" + array[key]); //For-in loop output\n}\n</code></pre>\n\n<p>while in this case the output is:</p>\n\n<p>FOR-IN LOOP:</p>\n\n<p>ARRAY[1] = B</p>\n\n<p>ARRAY[2] = C</p>\n\n<p>ARRAY[10] = D</p>\n\n<p>ARRAY[ABC] = 123</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17375/" ]
Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why? Let's say we have an array of associative arrays: ``` var myArray = [{'key': 'value'}, {'key': 'value1'}]; ``` So we can iterate: ``` for (var i = 0; i < myArray.length; i++) ``` And: ``` for (var i in myArray) ``` I don't see a big difference. Are there any performance issues?
The choice should be based on the which idiom is best understood. An array is iterated using: ``` for (var i = 0; i < a.length; i++) //do stuff with a[i] ``` An object being used as an associative array is iterated using: ``` for (var key in o) //do stuff with o[key] ``` Unless you have earth shattering reasons, stick to the established pattern of usage.
242,913
<p>We can see in a directory files ordered by Name in Windows Explorer.</p> <p>If I try the same thing in the Windows command prompt it orders by name differently - <em>correctly</em>:</p> <pre><code>dir *.jpg /ON /B cubierta.jpg pag00.jpg pag06.jpg pag08.jpg pag09.jpg pag100.jpg pag101.jpg pag102.jpg pag103.jpg pag104.jpg pag105.jpg pag106.jpg pag107.jpg pag108.jpg pag109.jpg pag11.jpg, etc, etc, etc, ... </code></pre> <p>Is there a way to get <code>dir</code> to order by Name where it reads the numbers as a human would do?</p>
[ { "answer_id": 242925, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": -1, "selected": false, "text": "<p>No, there's no way to do this. Windows Explorer uses a different approach to handle this.</p>\n" }, { "answer_id": 242928, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 4, "selected": true, "text": "<p>Your best option (if possible) is to add enough leading zeros (two, in this case) to your smaller numbers so that the sort does come out as expected. </p>\n" }, { "answer_id": 242986, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 3, "selected": false, "text": "<p>Windows Explorer uses a special sorting function, <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-strcmplogicalw\" rel=\"nofollow noreferrer\">StrCmpLogicalW</a>, which is not used by <em>cmd.exe</em>, hence the differences in the output. You could write your own sorting program with it, though.</p>\n\n<p>You might also be interested in Michael Kaplan's entries on <a href=\"http://www.siao2.com/2005/01/05/346933.aspx\" rel=\"nofollow noreferrer\">this</a> <a href=\"http://www.siao2.com/2006/10/02/783066.aspx\" rel=\"nofollow noreferrer\">subject</a> (from Raymond Chen's <a href=\"https://web.archive.org/web/20100508052411/http://blogs.msdn.com/oldnewthing/archive/2008/09/11/8942473.aspx\" rel=\"nofollow noreferrer\">suggestion box</a>).</p>\n" }, { "answer_id": 243575, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>4NT/TCC/TC from <a href=\"http://jpsoft.com\" rel=\"nofollow noreferrer\">JPSoft</a> use natural sort order by default. Alternatively, if you have access to a GNU <code>sort</code> program, such as the <a href=\"http://cygwin.org\" rel=\"nofollow noreferrer\">Cygwin tools</a>, you can do something like <code>ls -1 | /&lt;cygwin&gt;bin/sort -g</code> or <code>dir /b | \\cygwin\\bin\\sort -g</code>; that will give you the filenames in natural sort order.</p>\n<p>If you are constrained to tools that are native to Windows, you can try the <a href=\"http://msdn.microsoft.com/en-us/library/ms950396.aspx\" rel=\"nofollow noreferrer\">Windows Scripting tools</a> and do something like use a <a href=\"https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filesystemobject-object\" rel=\"nofollow noreferrer\">FileSystemObject</a> to get the filenames, and regular expressions to extract the numeric part of the filenames to use as keys in a Dictionary object. I'll leave the actual coding as an exercise to the reader :)</p>\n" }, { "answer_id": 352087, "author": "ian_scho", "author_id": 15530, "author_profile": "https://Stackoverflow.com/users/15530", "pm_score": -1, "selected": false, "text": "<p>I use a program called ImageMagick to convert my 200MB PDF files to JPG. At the end of the lengthy process it serializes all of the files in numerical order... So basically the file creation date increases in value slightly as each file is being written to the hard drive. Thus either of the following two batch file commands will write the files in the 'correct' order:</p>\n<pre class=\"lang-bat prettyprint-override\"><code>dir *.jpg /ODN /B &gt; files.txt\n\nfor /f &quot;tokens=*&quot; %%a in ('dir *.jpg /ODN /B') do (\n echo ^&lt;page^&gt;%%a^&lt;/page^&gt; &gt;&gt;pages.xml.fragment\n)\n</code></pre>\n<p>Thus the <code>dir *.jpg /OD</code> command orders the directory content by ascending (creation?) date, and we can completely ignore the actual file name.</p>\n" }, { "answer_id": 51874902, "author": "phuclv", "author_id": 995714, "author_profile": "https://Stackoverflow.com/users/995714", "pm_score": 1, "selected": false, "text": "<p>That's called a <a href=\"https://en.wikipedia.org/wiki/Natural_sort_order\" rel=\"nofollow noreferrer\">natural sort</a>. Currently there are no built-in command line tools that can sort naturally. If you want please <a href=\"https://aka.ms/AA21wr4\" rel=\"nofollow noreferrer\">vote for the feature</a> to make Microsoft change their mind</p>\n<p>This however can be simulated with a regex replacement to pad zeros to make numbers have the same length. That way a <a href=\"https://en.wikipedia.org/wiki/Lexicographic_order\" rel=\"nofollow noreferrer\">lexicographic sort</a> is equivalent to a natural sort. On Windows you can use Jscript and VBS to do that. But the easiest way is using powershell. You can call it from cmd.exe like this</p>\n<pre class=\"lang-bat prettyprint-override\"><code>powershell -Command &quot;(Get-ChildItem | Sort-Object { [regex]::Replace($_.Name, '\\d+', { $args[0].Value.PadLeft(20) }) }).Name&quot;\n</code></pre>\n<p>Of course you'll need to change the number in <code>PadLeft(20)</code> if your files contains a longer series of digits</p>\n<p><a href=\"https://stackoverflow.com/q/5427506/995714\">How to sort by file name the same way Windows Explorer does?</a></p>\n<p>A native batch solution can be found in\n<a href=\"https://stackoverflow.com/q/19297935/995714\">Naturally Sort Files in Batch</a> if your files have only a single number at the end</p>\n<pre class=\"lang-bat prettyprint-override\"><code>@echo off\nsetlocal enabledelayedexpansion\nfor %%a in (*.txt) do (\n set num=00000000000000000000%%a\n set num=!num:~-20!\n set $!num!=%%a\n)\nfor /f &quot;tokens=1,* delims==&quot; %%a in ('set $0') do echo %%b\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15530/" ]
We can see in a directory files ordered by Name in Windows Explorer. If I try the same thing in the Windows command prompt it orders by name differently - *correctly*: ``` dir *.jpg /ON /B cubierta.jpg pag00.jpg pag06.jpg pag08.jpg pag09.jpg pag100.jpg pag101.jpg pag102.jpg pag103.jpg pag104.jpg pag105.jpg pag106.jpg pag107.jpg pag108.jpg pag109.jpg pag11.jpg, etc, etc, etc, ... ``` Is there a way to get `dir` to order by Name where it reads the numbers as a human would do?
Your best option (if possible) is to add enough leading zeros (two, in this case) to your smaller numbers so that the sort does come out as expected.
242,914
<p>Is it possible in plain JPA or JPA+Hibernate extensions to declare a composite key, where an element of the composite key is a sequence?</p> <p>This is my composite class:</p> <pre><code>@Embeddable public class IntegrationEJBPk implements Serializable { //... @ManyToOne(cascade = {}, fetch = FetchType.EAGER) @JoinColumn(name = "APPLICATION") public ApplicationEJB getApplication() { return application; } @Column(name = "ENTITY", unique = false, nullable = false, insertable = true, updatable = true) public String getEntity() { return entity; } @GeneratedValue(strategy = GenerationType.AUTO, generator = "INTEGRATION_ID_GEN") @SequenceGenerator(name = "INTEGRATION_ID_GEN", sequenceName = "OMP_INTEGRATION_CANONICAL_SEQ") @Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getCanonicalId() { return canonicalId; } @Column(name = "NATIVE_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeId() { return nativeId; } @Column(name = "NATIVE_KEY", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeKey() { return nativeKey; } //... } </code></pre> <p>I already supply the values for <code>application</code>, <code>entity</code>, <code>nativeId</code> and <code>nativeKey</code>. I want to construct an entity like the one below:</p> <pre><code>IntegrationEJB i1 = new IntegrationEJB(); i1.setIntegrationId(new IntegrationEJBPk()); i1.getIntegrationId().setApplication(app1); i1.getIntegrationId().setEntity("Entity"); i1.getIntegrationId().setNativeId("Nid"); i1.getIntegrationId().setNativeKey("NK"); </code></pre> <p>And when I call <code>em.persist(i1</code>), I want that the <code>canonicalId</code> is generated and the integration is inserted.</p> <p>Is this possible? If so, what's the simple way? (I prefer not to use application-provided keys or native sql).</p>
[ { "answer_id": 244051, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 1, "selected": false, "text": "<p>Try like this:</p>\n\n<pre><code>@TableGenerator(name = \"canonicalKeys\", allocationSize = 1, initialValue = 1)\n@GeneratedValue(strategy = GenerationType.TABLE, generator = \"canonicalKeys\")\n@Column(name = \"CANONICAL_ID\", unique = false, nullable = false, insertable = true, updatable = true)\npublic String getCanonicalId() {\n return canonicalId;\n}\n</code></pre>\n\n<p>In this way instead of using a sequence you can use a table.</p>\n" }, { "answer_id": 583533, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 3, "selected": true, "text": "<p>I believe that this is not possible with plain JPA.</p>\n" }, { "answer_id": 697578, "author": "Petriborg", "author_id": 2815, "author_profile": "https://Stackoverflow.com/users/2815", "pm_score": 1, "selected": false, "text": "<p>I notice that it appears your building a composite primary key like this <a href=\"http://boris.kirzner.info/blog/archives/2008/07/19/hibernate-annotations-the-many-to-many-association-with-composite-key/\" rel=\"nofollow noreferrer\">example</a>. While I was poking at a similar problem in my own database I wondered if maybe you could call the sql directly like:</p>\n\n<p><code>select nextval ('hibernate_sequence')</code></p>\n\n<p>I suppose that would be cheating though ;-)</p>\n" }, { "answer_id": 12888458, "author": "Glen Best", "author_id": 1528401, "author_profile": "https://Stackoverflow.com/users/1528401", "pm_score": 2, "selected": false, "text": "<p>Using @GeneratedValue for composite PKs is not specified withi JPA 2 spec.</p>\n\n<p>From the JPA spec:</p>\n\n<blockquote>\n <p>11.1.17 GeneratedValue Annotation </p>\n \n <p>The GeneratedValue annotation provides for the specification of\n generation strategies for the values of primary keys. The\n GeneratedValue annotation may be applied to a primary key property or\n field of an entity or mapped superclass in conjunction with the Id\n annotation.[97] The use of the GeneratedValue annotation is only\n required to be supported for simple primary keys. Use of the\n GeneratedValue annotation is not supported for derived primary keys.</p>\n</blockquote>\n\n<p>Note that under a different scenario, you can have a parent entity with a simple PK (@Id) that uses @GeneratedValue, and then have a child entity that has a composite PK that includes the generated Id from the parent, plus another column. </p>\n\n<ul>\n<li>Give the child a @ManyToOne relationship to the parent entity, so that it inherits the generated ID in a FK column. </li>\n<li>Then give the child a composite PK, via @IdClass specified against the entity, plus two @Id columns within the entity.</li>\n</ul>\n\n<blockquote>\n<pre><code>@Entity\npublic class ParentEntity {\n</code></pre>\n</blockquote>\n\n<pre><code> @Id\n @GenerateValue(IDENTITY) // If using DB auto-increment or similar\n int id;\n\n // ...\n}\n</code></pre>\n\n<blockquote>\n<pre><code>@Entity\n@IdClass(ChildId.class)\npublic class ChildEntity {\n // The child table will have a composite PK:\n // (parent_ID, child_name)\n @Id \n @ManyToOne\n int parentEntity;\n</code></pre>\n</blockquote>\n\n<pre><code> @Id\n String childName;\n\n String favoriteColor; // plus other columns\n\n // ...\n\n}\n</code></pre>\n\n<blockquote>\n<pre><code>// child Id attributes have the same name as the child entity\n// however the types change to match the underlying PK attributes \n// (change ParentEntity to int)\n public class ChildId implements Serializable {\n</code></pre>\n</blockquote>\n\n<pre><code> int parentEntity;\n String childName;\n\n public ChildId() { //... }\n\n // Add extra constructor &amp; remove setter methods so Id objects are immutable\n public ChildId(int parentEntity, String childName) { //... }\n\n\n public int getParentEntity() { //... }\n // make Id objects immutable:\n // public void setParentEntity(int parentEntity) { //... }\n public String getChildName() { //... }\n // public void setChildName(String childName) { //... }\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22992/" ]
Is it possible in plain JPA or JPA+Hibernate extensions to declare a composite key, where an element of the composite key is a sequence? This is my composite class: ``` @Embeddable public class IntegrationEJBPk implements Serializable { //... @ManyToOne(cascade = {}, fetch = FetchType.EAGER) @JoinColumn(name = "APPLICATION") public ApplicationEJB getApplication() { return application; } @Column(name = "ENTITY", unique = false, nullable = false, insertable = true, updatable = true) public String getEntity() { return entity; } @GeneratedValue(strategy = GenerationType.AUTO, generator = "INTEGRATION_ID_GEN") @SequenceGenerator(name = "INTEGRATION_ID_GEN", sequenceName = "OMP_INTEGRATION_CANONICAL_SEQ") @Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getCanonicalId() { return canonicalId; } @Column(name = "NATIVE_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeId() { return nativeId; } @Column(name = "NATIVE_KEY", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeKey() { return nativeKey; } //... } ``` I already supply the values for `application`, `entity`, `nativeId` and `nativeKey`. I want to construct an entity like the one below: ``` IntegrationEJB i1 = new IntegrationEJB(); i1.setIntegrationId(new IntegrationEJBPk()); i1.getIntegrationId().setApplication(app1); i1.getIntegrationId().setEntity("Entity"); i1.getIntegrationId().setNativeId("Nid"); i1.getIntegrationId().setNativeKey("NK"); ``` And when I call `em.persist(i1`), I want that the `canonicalId` is generated and the integration is inserted. Is this possible? If so, what's the simple way? (I prefer not to use application-provided keys or native sql).
I believe that this is not possible with plain JPA.
242,941
<p>I have a main canvas 'blackboard' in a panel, this canvas has itself several children, like a toolbar (tiles), a label and some skinning.</p> <p>The problem is that when I move to the rectangle tool and I start drawing rectangles if I want to change the tool when I click on an other tool such as 'circle' or 'select' the button won't catch the click event, instead the canvas will catch the mouse down and start drawing.</p> <p>Just like on the picture. So I am unable to change tool once I start drawing.</p> <p><a href="http://www.freeimagehosting.net/uploads/397a7cd49e.png" rel="nofollow noreferrer">alt text http://www.freeimagehosting.net/uploads/397a7cd49e.png</a></p> <p>How could I not make the canvas react when it is on a tool, or how could I make the button catch the click first and tell the canvas no to do draw anything.</p> <p>Of course I could just put the toolbar somewhere else not on the canvas, but since space is important I would like the buttons to be on the canvas.</p> <p>I am open to any suggestions.</p> <p>=== Here are some code to show how it works internally. ===</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;mx:Panel xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; xmlns:degrafa=&quot;http://www.degrafa.com/2007&quot; xmlns:comp=&quot;org.foo.bar.view.components.*&quot; layout=&quot;absolute&quot; title=&quot;Tableau&quot;&gt; &lt;mx:Script&gt; &lt;![CDATA[ import org.edorado.edoboard.ApplicationFacade; ]]&gt; &lt;/mx:Script&gt; &lt;mx:Canvas id=&quot;blackBoard&quot;&gt; &lt;degrafa:Surface id=&quot;boardSurfaceContainer&quot;&gt; skinning &lt;/degrafa:Surface&gt; &lt;!-- Tool bar --&gt; &lt;comp:ToolbarView id = &quot;toolbar&quot; name = &quot;toolbar&quot; verticalScrollPolicy=&quot;off&quot; horizontalScrollPolicy=&quot;off&quot; bottom=&quot;5&quot; right=&quot;5&quot; top=&quot;5&quot; direction=&quot;vertical&quot; width=&quot;30&quot; /&gt; &lt;mx:Label x=&quot;10&quot; y=&quot;10&quot; text=&quot;Label&quot; color=&quot;#FFFFFF&quot; id=&quot;lbl&quot;/&gt; &lt;/mx:Canvas&gt; &lt;/mx:Panel&gt; </code></pre> <p>The toolbar is a list of buttons contained in a tile. The canvas 'blackboard' is linked to several events handling, in particular mouse up down and move for drawing shapes.</p> <pre><code>... boardCanvas.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown); boardCanvas.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp); ... private function handleMouseDown(event:MouseEvent):void { // Get the current mouse location which may be adjusted to the grid var selectPoint:Point = boardCanvas.globalToLocal(new Point(event.stageX, event.stageY)); startPoint = snapPoint(selectPoint.x, selectPoint.y); boardView.lbl.text = '(' + startPoint.x +',' + startPoint.y + ')'; .... </code></pre> <p>The toolbar also listen to clicks</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;mx:Tile xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.charts.BubbleChart; import org.edorado.edoboard.view.components.shapes.*; public static const TOOL_CHANGE:String = &quot;toolChange&quot;; public static const TEXT_TOOL:String = &quot;textTool&quot;; public static const SELECT_TOOL:String = &quot;selectTool&quot;; public static const RECTANGLE_TOOL:String = &quot;rectangleTool&quot;; private var b:Button = null; private function handleButtonClick(event:MouseEvent):void { trace(&quot;CLICKED TOOL&quot;); // selectButton.dispatchEvent(new Event(TOOL_CHANGE, true, true)) b = event.target as Button; b.dispatchEvent(new Event(TOOL_CHANGE, true, true)); } ]]&gt; &lt;/mx:Script&gt; &lt;!-- Use class facotry ? --&gt; &lt;mx:Button id=&quot;selectButton&quot; name=&quot;{SELECT_TOOL}&quot; selectedUpSkin=&quot;assets.skins.ToolButtonSkin&quot; width=&quot;30&quot; height=&quot;30&quot; styleName=&quot;selectButton&quot; toolTip=&quot;selection&quot; click=&quot;handleButtonClick(event); &quot; /&gt; &lt;mx:Button id=&quot;textButton&quot; name = &quot;{TEXT_TOOL}&quot; selectedUpSkin=&quot;assets.skins.ToolButtonSkin&quot; width=&quot;30&quot; height=&quot;30&quot; styleName=&quot;textButton&quot; toolTip=&quot;text&quot; click=&quot;handleButtonClick(event);&quot; /&gt; &lt;mx:Button id=&quot;rectButton&quot; name = &quot;{RECTANGLE_TOOL}&quot; selectedUpSkin=&quot;assets.skins.ToolButtonSkin&quot; width=&quot;30&quot; height=&quot;30&quot; styleName=&quot;rectButton&quot; toolTip=&quot;rectButton&quot; click=&quot;handleButtonClick(event);&quot; /&gt; &lt;/mx:Tile&gt; </code></pre>
[ { "answer_id": 242934, "author": "andy", "author_id": 32033, "author_profile": "https://Stackoverflow.com/users/32033", "pm_score": 1, "selected": false, "text": "<p>Portability... though C# isn't really know as lingua franca if you're going for portable, so this might be moot for your perspective?</p>\n" }, { "answer_id": 242953, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "<p>If your app is running on a 64 bit CPU then probably not much difference at all.</p>\n\n<p>On a 32 bit CPU, a 64 bit integer will be more processor intensive to perfom calculations with.</p>\n\n<p>There is also the obvious memory use.</p>\n" }, { "answer_id": 242957, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Only you can answer how much of a concern the space in your cache is. If that's the cache key and you've got some huge blob as the value, then adding an extra 4 bytes to the key isn't going to make much difference. If <em>all</em> you're storing is the ID, then obviously it's going to have a more proportionally significant effect.</p>\n\n<p>How much memory is spent storing your IDs at the moment?</p>\n" }, { "answer_id": 242959, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 3, "selected": true, "text": "<p>Well, int64 uses 8 byte of memory storage, while int uses 4 byte... however, you pointed out most of the disadvantages already. Of course calculations performed will also be slower on many systems (a 64 bit system running in 64 bit mode can perform operations on 64 bit as fast as on 32 bit, but a 32 bit system needs to perform extra work, that means adding two 64 bit numbers is performed by two 32 bit adds plus some extra code - other math operations will be equally broken down into 32 bit operations). However unless you store millions of these numbers and perform tons of operations with them, I doubt you will see any performance difference, though, neither in CPU time nor in memory.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32032/" ]
I have a main canvas 'blackboard' in a panel, this canvas has itself several children, like a toolbar (tiles), a label and some skinning. The problem is that when I move to the rectangle tool and I start drawing rectangles if I want to change the tool when I click on an other tool such as 'circle' or 'select' the button won't catch the click event, instead the canvas will catch the mouse down and start drawing. Just like on the picture. So I am unable to change tool once I start drawing. [alt text http://www.freeimagehosting.net/uploads/397a7cd49e.png](http://www.freeimagehosting.net/uploads/397a7cd49e.png) How could I not make the canvas react when it is on a tool, or how could I make the button catch the click first and tell the canvas no to do draw anything. Of course I could just put the toolbar somewhere else not on the canvas, but since space is important I would like the buttons to be on the canvas. I am open to any suggestions. === Here are some code to show how it works internally. === ``` <?xml version="1.0" encoding="utf-8"?> <mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:degrafa="http://www.degrafa.com/2007" xmlns:comp="org.foo.bar.view.components.*" layout="absolute" title="Tableau"> <mx:Script> <![CDATA[ import org.edorado.edoboard.ApplicationFacade; ]]> </mx:Script> <mx:Canvas id="blackBoard"> <degrafa:Surface id="boardSurfaceContainer"> skinning </degrafa:Surface> <!-- Tool bar --> <comp:ToolbarView id = "toolbar" name = "toolbar" verticalScrollPolicy="off" horizontalScrollPolicy="off" bottom="5" right="5" top="5" direction="vertical" width="30" /> <mx:Label x="10" y="10" text="Label" color="#FFFFFF" id="lbl"/> </mx:Canvas> </mx:Panel> ``` The toolbar is a list of buttons contained in a tile. The canvas 'blackboard' is linked to several events handling, in particular mouse up down and move for drawing shapes. ``` ... boardCanvas.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown); boardCanvas.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp); ... private function handleMouseDown(event:MouseEvent):void { // Get the current mouse location which may be adjusted to the grid var selectPoint:Point = boardCanvas.globalToLocal(new Point(event.stageX, event.stageY)); startPoint = snapPoint(selectPoint.x, selectPoint.y); boardView.lbl.text = '(' + startPoint.x +',' + startPoint.y + ')'; .... ``` The toolbar also listen to clicks ``` <?xml version="1.0" encoding="utf-8"?> <mx:Tile xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script> <![CDATA[ import mx.charts.BubbleChart; import org.edorado.edoboard.view.components.shapes.*; public static const TOOL_CHANGE:String = "toolChange"; public static const TEXT_TOOL:String = "textTool"; public static const SELECT_TOOL:String = "selectTool"; public static const RECTANGLE_TOOL:String = "rectangleTool"; private var b:Button = null; private function handleButtonClick(event:MouseEvent):void { trace("CLICKED TOOL"); // selectButton.dispatchEvent(new Event(TOOL_CHANGE, true, true)) b = event.target as Button; b.dispatchEvent(new Event(TOOL_CHANGE, true, true)); } ]]> </mx:Script> <!-- Use class facotry ? --> <mx:Button id="selectButton" name="{SELECT_TOOL}" selectedUpSkin="assets.skins.ToolButtonSkin" width="30" height="30" styleName="selectButton" toolTip="selection" click="handleButtonClick(event); " /> <mx:Button id="textButton" name = "{TEXT_TOOL}" selectedUpSkin="assets.skins.ToolButtonSkin" width="30" height="30" styleName="textButton" toolTip="text" click="handleButtonClick(event);" /> <mx:Button id="rectButton" name = "{RECTANGLE_TOOL}" selectedUpSkin="assets.skins.ToolButtonSkin" width="30" height="30" styleName="rectButton" toolTip="rectButton" click="handleButtonClick(event);" /> </mx:Tile> ```
Well, int64 uses 8 byte of memory storage, while int uses 4 byte... however, you pointed out most of the disadvantages already. Of course calculations performed will also be slower on many systems (a 64 bit system running in 64 bit mode can perform operations on 64 bit as fast as on 32 bit, but a 32 bit system needs to perform extra work, that means adding two 64 bit numbers is performed by two 32 bit adds plus some extra code - other math operations will be equally broken down into 32 bit operations). However unless you store millions of these numbers and perform tons of operations with them, I doubt you will see any performance difference, though, neither in CPU time nor in memory.
242,961
<p>I had a method with a lot of persistence calls that used a nHibernate session, it worked, was alright. But I needed to refactor this method, extracting a method from a content inside a loop, for multithread reasons. Then I created an class with this method. It is like a normal refactoring, but the nHibernate session inside this method call is broken, without context, I didn't finalize it at any moment. <strong>Has nHibernate problems with multithreading?</strong> Even when I have only one more thread executing, I have the same problem.</p> <p>I use nHibernate Session through a SessionFactory and Façade pattern, it means, the session is not a field of these objects, it is global at SessionFactory.</p> <hr> <p>Making it a little bit more clear:</p> <p><strong>BEFORE:</strong></p> <pre><code>Method() { ... persistence calls foreach(Thing..) { ...persistence calls for each thing (1) } ... } </code></pre> <p><strong>AFTER:</strong></p> <pre><code>Method() { ... persistence calls foreach(Thing..) { create a thingResolver object with some data open a new thread with thingResolver.Method (1) starts this thread } .. waits for finishing threads and continues } </code></pre> <hr> <p>Our nHibernate Session Factory is thread-aware, and stores/retrieves nHibernate session per thread. It is working nicely now ;)</p>
[ { "answer_id": 242983, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 5, "selected": true, "text": "<p>Sessions are <strong>not thread safe</strong> in NHibernate <strong>by design</strong>.\nSo it should be ok as long as you have a <em>session used by only one thread</em>.</p>\n\n<p>I'm not sure what you're thingResolver does, but if it does some persistance calls on <em>the same</em> session you've created in the originating thread - this most probably the cause of your problems, you could create a separate session in your new thread so that it would be a session per thread if my assumption is true.</p>\n\n<p>NHibernate reference has it in section 10.2</p>\n\n<p><a href=\"http://nhibernate.info/doc/nh/en/index.html#transactions\" rel=\"noreferrer\">http://nhibernate.info/doc/nh/en/index.html#transactions</a></p>\n" }, { "answer_id": 4636142, "author": "Hace", "author_id": 18703, "author_profile": "https://Stackoverflow.com/users/18703", "pm_score": 0, "selected": false, "text": "<p>You can have one NHibernate SessionFactory for multiple threads as long as you have a separate NHibernate session for each thread.</p>\n\n<p>here is an example that will give exceptions because it uses the same session for each thread:</p>\n\n<p><a href=\"https://forum.hibernate.org/viewtopic.php?p=2373236&amp;sid=db537baa5a57e3968abdda5cceec2a24\" rel=\"nofollow\">https://forum.hibernate.org/viewtopic.php?p=2373236&amp;sid=db537baa5a57e3968abdda5cceec2a24</a></p>\n\n<p>The solution is to store sessions on the LocaldataStoreSlot, that way you can have a session-per-request model.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21668/" ]
I had a method with a lot of persistence calls that used a nHibernate session, it worked, was alright. But I needed to refactor this method, extracting a method from a content inside a loop, for multithread reasons. Then I created an class with this method. It is like a normal refactoring, but the nHibernate session inside this method call is broken, without context, I didn't finalize it at any moment. **Has nHibernate problems with multithreading?** Even when I have only one more thread executing, I have the same problem. I use nHibernate Session through a SessionFactory and Façade pattern, it means, the session is not a field of these objects, it is global at SessionFactory. --- Making it a little bit more clear: **BEFORE:** ``` Method() { ... persistence calls foreach(Thing..) { ...persistence calls for each thing (1) } ... } ``` **AFTER:** ``` Method() { ... persistence calls foreach(Thing..) { create a thingResolver object with some data open a new thread with thingResolver.Method (1) starts this thread } .. waits for finishing threads and continues } ``` --- Our nHibernate Session Factory is thread-aware, and stores/retrieves nHibernate session per thread. It is working nicely now ;)
Sessions are **not thread safe** in NHibernate **by design**. So it should be ok as long as you have a *session used by only one thread*. I'm not sure what you're thingResolver does, but if it does some persistance calls on *the same* session you've created in the originating thread - this most probably the cause of your problems, you could create a separate session in your new thread so that it would be a session per thread if my assumption is true. NHibernate reference has it in section 10.2 <http://nhibernate.info/doc/nh/en/index.html#transactions>
242,975
<p>I have a problem, and was hoping I could rely on some of the experience here for advice and a push in the right direction. I have an MS Access file made by propietary software. I only want to take half the columns from this table, and import into new(not yet setup)mysql database.</p> <p>I have no idea how to do this or what the best way is. New data will be obtained each night, and again imported, as an automatic task.</p> <p>One of the columns in the access database is a url to a jpeg file, I want to download this file and import into the database as a BLOB type automatically.</p> <p>Is there a way to do this automatically? This will be on a windows machine, so perhaps it could be scripted with WSH?</p>
[ { "answer_id": 243069, "author": "Luis Melgratti", "author_id": 17032, "author_profile": "https://Stackoverflow.com/users/17032", "pm_score": 4, "selected": true, "text": "<p>This is a bash script <strong><em>linux</em></strong> example using <a href=\"http://mdbtools.sourceforge.net/\" rel=\"noreferrer\">mdbtools</a> for automatic extraction and import from a mdb file to mysql. </p>\n\n<pre><code>#!/bin/bash\n\nMDBFILE=\"Data.mdb\"\n\nOPTIONS=\"-H -D %y-%m-%d\"\nmdb-export $OPTIONS $MDBFILE TableName_1 &gt; output_1.txt\nmdb-export $OPTIONS $MDBFILE TableName_2 &gt; output_2.txt\n\nmdb-export $OPTIONS $MDBFILE TableName_n &gt; output_n.txt\n\nMYSQLOPTIONS=' --fields-optionally-enclosed-by=\" --fields-terminated-by=, -r '\nmysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_1.txt\nmysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_2.txt\nmysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_n.txt\n</code></pre>\n\n<p>You can use some others mysqlimport options: \n--delete: to delete previous Data from the target mysql table. \n--ignore: ignore duplicates\n--replace: replace if a duplicate is found</p>\n\n<p>It's not a windows solution but i Hope it helps.</p>\n" }, { "answer_id": 243098, "author": "Daniel Kreiseder", "author_id": 31406, "author_profile": "https://Stackoverflow.com/users/31406", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.dbtalk.net/mailing-database-mysql-win32/what-quickest-way-convert-access-136837.html\" rel=\"nofollow noreferrer\">http://www.dbtalk.net/mailing-database-mysql-win32/what-quickest-way-convert-access-136837.html</a></p>\n\n<p>Search for Kofler (He wrote a german Book, where Part of it was a mdb2sql converter)</p>\n\n<p>Here is a newer edition.\n<a href=\"http://www.amazon.de/Definitive-Guide-MySQL/dp/1590595351/ref=sr_1_3?ie=UTF8&amp;s=books-intl-de&amp;qid=1225197012&amp;sr=8-3\" rel=\"nofollow noreferrer\">http://www.amazon.de/Definitive-Guide-MySQL/dp/1590595351/ref=sr_1_3?ie=UTF8&amp;s=books-intl-de&amp;qid=1225197012&amp;sr=8-3</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
I have a problem, and was hoping I could rely on some of the experience here for advice and a push in the right direction. I have an MS Access file made by propietary software. I only want to take half the columns from this table, and import into new(not yet setup)mysql database. I have no idea how to do this or what the best way is. New data will be obtained each night, and again imported, as an automatic task. One of the columns in the access database is a url to a jpeg file, I want to download this file and import into the database as a BLOB type automatically. Is there a way to do this automatically? This will be on a windows machine, so perhaps it could be scripted with WSH?
This is a bash script ***linux*** example using [mdbtools](http://mdbtools.sourceforge.net/) for automatic extraction and import from a mdb file to mysql. ``` #!/bin/bash MDBFILE="Data.mdb" OPTIONS="-H -D %y-%m-%d" mdb-export $OPTIONS $MDBFILE TableName_1 > output_1.txt mdb-export $OPTIONS $MDBFILE TableName_2 > output_2.txt mdb-export $OPTIONS $MDBFILE TableName_n > output_n.txt MYSQLOPTIONS=' --fields-optionally-enclosed-by=" --fields-terminated-by=, -r ' mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_1.txt mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_2.txt mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_n.txt ``` You can use some others mysqlimport options: --delete: to delete previous Data from the target mysql table. --ignore: ignore duplicates --replace: replace if a duplicate is found It's not a windows solution but i Hope it helps.
243,021
<p>I have a VS2005 windows service where I have the need to use 'useUnsafeHeaderParsing' as per documentation from MSDN.</p> <p>As this is a library used within my windows service, I do not have a web.config to add httpwebrequest element and set useUnsafeHeaderParsing to true.</p> <p>How would I go about achieving this in code. I tried <a href="http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/ff098248-551c-4da9-8ba5-358a9f8ccc57/" rel="nofollow noreferrer">this</a> and <a href="http://wiki.lessthandot.com/index.php/Setting_unsafeheaderparsing" rel="nofollow noreferrer">this</a> but that was a no go.</p>
[ { "answer_id": 1359326, "author": "Blue Toque", "author_id": 116268, "author_profile": "https://Stackoverflow.com/users/116268", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what the trouble is. </p>\n\n<p>You don't use a web.config with a windows service, you use App.config (this gets moved into the deployment directory when you compile and renamed to .config</p>\n\n<p>I have used this setting in my App.Config for windows forms applications, web applications and many windows services without difficulty.</p>\n" }, { "answer_id": 3191915, "author": "Aaronontheweb", "author_id": 377476, "author_profile": "https://Stackoverflow.com/users/377476", "pm_score": 3, "selected": false, "text": "<p>You can enable unsafeHeaderParsing programmatically if you wish - here's a function I included in <a href=\"http://qdfeed.codeplex.com/\" rel=\"noreferrer\">Quick and Dirty Feed Parser</a> for turning that on - it's similar to some of the ones you linked to in your question:</p>\n\n<pre><code>private static bool SetUseUnsafeHeaderParsing(bool b)\n {\n Assembly a = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));\n if (a == null) return false;\n\n Type t = a.GetType(\"System.Net.Configuration.SettingsSectionInternal\");\n if (t == null) return false;\n\n object o = t.InvokeMember(\"Section\",\n BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });\n if (o == null) return false;\n\n FieldInfo f = t.GetField(\"useUnsafeHeaderParsing\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (f == null) return false;\n\n f.SetValue(o, b);\n\n return true;\n }\n</code></pre>\n\n<p>I've used that in production code and it works fine, regardless of what environment you're deployed in - as long as the System.Net.Configuration namespace is accessible via some assembly in the GAC you're good to go.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a VS2005 windows service where I have the need to use 'useUnsafeHeaderParsing' as per documentation from MSDN. As this is a library used within my windows service, I do not have a web.config to add httpwebrequest element and set useUnsafeHeaderParsing to true. How would I go about achieving this in code. I tried [this](http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/ff098248-551c-4da9-8ba5-358a9f8ccc57/) and [this](http://wiki.lessthandot.com/index.php/Setting_unsafeheaderparsing) but that was a no go.
You can enable unsafeHeaderParsing programmatically if you wish - here's a function I included in [Quick and Dirty Feed Parser](http://qdfeed.codeplex.com/) for turning that on - it's similar to some of the ones you linked to in your question: ``` private static bool SetUseUnsafeHeaderParsing(bool b) { Assembly a = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection)); if (a == null) return false; Type t = a.GetType("System.Net.Configuration.SettingsSectionInternal"); if (t == null) return false; object o = t.InvokeMember("Section", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { }); if (o == null) return false; FieldInfo f = t.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance); if (f == null) return false; f.SetValue(o, b); return true; } ``` I've used that in production code and it works fine, regardless of what environment you're deployed in - as long as the System.Net.Configuration namespace is accessible via some assembly in the GAC you're good to go.
243,022
<p>I'm building an application that needs to run through an XML feed but I'm having a little trouble with getting certain elements.</p> <p>I'm using the <a href="http://twitter.com/statuses/public_timeline.rss" rel="nofollow noreferrer">Twitter feed</a> and want to run through all the <code>&lt;item&gt;</code> elements. I can connect fine and get the content from the feed but I can't figure out how to select only the <code>item</code> elements when I'm loopuing through <code>reader.Read();</code>.</p> <p>Thanks for your help!</p>
[ { "answer_id": 1359326, "author": "Blue Toque", "author_id": 116268, "author_profile": "https://Stackoverflow.com/users/116268", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what the trouble is. </p>\n\n<p>You don't use a web.config with a windows service, you use App.config (this gets moved into the deployment directory when you compile and renamed to .config</p>\n\n<p>I have used this setting in my App.Config for windows forms applications, web applications and many windows services without difficulty.</p>\n" }, { "answer_id": 3191915, "author": "Aaronontheweb", "author_id": 377476, "author_profile": "https://Stackoverflow.com/users/377476", "pm_score": 3, "selected": false, "text": "<p>You can enable unsafeHeaderParsing programmatically if you wish - here's a function I included in <a href=\"http://qdfeed.codeplex.com/\" rel=\"noreferrer\">Quick and Dirty Feed Parser</a> for turning that on - it's similar to some of the ones you linked to in your question:</p>\n\n<pre><code>private static bool SetUseUnsafeHeaderParsing(bool b)\n {\n Assembly a = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));\n if (a == null) return false;\n\n Type t = a.GetType(\"System.Net.Configuration.SettingsSectionInternal\");\n if (t == null) return false;\n\n object o = t.InvokeMember(\"Section\",\n BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });\n if (o == null) return false;\n\n FieldInfo f = t.GetField(\"useUnsafeHeaderParsing\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (f == null) return false;\n\n f.SetValue(o, b);\n\n return true;\n }\n</code></pre>\n\n<p>I've used that in production code and it works fine, regardless of what environment you're deployed in - as long as the System.Net.Configuration namespace is accessible via some assembly in the GAC you're good to go.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
I'm building an application that needs to run through an XML feed but I'm having a little trouble with getting certain elements. I'm using the [Twitter feed](http://twitter.com/statuses/public_timeline.rss) and want to run through all the `<item>` elements. I can connect fine and get the content from the feed but I can't figure out how to select only the `item` elements when I'm loopuing through `reader.Read();`. Thanks for your help!
You can enable unsafeHeaderParsing programmatically if you wish - here's a function I included in [Quick and Dirty Feed Parser](http://qdfeed.codeplex.com/) for turning that on - it's similar to some of the ones you linked to in your question: ``` private static bool SetUseUnsafeHeaderParsing(bool b) { Assembly a = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection)); if (a == null) return false; Type t = a.GetType("System.Net.Configuration.SettingsSectionInternal"); if (t == null) return false; object o = t.InvokeMember("Section", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { }); if (o == null) return false; FieldInfo f = t.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance); if (f == null) return false; f.SetValue(o, b); return true; } ``` I've used that in production code and it works fine, regardless of what environment you're deployed in - as long as the System.Net.Configuration namespace is accessible via some assembly in the GAC you're good to go.
243,027
<p>I've got this ASP.NET drop down control that displays other textbox controls when the value is not UK (this is to help find UK addresses using postcodes). When UK is reselected I will like to hide the other controls. I've enabled view state and AutoPostBack to true. I have an <code>onSelectedIndexChanged</code> event that only gets fired once (when the dropdown value changes to a different country as by default it's UK).</p> <p>I'll like to have the <code>OnSelectedIndexChanged</code> to fire every time the value is different, but this isn't the case.</p> <p>P.S. Here's the code snippet.</p> <pre><code>&lt;asp:DropDownList runat="server" ID="Country2" AutoPostBack="True" OnSelectedIndexChanged="Country2_SelectedIndexChanged" DataSource="&lt;%# RegionList %&gt;" DataTextField="Name" DataValueField="Code" CssClass="dropdown country"&gt;&lt;/asp:DropDownList&gt; protected void Country2_SelectedIndexChanged(object sender, EventArgs e) { DropDownList d = (DropDownList)sender; addressEntry.CountryPrePostBack_SelectedIndexChanged(d.SelectedItem.Value); } </code></pre>
[ { "answer_id": 243047, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>How are you attaching the event? Are you using doing it code behind like:</p>\n\n<pre><code>this.dropDownList.SelectedIndexChanged += new EventHandler(dropDownList_SelectedIndexChanged);\n</code></pre>\n\n<p>Or are you assigning it in the ASPX/ ASCX?</p>\n\n<p>If it's the former make sure that you are not assigning it within a <code>!IsPostback</code> condition, you need to ensure that the event it added every postback.</p>\n\n<p>Have you tried using the debugger to see whether a postback is actually occuring in subsiquent events? It could be that you're newly added controls are causing a validation failure, if you are using validators make sure you set the drop down list to <code>CauseValidation = false</code> so it'll postback every time.</p>\n" }, { "answer_id": 271024, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 0, "selected": false, "text": "<p>I can only think of two questions to ask.</p>\n\n<p>1.) Are you populating (binding) to the list on the page_load event? if so then you need to only do this the first time the page loads. When you bind to the control (or other controls) it will reset the selected index. If viewstate is enabled then it will keep the original list.\n2.) Now I'm going ot assume that the above is already true so that would lead me to ask if viewstate is enable fro the parent of this page. If you turn trace on and look at the page control list you should be able to see the viewstate size for this particular item. If it's got a value then you know you are setting viewstate correctly. If not then work your way up the parent controls to see where viewstate ends. </p>\n\n<p>Viewstate is necessary to detect a postback so it's important to see that it's working properly.</p>\n\n<p>Now I’m a VB.net programmer and I noticed that in your sub there doesn’t appear to be a handler there.\nIn vb.net we would normally see something like </p>\n\n<pre><code>Private Sub LinkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkButton.Click\n</code></pre>\n\n<p>The only other way tot get the event to fire properly is to include it in the button but you seem to be doing that correctly already. You might want to try it in the manner that I’ve put above and see if that changes anything for you.</p>\n\n<p>Andrew</p>\n" }, { "answer_id": 293936, "author": "marclar", "author_id": 28118, "author_profile": "https://Stackoverflow.com/users/28118", "pm_score": 1, "selected": false, "text": "<p>I've seen similar behavior when a javascript error has been introduced upon the first postback.</p>\n\n<p>I think I saw this when the first postback caused a new div to be displayed (using javascript, not code-behind), and the div wasn't in the HTML. So the \"show(div)\" javascript referred to a missing object.</p>\n\n<p>Granted, a very specific case, but I'd recommend checking for any js errors after the first postback.</p>\n\n<p>Michael</p>\n" }, { "answer_id": 1212886, "author": "zakster82", "author_id": 144721, "author_profile": "https://Stackoverflow.com/users/144721", "pm_score": 2, "selected": false, "text": "<p>Every time I've ever had something like this happen it's been because of validation controls. Do those additional textboxes have validators attached to them that could be suppressing the postback? A quick way to tell would be to set CausesValidation=\"false\" on the dropdownlist.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got this ASP.NET drop down control that displays other textbox controls when the value is not UK (this is to help find UK addresses using postcodes). When UK is reselected I will like to hide the other controls. I've enabled view state and AutoPostBack to true. I have an `onSelectedIndexChanged` event that only gets fired once (when the dropdown value changes to a different country as by default it's UK). I'll like to have the `OnSelectedIndexChanged` to fire every time the value is different, but this isn't the case. P.S. Here's the code snippet. ``` <asp:DropDownList runat="server" ID="Country2" AutoPostBack="True" OnSelectedIndexChanged="Country2_SelectedIndexChanged" DataSource="<%# RegionList %>" DataTextField="Name" DataValueField="Code" CssClass="dropdown country"></asp:DropDownList> protected void Country2_SelectedIndexChanged(object sender, EventArgs e) { DropDownList d = (DropDownList)sender; addressEntry.CountryPrePostBack_SelectedIndexChanged(d.SelectedItem.Value); } ```
Every time I've ever had something like this happen it's been because of validation controls. Do those additional textboxes have validators attached to them that could be suppressing the postback? A quick way to tell would be to set CausesValidation="false" on the dropdownlist.
243,035
<p>I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products.</p> <p><strong>EDIT:</strong> To make it harder, I have another requirement. I have the bought table, the sold table, but I also have the products table. I want a list of all the products, and I want to know the quantity available of each product. The problem with the current answers is that they only return the products that we have sold or bought already. I want all the products.</p>
[ { "answer_id": 243063, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 4, "selected": true, "text": "<p>Try this</p>\n\n<pre><code>\nSELECT inv_t.product_id, inventory_total-nvl(sales_total,0)\nFROM \n (SELECT product_id, sum(quantity) as inventory_total\n FROM inventory\n GROUP BY product_id) inv_t LEFT OUTER JOIN\n (SELECT product_id, count(*) AS sales_total \n FROM sales \n GROUP BY product_id) sale_t\n ON (inv_t.product_id = sale_t.product_id)\n\n</code></pre>\n\n<p>This is a better solution than a few of the other ones posted, which do not account for the fact that some products may not have any corresponding rows in the sales table. You want to make sure that such products also show up in the results.</p>\n\n<p>NVL is an Oracle-specific function that returns the value of the first argument, unless it's null, in which case it returns the value of the second argument. There are equivalent functions in all commercial DBMSes -- you can use CASE in MySQL to the same effect.</p>\n" }, { "answer_id": 243066, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT product AS prd, \nSUM(quantity) - \n IFNULL((SELECT COUNT(*)\n FROM sells\n WHERE product = prd \n GROUP BY product), 0)\nAS stock \nFROM bought\nGROUP BY product;\n</code></pre>\n\n<p>This one also works when quantity sold is 0.</p>\n" }, { "answer_id": 243271, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>I suggest making the \"inventory\" and \"sales\" tables into views, so that they are re-usable and the final query becomes very simple. Obviously the field and table names will need to change to match your schema.</p>\n\n<pre><code>--First view: list products and the purchased qty\ncreate or replace view product_purchases as\nselect\n product_id\n ,sum(purchased_qty) as purchased_qty\nfrom\n purchases\ngroup by\n product_id;\n\n--Second view: list of products and the amount sold \ncreate or replace view product_sales as\nselect\n product_id\n ,count(*) as sales_qty\nfrom\n sales\ngroup by\n product_id;\n\n--after creating those two views, run this query:\nselect\n pp.product_id\n ,pp.purchased_qty - ps.sales_qty as on_hand_qty\nfrom\n product_purchases pp\n ,product_sales ps\nwhere ps.product_id = pp.product_id;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products. **EDIT:** To make it harder, I have another requirement. I have the bought table, the sold table, but I also have the products table. I want a list of all the products, and I want to know the quantity available of each product. The problem with the current answers is that they only return the products that we have sold or bought already. I want all the products.
Try this ``` SELECT inv_t.product_id, inventory_total-nvl(sales_total,0) FROM (SELECT product_id, sum(quantity) as inventory_total FROM inventory GROUP BY product_id) inv_t LEFT OUTER JOIN (SELECT product_id, count(*) AS sales_total FROM sales GROUP BY product_id) sale_t ON (inv_t.product_id = sale_t.product_id) ``` This is a better solution than a few of the other ones posted, which do not account for the fact that some products may not have any corresponding rows in the sales table. You want to make sure that such products also show up in the results. NVL is an Oracle-specific function that returns the value of the first argument, unless it's null, in which case it returns the value of the second argument. There are equivalent functions in all commercial DBMSes -- you can use CASE in MySQL to the same effect.
243,045
<p>What does Java do with long variables while performing addition?</p> <p>Wrong version 1:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = speeds.size() + estimated; // time = 21; string concatenation?? </code></pre> <p>Wrong version 2:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = estimated + speeds.size(); // time = 12; string concatenation?? </code></pre> <p>Correct version:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long size = speeds.size(); long time = size + estimated; // time = 3; correct </code></pre> <p>I don't get it, why Java concatenate them.</p> <p>Can anybody help me, why two primitive variables are concatenated?</p> <p>Greetings, guerda</p>
[ { "answer_id": 243054, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>I suspect you're not seeing what you think you're seeing. Java doesn't do this.</p>\n\n<p>Please try to provide a <a href=\"http://pobox.com/~skeet/csharp/complete.html\" rel=\"nofollow noreferrer\">short but complete program</a> which demonstrates this. Here's a short but complete program which demonstrates correct behaviour, but with your \"wrong\" code (i.e. a counterexample).</p>\n\n<pre><code>import java.util.*;\n\npublic class Test\n{\n public static void main(String[] args)\n {\n Vector speeds = new Vector();\n speeds.add(\"x\");\n speeds.add(\"y\");\n\n long estimated = 1l;\n long time = speeds.size() + estimated;\n System.out.println(time); // Prints out 3\n }\n}\n</code></pre>\n" }, { "answer_id": 243087, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 5, "selected": false, "text": "<p>My guess is you are actually doing something like:</p>\n\n<pre><code>System.out.println(\"\" + size + estimated); \n</code></pre>\n\n<p>This expression is evaluated left to right:</p>\n\n<pre><code>\"\" + size &lt;--- string concatenation, so if size is 3, will produce \"3\"\n\"3\" + estimated &lt;--- string concatenation, so if estimated is 2, will produce \"32\"\n</code></pre>\n\n<p>To get this to work, you should do:</p>\n\n<pre><code>System.out.println(\"\" + (size + estimated));\n</code></pre>\n\n<p>Again this is evaluated left to right:</p>\n\n<pre><code>\"\" + (expression) &lt;-- string concatenation - need to evaluate expression first\n(3 + 2) &lt;-- 5\nHence:\n\"\" + 5 &lt;-- string concatenation - will produce \"5\"\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32043/" ]
What does Java do with long variables while performing addition? Wrong version 1: ``` Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = speeds.size() + estimated; // time = 21; string concatenation?? ``` Wrong version 2: ``` Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = estimated + speeds.size(); // time = 12; string concatenation?? ``` Correct version: ``` Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long size = speeds.size(); long time = size + estimated; // time = 3; correct ``` I don't get it, why Java concatenate them. Can anybody help me, why two primitive variables are concatenated? Greetings, guerda
I suspect you're not seeing what you think you're seeing. Java doesn't do this. Please try to provide a [short but complete program](http://pobox.com/~skeet/csharp/complete.html) which demonstrates this. Here's a short but complete program which demonstrates correct behaviour, but with your "wrong" code (i.e. a counterexample). ``` import java.util.*; public class Test { public static void main(String[] args) { Vector speeds = new Vector(); speeds.add("x"); speeds.add("y"); long estimated = 1l; long time = speeds.size() + estimated; System.out.println(time); // Prints out 3 } } ```
243,057
<p>I'm using a Response.Redirect to redirect users to another server to download a file, and the other server is checking the header to ensure it came from the correct server... however it seems Response.Redirect strips the headers from the Response.</p> <p>Does anybody know how i can add the headers back? I've tried:</p> <pre><code>Response.AddHeader("Referer", "www.domain.com"); </code></pre> <p>But the receiving page tests false when i check if the Referrer header is set. </p> <p>Any suggestions how i can get this working, other than displaying a button for the user to click on (i'd like to keep the url hidden from the user as much as possible).</p>
[ { "answer_id": 243073, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>I don't think it's possible. What you are sending back to the client is a Location header that tells the client to load the page referred to instead of the page it originally requested. In this case the client is not coming from a link and thus does not set the referrer header. It's basically as if the user typed the redirect url in the location bar in his browser.</p>\n\n<p>You may be able to save the referrer in the session, or encode it in the URL as a query parameter. Like the Forms login does with ReturnUrl.</p>\n" }, { "answer_id": 243122, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": false, "text": "<p>Is <a href=\"http://msdn.microsoft.com/en-us/library/y4k58xk7.aspx\" rel=\"nofollow noreferrer\">Server.Transfer</a> an option?</p>\n\n<p>There are some caveats though that you will need to look into.\nE.G. Keeps the original URL, Authorization, etc... More details in the link.</p>\n\n<p>Keeping the original URL may be advantageous in this circumstance.</p>\n" }, { "answer_id": 243260, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 1, "selected": false, "text": "<p>The referrer Header that your second server gets is generated by the browser and it will be unlikely that you can change it in any sensible way.</p>\n\n<p>Did you try adding the Referrer to the URL and then reading that on your second server instead?</p>\n\n<pre><code>Response.Redirect(\"url?Referer=\" + Server.UrlEncode(Request.UrlReferrer));\n</code></pre>\n" }, { "answer_id": 243310, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>Set an auth cookie (with a keyed hash and a 5-minute expiration), send a redirect response, browser sends a new request to the second server (if it's the same domain) along with the auth coookie, second server checks the cookie, ensures that only the first server could have set it, and sends back the content to the browser.</p>\n" }, { "answer_id": 243350, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 2, "selected": false, "text": "<p>That will go against the Referer (sic) header <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.36\" rel=\"nofollow noreferrer\" title=\"HTTP/1.1 Header Field Definitions: Referer\">definition</a>:</p>\n\n<blockquote>\n <p>The Referer[sic] request-header field\n allows the client to specify, for the\n server's benefit, the <strong>address (URI) of\n the resource from which the\n Request-URI was obtained</strong> (the\n \"referrer\", although the header field\n is misspelled.)</p>\n</blockquote>\n\n<p>If you are redirecting this is clearly not the case to add this header.</p>\n\n<p>If you need this information try with a cookie or some session variable, or even better a variable in the URL as you have already been told.</p>\n" }, { "answer_id": 243524, "author": "Lazarus", "author_id": 19540, "author_profile": "https://Stackoverflow.com/users/19540", "pm_score": 0, "selected": false, "text": "<p>If the redirect is to the same process I'd use a Session value to store the referrer URI to allow the secondary page to pick it up. I use that on my system to maintain the referrer between the redirect of http connections to our https system.</p>\n" }, { "answer_id": 247518, "author": "matt.mercieca", "author_id": 30407, "author_profile": "https://Stackoverflow.com/users/30407", "pm_score": 4, "selected": false, "text": "<p>There is an HTML hack available.</p>\n\n<pre><code>&lt;form action=\"http://url.goes.here\" id=\"test\" method=\"GET\"&gt;&lt;/form&gt;\n&lt;script type=\"text/javascript\"&gt;\n document.getElementById(\"test\").submit();\n&lt;/script&gt;\n</code></pre>\n\n<p>If you need to trigger that from a code behind, that can be done too:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Response.Write( @\"&lt;form action='http://url.goes.here' id='test' method='GET'&gt;&lt;/form&gt;\n &lt;script type='text/javascript'&gt;\n document.getElementById('test').submit();\n &lt;/script&gt; \");\n</code></pre>\n\n<p>As Inkel might point out, that is a loose interpretation of the Referer[sic] spec. It will do what you want though.</p>\n" }, { "answer_id": 247539, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": -1, "selected": false, "text": "<p>+1 to inkel's comment above.</p>\n\n<p>Though if you don't care about the spec and just want to do it anyway, you can avoid using Response.Redirect and instead build the response headers yourself.</p>\n\n<pre><code>Response.StatusCode = 302; //temp redirect\nResponse.Headers.Add(\"Location\", \"your/url/here\");\nResponse.Headers.Add(\"Referer\", \"something.com\");\nResponse.End();\n</code></pre>\n\n<p>This is off the top of my head, you might need to have a few other things in the response header.</p>\n" }, { "answer_id": 4462712, "author": "Makkie", "author_id": 528853, "author_profile": "https://Stackoverflow.com/users/528853", "pm_score": 1, "selected": false, "text": "<p>Here is a version of previous that works for me:</p>\n\n<pre><code>default.asp\n\nservername = Lcase(Request.ServerVariables(\"SERVER_NAME\"))\nResponse.Status = \"301 Moved Permanently\"\nResponse.AddHeader \"Location\", \"http://yoursite\"\nResponse.AddHeader \"Referer\", servername\nResponse.End()\n</code></pre>\n" }, { "answer_id": 9584407, "author": "user787262", "author_id": 787262, "author_profile": "https://Stackoverflow.com/users/787262", "pm_score": 0, "selected": false, "text": "<p>I do not suggest to post - most websites block that.\njust use <code>javascript document.location = '&lt;%:yourURL%&gt;;';</code> which will automatically load the new page. this is working well for me - because redirect response does not include referrer.</p>\n" }, { "answer_id": 10137150, "author": "Mr Moose", "author_id": 685760, "author_profile": "https://Stackoverflow.com/users/685760", "pm_score": 1, "selected": false, "text": "<p>I know that this is old, but I just came across it while trying to do a similar thing. </p>\n\n<p>I didn't want to add it to the URL as it kinda polluted the URL with stuff I didn't want in there. Also, I didn't want people to accidently bookmark that URL. Therefore, I used Cookies to add my data;</p>\n\n<pre><code>string token = vwrApi.GetAuthenticationToken(userId);\nResponse.Cookies.Add(new HttpCookie(\"VwrAuthorization\", token));\nResponse.Redirect(returnUrl, true);\n</code></pre>\n\n<p>Of course this is reliant on your ability to change where the destination server looks for the information, but it is another option at least. </p>\n" }, { "answer_id": 11232430, "author": "Kristofor", "author_id": 860329, "author_profile": "https://Stackoverflow.com/users/860329", "pm_score": -1, "selected": false, "text": "<p>You will need to issue a 307 status response and set the location header to the destination you want the user to be redirected to. This will keep the original referer[sic] header intact.</p>\n\n<pre><code>HttpContext.Current.Response.StatusCode = 307;\nHttpContext.Current.Response.AddHeader(\"Location\", \"http://stackoverflow.com\");\nHttpContext.Current.Response.End(); \n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
I'm using a Response.Redirect to redirect users to another server to download a file, and the other server is checking the header to ensure it came from the correct server... however it seems Response.Redirect strips the headers from the Response. Does anybody know how i can add the headers back? I've tried: ``` Response.AddHeader("Referer", "www.domain.com"); ``` But the receiving page tests false when i check if the Referrer header is set. Any suggestions how i can get this working, other than displaying a button for the user to click on (i'd like to keep the url hidden from the user as much as possible).
There is an HTML hack available. ``` <form action="http://url.goes.here" id="test" method="GET"></form> <script type="text/javascript"> document.getElementById("test").submit(); </script> ``` If you need to trigger that from a code behind, that can be done too: ```cs Response.Write( @"<form action='http://url.goes.here' id='test' method='GET'></form> <script type='text/javascript'> document.getElementById('test').submit(); </script> "); ``` As Inkel might point out, that is a loose interpretation of the Referer[sic] spec. It will do what you want though.
243,060
<p>Emacs does not recognize my correct Python path. I think it is a general problem with Emacs not recognizing my environment variables. I have GNU Emacs 22.1.1 (i386-apple-darwin8.9.1, Carbon Version 1.6.0) of 2007-06-17 installed.</p> <p>I have set <code>PYTHONPATH</code> in my <code>~/.bashrc</code>. Maybe I should set it somewhere else?</p>
[ { "answer_id": 243239, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 6, "selected": true, "text": "<p><code>.bashrc</code> only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use <code>setenv</code> in your <code>.emacs</code>:</p>\n\n<pre><code>(setenv \"PYTHONPATH\" \"PATH_STRING_HERE\")\n</code></pre>\n\n<p>You can set <code>PYTHONPATH</code> for the entire Mac OS session, by adding it to <code>~/.MacOSX/environment.plist</code> (more <a href=\"http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html#//apple_ref/doc/uid/20002093-113982\" rel=\"noreferrer\">here</a>). You probably don't want to do this unless you have XCode (and its property list editor) installed.</p>\n\n<p>(<a href=\"http://procrastiblog.com/2007/07/09/changing-your-path-in-emacs-compilation-mode/\" rel=\"noreferrer\">Via Procrastiblog</a>)</p>\n" }, { "answer_id": 42206188, "author": "Christophe Van Neste", "author_id": 3940298, "author_profile": "https://Stackoverflow.com/users/3940298", "pm_score": 2, "selected": false, "text": "<p>In order not to manually copy paste:</p>\n\n<pre><code>(setenv \"PYTHONPATH\" (shell-command-to-string \"$SHELL --login -c 'echo -n $PYTHONPATH'\"))\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2007483/" ]
Emacs does not recognize my correct Python path. I think it is a general problem with Emacs not recognizing my environment variables. I have GNU Emacs 22.1.1 (i386-apple-darwin8.9.1, Carbon Version 1.6.0) of 2007-06-17 installed. I have set `PYTHONPATH` in my `~/.bashrc`. Maybe I should set it somewhere else?
`.bashrc` only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use `setenv` in your `.emacs`: ``` (setenv "PYTHONPATH" "PATH_STRING_HERE") ``` You can set `PYTHONPATH` for the entire Mac OS session, by adding it to `~/.MacOSX/environment.plist` (more [here](http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html#//apple_ref/doc/uid/20002093-113982)). You probably don't want to do this unless you have XCode (and its property list editor) installed. ([Via Procrastiblog](http://procrastiblog.com/2007/07/09/changing-your-path-in-emacs-compilation-mode/))
243,068
<p>How can I create EPS files in C#? Are there any opensource libraries available or do I have to resort to <a href="http://www.adobe.com/devnet/postscript/pdfs/5002.EPSF_Spec.pdf" rel="noreferrer">the spec</a> and do it by hand?</p>
[ { "answer_id": 243239, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 6, "selected": true, "text": "<p><code>.bashrc</code> only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use <code>setenv</code> in your <code>.emacs</code>:</p>\n\n<pre><code>(setenv \"PYTHONPATH\" \"PATH_STRING_HERE\")\n</code></pre>\n\n<p>You can set <code>PYTHONPATH</code> for the entire Mac OS session, by adding it to <code>~/.MacOSX/environment.plist</code> (more <a href=\"http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html#//apple_ref/doc/uid/20002093-113982\" rel=\"noreferrer\">here</a>). You probably don't want to do this unless you have XCode (and its property list editor) installed.</p>\n\n<p>(<a href=\"http://procrastiblog.com/2007/07/09/changing-your-path-in-emacs-compilation-mode/\" rel=\"noreferrer\">Via Procrastiblog</a>)</p>\n" }, { "answer_id": 42206188, "author": "Christophe Van Neste", "author_id": 3940298, "author_profile": "https://Stackoverflow.com/users/3940298", "pm_score": 2, "selected": false, "text": "<p>In order not to manually copy paste:</p>\n\n<pre><code>(setenv \"PYTHONPATH\" (shell-command-to-string \"$SHELL --login -c 'echo -n $PYTHONPATH'\"))\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25571/" ]
How can I create EPS files in C#? Are there any opensource libraries available or do I have to resort to [the spec](http://www.adobe.com/devnet/postscript/pdfs/5002.EPSF_Spec.pdf) and do it by hand?
`.bashrc` only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use `setenv` in your `.emacs`: ``` (setenv "PYTHONPATH" "PATH_STRING_HERE") ``` You can set `PYTHONPATH` for the entire Mac OS session, by adding it to `~/.MacOSX/environment.plist` (more [here](http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html#//apple_ref/doc/uid/20002093-113982)). You probably don't want to do this unless you have XCode (and its property list editor) installed. ([Via Procrastiblog](http://procrastiblog.com/2007/07/09/changing-your-path-in-emacs-compilation-mode/))
243,072
<p>When a user logs in to my site I want a css styled button to appear (this could be anything really, i.e. some special news text item etc), how can you do this via masterpages in asp.net? Or is there some other way you do this?</p>
[ { "answer_id": 243075, "author": "Steve Horn", "author_id": 10589, "author_profile": "https://Stackoverflow.com/users/10589", "pm_score": 1, "selected": false, "text": "<p>This MSDN article describes how you can find and manipulate master page content from a content page. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/xxwa0ff0(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n" }, { "answer_id": 243078, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "<p>Check out the LoginView control in ASP.Net. It takes two templates - one for logged in users and one for not-logged in users. I guess it should do what you want. </p>\n" }, { "answer_id": 243084, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": true, "text": "<p>You haven't provided a whole lot of information about your setup simon, but assuming you're using a .NET Membership Provider, then you can use a login view to have a section of your page render differently for logged in Vs. not</p>\n\n<pre><code> &lt;asp:LoginView&gt;\n &lt;AnonymousTemplate&gt;\n Nothing Displayed\n &lt;/AnonymousTemplate&gt;\n &lt;LoggedInTemplate&gt;\n &lt;asp:Button ID=\"myButton\" runat=\"server\"&gt;\n &lt;/LoggedInTemplate&gt;\n &lt;/asp:LoginView&gt;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175/" ]
When a user logs in to my site I want a css styled button to appear (this could be anything really, i.e. some special news text item etc), how can you do this via masterpages in asp.net? Or is there some other way you do this?
You haven't provided a whole lot of information about your setup simon, but assuming you're using a .NET Membership Provider, then you can use a login view to have a section of your page render differently for logged in Vs. not ``` <asp:LoginView> <AnonymousTemplate> Nothing Displayed </AnonymousTemplate> <LoggedInTemplate> <asp:Button ID="myButton" runat="server"> </LoggedInTemplate> </asp:LoginView> ```
243,082
<p>Let's say I have a <strong>Base</strong> class and several <strong>Derived</strong> classes. Is there any way to cast an object to one of the derived classes without the need to write something like this :</p> <pre><code> string typename = typeid(*object).name(); if(typename == "Derived1") { Derived1 *d1 = static_cast&lt Derived1*&gt(object); } else if(typename == "Derived2") { Derived2 *d2 = static_cast &lt Derived2*&gt(object); } ... else { ... } </code></pre>
[ { "answer_id": 243105, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 2, "selected": false, "text": "<p>usually, this is a sign of a bad design. Why do you need to do this? It might be possible to redesign so that this is not needed.</p>\n" }, { "answer_id": 243111, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>Your example won't port, because the exact format of name() isn't specified. You could try a succession of <code>dynamic_cast</code>s. <code>Dynamic_cast</code> returns a null pointer if you cast to the wrong type. However, if you're doing a typeswitch like this one, there's something wrong with your design.</p>\n" }, { "answer_id": 243115, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 3, "selected": false, "text": "<p>You can use <code>dynamic_cast</code> and test for NULL, but I'd <strong>strongly</strong> consider refactoring the code instead.</p>\n\n<p>If you need subclass-specific handling, <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow noreferrer\">Template Method</a> might be helpful, but without knowing what you're trying to achive, it's only a vague guess.</p>\n" }, { "answer_id": 243117, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 2, "selected": false, "text": "<p>What are you trying to accomplish, exactly?\nIn my experience, things like this are a sign of bad design. Re-evaluate your class hierarchy, because the goal of object oriented design is make things like this unnecessary.</p>\n" }, { "answer_id": 243123, "author": "marijne", "author_id": 7038, "author_profile": "https://Stackoverflow.com/users/7038", "pm_score": 3, "selected": false, "text": "<pre><code>Derived1* d1 = dynamic_cast&lt; Derived1* &gt;(object);\nif (d1 == NULL)\n{\n Derived2* d2 = dynamic_cast&lt; Derived2* &gt;(object);\n //etc\n}\n</code></pre>\n\n<p>I have the following methods on my smartpointer type, simulating C# 'is' and 'as':</p>\n\n<pre><code>template&lt; class Y &gt; bool is() const throw()\n {return !null() &amp;&amp; dynamic_cast&lt; Y* &gt;(ptr) != NULL;}\ntemplate&lt; class Y &gt; Y* as() const throw()\n {return null() ? NULL : dynamic_cast&lt; Y* &gt;(ptr);}\n</code></pre>\n" }, { "answer_id": 243126, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 2, "selected": false, "text": "<p>You can do this using <code>dynamic_cast</code>, e.g:</p>\n\n<pre><code>if ( Derived1* d1 = dynamic_cast&lt;Derived1*&gt;(object) ) {\n // object points to a Derived1\n d1-&gt;foo();\n}\nelse if ( Derived2* d2 = dynamic_cast&lt;Derived2*&gt;(object) ) {\n // object points to a Derived2\n d2-&gt;bar();\n}\nelse {\n // etc.\n}\n</code></pre>\n\n<p>But as others have said, code such as this can indicate a bad design, and you should generally use <a href=\"http://www.parashift.com/c++-faq-lite/virtual-functions.html\" rel=\"nofollow noreferrer\">virtual functions</a> to implement polymorphic behaviour.</p>\n" }, { "answer_id": 243150, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": true, "text": "<p>Don't. </p>\n\n<p>Read up on polymorphism. Almost every \"dynamic cast\" situation is an example of polymorphism struggling to be implemented.</p>\n\n<p>Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses. </p>\n\n<p>You left out the most important part of your example. The useful, polymorphic work.</p>\n\n<pre><code>string typename = typeid(*object).name();\nif(typename == \"Derived1\") {\n Derived1 *d1 = static_cast&lt; Derived1*&gt;(object);\n d1-&gt;doSomethingUseful();\n}\nelse if(typename == \"Derived2\") {\n Derived2 *d2 = static_cast &lt; Derived2*&gt;(object);\n d2-&gt;doSomethingUseful();\n}\n...\nelse {\n ...\n}\n</code></pre>\n\n<p>If every subclass implements doSomethingUseful, this is all much simpler. And polymorphic.</p>\n\n<pre><code>object-&gt;doSomethingUseful();\n</code></pre>\n" }, { "answer_id": 243243, "author": "Malkocoglu", "author_id": 31152, "author_profile": "https://Stackoverflow.com/users/31152", "pm_score": 1, "selected": false, "text": "<p>I think dynamic_cast is the way to go, but I don't particularly think this is a bad design for all possible conditions because object to be casted may be something provided by some third-party module. Let's say object was created by a plug-in that the application author has no knowledge of. And that particular plug-in may create Derived1 (being the old version) type object or Derived2 (being the new version) type object. Maybe the plug-in interface was not designed to do version specific stuff, it just creates the object so the application must do this kind of checking to ensure proper casting/execution. After this, we can safely call object.doSomethingUsefulThatDoesNotExistInDerived1();</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
Let's say I have a **Base** class and several **Derived** classes. Is there any way to cast an object to one of the derived classes without the need to write something like this : ``` string typename = typeid(*object).name(); if(typename == "Derived1") { Derived1 *d1 = static_cast< Derived1*>(object); } else if(typename == "Derived2") { Derived2 *d2 = static_cast < Derived2*>(object); } ... else { ... } ```
Don't. Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented. Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses. You left out the most important part of your example. The useful, polymorphic work. ``` string typename = typeid(*object).name(); if(typename == "Derived1") { Derived1 *d1 = static_cast< Derived1*>(object); d1->doSomethingUseful(); } else if(typename == "Derived2") { Derived2 *d2 = static_cast < Derived2*>(object); d2->doSomethingUseful(); } ... else { ... } ``` If every subclass implements doSomethingUseful, this is all much simpler. And polymorphic. ``` object->doSomethingUseful(); ```
243,083
<p>What is a strongly typed dataset? (.net)</p>
[ { "answer_id": 243093, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 2, "selected": false, "text": "<p>Short answer: A dataset which is guaranteed (by the compiler) to hold a specific type.</p>\n" }, { "answer_id": 243096, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 4, "selected": false, "text": "<p>A strongly typed dataset is one that has specific types for the tables and their columns.</p>\n\n<p>You can say</p>\n\n<pre><code>EmployeeDataset ds = ...\nEmployeeRow row = ds.Employees.Rows[0];\nrow.Name = \"Joe\";\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>DataSet ds = ...\nDataRow row = ds.Tables[\"Employees\"].Rows[0];\nrow[\"Name\"] = \"Joe\";\n</code></pre>\n\n<p>This helps because you catch mistakes in naming at compile time, rather than run time and also enforces types on columns.</p>\n" }, { "answer_id": 243102, "author": "user11039", "author_id": 11039, "author_profile": "https://Stackoverflow.com/users/11039", "pm_score": 2, "selected": false, "text": "<p>A dataset which is tightly to a specific table at compile time so you can access the columns of a table using actual column name instead of index.</p>\n" }, { "answer_id": 243121, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>It looks like DataSet has already been covered, but for completeness, note that in .NET 3.5 there are good alternatives for simple data access; in particular, things like LINQ to SQL. This has a similar objective, but retains a much purer simple OO model to your data classes.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is a strongly typed dataset? (.net)
A strongly typed dataset is one that has specific types for the tables and their columns. You can say ``` EmployeeDataset ds = ... EmployeeRow row = ds.Employees.Rows[0]; row.Name = "Joe"; ``` instead of: ``` DataSet ds = ... DataRow row = ds.Tables["Employees"].Rows[0]; row["Name"] = "Joe"; ``` This helps because you catch mistakes in naming at compile time, rather than run time and also enforces types on columns.
243,097
<p>I have a unit test where I have statically defined a quite large byte array (over 8000 bytes) as the byte data of a file I don't want to read every time I run my unit test.</p> <pre><code>private static final byte[] FILE_DATA = new byte[] { 12,-2,123,................ } </code></pre> <p>This compiles fine within Eclipse, but when compiling via Ant script I get the following error:</p> <pre><code>[javac] C:\workspace\CCUnitTest\src\UnitTest.java:72: code too large [javac] private static final byte[] FILE_DATA = new byte[] { [javac] ^ </code></pre> <p>Any ideas why and how I can avoid this?</p> <hr> <p><strong>Answer</strong>: Shimi's answer did the trick. I moved the byte array out to a separate class and it compiled fine. Thanks!</p>
[ { "answer_id": 243114, "author": "Shimi Bandiel", "author_id": 15100, "author_profile": "https://Stackoverflow.com/users/15100", "pm_score": 6, "selected": true, "text": "<p>Methods in Java are restricted to 64k in the byte code. Static initializations are done in a single method (see <a href=\"http://www.mail-archive.com/[email protected]/msg01990.html\" rel=\"noreferrer\">link</a>)\n<br/>\nYou may try to load the array data from a file.</p>\n" }, { "answer_id": 244100, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "<p>You can load the byte array from a file in you <code>@BeforeClass</code> static method. This will make sure it's loaded only once for all your unit tests.</p>\n" }, { "answer_id": 22637216, "author": "Josh", "author_id": 82505, "author_profile": "https://Stackoverflow.com/users/82505", "pm_score": 0, "selected": false, "text": "<p>You can leverage inner classes as each would have it's own 64KB limit. It may not help you with a single large array as the inner class will be subject to the same static initializer limit as your main class. However, you stated that you managed to solve the issue by moving your array to a separate class, so I suspect that you're loading more than just this single array in your main class.</p>\n\n<p>Instead of:</p>\n\n<pre><code>private static final byte[] FILE_DATA = new byte[] {12,-2,123,...,&lt;LARGE&gt;};\n</code></pre>\n\n<p>Try:</p>\n\n<pre><code>private static final class FILE_DATA\n{\n private static final byte[] VALUES = new byte[] {12,-2,123,...,&lt;LARGE&gt;};\n}\n</code></pre>\n\n<p>Then you can access the values as <code>FILE_DATA.VALUES[i]</code> instead of <code>FILE_DATA[i]</code>, but you're subject to a 128KB limit instead of just 64KB. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have a unit test where I have statically defined a quite large byte array (over 8000 bytes) as the byte data of a file I don't want to read every time I run my unit test. ``` private static final byte[] FILE_DATA = new byte[] { 12,-2,123,................ } ``` This compiles fine within Eclipse, but when compiling via Ant script I get the following error: ``` [javac] C:\workspace\CCUnitTest\src\UnitTest.java:72: code too large [javac] private static final byte[] FILE_DATA = new byte[] { [javac] ^ ``` Any ideas why and how I can avoid this? --- **Answer**: Shimi's answer did the trick. I moved the byte array out to a separate class and it compiled fine. Thanks!
Methods in Java are restricted to 64k in the byte code. Static initializations are done in a single method (see [link](http://www.mail-archive.com/[email protected]/msg01990.html)) You may try to load the array data from a file.
243,124
<p>Here is the problem: we have lots of Javascripts and lots of CSS files, which we'd rather be serving minified. Minification is easy: set up the YUI Compressor, run an Ant task, and it spits out minified files, which we save beside the originals.</p> <p>So we end up with the following directory structure somewhere inside our DocumentRoot:</p> <pre> / /js /min foo-min.js bar-min.js foo.js bar.js quux.js /css ... </pre> <p>Now what we need is that Apache serve files from the <strong>min</strong> subdirectory, <em>and fallback to serving uncompressed files</em>, if their minified versions are not available. The last issue is the one I cannot solve.</p> <p>For example: suppose we have a request to <strong>example.com/js/foo.js</strong> — in this case Apache should send contents of <strong>/js/min/foo-min.js</strong>. There is no minified <strong>quux.js</strong>, so request to <strong>/js/quux.js</strong> returns <strong>/js/quux.js</strong> itself, not 404. Finally, if there is no <strong>/js/fred.js</strong>, it should end up with 404.</p> <p>Actually, I'm setting build scripts in such a way that unminified files are not deployed on the production server, but this configuration still might be useful on an integration server and on development machines.</p>
[ { "answer_id": 243135, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>Is it possible to change your build scripts? If so, you can configure them to minify the files and give them the same file name, but only when provided the proper flag, e.g. <code>ant productionDeploy</code> instead of <code>ant integrationDeploy</code>. That way the minification process is completely transparent to everything except the build script.</p>\n" }, { "answer_id": 243154, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 2, "selected": false, "text": "<p>You can use RewriteCond to detect the presence of a minified file:</p>\n\n<pre><code>RewriteCond %{REQUESTURI} ^/js/(.*\\.js)\nRewriteCond js/min/%1 -f\nRewriteRule %1 min/%1 [L]\n</code></pre>\n" }, { "answer_id": 243373, "author": "Stepan Stolyarov", "author_id": 6573, "author_profile": "https://Stackoverflow.com/users/6573", "pm_score": 4, "selected": true, "text": "<p>Here is the configuration that finally worked:</p>\n\n<p>/js/.htaccess:</p>\n\n<pre><code>RewriteEngine On\n\nRewriteBase /js\n\nRewriteCond %{REQUEST_URI} ^/js/((.+)\\.js)$\nRewriteCond %{DOCUMENT_ROOT}/js/min/%2-min.js -f\nRewriteRule ^(.+)$ min/%2-min.js [L]\n</code></pre>\n\n<p>Same for <strong>css</strong> directory.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6573/" ]
Here is the problem: we have lots of Javascripts and lots of CSS files, which we'd rather be serving minified. Minification is easy: set up the YUI Compressor, run an Ant task, and it spits out minified files, which we save beside the originals. So we end up with the following directory structure somewhere inside our DocumentRoot: ``` / /js /min foo-min.js bar-min.js foo.js bar.js quux.js /css ... ``` Now what we need is that Apache serve files from the **min** subdirectory, *and fallback to serving uncompressed files*, if their minified versions are not available. The last issue is the one I cannot solve. For example: suppose we have a request to **example.com/js/foo.js** — in this case Apache should send contents of **/js/min/foo-min.js**. There is no minified **quux.js**, so request to **/js/quux.js** returns **/js/quux.js** itself, not 404. Finally, if there is no **/js/fred.js**, it should end up with 404. Actually, I'm setting build scripts in such a way that unminified files are not deployed on the production server, but this configuration still might be useful on an integration server and on development machines.
Here is the configuration that finally worked: /js/.htaccess: ``` RewriteEngine On RewriteBase /js RewriteCond %{REQUEST_URI} ^/js/((.+)\.js)$ RewriteCond %{DOCUMENT_ROOT}/js/min/%2-min.js -f RewriteRule ^(.+)$ min/%2-min.js [L] ``` Same for **css** directory.
243,152
<p>The thing is I've been using the <a href="http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx" rel="noreferrer">lock statement</a> to protect a critical part of my code, but now, I realize I could allow concurrent execution of that critical code is some conditions are met.<br> Is there a way to condition the lock?</p>
[ { "answer_id": 243168, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": true, "text": "<pre><code>Action doThatThing = someMethod;\n\nif (condition)\n{\n lock(thatThing)\n {\n doThatThing();\n }\n}\nelse\n{\n doThatThing();\n}\n</code></pre>\n" }, { "answer_id": 243180, "author": "noocyte", "author_id": 11220, "author_profile": "https://Stackoverflow.com/users/11220", "pm_score": 1, "selected": false, "text": "<p>I'm guessing you've got some code that looks a little like this:</p>\n\n<pre><code>private Monkey GetScaryMonkey(int numberOfHeads){\n Monkey ape = null; \n lock(this) {\n ape = new Monkey();\n ape.AddHeads(numberOfHeads); \n }\n return ape;\n}\n</code></pre>\n\n<p>To make this conditional couldn't you just do this:</p>\n\n<pre><code>private Monkey GetScaryMonkey(int numberOfHeads){\n if ( numberOfHeads &gt; 1 ) {\n lock(this) {\n return CreateNewMonkey( numberOfHeads ); \n }\n }\n return CreateNewMonkey( numberOfHeads );\n}\n</code></pre>\n\n<p>Should work, no?</p>\n" }, { "answer_id": 243190, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>Actually, to avoid a race condition, I'd be tempted to use a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx\" rel=\"noreferrer\"><code>ReaderWriterLockSlim</code></a> here - treat concurrent access as a read lock, and exclusive access as a write lock. That way, if the conditions change you won't end up with some inappropriate code still executing blindly in the region (under the false assumption that it is safe); a bit verbose, but\n(formatted for space):</p>\n\n<pre><code> if (someCondition) {\n lockObj.EnterReadLock();\n try { Foo(); }\n finally { lockObj.ExitReadLock(); }\n } else {\n lockObj.EnterWriteLock();\n try { Foo(); }\n finally { lockObj.ExitWriteLock(); }\n }\n</code></pre>\n" }, { "answer_id": 243192, "author": "marijne", "author_id": 7038, "author_profile": "https://Stackoverflow.com/users/7038", "pm_score": 3, "selected": false, "text": "<pre><code>bool locked = false;\nif (condition) {\n Monitor.Enter(lockObject);\n locked = true;\n}\ntry {\n // possibly critical section\n}\nfinally {\n if (locked) Monitor.Exit(lockObject);\n}\n</code></pre>\n\n<p>EDIT: yes, there is a race condition unless you can assure that the condition is constant while threads are entering.</p>\n" }, { "answer_id": 243743, "author": "user31934", "author_id": 31934, "author_profile": "https://Stackoverflow.com/users/31934", "pm_score": 3, "selected": false, "text": "<p>I'm no threading expert, but it sounds like you might be looking for something like this (double-checked locking). The idea is to check the condition both before and after acquiring the lock.</p>\n\n<pre><code>private static object lockHolder = new object();\n\nif (ActionIsValid()) {\n lock(lockHolder) {\n if (ActionIsValid()) {\n DoSomething(); \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 277147, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://en.wikipedia.org/wiki/Double_checked_locking_pattern\" rel=\"nofollow noreferrer\" title=\"Wikipedia link: Double-Checked Locking pattern\">Double-checked locking pattern</a>, as suggested above. that's the trick IMO :)</p>\n\n<p>make sure you have your lock object as a <em>static</em>, as listed in not.that.dave.foley.myopenid.com's example.</p>\n" }, { "answer_id": 63491084, "author": "l33t", "author_id": 419761, "author_profile": "https://Stackoverflow.com/users/419761", "pm_score": 2, "selected": false, "text": "<p>If you have many methods/properties that require conditional locking, you don't want to repeat the same pattern over and over again. I propose the following trick:</p>\n<h2>Non-repetitive conditional-lock pattern</h2>\n<p>With a private helper <code>struct</code> implementing <code>IDisposable</code> we can encapsulate the condition/lock without measurable overhead.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public void DoStuff()\n{\n using (ConditionalLock())\n {\n // Thread-safe code\n }\n}\n</code></pre>\n<p>It's quite easy to implement. Here's a sample class demonstrating this pattern:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Counter\n{\n private static readonly int MAX_COUNT = 100;\n\n private readonly bool synchronized;\n private int count;\n private readonly object lockObject = new object();\n\n private int lockCount;\n\n public Counter(bool synchronized)\n {\n this.synchronized = synchronized;\n }\n\n public int Count\n {\n get\n {\n using (ConditionalLock())\n {\n return count;\n }\n }\n }\n\n public int LockCount\n {\n get\n {\n using (ConditionalLock())\n {\n return lockCount;\n }\n }\n }\n\n public void Increase()\n {\n using (ConditionalLock())\n {\n if (count &lt; MAX_COUNT)\n {\n Thread.Sleep(10);\n ++count;\n }\n }\n }\n\n private LockHelper ConditionalLock() =&gt; new LockHelper(this);\n\n // This is where the magic happens!\n private readonly struct LockHelper : IDisposable\n {\n private readonly Counter counter;\n private readonly bool lockTaken;\n\n public LockHelper(Counter counter)\n {\n this.counter = counter;\n\n lockTaken = false;\n if (counter.synchronized)\n {\n Monitor.Enter(counter.lockObject, ref lockTaken);\n counter.lockCount++;\n }\n }\n\n private void Exit()\n {\n if (lockTaken)\n {\n Monitor.Exit(counter.lockObject);\n }\n }\n\n void IDisposable.Dispose() =&gt; Exit();\n }\n}\n</code></pre>\n<p>Now, let's create a small sample program demonstrating its correctness.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Program\n{\n static void Main(string[] args)\n {\n var onlyOnThisThread = new Counter(synchronized: false);\n IncreaseToMax(c1);\n\n var onManyThreads = new Counter(synchronized: true);\n var t1 = Task.Factory.StartNew(() =&gt; IncreaseToMax(c2));\n var t2 = Task.Factory.StartNew(() =&gt; IncreaseToMax(c2));\n var t3 = Task.Factory.StartNew(() =&gt; IncreaseToMax(c2));\n Task.WaitAll(t1, t2, t3);\n\n Console.WriteLine($&quot;Counter(false) =&gt; Count = {c1.Count}, LockCount = {c1.LockCount}&quot;);\n Console.WriteLine($&quot;Counter(true) =&gt; Count = {c2.Count}, LockCount = {c2.LockCount}&quot;);\n }\n\n private static void IncreaseToMax(Counter counter)\n {\n for (int i = 0; i &lt; 1000; i++)\n {\n counter.Increase();\n }\n }\n}\n</code></pre>\n<h2>Output:</h2>\n<pre><code>Counter(false) =&gt; Count = 100, LockCount = 0\nCounter(true) =&gt; Count = 100, LockCount = 3002\n</code></pre>\n<p>Now you can let the caller decide whether locking (costly) is needed.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23893/" ]
The thing is I've been using the [lock statement](http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx) to protect a critical part of my code, but now, I realize I could allow concurrent execution of that critical code is some conditions are met. Is there a way to condition the lock?
``` Action doThatThing = someMethod; if (condition) { lock(thatThing) { doThatThing(); } } else { doThatThing(); } ```
243,173
<p>I'm having an issue with a USB project using <code>LIB-USB</code>. The USB device is based on a PIC18F4550 and has a single control endpoint. The PC front-end is written in MSVC and uses Lib-Usb 1.12.</p> <p>On the PC end, the program begins by setting the configuration, claiming the interface, then sending (and receiving) control messages (vendor specific), all successfully. After what seems like a random # of bytes have been transferred (anywhere between 100 and 2000) the transfer halts with an <strong>error rc=-5</strong> returned from the usb_control_msg call.</p> <p>On the PC-end, the calls look like this:</p> <pre><code>ret = usb_set_configuration(udev, 1); ret = usb_claim_interface(udev, 0); ret = usb_control_msg(udev, USB_TYPE_VENDOR|USB_RECIP_DEVICE, CMD_RESET, 0, 0, buffer, 0, 100); ret = usb_control_msg(udev, 0xC0, GET_FIFO_DATA, 0, 0, buffer, 8, 100); </code></pre> <p>The last call, which actually acquires data from the USB device, runs many times in succession but always dies after a random number of bytes (100 to 2000 in total) are transferred in this way. Changing the pipe to EP1 does the same thing with the same error eventually appearing.</p> <p>On the USB device (PIC) end the descriptor is very simple, having only the EP0 pipe, and looks like this:</p> <pre><code>Device db 0x12, DEVICE ; bLength, bDescriptorType db 0x10, 0x01 ; bcdUSB (low byte), bcdUSB (high byte) db 0x00, 0x00 ; bDeviceClass, bDeviceSubClass db 0x00, MAX_PACKET_SIZE ; bDeviceProtocol, bMaxPacketSize db 0xD8, 0x04 ; idVendor (low byte), idVendor (high byte) db 0x01, 0x00 ; idProduct (low byte), idProduct (high byte) db 0x00, 0x00 ; bcdDevice (low byte), bcdDevice (high byte) db 0x01, 0x02 ; iManufacturer, iProduct db 0x00, NUM_CONFIGURATIONS ; iSerialNumber (none), bNumConfigurations Configuration1 db 0x09, CONFIGURATION ; bLength, bDescriptorType db 0x12, 0x00 ; wTotalLength (low byte), wTotalLength (high byte) db NUM_INTERFACES, 0x01 ; bNumInterfaces, bConfigurationValue db 0x00, 0xA0 ; iConfiguration (none), bmAttributes db 0x32, 0x09 ; bMaxPower (100 mA), bLength (Interface1 descriptor starts here) db INTERFACE, 0x00 ; bDescriptorType, bInterfaceNumber db 0x00, 0x00 ; bAlternateSetting, bNumEndpoints (excluding EP0) db 0xFF, 0x00 ; bInterfaceClass (vendor specific class code), bInterfaceSubClass db 0xFF, 0x00 ; bInterfaceProtocol (vendor specific protocol used), iInterface (none) </code></pre> <p>The actual framework is that of Bradley Minch's in assembly language. </p> <p>If anyone has encountered this type of problem before I'd love to hear about it as I've tried just about everything to solve it including using a different pipe (EP1, with the same results), checking the UOWN bit on the PIC before writing to the pipe, handshaking with the PC host (where the PC must send a vendor-specific command first before the datsa is written) but to no avail.</p>
[ { "answer_id": 243748, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 1, "selected": false, "text": "<p>It's very advisable to have USB bus analyzer <a href=\"http://www.lecroy.com/tm/products/ProtocolAnalyzers/usb.asp?menuid=67\" rel=\"nofollow noreferrer\">Lecroy</a> and <a href=\"http://www.ellisys.com/products/usbcompare.php\" rel=\"nofollow noreferrer\">Ellisys</a> are high end and a little bit expensive. <a href=\"http://www.totalphase.com/products/overview/usb/?gclid=CKOLje-aypYCFQOx1AodqkvEzA\" rel=\"nofollow noreferrer\">Total Phase</a> is an example of low end one.<br>\nUsing bus analyzers will help you great deal writing both your firmware and pc side software if you can afford one. Using the analyzer you can determine if the problem in your pc side (data you read is on the bus, but you can't see it in you software) or problem in your firmware implementation (you don't see data on the bus). </p>\n\n<p>From your description is hard to understand what is the problem and i don't know what is error -5 mean, if you can post the define name for this i might be more helpful.<br>\nIn general it's a good practice to transfer data from/to device in multiplies of max packet size. I also suggest you to read carefully relevant sections 5.5.3 (for control transfers) and 5.8.3 for bulk transfers in <a href=\"http://www.usb.org/developers/docs/\" rel=\"nofollow noreferrer\">USB Spec</a> </p>\n\n<p><strong>Additional comment based on the second log provided</strong>: </p>\n\n<p>The real error returned by the usb stack is in your log and its:<br>\n<code>vendor_class_request(): request failed: status: 0xc0000001, urb-status: 0xc000000c</code></p>\n\n<p>URB (usb request block) status defined in Windows Driver kit usb.h as :<br>\n<code>usb.h:#define USBD_STATUS_BUFFER_OVERRUN ((USBD_STATUS)0xC000000CL)</code></p>\n\n<p>I found a good explanation about this error <a href=\"http://www.jungo.com/support/tech_docs/td55.html\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>Please ignore the fact that this is WinDriver defined error it's just redefined error from Windows and the explanation about what it's usually mean is correct. </p>\n\n<p><a href=\"http://www.osronline.com/showthread.cfm?link=124579\" rel=\"nofollow noreferrer\">Here</a> is an example why it's can happened, but there is more potential reasons for this behavior.</p>\n" }, { "answer_id": 249077, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I do not have an analyzer (\"yet\", at least) but I did install DebugView to see what the driver is doing, with the following output trace. The first transfer shown (a vendor-specific one) is successful while the second one dies. A return code of \"-5\" which means \"I/O error\" (not particularly useful) is returned from the call.</p>\n\n<blockquote>\n <p>00002674 315.26220703 LIBUSB-DRIVER - vendor_class_request(): type: vendor<br>\n 00002675 315.26223755 LIBUSB-DRIVER - vendor_class_request(): recipient: device<br>\n 00002676 315.26223755 LIBUSB-DRIVER - vendor_class_request(): request: 0x04<br>\n 00002677 315.26223755 LIBUSB-DRIVER - vendor_class_request(): value: 0x0000<br>\n 00002678 315.26223755 LIBUSB-DRIVER - vendor_class_request(): index: 0x0000<br>\n 00002679 315.26223755 LIBUSB-DRIVER - vendor_class_request(): size: 8 \n 00002680 315.26226807 LIBUSB-DRIVER - vendor_class_request(): direction: in<br>\n 00002681 315.26226807 LIBUSB-DRIVER - vendor_class_request(): timeout: 100<br>\n 00002682 315.26617432 LIBUSB-DRIVER - vendor_class_request(): 8 bytes transmitted \n 00002683 315.26721191<br>\n 00002684 315.26721191<br>\n 00002685 315.26721191 LIBUSB-DRIVER - vendor_class_request(): type: vendor<br>\n 00002686 315.26721191 LIBUSB-DRIVER - vendor_class_request(): recipient: device<br>\n 00002687 315.26724243 LIBUSB-DRIVER - vendor_class_request(): request: 0x04<br>\n 00002688 315.26724243 LIBUSB-DRIVER - vendor_class_request(): value: 0x0000<br>\n 00002689 315.26724243 LIBUSB-DRIVER - vendor_class_request(): index: 0x0000<br>\n 00002690 315.26724243 LIBUSB-DRIVER - vendor_class_request(): size: 8 \n 00002691 315.26724243 LIBUSB-DRIVER - vendor_class_request(): direction: in<br>\n 00002692 315.26727295 LIBUSB-DRIVER - vendor_class_request(): timeout: 100<br>\n 00002693 315.27017212 LIBUSB-DRIVER - vendor_class_request(): request failed: status: 0xc0000001, urb-status: 0xc000000c<br>\n 00002694 315.27407837 [3684] LIBUSB_DLL: error: usb_control_msg: sending control message failed, win error: A device attached to the system is not functioning.<br>\n 00002695 315.27407837 [3684]<br>\n 00002696 315.27511597<br>\n 00002697 315.27514648 LIBUSB-DRIVER - release_interface(): interface 0 </p>\n</blockquote>\n" }, { "answer_id": 252480, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><strong>It Now Works!!</strong></p>\n\n<p>Of course, I now feel \"smart like a bag of hammers\" Had I read section 18 thoroughly I would have noticed the line about adding a 220nF capacitor between Vusb and ground. Added a 470nF cap between pin18 and ground and that was all it took .... reliable transfers now. </p>\n\n<p>Just another case of <code>\"I forgot to read the fine print\"</code></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm having an issue with a USB project using `LIB-USB`. The USB device is based on a PIC18F4550 and has a single control endpoint. The PC front-end is written in MSVC and uses Lib-Usb 1.12. On the PC end, the program begins by setting the configuration, claiming the interface, then sending (and receiving) control messages (vendor specific), all successfully. After what seems like a random # of bytes have been transferred (anywhere between 100 and 2000) the transfer halts with an **error rc=-5** returned from the usb\_control\_msg call. On the PC-end, the calls look like this: ``` ret = usb_set_configuration(udev, 1); ret = usb_claim_interface(udev, 0); ret = usb_control_msg(udev, USB_TYPE_VENDOR|USB_RECIP_DEVICE, CMD_RESET, 0, 0, buffer, 0, 100); ret = usb_control_msg(udev, 0xC0, GET_FIFO_DATA, 0, 0, buffer, 8, 100); ``` The last call, which actually acquires data from the USB device, runs many times in succession but always dies after a random number of bytes (100 to 2000 in total) are transferred in this way. Changing the pipe to EP1 does the same thing with the same error eventually appearing. On the USB device (PIC) end the descriptor is very simple, having only the EP0 pipe, and looks like this: ``` Device db 0x12, DEVICE ; bLength, bDescriptorType db 0x10, 0x01 ; bcdUSB (low byte), bcdUSB (high byte) db 0x00, 0x00 ; bDeviceClass, bDeviceSubClass db 0x00, MAX_PACKET_SIZE ; bDeviceProtocol, bMaxPacketSize db 0xD8, 0x04 ; idVendor (low byte), idVendor (high byte) db 0x01, 0x00 ; idProduct (low byte), idProduct (high byte) db 0x00, 0x00 ; bcdDevice (low byte), bcdDevice (high byte) db 0x01, 0x02 ; iManufacturer, iProduct db 0x00, NUM_CONFIGURATIONS ; iSerialNumber (none), bNumConfigurations Configuration1 db 0x09, CONFIGURATION ; bLength, bDescriptorType db 0x12, 0x00 ; wTotalLength (low byte), wTotalLength (high byte) db NUM_INTERFACES, 0x01 ; bNumInterfaces, bConfigurationValue db 0x00, 0xA0 ; iConfiguration (none), bmAttributes db 0x32, 0x09 ; bMaxPower (100 mA), bLength (Interface1 descriptor starts here) db INTERFACE, 0x00 ; bDescriptorType, bInterfaceNumber db 0x00, 0x00 ; bAlternateSetting, bNumEndpoints (excluding EP0) db 0xFF, 0x00 ; bInterfaceClass (vendor specific class code), bInterfaceSubClass db 0xFF, 0x00 ; bInterfaceProtocol (vendor specific protocol used), iInterface (none) ``` The actual framework is that of Bradley Minch's in assembly language. If anyone has encountered this type of problem before I'd love to hear about it as I've tried just about everything to solve it including using a different pipe (EP1, with the same results), checking the UOWN bit on the PIC before writing to the pipe, handshaking with the PC host (where the PC must send a vendor-specific command first before the datsa is written) but to no avail.
**It Now Works!!** Of course, I now feel "smart like a bag of hammers" Had I read section 18 thoroughly I would have noticed the line about adding a 220nF capacitor between Vusb and ground. Added a 470nF cap between pin18 and ground and that was all it took .... reliable transfers now. Just another case of `"I forgot to read the fine print"`
243,193
<p>I have a set of tables that are used to track bills. These tables are loaded from an SSIS process that runs weekly.</p> <p>I am in the process of creating a second set of tables to track adjustments to the bills that are made via the web. Some of our clients hand key their bills and all of those entries need to be backed up on a more regular schedule (the SSIS fed data can always be imported again so it isn't backed up).</p> <p>Is there a best practice for this type of behavior? I'm looking at implementing a DDL trigger that will parse the ALTER TABLE call and change the table being called. This is somewhat painful, and I'm curious if there is a better way.</p>
[ { "answer_id": 243312, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>I personally would have the SSIS-fed tables in one database (set to simple recovery mode) and the other tables in a separate database on the same server which is set to full recovery mode,. Then I would set up backups on the second datbase on a regular schedule. A typical backup schedule would be full backup once a week, differntials nightly and transaction backups every 15-30 minutes depending on how much data is being input.) Be sure to periodically test recovering the backups, learning how to do that when the customer is screaming becasue the datbase is down isn;t a good thing.</p>\n" }, { "answer_id": 252233, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 1, "selected": true, "text": "<p>I ended up using a DDL trigger to make a copy of changes from one table to the other. The only problem is that if a table or column name contains part of a reserved word - ARCH for VARCHAR - it will cause problems with the modification script.</p>\n\n<p>Thanks, once again, to <a href=\"https://stackoverflow.com/users/26837/brent-ozar\">Brent Ozar</a> for error checking my thoughts before I <a href=\"http://facility9.com/2008/10/28/mirroring-table-changes-through-ddl-triggers/\" rel=\"nofollow noreferrer\">blogged them</a>.</p>\n\n<pre><code>-- Create pvt and pvtWeb as test tables\nCREATE TABLE [dbo].[pvt](\n [VendorID] [int] NULL,\n [Emp1] [int] NULL,\n [Emp2] [int] NULL,\n [Emp3] [int] NULL,\n [Emp4] [int] NULL,\n [Emp5] [int] NULL\n) ON [PRIMARY];\nGO\n\n\nCREATE TABLE [dbo].[pvtWeb](\n [VendorID] [int] NULL,\n [Emp1] [int] NULL,\n [Emp2] [int] NULL,\n [Emp3] [int] NULL,\n [Emp4] [int] NULL,\n [Emp5] [int] NULL\n) ON [PRIMARY];\nGO\n\n\nIF EXISTS(SELECT * FROM sys.triggers WHERE name = ‘ddl_trigger_pvt_alter’)\n DROP TRIGGER ddl_trigger_pvt_alter ON DATABASE;\nGO\n\n-- Create a trigger that will trap ALTER TABLE events\nCREATE TRIGGER ddl_trigger_pvt_alter\nON DATABASE\nFOR ALTER_TABLE\nAS\n DECLARE @data XML;\n DECLARE @tableName NVARCHAR(255);\n DECLARE @newTableName NVARCHAR(255);\n DECLARE @sql NVARCHAR(MAX);\n\n SET @sql = ”;\n -- Store the event in an XML variable\n SET @data = EVENTDATA();\n\n -- Get the name of the table that is being modified\n SELECT @tableName = @data.value(‘(/EVENT_INSTANCE/ObjectName)[1]‘, ‘NVARCHAR(255)’);\n -- Get the actual SQL that was executed\n SELECT @sql = @data.value(‘(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]‘, ‘NVARCHAR(MAX)’);\n\n -- Figure out the name of the new table\n SET @newTableName = @tableName + ‘Web’;\n\n -- Replace the original table name with the new table name\n -- str_replace is from Robyn Page and Phil Factor’s delighful post on \n -- string arrays in SQL. The other posts on string functions are indispensible\n -- to handling string input\n --\n -- http://www.simple-talk.com/sql/t-sql-programming/tsql-string-array-workbench/\n -- http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-1/\n --http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-2/\n SET @sql = dbo.str_replace(@tableName, @newTableName, @sql);\n\n -- Debug the SQL if needed.\n --PRINT @sql;\n\n IF OBJECT_ID(@newTableName, N’U’) IS NOT NULL\n BEGIN\n BEGIN TRY\n -- Now that the table name has been changed, execute the new SQL\n EXEC sp_executesql @sql;\n END TRY\n BEGIN CATCH\n -- Rollback any existing transactions and report the full nasty \n -- error back to the user.\n IF @@TRANCOUNT &gt; 0\n ROLLBACK TRANSACTION;\n\n DECLARE\n @ERROR_SEVERITY INT,\n @ERROR_STATE INT,\n @ERROR_NUMBER INT,\n @ERROR_LINE INT,\n @ERROR_MESSAGE NVARCHAR(4000);\n\n SELECT\n @ERROR_SEVERITY = ERROR_SEVERITY(),\n @ERROR_STATE = ERROR_STATE(),\n @ERROR_NUMBER = ERROR_NUMBER(),\n @ERROR_LINE = ERROR_LINE(),\n @ERROR_MESSAGE = ERROR_MESSAGE();\n\n RAISERROR(‘Msg %d, Line %d, :%s’,\n @ERROR_SEVERITY,\n @ERROR_STATE,\n @ERROR_NUMBER,\n @ERROR_LINE,\n @ERROR_MESSAGE);\n END CATCH\n END\nGO\n\n\n\n\nALTER TABLE pvt\nADD test INT NULL;\nGO\n\nEXEC sp_help pvt;\nGO\n\nALTER TABLE pvt\nDROP COLUMN test;\nGO\n\nEXEC sp_help pvt;\nGO\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11780/" ]
I have a set of tables that are used to track bills. These tables are loaded from an SSIS process that runs weekly. I am in the process of creating a second set of tables to track adjustments to the bills that are made via the web. Some of our clients hand key their bills and all of those entries need to be backed up on a more regular schedule (the SSIS fed data can always be imported again so it isn't backed up). Is there a best practice for this type of behavior? I'm looking at implementing a DDL trigger that will parse the ALTER TABLE call and change the table being called. This is somewhat painful, and I'm curious if there is a better way.
I ended up using a DDL trigger to make a copy of changes from one table to the other. The only problem is that if a table or column name contains part of a reserved word - ARCH for VARCHAR - it will cause problems with the modification script. Thanks, once again, to [Brent Ozar](https://stackoverflow.com/users/26837/brent-ozar) for error checking my thoughts before I [blogged them](http://facility9.com/2008/10/28/mirroring-table-changes-through-ddl-triggers/). ``` -- Create pvt and pvtWeb as test tables CREATE TABLE [dbo].[pvt]( [VendorID] [int] NULL, [Emp1] [int] NULL, [Emp2] [int] NULL, [Emp3] [int] NULL, [Emp4] [int] NULL, [Emp5] [int] NULL ) ON [PRIMARY]; GO CREATE TABLE [dbo].[pvtWeb]( [VendorID] [int] NULL, [Emp1] [int] NULL, [Emp2] [int] NULL, [Emp3] [int] NULL, [Emp4] [int] NULL, [Emp5] [int] NULL ) ON [PRIMARY]; GO IF EXISTS(SELECT * FROM sys.triggers WHERE name = ‘ddl_trigger_pvt_alter’) DROP TRIGGER ddl_trigger_pvt_alter ON DATABASE; GO -- Create a trigger that will trap ALTER TABLE events CREATE TRIGGER ddl_trigger_pvt_alter ON DATABASE FOR ALTER_TABLE AS DECLARE @data XML; DECLARE @tableName NVARCHAR(255); DECLARE @newTableName NVARCHAR(255); DECLARE @sql NVARCHAR(MAX); SET @sql = ”; -- Store the event in an XML variable SET @data = EVENTDATA(); -- Get the name of the table that is being modified SELECT @tableName = @data.value(‘(/EVENT_INSTANCE/ObjectName)[1]‘, ‘NVARCHAR(255)’); -- Get the actual SQL that was executed SELECT @sql = @data.value(‘(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]‘, ‘NVARCHAR(MAX)’); -- Figure out the name of the new table SET @newTableName = @tableName + ‘Web’; -- Replace the original table name with the new table name -- str_replace is from Robyn Page and Phil Factor’s delighful post on -- string arrays in SQL. The other posts on string functions are indispensible -- to handling string input -- -- http://www.simple-talk.com/sql/t-sql-programming/tsql-string-array-workbench/ -- http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-1/ --http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-2/ SET @sql = dbo.str_replace(@tableName, @newTableName, @sql); -- Debug the SQL if needed. --PRINT @sql; IF OBJECT_ID(@newTableName, N’U’) IS NOT NULL BEGIN BEGIN TRY -- Now that the table name has been changed, execute the new SQL EXEC sp_executesql @sql; END TRY BEGIN CATCH -- Rollback any existing transactions and report the full nasty -- error back to the user. IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; DECLARE @ERROR_SEVERITY INT, @ERROR_STATE INT, @ERROR_NUMBER INT, @ERROR_LINE INT, @ERROR_MESSAGE NVARCHAR(4000); SELECT @ERROR_SEVERITY = ERROR_SEVERITY(), @ERROR_STATE = ERROR_STATE(), @ERROR_NUMBER = ERROR_NUMBER(), @ERROR_LINE = ERROR_LINE(), @ERROR_MESSAGE = ERROR_MESSAGE(); RAISERROR(‘Msg %d, Line %d, :%s’, @ERROR_SEVERITY, @ERROR_STATE, @ERROR_NUMBER, @ERROR_LINE, @ERROR_MESSAGE); END CATCH END GO ALTER TABLE pvt ADD test INT NULL; GO EXEC sp_help pvt; GO ALTER TABLE pvt DROP COLUMN test; GO EXEC sp_help pvt; GO ```
243,200
<p>I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.</p> <p>Some examples:</p> <ol> <li><p>Class naming convention to handle namespaces: <code>Part1_Part2_ClassName</code> maps to file <code>Part1/Part2/ClassName.php</code></p></li> <li><p><code>if ( count($arrayName) ) // handles $arrayName being unset or empty</code></p></li> <li><p>Variable function names, e.g. <code>$func = 'foo'; $func($bar); // calls foo($bar);</code></p></li> </ol>
[ { "answer_id": 243254, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 3, "selected": false, "text": "<p>My experience with PHP has taught me a few things. To name a few:</p>\n\n<ul>\n<li>Always output errors. These are the first two lines of my typical project (in development mode):</li>\n</ul>\n\n<pre><code>ini_set('display_errors', '1');\nerror_reporting(E_ALL);</code></pre>\n\n<ul>\n<li><p>Never use <em>automagic</em>. Stuff like autoLoad may bite you in the future.</p></li>\n<li><p>Always require dependent classes using <code>require_once</code>. That way you can be sure you'll have your dependencies straight.</p></li>\n<li><p>Use <code>if(isset($array[$key]))</code> instead of <code>if($array[$key])</code>. The second will raise a warning if the key isn't defined.</p></li>\n<li><p>When defining variables (even with <code>for</code> cycles) give them verbose names (<code>$listIndex</code> instead of <code>$j</code>)</p></li>\n<li><p>Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.</p></li>\n</ul>\n\n<p>Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using <a href=\"http://framework.zend.com/manual/en/coding-standard.naming-conventions.html\" rel=\"noreferrer\">Zend Framework's naming conventions</a> because they feel right to me.</p>\n\n<p>Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the <a href=\"http://pt2.php.net/manual/en/function.debug-backtrace.php\" rel=\"noreferrer\">full backtrace</a>.</p>\n" }, { "answer_id": 243337, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 3, "selected": false, "text": "<p>Fortunately, namespaces are in 5.3 and 6. I would highly recommend against using the Path_To_ClassName idiom. It makes messy code, and you can never change your library structure... ever.</p>\n\n<p>The SPL's autoload is great. If you're organized, it can save you the typical 20-line block of includes and requires at the top of every file. You can also change things around in your code library, and as long as PHP can include from those directories, nothing breaks.</p>\n\n<p>Make liberal use of <code>===</code> over <code>==</code>. For instance:</p>\n\n<pre><code>if (array_search('needle',$array) == false) {\n // it's not there, i think...\n}\n</code></pre>\n\n<p>will give a false negative if 'needle' is at key zero. Instead:</p>\n\n<pre><code>if (array_search('needle',$array) === false) {\n // it's not there!\n}\n</code></pre>\n\n<p>will always be accurate.</p>\n" }, { "answer_id": 243339, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": false, "text": "<p>See this question: <a href=\"https://stackoverflow.com/questions/61401/hidden-features-of-php\">Hidden Features of PHP</a>. It has a lot of really useful PHP tips, the best of which have bubbled up to the top of the list.</p>\n" }, { "answer_id": 243496, "author": "philistyne", "author_id": 16597, "author_profile": "https://Stackoverflow.com/users/16597", "pm_score": 2, "selected": false, "text": "<p>I've been developing with PHP (and MySQL) for the last 5 years. Most recently I started using a framework (<a href=\"http://framework.zend.com\" rel=\"nofollow noreferrer\">Zend</a>) with a solid javascript library (<a href=\"http://www.dojotoolkit.org\" rel=\"nofollow noreferrer\">Dojo</a>) and it's changed the way I work forever (in a good way, I think).</p>\n\n<p>The thing that made me think of this was your first bullet: Zend framework does exactly this as it's standard way of accessing 'controllers' and 'actions'.</p>\n\n<p>In terms of encapsulating and abstracting issues with different databases, Zend_Db this very well. Dojo does an excellent job of ironing out javascript inconsistencies between different browsers.</p>\n\n<p>Overall, it's worth getting into good OOP techniques and using (and READING ABOUT!) frameworks has been a very hands-on way of getting to understand OOP issues.</p>\n\n<p>For some standalone tools worth using, see also:</p>\n\n<p><a href=\"http://www.smarty.net\" rel=\"nofollow noreferrer\">Smarty</a> (template engine)\n<a href=\"http://adodb.sourceforge.net\" rel=\"nofollow noreferrer\">ADODB</a> (database access abstraction)</p>\n" }, { "answer_id": 245488, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 2, "selected": false, "text": "<p>There are a few things I do in PHP that tend to be PHP-specific.</p>\n\n<ol>\n<li><p>Assemble strings with an array.</p>\n\n<p>A lot of string manipulation is expensive in PHP, so I tend to write algorithms that reduce the discrete number of string manipulations I do. The classic example is building a string with a loop. Start with an array(), instead, and do array concatenation in the loop. Then implode() it at the end. (This also neatly solves the trailing-comma problem.)</p></li>\n<li><p>Array constants are nifty for implementing named parameters to functions.</p></li>\n</ol>\n" }, { "answer_id": 245663, "author": "Preston", "author_id": 25213, "author_profile": "https://Stackoverflow.com/users/25213", "pm_score": 4, "selected": false, "text": "<p>Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...</p>\n\n<hr>\n\n<h2>Apply liberally for fun and profit:</h2>\n\n<ol>\n<li><p>Iterators in foreach loops. There's almost never a wrong time.</p></li>\n<li><p>Design around class autoloading. Use <code>spl_autoload_register()</code>, not <code>__autoload()</code>. For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.</p></li>\n<li><p>Typehint everywhere. Use assertions for scalars.</p>\n\n<pre><code>function f(SomeClass $x, array $y, $z) {\n assert(is_bool($z))\n}\n</code></pre></li>\n<li><p>Output something other than HTML.</p>\n\n<pre><code>header('Content-type: text/xml'); // or text/css, application/pdf, or...\n</code></pre></li>\n<li><p>Learn to use exceptions. Write an error handler that converts errors into exceptions.</p></li>\n<li><p>Replace your <code>define()</code> global constants with class constants.</p></li>\n<li><p>Replace your Unix timestamps with a proper <code>Date</code> class.</p></li>\n<li><p>In long functions, <code>unset()</code> variables when you're done with them.</p></li>\n</ol>\n\n<hr>\n\n<h2>Use with guilty pleasure:</h2>\n\n<ol>\n<li><p>Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.</p></li>\n<li><p>Use output buffers for assembling long strings.</p>\n\n<pre><code>ob_start();\necho \"whatever\\n\";\ndebug_print_backtrace();\n$s = ob_get_clean();\n</code></pre></li>\n</ol>\n\n<hr>\n\n<h2>Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:</h2>\n\n<ol>\n<li><p>Magic methods (<code>__get</code>, <code>__set</code>, <code>__call</code>)</p></li>\n<li><p><code>extract()</code></p></li>\n<li><p>Structured arrays -- use an object</p></li>\n</ol>\n" }, { "answer_id": 245714, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 2, "selected": false, "text": "<h2><strong>Declare variables before using them!</strong></h2>\n" }, { "answer_id": 246571, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Enable NOTICE, and if you realy want to STRICT error reporting. It prevents a lot of errors and code smell: <code>ini_set('display_errors', 1); error_reporting(E_ALL &amp;&amp; $_STRICT);</code></li>\n<li>Stay away from global variables</li>\n<li>Keep as many functions as possible short. It reads easier, and is easy to maintain. Some people say that you should be able to see the whole function on your screen, or, at least, that the beginning and end curly brackets of loops and structures in the function should both be on your screen</li>\n<li>Don't trust user input!</li>\n</ol>\n" }, { "answer_id": 452941, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 2, "selected": false, "text": "<p>Get to know the different types and the <code>===</code> operator, it's essential for some functions like <code>strpos()</code> and you'll start to use <code>return false</code> yourself.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4890/" ]
I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations. Some examples: 1. Class naming convention to handle namespaces: `Part1_Part2_ClassName` maps to file `Part1/Part2/ClassName.php` 2. `if ( count($arrayName) ) // handles $arrayName being unset or empty` 3. Variable function names, e.g. `$func = 'foo'; $func($bar); // calls foo($bar);`
Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that... --- Apply liberally for fun and profit: ----------------------------------- 1. Iterators in foreach loops. There's almost never a wrong time. 2. Design around class autoloading. Use `spl_autoload_register()`, not `__autoload()`. For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure. 3. Typehint everywhere. Use assertions for scalars. ``` function f(SomeClass $x, array $y, $z) { assert(is_bool($z)) } ``` 4. Output something other than HTML. ``` header('Content-type: text/xml'); // or text/css, application/pdf, or... ``` 5. Learn to use exceptions. Write an error handler that converts errors into exceptions. 6. Replace your `define()` global constants with class constants. 7. Replace your Unix timestamps with a proper `Date` class. 8. In long functions, `unset()` variables when you're done with them. --- Use with guilty pleasure: ------------------------- 1. Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp. 2. Use output buffers for assembling long strings. ``` ob_start(); echo "whatever\n"; debug_print_backtrace(); $s = ob_get_clean(); ``` --- Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself: ---------------------------------------------------------------------------------------------------------------------------- 1. Magic methods (`__get`, `__set`, `__call`) 2. `extract()` 3. Structured arrays -- use an object
243,206
<p>I'm trying to integrate against a SOAP web service, running on Apache Axis. The WSDL specifies a namespace with a URI, that looks like:</p> <pre><code>&lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:stns="java:dk.tdc.serviceproviderweb.datatypes" elementFormDefault="qualified" attributeFormDefault="qualified" targetNamespace="java:dk.tdc.serviceproviderweb.datatypes"&gt; </code></pre> <p>On the client-side, I'm using PHP, so the namespace <code>xmlns:stns</code> is meaningless. I have some Java class files (and their sources), that seems to correspond to this namespace. How do I handle this in a meaningful way?</p>
[ { "answer_id": 245179, "author": "Dave DiFranco", "author_id": 30547, "author_profile": "https://Stackoverflow.com/users/30547", "pm_score": 1, "selected": true, "text": "<p>Your snippet is the beginning of an XML schema that defines the contents of the \"java:dk.tdc.serviceproviderweb.datatypes\" namespace. (The targetNamespace attribute indicates this).</p>\n\n<p>So it shouldn't matter if you're handling this with java or PHP on the client side,\nas long as the rest of this schema is valid. </p>\n" }, { "answer_id": 248409, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 1, "selected": false, "text": "<p>OK. It seems that I got confused by the fact that my client library had a bug, which made it choke on the wsdl. I switched from NuSOAP to php5's native soap library, and things works now.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180/" ]
I'm trying to integrate against a SOAP web service, running on Apache Axis. The WSDL specifies a namespace with a URI, that looks like: ``` <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:stns="java:dk.tdc.serviceproviderweb.datatypes" elementFormDefault="qualified" attributeFormDefault="qualified" targetNamespace="java:dk.tdc.serviceproviderweb.datatypes"> ``` On the client-side, I'm using PHP, so the namespace `xmlns:stns` is meaningless. I have some Java class files (and their sources), that seems to correspond to this namespace. How do I handle this in a meaningful way?
Your snippet is the beginning of an XML schema that defines the contents of the "java:dk.tdc.serviceproviderweb.datatypes" namespace. (The targetNamespace attribute indicates this). So it shouldn't matter if you're handling this with java or PHP on the client side, as long as the rest of this schema is valid.
243,217
<p>I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example:</p> <pre><code>$value = ( $a == $b ) ? 'true value # 1' : ( $a == $c ) ? 'true value # 2' : 'false value'; </code></pre> <p>Personally which style you use, or find most readable?</p> <p><strong>Edit:</strong> <em>(on when to use ternary-operator)</em></p> <p>I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.</p>
[ { "answer_id": 243226, "author": "Tim", "author_id": 10755, "author_profile": "https://Stackoverflow.com/users/10755", "pm_score": 1, "selected": false, "text": "<p>I don't use it. It always smelled to me like trying to save space and typing in source code with the expectation that small source == more efficient compiled code.</p>\n\n<p>I don't find it readable at all, but much of that is because I just never use it. </p>\n" }, { "answer_id": 243227, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 0, "selected": false, "text": "<p>I tend not to use the ternary operator at all as I find if .. else much more readable.</p>\n" }, { "answer_id": 243229, "author": "biozinc", "author_id": 30698, "author_profile": "https://Stackoverflow.com/users/30698", "pm_score": 5, "selected": false, "text": "<p>Personally, I only use the ternary operator if it fits on one line. If it need to span, then it's time for the good old </p>\n\n<pre><code>if else if else\n</code></pre>\n" }, { "answer_id": 243234, "author": "Rick Kierner", "author_id": 11771, "author_profile": "https://Stackoverflow.com/users/11771", "pm_score": 4, "selected": false, "text": "<p>ternary operators are short effective ways to write simple if statements. They shouldn't be nested or difficult to read. Remember: You write the software once but is is read 100 times. It should be easier to read than write.</p>\n" }, { "answer_id": 243240, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>I'll dissent with the common opinion. I'm sort of like Imran with my conditional operator style. If it fits cleanly on one line, I keep it on one line. If it doesn't fit cleanly on one line, I do break it, but I use only a single tab (4 spaces; I have VS set to insert spaces for tabs) for the indent. I don't immediately jump to <code>if</code>-<code>else</code>, because a lot of the time the conditional operator makes more sense contextually. (If it doesn't make sense contextually, however, I simply don't use it.)</p>\n\n<p>Also, I don't nest conditional operators. At that point, I do find it too difficult to read, and it's time to go to the more verbose <code>if</code>-<code>else</code> style.</p>\n" }, { "answer_id": 243241, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": false, "text": "<p>I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional.</p>\n\n<p>Only if it can fit on a single line, and it's crystal-clear what it means, I use it:</p>\n\n<pre><code>$value = ($a &lt; 0) ? 'minus' : 'plus';\n</code></pre>\n" }, { "answer_id": 243264, "author": "Guillaume Gervais", "author_id": 10687, "author_profile": "https://Stackoverflow.com/users/10687", "pm_score": 3, "selected": false, "text": "<p>I tend to enclose the condition in parentheses : (a == b) ? 1 : 0</p>\n" }, { "answer_id": 243272, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 1, "selected": false, "text": "<p>Imran, you have formatted this beautifully. However, the ternary operator does tend to get unreadable as you nest more than two. an if-else block may give you an extra level of comprehensible nesting. Beyond that, use a function or table-driven programming.</p>\n" }, { "answer_id": 243349, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 8, "selected": true, "text": "<p>The ternary operator is generally to be avoided, but this form can be quite readable:</p>\n\n<pre><code> result = (foo == bar) ? result1 :\n (foo == baz) ? result2 :\n (foo == qux) ? result3 :\n (foo == quux) ? result4 : \n fail_result;\n</code></pre>\n\n<p>This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.</p>\n" }, { "answer_id": 246914, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>$foo = (isset($bar)) ? $bar : 'default';\n</code></pre>\n" }, { "answer_id": 246985, "author": "Vinze", "author_id": 26859, "author_profile": "https://Stackoverflow.com/users/26859", "pm_score": 1, "selected": false, "text": "<p>I personally only use it for an assignment of a variable (in java) for example :</p>\n\n<pre><code>String var = (obj == null) ? \"not set\" : obj.toString();\n</code></pre>\n\n<p>and (other example) when using function that doesn't allow null parameter such as :</p>\n\n<pre><code>String val; [...]\nint var = (val == null) ? 0 : Integer.parseInt(val);\n</code></pre>\n" }, { "answer_id": 283256, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": false, "text": "<p>a style I <em>sometimes</em> use, which I'm bringing up since it hasn't been mentioned, is like this:</p>\n\n<pre><code>$result = ($x == y)\n ? \"foo\"\n : \"bar\";\n</code></pre>\n\n<p>..but usually only if putting it all on one line makes it too long. I find that having the <code>= ? :</code> all line up makes it look neater.</p>\n" }, { "answer_id": 283268, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "<p>The \"contrived example\" is how I would indent it, except that I would indent from the left margin, not based on where the ( or whatever is on the line above.</p>\n\n<p>To the ternary detractors - readability is the point. If you don't think it makes for more readable code, don't use it. But I find the contrary to be the case at least some of the time.</p>\n" }, { "answer_id": 1475108, "author": "Chris Jacob", "author_id": 114140, "author_profile": "https://Stackoverflow.com/users/114140", "pm_score": 4, "selected": false, "text": "<p>PHP nested ternary operators behave differently.</p>\n\n<p>This syntax passes all the following tests.\nBased on <a href=\"http://deadlytechnology.com/web-development-tips/php-ternary-syntax/\" rel=\"noreferrer\">http://deadlytechnology.com/web-development-tips/php-ternary-syntax/</a></p>\n\n<pre><code>$myvar = ($x == $y)\n?(($x == $z)?'both':'foo')\n:(($x == $z)?'bar':'none');\n</code></pre>\n\n<p>.</p>\n\n<p>See: <a href=\"http://au.php.net/ternary\" rel=\"noreferrer\">http://au.php.net/ternary</a></p>\n\n<p>Example #3 \"Non-obvious Ternary Behaviour\" explains why the following does not work in PHP.</p>\n\n<pre><code>$x = 1;\n$y = 2;\n$z = 3; \n$myvar = ($x == $y) \n ? \"foo\" \n : ($x == $z) \n ? \"bar\" \n : \"none\"; \n$myvar == 'none'; // Good\n\n$x = 1;\n$y = 2;\n$z = 1; \n$myvar = ($x == $y) ? \"foo\" : ($x == $z) ? \"bar\" : \"none\"; \n$myvar == 'bar'; // Good\n\n$x = 1;\n$y = 1;\n$z = 3; \n$myvar = ($x == $y) ? \"foo\" : ($x == $z) ? \"bar\" : \"none\"; \n$myvar == 'bar'; // Bad!\n\n$x = 1;\n$y = 1;\n$z = 1; \n$myvar = ($x == $y) ? \"foo\" : ($x == $z) ? \"bar\" : \"none\"; \n$myvar == 'bar'; // Bad!\n</code></pre>\n" }, { "answer_id": 4902530, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 2, "selected": false, "text": "<p>The ternary conditional can make code cleaner and more elegant, and most importantly, help you put emphasis on the right things and avoid repeating yourself. Consider using them, but do not make the code less readable by doing so. In VB.NET:</p>\n<pre><code> 'before refactoring \n If x = 0 Then ' If-Then-Else puts emphasis on flow control\n label = &quot;None&quot;\n Else\n label = Foo.getLabel(x) ' If-Then-Else forces repeat of assignment line\n End If\n\n 'after refactoring \n label = If(x = 0, &quot;None&quot;, Foo.getLabel(x)) ' ternary If puts emphasis on assignment\n</code></pre>\n<p>Note that &quot;it is less readable&quot; is not the same thing as &quot;I'm not used to seeing that&quot;.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897/" ]
I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example: ``` $value = ( $a == $b ) ? 'true value # 1' : ( $a == $c ) ? 'true value # 2' : 'false value'; ``` Personally which style you use, or find most readable? **Edit:** *(on when to use ternary-operator)* I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.
The ternary operator is generally to be avoided, but this form can be quite readable: ``` result = (foo == bar) ? result1 : (foo == baz) ? result2 : (foo == qux) ? result3 : (foo == quux) ? result4 : fail_result; ``` This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.
243,232
<p>Inside my page, I have the following:</p> <pre><code>&lt;aspe:UpdatePanel runat="server" ID="updatePanel"&gt; &lt;ContentTemplate&gt; &lt;local:KeywordSelector runat="server" ID="ksKeywords" /&gt; &lt;/ContentTemplate&gt; &lt;/aspe:UpdatePanel&gt; </code></pre> <p>The <code>KeywordSelector</code> control is a control I define in the same assembly and <code>local</code> is mapped to its namespace.</p> <p>The control is made up of several other controls and is defined as such:</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="KeywordSelector.ascx.cs" Inherits="Keywords.KeywordSelector" %&gt; </code></pre> <p>and has quite a few server controls of its own, all defined as members in the <code>.designer.cs</code> file.</p> <p>However, <strong>during no part of the control's lifecycle does it have any child control objects nor does it produce HTML</strong>:</p> <ol> <li>All of the members defined in the <code>.designer.cs</code> file are <code>null</code>.</li> <li>Calls to <code>HasControls</code> return <code>false</code>.</li> <li>Calls to <code>EnsureChildControls</code> do nothing.</li> <li>The <code>Controls</code> collection is empty.</li> </ol> <p>Removing the <code>UpdatePanel</code> did no good. I tried to reproduce it in a clean page with a new <code>UserControl</code> and the same thing happens.</p> <p>I am using ASP.NET over .NET Framework 3.5 SP1 with the integrated web server.</p> <p>What am I missing here?</p> <p><strong>Update #1:</strong> Following Rob's comment, I looked into <code>OnInit</code> and found that the <code>UserControl</code> does not detect that it has any child controls. Moreover, <code>CreateControlCollection</code> is never called!</p>
[ { "answer_id": 243493, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 6, "selected": true, "text": "<p>Well, I've found the problem(s):</p>\n\n<ol>\n<li><p><em>User Controls</em>, as opposed to <em>Custom Controls</em> must be registered one-by-one in the <em>web.config</em> file. Do this:</p>\n\n<p><code>&lt;add tagPrefix=\"local\" tagName=\"KeywordSelector\" src=\"~/KeywordSelector.ascx\" /&gt;</code></p>\n\n<p>instead of:</p>\n\n<p><code>&lt;add tagPrefix=\"local\" namespace=\"Keywords\" assembly=\"Keywords\" /&gt;</code></p></li>\n<li><p>You should never place a <code>WebControl</code> in the same directory as the <code>Control</code> that is using it. This is downright silly. <a href=\"http://www.mertner.com/morten/?p=31\" rel=\"noreferrer\">Read about it here</a>.</p></li>\n</ol>\n\n<p>Thanks for the help. Now if only I could mark my own answer as <strong>the</strong> answer...</p>\n" }, { "answer_id": 26551804, "author": "vladimir", "author_id": 303298, "author_profile": "https://Stackoverflow.com/users/303298", "pm_score": 1, "selected": false, "text": "<p>In my case the reason was the Resharper 7.1 added incorrect @Register directive at the top of aspx - instead of this desired row:</p>\n\n<pre><code>&lt;%@ Register Src=\"~/Controls/Hello/Hello.ascx\" TagName=\"Hello\" TagPrefix=\"p\" %&gt;\n</code></pre>\n\n<p>i got wrong one:</p>\n\n<pre><code>&lt;%@ Register TagPrefix=\"p\" Namespace=\"MyNamespace.WebApp.Controls\" Assembly=\"MyApp.Web\" %&gt;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4979/" ]
Inside my page, I have the following: ``` <aspe:UpdatePanel runat="server" ID="updatePanel"> <ContentTemplate> <local:KeywordSelector runat="server" ID="ksKeywords" /> </ContentTemplate> </aspe:UpdatePanel> ``` The `KeywordSelector` control is a control I define in the same assembly and `local` is mapped to its namespace. The control is made up of several other controls and is defined as such: ``` <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="KeywordSelector.ascx.cs" Inherits="Keywords.KeywordSelector" %> ``` and has quite a few server controls of its own, all defined as members in the `.designer.cs` file. However, **during no part of the control's lifecycle does it have any child control objects nor does it produce HTML**: 1. All of the members defined in the `.designer.cs` file are `null`. 2. Calls to `HasControls` return `false`. 3. Calls to `EnsureChildControls` do nothing. 4. The `Controls` collection is empty. Removing the `UpdatePanel` did no good. I tried to reproduce it in a clean page with a new `UserControl` and the same thing happens. I am using ASP.NET over .NET Framework 3.5 SP1 with the integrated web server. What am I missing here? **Update #1:** Following Rob's comment, I looked into `OnInit` and found that the `UserControl` does not detect that it has any child controls. Moreover, `CreateControlCollection` is never called!
Well, I've found the problem(s): 1. *User Controls*, as opposed to *Custom Controls* must be registered one-by-one in the *web.config* file. Do this: `<add tagPrefix="local" tagName="KeywordSelector" src="~/KeywordSelector.ascx" />` instead of: `<add tagPrefix="local" namespace="Keywords" assembly="Keywords" />` 2. You should never place a `WebControl` in the same directory as the `Control` that is using it. This is downright silly. [Read about it here](http://www.mertner.com/morten/?p=31). Thanks for the help. Now if only I could mark my own answer as **the** answer...
243,242
<p>I had the following piece of code (simplified for this question):</p> <pre><code>struct StyleInfo { int width; int height; }; typedef int (StyleInfo::*StyleInfoMember); void AddStyleInfoMembers(std::vector&lt;StyleInfoMember&gt;&amp; members) { members.push_back(&amp;StyleInfo::width); members.push_back(&amp;StyleInfo::height); } </code></pre> <p>Now, we had to restructure this a bit, and we did something like this:</p> <pre><code>struct Rectangle { int width; int height; }; struct StyleInfo { Rectangle size; }; typedef int (StyleInfo::*StyleInfoMember); void AddStyleInfoMembers(std::vector&lt;StyleInfoMember&gt;&amp; members) { members.push_back(&amp;StyleInfo::size::width); members.push_back(&amp;StyleInfo::size::height); } </code></pre> <p>If this all looks like a stupid thing to do, or if you feel there's a good opportunity to apply BOOST here for some reason, I must warn you that I really simplified it all down to the problem at hand:</p> <blockquote> <p>error C3083: 'size': the symbol to the left of a '::' must be a type</p> </blockquote> <p>The point I'm trying to make is that I don't know what the correct syntax is to use here. It might be that "StyleInfo" is not the correct type of take the address from to begin with, but in my project I can fix that sort of thing (there's a whole framework there). I simply don't know how to point to this member-within-a-member.</p>
[ { "answer_id": 243396, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "<p>Is it definitely possible? I honestly don't know, never having played much with pointer-to-member.</p>\n\n<p>Suppose you were using non-POD types (I know you aren't, but the syntax would have to support it). Then pointer-to-member might have to encapsulate more than just an offset from the base pointer. There might be indirection as well, depending how multiple inheritance is implemented. With multiple levels of member indirection, this could get arbitrarily complicated, which is a lot to ask for a type that has to have fixed size.</p>\n\n<p>Perhaps you need a vector of pairs, of types defined by:</p>\n\n<pre><code>typedef Rectangle (StyleInfo::*StyleInfoMember);\ntypedef int (Rectangle::*RectangleMember);\n</code></pre>\n\n<p>Apply each in turn to get where you want to be. Of course this still doesn't let you build a vector of mappings from a StyleInfo to arbitrary members-of-members-of StyleInfo, since they wouldn't all go through Rectangle. For that you may need to open a can of functors...</p>\n" }, { "answer_id": 243418, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 0, "selected": false, "text": "<p>size (as in <code>&amp;StyleInfo::size::width</code>) is not the name of a type.</p>\n\n<p>try size->width or size.width instead, depending on how your 'AddStyleInfoMembers` knows about size at all.</p>\n" }, { "answer_id": 243829, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": "<p>Remember a pointer to a member is just used like a member.</p>\n\n<pre><code> Obj x;\n\n int y = (x.*)ptrMem;\n</code></pre>\n\n<p>But like normal members you can not access members of subclasses using the member access mechanism. So what you need to do is access it like you would access a member of the object (in your case via the size member).</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n\n\nstruct Rectangle\n{\n int width;\n int height;\n};\n\nstruct StyleInfo\n{\n Rectangle size;\n};\n\ntypedef Rectangle (StyleInfo::*StyleInfoMember);\ntypedef int (Rectangle::*RectangleMember);\n\ntypedef std::pair&lt;StyleInfoMember,RectangleMember&gt; Access;\n\nvoid AddStyleInfoMembers(std::vector&lt;Access&gt;&amp; members)\n{\n members.push_back(std::make_pair(&amp;StyleInfo::size,&amp;Rectangle::width));\n members.push_back(std::make_pair(&amp;StyleInfo::size,&amp;Rectangle::height));\n}\n\n\nint main()\n{\n std::vector&lt;Access&gt; data;\n AddStyleInfoMembers(data);\n\n StyleInfo obj;\n obj.size.width = 10;\n\n std::cout &lt;&lt; obj.*(data[0].first).*(data[0].second) &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>This is not something I would recommend doing!<br></p>\n\n<p>An alternative (that I recommend even less) is to find the byte offset from the beginning of the class and then just add this to the objects address. Obviously this will involve a lot of casting backwards and forwards so this looks even worse then the above.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/455874/" ]
I had the following piece of code (simplified for this question): ``` struct StyleInfo { int width; int height; }; typedef int (StyleInfo::*StyleInfoMember); void AddStyleInfoMembers(std::vector<StyleInfoMember>& members) { members.push_back(&StyleInfo::width); members.push_back(&StyleInfo::height); } ``` Now, we had to restructure this a bit, and we did something like this: ``` struct Rectangle { int width; int height; }; struct StyleInfo { Rectangle size; }; typedef int (StyleInfo::*StyleInfoMember); void AddStyleInfoMembers(std::vector<StyleInfoMember>& members) { members.push_back(&StyleInfo::size::width); members.push_back(&StyleInfo::size::height); } ``` If this all looks like a stupid thing to do, or if you feel there's a good opportunity to apply BOOST here for some reason, I must warn you that I really simplified it all down to the problem at hand: > > error C3083: 'size': the symbol to the left of a '::' must be a type > > > The point I'm trying to make is that I don't know what the correct syntax is to use here. It might be that "StyleInfo" is not the correct type of take the address from to begin with, but in my project I can fix that sort of thing (there's a whole framework there). I simply don't know how to point to this member-within-a-member.
Remember a pointer to a member is just used like a member. ``` Obj x; int y = (x.*)ptrMem; ``` But like normal members you can not access members of subclasses using the member access mechanism. So what you need to do is access it like you would access a member of the object (in your case via the size member). ``` #include <vector> #include <iostream> struct Rectangle { int width; int height; }; struct StyleInfo { Rectangle size; }; typedef Rectangle (StyleInfo::*StyleInfoMember); typedef int (Rectangle::*RectangleMember); typedef std::pair<StyleInfoMember,RectangleMember> Access; void AddStyleInfoMembers(std::vector<Access>& members) { members.push_back(std::make_pair(&StyleInfo::size,&Rectangle::width)); members.push_back(std::make_pair(&StyleInfo::size,&Rectangle::height)); } int main() { std::vector<Access> data; AddStyleInfoMembers(data); StyleInfo obj; obj.size.width = 10; std::cout << obj.*(data[0].first).*(data[0].second) << std::endl; } ``` This is not something I would recommend doing! An alternative (that I recommend even less) is to find the byte offset from the beginning of the class and then just add this to the objects address. Obviously this will involve a lot of casting backwards and forwards so this looks even worse then the above.
243,266
<p>Core Animation allows for custom animations by implementing the actionForKey method in your CALayer based class:</p> <pre><code>- (id&lt;CAAction&gt;)actionForKey:(NSString *)key { // Custom animations return [super actionForKey:key]; } </code></pre> <p>I can then create an animation and return it for the <code>onOrderIn</code> action (i.e. when the layer is added to another layer). This works just fine. If I do the same for <code>onOrderOut</code> (i.e. the layer is removed from its superlayer), the returned animation is ignored, and the default animation is applied instead.</p> <p>My goal is to zoom the layer in (<code>onOrderIn</code>) and out (<code>onOrderOut</code>):</p> <pre><code>- (id&lt;CAAction&gt;)actionForKey:(NSString *)key { if ([key isEqualToString:@"onOrderIn"] || [key isEqualToString:@"onOrderOut"]) { CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; a.duration = 0.25; a.removedOnCompletion = NO; a.fillMode = kCAFillModeBoth; if ([key isEqualToString:@"onOrderIn"]) { a.fromValue = [NSNumber numberWithFloat:0.0]; a.toValue = [NSNumber numberWithFloat:1.0]; } else { a.fromValue = [NSNumber numberWithFloat:1.0]; a.toValue = [NSNumber numberWithFloat:0.0]; } return a; } return [super actionForKey:key]; } </code></pre> <p>Zooming in works, zooming out does not. Instead the default fade out animation is used. </p> <p>The code might contain some typos, as I'm typing this on another machine.</p> <p>Can anyone help?</p>
[ { "answer_id": 245089, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 0, "selected": false, "text": "<p>Have you verified that your method is being called with <code>key</code> as <code>@\"onOrderOut\"</code> and that your method is returning the correct animation?</p>\n" }, { "answer_id": 1285044, "author": "tjw", "author_id": 11029, "author_profile": "https://Stackoverflow.com/users/11029", "pm_score": 3, "selected": true, "text": "<p>Quoting John Harper on <a href=\"http://lists.apple.com/archives/quartz-dev/2008/Nov/msg00039.html\" rel=\"nofollow noreferrer\">quartz-dev mailing list</a>:</p>\n<blockquote>\n<p>There's a fundamental problem with\nreturning any animation for the\nonOrderOut key—by the time the\nanimation should be running, the layer\nis no longer in the tree, so it has no\neffect. So onOrderOut is not useful\nfor triggering animations; it may be\nuseful for running other code when\nlayers are removed from the tree.</p>\n<p>The best solution I've found for this\n(assuming the default fade transition\non the parent is not what you want,\nwhich it often isn't) is to add custom\nanimations to apply the removal effect\nyou want, then, in the didStop\nanimation delegate, actually remove\nthe layer. It's often convenient to\ncreate a single group of animations\nwith the delegate property set, and\nfillMode=forwards,\nremovedOnCompletion=NO so that you can\nremove the layer at the end of the\nanimation with no possibility of the\nlayer still being visible in its\nnormal state.</p>\n</blockquote>\n<p>If you do many case of this, it is easy to write a common superclass that starts an animation, sets the animation delegate to the class and implements +<code>animationDidStop:</code> to remove the layer w/o animation enabled. This restores the fire-and-forget nature of CoreAnimation that you'd have hoped would be present with the default implementation.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9454/" ]
Core Animation allows for custom animations by implementing the actionForKey method in your CALayer based class: ``` - (id<CAAction>)actionForKey:(NSString *)key { // Custom animations return [super actionForKey:key]; } ``` I can then create an animation and return it for the `onOrderIn` action (i.e. when the layer is added to another layer). This works just fine. If I do the same for `onOrderOut` (i.e. the layer is removed from its superlayer), the returned animation is ignored, and the default animation is applied instead. My goal is to zoom the layer in (`onOrderIn`) and out (`onOrderOut`): ``` - (id<CAAction>)actionForKey:(NSString *)key { if ([key isEqualToString:@"onOrderIn"] || [key isEqualToString:@"onOrderOut"]) { CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; a.duration = 0.25; a.removedOnCompletion = NO; a.fillMode = kCAFillModeBoth; if ([key isEqualToString:@"onOrderIn"]) { a.fromValue = [NSNumber numberWithFloat:0.0]; a.toValue = [NSNumber numberWithFloat:1.0]; } else { a.fromValue = [NSNumber numberWithFloat:1.0]; a.toValue = [NSNumber numberWithFloat:0.0]; } return a; } return [super actionForKey:key]; } ``` Zooming in works, zooming out does not. Instead the default fade out animation is used. The code might contain some typos, as I'm typing this on another machine. Can anyone help?
Quoting John Harper on [quartz-dev mailing list](http://lists.apple.com/archives/quartz-dev/2008/Nov/msg00039.html): > > There's a fundamental problem with > returning any animation for the > onOrderOut key—by the time the > animation should be running, the layer > is no longer in the tree, so it has no > effect. So onOrderOut is not useful > for triggering animations; it may be > useful for running other code when > layers are removed from the tree. > > > The best solution I've found for this > (assuming the default fade transition > on the parent is not what you want, > which it often isn't) is to add custom > animations to apply the removal effect > you want, then, in the didStop > animation delegate, actually remove > the layer. It's often convenient to > create a single group of animations > with the delegate property set, and > fillMode=forwards, > removedOnCompletion=NO so that you can > remove the layer at the end of the > animation with no possibility of the > layer still being visible in its > normal state. > > > If you do many case of this, it is easy to write a common superclass that starts an animation, sets the animation delegate to the class and implements +`animationDidStop:` to remove the layer w/o animation enabled. This restores the fire-and-forget nature of CoreAnimation that you'd have hoped would be present with the default implementation.
243,267
<p>I'm looking for an efficient way of searching through a dataset to see if an item exists. I have an arraylist of ~6000 items and I need to determine which of those doesn't exist in the dataset by comparing each item within the arraylist with data in a particular column of the dataset.</p> <p>I attempted to loop through each item in the dataset for each in the arraylist but that took forever. I then attempted to use the RowFilter method below. None of which looks to be efficient. Any help is greatly appreciated, as you can tell I'm not much of a programmer...</p> <p>example:</p> <pre><code>Dim alLDAPUsers As ArrayList alLDAPUsers = clsLDAP.selectAllStudents Dim curStu, maxStu As Integer maxStu = alLDAPUsers.Count For curStu = 0 To maxStu - 1 Dim DomainUsername As String = "" DomainUsername = alLDAPUsers.Item(curStu).ToString Dim filteredView As DataView filteredView = dsAllStudents.Tables(0).DefaultView filteredView.RowFilter = "" filteredView.RowFilter = "szvausr_un = '" &amp; DomainUsername &amp; "'" Dim returnedrows As Integer = filteredView.Count If returnedrows = 0 Then '' Delete the user... End If Next </code></pre>
[ { "answer_id": 243297, "author": "Brian Boatright", "author_id": 3747, "author_profile": "https://Stackoverflow.com/users/3747", "pm_score": 2, "selected": false, "text": "<p>Try switching your array list to Generics. From what I understand they are much faster than an array list.</p>\n\n<p>Here is a previous SO on <a href=\"https://stackoverflow.com/questions/94884/generics-vs-array-lists\">Generics vs Array List</a> </p>\n" }, { "answer_id": 243309, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You can get better performance by Sorting the list and ordering the dataset. Then you can walk them together, matching as you go. This is especially true since you are probably already ordering the dataset at least (or, you should be) in the sql query that creates it, making that step essentially free. </p>\n\n<p>You should consider using a generic list rather than an ArrayList, and some other stylistic points on your existing code: </p>\n\n<pre><code>Dim LDAPUsers As List(Of String) = clsLDAP.selectAllStudents\n\nFor Each DomainUsername As String in LDAPUsers\n Dim filteredView As DataView = dsAllStudents.Tables(0).DefaultView\n filteredView.RowFilter = \"szvausr_un = '\" &amp; DomainUsername &amp; \"'\"\n\n If filteredView.Count = 0 Then\n '' Delete the user...\n End If\nNext\n</code></pre>\n\n<p>This does the same thing as your original snippet, but in half the space so it's much cleaner and more readable.</p>\n" }, { "answer_id": 243320, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "<p>Get the Dim statements out of the loop.... Your performance is suffering from repeated variable instantiation and reallocation. </p>\n\n<p>Also remove any statements you dont need (rowfilter = \"\")</p>\n\n<pre><code>Dim alLDAPUsers As ArrayList\nDim DomainUsername As String\nDim curStu, maxStu As Integer\nDim filteredView As DataView\nDim returnedrows As Integer\n\nalLDAPUsers = clsLDAP.selectAllStudents\nmaxStu = alLDAPUsers.Count\n\nFor curStu = 0 To maxStu - 1\n DomainUsername = alLDAPUsers.Item(curStu).ToString\n\n\n filteredView = dsAllStudents.Tables(0).DefaultView\n filteredView.RowFilter = \"szvausr_un = '\" &amp; DomainUsername &amp; \"'\"\n\n returnedrows = filteredView.Count\n If returnedrows = 0 Then\n '' Delete the user...\n End If\nNext\n</code></pre>\n" }, { "answer_id": 243389, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 2, "selected": false, "text": "<p>If you use generics as suggested, you can have two Lists of string and do the following:</p>\n\n<pre><code>for each s as string in LDAPUsers.Except(AllStudents)\n ''Delete the user (s)\nnext\n</code></pre>\n\n<p>Where LDAPUsers and AllStudents are both List(Of String)</p>\n\n<p>Edit:</p>\n\n<p>You can also change the except to:</p>\n\n<pre><code>LDAPUsers.Except(AllStudents, StringComparer.InvariantCultureIgnoreCase)\n</code></pre>\n\n<p>to ignore case etc.</p>\n\n<p>Edit 2:</p>\n\n<p>To get the generic lists could be as simple as:</p>\n\n<pre><code>Dim LDAPUsers as new List(Of String)(alLDAPUsers.Cast(Of String))\nDim AllStudents as new List(OfString)()\n\nfor each dr as DataRow in dsAllStudents.Tables(0).Rows\n AllStudents.Add(dr(\"szvausr_un\"))\nnext\n</code></pre>\n\n<p>Or you can go with the Linq-y goodness as Joel mentions, but my exposure to that is limited, unfortunately...</p>\n" }, { "answer_id": 319173, "author": "codeConcussion", "author_id": 1321, "author_profile": "https://Stackoverflow.com/users/1321", "pm_score": 1, "selected": false, "text": "<p>Like others have said, generics or linq would be better options. However, I wanted to point out that you don't need to use a <strong>DataView</strong>. The datatable has a <strong>Select</strong> method...</p>\n\n<pre><code>dsAllStudents.Tables(0).Select(\"szvausr_un = '\" &amp; DomainUserName &amp; \"'\")\n</code></pre>\n\n<p>It returns an array of DataRows. I'm sure it will perform just as poorly as the view but I think it's a little cleaner.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32059/" ]
I'm looking for an efficient way of searching through a dataset to see if an item exists. I have an arraylist of ~6000 items and I need to determine which of those doesn't exist in the dataset by comparing each item within the arraylist with data in a particular column of the dataset. I attempted to loop through each item in the dataset for each in the arraylist but that took forever. I then attempted to use the RowFilter method below. None of which looks to be efficient. Any help is greatly appreciated, as you can tell I'm not much of a programmer... example: ``` Dim alLDAPUsers As ArrayList alLDAPUsers = clsLDAP.selectAllStudents Dim curStu, maxStu As Integer maxStu = alLDAPUsers.Count For curStu = 0 To maxStu - 1 Dim DomainUsername As String = "" DomainUsername = alLDAPUsers.Item(curStu).ToString Dim filteredView As DataView filteredView = dsAllStudents.Tables(0).DefaultView filteredView.RowFilter = "" filteredView.RowFilter = "szvausr_un = '" & DomainUsername & "'" Dim returnedrows As Integer = filteredView.Count If returnedrows = 0 Then '' Delete the user... End If Next ```
Try switching your array list to Generics. From what I understand they are much faster than an array list. Here is a previous SO on [Generics vs Array List](https://stackoverflow.com/questions/94884/generics-vs-array-lists)
243,269
<p>Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening . I can't find in the documentation how this is done - can someone point me in the right direction?</p> <p>We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will take. So we can't do a progress bar, hence the proposal to use this busy wheel.</p>
[ { "answer_id": 243282, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": false, "text": "<p>I'm just guessing here, but I'd imagine it is <a href=\"http://msdn.microsoft.com/en-us/library/wc7bzytb%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">CWaitCursor</a>. Basically, you just create one on the stack, it appears, and disapppears when it is destructed as it goes out of scope e.g.</p>\n\n<pre><code>void DoSomethingSlow()\n{\n CWaitCursor cw;\n.\n.\n.\n.\n}\n</code></pre>\n" }, { "answer_id": 243304, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 4, "selected": true, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/ms940016.aspx\" rel=\"nofollow noreferrer\">SetCursor</a>/<a href=\"http://msdn.microsoft.com/en-us/library/aa453410.aspx\" rel=\"nofollow noreferrer\">LoadCursor</a>/<a href=\"http://msdn.microsoft.com/en-us/library/aa453730.aspx\" rel=\"nofollow noreferrer\">ShowCursor</a> APIs, like this:</p>\n\n<pre><code>SetCursor(LoadCursor(NULL, IDC_WAIT));\n\n// my code\n\nShowCursor(FALSE);\n</code></pre>\n" }, { "answer_id": 243323, "author": "Martin Liesén", "author_id": 20715, "author_profile": "https://Stackoverflow.com/users/20715", "pm_score": 2, "selected": false, "text": "<p>Using compactframework.</p>\n\n<p>Spining wheel:</p>\n\n<p>System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;</p>\n\n<p>Return to normal:</p>\n\n<p>System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;</p>\n" }, { "answer_id": 243336, "author": "Mat Nadrofsky", "author_id": 26853, "author_profile": "https://Stackoverflow.com/users/26853", "pm_score": 0, "selected": false, "text": "<p>From: <a href=\"http://mobiledeveloper.wordpress.com/2006/07/05/wait-cursor/\" rel=\"nofollow noreferrer\">http://mobiledeveloper.wordpress.com/2006/07/05/wait-cursor/</a></p>\n\n<p>Have a look at Cursor.Current = Cursors.WaitCursor;</p>\n\n<pre><code>try {\n Cursor.Current = Cursors.WaitCursor;\n //Do something time consuming…\n}\nfinally {\n Cursor.Current = Cursors.Default;\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21755/" ]
Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening . I can't find in the documentation how this is done - can someone point me in the right direction? We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will take. So we can't do a progress bar, hence the proposal to use this busy wheel.
Use [SetCursor](http://msdn.microsoft.com/en-us/library/ms940016.aspx)/[LoadCursor](http://msdn.microsoft.com/en-us/library/aa453410.aspx)/[ShowCursor](http://msdn.microsoft.com/en-us/library/aa453730.aspx) APIs, like this: ``` SetCursor(LoadCursor(NULL, IDC_WAIT)); // my code ShowCursor(FALSE); ```
243,277
<p>My SQL is rusty -- I have a simple requirement to calculate the sum of the greater of two column values:</p> <pre><code>CREATE TABLE [dbo].[Test] ( column1 int NOT NULL, column2 int NOT NULL ); insert into Test (column1, column2) values (2,3) insert into Test (column1, column2) values (6,3) insert into Test (column1, column2) values (4,6) insert into Test (column1, column2) values (9,1) insert into Test (column1, column2) values (5,8) </code></pre> <p>In the absence of the GREATEST function in SQL Server, I can get the larger of the two columns with this:</p> <pre><code>select column1, column2, (select max(c) from (select column1 as c union all select column2) as cs) Greatest from test </code></pre> <p>And I was hoping that I could simply sum them thus:</p> <pre><code>select sum((select max(c) from (select column1 as c union all select column2) as cs)) from test </code></pre> <p>But no dice:</p> <pre><code>Msg 130, Level 15, State 1, Line 7 Cannot perform an aggregate function on an expression containing an aggregate or a subquery. </code></pre> <p>Is this possible in T-SQL without resorting to a procedure/temp table?</p> <p>UPDATE: Eran, thanks - I used this approach. My final expression is a little more complicated, however, and I'm wondering about performance in this case:</p> <pre><code>SUM(CASE WHEN ABS(column1 * column2) &gt; ABS(column3 * column4) THEN column5 * ABS(column1 * column2) * column6 ELSE column5 * ABS(column3 * column4) * column6 END) </code></pre>
[ { "answer_id": 243292, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>Try this... Its not the best performing option, but should work. </p>\n\n<pre><code>SELECT\n 'LargerValue' = CASE \n WHEN SUM(c1) &gt;= SUM(c2) THEN SUM(c1)\n ELSE SUM(c2)\n END\nFROM Test\n</code></pre>\n" }, { "answer_id": 243308, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 5, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code> SELECT SUM(CASE WHEN column1 &gt; column2 \n THEN column1 \n ELSE column2 END) \n FROM test\n</code></pre>\n" }, { "answer_id": 243326, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT\n SUM(MaximumValue)\nFROM (\n SELECT \n CASE WHEN column1 > column2\n THEN\n column1\n ELSE\n column2\n END AS MaximumValue\n FROM\n Test\n) A</code></pre>\n" }, { "answer_id": 435776, "author": "Sean Reilly", "author_id": 8313, "author_profile": "https://Stackoverflow.com/users/8313", "pm_score": 0, "selected": false, "text": "<p>FYI, the more complicated case should be fine, so long as all of those columns are part of the same table. It's still looking up the same number of rows, so performance should be very similar to the simpler case (as SQL Server performance is usually IO bound).</p>\n" }, { "answer_id": 1665942, "author": "Dev Shah", "author_id": 201476, "author_profile": "https://Stackoverflow.com/users/201476", "pm_score": 0, "selected": false, "text": "<p>How to find max from single row data </p>\n\n<pre><code> -- eg (empid , data1,data2,data3 )\n select emplid , max(tmp.a)\n from\n (select emplid,date1 from table\n union \n select emplid,date2 from table \n union \n select emplid,date3 from table\n ) tmp , table\n where tmp.emplid = table.emplid\n</code></pre>\n" }, { "answer_id": 1678772, "author": "srinivas", "author_id": 203223, "author_profile": "https://Stackoverflow.com/users/203223", "pm_score": 0, "selected": false, "text": "<pre><code>select sum(id) from (\n select (select max(c)\n from (select column1 as c\n union all\n select column2) as cs) id\n from test\n)\n</code></pre>\n" }, { "answer_id": 15667805, "author": "Dominic Goulet", "author_id": 452792, "author_profile": "https://Stackoverflow.com/users/452792", "pm_score": 0, "selected": false, "text": "<p>The best answer to this is simply put :</p>\n\n<pre><code>;With Greatest_CTE As\n(\n Select ( Select Max(ValueField) From ( Values (column1), (column2) ) ValueTable(ValueField) ) Greatest\n From Test\n)\nSelect Sum(Greatest)\n From Greatest_CTE\n</code></pre>\n\n<p>It scales a lot better than the other answers with more than two value columns.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18482/" ]
My SQL is rusty -- I have a simple requirement to calculate the sum of the greater of two column values: ``` CREATE TABLE [dbo].[Test] ( column1 int NOT NULL, column2 int NOT NULL ); insert into Test (column1, column2) values (2,3) insert into Test (column1, column2) values (6,3) insert into Test (column1, column2) values (4,6) insert into Test (column1, column2) values (9,1) insert into Test (column1, column2) values (5,8) ``` In the absence of the GREATEST function in SQL Server, I can get the larger of the two columns with this: ``` select column1, column2, (select max(c) from (select column1 as c union all select column2) as cs) Greatest from test ``` And I was hoping that I could simply sum them thus: ``` select sum((select max(c) from (select column1 as c union all select column2) as cs)) from test ``` But no dice: ``` Msg 130, Level 15, State 1, Line 7 Cannot perform an aggregate function on an expression containing an aggregate or a subquery. ``` Is this possible in T-SQL without resorting to a procedure/temp table? UPDATE: Eran, thanks - I used this approach. My final expression is a little more complicated, however, and I'm wondering about performance in this case: ``` SUM(CASE WHEN ABS(column1 * column2) > ABS(column3 * column4) THEN column5 * ABS(column1 * column2) * column6 ELSE column5 * ABS(column3 * column4) * column6 END) ```
Try this: ``` SELECT SUM(CASE WHEN column1 > column2 THEN column1 ELSE column2 END) FROM test ```
243,351
<p>Is it ever OK to use <code>Environment.TickCount</code>to calculate time spans?</p> <pre><code>int start = Environment.TickCount; // Do stuff int duration = Environment.TickCount - start; Console.WriteLine("That took " + duration " ms"); </code></pre> <p>Because <code>TickCount</code> is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful. </p> <p>I'm using <code>DateTime.Now</code> instead. Is this the best way to do this?</p> <pre><code>DateTime start = DateTime.Now; // Do stuff TimeSpan duration = DateTime.Now - start; Console.WriteLine("That took " + duration.TotalMilliseconds + " ms"); </code></pre>
[ { "answer_id": 243357, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 7, "selected": true, "text": "<p>Use Stopwatch class. There is a decent example on msdn: <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx</a></p>\n\n<pre><code> Stopwatch stopWatch = Stopwatch.StartNew();\n Thread.Sleep(10000);\n stopWatch.Stop();\n // Get the elapsed time as a TimeSpan value.\n TimeSpan ts = stopWatch.Elapsed;\n</code></pre>\n" }, { "answer_id": 243358, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>You probably want <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"noreferrer\"><code>System.Diagnostics.StopWatch</code></a>.</p>\n" }, { "answer_id": 243359, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 3, "selected": false, "text": "<p>Use </p>\n\n<pre><code>System.Diagnostics.Stopwatch\n</code></pre>\n\n<p>It has a property called</p>\n\n<pre><code>EllapsedMilliseconds\n</code></pre>\n" }, { "answer_id": 243362, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 0, "selected": false, "text": "<p>You should use the <a href=\"https://stackoverflow.com/questions/28637/is-datetimenow-the-best-way-to-measure-a-functions-performance\">Stopwatch</a> class instead.</p>\n" }, { "answer_id": 243516, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>I use Environment.TickCount because:</p>\n\n<ol>\n<li>The Stopwatch class is not in the Compact Framework.</li>\n<li>Stopwatch uses the same underlying timing mechanism as TickCount, so the results won't be any more or less accurate.</li>\n<li><strong>The wrap-around problem with TickCount is cosmically unlikely to be hit</strong> (you'd have to leave your computer running for 27 days and then try to measure a time that just happens to span the wrap-around moment), and even if you did hit it the result would be a huge negative time span (so it would kind of stand out).</li>\n</ol>\n\n<p>That being said, I would also recommend using Stopwatch, if it's available to you. Or you could take about 1 minute and write a Stopwatch-like class that wraps Environment.TickCount.</p>\n\n<p>BTW, I see nothing in the Stopwatch documentation that mentions the wrap-around problem with the underlying timer mechanism, so I wouldn't be surprised at all to find that Stopwatch suffers from the same problem. But again, I wouldn't spend any time worrying about it.</p>\n" }, { "answer_id": 244544, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 0, "selected": false, "text": "<p>I was going to say wrap it into a stopwatch class, but Grzenio already said the right thing, so I will give him an uptick. Such encapsulation factors out the decision as to which way is better, and this can change in time. I remember being shocked at how expensive it can be getting the time on some systems, so having one place that can implement the best technique can be very important.</p>\n" }, { "answer_id": 652633, "author": "vanmelle", "author_id": 76365, "author_profile": "https://Stackoverflow.com/users/76365", "pm_score": 0, "selected": false, "text": "<p>For one-shot timing, it's even simpler to write</p>\n\n<pre><code>Stopwatch stopWatch = Stopwatch.StartNew();\n...dostuff...\nDebug.WriteLine(String.Format(\"It took {0} milliseconds\",\n stopWatch.EllapsedMilliseconds)));\n</code></pre>\n\n<p>I'd guess the cosmically unlikely wraparound in TickCount is even less of a concern for StopWatch, given that the ElapsedTicks field is a long. On my machine, StopWatch is high resolution, at 2.4e9 ticks per second. Even at that rate, it would take over 121 years to overflow the ticks field. Of course, I don't know what's going on under the covers, so take that with a grain of salt. However, I notice that the documentation for StopWatch doesn't even mention the wraparound issue, while the doc for TickCount does.</p>\n" }, { "answer_id": 1078089, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Why are you worried about rollover? As long as the duration you are measuring is under 24.9 days and you calculate the <em>relative</em> duration, you're fine. It doesn't matter how long the system has been running, as long as you only concern yourself with your portion of that running time (as opposed to directly performing less-than or greater-than comparisons on the begin and end points). I.e. this:</p>\n\n<pre><code> int before_rollover = Int32.MaxValue - 5;\n int after_rollover = Int32.MinValue + 7;\n int duration = after_rollover - before_rollover;\n Console.WriteLine(\"before_rollover: \" + before_rollover.ToString());\n Console.WriteLine(\"after_rollover: \" + after_rollover.ToString());\n Console.WriteLine(\"duration: \" + duration.ToString());\n</code></pre>\n\n<p>correctly prints:</p>\n\n<pre><code> before_rollover: 2147483642\n after_rollover: -2147483641\n duration: 13\n</code></pre>\n\n<p>You don't have to worry about the sign bit. C#, like C, lets the CPU handle this.</p>\n\n<p>This is a common situation I've run into before with time counts in embedded systems. I would never compare beforerollover &lt; afterrollover directly, for instance. I would always perform the subtraction to find the duration that takes rollover into account, and then base any other calculations on the duration.</p>\n" }, { "answer_id": 6308701, "author": "Mark", "author_id": 90328, "author_profile": "https://Stackoverflow.com/users/90328", "pm_score": 3, "selected": false, "text": "<p>If you're looking for the functionality of <code>Environment.TickCount</code> but without the overhead of creating new <code>Stopwatch</code> objects, you can use the static <code>Stopwatch.GetTimestamp()</code> method (along with <code>Stopwatch.Frequency</code>) to calculate long time spans. Because <code>GetTimestamp()</code> returns a <code>long</code>, it won't overflow for a very, very long time (over 100,000 years, on the machine I'm using to write this). It's also much more accurate than <code>Environment.TickCount</code> which has a maximum resolution of 10 to 16 milliseconds.</p>\n" }, { "answer_id": 8865560, "author": "mistika", "author_id": 725903, "author_profile": "https://Stackoverflow.com/users/725903", "pm_score": 7, "selected": false, "text": "<p><strong>Environment.TickCount</strong> is based on <a href=\"http://msdn.microsoft.com/en-us/library/ms724408.aspx\">GetTickCount()</a> WinAPI function. It's in milliseconds\nBut the actual precision of it is about 15.6 ms. So you can't measure shorter time intervals (or you'll get 0)</p>\n\n<p><em>Note:</em> The returned value is Int32, so this counter rolls over each ~49.7 days. You shouldn't use it to measure such long intervals.</p>\n\n<p><strong>DateTime.Ticks</strong> is based on <a href=\"http://msdn.microsoft.com/en-us/library/ms724397.aspx\">GetSystemTimeAsFileTime</a>() WinAPI function. It's in 100s nanoseconds (tenths of microsoconds).\nThe actual precision of DateTime.Ticks depends on the system. On XP, the increment of system clock is about 15.6 ms, the same as in Environment.TickCount.\nOn Windows 7 its precision is 1 ms (while Environemnt.TickCount's is still 15.6 ms), however if a power saving scheme is used (usually on laptops) it can go down to 15.6 ms as well.</p>\n\n<p><strong>Stopwatch</strong> is based on <a href=\"http://msdn.microsoft.com/en-us/library/ms644904.aspx\">QueryPerformanceCounter()</a> WinAPI function (but if high-resolution performance counter is not supported by your system, DateTime.Ticks is used)</p>\n\n<p>Before using StopWatch notice two problems: </p>\n\n<ul>\n<li>it can be unreliable on multiprocessor systems (see MS <a href=\"http://support.microsoft.com/?scid=kb;en-us;895980\">kb895980</a>, <a href=\"http://support.microsoft.com/?scid=kb;en-us;896256\">kb896256</a>)</li>\n<li>it can be unreliable if CPU frequency varies (read <a href=\"http://www.virtualdub.org/blog/pivot/entry.php?id=106\">this</a> article) </li>\n</ul>\n\n<p>You can evaluate the precision on your system with simple test:</p>\n\n<pre><code>static void Main(string[] args)\n{\n int xcnt = 0;\n long xdelta, xstart;\n xstart = DateTime.UtcNow.Ticks;\n do {\n xdelta = DateTime.UtcNow.Ticks - xstart;\n xcnt++;\n } while (xdelta == 0);\n\n Console.WriteLine(\"DateTime:\\t{0} ms, in {1} cycles\", xdelta / (10000.0), xcnt);\n\n int ycnt = 0, ystart;\n long ydelta;\n ystart = Environment.TickCount;\n do {\n ydelta = Environment.TickCount - ystart;\n ycnt++;\n } while (ydelta == 0);\n\n Console.WriteLine(\"Environment:\\t{0} ms, in {1} cycles \", ydelta, ycnt);\n\n\n Stopwatch sw = new Stopwatch();\n int zcnt = 0;\n long zstart, zdelta;\n\n sw.Start();\n zstart = sw.ElapsedTicks; // This minimizes the difference (opposed to just using 0)\n do {\n zdelta = sw.ElapsedTicks - zstart;\n zcnt++;\n } while (zdelta == 0);\n sw.Stop();\n\n Console.WriteLine(\"StopWatch:\\t{0} ms, in {1} cycles\", (zdelta * 1000.0) / Stopwatch.Frequency, zcnt);\n Console.ReadKey();\n}\n</code></pre>\n" }, { "answer_id": 43338538, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 4, "selected": false, "text": "<p>Environment.TickCount seems to be much faster then the other solutions:</p>\n\n<pre><code>Environment.TickCount 71\nDateTime.UtcNow.Ticks 213\nsw.ElapsedMilliseconds 1273\n</code></pre>\n\n<p>The measurements were generated by the following code:</p>\n\n<pre><code>static void Main( string[] args ) {\n const int max = 10000000;\n //\n //\n for ( int j = 0; j &lt; 3; j++ ) {\n var sw = new Stopwatch();\n sw.Start();\n for ( int i = 0; i &lt; max; i++ ) {\n var a = Environment.TickCount;\n }\n sw.Stop();\n Console.WriteLine( $\"Environment.TickCount {sw.ElapsedMilliseconds}\" );\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for ( int i = 0; i &lt; max; i++ ) {\n var a = DateTime.UtcNow.Ticks;\n }\n sw.Stop();\n Console.WriteLine( $\"DateTime.UtcNow.Ticks {sw.ElapsedMilliseconds}\" );\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for ( int i = 0; i &lt; max; i++ ) {\n var a = sw.ElapsedMilliseconds;\n }\n sw.Stop();\n Console.WriteLine( $\"sw.ElapsedMilliseconds {sw.ElapsedMilliseconds}\" );\n }\n Console.WriteLine( \"Done\" );\n Console.ReadKey();\n}\n</code></pre>\n" }, { "answer_id": 43770774, "author": "Philm", "author_id": 1469896, "author_profile": "https://Stackoverflow.com/users/1469896", "pm_score": 4, "selected": false, "text": "<p>Here is kind of an updated&amp;refreshed summary of what may be the most useful answers &amp; comments in this thread + extra benchmarks and variants:</p>\n\n<p>First thing first: As others have pointed out in comments, things have changed the last years and with \"modern\" Windows (Win XP ++) and .NET, and modern hardware there are no or little reasons not to use Stopwatch(). \nSee <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408%28v=vs.85%29.aspx?f=255&amp;MSPPError=-2147217396#Guidance\" rel=\"noreferrer\">MSDN</a> for details. Quotations:</p>\n\n<blockquote>\n <p>\"Is QPC accuracy affected by processor frequency changes caused by power management or Turbo Boost technology?<br>\n <strong>No.</strong> If the <em>processor has an invariant TSC</em>, the QPC is not affected by these sort of changes. If the processor doesn't have an invariant TSC, QPC will revert to a platform hardware timer that won't be affected by processor frequency changes or Turbo Boost technology. </p>\n \n <p>Does QPC reliably work on multi-processor systems, multi-core system, and systems with hyper-threading?<br>\n <strong>Yes</strong> </p>\n \n <p>How do I determine and validate that QPC works on my machine?<br>\n <strong>You don't need to perform such checks.</strong> </p>\n \n <p>Which processors have non-invariant TSCs?\n [..Read further..]\n \"</p>\n</blockquote>\n\n<p>But if you don't need the precision of Stopwatch() or at least want to know exactly about the performance of Stopwatch (static vs. instance-based) and other possible variants, continue reading:</p>\n\n<p>I took over the benchmark above from cskwg, and extended the code for more variants. I have measured with a some years old i7 4700 MQ and C# 7 with VS 2017 (to be more precise, compiled with .NET 4.5.2, despite binary literals, it is C# 6 (used of this: string literals and 'using static'). Especially the Stopwatch() performance seems to be improved compared to the mentioned benchmark.</p>\n\n<p>This is an example of results of 10 million repetitions in a loop, as always, absolute values are not important, but even the relative values may differ on other hardware:</p>\n\n<p><strong>32 bit, Release mode without optimization:</strong> </p>\n\n<blockquote>\n <p>Measured: GetTickCount64() [ms]: 275<br>\n Measured: Environment.TickCount [ms]: 45<br>\n Measured: DateTime.UtcNow.Ticks [ms]: <strong>167</strong><br>\n Measured: Stopwatch: .ElapsedTicks [ms]: 277<br>\n Measured: Stopwatch: .ElapsedMilliseconds [ms]: 548<br>\n Measured: static Stopwatch.GetTimestamp [ms]: 193<br>\n Measured: Stopwatch+conversion to DateTime [ms]: 551<br>\n Compare that with DateTime.Now.Ticks [ms]: <strong>9010</strong> </p>\n</blockquote>\n\n<p><strong>32 bit, Release mode, optimized:</strong> </p>\n\n<blockquote>\n <p>Measured: GetTickCount64() [ms]: 198<br>\n Measured: Environment.TickCount [ms]: 39<br>\n Measured: DateTime.UtcNow.Ticks [ms]: 66 <strong>(!)</strong><br>\n Measured: Stopwatch: .ElapsedTicks [ms]: 175<br>\n Measured: Stopwatch: .ElapsedMilliseconds [ms]: <strong>491</strong><br>\n Measured: static Stopwatch.GetTimestamp [ms]: 175<br>\n Measured: Stopwatch+conversion to DateTime [ms]: <strong>510</strong><br>\n Compare that with DateTime.Now.Ticks [ms]: <strong>8460</strong> </p>\n</blockquote>\n\n<p><strong>64 bit, Release mode without optimization:</strong> </p>\n\n<blockquote>\n <p>Measured: GetTickCount64() [ms]: 205<br>\n Measured: Environment.TickCount [ms]: 39<br>\n Measured: DateTime.UtcNow.Ticks [ms]: <strong>127</strong><br>\n Measured: Stopwatch: .ElapsedTicks [ms]: 209<br>\n Measured: Stopwatch: .ElapsedMilliseconds [ms]: 285<br>\n Measured: static Stopwatch.GetTimestamp [ms]: 187<br>\n Measured: Stopwatch+conversion to DateTime [ms]: 319<br>\n Compare that with DateTime.Now.Ticks [ms]: 3040 </p>\n</blockquote>\n\n<p><strong>64 bit, Release mode, optimized:</strong> </p>\n\n<blockquote>\n <p>Measured: GetTickCount64() [ms]: 148<br>\n Measured: Environment.TickCount [ms]: 31 <strong>(is it still worth it?)</strong><br>\n Measured: DateTime.UtcNow.Ticks [ms]: 76 <strong>(!)</strong><br>\n Measured: Stopwatch: .ElapsedTicks [ms]: 178<br>\n Measured: Stopwatch: .ElapsedMilliseconds [ms]: 226<br>\n Measured: static Stopwatch.GetTimestamp [ms]: 175<br>\n Measured: Stopwatch+conversion to DateTime [ms]: 246<br>\n Compare that with DateTime.Now.Ticks [ms]: 3020 </p>\n</blockquote>\n\n<p>It may be very interesting, that <em>creating a DateTime value to print out the Stopwatch time seems to have nearly no costs</em>. Interesting in a more academic than practical way is that static Stopwatch is slightly faster (as expected). Some optimization points are quite interesting.\nFor example, I cannot explain why Stopwatch.ElapsedMilliseconds only with 32 bit is so slow compared to it's other variants, for example the static one. This and DateTime.Now more than double their speed with 64 bit.</p>\n\n<p>You can see: Only for millions of executions, the time of Stopwatch begins to matter. If this is really the case (but beware micro-optimizing too early), it may be interesting that with GetTickCount64(), but especially with <strong>DateTime.UtcNow</strong>, you have a 64 bit (long) timer with less precision than Stopwatch, but faster, so that you don't have to mess around with the 32 bit \"ugly\" Environment.TickCount.</p>\n\n<p>As expected, DateTime.Now is by far the slowest of all.</p>\n\n<p>If you run it, the code retrieves also your current Stopwatch accuracy and more.</p>\n\n<p>Here is the full benchmark code:</p>\n\n<pre><code>using System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing static System.Environment;\n</code></pre>\n\n<p>[...]</p>\n\n<pre><code> [DllImport(\"kernel32.dll\") ]\n public static extern UInt64 GetTickCount64(); // Retrieves a 64bit value containing ticks since system start\n\n static void Main(string[] args)\n {\n const int max = 10_000_000;\n const int n = 3;\n Stopwatch sw;\n\n // Following Process&amp;Thread lines according to tips by Thomas Maierhofer: https://codeproject.com/KB/testing/stopwatch-measure-precise.aspx\n // But this somewhat contradicts to assertions by MS in: https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408%28v=vs.85%29.aspx?f=255&amp;MSPPError=-2147217396#Does_QPC_reliably_work_on_multi-processor_systems__multi-core_system__and_________systems_with_hyper-threading\n Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1); // Use only the first core\n Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;\n Thread.CurrentThread.Priority = ThreadPriority.Highest;\n Thread.Sleep(2); // warmup\n\n Console.WriteLine($\"Repeating measurement {n} times in loop of {max:N0}:{NewLine}\");\n for (int j = 0; j &lt; n; j++)\n {\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i &lt; max; i++)\n {\n var tickCount = GetTickCount64();\n }\n sw.Stop();\n Console.WriteLine($\"Measured: GetTickCount64() [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i &lt; max; i++)\n {\n var tickCount = Environment.TickCount; // only int capacity, enough for a bit more than 24 days\n }\n sw.Stop();\n Console.WriteLine($\"Measured: Environment.TickCount [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i &lt; max; i++)\n {\n var a = DateTime.UtcNow.Ticks;\n }\n sw.Stop();\n Console.WriteLine($\"Measured: DateTime.UtcNow.Ticks [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i &lt; max; i++)\n {\n var a = sw.ElapsedMilliseconds;\n }\n sw.Stop();\n Console.WriteLine($\"Measured: Stopwatch: .ElapsedMilliseconds [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i &lt; max; i++)\n {\n var a = Stopwatch.GetTimestamp();\n }\n sw.Stop();\n Console.WriteLine($\"Measured: static Stopwatch.GetTimestamp [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n DateTime dt=DateTime.MinValue; // just init\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i &lt; max; i++)\n {\n var a = new DateTime(sw.Elapsed.Ticks); // using variable dt here seems to make nearly no difference\n }\n sw.Stop();\n //Console.WriteLine($\"Measured: Stopwatch+conversion to DateTime [s] with millisecs: {dt:s.fff}\");\n Console.WriteLine($\"Measured: Stopwatch+conversion to DateTime [ms]: {sw.ElapsedMilliseconds}\");\n\n Console.WriteLine();\n }\n //\n //\n sw = new Stopwatch();\n var tickCounterStart = Environment.TickCount;\n sw.Start();\n for (int i = 0; i &lt; max/10; i++)\n {\n var a = DateTime.Now.Ticks;\n }\n sw.Stop();\n var tickCounter = Environment.TickCount - tickCounterStart;\n Console.WriteLine($\"Compare that with DateTime.Now.Ticks [ms]: {sw.ElapsedMilliseconds*10}\");\n\n Console.WriteLine($\"{NewLine}General Stopwatch information:\");\n if (Stopwatch.IsHighResolution)\n Console.WriteLine(\"- Using high-resolution performance counter for Stopwatch class.\");\n else\n Console.WriteLine(\"- Using high-resolution performance counter for Stopwatch class.\");\n\n double freq = (double)Stopwatch.Frequency;\n double ticksPerMicroSec = freq / (1000d*1000d) ; // microsecond resolution: 1 million ticks per sec\n Console.WriteLine($\"- Stopwatch accuracy- ticks per microsecond (1000 ms): {ticksPerMicroSec:N1}\");\n Console.WriteLine(\" (Max. tick resolution normally is 100 nanoseconds, this is 10 ticks/microsecond.)\");\n\n DateTime maxTimeForTickCountInteger= new DateTime(Int32.MaxValue*10_000L); // tickCount means millisec -&gt; there are 10.000 milliseconds in 100 nanoseconds, which is the tick resolution in .NET, e.g. used for TimeSpan\n Console.WriteLine($\"- Approximated capacity (maxtime) of TickCount [dd:hh:mm:ss] {maxTimeForTickCountInteger:dd:HH:mm:ss}\");\n // this conversion from seems not really accurate, it will be between 24-25 days.\n Console.WriteLine($\"{NewLine}Done.\");\n\n while (Console.KeyAvailable)\n Console.ReadKey(false);\n Console.ReadKey();\n }\n</code></pre>\n" }, { "answer_id": 62860441, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 0, "selected": false, "text": "<h2>Overflow compensation</h2>\n<p>As said before, rollover may happen after 24.9 days, or, if you use an uint cast, after 49.8 days.\nBecause I did not want to pInvoke GetTickCount64, I wrote this overflow compensation. The sample code is using 'byte' to keep the numbers handy. Please have a look at it, it still might contain errors:</p>\n<pre><code>using System;\nnamespace ConsoleApp1 {\n class Program {\n //\n static byte Lower = byte.MaxValue / 3;\n static byte Upper = 2 * byte.MaxValue / 3;\n //\n ///&lt;summary&gt;Compute delta between two TickCount values reliably, because TickCount might wrap after 49.8 days.&lt;/summary&gt;\n static short Delta( byte next, byte ticks ) {\n if ( next &lt; Lower ) {\n if ( ticks &gt; Upper ) {\n return (short) ( ticks - ( byte.MaxValue + 1 + next ) );\n }\n }\n if ( next &gt; Upper ) {\n if ( ticks &lt; Lower ) {\n return (short) ( ( ticks + byte.MaxValue + 1 ) - next );\n }\n }\n return (short) ( ticks - next );\n }\n //\n static void Main( string[] args ) {\n // Init\n Random rnd = new Random();\n int max = 0;\n byte last = 0;\n byte wait = 3;\n byte next = (byte) ( last + wait );\n byte step = 0;\n // Loop tick\n for ( byte tick = 0; true; ) {\n //\n short delta = Delta( next, tick );\n if ( delta &gt;= 0 ) {\n Console.WriteLine( &quot;RUN: last: {0} next: {1} tick: {2} delta: {3}&quot;, last, next, tick, delta );\n last = tick;\n next = (byte) ( last + wait );\n }\n // Will overflow to 0 automatically\n step = (byte) rnd.Next( 0, 11 );\n tick += step;\n max++; if ( max &gt; 99999 ) break;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 62870428, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 1, "selected": false, "text": "<h2>TickCount64</h2>\n<p>Doing some quick measurements on this new function, I found (optimized, release 64-bit, 1000mio loops):</p>\n<pre><code>Environment.TickCount: 2265\nEnvironment.TickCount64: 2531\nDateTime.UtcNow.Ticks: 69016\n</code></pre>\n<p>The measurements for not-optimized code were similar.\nTest code:</p>\n<pre><code>static void Main( string[] args ) {\n long start, end, length = 1000 * 1000 * 1000;\n start = Environment.TickCount64;\n for ( int i = 0; i &lt; length; i++ ) {\n var a = Environment.TickCount;\n }\n end = Environment.TickCount64;\n Console.WriteLine( &quot;Environment.TickCount: {0}&quot;, end - start );\n start = Environment.TickCount64;\n for ( int i = 0; i &lt; length; i++ ) {\n var a = Environment.TickCount64;\n }\n end = Environment.TickCount64;\n Console.WriteLine( &quot;Environment.TickCount64: {0}&quot;, end - start );\n start = Environment.TickCount64;\n for ( int i = 0; i &lt; length; i++ ) {\n var a = DateTime.UtcNow.Ticks;\n }\n end = Environment.TickCount64;\n Console.WriteLine( &quot;DateTime.UtcNow.Ticks: {0}&quot;, end - start );\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27414/" ]
Is it ever OK to use `Environment.TickCount`to calculate time spans? ``` int start = Environment.TickCount; // Do stuff int duration = Environment.TickCount - start; Console.WriteLine("That took " + duration " ms"); ``` Because `TickCount` is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful. I'm using `DateTime.Now` instead. Is this the best way to do this? ``` DateTime start = DateTime.Now; // Do stuff TimeSpan duration = DateTime.Now - start; Console.WriteLine("That took " + duration.TotalMilliseconds + " ms"); ```
Use Stopwatch class. There is a decent example on msdn: <http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx> ``` Stopwatch stopWatch = Stopwatch.StartNew(); Thread.Sleep(10000); stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; ```
243,355
<p>Is there a way to quickly list which sites are on which IP address in IIS 7? </p> <p>If I remember correctly you could sort a view of domains by IP in IIS 6 which was a big help to me in seeing which IPs I had available.</p>
[ { "answer_id": 243370, "author": "Kieron", "author_id": 5791, "author_profile": "https://Stackoverflow.com/users/5791", "pm_score": 2, "selected": false, "text": "<p>You can try this script:</p>\n\n<pre><code>MachineName = \"localhost\"\nIIsObjectPath = \"IIS://\" &amp; MachineName &amp; \"/w3svc\"\n\nWScript.Echo \"Checking : \" &amp; IISObjectPath\n\nSet IIsObject = GetObject(IIsObjectPath)\nfor each obj in IISObject\n if (Obj.Class = \"IIsWebServer\") then\n BindingPath = IIsObjectPath &amp; \"/\" &amp; Obj.Name\n\n Set IIsObjectIP = GetObject(BindingPath)\n wScript.Echo BindingPath &amp; \" - \" &amp; IISObjectIP.ServerComment\n\n ValueList = IISObjectIP.Get(\"ServerBindings\")\n ValueString = \"\"\n For ValueIndex = 0 To UBound(ValueList)\n value = ValueList(ValueIndex)\n Values = split(value, \":\")\n IP = values(0)\n if (IP = \"\") then\n IP = \"(All Unassigned)\"\n end if \n TCP = values(1)\n if (TCP = \"\") then\n TCP = \"80\"\n end if \n HostHeader = values(2)\n\n if (HostHeader &lt;&gt; \"\") then\n wScript.Echo \" IP = \" &amp; IP &amp; \" TCP/IP Port = \" &amp; TCP &amp; \", HostHeader = \" &amp; HostHeader\n else\n wScript.Echo \" IP = \" &amp; IP &amp; \" TCP/IP Port = \" &amp; TCP \n end if\n Next \n wScript.Echo \"\"\n set IISObjectIP = Nothing\n end if\nnext\nset IISObject = Nothing\n</code></pre>\n\n<p>(source www.iisfaq.com)</p>\n" }, { "answer_id": 245593, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 3, "selected": false, "text": "<p>Take a look at <a href=\"http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe/#HowToUse\" rel=\"noreferrer\">APPCMD </a>.</p>\n\n<p>For example, to list all sites on the machine, use this command-line:</p>\n\n<pre><code> %systemroot%\\system32\\inetsrv\\APPCMD list sites\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34548/" ]
Is there a way to quickly list which sites are on which IP address in IIS 7? If I remember correctly you could sort a view of domains by IP in IIS 6 which was a big help to me in seeing which IPs I had available.
Take a look at [APPCMD](http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe/#HowToUse) . For example, to list all sites on the machine, use this command-line: ``` %systemroot%\system32\inetsrv\APPCMD list sites ```
243,363
<p>Can someone explain the structure of a Pid in Erlang?</p> <p>Pids looks like this: <code>&lt;A.B.C&gt;</code>, e.g. <code>&lt;0.30.0&gt;</code> , but I would like to know what is the meaning of these three &quot;bits&quot;: <code>A</code>, <code>B</code> and <code>C</code>.</p> <p><code>A</code> seems to be always <code>0</code> on a local node, but this value changes when the Pid's owner is located on another node.</p> <p>Is it possible to directly send a message on a remote node using only the Pid? Something like that: <code>&lt;4568.30.0&gt; ! Message</code>, without having to explicitly specify the name of the registered process and the node name (<code> {proc_name, Node} ! Message</code>)?</p>
[ { "answer_id": 243519, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 2, "selected": false, "text": "<p>The PID refers to a process and a node table. So you can only send a message directly to a PID if it is known in the node from which you do the call.</p>\n\n<p>It is possible that this will work if the node you do the call from already <a href=\"http://www.erlang.org/doc/reference_manual/part_frame.html\" rel=\"nofollow noreferrer\">knows about</a> the node on which the process is running. </p>\n" }, { "answer_id": 243668, "author": "Jon Gretar", "author_id": 5601, "author_profile": "https://Stackoverflow.com/users/5601", "pm_score": 4, "selected": false, "text": "<p>If I remember this correctly the format is <code>&lt;nodeid,serial,creation&gt;</code>. \n0 is current node much like a computer always has the hostname \"localhost\" to refer to itself. This is by old memory so it might not be 100% correct tough.</p>\n\n<p>But yes. You could build the pid with <code>list_to_pid/1</code> for example.</p>\n\n<pre><code>PidString = \"&lt;0.39.0&gt;\",\nlist_to_pid(PidString) ! message.\n</code></pre>\n\n<p>Of course. You just use whatever method you need to use to build your PidString. Probably write a function that generates it and use that instead of PidString like such:</p>\n\n<pre><code>list_to_pid( make_pid_from_term({proc_name, Node}) ) ! message\n</code></pre>\n" }, { "answer_id": 262179, "author": "archaelus", "author_id": 9040, "author_profile": "https://Stackoverflow.com/users/9040", "pm_score": 7, "selected": true, "text": "<p>Printed process ids &lt; A.B.C > are composed of <a href=\"http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L502\" rel=\"noreferrer\">6</a>:</p>\n\n<ul>\n<li>A, the node number (0 is the local\nnode, an arbitrary number for a remote node) </li>\n<li>B, the first 15 bits of the process number (an index into the process table) <a href=\"http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L534\" rel=\"noreferrer\">7</a></li>\n<li>C, bits 16-18 of the process number (the same process number as B) <a href=\"http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L534\" rel=\"noreferrer\">7</a></li>\n</ul>\n\n<p>Internally, the process number is 28 bits wide on the 32 bit emulator. The odd definition of B and C comes from R9B and earlier versions of Erlang in which B was a 15bit process ID and C was a wrap counter incremented when the max process ID was reached and lower IDs were reused.</p>\n\n<p>In the erlang distribution PIDs are a little larger as they include the node atom as well as the other information. (<a href=\"http://erlang.org/doc/apps/erts/erl_ext_dist.html#8.8\" rel=\"noreferrer\">Distributed PID format</a>)</p>\n\n<p>When an internal PID is sent from one node to the other, it's automatically converted to the external/distributed PID form, so what might be <code>&lt;0.10.0&gt;</code> (<code>inet_db</code>) on one node might end up as <code>&lt;2265.10.0&gt;</code> when sent to another node. You can just send to these PIDs as normal.</p>\n\n<pre><code>% get the PID of the user server on OtherNode\nRemoteUser = rpc:call(OtherNode, erlang,whereis,[user]), \n\ntrue = is_pid(RemoteUser),\n\n% send message to remote PID\nRemoteUser ! ignore_this, \n\n% print \"Hello from &lt;nodename&gt;\\n\" on the remote node's console.\nio:format(RemoteUser, \"Hello from ~p~n\", [node()]). \n</code></pre>\n\n<p>For more information see: <a href=\"http://github.com/mfoemmel/erlang-otp/tree/5b6dd0e84cf0f1dc19ddd05f86cf04b2695d8a9e/erts/emulator/beam/erl_term.h#L498\" rel=\"noreferrer\">Internal PID structure</a>,\n<a href=\"http://github.com/mfoemmel/erlang-otp/tree/5b6dd0e84cf0f1dc19ddd05f86cf04b2695d8a9e/erts/emulator/beam/erl_node_container_utils.h#L24\" rel=\"noreferrer\">Node creation information</a>,\n<a href=\"http://erlang.2086793.n4.nabble.com/PID-recycling-td2108252.html#a2108255\" rel=\"noreferrer\">Node creation counter interaction with EPMD</a></p>\n" }, { "answer_id": 809548, "author": "psyeugenic", "author_id": 99013, "author_profile": "https://Stackoverflow.com/users/99013", "pm_score": 3, "selected": false, "text": "<p>Process id &lt; A.B.C > is composed of:</p>\n\n<ul>\n<li>A, node id which is not arbitrary but the internal index for that node in dist_entry. (It is actually the atom slot integer for the node name.)</li>\n<li>B, process index which refers to the internal index in the proctab, (0 -> MAXPROCS).</li>\n<li>C, Serial which increases every time MAXPROCS has been reached.</li>\n</ul>\n\n<p>The creation tag of 2 bits is not displayed in the pid but is used internally and increases every time the node restarts.</p>\n" }, { "answer_id": 28542245, "author": "nacmartin", "author_id": 225540, "author_profile": "https://Stackoverflow.com/users/225540", "pm_score": 0, "selected": false, "text": "<p>Apart from what others have said, you may find this simple experiment useful to understand what is going on internally:</p>\n\n<pre><code>1&gt; node().\nnonode@nohost\n2&gt; term_to_binary(node()).\n&lt;&lt;131,100,0,13,110,111,110,111,100,101,64,110,111,104,111,\n 115,116&gt;&gt;\n3&gt; self(). \n&lt;0.32.0&gt;\n4&gt; term_to_binary(self()).\n&lt;&lt;131,103,100,0,13,110,111,110,111,100,101,64,110,111,104,\n 111,115,116,0,0,0,32,0,0,0,0,0&gt;&gt;\n</code></pre>\n\n<p>So, you can se that the node name is internally stored in the pid. More info in <a href=\"http://learnyousomeerlang.com/distribunomicon#setting-up-an-erlang-cluster\" rel=\"nofollow\">this section</a> of Learn You Some Erlang.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15539/" ]
Can someone explain the structure of a Pid in Erlang? Pids looks like this: `<A.B.C>`, e.g. `<0.30.0>` , but I would like to know what is the meaning of these three "bits": `A`, `B` and `C`. `A` seems to be always `0` on a local node, but this value changes when the Pid's owner is located on another node. Is it possible to directly send a message on a remote node using only the Pid? Something like that: `<4568.30.0> ! Message`, without having to explicitly specify the name of the registered process and the node name ( `{proc_name, Node} ! Message`)?
Printed process ids < A.B.C > are composed of [6](http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L502): * A, the node number (0 is the local node, an arbitrary number for a remote node) * B, the first 15 bits of the process number (an index into the process table) [7](http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L534) * C, bits 16-18 of the process number (the same process number as B) [7](http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L534) Internally, the process number is 28 bits wide on the 32 bit emulator. The odd definition of B and C comes from R9B and earlier versions of Erlang in which B was a 15bit process ID and C was a wrap counter incremented when the max process ID was reached and lower IDs were reused. In the erlang distribution PIDs are a little larger as they include the node atom as well as the other information. ([Distributed PID format](http://erlang.org/doc/apps/erts/erl_ext_dist.html#8.8)) When an internal PID is sent from one node to the other, it's automatically converted to the external/distributed PID form, so what might be `<0.10.0>` (`inet_db`) on one node might end up as `<2265.10.0>` when sent to another node. You can just send to these PIDs as normal. ``` % get the PID of the user server on OtherNode RemoteUser = rpc:call(OtherNode, erlang,whereis,[user]), true = is_pid(RemoteUser), % send message to remote PID RemoteUser ! ignore_this, % print "Hello from <nodename>\n" on the remote node's console. io:format(RemoteUser, "Hello from ~p~n", [node()]). ``` For more information see: [Internal PID structure](http://github.com/mfoemmel/erlang-otp/tree/5b6dd0e84cf0f1dc19ddd05f86cf04b2695d8a9e/erts/emulator/beam/erl_term.h#L498), [Node creation information](http://github.com/mfoemmel/erlang-otp/tree/5b6dd0e84cf0f1dc19ddd05f86cf04b2695d8a9e/erts/emulator/beam/erl_node_container_utils.h#L24), [Node creation counter interaction with EPMD](http://erlang.2086793.n4.nabble.com/PID-recycling-td2108252.html#a2108255)
243,365
<p>I was just reading this <a href="https://stackoverflow.com/questions/243082/c-casting-programmatically-can-it-be-done">thread</a> and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no better solution in C++, but I was wondering if any gurus out there know of a better way. Generally, I run into this situation when I need to create one of several subclasses of an object based one something unknown at compile time (such as based on a config file). I use the object polymorphically once it is created.</p> <p>There's another related situation when you're using a message-passing scheme (usually over TCP/IP) where each message is an object. I like to implement that pattern as letting each message serialize itself into some serialization stream interface, which works well and is fairly clean on the sending end, but on the receiver, I always find myself examining a header on the message to determine the type, then constructing an appropriate message object using the pattern from the linked article, then having it deserialize itself from the stream. Sometimes I implement it so that the construction and deserialization happen at the same time as part of the constructor, which seems more RAII, but that's small consolation for the mess of if/else statements figuring out the type.</p> <p>Any better solutions out there? If you're going to suggest a 3rd party library, it should be free (and ideally open source) and I'd appreciate it if you could explain how the library accomplishes this feat.</p>
[ { "answer_id": 243401, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 2, "selected": false, "text": "<p>What you're describing here is termed the <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">factory</a> pattern. A variant is the <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">builder</a> pattern. </p>\n" }, { "answer_id": 243405, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 2, "selected": false, "text": "<p>I'd suggest reading the <a href=\"http://www.parashift.com/c++-faq-lite/serialization.html\" rel=\"nofollow noreferrer\">C++ FAQ Lite questions concerning serialisation and unserialisation</a>.</p>\n\n<p>There's a lot of detail in there that I cannot easily summarise in my answer, but those FAQs do cover creating objects whose types are only known at run time.</p>\n\n<p>In particular:</p>\n\n<p><a href=\"http://www.parashift.com/c++-faq-lite/serialization.html#faq-36.8\" rel=\"nofollow noreferrer\">#36.8</a></p>\n\n<p>Although, at the most basic level, you could implement a factory similar to:</p>\n\n<pre><code>Base* Base::get_object(std::string type)\n{\n if (type == \"derived1\") return new Derived1;\n if (type == \"derived2\") return new Derived2;\n}\n</code></pre>\n" }, { "answer_id": 243452, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>Read the classic <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201633612\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Gang Of Four aka GOF</a>.\nConsider [this site[(<a href=\"http://www.dofactory.com/Patterns/PatternAbstract.aspx\" rel=\"nofollow noreferrer\">http://www.dofactory.com/Patterns/PatternAbstract.aspx</a>) for the Factory and other patterns in C#.</p>\n" }, { "answer_id": 243484, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 0, "selected": false, "text": "<p>Unless I'm missing something, you don't need a static_cast in order to create an object whose runtime type is a subclass of the type you're supposed to be returning from your factory, and then use it polymorphically:</p>\n\n<pre><code>class Sub1 : public Super { ... };\nclass Sub2 : public Super { ... };\n\nSuper *factory(int param) {\n if (param == 1) return new Sub1();\n if (param == 2) return new Sub2();\n return new Super();\n}\n\nint main(int argc, char **argv) {\n Super *parser = factory(argc);\n parser-&gt;parse(argv); // parse declared virtual in Super\n delete parser;\n return 0;\n}\n</code></pre>\n\n<p>The pattern the OP is talking about in the question you refer to is to get a Super* from somewhere, then cast it to its runtime type by examining RTTI and having if/else clauses for all the subclasses known to the programmer. This is the exact opposite of \"I use the object polymorphically once it's created\".</p>\n\n<p>In theory, my preferred approach to deserialisation is chain of responsibility: write factories capable of looking at serialised data (including the type header) and deciding for themselves whether they can construct an object from it. For efficiency, have factories register which types they're interested in, so they don't all look at every incoming object, but I've omitted that here:</p>\n\n<pre><code>Super *deserialize(char *data, vector&lt;Deserializer *&gt; &amp;factories&gt;) {\n for (int i = 0; i &lt; factories.size(); ++i) { // or a for_each loop\n Super *result = factories[i]-&gt;deserialize(data);\n if (result != NULL) return result;\n }\n throw stop_wasting_my_time_with_garbage_data();\n}\n</code></pre>\n\n<p>In practice I often end up writing a big switch anyway, like this only with an enumerated type, some named constants, and maybe a virtual deserialize method called after construction:</p>\n\n<pre><code>Super *deserialize(char *data) {\n uint32_t type = *((uint32_t *)data); // or use a stream\n switch(type) {\n case 0: return new Super(data+4);\n case 1: return new Sub1(data+4);\n case 2: return new Sub2(data+4);\n default: throw stop_wasting_my_time_with_garbage_data();\n }\n}\n</code></pre>\n" }, { "answer_id": 243548, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 3, "selected": true, "text": "<p>I think what you are asking is how to keep the object creation code with the objects themselves.</p>\n\n<p>This is usually what I do. It assumes that there is some key that gives you a type (int tag, string, etc). I make a class that has a map of key to factory functions, and a registration function that takes a key and factory function and adds it to the map. There is also a create function that takes a key, looks it up in the map, calls the factory function, and returns the created object. As an example, take a int key, and a stream that contains the rest of the info to build the objects. I haven't tested, or even compiled, this code, but it should give you an idea.</p>\n\n<pre><code>class Factory\n{\n public:\n typedef Object*(*Func)(istream&amp; is);\n static void register(int key, Func f) {m[key] = f;}\n Object* create(key, istream&amp; is) {return m[key](is);}\n private:\n std::map&lt;key, func&gt; m;\n}\n</code></pre>\n\n<p>Then in each class derived from subobject, the register() method is called with the appropriate key and factory method. </p>\n\n<p>To create the object, you just need something like this:</p>\n\n<pre><code>while(cin)\n{\n int key;\n is &gt;&gt; key;\n Object* obj = Factory::Create(key, is);\n // do something with objects\n}\n</code></pre>\n" }, { "answer_id": 244690, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 0, "selected": false, "text": "<p>The fundamental operation of the factory pattern is mapping an identifier to a (usually new) instance of a particular type where the type depends on some property of the identifier. If you don't do that, then it isn't a factory. Everything else is a matter of taste (i.e., performance, maintainability, extensibility, etc.).</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ]
I was just reading this [thread](https://stackoverflow.com/questions/243082/c-casting-programmatically-can-it-be-done) and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no better solution in C++, but I was wondering if any gurus out there know of a better way. Generally, I run into this situation when I need to create one of several subclasses of an object based one something unknown at compile time (such as based on a config file). I use the object polymorphically once it is created. There's another related situation when you're using a message-passing scheme (usually over TCP/IP) where each message is an object. I like to implement that pattern as letting each message serialize itself into some serialization stream interface, which works well and is fairly clean on the sending end, but on the receiver, I always find myself examining a header on the message to determine the type, then constructing an appropriate message object using the pattern from the linked article, then having it deserialize itself from the stream. Sometimes I implement it so that the construction and deserialization happen at the same time as part of the constructor, which seems more RAII, but that's small consolation for the mess of if/else statements figuring out the type. Any better solutions out there? If you're going to suggest a 3rd party library, it should be free (and ideally open source) and I'd appreciate it if you could explain how the library accomplishes this feat.
I think what you are asking is how to keep the object creation code with the objects themselves. This is usually what I do. It assumes that there is some key that gives you a type (int tag, string, etc). I make a class that has a map of key to factory functions, and a registration function that takes a key and factory function and adds it to the map. There is also a create function that takes a key, looks it up in the map, calls the factory function, and returns the created object. As an example, take a int key, and a stream that contains the rest of the info to build the objects. I haven't tested, or even compiled, this code, but it should give you an idea. ``` class Factory { public: typedef Object*(*Func)(istream& is); static void register(int key, Func f) {m[key] = f;} Object* create(key, istream& is) {return m[key](is);} private: std::map<key, func> m; } ``` Then in each class derived from subobject, the register() method is called with the appropriate key and factory method. To create the object, you just need something like this: ``` while(cin) { int key; is >> key; Object* obj = Factory::Create(key, is); // do something with objects } ```
243,368
<p>How do I programmatically reset the Excel <code>Find and Replace</code> dialog box parameters to defaults ("Find what", "Replace with", "Within", "Search", "Look in", "Match case", "Match entire cell contents")?</p> <p>I am using <code>Application.FindFormat.Clear</code> and <code>Application.ReplaceFormat.Clear</code> to reset find and replace cell formats.</p> <p>Interestingly, after using <code>expression.Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords)</code>, the <code>FindWhat</code> string shows in the <code>Find and Replace</code> dialog box but not the <code>ReplaceWhat</code> parameter.</p>
[ { "answer_id": 245276, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 1, "selected": false, "text": "<p>You can use the following command to open the \"Replace\" dialog with fields filled: </p>\n\n<p><strong>Application.Dialogs(xlDialogFormulaReplace).Show -arguments here-</strong></p>\n\n<p>the argument list is</p>\n\n<p>find_text, replace_text, look_at, look_by, active_cell, match_case, match_byte</p>\n\n<hr>\n\n<p>So far, the only way I've found to 'click' the buttons is with SendKey.</p>\n\n<hr>\n\n<p>After much research and testing, I now know exactly what you want to do, but don't think it can be done (without SendKey). It appears that there is a bug in Excel, that won't reset the replacement value (from VBA), no matter what you try and set it to.</p>\n\n<p>I did find this 'faster' way someone posted on MSDN, so you might give it a try.</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/293217af-6c12-4ed2-9021-8eefa71aa98a/\" rel=\"nofollow noreferrer\"><strong>Faster than Replace</strong></a></p>\n" }, { "answer_id": 2061040, "author": "DaveParillo", "author_id": 167483, "author_profile": "https://Stackoverflow.com/users/167483", "pm_score": 3, "selected": false, "text": "<p>You can use this macro to reset find &amp; replace. Unfortunately, you have to call them both as there are one or two arguments unique to each, so if you want to reset everything, you're stuck. There is no 'reset', so the only way I have found is to execute a fake find &amp; replace using the default parameters.</p>\n\n<pre><code>Sub ResetFind()\n Dim r As Range\n\n On Error Resume Next 'just in case there is no active cell\n Set r = ActiveCell\n On Error Goto 0\n\n Cells.Find what:=\"\", _\n After:=ActiveCell, _\n LookIn:=xlFormulas, _\n LookAt:=xlPart, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlNext, _\n MatchCase:=False, _\n SearchFormat:=False\n Cells.Replace what:=\"\", Replacement:=\"\", ReplaceFormat:=False\n\n If Not r Is Nothing Then r.Select\n Set r = Nothing\nEnd Sub\n</code></pre>\n" }, { "answer_id": 26062232, "author": "Mike", "author_id": 4083745, "author_profile": "https://Stackoverflow.com/users/4083745", "pm_score": 0, "selected": false, "text": "<p>No need to use sendkeys you can easily refer to the values you need to reset the dialog box values.</p>\n\n<pre><code>Sub ResetFindReplace()\n 'Resets the find/replace dialog box options\n Dim r As Range\n\n On Error Resume Next\n\n Set r = Cells.Find(What:=\"\", _\n LookIn:=xlFormulas, _\n SearchOrder:=xlRows, _\n LookAt:=xlPart, _\n MatchCase:=False)\n\n On Error GoTo 0\n\n 'Reset the defaults\n\n On Error Resume Next\n\n Set r = Cells.Find(What:=\"\", _\n LookIn:=xlFormulas, _\n SearchOrder:=xlRows, _\n LookAt:=xlPart, _\n MatchCase:=False)\n\n On Error GoTo 0\nEnd Sub\n</code></pre>\n" }, { "answer_id": 27459084, "author": "dave", "author_id": 4356987, "author_profile": "https://Stackoverflow.com/users/4356987", "pm_score": 0, "selected": false, "text": "<p>I tested this and it works. I have borrowed parts from a few places</p>\n\n<pre><code>Sub RR0() 'Replace Reset &amp; Open dialog (specs: clear settings, search columns, match case)\n\n'Dim r As RANGE 'not seem to need\n'Set r = ActiveCell 'not seem to need\nOn Error Resume Next 'just in case there is no active cell\nOn Error GoTo 0\n\nApplication.FindFormat.Clear 'yes\nApplication.ReplaceFormat.Clear 'yes\n\nCells.find what:=\"\", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext\nCells.Replace what:=\"\", Replacement:=\"\", ReplaceFormat:=False, MatchCase:=True 'format not seem to do anything\n'Cells.Replace what:=\"\", Replacement:=\"\", ReplaceFormat:=False 'orig, wo matchcase not work unless put here - in replace\n\n'If Not r Is Nothing Then r.Select 'not seem to need\n'Set r = Nothing\n\n'settings choices:\n'match entire cell: LookAt:=xlWhole, or: LookAt:=xlPart,\n'column or row: SearchOrder:=xlByColumns, or: SearchOrder:=xlByRows,\n\nApplication.CommandBars(\"Edit\").Controls(\"Replace...\").Execute 'YES WORKS\n'Application.CommandBars(\"Edit\").Controls(\"Find...\").Execute 'YES same, easier to manipulate\n'Application.CommandBars.FindControl(ID:=1849).Execute 'YES full find dialog\n\n'PROBLEM: how to expand options?\n'SendKeys (\"%{T}\") 'alt-T works the first time, want options to stay open\n\nApplication.EnableEvents = True 'EVENTS\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 69561199, "author": "UncleBob", "author_id": 3107264, "author_profile": "https://Stackoverflow.com/users/3107264", "pm_score": 0, "selected": false, "text": "<p>Dave Parillo's solution is very good but it does not reset the formatting options of Excel's Find an Replace dialog. The following is more thorough and does reset those options.</p>\n<pre><code>Sub ResetFindAndReplace()\n Dim oldActive As Range, oldSelection As Range\n On Error Resume Next ' just in case there is no active cell\n Set oldActive = ActiveCell\n Set oldSelection = Selection\n On Error GoTo 0 \n Cells.Find what:=&quot;&quot;, _\n After:=ActiveCell, _\n LookIn:=xlFormulas, _\n LookAt:=xlPart, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlNext, _\n MatchCase:=False, _\n SearchFormat:=False\n Cells.Replace what:=&quot;&quot;, Replacement:=&quot;&quot;, ReplaceFormat:=False\n Application.FindFormat.Clear\n ' return selection cell\n If Not oldSelection Is Nothing Then oldSelection.Select \n ' return active cell\n If Not oldActive Is Nothing Then oldActive.Activate\n Set oldActive = Nothing\nEnd Sub\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I programmatically reset the Excel `Find and Replace` dialog box parameters to defaults ("Find what", "Replace with", "Within", "Search", "Look in", "Match case", "Match entire cell contents")? I am using `Application.FindFormat.Clear` and `Application.ReplaceFormat.Clear` to reset find and replace cell formats. Interestingly, after using `expression.Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords)`, the `FindWhat` string shows in the `Find and Replace` dialog box but not the `ReplaceWhat` parameter.
You can use this macro to reset find & replace. Unfortunately, you have to call them both as there are one or two arguments unique to each, so if you want to reset everything, you're stuck. There is no 'reset', so the only way I have found is to execute a fake find & replace using the default parameters. ``` Sub ResetFind() Dim r As Range On Error Resume Next 'just in case there is no active cell Set r = ActiveCell On Error Goto 0 Cells.Find what:="", _ After:=ActiveCell, _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False Cells.Replace what:="", Replacement:="", ReplaceFormat:=False If Not r Is Nothing Then r.Select Set r = Nothing End Sub ```
243,375
<p>I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code:</p> <pre><code>&lt;img src="image.py?text=xxxxxxxxxxxxxx"&gt; </code></pre> <p>The problem is that I expect in the future the "text" field will get very long and the URL will become too large. From Googling around there doesn't seem to be a fixed limit on URL length (ie. depends on the browser, server, proxy, etc.) Is there a better way to do this? </p> <p>If it matters, I am working with Django and Python and I cannot use any client-side scripting (ie. JavaScript).</p> <p>Cheers, Ben</p>
[ { "answer_id": 243393, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 0, "selected": false, "text": "<p>img's use GET. You'll have to come up with another mechanism. How about calling the same functionality in image.py and saving the file as a temp file which you ref in the img tag? Or how about saving the value of text in a db row during the rendering of this img tag and using the row_id as what you pass into the image.py script?</p>\n" }, { "answer_id": 243397, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "<p>Store the text somewhere (e.g. a database) and then pass through the primary key.</p>\n" }, { "answer_id": 243515, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>This will get you an Image as the result of a POST -- you may not like it</p>\n\n<ol>\n<li>Put an iFrame where you want the image and size it and remove scrollbars</li>\n<li>Set the src to a form with hidden inputs set to your post parameters and the action set to the URL that will generate the image</li>\n<li><p>submit the form automatically with JavaScript in the body.onload of the iFrame's HTML</p>\n\n<p>Then, either:</p></li>\n<li><p>Serve back an content-type set to an image and stream the image bytes</p>\n\n<p>or:</p></li>\n<li><p>store the post parameters somewhere and generate a small id</p></li>\n<li><p>serve back HTML with an img tag using the id in the url -- on the server look up the post parameters</p>\n\n<p>or:</p></li>\n<li><p>generate a page with an image tag with an embedded image</p>\n\n<p><a href=\"http://danielmclaren.net/2008/03/embedding-base64-image-data-into-a-webpage\" rel=\"nofollow noreferrer\">http://danielmclaren.net/2008/03/embedding-base64-image-data-into-a-webpage</a></p></li>\n</ol>\n" }, { "answer_id": 243521, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 1, "selected": false, "text": "<p>Putting together what has already been said, how about creating two pages. First page sends a POST request when the form is submitted (lets say to create_img.py) with a text=xxxxxxx... parameter. Then create_img.py takes the text parameter and creates an image with it and inserts it (or a filesystem reference) into the db, then when rendering the second page, generate img tags like <code>&lt;img src=\"render_img.py?row_id=0122\"&gt;</code>. At this point, render_img.py simply queries the db for the given image. Before creating the image you can check to see if its already in the database therefore reusing/recycling previous images with the same text parameter.</p>\n" }, { "answer_id": 243538, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 0, "selected": false, "text": "<p>You may be able to mitigate the problem by compressing the text in the get parameter.</p>\n" }, { "answer_id": 243603, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 0, "selected": false, "text": "<p>From the link below it looks like you'll be fine for a while ;)</p>\n\n<p><a href=\"http://www.boutell.com/newfaq/misc/urllength.html\" rel=\"nofollow noreferrer\">http://www.boutell.com/newfaq/misc/urllength.html</a></p>\n" }, { "answer_id": 243860, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you're using django, maybe you can do this via a template tag instead?</p>\n\n<p>Something like:</p>\n\n<pre><code>&lt;img src=\"{% create_image \"This is the text that will be displayed\" %}\"&gt;\n</code></pre>\n\n<p>The create_image function would create the image with a dummy/random/generated filename, and return the path.</p>\n\n<p>This avoids having to GET or POST to the script, and the images will have manageable filenames.</p>\n\n<p>I can see some potential issues with this approach, I'm just tossing the idea out there ;)</p>\n" }, { "answer_id": 1051870, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>OK, I'm a bit late to the party, but you could use a mix of MHTML (for IE7 and below) and the data URI scheme (for all other modern browsers). It does require a bit of work on both client and server but you can ultimately end up with</p>\n\n<pre><code>newimg.src = 'blah';\n</code></pre>\n\n<p>The write-up on how to do this is at <a href=\"http://gingerbbm.com/?p=127\" rel=\"nofollow noreferrer\">http://gingerbbm.com/?p=127</a>.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27478/" ]
I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code: ``` <img src="image.py?text=xxxxxxxxxxxxxx"> ``` The problem is that I expect in the future the "text" field will get very long and the URL will become too large. From Googling around there doesn't seem to be a fixed limit on URL length (ie. depends on the browser, server, proxy, etc.) Is there a better way to do this? If it matters, I am working with Django and Python and I cannot use any client-side scripting (ie. JavaScript). Cheers, Ben
Store the text somewhere (e.g. a database) and then pass through the primary key.
243,383
<p>I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page:</p> <blockquote> <p>Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++.</p> </blockquote> <p>Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers?</p> <p>Using google, I only found that C can be perfectly parsed with LR(1) but C++ requires LR(∞). </p>
[ { "answer_id": 243447, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 8, "selected": true, "text": "<p>There is an interesting thread on <a href=\"http://lambda-the-ultimate.org/\" rel=\"noreferrer\">Lambda the Ultimate</a> that discusses the <a href=\"http://lambda-the-ultimate.org/node/2158#comment-27800\" rel=\"noreferrer\">LALR grammar for C++</a>. </p>\n\n<p>It includes a link to a <a href=\"http://www.computing.surrey.ac.uk/research/dsrg/fog/FogThesis.pdf\" rel=\"noreferrer\">PhD thesis</a> that includes a discussion of C++ parsing, which states that:</p>\n\n<blockquote>\n <p>\"C++ grammar is ambiguous,\n context-dependent and potentially\n requires infinite lookahead to resolve\n some ambiguities\".</p>\n</blockquote>\n\n<p>It goes on to give a number of examples (see page 147 of the pdf).</p>\n\n<p>The example is:</p>\n\n<pre><code>int(x), y, *const z;\n</code></pre>\n\n<p>meaning</p>\n\n<pre><code>int x;\nint y;\nint *const z;\n</code></pre>\n\n<p>Compare to:</p>\n\n<pre><code>int(x), y, new int;\n</code></pre>\n\n<p>meaning</p>\n\n<pre><code>(int(x)), (y), (new int));\n</code></pre>\n\n<p>(a comma-separated expression).</p>\n\n<p>The two token sequences have the same initial subsequence but different parse trees, which depend on the last element. There can be arbitrarily many tokens before the disambiguating one.</p>\n" }, { "answer_id": 243456, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 3, "selected": false, "text": "<p>I think you are pretty close to the answer. </p>\n\n<p>LR(1) means that parsing from left to right needs only one token to look-ahead for the context, whereas LR(&infin;) means an infinite look-ahead. That is, the parser would have to know everything that was coming in order to figure out where it is now.</p>\n" }, { "answer_id": 1004737, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 8, "selected": false, "text": "<p>LR parsers can't handle ambiguous grammar rules, by design. (Made the theory easier back in the 1970s when the ideas were being worked out).</p>\n\n<p>C and C++ both allow the following statement:</p>\n\n<pre><code>x * y ;\n</code></pre>\n\n<p>It has two different parses:</p>\n\n<ol>\n<li>It can be the declaration of y, as pointer to type x</li>\n<li>It can be a multiply of x and y, throwing away the answer.</li>\n</ol>\n\n<p>Now, you might think the latter is stupid and should be ignored.\nMost would agree with you; however, there are cases where it might\nhave a side effect (e.g., if multiply is overloaded). but that isn't the point.\nThe point is there <em>are</em> two different parses, and therefore a program\ncan mean different things depending on how this <em>should</em> have been parsed.</p>\n\n<p>The compiler must accept the appropriate one under the appropriate circumstances, and in the absence of any other information (e.g., knowledge of the type of x) must collect both in order to decide later what to do. Thus a grammar must allow this. And that makes the grammar ambiguous.</p>\n\n<p>Thus pure LR parsing can't handle this. Nor can many other widely available parser generators, such as Antlr, JavaCC, YACC, or traditional Bison, or even PEG-style parsers, used in a \"pure\" way.</p>\n\n<p>There are lots of more complicated cases (parsing template syntax requires arbitrary lookahead, whereas LALR(k) can look ahead at most k tokens), but only it only takes one counterexample to shoot down <em>pure</em> LR (or the others) parsing.</p>\n\n<p>Most real C/C++ parsers handle this example by using some\nkind of deterministic parser with an extra hack: they intertwine parsing with symbol table\ncollection... so that by the time \"x\" is encountered,\nthe parser knows if x is a type or not, and can thus\nchoose between the two potential parses. But a parser\nthat does this isn't context free, and LR parsers\n(the pure ones, etc.) are (at best) context free.</p>\n\n<p>One can cheat, and add per-rule reduction-time semantic checks in the \nto LR parsers to do this disambiguation. (This code often isn't simple). Most of the other parser types\nhave some means to add semantic checks at various points\nin the parsing, that can be used to do this.</p>\n\n<p>And if you cheat enough, you can make LR parsers work for\nC and C++. The GCC guys did for awhile, but gave it\nup for hand-coded parsing, I think because they wanted\nbetter error diagnostics.</p>\n\n<p>There's another approach, though, which is nice and clean\nand parses C and C++ just fine without any symbol table\nhackery: <a href=\"http://en.wikipedia.org/wiki/GLR_parser\" rel=\"noreferrer\">GLR parsers</a>.\nThese are full context free parsers (having effectively infinite\nlookahead). GLR parsers simply accept <em>both</em> parses,\nproducing a \"tree\" (actually a directed acyclic graph that is mostly tree like) \nthat represents the ambiguous parse. \nA post-parsing pass can resolve the ambiguities.</p>\n\n<p>We use this technique in the C and C++ front ends for our\nDMS Software Reengineering Tookit (as of June 2017\nthese handle full C++17 in MS and GNU dialects).\nThey have been used to process millions of lines\nof large C and C++ systems, with complete, precise parses producing ASTs with complete details of the source code. (See <a href=\"https://stackoverflow.com/a/17393852/120163\">the AST for C++'s most vexing parse.</a>)</p>\n" }, { "answer_id": 1365544, "author": "Sam Harwell", "author_id": 138304, "author_profile": "https://Stackoverflow.com/users/138304", "pm_score": 3, "selected": false, "text": "<p>As you can see in my <a href=\"https://stackoverflow.com/questions/1172939/is-any-part-of-c-syntax-context-sensitive/1173038#1173038\">answer here</a>, C++ contains syntax that cannot be deterministically parsed by an LL or LR parser due to the type resolution stage (typically post-parsing) changing the <em>order of operations</em>, and therefore the fundamental shape of the AST (typically expected to be provided by a first-stage parse).</p>\n" }, { "answer_id": 14852664, "author": "reuns", "author_id": 1952009, "author_profile": "https://Stackoverflow.com/users/1952009", "pm_score": 4, "selected": false, "text": "<p>The problem is never defined like this, whereas it should be interesting :</p>\n\n<p>what is the smallest set of modifications to C++ grammar that would be necessary so that this new grammar could be perfectly parsed by a \"non-context-free\" yacc parser ? (making use only of one 'hack' : the typename/identifier disambiguation, the parser informing the lexer of every typedef/class/struct)</p>\n\n<p>I see a few ones:</p>\n\n<ol>\n<li><p><code>Type Type;</code> is forbidden. An identifier declared as a typename cannot become a non-typename identifier (note that <code>struct Type Type</code> is not ambiguous and could be still allowed).</p>\n\n<p>There are 3 types of <code>names tokens</code> :</p>\n\n<ul>\n<li><code>types</code> : builtin-type or because of a typedef/class/struct</li>\n<li>template-functions</li>\n<li>identifiers : functions/methods and variables/objects</li>\n</ul>\n\n<p>Considering template-functions as different tokens solves the <code>func&lt;</code> ambiguity. If <code>func</code> is a template-function name, then <code>&lt;</code> must be the beginning of a template parameter list, otherwise <code>func</code> is a function pointer and <code>&lt;</code> is the comparison operator.</p></li>\n<li><p><code>Type a(2);</code> is an object instantiation. \n<code>Type a();</code> and <code>Type a(int)</code> are function prototypes.</p></li>\n<li><p><code>int (k);</code> is completely forbidden, should be written <code>int k;</code></p></li>\n<li><p><code>typedef int func_type();</code> and \n<code>typedef int (func_type)();</code> are forbidden. </p>\n\n<p>A function typedef must be a function pointer typedef : <code>typedef int (*func_ptr_type)();</code></p></li>\n<li><p>template recursion is limited to 1024, otherwise an increased maximum could be passed as an option to the compiler.</p></li>\n<li><p><code>int a,b,c[9],*d,(*f)(), (*g)()[9], h(char);</code> could be forbidden too, replaced by <code>int a,b,c[9],*d;</code>\n<code>int (*f)();</code> </p>\n\n<p><code>int (*g)()[9];</code> </p>\n\n<p><code>int h(char);</code> </p>\n\n<p>one line per function prototype or function pointer declaration.</p>\n\n<p>An highly preferred alternative would be to change the awful function pointer syntax, </p>\n\n<p><code>int (MyClass::*MethodPtr)(char*);</code> </p>\n\n<p>being resyntaxed as:</p>\n\n<p><code>int (MyClass::*)(char*) MethodPtr;</code> </p>\n\n<p>this being coherent with the cast operator <code>(int (MyClass::*)(char*))</code></p></li>\n<li><p><code>typedef int type, *type_ptr;</code> could be forbidden too : one line per typedef. Thus it would become</p>\n\n<p><code>typedef int type;</code> </p>\n\n<p><code>typedef int *type_ptr;</code> </p></li>\n<li><p><code>sizeof int</code>, <code>sizeof char</code>, <code>sizeof long long</code> and co. could be declared in each source file.\nThus, each source file making use of the type <code>int</code> should begin with</p>\n\n<p><code>#type int : signed_integer(4)</code></p>\n\n<p>and <code>unsigned_integer(4)</code> would be forbidden outside of that <code>#type</code> directive\nthis would be a big step into the stupid <code>sizeof int</code> ambiguity present in so many C++ headers</p></li>\n</ol>\n\n<p>The compiler implementing the resyntaxed C++ would, if encountering a C++ source making use of ambiguous syntax, move <code>source.cpp</code> too an <code>ambiguous_syntax</code> folder, and would create automatically an unambiguous translated <code>source.cpp</code> before compiling it.</p>\n\n<p>Please add your ambiguous C++ syntaxes if you know some!</p>\n" }, { "answer_id": 51898104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The \"typedef\" problem in C++ can be parsed with an LALR(1) parser that builds a symbol table while parsing (not a pure LALR parser). The \"template\" problem probably cannot be solved with this method. The advantage of this kind of LALR(1) parser is that the grammar (shown below) is an LALR(1) grammar (no ambiguity). </p>\n\n<pre><code>/* C Typedef Solution. */\n\n/* Terminal Declarations. */\n\n &lt;identifier&gt; =&gt; lookup(); /* Symbol table lookup. */\n\n/* Rules. */\n\n Goal -&gt; [Declaration]... &lt;eof&gt; +&gt; goal_\n\n Declaration -&gt; Type... VarList ';' +&gt; decl_\n -&gt; typedef Type... TypeVarList ';' +&gt; typedecl_\n\n VarList -&gt; Var /','... \n TypeVarList -&gt; TypeVar /','...\n\n Var -&gt; [Ptr]... Identifier \n TypeVar -&gt; [Ptr]... TypeIdentifier \n\n Identifier -&gt; &lt;identifier&gt; +&gt; identifier_(1) \n TypeIdentifier -&gt; &lt;identifier&gt; =+&gt; typedefidentifier_(1,{typedef})\n\n// The above line will assign {typedef} to the &lt;identifier&gt;, \n// because {typedef} is the second argument of the action typeidentifier_(). \n// This handles the context-sensitive feature of the C++ language.\n\n Ptr -&gt; '*' +&gt; ptr_\n\n Type -&gt; char +&gt; type_(1)\n -&gt; int +&gt; type_(1)\n -&gt; short +&gt; type_(1)\n -&gt; unsigned +&gt; type_(1)\n -&gt; {typedef} +&gt; type_(1)\n\n/* End Of Grammar. */\n</code></pre>\n\n<p>The following input can be parsed without a problem:</p>\n\n<pre><code> typedef int x;\n x * y;\n\n typedef unsigned int uint, *uintptr;\n uint a, b, c;\n uintptr p, q, r;\n</code></pre>\n\n<p>The <a href=\"http://lrstar.tech\" rel=\"nofollow noreferrer\">LRSTAR parser generator</a> reads the above grammar notation and generates a parser that handles the \"typedef\" problem without ambiguity in the parse tree or AST. (Disclosure: I am the guy who created LRSTAR.)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21711/" ]
I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page: > > Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++. > > > Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers? Using google, I only found that C can be perfectly parsed with LR(1) but C++ requires LR(∞).
There is an interesting thread on [Lambda the Ultimate](http://lambda-the-ultimate.org/) that discusses the [LALR grammar for C++](http://lambda-the-ultimate.org/node/2158#comment-27800). It includes a link to a [PhD thesis](http://www.computing.surrey.ac.uk/research/dsrg/fog/FogThesis.pdf) that includes a discussion of C++ parsing, which states that: > > "C++ grammar is ambiguous, > context-dependent and potentially > requires infinite lookahead to resolve > some ambiguities". > > > It goes on to give a number of examples (see page 147 of the pdf). The example is: ``` int(x), y, *const z; ``` meaning ``` int x; int y; int *const z; ``` Compare to: ``` int(x), y, new int; ``` meaning ``` (int(x)), (y), (new int)); ``` (a comma-separated expression). The two token sequences have the same initial subsequence but different parse trees, which depend on the last element. There can be arbitrarily many tokens before the disambiguating one.
243,388
<p>I <del>understand (I think) the basic idea behind RESTful-ness. Use HTTP methods semantically - GET gets, PUT puts, DELETE deletes, etc... Right?</del> thought I understood the idea behind REST, but I think I'm confusing that with the details of an HTTP implementation. What is the driving idea behind rest, why is this becoming an important thing? Have people actually been using it for a long time, in a corner of the internets that my flashlight never shined upon? <hr/> The Google talk mentions Atom Publishing Protocols having a lot of synergy with RESTful implementations. Any thoughts on that?</p>
[ { "answer_id": 243437, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "<p>REST is an architecture where resources are defined and addressed. </p>\n\n<p>To understand REST best, you should look at the <a href=\"http://en.wikipedia.org/wiki/Resource_oriented_architecture\" rel=\"noreferrer\">Resource Oriented Architecture (ROA)</a> which gives a set of guidelines for when actually implementing the REST architecture. </p>\n\n<p>REST does not need to be over HTTP, but it is the most common. REST was first created by one of the creators of HTTP though. </p>\n" }, { "answer_id": 243518, "author": "miceuz", "author_id": 24443, "author_profile": "https://Stackoverflow.com/users/24443", "pm_score": 4, "selected": false, "text": "<p>HTTP currently is under-used and mis-used.</p>\n\n<p>We usually use only two methods of HTTP: GET and POST, but there are some more: DELETE, PUT, etc (<a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html\" rel=\"noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html</a>)</p>\n\n<p>So if we have resources, defined by RESTful URLs (each domain object in your application has unique URL in form of <a href=\"http://yoursite.com/path/to/the/resource\" rel=\"noreferrer\">http://yoursite.com/path/to/the/resource</a>) and decent HTTP implementation, we can manipulate objects in your domain by writing sentences:</p>\n\n<p>GET <a href=\"http://yoursite.com/path/to/the/resource\" rel=\"noreferrer\">http://yoursite.com/path/to/the/resource</a></p>\n\n<p>DELETE <a href=\"http://yoursite.com/path/to/the/resource\" rel=\"noreferrer\">http://yoursite.com/path/to/the/resource</a></p>\n\n<p>POST <a href=\"http://yoursite.com/path/to/the/resource\" rel=\"noreferrer\">http://yoursite.com/path/to/the/resource</a></p>\n\n<p>etc</p>\n\n<p>the architecture is nice and everything.</p>\n\n<p>but this is just theoretical view, real world scenarios are described in all the links posted in answers before mine.</p>\n" }, { "answer_id": 243714, "author": "bryanbcook", "author_id": 30809, "author_profile": "https://Stackoverflow.com/users/30809", "pm_score": 4, "selected": false, "text": "<p>Here's my view...</p>\n\n<p>The attraction to making RESTful services is that rather than creating web-services with dozens of functional methods, we standardize on <strong>four methods</strong> (Create,Retrieve, Update, Destroy):</p>\n\n<ul>\n<li>POST</li>\n<li>GET</li>\n<li>PUT</li>\n<li>DELETE</li>\n</ul>\n\n<p>REST is becoming popular because it also represents a standardization of messaging formats at the application layer. While HTTP uses the four basic verbs of REST, the common HTTP message format of HTML isn't a contract for building applications.</p>\n\n<p>The best explanation I've heard is a comparison of TCP/IP to RSS.</p>\n\n<p>Ethernet represents a standardization on the physical network. The Internet Protocol (IP) represents a standardization higher up the stack, and has several different flavors (TCP, UDP, etc). The introduction of the \"Transmission Control Protocol\" (guaranteed packet delivery) defined communication contracts that opened us up to a whole new set of services (FTP, Gopher, Telnet, HTTP) for the application layer.</p>\n\n<p>In the analogy, we've adopted XML as the \"Protocol\", we are now beginning to standardize message formats. <strong>RSS</strong> is quickly becoming the basis for many RESTful services. Google's GData API is a RSS/ATOM variant.</p>\n\n<p>The \"desktop gadget\" is a great realization of this hype: a simple client can consume basic web-content or complex-mashups using a common API and messaging standard.</p>\n" }, { "answer_id": 1081615, "author": "pbreitenbach", "author_id": 42048, "author_profile": "https://Stackoverflow.com/users/42048", "pm_score": 7, "selected": true, "text": "<p>This is what REST might look like:</p>\n\n<pre><code>POST /user\nfname=John&amp;lname=Doe&amp;age=25\n</code></pre>\n\n<p>The server responds:</p>\n\n<pre><code>201 Created\nLocation: /user/123\n</code></pre>\n\n<p>In the future, you can then retrieve the user information:</p>\n\n<pre><code>GET /user/123\n</code></pre>\n\n<p>The server responds (assuming an XML response):</p>\n\n<pre><code>200 OK\n&lt;user&gt;&lt;fname&gt;John&lt;/fname&gt;&lt;lname&gt;Doe&lt;/lname&gt;&lt;age&gt;25&lt;/age&gt;&lt;/user&gt;\n</code></pre>\n\n<p>To update:</p>\n\n<pre><code>PUT /user/123\nfname=Johnny\n</code></pre>\n" }, { "answer_id": 32514703, "author": "Sumit Arora", "author_id": 671170, "author_profile": "https://Stackoverflow.com/users/671170", "pm_score": 3, "selected": false, "text": "<p>Lets go to history, Talk about the Roy Fielding Research – “<a href=\"https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf\" rel=\"noreferrer\">Architectural Styles and the Design of Network-based Software Architectures</a>“. Its a big paper and talks a lot of various stuff. But as a standard engineer How you would like to explain the clear meaning of REST (Representational State Transfer), and what is its Architectural Style.</p>\n\n<p>Here is my way to explain – “What is REST”.</p>\n\n<p>See this www(world wide web) running on top of various hardwares e.g. routers,servers,firewalls, cloud infrastructures,switches,LAN,WAN. The overall objective of this www(world wide web) to distribute <a href=\"https://en.wikipedia.org/wiki/Hypermedia\" rel=\"noreferrer\">hypermedia</a>. This world wide web equipped with various services e.g. informational based services, websites, youtube channels, dynamic websites, static websites. This world wide web uses HTTP protocol to distribute hypermedia across the world with a client/server mechanism. This HTTP Protocol works on top of TCP/IP or other appropriate network stack.</p>\n\n<p>This <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616.txt\" rel=\"noreferrer\">HTTP protocol</a> is using eight methods to manage the ‘protocol of distribution’ or ‘Architectural Style of Distribution’. Those eight methods are namely : OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT.</p>\n\n<p>But on Top of this HTTP, web applications are using its own way of distributing hypermedia e.g web applications are using web services which are highly tied with clients and servers ‘or’ web applications are using its own way of designed client/server mechanism to make such distribution channel on top of HTTP.</p>\n\n<p>What <a href=\"http://www.cs.colorado.edu/~kena/classes/7818/f08/lectures/lecture_9_fielding_disserta.pdf\" rel=\"noreferrer\">Roy Fielding Research</a> says , that these eight methods OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT of HTTP are so successful to deliver HyperMedia to all across the world on top of variety of hardware resources and network stacks with client/server mechanism, Why don’t we use the similar strategy with our web based application as well. On this GET,POST,DELETE and PUT are used the most. so four methods deliver HyperMedia to all across the world.</p>\n\n<p>In REST API <strong><a href=\"https://en.wikipedia.org/wiki/Architectural_style\" rel=\"noreferrer\">Architecture Style</a></strong> application, a web application need to design the business logic(resides in a server e.g. Tomcat,Apache HTTP) with all set of object entities(e.g. Customer is an entity) and possible operations(e.g.‘Retrieve Customer Information based on a customer id’) on them. Those possible operations with these entities should be designed with four main operations or methods namely- Create,Retrieve,Update,Delete. These entities called as resources and these are <strong>presented</strong> or <strong>represented</strong> in a form e.g. JSON or XML or something else. We have Client(Browsers) who calls Create,Retrieve,Update,Delete <strong>(CRUD)</strong> methods to perform the appropriate function on such resource resides in the Server.</p>\n\n<p>But as explained the concept of <strong>Representation</strong>, means the way entities of business logic or objects are represented. but what about with ‘State Transfer’ ?.</p>\n\n<p>The <strong>State Transfer</strong>, its talks about the “state of communication” from Client to Server. It talks about the design of ‘state transfers’ from Client to Server e.g. Client first called the operation ‘Create Customer’, after calling this what would be next state of customer or states of customer which ‘client’ can call. Its state may be to ‘retrieve the created client data’, ‘update the client data’ or what</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
I ~~understand (I think) the basic idea behind RESTful-ness. Use HTTP methods semantically - GET gets, PUT puts, DELETE deletes, etc... Right?~~ thought I understood the idea behind REST, but I think I'm confusing that with the details of an HTTP implementation. What is the driving idea behind rest, why is this becoming an important thing? Have people actually been using it for a long time, in a corner of the internets that my flashlight never shined upon? --- The Google talk mentions Atom Publishing Protocols having a lot of synergy with RESTful implementations. Any thoughts on that?
This is what REST might look like: ``` POST /user fname=John&lname=Doe&age=25 ``` The server responds: ``` 201 Created Location: /user/123 ``` In the future, you can then retrieve the user information: ``` GET /user/123 ``` The server responds (assuming an XML response): ``` 200 OK <user><fname>John</fname><lname>Doe</lname><age>25</age></user> ``` To update: ``` PUT /user/123 fname=Johnny ```
243,409
<p>I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER.</p> <p>Currently, I have something like:</p> <pre><code>Session s = HibernateUtil.getSessionFactory().openSession(); MyClass c = (MyClass)session.get(MyClass.class, myClassID); </code></pre>
[ { "answer_id": 243488, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 4, "selected": true, "text": "<p>You could try something like this: (code off the top of my head)</p>\n\n<pre><code>Criteria crit = session.createCriteria(MyClass.class);\ncrit.add(Restrictions.eq(\"id\", myClassId));\ncrit.setFetchMode(\"myProperty\", FetchMode.EAGER);\nMyClass myThingy = (MyClass)crit.uniqueResult();\n</code></pre>\n\n<p>I believe that FetchMode.JOIN or FetchMode.SELECT should be used instead of FetchMode.EAGER, though.</p>\n" }, { "answer_id": 243555, "author": "Henning", "author_id": 29549, "author_profile": "https://Stackoverflow.com/users/29549", "pm_score": 1, "selected": false, "text": "<p>There is a static <code>initialize(Object)</code> method in the <code>Hibernate</code> main class. You could use that to force loading of your collection:</p>\n\n<pre><code>MyClass c = (MyClass)session.get(MyClass.class, myClassID);\nHibernate.initialize(c.getMySetOfMyClass2());\n</code></pre>\n\n<p>However, a default value of lazy fetching is just that: a <em>default</em> value. You probably want to override the laziness in the mapping for your particular Set.</p>\n" }, { "answer_id": 243642, "author": "Damo", "author_id": 2955, "author_profile": "https://Stackoverflow.com/users/2955", "pm_score": 2, "selected": false, "text": "<p>If you're not using Criteria there's also the <code>JOIN FETCH</code> keyword that will eagerly load the association specified by the join.</p>\n\n<pre><code>session.createQuery(\"select p from Parent p join fetch p.children c\")\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER. Currently, I have something like: ``` Session s = HibernateUtil.getSessionFactory().openSession(); MyClass c = (MyClass)session.get(MyClass.class, myClassID); ```
You could try something like this: (code off the top of my head) ``` Criteria crit = session.createCriteria(MyClass.class); crit.add(Restrictions.eq("id", myClassId)); crit.setFetchMode("myProperty", FetchMode.EAGER); MyClass myThingy = (MyClass)crit.uniqueResult(); ``` I believe that FetchMode.JOIN or FetchMode.SELECT should be used instead of FetchMode.EAGER, though.
243,417
<p>How do you pass "this" to the constructor for ObjectDataProvider in XAML.</p> <p>Lets say my presenter class is:</p> <pre><code>public class ApplicationPresenter(IView view){} </code></pre> <p>and that my UserControl implements IView.</p> <p>What do I pass to the ConstructorParameters in the code below so that the UserControl can create the ApplicationPresenter using the default constructor? </p> <pre><code>&lt;ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type Fenix_Presenters:ApplicationPresenter}" ConstructorParameters="{ ?? what goes here ??}" d:IsDataSource="True" /&gt; </code></pre> <p>I only need to do this so that I can use Blend 2. I know that I can do this in the code behind, but if I do I can't instantiate the class from within Blend. I also know that I can create a parameterless constructor for ApplicationPresenter and pass it a dummy class that implements IView, but I would rather do this in markup if at all possible.</p> <p>My code behind at the moment is:</p> <pre><code>public MyUserControl() { InitializeComponent(); DataContext = new ApplicationPresenter(this); } </code></pre>
[ { "answer_id": 243429, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "<p>i don't know if it works, but you could give your user control a name , e.g.</p>\n\n<pre><code>x:Name=\"myUserCotrol\"\n</code></pre>\n\n<p>and then use it in a binding:</p>\n\n<pre><code>... ConstructorParameters=\"{Binding ElementName=myUserControl}\" ...\n</code></pre>\n\n<p>this could work</p>\n" }, { "answer_id": 247965, "author": "Jeremy Holt", "author_id": 30046, "author_profile": "https://Stackoverflow.com/users/30046", "pm_score": 1, "selected": false, "text": "<p>I'm just starting with Wpf and was under the misapprehension that I should be trying to do everything in XAML. I've just watched a few videos from <a href=\"http://windowsclient.net/\" rel=\"nofollow noreferrer\">WindowsClient.net</a> which are starting to clear some things up. But boy is this a complex technology!!!</p>\n" }, { "answer_id": 259945, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 0, "selected": false, "text": "<p>This will be directly supported (if memory serves well) in the next version of XAML as <a href=\"http://blogs.windowsclient.net/rob_relyea/archive/2008/10/31/pdc08-news-xaml-in-net-4-xaml2009-amp-system-xaml-dll.aspx\" rel=\"nofollow noreferrer\">demonstrated by Rob Relyea at this year's PDC</a>.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30046/" ]
How do you pass "this" to the constructor for ObjectDataProvider in XAML. Lets say my presenter class is: ``` public class ApplicationPresenter(IView view){} ``` and that my UserControl implements IView. What do I pass to the ConstructorParameters in the code below so that the UserControl can create the ApplicationPresenter using the default constructor? ``` <ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type Fenix_Presenters:ApplicationPresenter}" ConstructorParameters="{ ?? what goes here ??}" d:IsDataSource="True" /> ``` I only need to do this so that I can use Blend 2. I know that I can do this in the code behind, but if I do I can't instantiate the class from within Blend. I also know that I can create a parameterless constructor for ApplicationPresenter and pass it a dummy class that implements IView, but I would rather do this in markup if at all possible. My code behind at the moment is: ``` public MyUserControl() { InitializeComponent(); DataContext = new ApplicationPresenter(this); } ```
I'm just starting with Wpf and was under the misapprehension that I should be trying to do everything in XAML. I've just watched a few videos from [WindowsClient.net](http://windowsclient.net/) which are starting to clear some things up. But boy is this a complex technology!!!
243,464
<p>I was mapping a relation using something like the following </p> <pre><code>&lt;map name="Foo" cascade="all-delete-orphan" lazy="false"&gt; &lt;key column="FooId"/&gt; &lt;index column="FooType" type="Domain.Enum.FooType, Domain"/&gt; &lt;element column ="FooStatus" type="Domain.Enum.FooStatus, Domain"/&gt; &lt;/map&gt; </code></pre> <p>The class is like this</p> <pre><code>namespace Domain { public class Enum { public enum FooType { Foo1, Foo2, ... Foo50} public enum FooStatus { NotNeeded, NeededFor1, NeededFor2, NeededFor3, NiceToHave} } } </code></pre> <p>Can I do this using Fluent Nhibernate? If not can I map a class mixing Fluent and XML?</p>
[ { "answer_id": 247036, "author": "Nikelman", "author_id": 32388, "author_profile": "https://Stackoverflow.com/users/32388", "pm_score": 0, "selected": false, "text": "<p>Forget to add </p>\n\n<pre><code>namespace Domain \n{\npublic virtual IDictionary&lt;FooType, FooStatus&gt; MyFoo { set; get; }\n}\n</code></pre>\n" }, { "answer_id": 266607, "author": "Nikelman", "author_id": 32388, "author_profile": "https://Stackoverflow.com/users/32388", "pm_score": 1, "selected": false, "text": "<p>ANSWER From Fluent NHibernate Google group were I asked the same question</p>\n\n<p>The short answer is no, you cannot do this with the fluent interface at the \nmoment. My initial implementation of AsMap() was rather naive and does not \nsupport your scenario. I will raise it as an issue and get back to you once \na fix is in place but in the meantime you should be able to work around it \nby mixing xml with fluent mappings. I know we have several users that are \ncurrently doing this. The exact steps would depend on how you have it set \nup. </p>\n\n<p>Paul Batum </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I was mapping a relation using something like the following ``` <map name="Foo" cascade="all-delete-orphan" lazy="false"> <key column="FooId"/> <index column="FooType" type="Domain.Enum.FooType, Domain"/> <element column ="FooStatus" type="Domain.Enum.FooStatus, Domain"/> </map> ``` The class is like this ``` namespace Domain { public class Enum { public enum FooType { Foo1, Foo2, ... Foo50} public enum FooStatus { NotNeeded, NeededFor1, NeededFor2, NeededFor3, NiceToHave} } } ``` Can I do this using Fluent Nhibernate? If not can I map a class mixing Fluent and XML?
ANSWER From Fluent NHibernate Google group were I asked the same question The short answer is no, you cannot do this with the fluent interface at the moment. My initial implementation of AsMap() was rather naive and does not support your scenario. I will raise it as an issue and get back to you once a fix is in place but in the meantime you should be able to work around it by mixing xml with fluent mappings. I know we have several users that are currently doing this. The exact steps would depend on how you have it set up. Paul Batum
243,489
<p>I am doing an Financial Winforms application and am having some trouble with the controls.</p> <p>My customer needs to insert decimal values all over the place (Prices, Discounts etc) and I'd like to avoid some of the repeating validation.</p> <p>So I immediately tried the MaskedTextBox that would fit my needs (with a Mask like "€ 00000.00"), if it weren't for the focus and the length of the mask.</p> <p>I can't predict how big the numbers are my customer is going to enter into the app. </p> <p>I also can't expect him to start everything with 00 to get to the comma. Everything should be keyboard-friendly.</p> <p>Am I missing something or is there simply no way (beyond writing a custom control) to achieve this with the standard Windows Forms controls?</p>
[ { "answer_id": 243502, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 3, "selected": false, "text": "<p>You will need a custom control. Just trap the Validating event on the control and check if the string input can be parsed as a decimal.</p>\n" }, { "answer_id": 243512, "author": "Rockcoder", "author_id": 5290, "author_profile": "https://Stackoverflow.com/users/5290", "pm_score": 1, "selected": false, "text": "<p>MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/ms229603.aspx\" rel=\"nofollow noreferrer\">User Input Validation in Windows Forms</a></p>\n" }, { "answer_id": 243522, "author": "nportelli", "author_id": 7024, "author_profile": "https://Stackoverflow.com/users/7024", "pm_score": 2, "selected": false, "text": "<p>I don't think you need a custom control, just write a decimal validating method for the validating event and use that for all the places you need to validate. Don't forget to include the <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx\" rel=\"nofollow noreferrer\">NumberFormatInfo</a>, it will deal with commas and numebr signs.</p>\n" }, { "answer_id": 243536, "author": "Abel Gaxiola", "author_id": 31191, "author_profile": "https://Stackoverflow.com/users/31191", "pm_score": 4, "selected": true, "text": "<p>This two overriden methods did it for me (disclaimer: this code is not in production yet. You may need to modify)</p>\n\n<pre><code> protected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (!char.IsNumber(e.KeyChar) &amp; (Keys)e.KeyChar != Keys.Back \n &amp; e.KeyChar != '.')\n {\n e.Handled = true;\n }\n\n base.OnKeyPress(e);\n }\n\n private string currentText;\n\n protected override void OnTextChanged(EventArgs e)\n {\n if (this.Text.Length &gt; 0)\n {\n float result;\n bool isNumeric = float.TryParse(this.Text, out result);\n\n if (isNumeric)\n {\n currentText = this.Text;\n }\n else\n {\n this.Text = currentText;\n this.Select(this.Text.Length, 0);\n }\n }\n base.OnTextChanged(e);\n }\n</code></pre>\n" }, { "answer_id": 29064309, "author": "madmaniac", "author_id": 2428976, "author_profile": "https://Stackoverflow.com/users/2428976", "pm_score": 0, "selected": false, "text": "<p>You only need to let numbers and decimal symbols through, and avoid a double decimal symbol. As an extra, this automatically adds a 0 before a starting decimal number.</p>\n\n<pre><code>public class DecimalBox : TextBox\n{\n protected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (e.KeyChar == ',')\n {\n e.KeyChar = '.';\n }\n\n if (!char.IsNumber(e.KeyChar) &amp;&amp; (Keys)e.KeyChar != Keys.Back &amp;&amp; e.KeyChar != '.')\n {\n e.Handled = true;\n }\n\n if(e.KeyChar == '.' )\n {\n if (this.Text.Length == 0)\n {\n this.Text = \"0.\";\n this.SelectionStart = 2;\n e.Handled = true;\n }\n else if (this.Text.Contains(\".\"))\n {\n e.Handled = true;\n }\n }\n\n base.OnKeyPress(e);\n }\n}\n</code></pre>\n" }, { "answer_id": 52339938, "author": "clamchoda", "author_id": 591285, "author_profile": "https://Stackoverflow.com/users/591285", "pm_score": 0, "selected": false, "text": "<p>Another approach is to block what you don't want, and format when your done with it. </p>\n\n<pre><code>class DecimalTextBox : TextBox\n{\n // Handle multiple decimals\n protected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (e.KeyChar == '.')\n if (this.Text.Contains('.'))\n e.Handled = true;\n\n base.OnKeyPress(e);\n }\n\n // Block non digits\n // I scrub characters here instead of handling in OnKeyPress so I can support keyboard events (ctrl + c/v/a)\n protected override void OnTextChanged(EventArgs e)\n {\n this.Text = System.Text.RegularExpressions.Regex.Replace(this.Text, \"[^.0-9]\", \"\");\n base.OnTextChanged(e);\n }\n\n // Apply our format when we're done\n protected override void OnLostFocus(EventArgs e)\n {\n if (!String.IsNullOrEmpty(this.Text))\n this.Text = string.Format(\"{0:N}\", Convert.ToDouble(this.Text));\n\n base.OnLostFocus(e);\n }\n\n\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
I am doing an Financial Winforms application and am having some trouble with the controls. My customer needs to insert decimal values all over the place (Prices, Discounts etc) and I'd like to avoid some of the repeating validation. So I immediately tried the MaskedTextBox that would fit my needs (with a Mask like "€ 00000.00"), if it weren't for the focus and the length of the mask. I can't predict how big the numbers are my customer is going to enter into the app. I also can't expect him to start everything with 00 to get to the comma. Everything should be keyboard-friendly. Am I missing something or is there simply no way (beyond writing a custom control) to achieve this with the standard Windows Forms controls?
This two overriden methods did it for me (disclaimer: this code is not in production yet. You may need to modify) ``` protected override void OnKeyPress(KeyPressEventArgs e) { if (!char.IsNumber(e.KeyChar) & (Keys)e.KeyChar != Keys.Back & e.KeyChar != '.') { e.Handled = true; } base.OnKeyPress(e); } private string currentText; protected override void OnTextChanged(EventArgs e) { if (this.Text.Length > 0) { float result; bool isNumeric = float.TryParse(this.Text, out result); if (isNumeric) { currentText = this.Text; } else { this.Text = currentText; this.Select(this.Text.Length, 0); } } base.OnTextChanged(e); } ```
243,494
<p>I have some legacy code that uses VBA to parse a word document and build some XML output; </p> <p>Needless to say it runs like a dog but I was interested in profiling it to see where it's breaking down and maybe if there are some options to make it faster.</p> <p>I don't want to try anything until I can start measuring my results so profiling is a must - I've done a little searching around but can't find anything that would do this job easily. There was one tool by brentwood? that requires modifying your code but it didn't work and I ran outa time.</p> <p>Anyone know anything simple that works?</p> <p>Update: The code base is about 20 or so files, each with at least 100 methods - manually adding in start/end calls for each method just isn't appropriate - especially removing them all afterwards - I was actually thinking about doing some form of REGEX to solve this issue and another to remove them all after but its just a little too intrusive but may be the only solution. I've found some nice timing code on here earlier so the timing part of it isn't an issue.</p>
[ { "answer_id": 243545, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 0, "selected": false, "text": "<p>Insert a bunch of</p>\n\n<pre><code>Debug.Print \"before/after foo\", Now\n</code></pre>\n\n<p>before and after snippets that you think might run for long terms, then just compare them and voila there you are.</p>\n" }, { "answer_id": 243936, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>It may be possible to use a template to add a line to each procedure:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa191135(office.10).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa191135(office.10).aspx</a></p>\n\n<p>Error handler templates usually include an ExitHere label of some description.. The first line after the label could be the timer print. </p>\n\n<p>It is also possible to modify code through code: <a href=\"http://wiki.lessthandot.com/index.php/Code_and_Code_Windows\" rel=\"nofollow noreferrer\">\"Example: Add some lines required for DAO\"</a> is an Access example, but something similar could be done with Word.</p>\n\n<p>This would, hopefully, narrow down the area to search for problems. The line could then be commented out, or you could revert to back-ups.</p>\n" }, { "answer_id": 244103, "author": "Aardvark", "author_id": 3655, "author_profile": "https://Stackoverflow.com/users/3655", "pm_score": 2, "selected": true, "text": "<p>Using a class and #if would make that \"adding code to each method\" a little easier...</p>\n\n<p><strong><em>Profiler</em> Class Module:</strong>:</p>\n\n<pre><code>#If PROFILE = 1 Then\n\nPrivate m_locationName As String\nPrivate Sub Class_Initialize()\n m_locationName = \"unknown\"\nEnd Sub\n\nPublic Sub Start(locationName As String)\n m_locationName = locationName\n MsgBox m_locationName\nEnd Sub\n\nPrivate Sub Class_Terminate()\n MsgBox m_locationName &amp; \" end\"\nEnd Sub\n\n#Else\n\nPublic Sub Start(locationName As String)\n 'no op\nEnd Sub\n\n#End If\n</code></pre>\n\n<p><strong>some other code module:</strong></p>\n\n<pre><code>' helper \"factory\" since VBA classes don't have ctor params (or do they?)\nPrivate Function start_profile(location As String) As Profiler\n Set start_profile = New Profiler\n start_profile.Start location\nEnd Function\n\nPrivate Sub test()\n Set p = start_profile(\"test\")\n MsgBox \"do work\"\n subroutine\nEnd Sub\n\nPrivate Sub subroutine()\n Set p = start_profile(\"subroutine\")\nEnd Sub\n</code></pre>\n\n<p>In Project Properties set <em>Conditional Compilation Arguments</em> to:</p>\n\n<pre><code>PROFILE = 1\n</code></pre>\n\n<p>Remove the line for normal, non-profiled versions.</p>\n\n<p>Adding the lines is a pain, I don't know of any way to automatically get the current method name which would make adding the profiling line to each function easy. You could use the VBE object model to inject the code for you - but I wonder is doing this manually would be ultimately faster.</p>\n" }, { "answer_id": 246078, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "<p>My suggestion would be to divide and conquer, by inserting some timing lines in a few key places to try to isolate the problem, and then drill down on that area.</p>\n\n<p>If the problem is more diffused and not obvious, I'd suggest simplifying by progressively disabling whole chunks of code one at a time, as far as is possible without breaking the process. This is the analogy of finding speed bumps in an Excel workbook by progressively hard coding sheets or parts of sheets until the speed problem disappears.</p>\n" }, { "answer_id": 444097, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>About that \"<strong>Now</strong>\" function (above, svinto) ...</p>\n\n<p>I've used the \"<strong>Timer</strong>\" function (in Excel VBA), which returns a Single.\nIt seems to work just fine. Larry</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24525/" ]
I have some legacy code that uses VBA to parse a word document and build some XML output; Needless to say it runs like a dog but I was interested in profiling it to see where it's breaking down and maybe if there are some options to make it faster. I don't want to try anything until I can start measuring my results so profiling is a must - I've done a little searching around but can't find anything that would do this job easily. There was one tool by brentwood? that requires modifying your code but it didn't work and I ran outa time. Anyone know anything simple that works? Update: The code base is about 20 or so files, each with at least 100 methods - manually adding in start/end calls for each method just isn't appropriate - especially removing them all afterwards - I was actually thinking about doing some form of REGEX to solve this issue and another to remove them all after but its just a little too intrusive but may be the only solution. I've found some nice timing code on here earlier so the timing part of it isn't an issue.
Using a class and #if would make that "adding code to each method" a little easier... ***Profiler* Class Module:**: ``` #If PROFILE = 1 Then Private m_locationName As String Private Sub Class_Initialize() m_locationName = "unknown" End Sub Public Sub Start(locationName As String) m_locationName = locationName MsgBox m_locationName End Sub Private Sub Class_Terminate() MsgBox m_locationName & " end" End Sub #Else Public Sub Start(locationName As String) 'no op End Sub #End If ``` **some other code module:** ``` ' helper "factory" since VBA classes don't have ctor params (or do they?) Private Function start_profile(location As String) As Profiler Set start_profile = New Profiler start_profile.Start location End Function Private Sub test() Set p = start_profile("test") MsgBox "do work" subroutine End Sub Private Sub subroutine() Set p = start_profile("subroutine") End Sub ``` In Project Properties set *Conditional Compilation Arguments* to: ``` PROFILE = 1 ``` Remove the line for normal, non-profiled versions. Adding the lines is a pain, I don't know of any way to automatically get the current method name which would make adding the profiling line to each function easy. You could use the VBE object model to inject the code for you - but I wonder is doing this manually would be ultimately faster.
243,510
<p>Does anyone know what is wrong with this query?</p> <pre><code> SELECT DISTINCT c.CN as ClaimNumber, a.ItemDate as BillReceivedDate, c.DTN as DocTrackNumber FROM ItemData a, ItemDataPage b, KeyGroupData c WHERE a.ItemTypeNum in (112, 113, 116, 172, 189) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC; </code></pre> <p>I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL.</p> <p>Thanks!</p> <p>[EDIT] For future reference, the error given by SQL*Plus was: "ORA-01791: not a SELECTed expression" </p>
[ { "answer_id": 243520, "author": "Chris Conway", "author_id": 2849, "author_profile": "https://Stackoverflow.com/users/2849", "pm_score": 2, "selected": false, "text": "<p>Nevermind, executing in SQL Plus gave me a more informative answer. The DateStored needs to be in the select statement so this works:</p>\n\n<pre><code> SELECT DISTINCT c.CN as ClaimNumber, \na.ItemDate as BillReceivedDate, \nc.DTN as DocTrackNumber, \na.DateStored \nFROM ItemData a, \nItemDataPage b, \nKeyGroupData c \nWHERE a.ItemTypeNum in (112, 113, 116, 172, 189) \nAND a.ItemNum = b.ItemNum \nAND b.ItemNum = c.ItemNum \nORDER BY a.DateStored DESC;\n</code></pre>\n" }, { "answer_id": 243523, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 5, "selected": true, "text": "<p>You will need to modify the query as such:</p>\n\n<pre><code>SELECT DISTINCT c.CN as ClaimNumber, \n a.ItemDate as BillReceivedDate, c.DTN as\n DocTrackNumber, a.DateStored\n FROM ItemData a,\n ItemDataPage b,\n KeyGroupData c\n WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)\n AND a.ItemNum = b.ItemNum\n AND b.ItemNum = c.ItemNum\n ORDER BY a.DateStored DESC;\n</code></pre>\n\n<p>When doing a DISTINCT your order by needs to be one of the selected columns.</p>\n" }, { "answer_id": 243527, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I believe that the elements of the order by clause must also be in the select clause.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
Does anyone know what is wrong with this query? ``` SELECT DISTINCT c.CN as ClaimNumber, a.ItemDate as BillReceivedDate, c.DTN as DocTrackNumber FROM ItemData a, ItemDataPage b, KeyGroupData c WHERE a.ItemTypeNum in (112, 113, 116, 172, 189) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC; ``` I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL. Thanks! [EDIT] For future reference, the error given by SQL\*Plus was: "ORA-01791: not a SELECTed expression"
You will need to modify the query as such: ``` SELECT DISTINCT c.CN as ClaimNumber, a.ItemDate as BillReceivedDate, c.DTN as DocTrackNumber, a.DateStored FROM ItemData a, ItemDataPage b, KeyGroupData c WHERE a.ItemTypeNum in (112, 113, 116, 172, 189) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC; ``` When doing a DISTINCT your order by needs to be one of the selected columns.
243,567
<p>The database type is PostGres 8.3.</p> <p>If I wrote: </p> <pre><code>SELECT field1, field2, field3, count(*) FROM table1 GROUP BY field1, field2, field3 having count(*) &gt; 1; </code></pre> <p>I have some rows that have a count over 1. How can I take out the duplicate (I do still want 1 row for each of them instead of +1 row... I do not want to delete them all.)</p> <p>Example:</p> <pre><code>1-2-3 1-2-3 1-2-3 2-3-4 4-5-6 </code></pre> <p>Should become :</p> <pre><code>1-2-3 2-3-4 4-5-6 </code></pre> <p><em>The only answer I found is <a href="http://www.siafoo.net/article/64" rel="noreferrer">there</a> but I am wondering if I could do it without hash column.</em></p> <p><strong>Warning</strong> I do not have a PK with an unique number so I can't use the technique of min(...). The PK is the 3 fields.</p>
[ { "answer_id": 243627, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>One possible answer is:</p>\n\n<pre><code>CREATE &lt;temporary table&gt; (&lt;correct structure for table being cleaned&gt;);\nBEGIN WORK; -- if needed\nINSERT INTO &lt;temporary table&gt; SELECT DISTINCT * FROM &lt;source table&gt;;\nDELETE FROM &lt;source table&gt;\nINSERT INTO &lt;source table&gt; SELECT * FROM &lt;temporary table&gt;;\nCOMMIT WORK; -- needed\nDROP &lt;temporary table&gt;;\n</code></pre>\n\n<p>I'm not sure whether the 'work' is needed on transaction statements, nor whether the explicit BEGIN is necessary in PostgreSQL. But the concept applies to any DBMS.</p>\n\n<p>The only thing to beware of is referential constraints and in particular triggered delete operations. If those exist, this may prove less satisfactory.</p>\n" }, { "answer_id": 243629, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 4, "selected": true, "text": "<p>This is one of many reasons that all tables should have a primary key (not necessarily an ID number or IDENTITY, but a combination of one or more columns that uniquely identifies a row and which has its uniqueness enforced in the database).</p>\n\n<p>Your best bet is something like this:</p>\n\n<pre><code>SELECT field1, field2, field3, count(*) \nINTO temp_table1\nFROM table1\nGROUP BY field1, field2, field3 having count(*) &gt; 1\n\nDELETE T1\nFROM table1 T1\nINNER JOIN (SELECT field1, field2, field3\n FROM table1\n GROUP BY field1, field2, field3 having count(*) &gt; 1) SQ ON\n SQ.field1 = T1.field1 AND\n SQ.field2 = T1.field2 AND\n SQ.field3 = T1.field3\n\nINSERT INTO table1 (field1, field2, field3)\nSELECT field1, field2, field3\nFROM temp_table1\n\nDROP TABLE temp_table1\n</code></pre>\n" }, { "answer_id": 243638, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 0, "selected": false, "text": "<p>This will use the <a href=\"http://www.postgresql.org/docs/8.1/static/datatype-oid.html\" rel=\"nofollow noreferrer\">OID</a> Object ID (if the table was created with it):</p>\n\n<pre><code>DELETE FROM table1\nWHERE OID NOT IN (SELECT MIN (OID)\n FROM table1\n GROUP BY field1, field2, field3)\n</code></pre>\n" }, { "answer_id": 243648, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Well I should misunderstand something but I'll say :</p>\n\n<p>SELECT <strong>DISTINCT</strong> field1, field2, field3 FROM table1</p>\n\n<p>Too easy to be good? ^^</p>\n" }, { "answer_id": 243652, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "<p>Using TSQL, no idea if Postgres supports temp tables but you could select into a temp table, and then loop through and delete and insert your results back into the original</p>\n\n<pre><code>-- **Disclaimer** using TSQL\n-- You could select your records into a temp table with a pk\nCreate Table #dupes\n([id] int not null identity(1,1), f1 int, f2 int, f3 int)\n\nInsert Into #dupes (f1,f2,f3) values (1,2,3)\nInsert Into #dupes (f1,f2,f3) values (1,2,3)\nInsert Into #dupes (f1,f2,f3) values (1,2,3)\nInsert Into #dupes (f1,f2,f3) values (2,3,4)\nInsert Into #dupes (f1,f2,f3) values (4,5,6)\nInsert Into #dupes (f1,f2,f3) values (4,5,6)\nInsert Into #dupes (f1,f2,f3) values (4,5,6)\nInsert Into #dupes (f1,f2,f3) values (7,8,9)\n\nSelect f1,f2,f3 From #dupes\n\nDeclare @rowCount int\nDeclare @counter int\nSet @counter = 1\nSet @rowCount = (Select Count([id]) from #dupes)\n\nwhile (@counter &lt; @rowCount + 1)\n Begin\n Delete From #dupes\n Where [Id] &lt;&gt; \n (Select [id] From #dupes where [id]=@counter)\n and\n (\n [f1] = (Select [f1] from #dupes where [id]=@counter)\n and\n [f2] = (Select [f2] from #dupes where [id]=@counter)\n and\n [f3] = (Select [f3] from #dupes where [id]=@counter)\n )\n Set @counter = @counter + 1\n End\n\nSelect f1,f2,f3 From #dupes -- You could take these results and pump them back into --your original table\n\nDrop Table #dupes\n</code></pre>\n\n<p>Tested this on MS SQL Server 2000. Not familiar with Postgres' options but maybe this will lead you in a right direction. </p>\n" }, { "answer_id": 243666, "author": "Aaron Palmer", "author_id": 24908, "author_profile": "https://Stackoverflow.com/users/24908", "pm_score": 0, "selected": false, "text": "<p>This is the simplest method I've found:</p>\n\n<p>Postgre SQL syntax:</p>\n\n<pre><code>CREATE TABLE tmp AS SELECT distinct * FROM table1\ntruncate table table1\ninsert into table1 select * from tmp\ndrop table tmp\n</code></pre>\n\n<p>T-SQL syntax:</p>\n\n<pre><code>select distinct * into #tmp from table1\ntruncate table table1\ninsert into table1 select * from #tmp\ndrop table #tmp\n</code></pre>\n" }, { "answer_id": 243718, "author": "Vijay Dev", "author_id": 27474, "author_profile": "https://Stackoverflow.com/users/27474", "pm_score": 0, "selected": false, "text": "<p>A good <a href=\"http://www.mssqltips.com/tip.asp?tip=1103\" rel=\"nofollow noreferrer\">Answer</a> for this problem, but for SQL Server. It uses the ROWCOUNT that SQL Server offers, to good effect. I have never used PostgreSQL and hence don't know the equivalent of ROWCOUNT in PostgreSQL. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
The database type is PostGres 8.3. If I wrote: ``` SELECT field1, field2, field3, count(*) FROM table1 GROUP BY field1, field2, field3 having count(*) > 1; ``` I have some rows that have a count over 1. How can I take out the duplicate (I do still want 1 row for each of them instead of +1 row... I do not want to delete them all.) Example: ``` 1-2-3 1-2-3 1-2-3 2-3-4 4-5-6 ``` Should become : ``` 1-2-3 2-3-4 4-5-6 ``` *The only answer I found is [there](http://www.siafoo.net/article/64) but I am wondering if I could do it without hash column.* **Warning** I do not have a PK with an unique number so I can't use the technique of min(...). The PK is the 3 fields.
This is one of many reasons that all tables should have a primary key (not necessarily an ID number or IDENTITY, but a combination of one or more columns that uniquely identifies a row and which has its uniqueness enforced in the database). Your best bet is something like this: ``` SELECT field1, field2, field3, count(*) INTO temp_table1 FROM table1 GROUP BY field1, field2, field3 having count(*) > 1 DELETE T1 FROM table1 T1 INNER JOIN (SELECT field1, field2, field3 FROM table1 GROUP BY field1, field2, field3 having count(*) > 1) SQ ON SQ.field1 = T1.field1 AND SQ.field2 = T1.field2 AND SQ.field3 = T1.field3 INSERT INTO table1 (field1, field2, field3) SELECT field1, field2, field3 FROM temp_table1 DROP TABLE temp_table1 ```