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
109,464
<p>I have a report that I built for a client where I need to plot x 0-100, y 0-100. Let's imagine I have these points:</p> <pre><code> 0, 0 2, 24 50, 70 100, 100 </code></pre> <p>I need to represent these as a smoothed line chart, as the application of it is a dot gain graph for printing presses.</p> <p>Here's the problem. The line draws fine from 100,100 (top right) down to 2,24. But then what happens is from 2,24 to 0,0 the line curves out off the left of the graph and then to down to 0,0. Imagine it putting a point at -10,10.</p> <p>I understand this is because of the generic <a href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="nofollow noreferrer">Bézier curve</a> algorithm it is using and the large separation of control points, thus heavily weighting it.</p> <p>I was wondering however if anyone knows a way I can control it. I have tried adding in averaged points between the existing control points, but it still curves off the graph as if it's still heavily weighted.</p> <p>The only other answer I can think of is custom drawing a graph or looking into <a href="https://en.wikipedia.org/wiki/Dundas_Data_Visualization#History" rel="nofollow noreferrer">Dundas Charts</a> and using its <a href="https://en.wikipedia.org/wiki/Graphics_Device_Interface#Windows_XP" rel="nofollow noreferrer">GDI+</a> drawing support.</p> <p>But before I go that route, anyone have any thoughts?</p> <hr> <p>Here's the thing. I know how to draw the curve manually. The problem lies in the fact that there is such a high weighting between 2 and 50. I tried to add points in at the lows and the mids, but it was still bowing off the edge. I will have to go check out the source and modify the graph back and see if I can get a screenshot up.</p> <p>Right now I just have the graph stop at 2 until I can get this solved.</p>
[ { "answer_id": 109537, "author": "bkane", "author_id": 17097, "author_profile": "https://Stackoverflow.com/users/17097", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://img140.imageshack.us/img140/1279/smoothlinebezierxl0.jpg\" rel=\"nofollow noreferrer\">alt text http://img140.imageshack.us/img140/1279/smoothlinebezierxl0.jpg</a></p>\n\n<p>(Providing a picture of the behaviour to help you get a better answer).</p>\n\n<p>For those with a theory, you can try this out in Excel as well (not just Reporting Services). </p>\n\n<p>You mentioned adding points in your question, but it seems like adding in interpolated points near the problem area has the desired effect (e.g. { (1,12), (1.5, 18) }). This is a clumsy \"solution\" at best though.</p>\n" }, { "answer_id": 109646, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<p>You could try using a cosine interpolation for the points in-between.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14642/" ]
I have a report that I built for a client where I need to plot x 0-100, y 0-100. Let's imagine I have these points: ``` 0, 0 2, 24 50, 70 100, 100 ``` I need to represent these as a smoothed line chart, as the application of it is a dot gain graph for printing presses. Here's the problem. The line draws fine from 100,100 (top right) down to 2,24. But then what happens is from 2,24 to 0,0 the line curves out off the left of the graph and then to down to 0,0. Imagine it putting a point at -10,10. I understand this is because of the generic [Bézier curve](http://en.wikipedia.org/wiki/B%C3%A9zier_curve) algorithm it is using and the large separation of control points, thus heavily weighting it. I was wondering however if anyone knows a way I can control it. I have tried adding in averaged points between the existing control points, but it still curves off the graph as if it's still heavily weighted. The only other answer I can think of is custom drawing a graph or looking into [Dundas Charts](https://en.wikipedia.org/wiki/Dundas_Data_Visualization#History) and using its [GDI+](https://en.wikipedia.org/wiki/Graphics_Device_Interface#Windows_XP) drawing support. But before I go that route, anyone have any thoughts? --- Here's the thing. I know how to draw the curve manually. The problem lies in the fact that there is such a high weighting between 2 and 50. I tried to add points in at the lows and the mids, but it was still bowing off the edge. I will have to go check out the source and modify the graph back and see if I can get a screenshot up. Right now I just have the graph stop at 2 until I can get this solved.
[alt text http://img140.imageshack.us/img140/1279/smoothlinebezierxl0.jpg](http://img140.imageshack.us/img140/1279/smoothlinebezierxl0.jpg) (Providing a picture of the behaviour to help you get a better answer). For those with a theory, you can try this out in Excel as well (not just Reporting Services). You mentioned adding points in your question, but it seems like adding in interpolated points near the problem area has the desired effect (e.g. { (1,12), (1.5, 18) }). This is a clumsy "solution" at best though.
109,480
<p>I've created a forum, and we're implementing an apc and memcache caching solution to save the database some work.</p> <p>I started implementing the cache layer with keys like "Categories::getAll", and if I had user-specific data, I'd append the keys with stuff like the user ID, so you'd get <code>"User::getFavoriteThreads|1471"</code>. When a user added a new favorite thread, I'd delete the cache key, and it would recreate the entry.</p> <p><strong>However, and here comes the problem:</strong></p> <p>I wanted to cache the threads in a forum. Simple enough, "Forum::getThreads|$iForumId". But... With pagination, I'd have to split this into several cache entries, for example</p> <pre><code>"Forum::getThreads|$iForumId|$iLimit|$iOffset". </code></pre> <p>Which is alright, until someone posts a new thread in the forum. I will now have to delete all the keys under <code>"Forum::getThreads|$iForumId"</code>, no matter what the limit and offset is.</p> <p>What would be a good way of solving this problem? I'd really rather not loop through every possible limit and offset until I find something that doesn't match anymore.</p> <p>Thanks.</p>
[ { "answer_id": 109532, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 2, "selected": false, "text": "<p>You're essentially trying to cache a view, which is always going to get tricky. You should instead try to cache data only, because data rarely changes. Don't cache a forum, cache the thread rows. Then your db call should just return a list of ids, which you already have in your cache. The db call will be lightening fast on any MyISAM table, and then you don't have to do a big join, which eats db memory.</p>\n" }, { "answer_id": 109533, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 1, "selected": false, "text": "<p>One possible solution is not to paginate the cache of threads in a forum, but rather put the thread information in to <code>Forum::getThreads|$iForumId</code>. Then in your PHP code only pull out the ones you want for that given page, e.g.</p>\n\n<pre><code>$page = 2;\n$threads_per_page = 25;\n$start_thread = $page * $threads_per_page;\n\n// Pull threads from cache (assuming $cache class for memcache interface..)\n$threads = $cache-&gt;get(\"Forum::getThreads|$iForumId\");\n\n// Only take the ones we need\nfor($i=$start_thread; $i&lt;=$start_thread+$threads_per_page; $i++)\n{\n // Thread display logic here...\n showThread($threads[$i]);\n}\n</code></pre>\n\n<p>This means that you do have a bit more work to do pulling them out on each page, but now only have to worry about invalidating the cache in one place on update / addition of new thread.</p>\n" }, { "answer_id": 109742, "author": "flungabunga", "author_id": 11000, "author_profile": "https://Stackoverflow.com/users/11000", "pm_score": 3, "selected": false, "text": "<p>I've managed to solve this by extending the <code>memcache</code> class with a custom class (say ExtendedMemcache) which has a protected property which will contain a hash table of group to key values.</p>\n\n<p>The <code>ExtendedMemcache-&gt;set</code> method accepts 3 args (<code>$strGroup</code>,<code>$strKey</code>, <code>$strValue</code>)\nWhen you call set, it will store the relationship between <code>$strGroup</code>, and <code>$strKey</code>, in the protected property and then go on to store the <code>$strKey</code> to <code>$strValue</code> relationship in <code>memcache</code>.</p>\n\n<p>You can then add a new method to the <code>ExtendedMemcache</code> class called \"deleteGroup\", which will, when passed a string, find that keys associated to that group, and purge each key in turn.</p>\n\n<p>It would be something like this:\n<a href=\"http://pastebin.com/f566e913b\" rel=\"nofollow noreferrer\">http://pastebin.com/f566e913b</a>\nI hope all that makes sense and works out for you.</p>\n\n<p>PS. I suppose if you wanted to use static calls the protected property could be saved in <code>memcache</code> itself under it's own key. Just a thought.</p>\n" }, { "answer_id": 109800, "author": "Rexxars", "author_id": 11167, "author_profile": "https://Stackoverflow.com/users/11167", "pm_score": 1, "selected": false, "text": "<p>flungabunga:\nYour solution is very close to what I'm looking for. The only thing keeping me from doing this is having to store the relationships in memcache after each request and loading them back. </p>\n\n<p>I'm not sure how much of a performance hit this would mean, but it seems a little inefficient. I will do some tests and see how it pans out. Thank you for a structured suggestion (and some code to show for it, thanks!).</p>\n" }, { "answer_id": 110167, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 4, "selected": true, "text": "<p>You might also want to have a look at the cost of storing the cache data, in terms of your effort and CPU cost, against how what the cache will buy you. </p>\n\n<p>If you find that 80% of your forum views are looking at the first page of threads, then you could decide to cache that page only. That would mean both cache reads and writes are much simpler to implment.</p>\n\n<p>Likewise with the list of a user's favourite threads. If this is something that each person visits rarely then cache might not improve performance too much.</p>\n" }, { "answer_id": 110778, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 1, "selected": false, "text": "<p>Be very careful about doing this kind of optimisation without having hard facts to measure against.</p>\n\n<p>Most databases have several levels of caches. If these are tuned correctly, the database will probably do a much better job at caching, than you can do your self.</p>\n" }, { "answer_id": 113679, "author": "Rexxars", "author_id": 11167, "author_profile": "https://Stackoverflow.com/users/11167", "pm_score": 3, "selected": false, "text": "<p>Just an update:\nI decided that Josh's point on data usage was a very good one.\nPeople are unlikely to keep viewing page 50 of a forum.</p>\n\n<p>Based on this model, I decided to cache the 90 latest threads in each forum. In the fetching function I check the limit and offset to see if the specified slice of threads is within cache or not. If it is within the cache limit, I use array_slice() to retrieve the right part and return it.</p>\n\n<p>This way, I can use a single cache key per forum, and it takes very little effort to clear/update the cache :-)</p>\n\n<p>I'd also like to point out that in other more resource heavy queries, I went with flungabunga's model, storing the relations between keys. Unfortunately Stack Overflow won't let me accept two answers. </p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 438064, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In response to flungabunga:</p>\n\n<p>Another way to implement grouping is to put the group name plus a sequence number into the keys themselves and increment the sequence number to \"clear\" the group. You store the current valid sequence number for each group in its own key.</p>\n\n<p>e.g.</p>\n\n<pre><code>get seqno_mygroup\n23\n\nget mygroup23_mykey\n&lt;mykeydata...&gt;\nget mygroup23_mykey2\n&lt;mykey2data...&gt;\n</code></pre>\n\n<p>Then to \"delete\" the group simply:</p>\n\n<pre><code>incr seqno_mygroup\n</code></pre>\n\n<p>Voila:</p>\n\n<pre><code>get seqno_mygroup\n24\n\nget mygroup24_mykey\n...empty\n</code></pre>\n\n<p>etc..</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11167/" ]
I've created a forum, and we're implementing an apc and memcache caching solution to save the database some work. I started implementing the cache layer with keys like "Categories::getAll", and if I had user-specific data, I'd append the keys with stuff like the user ID, so you'd get `"User::getFavoriteThreads|1471"`. When a user added a new favorite thread, I'd delete the cache key, and it would recreate the entry. **However, and here comes the problem:** I wanted to cache the threads in a forum. Simple enough, "Forum::getThreads|$iForumId". But... With pagination, I'd have to split this into several cache entries, for example ``` "Forum::getThreads|$iForumId|$iLimit|$iOffset". ``` Which is alright, until someone posts a new thread in the forum. I will now have to delete all the keys under `"Forum::getThreads|$iForumId"`, no matter what the limit and offset is. What would be a good way of solving this problem? I'd really rather not loop through every possible limit and offset until I find something that doesn't match anymore. Thanks.
You might also want to have a look at the cost of storing the cache data, in terms of your effort and CPU cost, against how what the cache will buy you. If you find that 80% of your forum views are looking at the first page of threads, then you could decide to cache that page only. That would mean both cache reads and writes are much simpler to implment. Likewise with the list of a user's favourite threads. If this is something that each person visits rarely then cache might not improve performance too much.
109,488
<p>I keep hearing that <code>div</code> tags should be used for layout purposes and not <code>table</code> tags. So does that also apply to form layout? I know a form layout is still a layout, but it seems like creating form layouts with <code>div</code>s requires more <code>html</code> and <code>css</code>. So with that in mind, should forms layouts use <code>div</code> tags instead?</p>
[ { "answer_id": 109493, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 2, "selected": false, "text": "<p>It's certainly easier to use table than div to layout a table, but keep in mind that a table is supposed to mean something - it's presenting data in a regular way for the user to see, more than putting boxes on the screen in a given order. Generally, I think forms layouts should use divs to decide how the form elements are displayed.</p>\n" }, { "answer_id": 109510, "author": "mbrevoort", "author_id": 18228, "author_profile": "https://Stackoverflow.com/users/18228", "pm_score": 3, "selected": false, "text": "<p>If you just need a simply row column grip type layout you shouldn't feel guilty using tables. I don't know how anyone can call that 'bad design' just because it's not CSS. I've seen <strong>many</strong> bad CSS based designs. I love CSS and think it far superior in many ways to traditional nested table layouts, but do what works bests and what is easiest to maintain and move onto more important, more impactful decisions.</p>\n" }, { "answer_id": 109511, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<p>It's a grey area. Not everything in markup has clearly defined boundaries, and this is one case where you get to use your personal preference and make a judgement call. It doesn't quite fit the idea of data being organised, but the cells are related across multiple axes, and that's the rule of thumb I use to decide whether something fits in a table or not.</p>\n" }, { "answer_id": 109516, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 6, "selected": true, "text": "<p>Yes, it does apply for form layouts. Keep in mind that there are also tags like FIELDSET and LABEL which exist specifically for adding structure to a form, so it's not really a question of just using DIV. You should be able to markup a form with pretty minimal HTML, and let CSS do the rest of the work. E.g.:</p>\n\n<pre><code>&lt;fieldset&gt;\n &lt;div&gt;\n &lt;label for=\"nameTextBox\"&gt;Name:&lt;/label&gt;\n &lt;input id=\"nameTextBox\" type=\"text\" /&gt;\n &lt;/div&gt;\n ...\n&lt;/fieldset&gt;\n</code></pre>\n" }, { "answer_id": 109517, "author": "Jason Francis", "author_id": 5338, "author_profile": "https://Stackoverflow.com/users/5338", "pm_score": 2, "selected": false, "text": "<p>The general principle is that you want to use whatever HTML elements best convey the semantic content that you are intending and then rely on css to visually represent that semantic content. Following that principle buys a lot of intrinsic benefits including easier site-general visual changes, search engine optimization, multi-device layouts, and accessibility.</p>\n\n<p>So, the short answer is: you can do whatever you want, but best practices suggest that you only use table tags to represent tabular data and instead use whatever html tags best convey what it is that you are trying to represent. It might be a little harder initially, but once you get used to the idea, you'll wonder why you ever did it any other way.</p>\n\n<p>Depending on what you are trying to do with your form, it shouldn't take that much more markup to use semantic markup and css, especially if you rely on the cascading properties of css. Also, if you have several of the same form across many pages in your site, the semantic approach is much more efficient, both to code and to maintain.</p>\n" }, { "answer_id": 109525, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "<p>If your forms are laid out in a tabular format (for example, labels on the left and fields on the right), then yes, use table tags.</p>\n" }, { "answer_id": 109538, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 4, "selected": false, "text": "<p>I think it's a myth that forms are \"difficult\" to layout nicely with good HTML and CSS. The level of control that CSS gives you over your layout goes way beyond what any clunky table-based layout ever would. This isn't a new idea, as <a href=\"http://www.smashingmagazine.com/2006/11/11/css-based-forms-modern-solutions/\" rel=\"nofollow noreferrer\">this Smashing Magazine article</a> from way back in 2006 shows.</p>\n\n<p>I tend to use variants of the following markup in my forms. I have a generic .form style in my CSS and then variants for text inputs, checkboxes, selects, textareas etc etc.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.field label {\r\n float: left;\r\n width: 20%;\r\n}\r\n\r\n.field.text input {\r\n width: 75%;\r\n margin-left: 2%;\r\n padding: 3px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"field text\"&gt;\r\n &lt;label for=\"fieldName\"&gt;Field Title&lt;/label&gt;\r\n &lt;input value=\"input value\" type=\"text\" name=\"fieldName\" id=\"fieldName\" /&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Tables aren't evil. They are by far the best option when tabular data needs to be displayed. Forms IMHO aren't tabular data - they're forms, and CSS provides more than enough tools to layout forms however you like.</p>\n" }, { "answer_id": 109548, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 0, "selected": false, "text": "<p>A form is not \"presentation\", you ask for data, you do not usually present data. I use a lot of inline editing in tabular data. Obviousely i use the datacells - td as holders for the input elements when switching from presentation to input.</p>\n" }, { "answer_id": 109573, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 2, "selected": false, "text": "<p>To make forms as accessible as possible and semantically correct, I use the following format:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;fieldset&gt;\n &lt;ol&gt;\n &lt;li&gt;\n &lt;label for='text_field'&gt;Text Field&lt;/label&gt;\n &lt;input type='text' name='text_field' id='text_field' /&gt;\n &lt;/li&gt;\n &lt;/ol&gt;\n&lt;/fieldset&gt;\n</code></pre>\n" }, { "answer_id": 109739, "author": "robertc", "author_id": 8655, "author_profile": "https://Stackoverflow.com/users/8655", "pm_score": 1, "selected": false, "text": "<p>One thing that I don't often see discussed in these form layout questions, if you've chosen a table to layout your form (with labels on the left and fields on the right as mentioned in one of the answers) then that layout is fixed. At work we recently had to do a quick 'proof of concept' of our web apps in Arabic. The apps which had used tables for form layout were basically stuck, whereas I was able to reverse the order of all the form fields and labels on all my pages by changing about ten lines in my CSS file.</p>\n" }, { "answer_id": 110200, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 0, "selected": false, "text": "<p>Most of the answers I've seen here seem appropriate. The only thing I'd add, specifically to apathetic's or Mr. Matt's is to use <code>&lt;dl&gt;/&lt;dt&gt;/&lt;dd&gt;</code>. I believe these represent the list semantically.</p>\n\n<pre><code>&lt;dl&gt;\n &lt;dt&gt;&lt;label for=\"nameTextBox\"&gt;Name:&lt;/label&gt;&lt;/dt&gt;\n &lt;dd&gt;&lt;input value=\"input value\" type=\"text\" name=\"fieldName\" id=\"fieldName\" /&gt;&lt;/dd&gt;\n&lt;/dl&gt;\n</code></pre>\n\n<p>You might want to restyle these, but this says semantically what's going on, that is you've got a list of \"terms\" (<code>&lt;dt&gt;</code>) and \"definitions\" (<code>&lt;dd&gt;</code>), with the term being the label and the definition being the user entered values.</p>\n" }, { "answer_id": 554448, "author": "Abdu", "author_id": 5232, "author_profile": "https://Stackoverflow.com/users/5232", "pm_score": 2, "selected": false, "text": "<p>I use CSS mostly until CSS becomes a drag. For example it's a lot easier to create a 3+ column (3 sets of label + form field) form using a table than in css. I couldn't get the layout to look properly in all major browsers using pure css and I was spending too much time getting it to work. So I said screw it and I did it easily using a table. Table are not bad.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
I keep hearing that `div` tags should be used for layout purposes and not `table` tags. So does that also apply to form layout? I know a form layout is still a layout, but it seems like creating form layouts with `div`s requires more `html` and `css`. So with that in mind, should forms layouts use `div` tags instead?
Yes, it does apply for form layouts. Keep in mind that there are also tags like FIELDSET and LABEL which exist specifically for adding structure to a form, so it's not really a question of just using DIV. You should be able to markup a form with pretty minimal HTML, and let CSS do the rest of the work. E.g.: ``` <fieldset> <div> <label for="nameTextBox">Name:</label> <input id="nameTextBox" type="text" /> </div> ... </fieldset> ```
109,491
<p>I keep getting compiler errors when I try to access flashVars in an AS3 class.</p> <p>Here's a stripped version of the code:</p> <pre><code>package myPackage { import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; public class myClass { public function CTrafficHandler() { var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myFvar;}}} </code></pre> <p>And I get a compilation error:</p> <p><em>1119: Access of possibly undefined property root through a reference with static type source:myClass.</em></p> <p>When I change the class row to</p> <pre><code>public class myClass extends Sprite { </code></pre> <p>I don't get a compiler error, but I do get this in the output window:</p> <p><em>TypeError: Error #1009: Cannot access a property or method of a null object reference.</em></p> <p>Via the debugger (as suggested) I can see that <strong>this.root</strong> is null.</p> <p>How can I solve this problem?</p>
[ { "answer_id": 109505, "author": "Michael Pliskin", "author_id": 9777, "author_profile": "https://Stackoverflow.com/users/9777", "pm_score": 0, "selected": false, "text": "<p>I think you should extend from Sprite, but be sure to initialize it first and maybe put to the stage. Try to enable debugging and see what exactly is null as exception report says.</p>\n" }, { "answer_id": 109611, "author": "Eliram", "author_id": 18790, "author_profile": "https://Stackoverflow.com/users/18790", "pm_score": 3, "selected": true, "text": "<p>I found what the problem was. The class in question wasn't the main class used in the project, but rather a secondary class.</p>\n\n<p>I've moved the code to the main class to get the parameters and after I got them, I sent them to the class constructor function.</p>\n" }, { "answer_id": 109623, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 1, "selected": false, "text": "<p>As an alternative, you could try using the <strong>mx.core.Application.application.parameters</strong> object.</p>\n\n<p>From the LiveDocs page for <a href=\"http://livedocs.adobe.com/flex/3/langref/mx/core/Application.html#propertySummary\" rel=\"nofollow noreferrer\">mx.core.Application</a>:</p>\n\n<blockquote>\n <p><strong>application</strong> : Object\n <br/>[static] [read-only] A reference to the top-level application.\n <br/>\n <br/><strong>parameters</strong> : Object\n <br/>[read-only] The parameters property returns an Object containing name-value pairs representing the parameters provided to this Application.\n <br/>\n <br/>There are two sources of parameters: the query string of the Application's URL, and the value of the FlashVars HTML parameter (this affects only the main Application).</p>\n</blockquote>\n" }, { "answer_id": 116500, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 2, "selected": false, "text": "<p>The problem was indeed that you were attempting to access this information from a non-display object, or from outside of the document class. If you wish to access root or stage, the object that wishes to access such must be first added to the display list.</p>\n\n<p>I often use flashvars for variables that are used often throughout the project. Variables like country, and language. I find that in this case it is best to catch these parameters in the document class and create public variables with said parameters as values. This will give _global style access to these variables. That all being said, you really should use global variables sparingly, especially when working on collaborative projects.</p>\n" }, { "answer_id": 4268438, "author": "cleverbit", "author_id": 346098, "author_profile": "https://Stackoverflow.com/users/346098", "pm_score": 2, "selected": false, "text": "<p>Your problem is that your DisplayObject has not been added to the DisplayList, at the point at which you're trying to access flash vars. The root display object is therefore null, according to your object.</p>\n\n<p>You can ensure that your DisplayObject is on the stage by using the following:</p>\n\n<pre><code>package\n{\n import flash.display.Sprite;\n import flash.events.Event;\n\n public class MySprite extends Sprite\n {\n // constructor\n public function MySprite()\n {\n super();\n addEventListener( Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true );\n }\n\n private function onAddedToStage( event:Event ):void\n {\n removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );\n\n var paramList:Object = LoaderInfo( this.root.loaderInfo ).parameters;\n var myParam:String = paramList[\"myParam\"];\n }\n }\n}\n</code></pre>\n\n<p>`</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18790/" ]
I keep getting compiler errors when I try to access flashVars in an AS3 class. Here's a stripped version of the code: ``` package myPackage { import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; public class myClass { public function CTrafficHandler() { var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myFvar;}}} ``` And I get a compilation error: *1119: Access of possibly undefined property root through a reference with static type source:myClass.* When I change the class row to ``` public class myClass extends Sprite { ``` I don't get a compiler error, but I do get this in the output window: *TypeError: Error #1009: Cannot access a property or method of a null object reference.* Via the debugger (as suggested) I can see that **this.root** is null. How can I solve this problem?
I found what the problem was. The class in question wasn't the main class used in the project, but rather a secondary class. I've moved the code to the main class to get the parameters and after I got them, I sent them to the class constructor function.
109,520
<p>I've got my Rails (2.1) app setup to send email via Gmail, however whenever I send an email no matter what I set the from address to in my ActionMailer the emails always come as if sent from my Gmail email address. Is this a security restriction they've put in place at Gmail to stop spammers using their SMTP?</p> <p>Note: I've tried both of the following methods within my ActionMailer (just in case):</p> <pre><code>@from = [email protected] from '[email protected]' </code></pre>
[ { "answer_id": 109539, "author": "ColinD", "author_id": 13792, "author_profile": "https://Stackoverflow.com/users/13792", "pm_score": 4, "selected": true, "text": "<p>I believe it's just something Gmail does when mail is sent through its SMTP, as it was mentioned that they do this on a tutorial about using their SMTP to send mail.</p>\n" }, { "answer_id": 109558, "author": "Chris", "author_id": 19290, "author_profile": "https://Stackoverflow.com/users/19290", "pm_score": 2, "selected": false, "text": "<p>This is most likely to stop people trying to send email from addresses that Google can't verify that the sender owns. This is fairly common amongst mail providers, and is probably a safeguard to stop people using Google's services for sending spam.</p>\n" }, { "answer_id": 109617, "author": "Bill Turner", "author_id": 17773, "author_profile": "https://Stackoverflow.com/users/17773", "pm_score": 2, "selected": false, "text": "<p>I think I tried and failed in the past myself, but I did just come across this on the gmail site: <a href=\"http://mail.google.com/support/bin/answer.py?ctx=gmail&amp;hl=en&amp;answer=22370\" rel=\"nofollow noreferrer\">http://mail.google.com/support/bin/answer.py?ctx=gmail&amp;hl=en&amp;answer=22370</a></p>\n\n<p>Looks like you can specify a custom \"From\" address within gmail, and perhaps at that point, see if setting @from will work (now that gmail knows about your custom from address).</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
I've got my Rails (2.1) app setup to send email via Gmail, however whenever I send an email no matter what I set the from address to in my ActionMailer the emails always come as if sent from my Gmail email address. Is this a security restriction they've put in place at Gmail to stop spammers using their SMTP? Note: I've tried both of the following methods within my ActionMailer (just in case): ``` @from = [email protected] from '[email protected]' ```
I believe it's just something Gmail does when mail is sent through its SMTP, as it was mentioned that they do this on a tutorial about using their SMTP to send mail.
109,580
<p>I'm looking to grab cookie values for the same domain within a Flash movie. Is this possible?</p> <p>Let's see I let a user set a variable foo and I store it using any web programming language. I can access it easily via that language, but I would like to access it via the Flash movie without passing it in via printing it within the HTML page.</p>
[ { "answer_id": 109597, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>I believe flash objects have functions accessible through javascript, so if there's no easier way, you could at least use a javascript onload handler and pass document.cookie into your flash app from the outside. </p>\n\n<p>More info here: <a href=\"http://www.permadi.com/tutorial/flashjscommand/\" rel=\"nofollow noreferrer\">http://www.permadi.com/tutorial/flashjscommand/</a></p>\n" }, { "answer_id": 109600, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 0, "selected": false, "text": "<p>You can read and write cookies (Local Shared Object) from flash. Flash cookies are stored on your PC within a directory with the name of your domain. Those directories are located at: </p>\n\n<pre><code>[Root drive]:\\Documents and Settings\\[username]\\Application Data\\Macromedia\\Flash Player\\#SharedObjects\\\n</code></pre>\n\n<p>This <a href=\"http://www.adobe.com/products/flashplayer/articles/lso/\" rel=\"nofollow noreferrer\">article</a> from Adobe is a good start.</p>\n" }, { "answer_id": 109609, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 0, "selected": false, "text": "<p>Some Googling shows that it can be done by using <a href=\"http://forums.asp.net/t/1315014.aspx\" rel=\"nofollow noreferrer\">query strings</a>:</p>\n\n<blockquote>\n <p>For web applications, you can pass\n values to swf by url parameters, and\n (with action script inside swf) save\n them to the sandbox.</p>\n</blockquote>\n" }, { "answer_id": 110626, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 0, "selected": false, "text": "<p>cookies are available to javascript through document.cookie - try using flash's getURL to call a javascript function.</p>\n\n<p><code>getURL('javascript:document.cookie = \"varname=varvalue; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=\"');</code></p>\n" }, { "answer_id": 114287, "author": "Simon", "author_id": 15371, "author_profile": "https://Stackoverflow.com/users/15371", "pm_score": 5, "selected": true, "text": "<p>If you just want to store and retrieve data, you probably want to use the SharedObject class. See <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html\" rel=\"noreferrer\">Adobe's SharedObject reference</a> for more details of that.</p>\n\n<p>If you want to access the HTTP cookies, you'll need to use ExternalInterface to talk to javascript. The way we do that here is to have a helper class called HTTPCookies.</p>\n\n<p>HTTPCookies.as:</p>\n\n<pre><code>import flash.external.ExternalInterface;\n\npublic class HTTPCookies\n{\n public static function getCookie(key:String):*\n {\n return ExternalInterface.call(\"getCookie\", key);\n }\n\n public static function setCookie(key:String, val:*):void\n {\n ExternalInterface.call(\"setCookie\", key, val);\n }\n}\n</code></pre>\n\n<p>You need to make sure you enable javascript using the 'allowScriptAccess' parameter in your flash object.</p>\n\n<p>Then you need to create a pair of javascript functions, getCookie and setCookie, as follows (with thanks to <a href=\"http://www.quirksmode.org/js/cookies.html\" rel=\"noreferrer\">quirksmode.org</a>)</p>\n\n<p>HTTPCookies.js:</p>\n\n<pre><code>function getCookie(key)\n{\n var cookieValue = null;\n\n if (key)\n {\n var cookieSearch = key + \"=\";\n\n if (document.cookie)\n {\n var cookieArray = document.cookie.split(\";\");\n for (var i = 0; i &lt; cookieArray.length; i++)\n {\n var cookieString = cookieArray[i];\n\n // skip past leading spaces\n while (cookieString.charAt(0) == ' ')\n {\n cookieString = cookieString.substr(1);\n }\n\n // extract the actual value\n if (cookieString.indexOf(cookieSearch) == 0)\n {\n cookieValue = cookieString.substr(cookieSearch.length);\n }\n }\n }\n }\n\n return cookieValue;\n}\n\nfunction setCookie(key, val)\n{\n if (key)\n {\n var date = new Date();\n\n if (val != null)\n {\n // expires in one year\n date.setTime(date.getTime() + (365*24*60*60*1000));\n document.cookie = key + \"=\" + val + \"; expires=\" + date.toGMTString();\n }\n else\n {\n // expires yesterday\n date.setTime(date.getTime() - (24*60*60*1000));\n document.cookie = key + \"=; expires=\" + date.toGMTString();\n }\n }\n}\n</code></pre>\n\n<p>Once you have HTTPCookies.as in your flash project, and HTTPCookies.js loaded from your web page, you should be able to call getCookie and setCookie from within your flash movie to get or set HTTP cookies.</p>\n\n<p>This will only work for very simple values - strings or numbers - but for anything more complicated you really should be using SharedObject.</p>\n" }, { "answer_id": 159007, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>getCookie method in HTTPCookies.as should use \"return\" statement.</p>\n\n<pre><code>import flash.external.ExternalInterface;\npublic class HTTPCookies\n{ \n public static function getCookie(key:String):* \n {\n return ExternalInterface.call(\"getCookie\", key); \n }\n public static function setCookie(key:String, val:*):void \n {\n ExternalInterface.call(\"setCookie\", key, val); \n }\n}\n</code></pre>\n" }, { "answer_id": 50107487, "author": "Eddie", "author_id": 654499, "author_profile": "https://Stackoverflow.com/users/654499", "pm_score": 0, "selected": false, "text": "<p>I'm 10 years too late. If you can embed the data you need in the page, it's 10 times easier to grab.</p>\n\n<pre><code>import flash.net.*\n\nvar _loader:URLLoader = new URLLoader();\nvar _req:URLRequest = new URLRequest('https://stackoverflow.com');\n_loader.addEventListener(Event.COMPLETE, _onComplete);\n_loader.load(_req);\n\nfunction _onComplete(e:Event):void{\n var wantedData:RegExp = /&lt;div class=\"cool-data\"&gt;(.*?)&lt;/div&gt;/ig;\n var result:Object = wantedData.exec(String(_loader.data));\n trace(result[0].split('&lt;div class=\"cool-data\"&gt;').join('')\n .split('&lt;/div&gt;').join(''));\n\n}\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497/" ]
I'm looking to grab cookie values for the same domain within a Flash movie. Is this possible? Let's see I let a user set a variable foo and I store it using any web programming language. I can access it easily via that language, but I would like to access it via the Flash movie without passing it in via printing it within the HTML page.
If you just want to store and retrieve data, you probably want to use the SharedObject class. See [Adobe's SharedObject reference](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html) for more details of that. If you want to access the HTTP cookies, you'll need to use ExternalInterface to talk to javascript. The way we do that here is to have a helper class called HTTPCookies. HTTPCookies.as: ``` import flash.external.ExternalInterface; public class HTTPCookies { public static function getCookie(key:String):* { return ExternalInterface.call("getCookie", key); } public static function setCookie(key:String, val:*):void { ExternalInterface.call("setCookie", key, val); } } ``` You need to make sure you enable javascript using the 'allowScriptAccess' parameter in your flash object. Then you need to create a pair of javascript functions, getCookie and setCookie, as follows (with thanks to [quirksmode.org](http://www.quirksmode.org/js/cookies.html)) HTTPCookies.js: ``` function getCookie(key) { var cookieValue = null; if (key) { var cookieSearch = key + "="; if (document.cookie) { var cookieArray = document.cookie.split(";"); for (var i = 0; i < cookieArray.length; i++) { var cookieString = cookieArray[i]; // skip past leading spaces while (cookieString.charAt(0) == ' ') { cookieString = cookieString.substr(1); } // extract the actual value if (cookieString.indexOf(cookieSearch) == 0) { cookieValue = cookieString.substr(cookieSearch.length); } } } } return cookieValue; } function setCookie(key, val) { if (key) { var date = new Date(); if (val != null) { // expires in one year date.setTime(date.getTime() + (365*24*60*60*1000)); document.cookie = key + "=" + val + "; expires=" + date.toGMTString(); } else { // expires yesterday date.setTime(date.getTime() - (24*60*60*1000)); document.cookie = key + "=; expires=" + date.toGMTString(); } } } ``` Once you have HTTPCookies.as in your flash project, and HTTPCookies.js loaded from your web page, you should be able to call getCookie and setCookie from within your flash movie to get or set HTTP cookies. This will only work for very simple values - strings or numbers - but for anything more complicated you really should be using SharedObject.
109,592
<p>In tomcat 6 i have a servlet running openbluedragon, everything compiles and servers up quik, with the exception of images, they really lag significantly. Any suggestions optimization for image serving?</p> <p>Here is my server.xml:</p> <pre><code> &lt;Service name="Catalina"&gt; &lt;Connector port="8009" protocol="AJP/1.3" /&gt; &lt;Connector port="8080" maxThreads="100" protocol="HTTP/1.1" connectionTimeout="20000" /&gt; &lt;Engine name="Standalone" defaultHost="hostname.whatever" jvmRoute="ajp13"&gt; &lt;Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/&gt; &lt;Host name="hostname.whatever" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"&gt; ...context &lt;/Host&gt; &lt;/Engine&gt; &lt;/Service&gt; </code></pre>
[ { "answer_id": 109679, "author": "user19113", "author_id": 19113, "author_profile": "https://Stackoverflow.com/users/19113", "pm_score": 2, "selected": false, "text": "<p>If you have the option, you could add a reverse proxy in advance of your application. At work I have an Apache web server that receives all inbound HTTP connections. Based on the URL, it either forwards the request to another server or serves up the content itself. I've used this approach to accelerate serving up static content for a Trac site. The ProxyPass and ProxyPassReverse directives are a good place to start looking if you want to go this route.</p>\n\n<p>As a simple example, if you have a virtual directory called /images, Apache could serve up any request for something in that directory and forward everything else to your Tomcat instance. The syntax is pretty comprehensive. If there is any method at all to the way your static content is identified this is an approach that will work.</p>\n\n<p>Apache isn't the only choice here. I think all modern web servers include similar functionality. If I was starting today I'd probably look at LigHTTPd instead, just because it does less.</p>\n\n<p>There may even be caching reverse proxies that figure this out for you automatically. I'm not familiar with any of them though.</p>\n" }, { "answer_id": 113480, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 3, "selected": true, "text": "<p>Another option is to use apache as a frontend, connecting tomcat with mod_jk. This way you can let apache serve static content (e.g. images, css, javascript) and let tomcat generate the dynamic content. Might leave a bit of work to separate the static content from the dynamic ones, but works great for me.</p>\n\n<p>On Unix, having an apache as frontend is a nice option because being bound to port 80 you're often forced to run as root. Apache knows how to drop root permissions after binding a port, Tomcat doesn't. You don't want a server faced to the public to run as root.</p>\n\n<p>(This is similar to the reverse proxy answer, but doesn't involve a proxy but mod_jk)</p>\n" }, { "answer_id": 442686, "author": "Simon Groenewolt", "author_id": 31884, "author_profile": "https://Stackoverflow.com/users/31884", "pm_score": 2, "selected": false, "text": "<p>Are you serving the same set of images over and over? In that case adding a servlet filter that adds a reasonable Expires header might save tomcat a lot of work. It will not increase the speed of the served image but will just make the number of requests it has to handle less. Lots of examples for this on the web.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18159/" ]
In tomcat 6 i have a servlet running openbluedragon, everything compiles and servers up quik, with the exception of images, they really lag significantly. Any suggestions optimization for image serving? Here is my server.xml: ``` <Service name="Catalina"> <Connector port="8009" protocol="AJP/1.3" /> <Connector port="8080" maxThreads="100" protocol="HTTP/1.1" connectionTimeout="20000" /> <Engine name="Standalone" defaultHost="hostname.whatever" jvmRoute="ajp13"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> <Host name="hostname.whatever" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> ...context </Host> </Engine> </Service> ```
Another option is to use apache as a frontend, connecting tomcat with mod\_jk. This way you can let apache serve static content (e.g. images, css, javascript) and let tomcat generate the dynamic content. Might leave a bit of work to separate the static content from the dynamic ones, but works great for me. On Unix, having an apache as frontend is a nice option because being bound to port 80 you're often forced to run as root. Apache knows how to drop root permissions after binding a port, Tomcat doesn't. You don't want a server faced to the public to run as root. (This is similar to the reverse proxy answer, but doesn't involve a proxy but mod\_jk)
109,608
<p>When I place a control on a tabpage in Silverlight the control is placed ~10 pixels down and ~10 pixels right. For example, the following xaml:</p> <pre><code>&lt;System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left="0" Canvas.Top="75" Width="800" Height="525" Background="Red" HorizontalContentAlignment="Left" VerticalContentAlignment="Top" Padding="0" Margin="0"&gt; &lt;System_Windows_Controls:TabItem Header="Test" VerticalContentAlignment="Top" BorderThickness="0" Margin="0" Padding="0" HorizontalContentAlignment="Left"&gt; &lt;ContentControl&gt; &lt;Grid Width="400" Height="200" Background="White"/&gt; &lt;/ContentControl&gt; &lt;/System_Windows_Controls:TabItem&gt; &lt;/System_Windows_Controls:TabControl&gt; </code></pre> <p>will produce:</p> <p><img src="https://i.stack.imgur.com/y5LuN.jpg" alt="alt text"></p> <p>How do I position the content at 0,0?</p>
[ { "answer_id": 110046, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 2, "selected": false, "text": "<p>Check the control template of your TabItem , it might have some default Margin of 10. Just a guess</p>\n" }, { "answer_id": 110400, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 2, "selected": true, "text": "<p>Look at the control template, it has a margin of that size. Use blend to modify the a copy of the tab control's template.</p>\n" }, { "answer_id": 110845, "author": "Stefan Rusek", "author_id": 19704, "author_profile": "https://Stackoverflow.com/users/19704", "pm_score": 0, "selected": false, "text": "<p>After spending a couple hours fooling around with this problem. Brian is totally right. The current version of VS does not allow changing the TabControl's template, but it can be done using Blend, and there is a margin on the template. The main drawback of doing this is that the XAML file will no longer be previewable from Visual Studio.</p>\n" }, { "answer_id": 159396, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can also add a negative margin to the content. I found the value to be 9 pixels...</p>\n\n<pre><code>&lt;System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left=\"0\" Canvas.Top=\"75\" Width=\"800\" Height=\"525\" Background=\"Red\" HorizontalContentAlignment=\"Left\" VerticalContentAlignment=\"Top\" Padding=\"0\" Margin=\"0\"&gt;\n &lt;System_Windows_Controls:TabItem Header=\"Test\" VerticalContentAlignment=\"Top\" BorderThickness=\"0\" Margin=\"0\" Padding=\"0\" HorizontalContentAlignment=\"Left\"&gt;\n &lt;ContentControl&gt;\n &lt;Grid Width=\"400\" Height=\"200\" Margin=\"-9,-9,-9,-9\" Background=\"White\"/&gt;\n &lt;/ContentControl&gt;\n &lt;/System_Windows_Controls:TabItem&gt; \n&lt;/System_Windows_Controls:TabControl&gt;\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4244/" ]
When I place a control on a tabpage in Silverlight the control is placed ~10 pixels down and ~10 pixels right. For example, the following xaml: ``` <System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left="0" Canvas.Top="75" Width="800" Height="525" Background="Red" HorizontalContentAlignment="Left" VerticalContentAlignment="Top" Padding="0" Margin="0"> <System_Windows_Controls:TabItem Header="Test" VerticalContentAlignment="Top" BorderThickness="0" Margin="0" Padding="0" HorizontalContentAlignment="Left"> <ContentControl> <Grid Width="400" Height="200" Background="White"/> </ContentControl> </System_Windows_Controls:TabItem> </System_Windows_Controls:TabControl> ``` will produce: ![alt text](https://i.stack.imgur.com/y5LuN.jpg) How do I position the content at 0,0?
Look at the control template, it has a margin of that size. Use blend to modify the a copy of the tab control's template.
109,618
<p>I want the following layout to appear on the screen:</p> <pre><code>FieldName 1 [Field input 1] FieldName 2 is longer [Field input 2] . . . . FieldName N [Field input N] </code></pre> <p>Requirements:</p> <ul> <li>Field names and field inputs must align on the left edges</li> <li>Both columns must dynamically size themselves to their content</li> <li>Must work cross-browsers</li> </ul> <p>I find this layout extremely simple to do using HTML tables, but since I see a lot of CSS purists insisting that tables only be used for tabular data I figured I'd find out if there was a way to do it using CSS.</p>
[ { "answer_id": 109628, "author": "Héctor Ramos", "author_id": 19617, "author_profile": "https://Stackoverflow.com/users/19617", "pm_score": -1, "selected": false, "text": "<p>FieldName objects should be contained in SPANs with style attributes of float: left and a width that is wide enough for your labels.</p>\n\n<p>Inputs should be contained within a span styled to float: left. Place a <code>&lt;div style=\"clear: both\"/&gt;</code> or <code>&lt;br/&gt;</code> after each field input to break the floating.</p>\n\n<p>You may enclose the aforementioned objects into a div with the width style attribute set that is wide enough for both labels and inputs, so that the \"table\" stays small and contained.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;span style=\"float: left; width: 200px\"&gt;FieldName1&lt;/span&gt;&lt;span style=\"float: left\"&gt;&lt;input/&gt;&lt;br/&gt;\n\n&lt;span style=\"float: left; width: 200px\"&gt;FieldName2&lt;/span&gt;&lt;span style=\"float: left\"&gt;&lt;input/&gt;&lt;br/&gt;\n\n&lt;span style=\"float: left\"&gt;FieldName3&lt;/span&gt;&lt;span style=\"float: left\"&gt;&lt;input/&gt;&lt;br/&gt;\n</code></pre>\n" }, { "answer_id": 109653, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": -1, "selected": false, "text": "<p>Each row is to be taken as a 'div' that contains two 'spans' one for fieldname and one for the input. Set 'float:left' on both the spans. However, you need to set some width for the 'fieldname' span.</p>\n\n<p>Also, style the div to include the attribute 'clear:both' for precaution.</p>\n" }, { "answer_id": 109656, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 2, "selected": false, "text": "<p>better still use a list</p>\n\n<pre><code> &lt;fieldset class=\"classname\"&gt;\n &lt;ul&gt;\n &lt;li&gt;\n &lt;label&gt;Title:&lt;/label&gt;\n &lt;input type=\"text\" name=\"title\" value=\"\" /&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/fieldset&gt;\n</code></pre>\n\n<p>the set the li tags width wide enough for both label and input and float the label to the left.</p>\n\n<p>also to achieve that table like block with the tables you could set the label width to be as big as the largest fieldname forcing all the labels or expand that wide.</p>\n\n<p>[edit] this is some good reading on <a href=\"http://www.alistapart.com/stories/practicalcss/\" rel=\"nofollow noreferrer\">a list apart</a></p>\n" }, { "answer_id": 109670, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 4, "selected": false, "text": "<p>I wouldn't, I would use a table. This is a classic example of a tabular layout - exactly the sort of thing tables are <em>supposed</em> to be used for.</p>\n" }, { "answer_id": 109714, "author": "robertc", "author_id": 8655, "author_profile": "https://Stackoverflow.com/users/8655", "pm_score": 2, "selected": false, "text": "<p>It's not clear that it is tabular data as some others have commented, though it could be. A table would imply a semantic relationship between all the items in the respective columns (other than just \"they're all names of database columns\"). Anyway, here's how I've done it before:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"&gt;\n&lt;head&gt;\n &lt;title&gt;Form layout&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n fieldset {width: 60%; margin: 0 auto;}\n div.row {clear: both;}\n div.row label {float: left; width: 60%;}\n div.row span {float: right; width: 35%;}\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form action=\"#\" method=\"post\"&gt;\n &lt;fieldset&gt;\n &lt;legend&gt;Section one&lt;/legend&gt;\n &lt;div class=\"row\"&gt;\n &lt;label for=\"first-field\"&gt;The first field&lt;/label&gt;\n &lt;span&gt;&lt;input type=\"text\" id=\"first-field\" size=\"15\" /&gt;&lt;/span&gt;\n &lt;/div&gt;\n &lt;div class=\"row\"&gt;\n &lt;label for=\"second-field\"&gt;The second field with a longer label&lt;/label&gt;\n &lt;span&gt;&lt;input type=\"text\" id=\"second-field\" size=\"10\" /&gt;&lt;/span&gt;\n &lt;/div&gt;\n &lt;div class=\"row\"&gt;\n &lt;label for=\"third-field\"&gt;The third field&lt;/label&gt;\n &lt;span&gt;&lt;input type=\"text\" id=\"third-field\" size=\"5\" /&gt;&lt;/span&gt;\n &lt;/div&gt;\n &lt;div class=\"row\"&gt;\n &lt;input type=\"submit\" value=\"Go\" /&gt;\n &lt;/div&gt;\n &lt;/fieldset&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Edit: Seems that 'by design' I can't reply to comments on my answer, obviously this is somehow less confusing. So, in reply to 17 of 26's comment - the 60% width is entirely optional, by default the fieldset will inherit the width of the containing element. You could also, of course, make use of min-width and max-width, or any of the table layout rules, if only IE supported them, but that's not CSS failing miserably ;)</p>\n" }, { "answer_id": 109756, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 4, "selected": true, "text": "<p>I think most of the answers are missing the point that the original questioner wanted the columns widths to depend on the width of the content. I believe the only way to do this with pure CSS is by using 'display: table', 'display: table-row' and 'display: table-cell', but that isn't supported by IE. But I'm not sure that this property is desirable, I find that creating a wide columns because there is a single long field name makes the layout less aesthetically pleasing and harder to use. Wrapped lines are fine in my opinion, so I think the answers that I just suggested were incorrect are probably the way to go.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/109618/how-would-you-achieve-this-table-based-layout-using-css-instead-of-html-tables#109714\">Robertc's example</a> is ideal but if you really must use tables, I think you can make it a little more 'semantic' by using <code>&lt;th&gt;</code> for the field names. I'm not sure about this so please someone correct me if I'm wrong.</p>\n\n<pre><code>&lt;table&gt;\n &lt;tr&gt;&lt;th scope=\"row\"&gt;&lt;label for=\"field1\"&gt;FieldName 1&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input id=\"field1\" name=\"field1\"&gt;&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;th scope=\"row\"&gt;&lt;label for=\"field2\"&gt;FieldName 2 is longer&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input id=\"field2\" name=\"field2\"&gt;&lt;/td&gt;&lt;/tr&gt;\n &lt;!-- ....... --&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>Update: I haven't been following this closely, but IE8 apparently supports CSS tables, so some are suggesting that we should start using them. There's an <a href=\"http://24ways.org/2008/the-first-tool-you-reach-for\" rel=\"nofollow noreferrer\">article on 24 ways</a> which contains a relevant example at the end.</p>\n" }, { "answer_id": 167263, "author": "Carl Camera", "author_id": 12804, "author_profile": "https://Stackoverflow.com/users/12804", "pm_score": 2, "selected": false, "text": "<p>This markup and CSS roughly achieves your stated goals under the restrictions for this question...</p>\n<p><strong>The Proposal</strong></p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;\n&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;\n&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot; lang=&quot;en&quot;&gt;\n &lt;head&gt;\n &lt;title&gt;My Form&lt;/title&gt;\n &lt;style type=&quot;text/css&quot;&gt;\n #frm1 div {float: left;}\n #frm1 div.go {clear: both; }\n #frm1 label, #frm1 input { float: left; clear: left; }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;form id=&quot;frm1&quot; action=&quot;#&quot; method=&quot;post&quot;&gt;\n &lt;fieldset&gt;\n &lt;legend&gt;Section One&lt;/legend&gt;\n &lt;div&gt;\n &lt;label for=&quot;field1&quot;&gt;Name&lt;/label&gt;\n &lt;label for=&quot;field2&quot;&gt;Address, City, State, Zip&lt;/label&gt;\n &lt;label for=&quot;field3&quot;&gt;Country&lt;/label&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;input type=&quot;text&quot; id=&quot;field1&quot; size=&quot;15&quot; /&gt;\n &lt;input type=&quot;text&quot; id=&quot;field2&quot; size=&quot;20&quot; /&gt;\n &lt;input type=&quot;text&quot; id=&quot;field3&quot; size=&quot;10&quot; /&gt;\n &lt;/div&gt;\n &lt;div class=&quot;go&quot;&gt;\n &lt;input type=&quot;submit&quot; value=&quot;Go&quot; /&gt;\n &lt;/div&gt;\n &lt;/fieldset&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<p><strong>The Merits</strong></p>\n<p>...but I would not recommend its use. The problems with this solution are</p>\n<ol>\n<li>the very annoying entire-column wrap at skinny browser widths</li>\n<li>it separates the labels from their associated input fields in the markup</li>\n</ol>\n<p>The solution above should be (I haven't verified this) accessible-friendly because screen readers, I have read, do a good job of using the <code>for=&quot;&quot;</code> attribute in associating labels to input fields. So visually and accessibly-wise this works, but you might not like listing all your labels separately from your input fields.</p>\n<p><strong>Conclusion</strong></p>\n<p>The question as it is crafted -- specifically the requirement to automatically size the width of an entire column of different-length labels to the largest label length -- biases the markup solution towards tables. Absent that requirement, there are several great semantic solutions to presenting forms, as has been mentioned and suggested by others in this thread.</p>\n<p>My point is this: There are several ways to present forms and collect user input in a pleasing, accessible, and intuitive way. If you can find no CSS layout that can meet your minimum requirements but tables can, then use tables.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284/" ]
I want the following layout to appear on the screen: ``` FieldName 1 [Field input 1] FieldName 2 is longer [Field input 2] . . . . FieldName N [Field input N] ``` Requirements: * Field names and field inputs must align on the left edges * Both columns must dynamically size themselves to their content * Must work cross-browsers I find this layout extremely simple to do using HTML tables, but since I see a lot of CSS purists insisting that tables only be used for tabular data I figured I'd find out if there was a way to do it using CSS.
I think most of the answers are missing the point that the original questioner wanted the columns widths to depend on the width of the content. I believe the only way to do this with pure CSS is by using 'display: table', 'display: table-row' and 'display: table-cell', but that isn't supported by IE. But I'm not sure that this property is desirable, I find that creating a wide columns because there is a single long field name makes the layout less aesthetically pleasing and harder to use. Wrapped lines are fine in my opinion, so I think the answers that I just suggested were incorrect are probably the way to go. [Robertc's example](https://stackoverflow.com/questions/109618/how-would-you-achieve-this-table-based-layout-using-css-instead-of-html-tables#109714) is ideal but if you really must use tables, I think you can make it a little more 'semantic' by using `<th>` for the field names. I'm not sure about this so please someone correct me if I'm wrong. ``` <table> <tr><th scope="row"><label for="field1">FieldName 1</label></th> <td><input id="field1" name="field1"></td></tr> <tr><th scope="row"><label for="field2">FieldName 2 is longer</label></th> <td><input id="field2" name="field2"></td></tr> <!-- ....... --> </table> ``` Update: I haven't been following this closely, but IE8 apparently supports CSS tables, so some are suggesting that we should start using them. There's an [article on 24 ways](http://24ways.org/2008/the-first-tool-you-reach-for) which contains a relevant example at the end.
109,644
<p><code>temp2</code>, <code>temp1</code> are pointers to some struct x:</p> <pre><code>struct FunkyStruct x; struct FunkyStruct *temp1 = &amp;x, *temp2 = &amp;x; </code></pre> <p>Now, after execution of following lines:</p> <pre><code>temp2=temp1; temp1=temp1-&gt;nxt; </code></pre> <p>...Will <code>temp2</code> and <code>temp1</code> still point to the same memory location? If not, please explain why they would be different. </p>
[ { "answer_id": 109649, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 2, "selected": false, "text": "<p>temp2 will not be updated, but temp1 will point to the next item. So if temp1 is 0x89abcdef and temp1->next is 0x89b00000, then after you're done, temp1 will be 0x89b00000 and temp2 will be 0x89abcdef.</p>\n\n<p>Assuming you're making a linked list, of course.</p>\n" }, { "answer_id": 109652, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 1, "selected": false, "text": "<p>You're not really giving us enough information to answer your question. Are they starting out pointing to the same structure, or are they only both of type pointer to structure x? And if it's some struct x, what's the definition of the nxt field?</p>\n" }, { "answer_id": 109655, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 1, "selected": false, "text": "<p>Different.</p>\n\n<p>You've saved the address of what temp1 is initially pointed to into temp2. You then changed what temp1 is pointed to, not the variable at the other end of what temp1 is pointed to.</p>\n\n<p>If you had done</p>\n\n<pre><code>temp2 = temp1;\n*temp1 = temp1-&gt;foo;\n</code></pre>\n\n<p>then temp1 &amp; temp2 will both be pointing to (the same) modified variable.</p>\n" }, { "answer_id": 109660, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 1, "selected": false, "text": "<p>No, assuming there are pointers like in C. temp2 would be pointing at the location of x and temp1 would be pointing at whatever the nxt pointer points to. Usually this would be the layout for a singly linked list.</p>\n" }, { "answer_id": 109678, "author": "Pitarou", "author_id": 1260685, "author_profile": "https://Stackoverflow.com/users/1260685", "pm_score": 3, "selected": false, "text": "<p>Initially, <code>temp1</code> and <code>temp2</code> both contain the memory address of <code>x</code>.</p>\n\n<p><code>temp2 = temp1</code> means \"assign the value of <code>temp1</code> to <code>temp2</code>\". Since they have the same value to start with, this command does nothing.</p>\n\n<p>The expression <code>temp1-&gt;next</code> means \"Look inside the data structure that <code>temp1</code> points to, and return the value of the field <code>next</code>.\" So <code>temp1 = temp1-&gt;next</code> assigns the value of <code>temp1-&gt;next</code> to <code>temp1</code>. (Of course, the lookup happen <em>before</em> the assignment.) <code>temp1</code> will now contain whatever value the <code>next</code> field happened to contain. It could be the same as the old value, or it could be different.</p>\n" }, { "answer_id": 109789, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": false, "text": "<p>This sounds like a question based on a background in java?</p>\n\n<p>The answer that <a href=\"https://stackoverflow.com/users/10704/dysfunctor\">dysfunctor</a> gave is good.</p>\n\n<p>The important thing to realise is that in C assigning a pointer is no different to assigning an integer.</p>\n\n<p>Consider the following modification to your original code:</p>\n\n<pre><code> int temp1 = 1;\n int temp2;\n temp2=temp1;\n temp1=temp1 + 1;\n</code></pre>\n\n<p>At the end of this temp1 is 2, temp2 is 1.</p>\n\n<p>It's not like assigning a (non-primitive) object in java, where the assignment actually assigns a reference to the object rather than the value.</p>\n" }, { "answer_id": 110194, "author": "Marcelo Cantos", "author_id": 9990, "author_profile": "https://Stackoverflow.com/users/9990", "pm_score": 0, "selected": false, "text": "<p>x (and therefore x.nxt) will be initialised to an unspecified value, depending on the combination of compiler, compiler options and the runtime environment. temp1 and temp2 will both point to x (before and after temp1=temp2). Then temp1 will be assigned whatever value x.nxt has.</p>\n\n<p>Final answer: 0 &lt; Pr(temp1 == temp2) &lt;&lt; 1, because temp1 == temp2 iff x.nxt == &amp;x.</p>\n" }, { "answer_id": 110485, "author": "Thomas Bratt", "author_id": 15985, "author_profile": "https://Stackoverflow.com/users/15985", "pm_score": 0, "selected": false, "text": "<p>The short answer is no. But only if <strong>nxt</strong> is different to both <strong>temp1</strong> and <strong>temp2</strong> to start with.</p>\n\n<p>The line <strong>temp1=temp1->nxt;</strong> has two parts, separated by the <strong>=</strong> operator. These are:</p>\n\n<ul>\n<li>The right hand side <strong>temp1->nxt</strong> looks up the structure pointed to by <strong>temp1</strong> and takes the value of the <strong>nxt</strong> variable. This is a pointer (new memory location).</li>\n<li>The pointer from the right hand side is then used to update the value of <strong>temp1</strong>.</li>\n</ul>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19790/" ]
`temp2`, `temp1` are pointers to some struct x: ``` struct FunkyStruct x; struct FunkyStruct *temp1 = &x, *temp2 = &x; ``` Now, after execution of following lines: ``` temp2=temp1; temp1=temp1->nxt; ``` ...Will `temp2` and `temp1` still point to the same memory location? If not, please explain why they would be different.
Initially, `temp1` and `temp2` both contain the memory address of `x`. `temp2 = temp1` means "assign the value of `temp1` to `temp2`". Since they have the same value to start with, this command does nothing. The expression `temp1->next` means "Look inside the data structure that `temp1` points to, and return the value of the field `next`." So `temp1 = temp1->next` assigns the value of `temp1->next` to `temp1`. (Of course, the lookup happen *before* the assignment.) `temp1` will now contain whatever value the `next` field happened to contain. It could be the same as the old value, or it could be different.
109,705
<p>The following program is very simple: it outputs a single dot each half a second. If it recieves a <strong>SIGQUIT</strong>, it proceeds to output ten <strong>Q</strong>s. If it recieves a <strong>SIGTSTP</strong> <em>(<kbd>Ctrl</kbd>-<kbd>Z</kbd>)</em>, it outputs ten <strong>Z</strong>s.</p> <p>If it recieves a <strong>SIGTSTP</strong> while printing <strong>Q</strong>s, it will print ten <strong>Z</strong>s after it's done with the ten <strong>Q</strong>s. This is a good thing.</p> <p>However, if it recieves a <strong>SIGQUIT</strong> while printing <strong>Z</strong>s, it fails to print <strong>Q</strong>s after them. Instead, it prints them out only after I manually terminate execution via a KeyboardInterrupt. I want the <strong>Q</strong>s to be printed immediately after the <strong>Z</strong>s.</p> <p>This happens using Python2.3.</p> <p>What am I doing wrong?</p> <pre><code>#!/usr/bin/python from signal import * from time import sleep from sys import stdout def write(text): stdout.write(text) stdout.flush() def process_quit(signum, frame): for i in range(10): write(&quot;Q&quot;) sleep(0.5) def process_tstp(signum, frame): for i in range(10): write(&quot;Z&quot;) sleep(0.5) signal(SIGQUIT, process_quit) signal(SIGTSTP, process_tstp) while 1: write('.') sleep(0.5) </code></pre>
[ { "answer_id": 109783, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 4, "selected": true, "text": "<p>Your larger problem is blocking in signal handlers.</p>\n\n<p>This is usually discouraged since it can lead to strange timing conditions. But it's not quite the cause of your problem since the timing condition you're vulnerable to exists because of your choice of signal handlers.</p>\n\n<p>Anyway, here's how to at least minimize the timing condition by only setting flags in your handlers and leaving the main while loop to do the actual work. The explanation for why your code is behaving strangely is described after the code.</p>\n\n<pre><code>#!/usr/bin/python\n\nfrom signal import *\nfrom time import sleep\nfrom sys import stdout\n\nprint_Qs = 0\nprint_Zs = 0\n\ndef write(text):\n stdout.write(text)\n stdout.flush()\n\ndef process_quit(signum, frame):\n global print_Qs\n print_Qs = 10\n\ndef process_tstp(signum, frame):\n global print_Zs\n print_Zs = 10\n\nsignal(SIGQUIT, process_quit)\nsignal(SIGTSTP, process_tstp)\n\nwhile 1:\n if print_Zs:\n print_Zs -= 1\n c = 'Z'\n elif print_Qs:\n print_Qs -= 1\n c = 'Q'\n else:\n c = '.'\n write(c)\n sleep(0.5)\n</code></pre>\n\n<p>Anyway, here's what's going on.</p>\n\n<p>SIGTSTP is more special than SIGQUIT.</p>\n\n<p>SIGTSTP masks the other signals from being delivered while its signal handler is running. When the kernel goes to deliver SIGQUIT and sees that SIGTSTP's handler is still running, it simply saves it for later. Once another signal comes through for delivery, such as SIGINT when you <kbd>CTRL</kbd>+<kbd>C</kbd> (aka KeyboardInterrupt), the kernel remembers that it never delivered SIGQUIT and delivers it now.</p>\n\n<p>You will notice if you change <code>while 1:</code> to <code>for i in range(60):</code> in the main loop and do your test case again, the program will exit without running the SIGTSTP handler since exit doesn't re-trigger the kernel's signal delivery mechanism.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 109803, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 1, "selected": false, "text": "<p>On Python 2.5.2 on Linux 2.6.24, your code works exactly as you describe your desired results (if a signal is received while still processing a previous signal, the new signal is processed immediately after the first one is finished).</p>\n\n<p>On Python 2.4.4 on Linux 2.6.16, I see the problem behavior you describe.</p>\n\n<p>I don't know whether this is due to a change in Python or in the Linux kernel.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The following program is very simple: it outputs a single dot each half a second. If it recieves a **SIGQUIT**, it proceeds to output ten **Q**s. If it recieves a **SIGTSTP** *(`Ctrl`-`Z`)*, it outputs ten **Z**s. If it recieves a **SIGTSTP** while printing **Q**s, it will print ten **Z**s after it's done with the ten **Q**s. This is a good thing. However, if it recieves a **SIGQUIT** while printing **Z**s, it fails to print **Q**s after them. Instead, it prints them out only after I manually terminate execution via a KeyboardInterrupt. I want the **Q**s to be printed immediately after the **Z**s. This happens using Python2.3. What am I doing wrong? ``` #!/usr/bin/python from signal import * from time import sleep from sys import stdout def write(text): stdout.write(text) stdout.flush() def process_quit(signum, frame): for i in range(10): write("Q") sleep(0.5) def process_tstp(signum, frame): for i in range(10): write("Z") sleep(0.5) signal(SIGQUIT, process_quit) signal(SIGTSTP, process_tstp) while 1: write('.') sleep(0.5) ```
Your larger problem is blocking in signal handlers. This is usually discouraged since it can lead to strange timing conditions. But it's not quite the cause of your problem since the timing condition you're vulnerable to exists because of your choice of signal handlers. Anyway, here's how to at least minimize the timing condition by only setting flags in your handlers and leaving the main while loop to do the actual work. The explanation for why your code is behaving strangely is described after the code. ``` #!/usr/bin/python from signal import * from time import sleep from sys import stdout print_Qs = 0 print_Zs = 0 def write(text): stdout.write(text) stdout.flush() def process_quit(signum, frame): global print_Qs print_Qs = 10 def process_tstp(signum, frame): global print_Zs print_Zs = 10 signal(SIGQUIT, process_quit) signal(SIGTSTP, process_tstp) while 1: if print_Zs: print_Zs -= 1 c = 'Z' elif print_Qs: print_Qs -= 1 c = 'Q' else: c = '.' write(c) sleep(0.5) ``` Anyway, here's what's going on. SIGTSTP is more special than SIGQUIT. SIGTSTP masks the other signals from being delivered while its signal handler is running. When the kernel goes to deliver SIGQUIT and sees that SIGTSTP's handler is still running, it simply saves it for later. Once another signal comes through for delivery, such as SIGINT when you `CTRL`+`C` (aka KeyboardInterrupt), the kernel remembers that it never delivered SIGQUIT and delivers it now. You will notice if you change `while 1:` to `for i in range(60):` in the main loop and do your test case again, the program will exit without running the SIGTSTP handler since exit doesn't re-trigger the kernel's signal delivery mechanism. Good luck!
109,710
<p>I've been digging through some parts of the Linux kernel, and found calls like this:</p> <pre><code>if (unlikely(fd &lt; 0)) { /* Do something */ } </code></pre> <p>or</p> <pre><code>if (likely(!err)) { /* Do something */ } </code></pre> <p>I've found the definition of them:</p> <pre><code>#define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) </code></pre> <p>I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).</p>
[ { "answer_id": 109718, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 1, "selected": false, "text": "<p>They're hints to the compiler to generate the hint prefixes on branches. On x86/x64, they take up one byte, so you'll get at most a one-byte increase for each branch. As for performance, it entirely depends on the application -- in most cases, the branch predictor on the processor will ignore them, these days.</p>\n\n<p>Edit: Forgot about one place they can actually really help with. It can allow the compiler to reorder the control-flow graph to reduce the number of branches taken for the 'likely' path. This can have a marked improvement in loops where you're checking multiple exit cases.</p>\n" }, { "answer_id": 109720, "author": "dcgibbons", "author_id": 9644, "author_profile": "https://Stackoverflow.com/users/9644", "pm_score": 1, "selected": false, "text": "<p>These are GCC functions for the programmer to give a hint to the compiler about what the most likely branch condition will be in a given expression. This allows the compiler to build the branch instructions so that the most common case takes the fewest number of instructions to execute.</p>\n\n<p>How the branch instructions are built are dependent upon the processor architecture.</p>\n" }, { "answer_id": 109721, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 10, "selected": true, "text": "<p>They are hint to the compiler to emit instructions that will cause branch prediction to favour the \"likely\" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance.</p>\n\n<p>Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate.</p>\n" }, { "answer_id": 109727, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 4, "selected": false, "text": "<p>They cause the compiler to emit the appropriate branch hints where the hardware supports them. This usually just means twiddling a few bits in the instruction opcode, so code size will not change. The CPU will start fetching instructions from the predicted location, and flush the pipeline and start over if that turns out to be wrong when the branch is reached; in the case where the hint is correct, this will make the branch much faster - precisely how much faster will depend on the hardware; and how much this affects the performance of the code will depend on what proportion of the time hint is correct.</p>\n\n<p>For instance, on a PowerPC CPU an unhinted branch might take 16 cycles, a correctly hinted one 8 and an incorrectly hinted one 24. In innermost loops good hinting can make an enormous difference.</p>\n\n<p>Portability isn't really an issue - presumably the definition is in a per-platform header; you can simply define \"likely\" and \"unlikely\" to nothing for platforms that do not support static branch hints.</p>\n" }, { "answer_id": 109732, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 6, "selected": false, "text": "<p>These are macros that give hints to the compiler about which way a branch may go. The macros expand to GCC specific extensions, if they're available. </p>\n\n<p>GCC uses these to to optimize for branch prediction. For example, if you have something like the following</p>\n\n<pre><code>if (unlikely(x)) {\n dosomething();\n}\n\nreturn x;\n</code></pre>\n\n<p>Then it can restructure this code to be something more like:</p>\n\n<pre><code>if (!x) {\n return x;\n}\n\ndosomething();\nreturn x;\n</code></pre>\n\n<p>The benefit of this is that when the processor takes a branch the first time, there is significant overhead, because it may have been speculatively loading and executing code further ahead. When it determines it will take the branch, then it has to invalidate that, and start at the branch target.</p>\n\n<p>Most modern processors now have some sort of branch prediction, but that only assists when you've been through the branch before, and the branch is still in the branch prediction cache.</p>\n\n<p>There are a number of other strategies that the compiler and processor can use in these scenarios. You can find more details on how branch predictors work at Wikipedia: <a href=\"http://en.wikipedia.org/wiki/Branch_predictor\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Branch_predictor</a></p>\n" }, { "answer_id": 109744, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 2, "selected": false, "text": "<p>(general comment - other answers cover the details)</p>\n\n<p>There's no reason that you should lose portability by using them.</p>\n\n<p>You always have the option of creating a simple nil-effect \"inline\" or macro that will allow you to compile on other platforms with other compilers.</p>\n\n<p>You just won't get the benefit of the optimization if you're on other platforms.</p>\n" }, { "answer_id": 9594973, "author": "Finaldie", "author_id": 992917, "author_profile": "https://Stackoverflow.com/users/992917", "pm_score": 2, "selected": false, "text": "<p>In many linux release, you can find <code>compiler.h</code> in <code>/usr/linux/</code> , you can include it for use simply. And another opinion, unlikely() is more useful rather than likely(), because</p>\n<pre><code>if ( likely( ... ) ) {\n doSomething();\n}\n</code></pre>\n<p>it can be optimized as well in many compiler.</p>\n<p>And by the way, if you want to observe the detail behavior of the code, you can do simply as follow:</p>\n<blockquote>\n<p>gcc -c test.c\nobjdump -d test.o &gt; obj.s</p>\n</blockquote>\n<p>Then, open obj.s, you can find the answer.</p>\n" }, { "answer_id": 21391535, "author": "artless noise", "author_id": 1880339, "author_profile": "https://Stackoverflow.com/users/1880339", "pm_score": 2, "selected": false, "text": "<p>As per the comment by <a href=\"https://stackoverflow.com/users/4977/cody-brocious\">Cody</a>, this has nothing to do with Linux, but is a hint to the compiler. What happens will depend on the architecture and compiler version. </p>\n\n<p>This particular feature in Linux is somewhat mis-used in drivers. As <a href=\"https://stackoverflow.com/users/196561/osgx\">osgx</a> points out in <a href=\"https://stackoverflow.com/questions/15028990/semantics-of-gcc-hot-attribute\">semantics of hot attribute</a>, any <code>hot</code> or <code>cold</code> function called with in a block can automatically hint that the condition is likely or not. For instance, <code>dump_stack()</code> is marked <code>cold</code> so this is redundant,</p>\n\n<pre><code> if(unlikely(err)) {\n printk(\"Driver error found. %d\\n\", err);\n dump_stack();\n }\n</code></pre>\n\n<p>Future versions of <code>gcc</code> may selectively inline a function based on these hints. There have also been suggestions that it is not <code>boolean</code>, but a score as in <em>most likely</em>, etc. Generally, it should be preferred to use some alternate mechanism like <code>cold</code>. There is no reason to use it in any place but hot paths. What a compiler will do on one architecture can be completely different on another.</p>\n" }, { "answer_id": 31133787, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 7, "selected": false, "text": "<p><strong>Let's decompile to see what GCC 4.8 does with it</strong></p>\n\n<p><strong>Without <code>__builtin_expect</code></strong></p>\n\n<pre><code>#include \"stdio.h\"\n#include \"time.h\"\n\nint main() {\n /* Use time to prevent it from being optimized away. */\n int i = !time(NULL);\n if (i)\n printf(\"%d\\n\", i);\n puts(\"a\");\n return 0;\n}\n</code></pre>\n\n<p>Compile and decompile with GCC 4.8.2 x86_64 Linux:</p>\n\n<pre><code>gcc -c -O3 -std=gnu11 main.c\nobjdump -dr main.o\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>0000000000000000 &lt;main&gt;:\n 0: 48 83 ec 08 sub $0x8,%rsp\n 4: 31 ff xor %edi,%edi\n 6: e8 00 00 00 00 callq b &lt;main+0xb&gt;\n 7: R_X86_64_PC32 time-0x4\n b: 48 85 c0 test %rax,%rax\n e: 75 14 jne 24 &lt;main+0x24&gt;\n 10: ba 01 00 00 00 mov $0x1,%edx\n 15: be 00 00 00 00 mov $0x0,%esi\n 16: R_X86_64_32 .rodata.str1.1\n 1a: bf 01 00 00 00 mov $0x1,%edi\n 1f: e8 00 00 00 00 callq 24 &lt;main+0x24&gt;\n 20: R_X86_64_PC32 __printf_chk-0x4\n 24: bf 00 00 00 00 mov $0x0,%edi\n 25: R_X86_64_32 .rodata.str1.1+0x4\n 29: e8 00 00 00 00 callq 2e &lt;main+0x2e&gt;\n 2a: R_X86_64_PC32 puts-0x4\n 2e: 31 c0 xor %eax,%eax\n 30: 48 83 c4 08 add $0x8,%rsp\n 34: c3 retq\n</code></pre>\n\n<p>The instruction order in memory was unchanged: first the <code>printf</code> and then <code>puts</code> and the <code>retq</code> return.</p>\n\n<p><strong>With <code>__builtin_expect</code></strong></p>\n\n<p>Now replace <code>if (i)</code> with:</p>\n\n<pre><code>if (__builtin_expect(i, 0))\n</code></pre>\n\n<p>and we get:</p>\n\n<pre><code>0000000000000000 &lt;main&gt;:\n 0: 48 83 ec 08 sub $0x8,%rsp\n 4: 31 ff xor %edi,%edi\n 6: e8 00 00 00 00 callq b &lt;main+0xb&gt;\n 7: R_X86_64_PC32 time-0x4\n b: 48 85 c0 test %rax,%rax\n e: 74 11 je 21 &lt;main+0x21&gt;\n 10: bf 00 00 00 00 mov $0x0,%edi\n 11: R_X86_64_32 .rodata.str1.1+0x4\n 15: e8 00 00 00 00 callq 1a &lt;main+0x1a&gt;\n 16: R_X86_64_PC32 puts-0x4\n 1a: 31 c0 xor %eax,%eax\n 1c: 48 83 c4 08 add $0x8,%rsp\n 20: c3 retq\n 21: ba 01 00 00 00 mov $0x1,%edx\n 26: be 00 00 00 00 mov $0x0,%esi\n 27: R_X86_64_32 .rodata.str1.1\n 2b: bf 01 00 00 00 mov $0x1,%edi\n 30: e8 00 00 00 00 callq 35 &lt;main+0x35&gt;\n 31: R_X86_64_PC32 __printf_chk-0x4\n 35: eb d9 jmp 10 &lt;main+0x10&gt;\n</code></pre>\n\n<p>The <code>printf</code> (compiled to <code>__printf_chk</code>) was moved to the very end of the function, after <code>puts</code> and the return to improve branch prediction as mentioned by other answers.</p>\n\n<p>So it is basically the same as:</p>\n\n<pre><code>int main() {\n int i = !time(NULL);\n if (i)\n goto printf;\nputs:\n puts(\"a\");\n return 0;\nprintf:\n printf(\"%d\\n\", i);\n goto puts;\n}\n</code></pre>\n\n<p>This optimization was not done with <code>-O0</code>.</p>\n\n<p>But good luck on writing an example that runs faster with <code>__builtin_expect</code> than without, <a href=\"https://stackoverflow.com/a/1851905/895245\">CPUs are really smart these days</a>. My naive attempts <a href=\"https://github.com/cirosantilli/assembly-cheat/tree/ba3b76cd4530268d4c34e29c354d399c0d8552fc/compiler-generated/gcc/interactive\" rel=\"noreferrer\">are here</a>.</p>\n\n<p><strong>C++20 <code>[[likely]]</code> and <code>[[unlikely]]</code></strong></p>\n\n<p>C++20 has standardized those C++ built-ins: <a href=\"https://stackoverflow.com/questions/51797959/how-to-use-c20s-likely-unlikely-attribute-in-if-else-statement\">How to use C++20&#39;s likely/unlikely attribute in if-else statement</a> They will likely (a pun!) do the same thing.</p>\n" }, { "answer_id": 40765708, "author": "Ashish Maurya", "author_id": 3263654, "author_profile": "https://Stackoverflow.com/users/3263654", "pm_score": 3, "selected": false, "text": "<pre><code>long __builtin_expect(long EXP, long C);\n</code></pre>\n\n<p>This construct tells the compiler that the expression EXP\nmost likely will have the value C. The return value is EXP.\n<strong>__builtin_expect</strong> is meant to be used in an conditional\nexpression. In almost all cases will it be used in the\ncontext of boolean expressions in which case it is much\nmore convenient to define two helper macros:</p>\n\n<pre><code>#define unlikely(expr) __builtin_expect(!!(expr), 0)\n#define likely(expr) __builtin_expect(!!(expr), 1)\n</code></pre>\n\n<p>These macros can then be used as in</p>\n\n<pre><code>if (likely(a &gt; 1))\n</code></pre>\n\n<p>Reference: <a href=\"https://www.akkadia.org/drepper/cpumemory.pdf\" rel=\"noreferrer\">https://www.akkadia.org/drepper/cpumemory.pdf</a></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9232/" ]
I've been digging through some parts of the Linux kernel, and found calls like this: ``` if (unlikely(fd < 0)) { /* Do something */ } ``` or ``` if (likely(!err)) { /* Do something */ } ``` I've found the definition of them: ``` #define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) ``` I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).
They are hint to the compiler to emit instructions that will cause branch prediction to favour the "likely" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance. Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate.
109,717
<p>In C#, if you have multiple constructors, you can do something like this:</p> <pre><code>public MyClass(Guid inputId, string inputName){ // do something } public MyClass(Guid inputId): this(inputId, "foo") {} </code></pre> <p>The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic needed? Say I want this constructor:</p> <pre><code>public MyClass(MyOtherClass inputObject) { Guid inputId = inputObject.ID; MyThirdClass mc = inputObject.CreateHelper(); string inputText = mc.Text; mc.Dispose(); // Need to call the main Constructor now with inputId and inputText } </code></pre> <p>The caveat here is that I need to create an object that <strong>has</strong> to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection)</p> <p>However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one?</p> <p>Or is it possible to use</p> <pre><code>public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.CreateHelper().Text) {} </code></pre> <p>Would this automatically Dispose the generated Object from CreateHelper()?</p> <p><strong>Edit:</strong> Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0...). I do control my own class though, and since I've just started writing it, I have no problem refactoring the constructors if there is a good approach.</p>
[ { "answer_id": 109728, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>The object would only be automatically disposed when garbage collection runs. If you want the dispose to run as soon as it went out of scope, you should use a <code>using</code> block:</p>\n\n<pre><code>using (MyThirdClass mc = inputObject.CreateHelper())\n{\n // do something with mc\n}\n</code></pre>\n\n<p>This is really more of an issue with style and not really central to the question you had.</p>\n" }, { "answer_id": 109729, "author": "Stefan Rusek", "author_id": 19704, "author_profile": "https://Stackoverflow.com/users/19704", "pm_score": 5, "selected": true, "text": "<p>The most common pattern used to solve this problem is to have an Initialize() method that your constructors call, but in the example you just gave, adding a static method that you called like the code below, would do the trick.</p>\n\n<pre><code>public MyClass(MyOtherClass inputObject): this(inputObject.ID, GetHelperText(inputObject) {}\n\nprivate static string GetHelperText(MyOtherClass o)\n{\n using (var helper = o.CreateHelper())\n return helper.Text;\n}\n</code></pre>\n" }, { "answer_id": 109737, "author": "Nathan", "author_id": 541, "author_profile": "https://Stackoverflow.com/users/541", "pm_score": 2, "selected": false, "text": "<p>I don't see any reason to believe that creating an object in the constructor will automatically dispose the object. Yes, your object will immediately go out of scope and be available for garbage collection, but that is certainly not the same as being disposed.</p>\n\n<p>There really isn't a great way to do exactly what you want to do, but the whole thing feels like it could benefit from some refactoring. That is usually the case in my own code when I find myself trying to bend over backwards to create a constructor overload.</p>\n\n<p>If you have control over MyOtherClass, why not simplify the access to that text property by adding a getter method that handles the dispose:</p>\n\n<pre><code>public class MyOtherClass\n{\n //...\n public string GetText()\n {\n using (var h = CreateHelper())\n return h.Text;\n }\n}\n</code></pre>\n\n<p>if you don't control MyOtherClass you could use an extension method</p>\n\n<pre><code>public static class MyOtherClassExtensions\n{\n public static string GetText(this MyOtherClass parent)\n {\n using(var helper = parent.CreateHelper())\n {\n return helper.Text;\n }\n }\n}\n</code></pre>\n\n<p>Then, of course, in your constructor you can safely call</p>\n\n<pre><code>public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.GetText()) {}\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
In C#, if you have multiple constructors, you can do something like this: ``` public MyClass(Guid inputId, string inputName){ // do something } public MyClass(Guid inputId): this(inputId, "foo") {} ``` The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic needed? Say I want this constructor: ``` public MyClass(MyOtherClass inputObject) { Guid inputId = inputObject.ID; MyThirdClass mc = inputObject.CreateHelper(); string inputText = mc.Text; mc.Dispose(); // Need to call the main Constructor now with inputId and inputText } ``` The caveat here is that I need to create an object that **has** to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection) However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one? Or is it possible to use ``` public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.CreateHelper().Text) {} ``` Would this automatically Dispose the generated Object from CreateHelper()? **Edit:** Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0...). I do control my own class though, and since I've just started writing it, I have no problem refactoring the constructors if there is a good approach.
The most common pattern used to solve this problem is to have an Initialize() method that your constructors call, but in the example you just gave, adding a static method that you called like the code below, would do the trick. ``` public MyClass(MyOtherClass inputObject): this(inputObject.ID, GetHelperText(inputObject) {} private static string GetHelperText(MyOtherClass o) { using (var helper = o.CreateHelper()) return helper.Text; } ```
109,759
<p>I've just switched an application to use ar_mailer and when I run ar_sendmail (after a long pause) I get the following error:</p> <pre><code>Unhandled exception 530 5.7.0 Must issue a STARTTLS command first. h7sm16260325nfh.4 </code></pre> <p>I am using Gmail SMTP to send the emails and I haven't changed any of the ActionMailer::Base.smtp_settings just installed ar_mailer.</p> <p>Versions: </p> <p>Rails: 2.1, ar_mailer: 1.3.1</p>
[ { "answer_id": 109763, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "<p>What version of ar_mailer are you using? A gmail specific bug was fixed in 1.3.1, as shown here:</p>\n\n<p><a href=\"http://rubyforge.org/forum/forum.php?forum_id=16364\" rel=\"nofollow noreferrer\">http://rubyforge.org/forum/forum.php?forum_id=16364</a></p>\n" }, { "answer_id": 109795, "author": "DEfusion", "author_id": 6432, "author_profile": "https://Stackoverflow.com/users/6432", "pm_score": 2, "selected": true, "text": "<p>Did some digging in the lib and it seems that if you want to use TLS (as you do with Gmail) then it adds a new option to the ActionMailer::Base.smtp_settings of :tls (default of which is false) which you should set to true.</p>\n\n<p>The only thing the installation instructions mention regarding TLS is to remove any other smtp_tls files, but the one I had didn't require the tls option to work.</p>\n" }, { "answer_id": 985034, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Maybe you use the Ruby version 1.8.7 </p>\n\n<p>You don't need the <code>smtp_tls</code> before.</p>\n\n<p>You just need add the <code>enable_startls_auto</code> option:</p>\n\n<pre><code>ActionMailer::Base.smtp_settings = {\n :enable_starttls_auto =&gt; true,\n ...\n ...\n}\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
I've just switched an application to use ar\_mailer and when I run ar\_sendmail (after a long pause) I get the following error: ``` Unhandled exception 530 5.7.0 Must issue a STARTTLS command first. h7sm16260325nfh.4 ``` I am using Gmail SMTP to send the emails and I haven't changed any of the ActionMailer::Base.smtp\_settings just installed ar\_mailer. Versions: Rails: 2.1, ar\_mailer: 1.3.1
Did some digging in the lib and it seems that if you want to use TLS (as you do with Gmail) then it adds a new option to the ActionMailer::Base.smtp\_settings of :tls (default of which is false) which you should set to true. The only thing the installation instructions mention regarding TLS is to remove any other smtp\_tls files, but the one I had didn't require the tls option to work.
109,761
<p>I have the following config in my lighttpd.conf:</p> <pre><code>$HTTP["host"] == "trac.domain.tld" { server.document-root = "/usr/home/daniels/trac/htdocs/" fastcgi.server = ( "/trac" =&gt; ( "trac" =&gt; ( "socket" =&gt; "/tmp/trac-fastcgi.sock", "bin-path" =&gt; "/usr/home/daniels/trac/cgi-bin/trac.fcgi", "check-local" =&gt; "disable", "bin-environment" =&gt; ( "TRAC_ENV" =&gt; "/usr/home/daniels/trac" ) ) ) ) } </code></pre> <p>And it runs at trac.domain.tld/trac. How can i make it to run at trac.domain.tld/ so i will have trac.domain.tld/wiki, trac.domain.tld/timeline, etc instead of trac.domain.tld/trac/wiki, etc...</p>
[ { "answer_id": 109841, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 1, "selected": true, "text": "<p>Look for \"For top level setup: ...\" <a href=\"http://trac.lighttpd.net/trac/wiki/HowToSetupTrac\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 109842, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 1, "selected": false, "text": "<p>Just change \"/trac\" to \"/\" in fastcgi.server</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
I have the following config in my lighttpd.conf: ``` $HTTP["host"] == "trac.domain.tld" { server.document-root = "/usr/home/daniels/trac/htdocs/" fastcgi.server = ( "/trac" => ( "trac" => ( "socket" => "/tmp/trac-fastcgi.sock", "bin-path" => "/usr/home/daniels/trac/cgi-bin/trac.fcgi", "check-local" => "disable", "bin-environment" => ( "TRAC_ENV" => "/usr/home/daniels/trac" ) ) ) ) } ``` And it runs at trac.domain.tld/trac. How can i make it to run at trac.domain.tld/ so i will have trac.domain.tld/wiki, trac.domain.tld/timeline, etc instead of trac.domain.tld/trac/wiki, etc...
Look for "For top level setup: ..." [here](http://trac.lighttpd.net/trac/wiki/HowToSetupTrac).
109,769
<p>I am looking for an enhancement to JSON that will also serialize methods. I have an object that acts as a collection of objects, and would like to serialize the methods of the collection object as well. So far I've located <a href="http://www.thomasfrank.se/classier_json.html" rel="nofollow noreferrer">ClassyJSON</a>. Any thoughts?</p>
[ { "answer_id": 109785, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>Try to get away without serializing javascript code. That way lies a world of pain. Debugging will be much easier if code can only come from static files, not from a database. Instead, walk your JSON responses after you receive them and pass the appropriate data to the appropriate object constructors.</p>\n\n<p>If you absolutely must serialize them, calling toString() on a function will return its source.</p>\n" }, { "answer_id": 109786, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "<p>If you use WCF framework to develop RESTful web service, that is very easy to achieve.\nSimply create your data structure classes with your desired collection with DataContract, DataMember attributes.</p>\n\n<pre><code>[DataContract]\npublic class Foo\n{\n [DataMember]\n public string FooName {get;set;}\n [DataMember]\n public FooItem[] FooItems {get;set;}\n}\n\n\n[DataContract]\npublic class FooItem\n{\n [DataMember]\n public string Name {get;set;}\n}\n</code></pre>\n" }, { "answer_id": 109788, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 2, "selected": true, "text": "<p>I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects.</p>\n\n<p>I do believe though that <code>\"f = \"+function() {}</code> will yield you a to string version that you can eval:</p>\n\n<pre><code>var test = \"f = \" + function() { alert(\"Hello\"); };\neval(test)\n</code></pre>\n\n<p>And for good json handling, I would recommend prototype, which has great methods for serializing objects to json.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19799/" ]
I am looking for an enhancement to JSON that will also serialize methods. I have an object that acts as a collection of objects, and would like to serialize the methods of the collection object as well. So far I've located [ClassyJSON](http://www.thomasfrank.se/classier_json.html). Any thoughts?
I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects. I do believe though that `"f = "+function() {}` will yield you a to string version that you can eval: ``` var test = "f = " + function() { alert("Hello"); }; eval(test) ``` And for good json handling, I would recommend prototype, which has great methods for serializing objects to json.
109,776
<p>What's the best way to create recurring tasks?</p> <p>Should I create some special syntax and parse it, kind of similar to Cronjobs on Linux or should I much rather just use a cronjob that runs every hour to create more of those recurring tasks with no end?</p> <p>Keep in mind, that you can have endless recurring tasks and tasks with an enddate.</p>
[ { "answer_id": 109785, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>Try to get away without serializing javascript code. That way lies a world of pain. Debugging will be much easier if code can only come from static files, not from a database. Instead, walk your JSON responses after you receive them and pass the appropriate data to the appropriate object constructors.</p>\n\n<p>If you absolutely must serialize them, calling toString() on a function will return its source.</p>\n" }, { "answer_id": 109786, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "<p>If you use WCF framework to develop RESTful web service, that is very easy to achieve.\nSimply create your data structure classes with your desired collection with DataContract, DataMember attributes.</p>\n\n<pre><code>[DataContract]\npublic class Foo\n{\n [DataMember]\n public string FooName {get;set;}\n [DataMember]\n public FooItem[] FooItems {get;set;}\n}\n\n\n[DataContract]\npublic class FooItem\n{\n [DataMember]\n public string Name {get;set;}\n}\n</code></pre>\n" }, { "answer_id": 109788, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 2, "selected": true, "text": "<p>I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects.</p>\n\n<p>I do believe though that <code>\"f = \"+function() {}</code> will yield you a to string version that you can eval:</p>\n\n<pre><code>var test = \"f = \" + function() { alert(\"Hello\"); };\neval(test)\n</code></pre>\n\n<p>And for good json handling, I would recommend prototype, which has great methods for serializing objects to json.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9535/" ]
What's the best way to create recurring tasks? Should I create some special syntax and parse it, kind of similar to Cronjobs on Linux or should I much rather just use a cronjob that runs every hour to create more of those recurring tasks with no end? Keep in mind, that you can have endless recurring tasks and tasks with an enddate.
I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects. I do believe though that `"f = "+function() {}` will yield you a to string version that you can eval: ``` var test = "f = " + function() { alert("Hello"); }; eval(test) ``` And for good json handling, I would recommend prototype, which has great methods for serializing objects to json.
109,781
<p>What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes?</p> <p>These objects are stored in ActiveRecord so using AR's methods would be fine too. </p>
[ { "answer_id": 109794, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 3, "selected": false, "text": "<p>I had originally suggested using the <code>select</code> method on Array. To wit:</p>\n\n<p><code>[1, 2, 3, 4, 5, 6, 7].select{|e| e%2 == 0}</code>\ngives us <code>[2,4,6]</code> back.</p>\n\n<p>But if you want the first such object, use <code>detect</code>.</p>\n\n<p><code>[1, 2, 3, 4, 5, 6, 7].detect{|e| e&gt;3}</code> gives us <code>4</code>.</p>\n\n<p>I'm not sure what you're going for here, though.</p>\n" }, { "answer_id": 109828, "author": "Drew Olson", "author_id": 9434, "author_profile": "https://Stackoverflow.com/users/9434", "pm_score": 2, "selected": false, "text": "<p>If I understand your question correctly, I've tackled this problem using the quasi-hacky approach of comparing the Marshaled objects to determine if any attributes vary. The inject at the end of the following code would be an example:</p>\n\n<pre><code>class Foo\n attr_accessor :foo, :bar, :baz\n\n def initialize(foo,bar,baz)\n @foo = foo\n @bar = bar\n @baz = baz\n end\nend\n\nobjs = [Foo.new(1,2,3),Foo.new(1,2,3),Foo.new(2,3,4)]\n\n# find objects that are uniq with respect to attributes\nobjs.inject([]) do |uniqs,obj|\n if uniqs.all? { |e| Marshal.dump(e) != Marshal.dump(obj) }\n uniqs &lt;&lt; obj\n end\n uniqs\nend\n</code></pre>\n" }, { "answer_id": 109911, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 0, "selected": false, "text": "<p>Now if you can sort on the attribute values this can be done:</p>\n\n<pre><code>class A\n attr_accessor :val\n def initialize(v); self.val = v; end\nend\n\nobjs = [1,2,6,3,7,7,8,2,8].map{|i| A.new(i)}\n\nobjs.sort_by{|a| a.val}.inject([]) do |uniqs, a|\n uniqs &lt;&lt; a if uniqs.empty? || a.val != uniqs.last.val\n uniqs\nend\n</code></pre>\n\n<p>That's for a 1-attribute unique, but the same thing can be done w/ lexicographical sort ...</p>\n" }, { "answer_id": 109969, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 4, "selected": false, "text": "<p>Do it on the database level:</p>\n\n<pre><code>YourModel.find(:all, :group =&gt; \"status\")\n</code></pre>\n" }, { "answer_id": 109983, "author": "jmah", "author_id": 3948, "author_profile": "https://Stackoverflow.com/users/3948", "pm_score": 2, "selected": false, "text": "<p>You can use a hash, which contains only one value for each key:</p>\n\n<pre><code>Hash[*recs.map{|ar| [ar[attr],ar]}.flatten].values\n</code></pre>\n" }, { "answer_id": 113770, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 5, "selected": false, "text": "<p>Add the <code>uniq_by</code> method to Array in your project. It works by analogy with <code>sort_by</code>. So <code>uniq_by</code> is to <code>uniq</code> as <code>sort_by</code> is to <code>sort</code>. Usage:</p>\n\n<pre><code>uniq_array = my_array.uniq_by {|obj| obj.id}\n</code></pre>\n\n<p>The implementation:</p>\n\n<pre><code>class Array\n def uniq_by(&amp;blk)\n transforms = []\n self.select do |el|\n should_keep = !transforms.include?(t=blk[el])\n transforms &lt;&lt; t\n should_keep\n end\n end\nend\n</code></pre>\n\n<p>Note that it returns a new array rather than modifying your current one in place. We haven't written a <code>uniq_by!</code> method but it should be easy enough if you wanted to.</p>\n\n<p>EDIT: Tribalvibes points out that that implementation is O(n^2). Better would be something like (untested)...</p>\n\n<pre><code>class Array\n def uniq_by(&amp;blk)\n transforms = {}\n select do |el|\n t = blk[el]\n should_keep = !transforms[t]\n transforms[t] = true\n should_keep\n end\n end\nend\n</code></pre>\n" }, { "answer_id": 231549, "author": "Head", "author_id": 30951, "author_profile": "https://Stackoverflow.com/users/30951", "pm_score": 3, "selected": false, "text": "<p>I like jmah's use of a Hash to enforce uniqueness. Here's a couple more ways to skin that cat:</p>\n\n<pre><code>objs.inject({}) {|h,e| h[e.attr]=e; h}.values\n</code></pre>\n\n<p>That's a nice 1-liner, but I suspect this might be a little faster:</p>\n\n<pre><code>h = {}\nobjs.each {|e| h[e.attr]=e}\nh.values\n</code></pre>\n" }, { "answer_id": 5945378, "author": "apb", "author_id": 374873, "author_profile": "https://Stackoverflow.com/users/374873", "pm_score": 2, "selected": false, "text": "<p>Rails also has a <code>#uniq_by</code> method.</p>\n\n<p>Reference: <a href=\"https://stackoverflow.com/questions/5251871/parameterized-arrayuniq-i-e-uniq-by\">Parameterized Array#uniq (i.e., uniq_by)</a></p>\n" }, { "answer_id": 9656625, "author": "TKH", "author_id": 458244, "author_profile": "https://Stackoverflow.com/users/458244", "pm_score": 1, "selected": false, "text": "<p>I like jmah and Head's answers. But do they preserve array order? They might in later versions of ruby since there have been some hash insertion-order-preserving requirements written into the language specification, but here's a similar solution that I like to use that preserves order regardless.</p>\n\n<pre><code>h = Set.new\nobjs.select{|el| h.add?(el.attr)}\n</code></pre>\n" }, { "answer_id": 10083791, "author": "Lane", "author_id": 639040, "author_profile": "https://Stackoverflow.com/users/639040", "pm_score": 9, "selected": true, "text": "<p>Use <a href=\"http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq\" rel=\"noreferrer\"><code>Array#uniq</code></a> with a block:</p>\n\n<pre><code>@photos = @photos.uniq { |p| p.album_id }\n</code></pre>\n" }, { "answer_id": 11551341, "author": "grosser", "author_id": 110333, "author_profile": "https://Stackoverflow.com/users/110333", "pm_score": 1, "selected": false, "text": "<p>ActiveSupport implementation:</p>\n\n<pre><code>def uniq_by\n hash, array = {}, []\n each { |i| hash[yield(i)] ||= (array &lt;&lt; i) }\n array\nend\n</code></pre>\n" }, { "answer_id": 37705197, "author": "yauhenininjia", "author_id": 6128896, "author_profile": "https://Stackoverflow.com/users/6128896", "pm_score": 4, "selected": false, "text": "<p>You can use this trick to select unique by several attributes elements from array:</p>\n\n<pre><code>@photos = @photos.uniq { |p| [p.album_id, p.author_id] }\n</code></pre>\n" }, { "answer_id": 46332903, "author": "Igbanam", "author_id": 393021, "author_profile": "https://Stackoverflow.com/users/393021", "pm_score": 2, "selected": false, "text": "<p>The most elegant way I have found is a spin-off using <a href=\"http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq\" rel=\"nofollow noreferrer\"><code>Array#uniq</code></a> with a block</p>\n\n<pre><code>enumerable_collection.uniq(&amp;:property)\n</code></pre>\n\n<p>…it reads better too!</p>\n" }, { "answer_id": 58033851, "author": "7mode", "author_id": 3129011, "author_profile": "https://Stackoverflow.com/users/3129011", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq\" rel=\"noreferrer\">Array#uniq</a> with a block:</p>\n\n<pre><code>objects.uniq {|obj| obj.attribute}\n</code></pre>\n\n<p>Or a more concise approach:</p>\n\n<pre><code>objects.uniq(&amp;:attribute)\n</code></pre>\n" }, { "answer_id": 68949632, "author": "Vasanth Saminathan", "author_id": 5634603, "author_profile": "https://Stackoverflow.com/users/5634603", "pm_score": 0, "selected": false, "text": "<p>If you are not married with arrays, we can also try eliminating duplicates through sets</p>\n<pre><code>set = Set.new\nset &lt;&lt; obj1\nset &lt;&lt; obj2\nset.inspect\n</code></pre>\n<p>Note that in case of custom objects, we need to override <code>eql?</code> and <code>hash</code> methods</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes? These objects are stored in ActiveRecord so using AR's methods would be fine too.
Use [`Array#uniq`](http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq) with a block: ``` @photos = @photos.uniq { |p| p.album_id } ```
109,859
<p>I am reading a .NET book, and in one of the code examples there is a class definition with this field:</p> <pre><code>private DateTime? startdate </code></pre> <p>What does <code>DateTime?</code> mean?</p>
[ { "answer_id": 109862, "author": "Daniel Auger", "author_id": 1644, "author_profile": "https://Stackoverflow.com/users/1644", "pm_score": 5, "selected": false, "text": "<p>It's a nullable DateTime. <code>?</code> after a primitive type/structure indicates that it is the nullable version.</p>\n\n<p>DateTime is a structure that can never be null. From <a href=\"http://msdn.microsoft.com/en-us/library/ee432844.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini, or A.D. (also known as Common Era, or C.E.) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)</p>\n</blockquote>\n\n<p><code>DateTime?</code> can be null however.</p>\n" }, { "answer_id": 109870, "author": "Ted Elliott", "author_id": 16501, "author_profile": "https://Stackoverflow.com/users/16501", "pm_score": 3, "selected": false, "text": "<p>It's equivalent to Nullable&lt; DateTime>. You can append \"?\" to any primitive type or struct.</p>\n" }, { "answer_id": 109872, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 8, "selected": true, "text": "<p>Since <code>DateTime</code> is a <code>struct</code>, not a <code>class</code>, you get a <code>DateTime</code> <em>object</em>, not a <em>reference</em>, when you declare a field or variable of that type. </p>\n\n<p>And, in the same way as an <code>int</code> cannot be <code>null</code>, so this <code>DateTime</code> object can never be <code>null</code>, because it's not a reference.</p>\n\n<p>Adding the question mark turns it into a <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.80%29.aspx\" rel=\"noreferrer\"><em>nullable type</em></a>, which means that <em>either</em> it is a <code>DateTime</code> object, <em>or</em> it is <code>null</code>.</p>\n\n<p><code>DateTime?</code> is syntactic sugar for <code>Nullable&lt;DateTime&gt;</code>, where <a href=\"http://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.80%29.aspx\" rel=\"noreferrer\"><code>Nullable</code></a> is itself a <code>struct</code>.</p>\n" }, { "answer_id": 109873, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": "<p>A <strong>?</strong> as a suffix for a value type allows for null assignments that would be othwerwise impossible.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx</a></p>\n\n<blockquote>\n <p>Represents an object whose underlying\n type is a value type that can also be\n assigned a null reference.</p>\n</blockquote>\n\n<p>This means that you can write something like this:</p>\n\n<pre><code> DateTime? a = null;\n if (!a.HasValue)\n {\n a = DateTime.Now;\n if (a.HasValue)\n {\n Console.WriteLine(a.Value);\n }\n }\n</code></pre>\n\n<p><strong>DateTime?</strong> is syntatically equivalent to <strong>Nullable&lt;DateTime&gt;</strong>.</p>\n" }, { "answer_id": 109874, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 3, "selected": false, "text": "<p>it basically gives you an extra state for primitives. It can be a value, or it can be null. It can be usefull in situations where a value does not need to be assigned. So rather than using for example, datetime.min or max, you can assign it null to represent no value.</p>\n" }, { "answer_id": 30253579, "author": "Sonu Rajpoot", "author_id": 3600880, "author_profile": "https://Stackoverflow.com/users/3600880", "pm_score": 1, "selected": false, "text": "<p>As we know, DateTime is a struct means DateTime is a value type, so you get a DateTime object, not a reference because DateTime is not a class, when you declare a field or variable of that type you cannot initial with null Because value types don't accept null. In the same way as an int cannot be null. so DateTime object never be null, because it's not a reference.</p>\n\n<p>But sometimes we need nullable variable or field of value types, that time we use question mark to make them nullable type so they allow null.</p>\n\n<p><strong>For Example:-</strong></p>\n\n<p>DateTime? date = null;</p>\n\n<p>int? intvalue = null;</p>\n\n<p>In above code, variable <strong>date</strong> is an object of DateTime or it is null. Same for intvalue.</p>\n" }, { "answer_id": 59454112, "author": "PArikshit KAmat", "author_id": 10828078, "author_profile": "https://Stackoverflow.com/users/10828078", "pm_score": 0, "selected": false, "text": "<pre><code>public class ReportsMapper : CommonMapper\n{\n\n\n public DateTime? cb_Bill_From_Date { get; set; }\n\n public DateTime? cb_Bill_To_Date { get; set; }\n\n public DateTime? tff_Bill_From_Date { get; set; }\n public DateTime? tff_Bill_To_Date { get; set; }\n}\n</code></pre>\n\n<p>If you declare DateTime As Null In Procedure Then You get an error stating DateTime Object Can never be Null so you need to add ? After DateTime that will say DateTime is Nullable too. </p>\n\n<p>Hope This Help!</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148/" ]
I am reading a .NET book, and in one of the code examples there is a class definition with this field: ``` private DateTime? startdate ``` What does `DateTime?` mean?
Since `DateTime` is a `struct`, not a `class`, you get a `DateTime` *object*, not a *reference*, when you declare a field or variable of that type. And, in the same way as an `int` cannot be `null`, so this `DateTime` object can never be `null`, because it's not a reference. Adding the question mark turns it into a [*nullable type*](http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.80%29.aspx), which means that *either* it is a `DateTime` object, *or* it is `null`. `DateTime?` is syntactic sugar for `Nullable<DateTime>`, where [`Nullable`](http://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.80%29.aspx) is itself a `struct`.
109,880
<p>Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like </p> <pre><code>for my $item ( map { ... } @list ) { } </code></pre> <p>into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop? </p> <p><strong>Note:</strong> I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space. </p>
[ { "answer_id": 109899, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "<p>If I remember correctly, for/foreach do get the whole list first anyways, so a lazily evaluated list would be read completely and then it would start to iterate through the elements. Therefore, I think there's no other way than using a while loop. But I may be wrong.</p>\n\n<p>The advantage of a while loop is that you can fake the sensation of a lazily evaluated list with a code reference:</p>\n\n<pre><code>my $list = sub { return calculate_next_element };\nwhile(defined(my $element = &amp;$list)) {\n ...\n}\n</code></pre>\n\n<p>After all, I guess a tie is as close as you can get in Perl 5.</p>\n" }, { "answer_id": 109907, "author": "Fhoxh", "author_id": 14785, "author_profile": "https://Stackoverflow.com/users/14785", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://perldesignpatterns.com/?LazyEvaluation\" rel=\"nofollow noreferrer\">Use an iterator</a> or consider using <a href=\"http://search.cpan.org/dist/Tie-LazyList/\" rel=\"nofollow noreferrer\">Tie::LazyList</a> from CPAN (which is a tad dated).</p>\n" }, { "answer_id": 109908, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 3, "selected": false, "text": "<p>There is at least one special case where for and foreach have been optimized to not generate the whole list at once. And that is the range operator. So you have the option of saying:</p>\n\n<pre><code>for my $i (0..$#list) {\n my $item = some_function($list[$i]);\n ...\n}\n</code></pre>\n\n<p>and this will iterate through the array, transformed however you like, without creating a long list of values up front.</p>\n\n<p>If you wish your map statement to return variable numbers of elements, you could do this instead:</p>\n\n<pre><code>for my $i (0..$#array) {\n for my $item (some_function($array[$i])) {\n ...\n }\n}\n</code></pre>\n\n<p>If you wish more pervasive laziness than this, then your best option is to learn how to use closures to generate lazy lists. MJD's excellent book <em>Higher Order Perl</em> can walk you through those techniques. However do be warned that they will involve far larger changes to your code.</p>\n" }, { "answer_id": 109920, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 5, "selected": true, "text": "<p>As mentioned previously, for(each) is an eager loop, so it wants to evaluate the entire list before starting.</p>\n\n<p>For simplicity, I would recommend using an iterator object or closure rather than trying to have a lazily evaluated array. While you <em>can</em> use a tie to have a lazily evaluated infinite list, you can run into troubles if you ever ask (directly or indirectly, as in the foreach above) for the entire list (or even the size of the entire list).</p>\n\n<p>Without writing a full class or using any modules, you can make a simple iterator factory just by using closures:</p>\n\n<pre><code>sub make_iterator {\n my ($value, $max, $step) = @_;\n\n return sub {\n return if $value &gt; $max; # Return undef when we overflow max.\n\n my $current = $value;\n $value += $step; # Increment value for next call.\n return $current; # Return current iterator value.\n };\n}\n</code></pre>\n\n<p>And then to use it:</p>\n\n<pre><code># All the even numbers between 0 - 100.\nmy $evens = make_iterator(0, 100, 2);\n\nwhile (defined( my $x = $evens-&gt;() ) ) {\n print \"$x\\n\";\n}\n</code></pre>\n\n<p>There's also the <a href=\"http://search.cpan.org/perldoc?Tie::Array::Lazy\" rel=\"nofollow noreferrer\">Tie::Array::Lazy</a> module on the CPAN, which provides a much richer and fuller interface to lazy arrays. I've not used the module myself, so your mileage may vary.</p>\n\n<p>All the best,</p>\n\n<p>Paul</p>\n" }, { "answer_id": 111527, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "<p>[Sidenote: Be aware that each individual step along a map/grep chain is eager. If you give it a big list all at once, your problems start much sooner than at the final <code>foreach</code>.]</p>\n\n<p>What you can do to avoid a complete rewrite is to wrap your loop with an outer loop. Instead of writing this:</p>\n\n<pre><code>for my $item ( map { ... } grep { ... } map { ... } @list ) { ... }\n</code></pre>\n\n<p>… write it like this:</p>\n\n<pre><code>while ( my $input = calculcate_next_element() ) {\n for my $item ( map { ... } grep { ... } map { ... } $input ) { ... }\n}\n</code></pre>\n\n<p>This saves you from having to significantly rewrite your existing code, and as long as the list does not grow by several orders of magnitude during transformation, you get pretty nearly all the benefit that a rewrite to iterator style would offer.</p>\n" }, { "answer_id": 111640, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>If you want to make lazy lists, you'll have to write your own iterator. Once you have that, you can use something like <A href=\"http://search.cpan.org/dist/Object-Iterate\" rel=\"nofollow noreferrer\">Object::Iterate</a> which has iterator-aware versions of <code>map</code> and <code>grep</code>. Take a look at the source for that module: it's pretty simple and you'll see how to write your own iterator-aware subroutines.</p>\n\n<p>Good luck, :)</p>\n" }, { "answer_id": 113832, "author": "Corion", "author_id": 11253, "author_profile": "https://Stackoverflow.com/users/11253", "pm_score": 2, "selected": false, "text": "<p>I asked a similar question at <a href=\"http://perlmonks.org/?node_id=712235\" rel=\"nofollow noreferrer\">perlmonks.org</a>, and BrowserUk gave a really good framework <a href=\"http://perlmonks.org/?node_id=712271\" rel=\"nofollow noreferrer\">in his answer</a>. Basically, a convenient way to get lazy evaluation is to spawn threads for the computation, at least as long as you're sure you want the results, Just Not Now. If you want lazy evaluation not to reduce latency but to avoid calculations, my approach won't help because it relies on a push model, not a pull model. Possibly using <a href=\"http://search.cpan.org/perldoc?Coro\" rel=\"nofollow noreferrer\">Coro</a>outines, you can turn this approach into a (single-threaded) pull model as well.</p>\n\n<p>While pondering this problem, I also investigated tie-ing an array to the thread results to make the Perl program flow more like <code>map</code>, but so far, I like my API of introducing the <code>parallel</code> \"keyword\" (an object constructor in disguise) and then calling methods on the result. The more documented version of the code will be posted as a reply to <a href=\"http://perlmonks.org/?node_id=712235\" rel=\"nofollow noreferrer\">that thread</a> and possibly released onto CPAN as well.</p>\n" }, { "answer_id": 2136070, "author": "Eric Strom", "author_id": 189416, "author_profile": "https://Stackoverflow.com/users/189416", "pm_score": 2, "selected": false, "text": "<p>Bringing this back from the dead to mention that I just wrote the module <code>List::Gen</code> on <a href=\"http://search.cpan.org/search%3fmodule=List::Gen\" rel=\"nofollow noreferrer\">CPAN</a> which does exactly what the poster was looking for:</p>\n\n<pre><code>use List::Gen;\n\nfor my $item ( @{gen { ... } \\@list} ) {...}\n</code></pre>\n\n<p>all computation of the lists are lazy, and there are map / grep equivalents along with a few other functions.</p>\n\n<p>each of the functions returns a 'generator' which is a reference to a tied array. you can use the tied array directly, or there are a bunch of accessor methods like iterators to use.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11289/" ]
Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like ``` for my $item ( map { ... } @list ) { } ``` into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop? **Note:** I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space.
As mentioned previously, for(each) is an eager loop, so it wants to evaluate the entire list before starting. For simplicity, I would recommend using an iterator object or closure rather than trying to have a lazily evaluated array. While you *can* use a tie to have a lazily evaluated infinite list, you can run into troubles if you ever ask (directly or indirectly, as in the foreach above) for the entire list (or even the size of the entire list). Without writing a full class or using any modules, you can make a simple iterator factory just by using closures: ``` sub make_iterator { my ($value, $max, $step) = @_; return sub { return if $value > $max; # Return undef when we overflow max. my $current = $value; $value += $step; # Increment value for next call. return $current; # Return current iterator value. }; } ``` And then to use it: ``` # All the even numbers between 0 - 100. my $evens = make_iterator(0, 100, 2); while (defined( my $x = $evens->() ) ) { print "$x\n"; } ``` There's also the [Tie::Array::Lazy](http://search.cpan.org/perldoc?Tie::Array::Lazy) module on the CPAN, which provides a much richer and fuller interface to lazy arrays. I've not used the module myself, so your mileage may vary. All the best, Paul
109,916
<p>To see what file to invoke the unrar command on, one needs to determine which file is the first in the file set.</p> <p>Here are some sample file names, of which - naturally - only the first group should be matched:</p> <pre><code>yes.rar yes.part1.rar yes.part01.rar yes.part001.rar no.part2.rar no.part02.rar no.part002.rar no.part011.rar </code></pre> <p>One (limited) way to do it with PCRE compatible regexps is this:</p> <pre><code>.*(?:(?&lt;!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar) </code></pre> <p>This did not work in Ruby when I tested it at <a href="http://www.projects.aphexcreations.net/rejax/" rel="nofollow noreferrer">Rejax</a> however.</p> <p>How would you write one <strong>Ruby compatible</strong> regular expression to match only the first file in a set of RAR files?</p>
[ { "answer_id": 110120, "author": "Matthew Encinas", "author_id": 14433, "author_profile": "https://Stackoverflow.com/users/14433", "pm_score": 0, "selected": false, "text": "<p>I am no regex expert but here is my attempt</p>\n\n<pre><code>^(yes|no)\\.(rar|part0*1\\.rar)$\n</code></pre>\n\n<p>Replace \"yes|no\" with the actual file name. I matched it against your examples to see if it would only match the first set hence the \"yes|no\" in the regex.</p>\n\n<p>UPDATE: fixed as per the comment. Not sure why the user would not know the filename so i did not fix that part...</p>\n" }, { "answer_id": 110122, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 0, "selected": false, "text": "<p>Personally I wouldn't use (extended) regular expressions in this case (or at least not just one to do it all). What's wrong with coding this in, for example, a few <code>if</code>s?</p>\n" }, { "answer_id": 110169, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 3, "selected": true, "text": "<p>The short answer is that it's not possible to construct a single regex to satisfy your problem. Ruby 1.8 does not have lookaround assertions (the (?&lt;! stuff in your example regex) which is why your regex doesn't work. This leaves you with two options.</p>\n\n<p>1) Use more than one regex to do it.</p>\n\n<pre><code>def is_first_rar(filename)\n if ((filename =~ /part(\\d+)\\.rar$/) == nil)\n return (filename =~ /\\.rar$/) != nil\n else\n return $1.to_i == 1\n end\nend\n</code></pre>\n\n<p>2) Use the regex engine for ruby 1.9, <a href=\"http://www.geocities.jp/kosako3/oniguruma/\" rel=\"nofollow noreferrer\">Oniguruma</a>. It supports lookaround assertions, and you can <a href=\"http://oniguruma.rubyforge.org/\" rel=\"nofollow noreferrer\">install it as a gem for ruby 1.8</a>. After that, you can do something like this:</p>\n\n<pre><code>def is_first_rar(filename)\n reg = Oniguruma::ORegexp.new('.*(?:(?&lt;!part\\d\\d\\d|part\\d\\d|\\d)\\.rar|\\.part0*1\\.rar)')\n match = reg.match(filename)\n return match != nil\nend\n</code></pre>\n" }, { "answer_id": 2538086, "author": "Welbog", "author_id": 52443, "author_profile": "https://Stackoverflow.com/users/52443", "pm_score": 2, "selected": false, "text": "<p>Don't rely on the names of the files to determine which one is first. You're going to end up finding an edge case where you get the wrong file.</p>\n\n<p><a href=\"http://www.win-rar.com/index.php?id=24&amp;kb_article_id=162\" rel=\"nofollow noreferrer\">RAR's headers</a> will tell you which file is the first on in the volume, assuming they were created in a somewhat-recent version of RAR.</p>\n\n<blockquote>\n <p>HEAD_FLAGS Bit flags:<br>\n 2 bytes </p>\n \n <blockquote>\n <p>0x0100 - First volume (set only by RAR 3.0 and later)</p>\n </blockquote>\n</blockquote>\n\n<p>So open up each file and examine the RAR headers, looking specifically for the flag that indicates which file is the first volume. This will never fail, as long as the archive isn't corrupt. I have done my own tests with spanning RAR archives and their headers are correct according to the link above.</p>\n\n<p>This is a much, much safer way of determining which file is first in a set like this.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19392/" ]
To see what file to invoke the unrar command on, one needs to determine which file is the first in the file set. Here are some sample file names, of which - naturally - only the first group should be matched: ``` yes.rar yes.part1.rar yes.part01.rar yes.part001.rar no.part2.rar no.part02.rar no.part002.rar no.part011.rar ``` One (limited) way to do it with PCRE compatible regexps is this: ``` .*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar) ``` This did not work in Ruby when I tested it at [Rejax](http://www.projects.aphexcreations.net/rejax/) however. How would you write one **Ruby compatible** regular expression to match only the first file in a set of RAR files?
The short answer is that it's not possible to construct a single regex to satisfy your problem. Ruby 1.8 does not have lookaround assertions (the (?<! stuff in your example regex) which is why your regex doesn't work. This leaves you with two options. 1) Use more than one regex to do it. ``` def is_first_rar(filename) if ((filename =~ /part(\d+)\.rar$/) == nil) return (filename =~ /\.rar$/) != nil else return $1.to_i == 1 end end ``` 2) Use the regex engine for ruby 1.9, [Oniguruma](http://www.geocities.jp/kosako3/oniguruma/). It supports lookaround assertions, and you can [install it as a gem for ruby 1.8](http://oniguruma.rubyforge.org/). After that, you can do something like this: ``` def is_first_rar(filename) reg = Oniguruma::ORegexp.new('.*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar)') match = reg.match(filename) return match != nil end ```
109,934
<p>I've got a generic&lt;> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)?</p> <p>So equivalent to the sql: select *, 'bar' as Foo from items</p> <pre><code>foreach (var item in items) { var newItem = new { item, // I'd like just the properties here, not the 'item' object! Foo = "bar" }; newItems.Add(newItem); } </code></pre>
[ { "answer_id": 109967, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 0, "selected": false, "text": "<pre><code>from item in items\nwhere someConditionOnItem\nselect\n{\n propertyOne,\n propertyTwo\n};\n</code></pre>\n" }, { "answer_id": 109992, "author": "Kris", "author_id": 14439, "author_profile": "https://Stackoverflow.com/users/14439", "pm_score": 4, "selected": true, "text": "<p>There's no easy way of doing what you're suggesting, as all types in C# are strong-typed, even the anonymous ones like you're using. However it's not impossible to pull it off. To do it you would have to utilize reflection and emit your own assembly in memory, adding a new module and type that contains the specific properties you want. It's possible to obtain a list of properties from your anonymous item using:</p>\n\n<pre><code>foreach(PropertyInfo info in item.GetType().GetProperties())\n Console.WriteLine(\"{0} = {1}\", info.Name, info.GetValue(item, null));\n</code></pre>\n" }, { "answer_id": 110000, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>Shoot you wrote exactly what i was going to post. I was just getting some code ready :/</p>\n\n<p>Its a little convoluted but anyways:</p>\n\n<pre><code>ClientCollection coll = new ClientCollection();\nvar results = coll.Select(c =&gt;\n{\n Dictionary&lt;string, object&gt; objlist = new Dictionary&lt;string, object&gt;();\n foreach (PropertyInfo pi in c.GetType().GetProperties())\n {\n objlist.Add(pi.Name, pi.GetValue(c, null));\n }\n return new { someproperty = 1, propertyValues = objlist };\n});\n</code></pre>\n" }, { "answer_id": 110109, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Ask the item to give them to you.</p>\n\n<p>Reflection is one way... however, since all the properties are known at compile time, each item could have a method that helps this query get what it needs.</p>\n\n<p>Here's some example method signatures:</p>\n\n<pre><code>public XElement ToXElement()\npublic IEnumerable ToPropertyEnumerable()\npublic Dictionary&lt;string, object&gt; ToNameValuePairs()\n</code></pre>\n" }, { "answer_id": 25927626, "author": "Achal kumar", "author_id": 1007119, "author_profile": "https://Stackoverflow.com/users/1007119", "pm_score": 0, "selected": false, "text": "<p>Suppose you have a collection of Department class:</p>\n\n<pre><code> public int DepartmentId { get; set; }\n public string DepartmentName { get; set; }\n</code></pre>\n\n<p>Then use anonymous type like this:</p>\n\n<pre><code> List&lt;DepartMent&gt; depList = new List&lt;DepartMent&gt;();\n depList.Add(new DepartMent { DepartmentId = 1, DepartmentName = \"Finance\" });\n depList.Add(new DepartMent { DepartmentId = 2, DepartmentName = \"HR\" });\n depList.Add(new DepartMent { DepartmentId = 3, DepartmentName = \"IT\" });\n depList.Add(new DepartMent { DepartmentId = 4, DepartmentName = \"Admin\" });\n var result = from b in depList\n select new {Id=b.DepartmentId,Damartment=b.DepartmentName,Foo=\"bar\" };\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
I've got a generic<> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)? So equivalent to the sql: select \*, 'bar' as Foo from items ``` foreach (var item in items) { var newItem = new { item, // I'd like just the properties here, not the 'item' object! Foo = "bar" }; newItems.Add(newItem); } ```
There's no easy way of doing what you're suggesting, as all types in C# are strong-typed, even the anonymous ones like you're using. However it's not impossible to pull it off. To do it you would have to utilize reflection and emit your own assembly in memory, adding a new module and type that contains the specific properties you want. It's possible to obtain a list of properties from your anonymous item using: ``` foreach(PropertyInfo info in item.GetType().GetProperties()) Console.WriteLine("{0} = {1}", info.Name, info.GetValue(item, null)); ```
109,948
<p>just a quick question:</p> <p>I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs. I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out. Right after the line where I declare a new instance of an ArrayList: </p> <pre><code>dictionary = new ArrayList&lt;String&gt;(); </code></pre> <p>I get the following error: <b>generics are not supported in -source 1.3</b>.</p> <p>I was just wondering if anybody could offer advice as to what the problem might be. The same project compiles in Eclipse on the same machine. I'm running OSX 10.5.4, with Java 1.5.0_13. </p> <p>Thank you.</p>
[ { "answer_id": 109957, "author": "user7305", "author_id": 7305, "author_profile": "https://Stackoverflow.com/users/7305", "pm_score": 0, "selected": false, "text": "<p>Generics are introduced in Java 5, so you can't use generics with -source 1.3 option.</p>\n" }, { "answer_id": 109966, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 4, "selected": true, "text": "<p>Java support in Xcode is obsolete and unmaintained; it's the only bit of Xcode that still uses the \"old\" build system inherited from Project Builder. Even Apple suggests using Eclipse instead. For Java, both Eclipse and NetBeans work quite well on the Mac; if you want to try native Mac programming, use Objective-C and Cocoa, for which Xcode is fine.</p>\n\n<p>That said, the problem is that javac is targeting Java 1.3, which doesn't have generics. You can modify the javac reference in the Ant buildfile (build.xml) as follows:</p>\n\n<pre><code> &lt;target name=\"compile\" depends=\"init\" description=\"Compile code\"&gt;\n &lt;mkdir dir=\"${bin}\"/&gt;\n &lt;javac deprecation=\"on\" srcdir=\"${src}\" destdir=\"${bin}\"\n source=\"1.3\" target=\"1.2\"\n</code></pre>\n\n<p>Change \"source\" and \"target\" to \"1.5\".</p>\n" }, { "answer_id": 163607, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The build.xml file is placed in</p>\n\n<pre><code>/Developer/Library/XCode/Project Templates/Java/Java Tool/build.xml\n</code></pre>\n\n<p>(replace Java Tool with your own kind of project). </p>\n\n<p>If you look for <code>source=\"XX\" target=\"YY\"</code> in line 30, and change XX and YY to your preferred values, things go better, much as explained in the previous posts.</p>\n\n<p>Cheers,</p>\n\n<p>Pieter</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
just a quick question: I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs. I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out. Right after the line where I declare a new instance of an ArrayList: ``` dictionary = new ArrayList<String>(); ``` I get the following error: **generics are not supported in -source 1.3**. I was just wondering if anybody could offer advice as to what the problem might be. The same project compiles in Eclipse on the same machine. I'm running OSX 10.5.4, with Java 1.5.0\_13. Thank you.
Java support in Xcode is obsolete and unmaintained; it's the only bit of Xcode that still uses the "old" build system inherited from Project Builder. Even Apple suggests using Eclipse instead. For Java, both Eclipse and NetBeans work quite well on the Mac; if you want to try native Mac programming, use Objective-C and Cocoa, for which Xcode is fine. That said, the problem is that javac is targeting Java 1.3, which doesn't have generics. You can modify the javac reference in the Ant buildfile (build.xml) as follows: ``` <target name="compile" depends="init" description="Compile code"> <mkdir dir="${bin}"/> <javac deprecation="on" srcdir="${src}" destdir="${bin}" source="1.3" target="1.2" ``` Change "source" and "target" to "1.5".
110,078
<p>I need to store app specific configuration in rails. But it has to be:</p> <ul> <li>reachable in any file (model, view, helpers and controllers</li> <li>environment specified (or not), that means each environment can overwrite the configs specified in environment.rb</li> </ul> <p>I've tried to use environment.rb and put something like</p> <pre><code>USE_USER_APP = true </code></pre> <p>that worked to me but when trying to overwrite it in a specific environment it wont work because production.rb, for instance, seems to be inside the Rails:Initializer.run block.</p> <p>So, anyone?</p>
[ { "answer_id": 110103, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 0, "selected": false, "text": "<p>I found a good way <a href=\"http://kpumuk.info/ruby-on-rails/flexible-application-configuration-in-ruby-on-rails/\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 110105, "author": "Bill Turner", "author_id": 17773, "author_profile": "https://Stackoverflow.com/users/17773", "pm_score": 4, "selected": false, "text": "<p>Look at Configatron: <a href=\"http://github.com/markbates/configatron/tree/master\" rel=\"noreferrer\">http://github.com/markbates/configatron/tree/master</a></p>\n\n<p>I have yet to use it, but he's actively developing it now, and looks quite nice.</p>\n" }, { "answer_id": 110307, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 2, "selected": false, "text": "<p>The most basic thing to do is to set a class variable from your environment.rb. I've done this for Google Analytics. Essentially I want a different key depending on which environment I'm in so development or staging don't skew the metrics.</p>\n\n<p>This is how I did it.</p>\n\n<p>In <code>lib/analytics/google_analytics.rb</code>:</p>\n\n<pre><code>module Analytics\n class GoogleAnalytics\n @@account_id = nil\n\n cattr_accessor :account_id\n end\nend\n</code></pre>\n\n<p>And then in <code>environment.rb</code> or in <code>environments/production.rb</code> or any of the other environment files:</p>\n\n<pre><code>Analytics::GoogleAnalytics.account_id = \"xxxxxxxxx\"\n</code></pre>\n\n<p>Then anywhere you ned to reference, say the default layout with the Google Analytics JavaScript, it you just call <code>Analytics::GoogleAnalytics.account_id</code>. </p>\n" }, { "answer_id": 110834, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 3, "selected": true, "text": "<p>I was helping a friend set up <a href=\"http://kpumuk.info/ruby-on-rails/flexible-application-configuration-in-ruby-on-rails/\" rel=\"nofollow noreferrer\">the solution mentioned by Ricardo</a> yesterday. We hacked it a bit by loading the YAML file with something similar to this (going from memory here):</p>\n\n<pre><code>require 'ostruct'\nrequire 'yaml'\nrequire 'erb'\n#config = OpenStruct.new(YAML.load_file(\"#{RAILS_ROOT}/config/config.yml\"))\nconfig = OpenStruct.new(YAML.load(ERB.new(File.read(\"#{RAILS_ROOT}/config/config.yml\")).result))\nenv_config = config.send(RAILS_ENV)\nconfig.common.update(env_config) unless env_config.nil?\n::AppConfig = OpenStruct.new(config.common)\n</code></pre>\n\n<p>This allowed him to embed Ruby code in the config, like in Rhtml:</p>\n\n<pre><code>development:\n path_to_something: &lt;%= RAILS_ROOT %&gt;/config/something.yml\n</code></pre>\n" }, { "answer_id": 6753923, "author": "Joe Van Dyk", "author_id": 17076, "author_profile": "https://Stackoverflow.com/users/17076", "pm_score": 0, "selected": false, "text": "<p>Use environment variables. Heroku uses this. Remember that if you keep configuration in the codebase, anyone with access to the code has access to any secret configuration (aws api keys, gateway api keys, etc).</p>\n\n<p>daemontool's envdir is a good tool for setting configuration, I'm pretty sure that's what Heroku uses to give application their environment variables.</p>\n" }, { "answer_id": 13020931, "author": "Pikachu", "author_id": 356965, "author_profile": "https://Stackoverflow.com/users/356965", "pm_score": 0, "selected": false, "text": "<p>I have used <a href=\"https://github.com/huacnlee/rails-settings-cached\" rel=\"nofollow\">Rails Settings Cached</a>. </p>\n\n<p>It is very simple to use, keeps your configuration values cached and allows you to change them dynamically.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224/" ]
I need to store app specific configuration in rails. But it has to be: * reachable in any file (model, view, helpers and controllers * environment specified (or not), that means each environment can overwrite the configs specified in environment.rb I've tried to use environment.rb and put something like ``` USE_USER_APP = true ``` that worked to me but when trying to overwrite it in a specific environment it wont work because production.rb, for instance, seems to be inside the Rails:Initializer.run block. So, anyone?
I was helping a friend set up [the solution mentioned by Ricardo](http://kpumuk.info/ruby-on-rails/flexible-application-configuration-in-ruby-on-rails/) yesterday. We hacked it a bit by loading the YAML file with something similar to this (going from memory here): ``` require 'ostruct' require 'yaml' require 'erb' #config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml")) config = OpenStruct.new(YAML.load(ERB.new(File.read("#{RAILS_ROOT}/config/config.yml")).result)) env_config = config.send(RAILS_ENV) config.common.update(env_config) unless env_config.nil? ::AppConfig = OpenStruct.new(config.common) ``` This allowed him to embed Ruby code in the config, like in Rhtml: ``` development: path_to_something: <%= RAILS_ROOT %>/config/something.yml ```
110,083
<pre><code>String s = ""; for(i=0;i&lt;....){ s = some Assignment; } </code></pre> <p>or</p> <pre><code>for(i=0;i&lt;..){ String s = some Assignment; } </code></pre> <p>I don't need to use 's' outside the loop ever again. The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself.</p> <p>EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through.</p> <p>Also, the question isn't because I'm worried about memory management. Just want to know which is better.</p>
[ { "answer_id": 110090, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 5, "selected": false, "text": "<p>In <em>theory</em>, it's a waste of resources to declare the string inside the loop. \nIn <em>practice</em>, however, both of the snippets you presented will compile down to the same code (declaration outside the loop). </p>\n\n<p>So, if your compiler does any amount of optimization, there's no difference.</p>\n" }, { "answer_id": 110094, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>In general I would choose the second one, because the scope of the 's' variable is limited to the loop. Benefits:</p>\n\n<ul>\n<li>This is better for the programmer because you don't have to worry about 's' being used again somewhere later in the function</li>\n<li>This is better for the compiler because the scope of the variable is smaller, and so it can potentially do more analysis and optimisation</li>\n<li>This is better for future readers because they won't wonder why the 's' variable is declared outside the loop if it's never used later</li>\n</ul>\n" }, { "answer_id": 110099, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>To add on a bit to @<a href=\"https://stackoverflow.com/questions/110083/which-of-these-loops-is-better-code-in-terms-of-performance-garbage-collection#110090\">Esteban Araya's answer</a>, they will both require the creation of a new string each time through the loop (as the return value of the <code>some Assignment</code> expression). Those strings need to be garbage collected either way.</p>\n" }, { "answer_id": 110322, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 1, "selected": false, "text": "<p>It seems to me that we need more specification of the problem.</p>\n\n<p>The </p>\n\n<pre><code>s = some Assignment;\n</code></pre>\n\n<p>is not specified as to what kind of assignment this is. If the assignment is </p>\n\n<pre><code>s = \"\" + i + \"\";\n</code></pre>\n\n<p>then a new sting needs to be allocated.</p>\n\n<p>but if it is </p>\n\n<pre><code>s = some Constant;\n</code></pre>\n\n<p>s will merely point to the constants memory location, and thus the first version would be more memory efficient.</p>\n\n<p>Seems i little silly to worry about to much optimization of a for loop for an interpreted lang IMHO.</p>\n" }, { "answer_id": 110389, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 8, "selected": true, "text": "<h3>Limited Scope is Best</h3>\n\n<p>Use your second option:</p>\n\n<pre><code>for ( ... ) {\n String s = ...;\n}\n</code></pre>\n\n<h3>Scope Doesn't Affect Performance</h3>\n\n<p>If you disassemble code the compiled from each (with the JDK's <code>javap</code> tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that <a href=\"https://stackoverflow.com/questions/110083/which-of-these-loops-is-better-code-in-terms-of-performance-garbage-collection#110095\">Brian R. Bondy's</a> \"Option #3\" is identical to Option #1. Nothing extra is added or removed from the stack when using the tighter scope, and same data are used on the stack in both cases.</p>\n\n<h3>Avoid Premature Initialization</h3>\n\n<p>The only difference between the two cases is that, in the first example, the variable <code>s</code> is unnecessarily initialized. This is a separate issue from the location of the variable declaration. This adds two wasted instructions (to load a string constant and store it in a stack frame slot). A good static analysis tool will warn you that you are never reading the value you assign to <code>s</code>, and a good JIT compiler will probably elide it at runtime. </p>\n\n<p>You could fix this simply by using an empty declaration (i.e., <code>String s;</code>), but this is considered bad practice and has another side-effect discussed below. </p>\n\n<p>Often a bogus value like <code>null</code> is assigned to a variable simply to hush a compiler error that a variable is read without being initialized. This error can be taken as a hint that the variable scope is too large, and that it is being declared before it is needed to receive a valid value. Empty declarations force you to consider every code path; don't ignore this valuable warning by assigning a bogus value.</p>\n\n<h3>Conserve Stack Slots</h3>\n\n<p>As mentioned, while the JVM instructions are the same in both cases, there is a subtle side-effect that makes it best, at a JVM level, to use the most limited scope possible. This is visible in the \"local variable table\" for the method. Consider what happens if you have multiple loops, with the variables declared in unnecessarily large scope:</p>\n\n<pre><code>void x(String[] strings, Integer[] integers) {\n String s;\n for (int i = 0; i &lt; strings.length; ++i) {\n s = strings[0];\n ...\n }\n Integer n;\n for (int i = 0; i &lt; integers.length; ++i) {\n n = integers[i];\n ...\n }\n}\n</code></pre>\n\n<p>The variables <code>s</code> and <code>n</code> could be declared inside their respective loops, but since they are not, the compiler uses two \"slots\" in the stack frame. If they were declared inside the loop, the compiler can reuse the same slot, making the stack frame smaller.</p>\n\n<h3>What Really Matters</h3>\n\n<p>However, most of these issues are immaterial. A good JIT compiler will see that it is not possible to read the initial value you are wastefully assigning, and optimize the assignment away. Saving a slot here or there isn't going to make or break your application.</p>\n\n<p>The important thing is to make your code readable and easy to maintain, and in that respect, using a limited scope is clearly better. The smaller scope a variable has, the easier it is to comprehend how it is used and what impact any changes to the code will have.</p>\n" }, { "answer_id": 111075, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 3, "selected": false, "text": "<p>If you want to speed up for loops, I prefer declaring a max variable next to the counter so that no repeated lookups for the condidtion are needed:</p>\n\n<p>instead of</p>\n\n<pre><code>for (int i = 0; i &lt; array.length; i++) {\n Object next = array[i];\n}\n</code></pre>\n\n<p>I prefer</p>\n\n<pre><code>for (int i = 0, max = array.lenth; i &lt; max; i++) {\n Object next = array[i];\n}\n</code></pre>\n\n<p>Any other things that should be considered have already been mentioned, so just my two cents (see ericksons post)</p>\n\n<p>Greetz, GHad</p>\n" }, { "answer_id": 745206, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 2, "selected": false, "text": "<p>I know this is an old question, but I thought I'd add a bit that is <em>slightly</em> related.</p>\n\n<p>I've noticed while browsing the Java source code that some methods, like String.contentEquals (duplicated below) makes redundant local variables that are merely copies of class variables. I believe that there was a comment somewhere, that implied that accessing local variables is faster than accessing class variables.</p>\n\n<p>In this case \"v1\" and \"v2\" are seemingly unnecessary and could be eliminated to simplify the code, but were added to improve performance.</p>\n\n<pre><code>public boolean contentEquals(StringBuffer sb) {\n synchronized(sb) {\n if (count != sb.length())\n return false;\n char v1[] = value;\n char v2[] = sb.getValue();\n int i = offset;\n int j = 0;\n int n = count;\n while (n-- != 0) {\n if (v1[i++] != v2[j++])\n return false;\n }\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 17934262, "author": "Petro", "author_id": 2163927, "author_profile": "https://Stackoverflow.com/users/2163927", "pm_score": 1, "selected": false, "text": "<p>When I'm using multiple threads (50+) then i found this to be a very effective way of handling ghost thread issues with not being able to close a process correctly ....if I'm wrong, please let me know why I'm wrong:</p>\n\n<pre><code>Process one;\nBufferedInputStream two;\ntry{\none = Runtime.getRuntime().exec(command);\ntwo = new BufferedInputStream(one.getInputStream());\n}\n}catch(e){\ne.printstacktrace\n}\nfinally{\n//null to ensure they are erased\none = null;\ntwo = null;\n//nudge the gc\nSystem.gc();\n}\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16485/" ]
``` String s = ""; for(i=0;i<....){ s = some Assignment; } ``` or ``` for(i=0;i<..){ String s = some Assignment; } ``` I don't need to use 's' outside the loop ever again. The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself. EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through. Also, the question isn't because I'm worried about memory management. Just want to know which is better.
### Limited Scope is Best Use your second option: ``` for ( ... ) { String s = ...; } ``` ### Scope Doesn't Affect Performance If you disassemble code the compiled from each (with the JDK's `javap` tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that [Brian R. Bondy's](https://stackoverflow.com/questions/110083/which-of-these-loops-is-better-code-in-terms-of-performance-garbage-collection#110095) "Option #3" is identical to Option #1. Nothing extra is added or removed from the stack when using the tighter scope, and same data are used on the stack in both cases. ### Avoid Premature Initialization The only difference between the two cases is that, in the first example, the variable `s` is unnecessarily initialized. This is a separate issue from the location of the variable declaration. This adds two wasted instructions (to load a string constant and store it in a stack frame slot). A good static analysis tool will warn you that you are never reading the value you assign to `s`, and a good JIT compiler will probably elide it at runtime. You could fix this simply by using an empty declaration (i.e., `String s;`), but this is considered bad practice and has another side-effect discussed below. Often a bogus value like `null` is assigned to a variable simply to hush a compiler error that a variable is read without being initialized. This error can be taken as a hint that the variable scope is too large, and that it is being declared before it is needed to receive a valid value. Empty declarations force you to consider every code path; don't ignore this valuable warning by assigning a bogus value. ### Conserve Stack Slots As mentioned, while the JVM instructions are the same in both cases, there is a subtle side-effect that makes it best, at a JVM level, to use the most limited scope possible. This is visible in the "local variable table" for the method. Consider what happens if you have multiple loops, with the variables declared in unnecessarily large scope: ``` void x(String[] strings, Integer[] integers) { String s; for (int i = 0; i < strings.length; ++i) { s = strings[0]; ... } Integer n; for (int i = 0; i < integers.length; ++i) { n = integers[i]; ... } } ``` The variables `s` and `n` could be declared inside their respective loops, but since they are not, the compiler uses two "slots" in the stack frame. If they were declared inside the loop, the compiler can reuse the same slot, making the stack frame smaller. ### What Really Matters However, most of these issues are immaterial. A good JIT compiler will see that it is not possible to read the initial value you are wastefully assigning, and optimize the assignment away. Saving a slot here or there isn't going to make or break your application. The important thing is to make your code readable and easy to maintain, and in that respect, using a limited scope is clearly better. The smaller scope a variable has, the easier it is to comprehend how it is used and what impact any changes to the code will have.
110,121
<p>Everything inherits from object. It's the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie.</p> <pre><code>object me = new Person(); </code></pre> <p>Therefore, following this through to its logical conclusion, a group of People would also be a group of objects:</p> <pre><code>List&lt;Person&gt; people = new List&lt;Person&gt;(); people.Add(me); people.Add(you); List&lt;object&gt; things = people; // Ooops. </code></pre> <p>Except, that won't work, the people who designed .NET either overlooked this, or there's a reason, and I'm not sure which. At least once I have run into a situation where this would have been useful, but I had to end up using a nasty hack (subclassing List just to implement a cast operator). </p> <p>The question is this: is there a reason for this behaviour? Is there a simpler solution to get the desired behaviour?</p> <p>For the record, I believe the situation that I wanted this sort of behaviour was a generic printing function that displayed lists of objects by calling ToString() and formatting the strings nicely.</p>
[ { "answer_id": 110136, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>you can use linq to cast it:</p>\n\n<pre><code>IEnumerable&lt;Person&gt; oldList = someIenumarable;\nIEnumerable&lt;object&gt; newList = oldlist.Cast&lt;object&gt;()\n</code></pre>\n" }, { "answer_id": 110137, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 4, "selected": true, "text": "<p>OK, everyone who has used generics in .net must have run into this at one point or another.</p>\n<p>Yes, intuitively it should work. No, in the current version of the C# compiler it doesn't.</p>\n<p>Eric Lippert has a really good explanation of this issue (it's in eleven parts or something and will bend you mind in places, but it's well worth the read). See <a href=\"http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h3>edit:</h3>\n<p>dug out another relevant link, this one discusses how java handles this. See <a href=\"http://etymon.blogspot.com/2007/02/java-generics-and-covariance-and.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 110138, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>With linq extension methods you can do</p>\n\n<pre><code>IEnumerable&lt;object&gt; things = people.Cast&lt;object&gt;();\nList&lt;object&gt; things = people.Cast&lt;object&gt;().ToList();\n</code></pre>\n\n<p>Otherwise since you are strongly typing the list the implicit conversion isn't allowed.</p>\n" }, { "answer_id": 110155, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 2, "selected": false, "text": "<p>At first glance, this does not make intuitive sense. But it does. Look at this code:</p>\n\n<pre><code>List&lt;Person&gt; people = new List&lt;Person&gt;();\nList&lt;object&gt; things = people; // this is not allowed\n// ...\nMouse gerald = new Mouse();\nthings.add(gerald);\n</code></pre>\n\n<p>Now we suddenly have a <code>List</code> of <code>Person</code> objects... with a <code>Mouse</code> inside it!</p>\n\n<p>This explains why the assignment of an object of type <code>A&lt;T&gt;</code> to a variable of type <code>A&lt;S&gt;</code> is not allowed, even if <code>S</code> is a supertype of <code>T</code>.</p>\n" }, { "answer_id": 110159, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 2, "selected": false, "text": "<p>The linq workaround is a good one. Another workaround, since you are using type object, is to pass the list as IEnumerable (not the generic version).</p>\n\n<p><strong>Edit</strong>: C# 4 (currently beta) supports a covariant type parameter in IEnumerable. While you won't be able to assign directly to a List&lt;object&gt;, you can pass your list to a method expecting an IEnumerable&lt;object&gt;.</p>\n" }, { "answer_id": 936354, "author": "jrista", "author_id": 111554, "author_profile": "https://Stackoverflow.com/users/111554", "pm_score": 2, "selected": false, "text": "<p>While what your trying to does indeed flow logically, its actually a feature that many languages don't natively support. This is whats called co/contra variance, which has to do with when and how objects can be implicitly cast from one thing to nother by a compiler. Thankfully, C# 4.0 will bring covariance and contravariance to the C# arena, and such implicit casts like this should be possible.</p>\n\n<p>For a detailed explanation of this, the following Channel9 video should be helpful:</p>\n\n<p><a href=\"http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/\" rel=\"nofollow noreferrer\">http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/</a></p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
Everything inherits from object. It's the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie. ``` object me = new Person(); ``` Therefore, following this through to its logical conclusion, a group of People would also be a group of objects: ``` List<Person> people = new List<Person>(); people.Add(me); people.Add(you); List<object> things = people; // Ooops. ``` Except, that won't work, the people who designed .NET either overlooked this, or there's a reason, and I'm not sure which. At least once I have run into a situation where this would have been useful, but I had to end up using a nasty hack (subclassing List just to implement a cast operator). The question is this: is there a reason for this behaviour? Is there a simpler solution to get the desired behaviour? For the record, I believe the situation that I wanted this sort of behaviour was a generic printing function that displayed lists of objects by calling ToString() and formatting the strings nicely.
OK, everyone who has used generics in .net must have run into this at one point or another. Yes, intuitively it should work. No, in the current version of the C# compiler it doesn't. Eric Lippert has a really good explanation of this issue (it's in eleven parts or something and will bend you mind in places, but it's well worth the read). See [here](http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx). ### edit: dug out another relevant link, this one discusses how java handles this. See [here](http://etymon.blogspot.com/2007/02/java-generics-and-covariance-and.html)
110,123
<p>I'm using ASP.NET Web Forms for blog style comments. </p> <p>Edit 1: This looks way more complicated then I first thought. How do you filter the src?<br> I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that?</p>
[ { "answer_id": 110146, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "<p>Use an XML parser to validate your input, and drop or encode all elements, and attributes, that you do not want to allow. In this case, delete or encode all tags except the <code>&lt;img&gt;<code> tag, and all attributes from that except <code>src</code>, alt</code> and title</code>.</p>\n" }, { "answer_id": 110233, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>If IMG is the only thing you'd allow, I'd suggest you use a simple square-bracket syntax to allow it. This would eliminate the need for a parser and reduce a load of other dangerous edge cases with the parser as well. Say, something like:</p>\n\n<pre><code>Look at this! [http://a.b.c/m.jpg]\n</code></pre>\n\n<p>Which would get converted to</p>\n\n<pre><code>Look at this! &lt;img src=\"http://a.b.c/m.jpg\" /&gt;\n</code></pre>\n\n<p>You should filter the SRC address so that no malicious things get passed in the SRC part too. Like maybe</p>\n\n<pre><code>Look at this! [javascript:alert('pwned!')]\n</code></pre>\n" }, { "answer_id": 110260, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 0, "selected": false, "text": "<p>If you end up going with a non-HTML format (which makes things easier b/c you can literally escape all HTML), use a standard syntax like <a href=\"http://daringfireball.net/projects/markdown/\" rel=\"nofollow noreferrer\">markdown</a>. The <a href=\"http://daringfireball.net/projects/markdown/syntax#img\" rel=\"nofollow noreferrer\">markdown image syntax</a> is <code>![alt text](/path/to/image.jpg)</code></p>\n\n<p>There are others also, like <a href=\"http://www.textism.com/tools/textile/\" rel=\"nofollow noreferrer\">Textile</a>. Its syntax for images is <code>!imageurl!</code></p>\n" }, { "answer_id": 110373, "author": "AviD", "author_id": 10080, "author_profile": "https://Stackoverflow.com/users/10080", "pm_score": 0, "selected": false, "text": "<p>@chakrit suggested using a custom syntax, e.g. bracketed URLs - This might very well be the best solution. You <strong>DEFINITELY</strong> dont want to start messing with parsing etc.<br>\nJust make sure you properly encode the entire comment (according to the context - see my answer on this here <a href=\"https://stackoverflow.com/questions/53728/will-html-encoding-prevent-all-kinds-of-xss-attacks#70222\">Will HTML Encoding prevent all kinds of XSS attacks?</a>)<br>\n(btw I just discovered a good example of custom syntax right there... ;-) )</p>\n\n<p>As also mentioned, restrict the file extension to jpg/gif/etc - even though this can be bypassed, and also restrict the protocol (e.g. http://).</p>\n\n<p>Another issue to be considered besides XSS - is CSRF (<a href=\"http://www.owasp.org/index.php/Cross-Site_Request_Forgery\" rel=\"nofollow noreferrer\">http://www.owasp.org/index.php/Cross-Site_Request_Forgery</a>). If you're not familiar with this security issue, it basically allows the attacker to force my browser to submit a valid authenticated request to your application, for instance to transfer money or to change my password. If this is hosted on your site, he can anonymously attack any vulnerable application - <em>including yours</em>. (Note that even if other applications are vulnerable, its not your fault they get attacked, but you still dont want to be the exploit host or the source of the attack...). As far as your own site goes, it's that much easier for the attacker to change the users password on your site, for instance.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
I'm using ASP.NET Web Forms for blog style comments. Edit 1: This looks way more complicated then I first thought. How do you filter the src? I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that?
If IMG is the only thing you'd allow, I'd suggest you use a simple square-bracket syntax to allow it. This would eliminate the need for a parser and reduce a load of other dangerous edge cases with the parser as well. Say, something like: ``` Look at this! [http://a.b.c/m.jpg] ``` Which would get converted to ``` Look at this! <img src="http://a.b.c/m.jpg" /> ``` You should filter the SRC address so that no malicious things get passed in the SRC part too. Like maybe ``` Look at this! [javascript:alert('pwned!')] ```
110,157
<p>This is one of the possible ways I come out:</p> <pre><code>struct RetrieveKey { template &lt;typename T&gt; typename T::first_type operator()(T keyValuePair) const { return keyValuePair.first; } }; map&lt;int, int&gt; m; vector&lt;int&gt; keys; // Retrieve all keys transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey()); // Dump all keys copy(keys.begin(), keys.end(), ostream_iterator&lt;int&gt;(cout, &quot;\n&quot;)); </code></pre> <p>Of course, we can also retrieve all values from the map by defining another functor <strong>RetrieveValues</strong>.</p> <p>Is there any other way to achieve this easily? (I'm always wondering why <code>std::map</code> does not include a member function for us to do so.)</p>
[ { "answer_id": 110170, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<p>The SGI STL has an extension called <a href=\"http://www.sgi.com/tech/stl/select1st.html\" rel=\"noreferrer\"><code>select1st</code></a>. Too bad it's not in standard STL!</p>\n" }, { "answer_id": 110211, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "<p>Your solution is fine but you can use an iterator to do it:</p>\n\n<pre><code>std::map&lt;int, int&gt; m;\nm.insert(std::pair&lt;int, int&gt;(3, 4));\nm.insert(std::pair&lt;int, int&gt;(5, 6));\nfor(std::map&lt;int, int&gt;::const_iterator it = m.begin(); it != m.end(); it++)\n{\n int key = it-&gt;first;\n int value = it-&gt;second;\n //Do something\n}\n</code></pre>\n" }, { "answer_id": 110221, "author": "Marcelo Cantos", "author_id": 9990, "author_profile": "https://Stackoverflow.com/users/9990", "pm_score": 3, "selected": false, "text": "<p>Also, if you have Boost, use transform_iterator to avoid making a temporary copy of the keys.</p>\n" }, { "answer_id": 110228, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 3, "selected": false, "text": "<p>You can use the versatile boost::transform_iterator. The transform_iterator allows you to transform the iterated values, for example in our case when you want to deal only with the keys, not the values. See <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html#example\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html#example</a></p>\n" }, { "answer_id": 110255, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 9, "selected": true, "text": "<p>While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.</p>\n<p>I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:</p>\n<pre><code>std::map&lt;int, int&gt; m;\nstd::vector&lt;int&gt; key, value;\nfor(std::map&lt;int,int&gt;::iterator it = m.begin(); it != m.end(); ++it) {\n key.push_back(it-&gt;first);\n value.push_back(it-&gt;second);\n std::cout &lt;&lt; &quot;Key: &quot; &lt;&lt; it-&gt;first &lt;&lt; std::endl();\n std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; it-&gt;second &lt;&lt; std::endl();\n}\n</code></pre>\n<p>Or even simpler, if you are using Boost:</p>\n<pre><code>map&lt;int,int&gt; m;\npair&lt;int,int&gt; me; // what a map&lt;int, int&gt; is made of\nvector&lt;int&gt; v;\nBOOST_FOREACH(me, m) {\n v.push_back(me.first);\n cout &lt;&lt; me.first &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<p>Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing.</p>\n" }, { "answer_id": 110388, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": false, "text": "<p>I think the BOOST_FOREACH presented above is nice and clean, however, there is another option using BOOST as well.</p>\n\n<pre><code>#include &lt;boost/lambda/lambda.hpp&gt;\n#include &lt;boost/lambda/bind.hpp&gt;\n\nstd::map&lt;int, int&gt; m;\nstd::vector&lt;int&gt; keys;\n\nusing namespace boost::lambda;\n\ntransform( m.begin(), \n m.end(), \n back_inserter(keys), \n bind( &amp;std::map&lt;int,int&gt;::value_type::first, _1 ) \n );\n\ncopy( keys.begin(), keys.end(), std::ostream_iterator&lt;int&gt;(std::cout, \"\\n\") );\n</code></pre>\n\n<p>Personally, I don't think this approach is as clean as the BOOST_FOREACH approach in this case, but boost::lambda can be really clean in other cases. </p>\n" }, { "answer_id": 110784, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>(I'm always wondering why std::map does not include a member function for us to do so.)</p>\n</blockquote>\n\n<p>Because it can't do it any better than you can do it. If a method's implementation will be no superior to a free function's implementation then in general you should not write a method; you should write a free function.</p>\n\n<p>It's also not immediately clear why it's useful anyway.</p>\n" }, { "answer_id": 2389291, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 2, "selected": false, "text": "<p>The best non-sgi, non-boost STL solution is to extend map::iterator like so:</p>\n\n<pre><code>template&lt;class map_type&gt;\nclass key_iterator : public map_type::iterator\n{\npublic:\n typedef typename map_type::iterator map_iterator;\n typedef typename map_iterator::value_type::first_type key_type;\n\n key_iterator(const map_iterator&amp; other) : map_type::iterator(other) {} ;\n\n key_type&amp; operator *()\n {\n return map_type::iterator::operator*().first;\n }\n};\n\n// helpers to create iterators easier:\ntemplate&lt;class map_type&gt;\nkey_iterator&lt;map_type&gt; key_begin(map_type&amp; m)\n{\n return key_iterator&lt;map_type&gt;(m.begin());\n}\ntemplate&lt;class map_type&gt;\nkey_iterator&lt;map_type&gt; key_end(map_type&amp; m)\n{\n return key_iterator&lt;map_type&gt;(m.end());\n}\n</code></pre>\n\n<p>and then use them like so:</p>\n\n<pre><code> map&lt;string,int&gt; test;\n test[\"one\"] = 1;\n test[\"two\"] = 2;\n\n vector&lt;string&gt; keys;\n\n// // method one\n// key_iterator&lt;map&lt;string,int&gt; &gt; kb(test.begin());\n// key_iterator&lt;map&lt;string,int&gt; &gt; ke(test.end());\n// keys.insert(keys.begin(), kb, ke);\n\n// // method two\n// keys.insert(keys.begin(),\n// key_iterator&lt;map&lt;string,int&gt; &gt;(test.begin()),\n// key_iterator&lt;map&lt;string,int&gt; &gt;(test.end()));\n\n // method three (with helpers)\n keys.insert(keys.begin(), key_begin(test), key_end(test));\n\n string one = keys[0];\n</code></pre>\n" }, { "answer_id": 2794168, "author": "DanDan", "author_id": 141985, "author_profile": "https://Stackoverflow.com/users/141985", "pm_score": 6, "selected": false, "text": "<p>C++0x has given us a further, excellent solution:</p>\n\n<pre><code>std::vector&lt;int&gt; keys;\n\nstd::transform(\n m_Inputs.begin(),\n m_Inputs.end(),\n std::back_inserter(keys),\n [](const std::map&lt;int,int&gt;::value_type &amp;pair){return pair.first;});\n</code></pre>\n" }, { "answer_id": 9572688, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 6, "selected": false, "text": "<p>There is a <a href=\"http://www.boost.org/doc/libs/1_49_0/libs/range/doc/html/range/reference/adaptors/reference/map_keys.html\" rel=\"nofollow noreferrer\">boost range adaptor</a> for this purpose:</p>\n<pre><code>#include &lt;boost/range/adaptor/map.hpp&gt;\n#include &lt;boost/range/algorithm/copy.hpp&gt;\nvector&lt;int&gt; keys;\nboost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));\n</code></pre>\n<p>There is a similar map_values range adaptor for extracting the values.</p>\n" }, { "answer_id": 9693232, "author": "Juan", "author_id": 1267669, "author_profile": "https://Stackoverflow.com/users/1267669", "pm_score": 8, "selected": false, "text": "<pre><code>//c++0x too\nstd::map&lt;int,int&gt; mapints;\nstd::vector&lt;int&gt; vints;\nfor(auto const&amp; imap: mapints)\n vints.push_back(imap.first);\n</code></pre>\n" }, { "answer_id": 35905762, "author": "Rusty Parks", "author_id": 4848969, "author_profile": "https://Stackoverflow.com/users/4848969", "pm_score": 3, "selected": false, "text": "<p>Bit of a c++11 take:</p>\n\n<pre><code>std::map&lt;uint32_t, uint32_t&gt; items;\nstd::vector&lt;uint32_t&gt; itemKeys;\nfor (auto &amp; kvp : items)\n{\n itemKeys.emplace_back(kvp.first);\n std::cout &lt;&lt; kvp.first &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 38885161, "author": "Clemens Sielaff", "author_id": 3444217, "author_profile": "https://Stackoverflow.com/users/3444217", "pm_score": 3, "selected": false, "text": "<p>Here's a nice function template using C++11 magic, working for both std::map, std::unordered_map:</p>\n\n<pre><code>template&lt;template &lt;typename...&gt; class MAP, class KEY, class VALUE&gt;\nstd::vector&lt;KEY&gt;\nkeys(const MAP&lt;KEY, VALUE&gt;&amp; map)\n{\n std::vector&lt;KEY&gt; result;\n result.reserve(map.size());\n for(const auto&amp; it : map){\n result.emplace_back(it.first);\n }\n return result;\n}\n</code></pre>\n\n<p>Check it out here: <a href=\"http://ideone.com/lYBzpL\" rel=\"noreferrer\">http://ideone.com/lYBzpL</a></p>\n" }, { "answer_id": 39531911, "author": "James Hirschorn", "author_id": 1349673, "author_profile": "https://Stackoverflow.com/users/1349673", "pm_score": 5, "selected": false, "text": "<p>@DanDan's answer, using C++11 is:</p>\n\n<pre><code>using namespace std;\nvector&lt;int&gt; keys;\n\ntransform(begin(map_in), end(map_in), back_inserter(keys), \n [](decltype(map_in)::value_type const&amp; pair) {\n return pair.first;\n}); \n</code></pre>\n\n<p>and using C++14 (as noted by @ivan.ukr) we can replace <code>decltype(map_in)::value_type</code> with <code>auto</code>.</p>\n" }, { "answer_id": 55676229, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": -1, "selected": false, "text": "<p>Slightly similar to one of examples here, simplified from <code>std::map</code> usage perspective.</p>\n\n<pre><code>template&lt;class KEY, class VALUE&gt;\nstd::vector&lt;KEY&gt; getKeys(const std::map&lt;KEY, VALUE&gt;&amp; map)\n{\n std::vector&lt;KEY&gt; keys(map.size());\n for (const auto&amp; it : map)\n keys.push_back(it.first);\n return keys;\n}\n</code></pre>\n\n<p>Use like this:</p>\n\n<pre><code>auto keys = getKeys(yourMap);\n</code></pre>\n" }, { "answer_id": 55977141, "author": "Madiyar", "author_id": 3320697, "author_profile": "https://Stackoverflow.com/users/3320697", "pm_score": 5, "selected": false, "text": "<p>Based on @rusty-parks solution, but in c++17:</p>\n<pre><code>std::map&lt;int, int&gt; items;\nstd::vector&lt;int&gt; itemKeys;\n\nfor (const auto&amp; [key, _] : items) {\n itemKeys.push_back(key);\n}\n</code></pre>\n" }, { "answer_id": 60838141, "author": "Deniz Babat", "author_id": 7709851, "author_profile": "https://Stackoverflow.com/users/7709851", "pm_score": 0, "selected": false, "text": "<p>With atomic map example</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;vector&gt; \n#include &lt;atomic&gt;\n\nusing namespace std;\n\ntypedef std::atomic&lt;std::uint32_t&gt; atomic_uint32_t;\ntypedef std::map&lt;int, atomic_uint32_t&gt; atomic_map_t;\n\nint main()\n{\n atomic_map_t m;\n\n m[4] = 456;\n m[2] = 45678;\n\n vector&lt;int&gt; v;\n for(map&lt;int,atomic_uint32_t&gt;::iterator it = m.begin(); it != m.end(); ++it) {\n v.push_back(it-&gt;second);\n cout &lt;&lt; it-&gt;first &lt;&lt; \" \"&lt;&lt;it-&gt;second&lt;&lt;\"\\n\";\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 63182487, "author": "Chrissi", "author_id": 12165405, "author_profile": "https://Stackoverflow.com/users/12165405", "pm_score": 2, "selected": false, "text": "<p>I found the following three lines of code as the easiest way:</p>\n<pre><code>// save keys in vector\n\nvector&lt;string&gt; keys;\nfor (auto &amp; it : m) {\n keys.push_back(it.first);\n}\n</code></pre>\n<p>It is a shorten version of the first way of <a href=\"https://stackoverflow.com/a/110255/12165405\">this answer</a>.</p>\n" }, { "answer_id": 65378776, "author": "KaiserKatze", "author_id": 4927212, "author_profile": "https://Stackoverflow.com/users/4927212", "pm_score": 1, "selected": false, "text": "<p>The following functor retrieves the key set of a map:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n\ntemplate &lt;class _Map&gt;\nstd::vector&lt;typename _Map::key_type&gt; keyset(const _Map&amp; map)\n{\n std::vector&lt;typename _Map::key_type&gt; result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.first;\n });\n return result;\n}\n</code></pre>\n<p><em>Bonus</em>: The following functors retrieve the value set of a map:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n#include &lt;functional&gt;\n\ntemplate &lt;class _Map&gt;\nstd::vector&lt;typename _Map::mapped_type&gt; valueset(const _Map&amp; map)\n{\n std::vector&lt;typename _Map::mapped_type&gt; result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.second;\n });\n return result;\n}\n\ntemplate &lt;class _Map&gt;\nstd::vector&lt;std::reference_wrapper&lt;typename _Map::mapped_type&gt;&gt; valueset(_Map&amp; map)\n{\n std::vector&lt;std::reference_wrapper&lt;typename _Map::mapped_type&gt;&gt; result;\n result.reserve(map.size());\n std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) {\n return std::ref(kvpair.second);\n });\n return result;\n}\n</code></pre>\n<p><em>Usage</em>:</p>\n<pre><code>int main()\n{\n std::map&lt;int, double&gt; map{\n {1, 9.0},\n {2, 9.9},\n {3, 9.99},\n {4, 9.999},\n };\n auto ks = keyset(map);\n auto vs = valueset(map);\n for (auto&amp; k : ks) std::cout &lt;&lt; k &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;------------------\\n&quot;;\n for (auto&amp; v : vs) std::cout &lt;&lt; v &lt;&lt; '\\n';\n for (auto&amp; v : vs) v += 100.0;\n std::cout &lt;&lt; &quot;------------------\\n&quot;;\n for (auto&amp; v : vs) std::cout &lt;&lt; v &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;------------------\\n&quot;;\n for (auto&amp; [k, v] : map) std::cout &lt;&lt; v &lt;&lt; '\\n';\n\n return 0;\n}\n</code></pre>\n<p>Expected output:</p>\n<pre><code>1\n2\n3\n4\n------------------\n9\n9.9\n9.99\n9.999\n------------------\n109\n109.9\n109.99\n109.999\n------------------\n109\n109.9\n109.99\n109.999\n</code></pre>\n" }, { "answer_id": 65918927, "author": "Константин Ван", "author_id": 4510033, "author_profile": "https://Stackoverflow.com/users/4510033", "pm_score": 3, "selected": false, "text": "<h3>With <a href=\"https://en.cppreference.com/w/cpp/language/structured_binding\" rel=\"noreferrer\">the <em>structured binding (“destructuring”) declaration</em> syntax</a> of C++17,</h3>\n<p>you can do this, which is easier to understand.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// To get the keys\nstd::map&lt;int, double&gt; map;\nstd::vector&lt;int&gt; keys;\nkeys.reserve(map.size());\nfor(const auto&amp; [key, value] : map) {\n keys.push_back(key);\n}\n</code></pre>\n<pre class=\"lang-cpp prettyprint-override\"><code>// To get the values\nstd::map&lt;int, double&gt; map;\nstd::vector&lt;double&gt; values;\nvalues.reserve(map.size());\nfor(const auto&amp; [key, value] : map) {\n values.push_back(value);\n}\n</code></pre>\n" }, { "answer_id": 67869753, "author": "uol3c", "author_id": 4705766, "author_profile": "https://Stackoverflow.com/users/4705766", "pm_score": 0, "selected": false, "text": "<p>You can use get_map_keys() from <a href=\"https://github.com/Dobiasd/FunctionalPlus/\" rel=\"nofollow noreferrer\">fplus library</a>:</p>\n<pre><code>#include&lt;fplus/maps.hpp&gt;\n// ...\n\nint main() {\n map&lt;string, int32_t&gt; myMap{{&quot;a&quot;, 1}, {&quot;b&quot;, 2}};\n vector&lt;string&gt; keys = fplus::get_map_keys(myMap);\n // ...\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 68094571, "author": "Mercury Dime", "author_id": 8075321, "author_profile": "https://Stackoverflow.com/users/8075321", "pm_score": 5, "selected": false, "text": "<p><strong>Yet Another Way using C++20</strong></p>\n<p>The ranges library has a keys view, which retrieves the first element in a pair/tuple-like type:</p>\n<pre><code>#include &lt;ranges&gt;\n\nauto kv = std::views::keys(m);\nstd::vector&lt;int&gt; keys{ kv.begin(), kv.end() };\n</code></pre>\n<p>Two related views worth mentioning:</p>\n<ol>\n<li>values - to get the values in a map (2nd element in a pair/tuple-like type)</li>\n<li>elements - to get the nth elements in a tuple-like type</li>\n</ol>\n" }, { "answer_id": 72314969, "author": "Olppah", "author_id": 2021579, "author_profile": "https://Stackoverflow.com/users/2021579", "pm_score": 2, "selected": false, "text": "<p>Using ranges in C++20 you can use std::ranges::copy like this</p>\n<pre><code>#include &lt;ranges&gt;\nstd::map&lt;int,int&gt; mapints;\nstd::vector&lt;int&gt; vints;\n\nstd::ranges::copy(mapints | std::views::keys, std::back_inserter(vints));\n</code></pre>\n<p>if you want values instead of keys</p>\n<pre><code>std::ranges::copy(mapints | std::views::values, std::back_inserter(vints));\n</code></pre>\n<p>and if you don't like the pipe syntax</p>\n<pre><code>std::ranges::copy(std::views::values(mapints), std::back_inserter(vints));\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18638/" ]
This is one of the possible ways I come out: ``` struct RetrieveKey { template <typename T> typename T::first_type operator()(T keyValuePair) const { return keyValuePair.first; } }; map<int, int> m; vector<int> keys; // Retrieve all keys transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey()); // Dump all keys copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n")); ``` Of course, we can also retrieve all values from the map by defining another functor **RetrieveValues**. Is there any other way to achieve this easily? (I'm always wondering why `std::map` does not include a member function for us to do so.)
While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult. I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this: ``` std::map<int, int> m; std::vector<int> key, value; for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) { key.push_back(it->first); value.push_back(it->second); std::cout << "Key: " << it->first << std::endl(); std::cout << "Value: " << it->second << std::endl(); } ``` Or even simpler, if you are using Boost: ``` map<int,int> m; pair<int,int> me; // what a map<int, int> is made of vector<int> v; BOOST_FOREACH(me, m) { v.push_back(me.first); cout << me.first << "\n"; } ``` Personally, I like the BOOST\_FOREACH version because there is less typing and it is very explicit about what it is doing.
110,163
<p>I have a rails model that looks something like this:</p> <pre><code>class Recipe &lt; ActiveRecord::Base has_many :ingredients attr_accessor :ingredients_string attr_accessible :title, :directions, :ingredients, :ingredients_string before_save :set_ingredients def ingredients_string ingredients.join("\n") end private def set_ingredients self.ingredients.each { |x| x.destroy } self.ingredients_string ||= false if self.ingredients_string self.ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string =&gt; x) self.ingredients &lt;&lt; ingredient end end end end </code></pre> <p>The idea is that when I create the ingredient from the webpage, I pass in the <code>ingredients_string</code> and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient_string (elegantly) and still check to see if the <code>ingredient_string</code> is defined in the <code>set_ingredients</code> method?</p>
[ { "answer_id": 110170, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<p>The SGI STL has an extension called <a href=\"http://www.sgi.com/tech/stl/select1st.html\" rel=\"noreferrer\"><code>select1st</code></a>. Too bad it's not in standard STL!</p>\n" }, { "answer_id": 110211, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "<p>Your solution is fine but you can use an iterator to do it:</p>\n\n<pre><code>std::map&lt;int, int&gt; m;\nm.insert(std::pair&lt;int, int&gt;(3, 4));\nm.insert(std::pair&lt;int, int&gt;(5, 6));\nfor(std::map&lt;int, int&gt;::const_iterator it = m.begin(); it != m.end(); it++)\n{\n int key = it-&gt;first;\n int value = it-&gt;second;\n //Do something\n}\n</code></pre>\n" }, { "answer_id": 110221, "author": "Marcelo Cantos", "author_id": 9990, "author_profile": "https://Stackoverflow.com/users/9990", "pm_score": 3, "selected": false, "text": "<p>Also, if you have Boost, use transform_iterator to avoid making a temporary copy of the keys.</p>\n" }, { "answer_id": 110228, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 3, "selected": false, "text": "<p>You can use the versatile boost::transform_iterator. The transform_iterator allows you to transform the iterated values, for example in our case when you want to deal only with the keys, not the values. See <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html#example\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html#example</a></p>\n" }, { "answer_id": 110255, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 9, "selected": true, "text": "<p>While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.</p>\n<p>I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:</p>\n<pre><code>std::map&lt;int, int&gt; m;\nstd::vector&lt;int&gt; key, value;\nfor(std::map&lt;int,int&gt;::iterator it = m.begin(); it != m.end(); ++it) {\n key.push_back(it-&gt;first);\n value.push_back(it-&gt;second);\n std::cout &lt;&lt; &quot;Key: &quot; &lt;&lt; it-&gt;first &lt;&lt; std::endl();\n std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; it-&gt;second &lt;&lt; std::endl();\n}\n</code></pre>\n<p>Or even simpler, if you are using Boost:</p>\n<pre><code>map&lt;int,int&gt; m;\npair&lt;int,int&gt; me; // what a map&lt;int, int&gt; is made of\nvector&lt;int&gt; v;\nBOOST_FOREACH(me, m) {\n v.push_back(me.first);\n cout &lt;&lt; me.first &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<p>Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing.</p>\n" }, { "answer_id": 110388, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": false, "text": "<p>I think the BOOST_FOREACH presented above is nice and clean, however, there is another option using BOOST as well.</p>\n\n<pre><code>#include &lt;boost/lambda/lambda.hpp&gt;\n#include &lt;boost/lambda/bind.hpp&gt;\n\nstd::map&lt;int, int&gt; m;\nstd::vector&lt;int&gt; keys;\n\nusing namespace boost::lambda;\n\ntransform( m.begin(), \n m.end(), \n back_inserter(keys), \n bind( &amp;std::map&lt;int,int&gt;::value_type::first, _1 ) \n );\n\ncopy( keys.begin(), keys.end(), std::ostream_iterator&lt;int&gt;(std::cout, \"\\n\") );\n</code></pre>\n\n<p>Personally, I don't think this approach is as clean as the BOOST_FOREACH approach in this case, but boost::lambda can be really clean in other cases. </p>\n" }, { "answer_id": 110784, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>(I'm always wondering why std::map does not include a member function for us to do so.)</p>\n</blockquote>\n\n<p>Because it can't do it any better than you can do it. If a method's implementation will be no superior to a free function's implementation then in general you should not write a method; you should write a free function.</p>\n\n<p>It's also not immediately clear why it's useful anyway.</p>\n" }, { "answer_id": 2389291, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 2, "selected": false, "text": "<p>The best non-sgi, non-boost STL solution is to extend map::iterator like so:</p>\n\n<pre><code>template&lt;class map_type&gt;\nclass key_iterator : public map_type::iterator\n{\npublic:\n typedef typename map_type::iterator map_iterator;\n typedef typename map_iterator::value_type::first_type key_type;\n\n key_iterator(const map_iterator&amp; other) : map_type::iterator(other) {} ;\n\n key_type&amp; operator *()\n {\n return map_type::iterator::operator*().first;\n }\n};\n\n// helpers to create iterators easier:\ntemplate&lt;class map_type&gt;\nkey_iterator&lt;map_type&gt; key_begin(map_type&amp; m)\n{\n return key_iterator&lt;map_type&gt;(m.begin());\n}\ntemplate&lt;class map_type&gt;\nkey_iterator&lt;map_type&gt; key_end(map_type&amp; m)\n{\n return key_iterator&lt;map_type&gt;(m.end());\n}\n</code></pre>\n\n<p>and then use them like so:</p>\n\n<pre><code> map&lt;string,int&gt; test;\n test[\"one\"] = 1;\n test[\"two\"] = 2;\n\n vector&lt;string&gt; keys;\n\n// // method one\n// key_iterator&lt;map&lt;string,int&gt; &gt; kb(test.begin());\n// key_iterator&lt;map&lt;string,int&gt; &gt; ke(test.end());\n// keys.insert(keys.begin(), kb, ke);\n\n// // method two\n// keys.insert(keys.begin(),\n// key_iterator&lt;map&lt;string,int&gt; &gt;(test.begin()),\n// key_iterator&lt;map&lt;string,int&gt; &gt;(test.end()));\n\n // method three (with helpers)\n keys.insert(keys.begin(), key_begin(test), key_end(test));\n\n string one = keys[0];\n</code></pre>\n" }, { "answer_id": 2794168, "author": "DanDan", "author_id": 141985, "author_profile": "https://Stackoverflow.com/users/141985", "pm_score": 6, "selected": false, "text": "<p>C++0x has given us a further, excellent solution:</p>\n\n<pre><code>std::vector&lt;int&gt; keys;\n\nstd::transform(\n m_Inputs.begin(),\n m_Inputs.end(),\n std::back_inserter(keys),\n [](const std::map&lt;int,int&gt;::value_type &amp;pair){return pair.first;});\n</code></pre>\n" }, { "answer_id": 9572688, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 6, "selected": false, "text": "<p>There is a <a href=\"http://www.boost.org/doc/libs/1_49_0/libs/range/doc/html/range/reference/adaptors/reference/map_keys.html\" rel=\"nofollow noreferrer\">boost range adaptor</a> for this purpose:</p>\n<pre><code>#include &lt;boost/range/adaptor/map.hpp&gt;\n#include &lt;boost/range/algorithm/copy.hpp&gt;\nvector&lt;int&gt; keys;\nboost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));\n</code></pre>\n<p>There is a similar map_values range adaptor for extracting the values.</p>\n" }, { "answer_id": 9693232, "author": "Juan", "author_id": 1267669, "author_profile": "https://Stackoverflow.com/users/1267669", "pm_score": 8, "selected": false, "text": "<pre><code>//c++0x too\nstd::map&lt;int,int&gt; mapints;\nstd::vector&lt;int&gt; vints;\nfor(auto const&amp; imap: mapints)\n vints.push_back(imap.first);\n</code></pre>\n" }, { "answer_id": 35905762, "author": "Rusty Parks", "author_id": 4848969, "author_profile": "https://Stackoverflow.com/users/4848969", "pm_score": 3, "selected": false, "text": "<p>Bit of a c++11 take:</p>\n\n<pre><code>std::map&lt;uint32_t, uint32_t&gt; items;\nstd::vector&lt;uint32_t&gt; itemKeys;\nfor (auto &amp; kvp : items)\n{\n itemKeys.emplace_back(kvp.first);\n std::cout &lt;&lt; kvp.first &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 38885161, "author": "Clemens Sielaff", "author_id": 3444217, "author_profile": "https://Stackoverflow.com/users/3444217", "pm_score": 3, "selected": false, "text": "<p>Here's a nice function template using C++11 magic, working for both std::map, std::unordered_map:</p>\n\n<pre><code>template&lt;template &lt;typename...&gt; class MAP, class KEY, class VALUE&gt;\nstd::vector&lt;KEY&gt;\nkeys(const MAP&lt;KEY, VALUE&gt;&amp; map)\n{\n std::vector&lt;KEY&gt; result;\n result.reserve(map.size());\n for(const auto&amp; it : map){\n result.emplace_back(it.first);\n }\n return result;\n}\n</code></pre>\n\n<p>Check it out here: <a href=\"http://ideone.com/lYBzpL\" rel=\"noreferrer\">http://ideone.com/lYBzpL</a></p>\n" }, { "answer_id": 39531911, "author": "James Hirschorn", "author_id": 1349673, "author_profile": "https://Stackoverflow.com/users/1349673", "pm_score": 5, "selected": false, "text": "<p>@DanDan's answer, using C++11 is:</p>\n\n<pre><code>using namespace std;\nvector&lt;int&gt; keys;\n\ntransform(begin(map_in), end(map_in), back_inserter(keys), \n [](decltype(map_in)::value_type const&amp; pair) {\n return pair.first;\n}); \n</code></pre>\n\n<p>and using C++14 (as noted by @ivan.ukr) we can replace <code>decltype(map_in)::value_type</code> with <code>auto</code>.</p>\n" }, { "answer_id": 55676229, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": -1, "selected": false, "text": "<p>Slightly similar to one of examples here, simplified from <code>std::map</code> usage perspective.</p>\n\n<pre><code>template&lt;class KEY, class VALUE&gt;\nstd::vector&lt;KEY&gt; getKeys(const std::map&lt;KEY, VALUE&gt;&amp; map)\n{\n std::vector&lt;KEY&gt; keys(map.size());\n for (const auto&amp; it : map)\n keys.push_back(it.first);\n return keys;\n}\n</code></pre>\n\n<p>Use like this:</p>\n\n<pre><code>auto keys = getKeys(yourMap);\n</code></pre>\n" }, { "answer_id": 55977141, "author": "Madiyar", "author_id": 3320697, "author_profile": "https://Stackoverflow.com/users/3320697", "pm_score": 5, "selected": false, "text": "<p>Based on @rusty-parks solution, but in c++17:</p>\n<pre><code>std::map&lt;int, int&gt; items;\nstd::vector&lt;int&gt; itemKeys;\n\nfor (const auto&amp; [key, _] : items) {\n itemKeys.push_back(key);\n}\n</code></pre>\n" }, { "answer_id": 60838141, "author": "Deniz Babat", "author_id": 7709851, "author_profile": "https://Stackoverflow.com/users/7709851", "pm_score": 0, "selected": false, "text": "<p>With atomic map example</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;vector&gt; \n#include &lt;atomic&gt;\n\nusing namespace std;\n\ntypedef std::atomic&lt;std::uint32_t&gt; atomic_uint32_t;\ntypedef std::map&lt;int, atomic_uint32_t&gt; atomic_map_t;\n\nint main()\n{\n atomic_map_t m;\n\n m[4] = 456;\n m[2] = 45678;\n\n vector&lt;int&gt; v;\n for(map&lt;int,atomic_uint32_t&gt;::iterator it = m.begin(); it != m.end(); ++it) {\n v.push_back(it-&gt;second);\n cout &lt;&lt; it-&gt;first &lt;&lt; \" \"&lt;&lt;it-&gt;second&lt;&lt;\"\\n\";\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 63182487, "author": "Chrissi", "author_id": 12165405, "author_profile": "https://Stackoverflow.com/users/12165405", "pm_score": 2, "selected": false, "text": "<p>I found the following three lines of code as the easiest way:</p>\n<pre><code>// save keys in vector\n\nvector&lt;string&gt; keys;\nfor (auto &amp; it : m) {\n keys.push_back(it.first);\n}\n</code></pre>\n<p>It is a shorten version of the first way of <a href=\"https://stackoverflow.com/a/110255/12165405\">this answer</a>.</p>\n" }, { "answer_id": 65378776, "author": "KaiserKatze", "author_id": 4927212, "author_profile": "https://Stackoverflow.com/users/4927212", "pm_score": 1, "selected": false, "text": "<p>The following functor retrieves the key set of a map:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n\ntemplate &lt;class _Map&gt;\nstd::vector&lt;typename _Map::key_type&gt; keyset(const _Map&amp; map)\n{\n std::vector&lt;typename _Map::key_type&gt; result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.first;\n });\n return result;\n}\n</code></pre>\n<p><em>Bonus</em>: The following functors retrieve the value set of a map:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n#include &lt;functional&gt;\n\ntemplate &lt;class _Map&gt;\nstd::vector&lt;typename _Map::mapped_type&gt; valueset(const _Map&amp; map)\n{\n std::vector&lt;typename _Map::mapped_type&gt; result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.second;\n });\n return result;\n}\n\ntemplate &lt;class _Map&gt;\nstd::vector&lt;std::reference_wrapper&lt;typename _Map::mapped_type&gt;&gt; valueset(_Map&amp; map)\n{\n std::vector&lt;std::reference_wrapper&lt;typename _Map::mapped_type&gt;&gt; result;\n result.reserve(map.size());\n std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) {\n return std::ref(kvpair.second);\n });\n return result;\n}\n</code></pre>\n<p><em>Usage</em>:</p>\n<pre><code>int main()\n{\n std::map&lt;int, double&gt; map{\n {1, 9.0},\n {2, 9.9},\n {3, 9.99},\n {4, 9.999},\n };\n auto ks = keyset(map);\n auto vs = valueset(map);\n for (auto&amp; k : ks) std::cout &lt;&lt; k &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;------------------\\n&quot;;\n for (auto&amp; v : vs) std::cout &lt;&lt; v &lt;&lt; '\\n';\n for (auto&amp; v : vs) v += 100.0;\n std::cout &lt;&lt; &quot;------------------\\n&quot;;\n for (auto&amp; v : vs) std::cout &lt;&lt; v &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;------------------\\n&quot;;\n for (auto&amp; [k, v] : map) std::cout &lt;&lt; v &lt;&lt; '\\n';\n\n return 0;\n}\n</code></pre>\n<p>Expected output:</p>\n<pre><code>1\n2\n3\n4\n------------------\n9\n9.9\n9.99\n9.999\n------------------\n109\n109.9\n109.99\n109.999\n------------------\n109\n109.9\n109.99\n109.999\n</code></pre>\n" }, { "answer_id": 65918927, "author": "Константин Ван", "author_id": 4510033, "author_profile": "https://Stackoverflow.com/users/4510033", "pm_score": 3, "selected": false, "text": "<h3>With <a href=\"https://en.cppreference.com/w/cpp/language/structured_binding\" rel=\"noreferrer\">the <em>structured binding (“destructuring”) declaration</em> syntax</a> of C++17,</h3>\n<p>you can do this, which is easier to understand.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// To get the keys\nstd::map&lt;int, double&gt; map;\nstd::vector&lt;int&gt; keys;\nkeys.reserve(map.size());\nfor(const auto&amp; [key, value] : map) {\n keys.push_back(key);\n}\n</code></pre>\n<pre class=\"lang-cpp prettyprint-override\"><code>// To get the values\nstd::map&lt;int, double&gt; map;\nstd::vector&lt;double&gt; values;\nvalues.reserve(map.size());\nfor(const auto&amp; [key, value] : map) {\n values.push_back(value);\n}\n</code></pre>\n" }, { "answer_id": 67869753, "author": "uol3c", "author_id": 4705766, "author_profile": "https://Stackoverflow.com/users/4705766", "pm_score": 0, "selected": false, "text": "<p>You can use get_map_keys() from <a href=\"https://github.com/Dobiasd/FunctionalPlus/\" rel=\"nofollow noreferrer\">fplus library</a>:</p>\n<pre><code>#include&lt;fplus/maps.hpp&gt;\n// ...\n\nint main() {\n map&lt;string, int32_t&gt; myMap{{&quot;a&quot;, 1}, {&quot;b&quot;, 2}};\n vector&lt;string&gt; keys = fplus::get_map_keys(myMap);\n // ...\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 68094571, "author": "Mercury Dime", "author_id": 8075321, "author_profile": "https://Stackoverflow.com/users/8075321", "pm_score": 5, "selected": false, "text": "<p><strong>Yet Another Way using C++20</strong></p>\n<p>The ranges library has a keys view, which retrieves the first element in a pair/tuple-like type:</p>\n<pre><code>#include &lt;ranges&gt;\n\nauto kv = std::views::keys(m);\nstd::vector&lt;int&gt; keys{ kv.begin(), kv.end() };\n</code></pre>\n<p>Two related views worth mentioning:</p>\n<ol>\n<li>values - to get the values in a map (2nd element in a pair/tuple-like type)</li>\n<li>elements - to get the nth elements in a tuple-like type</li>\n</ol>\n" }, { "answer_id": 72314969, "author": "Olppah", "author_id": 2021579, "author_profile": "https://Stackoverflow.com/users/2021579", "pm_score": 2, "selected": false, "text": "<p>Using ranges in C++20 you can use std::ranges::copy like this</p>\n<pre><code>#include &lt;ranges&gt;\nstd::map&lt;int,int&gt; mapints;\nstd::vector&lt;int&gt; vints;\n\nstd::ranges::copy(mapints | std::views::keys, std::back_inserter(vints));\n</code></pre>\n<p>if you want values instead of keys</p>\n<pre><code>std::ranges::copy(mapints | std::views::values, std::back_inserter(vints));\n</code></pre>\n<p>and if you don't like the pipe syntax</p>\n<pre><code>std::ranges::copy(std::views::values(mapints), std::back_inserter(vints));\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
I have a rails model that looks something like this: ``` class Recipe < ActiveRecord::Base has_many :ingredients attr_accessor :ingredients_string attr_accessible :title, :directions, :ingredients, :ingredients_string before_save :set_ingredients def ingredients_string ingredients.join("\n") end private def set_ingredients self.ingredients.each { |x| x.destroy } self.ingredients_string ||= false if self.ingredients_string self.ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end end ``` The idea is that when I create the ingredient from the webpage, I pass in the `ingredients_string` and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient\_string (elegantly) and still check to see if the `ingredient_string` is defined in the `set_ingredients` method?
While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult. I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this: ``` std::map<int, int> m; std::vector<int> key, value; for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) { key.push_back(it->first); value.push_back(it->second); std::cout << "Key: " << it->first << std::endl(); std::cout << "Value: " << it->second << std::endl(); } ``` Or even simpler, if you are using Boost: ``` map<int,int> m; pair<int,int> me; // what a map<int, int> is made of vector<int> v; BOOST_FOREACH(me, m) { v.push_back(me.first); cout << me.first << "\n"; } ``` Personally, I like the BOOST\_FOREACH version because there is less typing and it is very explicit about what it is doing.
110,175
<p>How can you automatically import the latest build/revision number in subversion?</p> <p>The goal would be to have that number visible on your webpage footer like SO does.</p>
[ { "answer_id": 110182, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 1, "selected": false, "text": "<p>Well, you can run 'svn info' to determine the current revision number, and you could probably extract that pretty easily with a regex, like \"Revision: ([0-9]+)\".</p>\n" }, { "answer_id": 110185, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 5, "selected": true, "text": "<pre><code>svn info &lt;Repository-URL&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>svn info --xml &lt;Repository-URL&gt;\n</code></pre>\n\n<p>Then look at the result. For xml, parse /info/entry/@revision for the revision of the repository (151 in this example) or /info/entry/commit/@revision for the revision of the last commit against this path (133, useful when working with tags):</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;info&gt;\n&lt;entry\n kind=\"dir\"\n path=\"cmdtools\"\n revision=\"151\"&gt;\n&lt;url&gt;http://myserver/svn/stumde/cmdtools&lt;/url&gt;\n&lt;repository&gt;\n&lt;root&gt;http://myserver/svn/stumde&lt;/root&gt;\n&lt;uuid&gt;a148ce7d-da11-c240-b47f-6810ff02934c&lt;/uuid&gt;\n&lt;/repository&gt;\n&lt;commit\n revision=\"133\"&gt;\n&lt;author&gt;mstum&lt;/author&gt;\n&lt;date&gt;2008-07-12T17:09:08.315246Z&lt;/date&gt;\n&lt;/commit&gt;\n&lt;/entry&gt;\n&lt;/info&gt;\n</code></pre>\n\n<p>I wrote a tool (<a href=\"http://www.stum.de/various-tools/cmdtools/\" rel=\"noreferrer\">cmdnetsvnrev</a>, source code included) for myself which replaces the Revision in my AssemblyInfo.cs files. It's limited to that purpose though, but generally svn info and then processing is the way to go.</p>\n" }, { "answer_id": 110188, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "<p>If you have tortoise SVN you can use SubWCRev.exe</p>\n\n<p>Create a file called: </p>\n\n<p>RevisionInfo.tmpl</p>\n\n<pre><code>SvnRevision = $WCREV$;\n</code></pre>\n\n<p>Then execute this command:</p>\n\n<pre><code>SubWCRev.exe . RevisionInfo.tmpl RevisionInfo.txt\n</code></pre>\n\n<p>It will create a file ReivisonInfo.txt with your revision number as follows:</p>\n\n<pre><code>SvnRevision = 5000;\n</code></pre>\n\n<p>But instead of using the .txt you could use whatever source file you want, and have access to the reivsion number within your source code.</p>\n" }, { "answer_id": 110192, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 4, "selected": false, "text": "<p>Add svn:keywords to the SVN properties of the source file:</p>\n\n<pre><code>svn:keywords Revision\n</code></pre>\n\n<p>Then in the source file include:</p>\n\n<pre><code>private const string REVISION = \"$Revision$\";\n</code></pre>\n\n<p>The revision will be updated with the revision number at the next commit to (e.g.) <code>\"$Revision: 4455$\"</code>. You can parse this string to extract just the revision number.</p>\n" }, { "answer_id": 110197, "author": "Omer Zak", "author_id": 11886, "author_profile": "https://Stackoverflow.com/users/11886", "pm_score": 1, "selected": false, "text": "<p>If you are running under GNU/Linux, cd to the working copy's directory and run:</p>\n\n<pre>svn -u status | grep Status\\ against\\ revision: | awk '{print $4}'</pre>\n\n<p>From my experience, svn info does not give reliable numbers after renaming directories.</p>\n" }, { "answer_id": 110206, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 3, "selected": false, "text": "<p>You don't say what programming language/framework you're using. Here's how to do it in Python using <a href=\"http://pysvn.tigris.org\" rel=\"noreferrer\">PySVN</a></p>\n\n<pre><code>import pysvn\nrepo = REPOSITORY_LOCATION\nrev = pysvn.Revision( pysvn.opt_revision_kind.head )\nclient = pysvn.Client()\ninfo = client.info2(repo,revision=rev,recurse=False)\nrevno = info[0][1].rev.number # revision number as an integer\n</code></pre>\n" }, { "answer_id": 110207, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 0, "selected": false, "text": "<p>You want the Subversion <strong>info</strong> subcommand, as follows:</p>\n\n<pre><code>$ svn info .\nPath: .\nURL: http://trac-hacks.org/svn/tracdeveloperplugin/trunk\nRepository Root: http://trac-hacks.org/svn\nRepository UUID: 7322e99d-02ea-0310-aa39-e9a107903beb\nRevision: 4190\nNode Kind: directory\nSchedule: normal\nLast Changed Author: coderanger\nLast Changed Rev: 3397\nLast Changed Date: 2008-03-19 00:49:02 -0400 (Wed, 19 Mar 2008)\n</code></pre>\n\n<p>In this case, there are two revision numbers: 4190 and 3397. 4190 is the last revision number for the repository, and 3397 is the revision number of the last change to the subtree that this workspace was checked out from. You can specify a path to a workspace, or a URL to a repository.</p>\n\n<p>A C# fragment to extract this under Windows would look something like this:</p>\n\n<pre><code>Process process = new Process();\nprocess.StartInfo.FileName = @\"svn.exe\";\nprocess.StartInfo.Arguments = String.Format(@\"info {0}\", path);\nprocess.StartInfo.UseShellExecute = false;\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.Start();\n\n// Parse the svn info output for something like \"Last Changed Rev: 1234\"\nusing (StreamReader output = process.StandardOutput)\n{\n Regex LCR = new Regex(@\"Last Changed Rev: (\\d+)\");\n\n string line;\n while ((line = output.ReadLine()) != null)\n {\n Match match = LCR.Match(line);\n if (match.Success)\n {\n revision = match.Groups[1].Value;\n }\n }\n}\n</code></pre>\n\n<p>(In my case, we use the Subversion revision as part of the version number for assemblies.)</p>\n" }, { "answer_id": 110813, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 3, "selected": false, "text": "<p>Using c# and SharpSvn (from <a href=\"http://sharpsvn.net\" rel=\"nofollow noreferrer\">http://sharpsvn.net</a>) the code would be:</p>\n\n<pre><code>//using SharpSvn;\nlong revision = -1;\nusing(SvnClient client = new SvnClient())\n{\n client.Info(path,\n delegate(object sender, SvnInfoEventArgs e)\n {\n revision = e.Revision;\n });\n}\n</code></pre>\n" }, { "answer_id": 111173, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 5, "selected": false, "text": "<p>Have your build process call the <a href=\"http://svnbook.red-bean.com/en/1.4/svn.ref.svnversion.re.html\" rel=\"noreferrer\">svnversion</A> command, and embed its output into generated {source|binaries}. This will not only give the current revision (as many other examples here do), but its output string will also tell whether a build is being done in a mixed tree or a tree which doesn't exactly match the revision number in question (ie. a tree with local changes).</p>\n\n<p>With a standard tree:</p>\n\n<pre><code>$ svnversion\n3846\n</code></pre>\n\n<p>With a modified tree:</p>\n\n<pre><code>$ echo 'foo' &gt;&gt; project-ext.dtd\n$ svnversion \n3846M\n</code></pre>\n\n<p>With a mixed-revision, modified tree:</p>\n\n<pre><code>$ (cd doc; svn up &gt;/dev/null 2&gt;/dev/null)\n$ svnversion\n3846:4182M\n</code></pre>\n" }, { "answer_id": 111259, "author": "Ryan Taylor", "author_id": 19977, "author_profile": "https://Stackoverflow.com/users/19977", "pm_score": 2, "selected": false, "text": "<p>In my latest project I solved this problem by using several tools, SVN, NAnt, and a custom NAnt task. </p>\n\n<ol>\n<li>Use NAnt to execute <code>svn info --xml ./svnInfo.xml</code></li>\n<li>Use NAnt to pull the revision number from the xml file with <code>&lt;xmlpeek&gt;</code></li>\n<li>Use a custom NAnt task to update the AssemblyVersion attribute in the AssemblyInfo.cs file with the latest with the version number (e.g., major.minor.maintenance, revision) before compiling the project.</li>\n</ol>\n\n<p>The version related sections of my build script look like this:</p>\n\n<pre><code>&lt;!-- Retrieve the current revision number for the working directory --&gt;\n&lt;exec program=\"svn\" commandline='info --xml' output=\"./svnInfo.xml\" failonerror=\"false\"/&gt;\n&lt;xmlpeek file=\"./svnInfo.xml\" xpath=\"info/entry/@revision\" property=\"build.version.revision\" if=\"${file::exists('./svnInfo.xml')}\"/&gt;\n\n&lt;!-- Custom NAnt task to replace strings matching a pattern with a specific value --&gt;\n&lt;replace file=\"${filename}\" \n pattern=\"AssemblyVersion(?:Attribute)?\\(\\s*?\\&amp;quot;(?&amp;lt;version&amp;gt;(?&amp;lt;major&amp;gt;[0-9]+)\\.(?&amp;lt;minor&amp;gt;[0-9]+)\\.(?&amp;lt;build&amp;gt;[0-9]+)\\.(?&amp;lt;revision&amp;gt;[0-9]+))\\&amp;quot;\\s*?\\)\" \n value=\"AssemblyVersion(${build.version})\"\n outfile=\"${filename}\"/&gt;\n</code></pre>\n\n<p>The credit for the regular expression goes to: <a href=\"http://code.mattgriffith.net/UpdateVersion/\" rel=\"nofollow noreferrer\">http://code.mattgriffith.net/UpdateVersion/</a>. However, I found that UpdateVersion did not meet my needs as the pin feature was broken in the build I had. Hence the custom NAnt task.</p>\n\n<p>If anyone is interested in the code, for the custom NAnt <code>replace</code> task let me know. Since this was for a work related project I will need to check with management to see if we can release it under a friendly (free) license.</p>\n" }, { "answer_id": 112674, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://svnbook.red-bean.com/en/1.8/svn.ref.svnversion.re.html\" rel=\"nofollow noreferrer\"><code>svnversion</code></a> command is the correct way to do this. It outputs the revision number your entire working copy is at, or a range of revisions if your working copy is mixed (e.g. some directories are up to date and some aren't). It will also indicate if the working copy has local modifications. For example, in a rather unclean working directory:</p>\n\n<pre><code>$ svnversion\n662:738M\n</code></pre>\n\n<p>The $Revision$ keyword doesn't do what you want: it only changes when the containing file does. The Subversion book gives <a href=\"http://svnbook.red-bean.com/en/1.8/svn.advanced.props.special.keywords.html\" rel=\"nofollow noreferrer\">more detail</a>. The \"svn info\" command also doesn't do what you want, as it only tells you the state of your current directory, ignoring the state of any subdirectories. In the same working tree as the previous example, I had some subdirectories which were newer than the directory I was in, but \"svn info\" doesn't notice:</p>\n\n<pre><code>$ svn info\n... snip ...\nRevision: 662\n</code></pre>\n\n<p>It's easy to incorporate svnversion into your build process, so that each build gets the revision number in some runtime-accessible form. For a Java project, for example, I had our makefile dump the svnversion output into a .properties file.</p>\n" }, { "answer_id": 750475, "author": "mlambie", "author_id": 17453, "author_profile": "https://Stackoverflow.com/users/17453", "pm_score": 2, "selected": false, "text": "<p>In Rails I use this snippet in my environment.rb which gives me a constant I can use throughout the application (like in the footer of an application layout).</p>\n\n<pre><code>SVN_VERSION = IO.popen(\"svn info\").readlines[4].strip.split[1]\n</code></pre>\n" }, { "answer_id": 1022238, "author": "ivan_ivanovich_ivanoff", "author_id": 76393, "author_profile": "https://Stackoverflow.com/users/76393", "pm_score": 2, "selected": false, "text": "<p>Here is a hint, how you might use <strong>Netbeans</strong>' capabilities to<br>\ncreate <strong>custom ant tasks</strong> which would generate scm-version.txt:</p>\n\n<p>Open your <strong>build.xml</strong> file, and add following code right <strong>after</strong><br>\n<code>&lt;import file=\"nbproject/build-impl.xml\"/&gt;</code></p>\n\n<pre><code>&lt;!-- STORE SUBVERSION BUILD STRING --&gt;\n&lt;target name=\"-pre-compile\"&gt;\n &lt;exec executable=\"svnversion\"\n output=\"${src.dir}/YOUR/PACKAGE/NAME/scm-version.txt\"/&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p>Now, Netbeans strores the Subversion version string\nto <strong>scm-version.txt</strong> everytime you make <strong>clean/build</strong>.</p>\n\n<p>You can read the file during runtime by doing:</p>\n\n<pre><code>getClass().getResourceAsStream(\"scm-version.txt\"); // ...\n</code></pre>\n\n<p>Don't forget to mark the file <strong>scm-version.txt</strong> as <strong>svn:ignore</strong>.</p>\n" }, { "answer_id": 1347674, "author": "Chris Roberts", "author_id": 475, "author_profile": "https://Stackoverflow.com/users/475", "pm_score": 0, "selected": false, "text": "<p>I use the <a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\">MSBuild Community Tasks</a> project which has a tool to retrieve the SVN revision number and add it to your AssemblyInfo.vb. You can then use reflection to retrieve this string to display it in your UI.</p>\n\n<p>Here's a <a href=\"http://solutionmania.com/2009/8/28/automatically-adding-svn-revision-numbers-to-assemblies\" rel=\"nofollow noreferrer\">full blog post with instructions</a>.</p>\n" }, { "answer_id": 1878905, "author": "colin moock", "author_id": 228540, "author_profile": "https://Stackoverflow.com/users/228540", "pm_score": 0, "selected": false, "text": "<p>if you're using svnant, you can use wcVersion, which duplicates svnveresion and returns digestible values. see:\n<a href=\"http://subclipse.tigris.org/svnant/svn.html#wcVersion\" rel=\"nofollow noreferrer\">http://subclipse.tigris.org/svnant/svn.html#wcVersion</a></p>\n" }, { "answer_id": 2619402, "author": "grimus", "author_id": 74346, "author_profile": "https://Stackoverflow.com/users/74346", "pm_score": 0, "selected": false, "text": "<p>I created an <a href=\"http://happyturtle.codeplex.com/\" rel=\"nofollow noreferrer\">SVN version plug-in</a> for the <a href=\"http://autobuildversion.codeplex.com/\" rel=\"nofollow noreferrer\">Build Version Increment</a> project on CodePlex. This SVN plug-in will pull the latest change revision number from your working copy and allow you to use that in your version number, which should accomplish exactly what you're trying to do. Build Version Increment is pretty flexible and will allow you to set up how the versioning is done in a number of ways.</p>\n\n<p>BVI only works with Visual Studio, but since you're using Asp.Net, that won't be a problem. It doesn't require writing any code or editing xml, so yay!</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
How can you automatically import the latest build/revision number in subversion? The goal would be to have that number visible on your webpage footer like SO does.
``` svn info <Repository-URL> ``` or ``` svn info --xml <Repository-URL> ``` Then look at the result. For xml, parse /info/entry/@revision for the revision of the repository (151 in this example) or /info/entry/commit/@revision for the revision of the last commit against this path (133, useful when working with tags): ``` <?xml version="1.0"?> <info> <entry kind="dir" path="cmdtools" revision="151"> <url>http://myserver/svn/stumde/cmdtools</url> <repository> <root>http://myserver/svn/stumde</root> <uuid>a148ce7d-da11-c240-b47f-6810ff02934c</uuid> </repository> <commit revision="133"> <author>mstum</author> <date>2008-07-12T17:09:08.315246Z</date> </commit> </entry> </info> ``` I wrote a tool ([cmdnetsvnrev](http://www.stum.de/various-tools/cmdtools/), source code included) for myself which replaces the Revision in my AssemblyInfo.cs files. It's limited to that purpose though, but generally svn info and then processing is the way to go.
110,205
<p>I want to download this open source application, and they are using Git. What do I need to download the code base?</p> <p><b>Update</b> How do I change the working directory when I am using Git Bash? (I want to download the repo at a certain directory, using pwd tells me I will be downloading the repo where I don't want it.</p>
[ { "answer_id": 110209, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "<p>Download <a href=\"http://code.google.com/p/msysgit/\" rel=\"noreferrer\">Git on Msys</a>. Then:</p>\n\n<pre><code>git clone git://project.url.here\n</code></pre>\n" }, { "answer_id": 110237, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 1, "selected": false, "text": "<p>To change working directory in GitMSYS's Git Bash you can just use <code>cd</code></p>\n\n<p>cd /path/do/directory</p>\n\n<p>Note that:</p>\n\n<ul>\n<li>Directory separators use the forward-slash (<code>/</code>) instead of backslash.</li>\n<li>Drives are specified with a lower case letter and no colon, e.g. \"<code>C:\\stuff</code>\" should be represented with \"<code>/c/stuff</code>\".</li>\n<li>Spaces can be escaped with a backslash (<code>\\</code>)</li>\n<li>Command line completion is your friend. Press TAB at anytime to expand stuff, including Git options, branches, tags, and directories.</li>\n</ul>\n\n<p>Also, you can right click in Windows Explorer on a directory and \"Git Bash here\".</p>\n" }, { "answer_id": 110408, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 2, "selected": false, "text": "<p>I don't want to start a \"What's the best unix command line under Windows\" war, but have you thought of <a href=\"http://www.cygwin.com\" rel=\"nofollow noreferrer\"><em>Cygwin</em></a>? Git is in the Cygwin package repository.</p>\n\n<p>And you get a lot of beneficial side-effects! (:-)</p>\n" }, { "answer_id": 7001468, "author": "James Lawruk", "author_id": 88204, "author_profile": "https://Stackoverflow.com/users/88204", "pm_score": 3, "selected": false, "text": "<p>Install <a href=\"http://code.google.com/p/msysgit/\">mysysgit</a>. (Same as Greg Hewgill's answer.)</p>\n\n<p>Install <a href=\"http://code.google.com/p/tortoisegit/\">Tortoisegit</a>. (Tortoisegit requires mysysgit or something similiar like Cygwin.)</p>\n\n<p>After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.</p>\n\n<p><em>This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)</em></p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I want to download this open source application, and they are using Git. What do I need to download the code base? **Update** How do I change the working directory when I am using Git Bash? (I want to download the repo at a certain directory, using pwd tells me I will be downloading the repo where I don't want it.
Download [Git on Msys](http://code.google.com/p/msysgit/). Then: ``` git clone git://project.url.here ```
110,232
<p>I am creating a website in CakePHP and I am kind of new on it. I couldn't find good resources on this matter, so there you go:</p> <p>I have a three table structure for registering users: <code>Users</code>, <code>Addresses</code> and <code>Contacts</code>. I have to build a view with info of all three tables like:</p> <pre> Full Name: [ ] (from Users) Shipping Address: [ ] (from Address) Mobile Phone: [ ] (from Contact) e-Mail Address: [ ] (from Contact) </pre> <p>What is the best way to deal with this situation. <em>Specially for saving</em>. Creating a new Model to represent this, that will have a <code>save()</code> method itself (Maybe a sql view in the database) Create a Controller to deal with this View that <code>bind</code>s or <code>unbind</code>s info</p> <p>I wonder still how I will handle both contacts as they will be 2 different <code>INSERT</code>'s</p> <p>Any hint or resources I can dig of I will be glad.</p>
[ { "answer_id": 110432, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 2, "selected": false, "text": "<p>CakePHP allows you to easily maintains link between your models using relationship, see <a href=\"http://book.cakephp.org/view/78/Associations-Linking-Models-Together\" rel=\"nofollow noreferrer\">http://book.cakephp.org/view/78/Associations-Linking-Models-Together</a> for the complete detail. Then retreiving the right User, you'll also get \"for free\", its address and contact informations.</p>\n" }, { "answer_id": 112685, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>If your using the latest 1.2 code, check out Model::saveAll in the api</p>\n\n<p>eg. Your view might look something like this:</p>\n\n<pre><code>echo $form-&gt;create('User', array('action' =&gt; 'add');\necho $form-&gt;input('User.name');\necho $form-&gt;input('Address.line_1');\necho $form-&gt;input('Contact.tel');\necho $form-&gt;end('Save');\n</code></pre>\n\n<p>Then in your Users controller add method you'd have something like:</p>\n\n<pre><code>...\n\nif($this-&gt;User-&gt;saveAll($this-&gt;data)) {\n $this-&gt;Session-&gt;setFlash('Save Successful');\n $this-&gt;redirect(array('action' =&gt; 'index'));\n} else {\n $this-&gt;Session-&gt;setFlash('Please review the form for errors');\n}\n\n...\n</code></pre>\n\n<p>In your User model you will need something like:</p>\n\n<pre><code>var $hasOne = array('Address', 'Contact');\n</code></pre>\n\n<p>Hope that helps!</p>\n\n<p><a href=\"http://api.cakephp.org/class_model.html#49f295217028004b5a723caf086a86b1\" rel=\"nofollow noreferrer\">http://api.cakephp.org/class_model.html#49f295217028004b5a723caf086a86b1</a></p>\n" }, { "answer_id": 132416, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>3 models : User, Address, Contact</p>\n</blockquote>\n\n<pre><code>User hasOne Address, Contact\nAddress belongsTo User\nContact belongsTo User\n</code></pre>\n\n<p>in your model you define this like this :</p>\n\n<pre><code>class User extends AppModel {\nvar $name = 'User';\nvar $hasOne = array('Address','Contact');\n..\n</code></pre>\n\n<p>To make this view, you need <strong>user_id</strong> field ind <em>addresses</em>, and <em>contacts</em> tables</p>\n\n<p>To use this in a view, you simply call a find on the User model with a recursive of one (and btw, the users controller only uses User model).</p>\n\n<pre><code>$this-&gt;User-&gt;recursive = 1;\n$this-&gt;set('user', $this-&gt;User-&gt;find('first', array('conditions'=&gt;array('id'=&gt;666)));\n</code></pre>\n\n<p>This will result in this array for your view : </p>\n\n<pre><code>array(\n 'Use' =&gt; array(\n 'id' =&gt; 666,\n 'name' =&gt; 'Alexander'\n),\n 'Address' =&gt; array(\n 'id' =&gt; 123,\n 'zip' =&gt; 555\n),\n 'Contact' =&gt; array(\n 'id' =&gt; 432,\n 'phone' =&gt; '555-1515'\n));\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
I am creating a website in CakePHP and I am kind of new on it. I couldn't find good resources on this matter, so there you go: I have a three table structure for registering users: `Users`, `Addresses` and `Contacts`. I have to build a view with info of all three tables like: ``` Full Name: [ ] (from Users) Shipping Address: [ ] (from Address) Mobile Phone: [ ] (from Contact) e-Mail Address: [ ] (from Contact) ``` What is the best way to deal with this situation. *Specially for saving*. Creating a new Model to represent this, that will have a `save()` method itself (Maybe a sql view in the database) Create a Controller to deal with this View that `bind`s or `unbind`s info I wonder still how I will handle both contacts as they will be 2 different `INSERT`'s Any hint or resources I can dig of I will be glad.
If your using the latest 1.2 code, check out Model::saveAll in the api eg. Your view might look something like this: ``` echo $form->create('User', array('action' => 'add'); echo $form->input('User.name'); echo $form->input('Address.line_1'); echo $form->input('Contact.tel'); echo $form->end('Save'); ``` Then in your Users controller add method you'd have something like: ``` ... if($this->User->saveAll($this->data)) { $this->Session->setFlash('Save Successful'); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash('Please review the form for errors'); } ... ``` In your User model you will need something like: ``` var $hasOne = array('Address', 'Contact'); ``` Hope that helps! <http://api.cakephp.org/class_model.html#49f295217028004b5a723caf086a86b1>
110,249
<p>Since VS 2005, I see that it is not possible to simply build a dll against MS runtime and deploy them together (<a href="http://www.ddj.com/windows/184406482" rel="nofollow noreferrer">http://www.ddj.com/windows/184406482</a>). I am deeply confused by manifest, SxS and co: MSDN documentation is really poor, with circular references; specially since I am more a Unix guy, I find all those uninformative. My core problem is linking a dll against msvc9 or msvc8: since those runtime are not redistributable, what are the steps to link and deploy such a dll ? In particular, how are the manifest generated (I don't want mt.exe, I want something which is portable across compilers), how are they embedded, used ? What does Side by side assembly mean ?</p> <p>Basically, where can I find any kind of specification instead of MS jargon ?</p> <p>Thank you to everyone who answered, this was really helpful, </p>
[ { "answer_id": 110266, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 2, "selected": false, "text": "<p>Well, I've encountered some of these issues, so perhaps some of my comments will be helpful.</p>\n\n<ol>\n<li>The manifest is an xml file. While VS can and will make one for you when you compile, the other solution is to produce a resource file (.rc) and compile it into a compiled resource file (.res) using the resource compiler (rc.exe) included with VS. You'll want to run the VS commandline from the tools menu, which will cause rc to be in the path, as well as setting various environmental variables correctly. Then compile your resource. The resulting .res file can be used by other compilers.</li>\n<li>Make sure your manifest xml file's size is divisible by 4. Add whitespace in the middle of it to achieve this if needed. Try to avoid having any characters before the openning xml tag or after the closing xml tag. I've sometimes had issues with this. If you do step 2 incorrectly, expect to get side by side configuration errors. You can check if that is your mistake by openning the exe in a resource editor (e.g. devenv.exe) and examining the manifest resource. You can also see an example of a correct manifest by just opening a built file, though note that dlls and exes have tiny differences in what id the resource should be given.</li>\n</ol>\n\n<p>You'll probably want to test on Vista to make sure this is working properly.</p>\n" }, { "answer_id": 110270, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 1, "selected": false, "text": "<p>They are redistributable and you have redistributable packages inside msvs directory. </p>\n\n<p>Build with runtime of your choice, add corresponding package to your installer and don't bother - it will work. The difference is - they are <em>installed</em> in a different place now (but that is also where your app is going to look for libraries).</p>\n\n<p>Otherwise, MSDN or basically any not-too-old book on windows c++ programming.</p>\n" }, { "answer_id": 110318, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 2, "selected": false, "text": "<p>Here is the blog entry <a href=\"http://blogs.gotdotnet.com/martynl/archive/2005/10/13/480880.aspx\" rel=\"nofollow noreferrer\">explaining the rational behind the SxS crt decision for VC++</a>. It includes explaining how bad it is to statically link the crt, and why you shouldn't do that.</p>\n\n<p>Here is the <a href=\"http://msdn.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx\" rel=\"nofollow noreferrer\">documentation on how to statically link the crt</a>.</p>\n" }, { "answer_id": 110550, "author": "David Cournapeau", "author_id": 11465, "author_profile": "https://Stackoverflow.com/users/11465", "pm_score": 0, "selected": false, "text": "<p>Thanks for the answer. For deployment per se, I can see 3 options, then:</p>\n\n<ul>\n<li>Using .msi merge directive.</li>\n<li>Using the redistributable VS package and run it before my own installer</li>\n<li>Copying the redistributable <em>files</em> along my own application. But in this case, how do I refer to it in a filesystem hierarchy (say bar/foo1/foo1.dll and bar/foo2/foo2.dll refer to msvcr90.dll in bar/) ? I mean besides the obvious and ugly \"copy the dll in every directory where you have dll which depends on it).</li>\n</ul>\n" }, { "answer_id": 113022, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 3, "selected": true, "text": "<p>We use a simple include file in all our applications &amp; DLL's, vcmanifest.h, then set all projects to embedded the manifest file.</p>\n\n<p>vcmanifest.h</p>\n\n<pre><code>/*----------------------------------------------------------------------------*/\n\n#if _MSC_VER &gt;= 1400\n\n/*----------------------------------------------------------------------------*/\n\n#pragma message ( \"Setting up manifest...\" )\n\n/*----------------------------------------------------------------------------*/\n\n#ifndef _CRT_ASSEMBLY_VERSION\n#include &lt;crtassem.h&gt;\n#endif \n\n/*----------------------------------------------------------------------------*/\n\n#ifdef WIN64\n #pragma message ( \"processorArchitecture=amd64\" )\n #define MF_PROCESSORARCHITECTURE \"amd64\"\n#else\n #pragma message ( \"processorArchitecture=x86\" )\n #define MF_PROCESSORARCHITECTURE \"x86\"\n#endif \n\n/*----------------------------------------------------------------------------*/\n\n#pragma message ( \"Microsoft.Windows.Common-Controls=6.0.0.0\") \n#pragma comment ( linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='Microsoft.Windows.Common-Controls' \" \\\n \"version='6.0.0.0' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='6595b64144ccf1df'\\\"\" )\n\n/*----------------------------------------------------------------------------*/\n\n#ifdef _DEBUG\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".DebugCRT=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".DebugCRT' \" \\\n \"version='\" _CRT_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n#else\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".CRT=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".CRT' \" \\\n \"version='\" _CRT_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n#endif\n\n/*----------------------------------------------------------------------------*/\n\n#ifdef _MFC_ASSEMBLY_VERSION\n #ifdef _DEBUG\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC' \" \\\n \"version='\" _MFC_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n #else\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC' \" \\\n \"version='\" _MFC_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n #endif\n#endif /* _MFC_ASSEMBLY_VERSION */\n\n/*----------------------------------------------------------------------------*/\n\n#endif /* _MSC_VER */\n\n/*----------------------------------------------------------------------------*/\n</code></pre>\n" }, { "answer_id": 209291, "author": "garthy", "author_id": 25504, "author_profile": "https://Stackoverflow.com/users/25504", "pm_score": 0, "selected": false, "text": "<p>You can't use the VC++8 SP1/9 CRT as a merge module on Vista and windows Server 2008 if you have services you want to start or programs that you want to run before the \"InstallFinalize\" action in the MSI.</p>\n\n<p>This is because the dlls are installed in WinSXS in the \"InstallFinalize\" action.</p>\n\n<p>But the MSI \"ServiceStart\" action comes before this.</p>\n\n<p>So use either a bootstrapper \"<a href=\"http://www.davidguyer.us/bmg/publish.htm\" rel=\"nofollow noreferrer\">http://www.davidguyer.us/bmg/publish.htm</a>\"</p>\n\n<p>Or look into using the installer chainging in the installer 4.5. But this means you need a bootstrapper to install 4.5 so it seems a bit pointless..</p>\n" }, { "answer_id": 225950, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 2, "selected": false, "text": "<p>The simplest thing to do:\nAssuming a default install of VS2005, you will have a path like:</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 8\\VC\\redist\\x86\\Microsoft.VC80.CRT\n</code></pre>\n\n<p>Go, grab the files in this redist folder, and place the .manifest AND the msvcr80.dll (At least) in your applications .exe folder.\nThese files, present in the root of your installation, should enable your exe and all dlls linked against them, to work flawlessly without resorting to merge modules, MSIs or indeed any kind of just-in-time detection that the runtime is not installed.</p>\n" }, { "answer_id": 835580, "author": "EricJ", "author_id": 85824, "author_profile": "https://Stackoverflow.com/users/85824", "pm_score": 0, "selected": false, "text": "<p>If you intend to deploy the Microsoft DLLs/.manifest files and are using Java JNI then you will need to put them in the bin directory of your JDK/JRE.</p>\n\n<p>If you are running the app in JBoss, then you will need to put them in the JBoss/bin directory.</p>\n\n<p>You can put your JNI DLL where appropriate for your application.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11465/" ]
Since VS 2005, I see that it is not possible to simply build a dll against MS runtime and deploy them together (<http://www.ddj.com/windows/184406482>). I am deeply confused by manifest, SxS and co: MSDN documentation is really poor, with circular references; specially since I am more a Unix guy, I find all those uninformative. My core problem is linking a dll against msvc9 or msvc8: since those runtime are not redistributable, what are the steps to link and deploy such a dll ? In particular, how are the manifest generated (I don't want mt.exe, I want something which is portable across compilers), how are they embedded, used ? What does Side by side assembly mean ? Basically, where can I find any kind of specification instead of MS jargon ? Thank you to everyone who answered, this was really helpful,
We use a simple include file in all our applications & DLL's, vcmanifest.h, then set all projects to embedded the manifest file. vcmanifest.h ``` /*----------------------------------------------------------------------------*/ #if _MSC_VER >= 1400 /*----------------------------------------------------------------------------*/ #pragma message ( "Setting up manifest..." ) /*----------------------------------------------------------------------------*/ #ifndef _CRT_ASSEMBLY_VERSION #include <crtassem.h> #endif /*----------------------------------------------------------------------------*/ #ifdef WIN64 #pragma message ( "processorArchitecture=amd64" ) #define MF_PROCESSORARCHITECTURE "amd64" #else #pragma message ( "processorArchitecture=x86" ) #define MF_PROCESSORARCHITECTURE "x86" #endif /*----------------------------------------------------------------------------*/ #pragma message ( "Microsoft.Windows.Common-Controls=6.0.0.0") #pragma comment ( linker,"/manifestdependency:\"type='win32' " \ "name='Microsoft.Windows.Common-Controls' " \ "version='6.0.0.0' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='6595b64144ccf1df'\"" ) /*----------------------------------------------------------------------------*/ #ifdef _DEBUG #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".DebugCRT=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".DebugCRT' " \ "version='" _CRT_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #else #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT' " \ "version='" _CRT_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #endif /*----------------------------------------------------------------------------*/ #ifdef _MFC_ASSEMBLY_VERSION #ifdef _DEBUG #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC' " \ "version='" _MFC_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #else #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC' " \ "version='" _MFC_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #endif #endif /* _MFC_ASSEMBLY_VERSION */ /*----------------------------------------------------------------------------*/ #endif /* _MSC_VER */ /*----------------------------------------------------------------------------*/ ```
110,259
<p>I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory. Google search shows a commercial one is <a href="http://www.softwareverify.com/python/memory/index.html" rel="noreferrer">Python Memory Validator</a> (Windows only).</p> <p>And open source ones are <a href="http://pysizer.8325.org/" rel="noreferrer">PySizer</a> and <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="noreferrer">Heapy</a>.</p> <p>I haven't tried anyone, so I wanted to know which one is the best considering:</p> <ol> <li><p>Gives most details.</p></li> <li><p>I have to do least or no changes to my code.</p></li> </ol>
[ { "answer_id": 110272, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 6, "selected": false, "text": "<p>I recommend <a href=\"http://www.aminus.net/wiki/Dowser\" rel=\"noreferrer\">Dowser</a>. It is very easy to setup, and you need zero changes to your code. You can view counts of objects of each type through time, view list of live objects, view references to live objects, all from the simple web interface.</p>\n\n<pre><code># memdebug.py\n\nimport cherrypy\nimport dowser\n\ndef start(port):\n cherrypy.tree.mount(dowser.Root())\n cherrypy.config.update({\n 'environment': 'embedded',\n 'server.socket_port': port\n })\n cherrypy.server.quickstart()\n cherrypy.engine.start(blocking=False)\n</code></pre>\n\n<p>You import memdebug, and call memdebug.start. That's all.</p>\n\n<p>I haven't tried PySizer or Heapy. I would appreciate others' reviews.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>The above code is for <code>CherryPy 2.X</code>, <code>CherryPy 3.X</code> the <code>server.quickstart</code> method has been removed and <code>engine.start</code> does not take the <code>blocking</code> flag. So if you are using <code>CherryPy 3.X</code></p>\n\n<pre><code># memdebug.py\n\nimport cherrypy\nimport dowser\n\ndef start(port):\n cherrypy.tree.mount(dowser.Root())\n cherrypy.config.update({\n 'environment': 'embedded',\n 'server.socket_port': port\n })\n cherrypy.engine.start()\n</code></pre>\n" }, { "answer_id": 110826, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 9, "selected": true, "text": "<p><a href=\"https://github.com/zhuyifei1999/guppy3/\" rel=\"noreferrer\">guppy3</a> is quite simple to use. At some point in your code, you have to write the following:</p>\n<pre><code>from guppy import hpy\nh = hpy()\nprint(h.heap())\n</code></pre>\n<p>This gives you some output like this:</p>\n<pre><code>Partition of a set of 132527 objects. Total size = 8301532 bytes.\nIndex Count % Size % Cumulative % Kind (class / dict of class)\n0 35144 27 2140412 26 2140412 26 str\n1 38397 29 1309020 16 3449432 42 tuple\n2 530 0 739856 9 4189288 50 dict (no owner)\n</code></pre>\n<p>You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.</p>\n<p>There is a graphical browser as well, written in Tk.</p>\n<p>For Python 2.x, use <a href=\"http://guppy-pe.sourceforge.net/\" rel=\"noreferrer\">Heapy</a>.</p>\n" }, { "answer_id": 1633191, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 6, "selected": false, "text": "<p>Consider the <A HREF=\"http://mg.pov.lt/objgraph/\" rel=\"nofollow noreferrer\">objgraph</A> library (see <a href=\"http://web.archive.org/web/20201109012938/http://tech.labs.oliverwyman.com/blog/2008/11/14/tracing-python-memory-leaks\" rel=\"nofollow noreferrer\">this blog post</a> for an example use case).</p>\n" }, { "answer_id": 7896149, "author": "Calen Pennington", "author_id": 1013576, "author_profile": "https://Stackoverflow.com/users/1013576", "pm_score": 4, "selected": false, "text": "<p>I found <a href=\"https://launchpad.net/meliae\" rel=\"noreferrer\">meliae</a> to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then <a href=\"http://pypi.python.org/pypi/Dozer\" rel=\"noreferrer\">Dozer</a> is a nice middleware wrapper of Dowser</p>\n" }, { "answer_id": 10592072, "author": "Fabian Pedregosa", "author_id": 505591, "author_profile": "https://Stackoverflow.com/users/505591", "pm_score": 9, "selected": false, "text": "<p>My module <a href=\"http://pypi.python.org/pypi/memory_profiler\" rel=\"noreferrer\">memory_profiler</a> is capable of printing a line-by-line report of memory usage and works on Unix and Windows (needs psutil on this last one). Output is not very detailed but the goal is to give you an overview of where the code is consuming more memory, not an exhaustive analysis on allocated objects.</p>\n<p>After decorating your function with <code>@profile</code> and running your code with the <code>-m memory_profiler</code> flag it will print a line-by-line report like this:</p>\n<pre><code>Line # Mem usage Increment Line Contents\n==============================================\n 3 @profile\n 4 5.97 MB 0.00 MB def my_func():\n 5 13.61 MB 7.64 MB a = [1] * (10 ** 6)\n 6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)\n 7 13.61 MB -152.59 MB del b\n 8 13.61 MB 0.00 MB return a\n</code></pre>\n" }, { "answer_id": 15340874, "author": "Serrano", "author_id": 466781, "author_profile": "https://Stackoverflow.com/users/466781", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://pythonhosted.org/Pympler/muppy.html\" rel=\"noreferrer\">Muppy</a> is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks.</p>\n\n<p>Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects.</p>\n" }, { "answer_id": 17447650, "author": "jmdana", "author_id": 1231093, "author_profile": "https://Stackoverflow.com/users/1231093", "pm_score": 4, "selected": false, "text": "<p>I'm developing a memory profiler for Python called memprof:</p>\n\n<p><a href=\"http://jmdana.github.io/memprof/\" rel=\"noreferrer\">http://jmdana.github.io/memprof/</a></p>\n\n<p>It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using:</p>\n\n<pre><code>from memprof import memprof\n</code></pre>\n\n<p>And decorate your method using:</p>\n\n<pre><code>@memprof\n</code></pre>\n\n<p>This is an example on how the plots look like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Krt9v.png\" alt=\"enter image description here\"></p>\n\n<p>The project is hosted in GitHub:</p>\n\n<p><a href=\"https://github.com/jmdana/memprof\" rel=\"noreferrer\">https://github.com/jmdana/memprof</a></p>\n" }, { "answer_id": 18625117, "author": "vstinner", "author_id": 2325489, "author_profile": "https://Stackoverflow.com/users/2325489", "pm_score": 3, "selected": false, "text": "<p>Try also the <a href=\"http://pytracemalloc.readthedocs.org/\" rel=\"noreferrer\">pytracemalloc project</a> which provides the memory usage per Python line number.</p>\n\n<p>EDIT (2014/04): It now has a Qt GUI to analyze snapshots.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6946/" ]
I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory. Google search shows a commercial one is [Python Memory Validator](http://www.softwareverify.com/python/memory/index.html) (Windows only). And open source ones are [PySizer](http://pysizer.8325.org/) and [Heapy](http://guppy-pe.sourceforge.net/#Heapy). I haven't tried anyone, so I wanted to know which one is the best considering: 1. Gives most details. 2. I have to do least or no changes to my code.
[guppy3](https://github.com/zhuyifei1999/guppy3/) is quite simple to use. At some point in your code, you have to write the following: ``` from guppy import hpy h = hpy() print(h.heap()) ``` This gives you some output like this: ``` Partition of a set of 132527 objects. Total size = 8301532 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 35144 27 2140412 26 2140412 26 str 1 38397 29 1309020 16 3449432 42 tuple 2 530 0 739856 9 4189288 50 dict (no owner) ``` You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse. There is a graphical browser as well, written in Tk. For Python 2.x, use [Heapy](http://guppy-pe.sourceforge.net/).
110,281
<p>How can I make a style have all of the properties of the style defined in <code>.a .b .c</code> except for <code>background-color</code> (or some other property)? This does not seem to work.</p> <pre><code>.a .b .c { background-color: #0000FF; color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } .a .b .c .d { background-color: green; } </code></pre>
[ { "answer_id": 110287, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": "<pre><code>.a, .b, .c {color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; }\n\n.a {background-color: red;}\n\n.b {background-color: blue;}\n\n.c {background-color: green;}\n</code></pre>\n" }, { "answer_id": 110291, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": true, "text": "<p>You would add the .d class selector as a selector for your first rule, then add a rule to redefine the background color for .d:</p>\n\n<pre><code>.a .b .c,\n.d { \n background-color: #0000FF;\n color: #ffffff;\n border: 1px solid #c0c0c0;\n margin-top: 4px;\n padding: 3px;\n text-align: center;\n font-weight: bold; \n}\n\n.d {\n background-color: green;\n}\n</code></pre>\n\n<p>That is the answer to the question that you've asked, but I have a feeling that this is not what you are looking for. Maybe you should post an example of your markup and tell us what styles you would like to see applied so we can help you better.</p>\n" }, { "answer_id": 110296, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 1, "selected": false, "text": "<p>It seems you've got things mixed up there. If you want to apply the properties in the first set of brackets to \".d\" as well it will need to be specified in the selector list. You also need to separate the selectors with commas so they become a list, not an inheritance.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;style type=\"text/css\"&gt;\n .a, .b, .c, .d { background-color: #0000FF; color: #FF0000; border: 1px solid #00FF00; font-weight: bold; }\n .d { background-color: white; }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body style=\"background-color: grey;\"&gt;\n &lt;p class=\"a\"&gt;Lorem ipsum dolor sit amet.&lt;/p&gt;\n &lt;p class=\"b\"&gt;Lorem ipsum dolor sit amet.&lt;/p&gt;\n &lt;p class=\"c\"&gt;Lorem ipsum dolor sit amet.&lt;/p&gt;\n &lt;p class=\"d\"&gt;Lorem ipsum dolor sit amet.&lt;/p&gt;\n &lt;/body&gt;\n &lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 110315, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I think you're thinking about this a little backwards, so let's try to sort out the language your are using. </p>\n\n<pre><code>.a .b .c{\n background-color: #0000FF;\n color: #ffffff;\n}\n</code></pre>\n\n<p>Looking at the above CSS, the \".a .b .c\" part is the <strong>selector</strong>, and the part between the braces is the style. That selector says 'find me all of the elements with a class with \"c\" who are inside of elements that have a class of \"b\" who are inside of elements with a class \"a\", and apply these styles to them' -- it's a rule the says which elements on the page will get the look you want. </p>\n\n<p>More than one selector can match the same element on the page, and there are rules for what order they are applied to the element (<a href=\"http://www.w3.org/TR/CSS2/cascade.html\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/cascade.html</a>). The simple rule is that more \"Specific\" selectors override less \"specific\" selectors. \"div.blueBanner p a:hover.highlight\" is much more \"specific\" than \".blueBanner\". If two rules have the same specificity, then the one that comes later in the CSS file overrides. </p>\n\n<p>html sample:</p>\n\n<pre><code>&lt;div class=\"a\"&gt;\n &lt;div class=\"b\"&gt;\n &lt;div class=\"c\"&gt;foo&lt;/div&gt;\n &lt;div class=\"c d\"&gt;bar&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>So, you have a selector \".a .b .c\" (as you listed above) and two elements (foo and bar) on the page match that selector, so they all get the background color and all the other styles you defined.</p>\n\n<p>Now, you also want the second element to have a green background color. It has another class assigned to it \"d\", so you can just define another selector which matches only that second element \".a .b .d\" and set's it's background-color. The \"bar\" element still gets all the other styles from the \".a .b .c\" selector (font, color, etc), but the background color from \".a .b .d\".</p>\n" }, { "answer_id": 12912679, "author": "Someone", "author_id": 1749718, "author_profile": "https://Stackoverflow.com/users/1749718", "pm_score": 2, "selected": false, "text": "<pre><code>.a, .b, .c, .d\n{\n background-color: green;\n}\n\n.a, .b, .c\n{\n background-color: #0000FF;\n color: #ffffff;\n border: 1px solid #c0c0c0;\n margin-top: 4px;\n padding: 3px;\n text-align: center;\n font-weight: bold;\n}\n</code></pre>\n\n<p>is this what you meant? <br />\norder of definitions is very meaningful, because latter will apply.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059/" ]
How can I make a style have all of the properties of the style defined in `.a .b .c` except for `background-color` (or some other property)? This does not seem to work. ``` .a .b .c { background-color: #0000FF; color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } .a .b .c .d { background-color: green; } ```
You would add the .d class selector as a selector for your first rule, then add a rule to redefine the background color for .d: ``` .a .b .c, .d { background-color: #0000FF; color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } .d { background-color: green; } ``` That is the answer to the question that you've asked, but I have a feeling that this is not what you are looking for. Maybe you should post an example of your markup and tell us what styles you would like to see applied so we can help you better.
110,305
<p>I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox?</p> <p>You can view the live page <a href="http://www.taxminimiser.com/beta/whats_included.php" rel="nofollow noreferrer">here</a>. I know, I'm working on positioning the sidebar. Ignore that for now.</p> <p>Markup is as follows:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/global.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/whats_included.css" /&gt; &lt;script type="text/javascript" src="script/compliant_target_blank.js"&gt;&lt;/script&gt; &lt;!--[if lte IE 5]&gt; &lt;script type="text/javascript" src="script/ie_5_unsupported_warning.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;!--[if gt IE 5]&gt; &lt;link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" /&gt; &lt;![endif]--&gt; &lt;title&gt; The Daily Plan-It, LLC - Home of the Tax MiniMiser &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include("includes/nav_bar.php") ?&gt; &lt;div id="content"&gt; &lt;img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" /&gt; &lt;div id="bordered_wrapper"&gt; &lt;h1&gt;Here's What You Get With The Tax MiniMiser!&lt;/h1&gt; &lt;h2&gt;24 Envelopes, 7-hole punched to fit one-at-a-time in your binder&lt;/h2&gt; &lt;ol&gt; &lt;li class="main_item"&gt; Business Income &amp;amp; Expense Record &lt;div class="preview_image"&gt; &lt;a href="previews/large/bier/front.html" rel="external"&gt; &lt;img src="images/small_previews/large/bier_preview.jpg" alt="" /&gt;&lt;br/&gt; Click to Preview! &lt;/a&gt; &lt;/div&gt; &lt;div class="details"&gt; &lt;ul&gt; &lt;li&gt;12 receipt envelopes with all the income &amp;amp; expense columns you need to transform your planner or binder into a daily tax journal!&lt;/li&gt; &lt;li&gt;Store daily receipts in the convenient pocket envelopes.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;p&gt;To get a free copy of the &amp;quot;20 Column Heading Guidelines&amp;quot;, &lt;a href="files/downloads/20_column_heading_guidelines.pdf"&gt;click here&lt;/a&gt; or call our Fax-on-Demand line at 888-829-8237.&lt;/p&gt; &lt;/li&gt; &lt;li class="main_item"&gt; Vehicle Mileage &amp;amp; Expense Record &lt;div class="preview_image"&gt; &lt;a href="previews/large/vme/front.html" rel="external"&gt; &lt;img src="images/small_previews/large/mileage_preview.jpg" alt=""/&gt;&lt;br/&gt; Click to Preview! &lt;/a&gt; &lt;/div&gt; &lt;div class="details"&gt; &lt;ul&gt; &lt;li&gt;12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).&lt;/li&gt; &lt;li&gt;Store daily receipts in the convenient pocket envelopes.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;p&gt;To get a free copy of the &amp;quot;Instructions for Vehicle Mileage &amp;amp; Expense Record&amp;quot;, &lt;a href="files/downloads/vehicle_record_instructions.pdf"&gt;click here&lt;/a&gt; or call our Fax-on-Demand line at 888-829-8237.&lt;/p&gt; &lt;/li&gt; &lt;li class="main_item"&gt; Annual Business Summary of Income and Expense &lt;div class="preview_image"&gt; &lt;a href="previews/large/cover/inside.html" rel="external"&gt; &lt;img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /&gt;&lt;br/&gt; Click to Preview! &lt;/a&gt; &lt;/div&gt; &lt;div class="details"&gt; &lt;ul&gt; &lt;li&gt;Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt; &lt;p class="end"&gt;To see previews of the small (6&amp;quot; x 8&amp;frac12;&amp;quot;) Tax MiniMisers, visit their respective pages &lt;a href="products.php"&gt;here.&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php include("includes/footer.php") ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And the CSS:</p> <pre><code>#content { background-color: white; } #bordered_wrapper { margin-left: 26px; background: top left no-repeat url(../images/borders/yellow-box-top.gif); } #bordered_wrapper h1, #bordered_wrapper h2 { margin-left: 20px; } #bordered_wrapper h1 { padding-top: 15px; margin-bottom: 0; } #bordered_wrapper h2 { margin-top: 0; font-size: 1.3em; } ol { font-size: 1.1em; } ul { list-style-type: disc; } li.main_item { width: 700px; clear: right; } li p { clear: both; margin-bottom: 20px; } .preview_image { width: 200px; float: right; text-align: center; margin-bottom: 10px; } .preview_image a { text-decoration: none; } .preview_image img { border-style: none; } .end { clear: right; padding-bottom: 25px; padding-left: 20px; background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif); } </code></pre>
[ { "answer_id": 110331, "author": "Abhi Beckert", "author_id": 19851, "author_profile": "https://Stackoverflow.com/users/19851", "pm_score": 0, "selected": false, "text": "<p>I just tested your example html in firefox 3/webkit nightly/internet explorer 7 and all of them rendered exactly the same with the number at the top where it should be.</p>\n\n<p>The problem is probably in your CSS, can you show us the actual page that is broken?</p>\n" }, { "answer_id": 110551, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>Same here, tested with IE6 on WinXP Pro SP3, it shows correctly. You should provide a snippet reproducing the problem, or a live Web page. Perhaps the environment counts, or the existing CSS, etc.</p>\n" }, { "answer_id": 131103, "author": "Dustman", "author_id": 16398, "author_profile": "https://Stackoverflow.com/users/16398", "pm_score": 5, "selected": true, "text": "<p>Congratulations, you are the victim of IE's <a href=\"http://msdn.microsoft.com/en-us/library/ms533776.aspx\" rel=\"noreferrer\">hasLayout</a> property.</p>\n\n<p>Short version: You've got it easy this time. Changes these rules:</p>\n\n<pre><code>...\n\nol {\n font-size: 1.1em;\n}\n\n...\n\nli.main_item {\n width: 700px;\n clear: right;\n}\n\n...\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>...\n\nol {\n font-size: 1.1em;\n width: 700px;\n}\n\n...\n\nli.main_item {\n clear: right;\n}\n\n...\n</code></pre>\n\n<p>And it's all good.</p>\n\n<p>Longer version: When you apply certain CSS rules to certain elements, IE 5.5+ gives those elements a property called \"hasLayout\" that changes how that element is rendered. Since hasLayout was a read-only property with no apparent purpose, it took quite a while before web designers caught on to the issue. Older sites (even Quirksmode.org!) still has pages that suggest twiddling padding, margins, or even using Javascript to fix these issues. If you can at all help it, don't do these things. Instead, see if you can find out what element is incorrectly being given hasLayout, and change the offending CSS so that the element no longer gets hasLayout. If that totally borks your page, use <a href=\"http://www.quirksmode.org/css/condcom.html\" rel=\"noreferrer\">conditional comments</a> to fix it just for IE. Here are some CSS rules that add \"hasLayout\" to an element that doesn't already have it:</p>\n\n<ul>\n<li>position: absolute</li>\n<li>float: left|right</li>\n<li>display: inline-block</li>\n<li>height: any value other than 'auto'</li>\n<li>zoom: any value other than 'normal' (MS proprietary)</li>\n<li>writing-mode: tb-rl (MS proprietary)</li>\n</ul>\n\n<p>As of IE7, overflow became a trigger for hasLayout.</p>\n\n<ul>\n<li>overflow: hidden|scroll|auto</li>\n</ul>\n\n<p>Longest version: read the following articles.</p>\n\n<ol>\n<li>Here's all the neat things Microsoft would like you do <a href=\"http://msdn.microsoft.com/en-us/library/bb250481.aspx\" rel=\"noreferrer\">by triggering \"hasLayout\"</a>. </li>\n<li>Here's the clean-language version of <a href=\"http://www.satzansatz.de/cssd/onhavinglayout\" rel=\"noreferrer\">what web designers thought about hasLayout</a> when they found out what was going on. Some of the same content, but includes CSS hacks and stuff.</li>\n</ol>\n" }, { "answer_id": 2213646, "author": "Jesse Dijkstra", "author_id": 267773, "author_profile": "https://Stackoverflow.com/users/267773", "pm_score": 0, "selected": false, "text": "<p>Actually, I ran into this bug as well. With my page it only happened after changing the numbering using javascript. The only somewhat real solution available is using:</p>\n\n<pre><code>vertical-align: top;\n</code></pre>\n\n<p>I honestly have no idea why IE7 is doing, however there is an easy way to fix it.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10140/" ]
I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox? You can view the live page [here](http://www.taxminimiser.com/beta/whats_included.php). I know, I'm working on positioning the sidebar. Ignore that for now. Markup is as follows: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="css/global.css" /> <link rel="stylesheet" type="text/css" href="css/whats_included.css" /> <script type="text/javascript" src="script/compliant_target_blank.js"></script> <!--[if lte IE 5]> <script type="text/javascript" src="script/ie_5_unsupported_warning.js"></script> <![endif]--> <!--[if gt IE 5]> <link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" /> <![endif]--> <title> The Daily Plan-It, LLC - Home of the Tax MiniMiser </title> </head> <body> <?php include("includes/nav_bar.php") ?> <div id="content"> <img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" /> <div id="bordered_wrapper"> <h1>Here's What You Get With The Tax MiniMiser!</h1> <h2>24 Envelopes, 7-hole punched to fit one-at-a-time in your binder</h2> <ol> <li class="main_item"> Business Income &amp; Expense Record <div class="preview_image"> <a href="previews/large/bier/front.html" rel="external"> <img src="images/small_previews/large/bier_preview.jpg" alt="" /><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>12 receipt envelopes with all the income &amp; expense columns you need to transform your planner or binder into a daily tax journal!</li> <li>Store daily receipts in the convenient pocket envelopes.</li> </ul> </div> <p>To get a free copy of the &quot;20 Column Heading Guidelines&quot;, <a href="files/downloads/20_column_heading_guidelines.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p> </li> <li class="main_item"> Vehicle Mileage &amp; Expense Record <div class="preview_image"> <a href="previews/large/vme/front.html" rel="external"> <img src="images/small_previews/large/mileage_preview.jpg" alt=""/><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).</li> <li>Store daily receipts in the convenient pocket envelopes.</li> </ul> </div> <p>To get a free copy of the &quot;Instructions for Vehicle Mileage &amp; Expense Record&quot;, <a href="files/downloads/vehicle_record_instructions.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p> </li> <li class="main_item"> Annual Business Summary of Income and Expense <div class="preview_image"> <a href="previews/large/cover/inside.html" rel="external"> <img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.</li> </ul> </div> </li> </ol> <p class="end">To see previews of the small (6&quot; x 8&frac12;&quot;) Tax MiniMisers, visit their respective pages <a href="products.php">here.</a></p> </div> </div> <?php include("includes/footer.php") ?> </body> </html> ``` And the CSS: ``` #content { background-color: white; } #bordered_wrapper { margin-left: 26px; background: top left no-repeat url(../images/borders/yellow-box-top.gif); } #bordered_wrapper h1, #bordered_wrapper h2 { margin-left: 20px; } #bordered_wrapper h1 { padding-top: 15px; margin-bottom: 0; } #bordered_wrapper h2 { margin-top: 0; font-size: 1.3em; } ol { font-size: 1.1em; } ul { list-style-type: disc; } li.main_item { width: 700px; clear: right; } li p { clear: both; margin-bottom: 20px; } .preview_image { width: 200px; float: right; text-align: center; margin-bottom: 10px; } .preview_image a { text-decoration: none; } .preview_image img { border-style: none; } .end { clear: right; padding-bottom: 25px; padding-left: 20px; background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif); } ```
Congratulations, you are the victim of IE's [hasLayout](http://msdn.microsoft.com/en-us/library/ms533776.aspx) property. Short version: You've got it easy this time. Changes these rules: ``` ... ol { font-size: 1.1em; } ... li.main_item { width: 700px; clear: right; } ... ``` To this: ``` ... ol { font-size: 1.1em; width: 700px; } ... li.main_item { clear: right; } ... ``` And it's all good. Longer version: When you apply certain CSS rules to certain elements, IE 5.5+ gives those elements a property called "hasLayout" that changes how that element is rendered. Since hasLayout was a read-only property with no apparent purpose, it took quite a while before web designers caught on to the issue. Older sites (even Quirksmode.org!) still has pages that suggest twiddling padding, margins, or even using Javascript to fix these issues. If you can at all help it, don't do these things. Instead, see if you can find out what element is incorrectly being given hasLayout, and change the offending CSS so that the element no longer gets hasLayout. If that totally borks your page, use [conditional comments](http://www.quirksmode.org/css/condcom.html) to fix it just for IE. Here are some CSS rules that add "hasLayout" to an element that doesn't already have it: * position: absolute * float: left|right * display: inline-block * height: any value other than 'auto' * zoom: any value other than 'normal' (MS proprietary) * writing-mode: tb-rl (MS proprietary) As of IE7, overflow became a trigger for hasLayout. * overflow: hidden|scroll|auto Longest version: read the following articles. 1. Here's all the neat things Microsoft would like you do [by triggering "hasLayout"](http://msdn.microsoft.com/en-us/library/bb250481.aspx). 2. Here's the clean-language version of [what web designers thought about hasLayout](http://www.satzansatz.de/cssd/onhavinglayout) when they found out what was going on. Some of the same content, but includes CSS hacks and stuff.
110,313
<p>If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure?</p> <p>With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups.</p> <p>Note that I don't consider it a good option to "make the developers push branches to a server" -- that's <a href="http://www.mattblodgett.com/2008/02/matt-blodgett-first-law-of-software.html" rel="nofollow noreferrer">tedious</a> and the developers will end up not doing it.</p> <p>Is there a common way around this problem?</p> <p><strong>Some clarification:</strong></p> <p>With a natively-central-server VCS then <em>everything</em> has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately.</p> <p>If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server".</p> <p>So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe?</p>
[ { "answer_id": 110319, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 1, "selected": false, "text": "<p>It's not uncommon to use a \"central\" server as an authority in DVCS, which also provides you the place to do your backups.</p>\n" }, { "answer_id": 110323, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 0, "selected": false, "text": "<p>You could have developer home directories mount remote devices over the local network. Then you only have to worry about making the network storage safe. Or maybe you could use something like <a href=\"http://www.getdropbox.com/\" rel=\"nofollow noreferrer\">DropBox</a> to copy your local repo elsewhere seamlessly.</p>\n" }, { "answer_id": 110324, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>I think it's a fallacy that using a distributed VCS necessarily means that you <em>must</em> use it in a completely distributed fashion. It's completely valid to set up a common git repository and tell everybody that repository is the official one. For normal development workflow, developers would pull changes from the common repository and update their own repositories. Only in the case of two developers actively collaborating on a specific feature might they need to pull changes directly from each other.</p>\n\n<p>With more than a few developers working on a project, it would be seriously tedious to have to remember to pull changes from everybody else. What would you do if you <em>didn't</em> have a central repository?</p>\n\n<p>At work we have a backup solution that backs up everybody's working directories daily, and writes the whole lot to a DVD weekly. So, although we have a central repository, each individual one is backed up too.</p>\n" }, { "answer_id": 110619, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 5, "selected": true, "text": "<p>I think that you will find that in practice developers will prefer to use a central repository than pushing and pulling between each other's local repositories. Once you've cloned a central repository, while working on any tracking branches, fetching and pushing are trivial commands. Adding half a dozen remotes to all your colleagues' local repositories is a pain and these repositories may not always be accessible (switched off, on a laptop taken home, etc.).</p>\n\n<p>At some point, if you are all working on the same project, all the work needs to be integrated. This means that you need an integration branch where all the changes come together. This naturally needs to be somewhere accessible by all the developers, it doesn't belong, for example, on the lead developer's laptop.</p>\n\n<p>Once you've set up a central repository you can use a cvs/svn style workflow to check in and update. cvs update becomes git fetch and rebase if you have local changes or just git pull if you don't. cvs commit becomes git commit and git push.</p>\n\n<p>With this setup you are in a similar position with your fully centralized VCS system. Once developers submit their changes (git push), which they need to do to be visible to the rest of the team, they are on the central server and will be backed up.</p>\n\n<p>What takes discipline in both cases is preventing developers keeping long running changes out of the central repository. Most of us have probably worked in a situation where one developer is working on feature 'x' which needs a fundamental change in some core code. The change will cause everyone else to need to completely rebuild but the feature isn't ready for the main stream yet so he just keeps it checked out until a suitable point in time.</p>\n\n<p>The situation is very similar in both situations although there are some practical differences. Using git, because you get to perform local commits and can manage local history, the need to push to the central repository may not be felt as much by the individual developer as with something like cvs.</p>\n\n<p>On the other hand, the use of local commits can be used as an advantage. Pushing all local commits to a safe place on the central repository should not be very difficult. Local branches can be stored in a developer specific tag namespace.</p>\n\n<p>For example, for Joe Bloggs, An alias could be made in his local repository to perform something like the following in response to (e.g.) <code>git mybackup</code>.</p>\n\n<pre><code>git push origin +refs/heads/*:refs/jbloggs/*\n</code></pre>\n\n<p>This is a single command that can be used at any point (such as the end of the day) to make sure that all his local changes are safely backed up.</p>\n\n<p>This helps with all sorts of disasters. Joe's machine blows up and he can use another machine and fetch is saved commits and carry on from where he left off. Joe's ill? Fred can fetch Joe's branches to grab that 'must have' fix that he made yesterday but didn't have a chance to test against master.</p>\n\n<p>To go back to the original question. Does there need to be a difference between dVCS and centralized VCS? You say that half-implemented features and bugfixes will not end up on the central repository in the dVCS case but I would contend that there need be no difference.</p>\n\n<p>I have seen many cases where a half-implemented feature stays on one developers working box when using centralized VCS. It either takes a policy that allows half written features to be checked in to the main stream or a decision has to be made to create a central branch.</p>\n\n<p>In the dVCS the same thing can happen, but the same decision should be made. If there is important but incomplete work, it needs to be saved centrally. The advantage of git is that creating this central branch is almost trivial.</p>\n" }, { "answer_id": 110812, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 0, "selected": false, "text": "<p>All developers on your team can have their own branches on the server as well (can be per ticket or just per dev, etc). This way they don't break the build in master branch but they still get to push their work in progress to the server that gets backed up.</p>\n\n<p><a href=\"http://programblings.com/2008/08/06/time-to-git-collaborating-with-git_remote_branch/\" rel=\"nofollow noreferrer\">My own git_remote_branch</a> tool may come in handy for that kind of workflow (Note that it requires Ruby). It helps manipulating remote branches.</p>\n\n<p>As a side note, talking about repo safety, on your server you can set up a post-commit hook that does a simple git clone or git push to another machine... You get an up to date backup after each commit!</p>\n" }, { "answer_id": 125382, "author": "Luuk Paulussen", "author_id": 10394, "author_profile": "https://Stackoverflow.com/users/10394", "pm_score": 0, "selected": false, "text": "<p>We use rsync to backup the individual developers .git directories to a directory on the server. This is setup using wrapper scripts around git clone, and the post-commit etc. hooks.</p>\n\n<p>Because it is done in the post-* hooks, developers don't need to remember to do it manually. And because we use rsync with a timeout, if the server goes down or the user is working remotely, they can still work.</p>\n" }, { "answer_id": 697730, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 1, "selected": false, "text": "<p>I find this question to be a little bit bizarre. Assuming you're using a non-distributed version control system, such as CVS, you will have a repository on the central server and work in progress on developers' servers. How do you back up the repository? How do you back up developers' work in progress? The answer to those questions is exactly what you have to do to handle your question.</p>\n\n<p>Using distributed version control, repositories on developers' servers are just work in progress. Do you want to back it up? Then back it up! It's as simple as that.</p>\n\n<p>We have an automated backup system that grabs any directories off our our machines which we specify, so I add any repositories and working copies on my machine to that last, including both git and CVS repositories.</p>\n\n<p>By the way, if you are using distributed version control in a company releasing a product, then you <strong>will</strong> have a central repository. It's the one you release from. It might not be on a special server; it might be on some developer's hard drive. But the repository you release from is the central repository. (I suppose if you haven't released, yet, you might not have one, yet.) I kind of feel that all projects have one or more central repositories. (And really if they have more than one, it's two projects and one is a fork.) This goes for open source as well.</p>\n\n<p>Even if you didn't have a central repository, the solution is the same: back up work on developer's machines. You should have been doing that anyway. The fact that the work in progress is in distributed repositories instead of CVS working copies or straight nonversioned directories is immaterial.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure? With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups. Note that I don't consider it a good option to "make the developers push branches to a server" -- that's [tedious](http://www.mattblodgett.com/2008/02/matt-blodgett-first-law-of-software.html) and the developers will end up not doing it. Is there a common way around this problem? **Some clarification:** With a natively-central-server VCS then *everything* has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately. If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server". So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe?
I think that you will find that in practice developers will prefer to use a central repository than pushing and pulling between each other's local repositories. Once you've cloned a central repository, while working on any tracking branches, fetching and pushing are trivial commands. Adding half a dozen remotes to all your colleagues' local repositories is a pain and these repositories may not always be accessible (switched off, on a laptop taken home, etc.). At some point, if you are all working on the same project, all the work needs to be integrated. This means that you need an integration branch where all the changes come together. This naturally needs to be somewhere accessible by all the developers, it doesn't belong, for example, on the lead developer's laptop. Once you've set up a central repository you can use a cvs/svn style workflow to check in and update. cvs update becomes git fetch and rebase if you have local changes or just git pull if you don't. cvs commit becomes git commit and git push. With this setup you are in a similar position with your fully centralized VCS system. Once developers submit their changes (git push), which they need to do to be visible to the rest of the team, they are on the central server and will be backed up. What takes discipline in both cases is preventing developers keeping long running changes out of the central repository. Most of us have probably worked in a situation where one developer is working on feature 'x' which needs a fundamental change in some core code. The change will cause everyone else to need to completely rebuild but the feature isn't ready for the main stream yet so he just keeps it checked out until a suitable point in time. The situation is very similar in both situations although there are some practical differences. Using git, because you get to perform local commits and can manage local history, the need to push to the central repository may not be felt as much by the individual developer as with something like cvs. On the other hand, the use of local commits can be used as an advantage. Pushing all local commits to a safe place on the central repository should not be very difficult. Local branches can be stored in a developer specific tag namespace. For example, for Joe Bloggs, An alias could be made in his local repository to perform something like the following in response to (e.g.) `git mybackup`. ``` git push origin +refs/heads/*:refs/jbloggs/* ``` This is a single command that can be used at any point (such as the end of the day) to make sure that all his local changes are safely backed up. This helps with all sorts of disasters. Joe's machine blows up and he can use another machine and fetch is saved commits and carry on from where he left off. Joe's ill? Fred can fetch Joe's branches to grab that 'must have' fix that he made yesterday but didn't have a chance to test against master. To go back to the original question. Does there need to be a difference between dVCS and centralized VCS? You say that half-implemented features and bugfixes will not end up on the central repository in the dVCS case but I would contend that there need be no difference. I have seen many cases where a half-implemented feature stays on one developers working box when using centralized VCS. It either takes a policy that allows half written features to be checked in to the main stream or a decision has to be made to create a central branch. In the dVCS the same thing can happen, but the same decision should be made. If there is important but incomplete work, it needs to be saved centrally. The advantage of git is that creating this central branch is almost trivial.
110,314
<p>So, I am using the Linq entity framework. I have 2 entities: <code>Content</code> and <code>Tag</code>. They are in a many-to-many relationship with one another. <code>Content</code> can have many <code>Tags</code> and <code>Tag</code> can have many <code>Contents</code>. So I am trying to write a query to select all contents where any tags names are equal to <code>blah</code></p> <p>The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for <code>Contains</code> (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&amp;SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&amp;SiteID=1</a></p> <h2>Edit 1</h2> <p><a href="https://stackoverflow.com/questions/110314/linq-to-entities-building-where-clauses-to-test-collections-within-a-many-to-ma#131551">I ended up finding my own answer.</a></p>
[ { "answer_id": 110348, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "<pre><code>tags.Select(testTag =&gt; testTag.Name)\n</code></pre>\n\n<p>Where does the tags variable gets initialized from? What is it?</p>\n" }, { "answer_id": 110363, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 2, "selected": false, "text": "<p>This is what the question itself asks for:</p>\n\n<pre><code>contentQuery.Where(\n content =&gt; content.Tags.Any(tag =&gt; tag.Name == \"blah\")\n);\n</code></pre>\n\n<p>I'm not sure what the thought process was to get to the questioner's code, really, and I'm not entirely sure exactly what its really doing. The one thing I'm really sure of is that .AsQueryable() call is completely unnecessary -- either .Tags is already an IQueryable, or the .AsQueryable() is just going to fake it for you -- adding extra calls in where there doesn't need to be any.</p>\n" }, { "answer_id": 111544, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>Summing it up...</p>\n\n<pre><code>contentQuery.Where(\n content =&gt; content.Tags.Any(tag =&gt; tags.Any(t =&gt; t.Name == tag.Name))\n);\n</code></pre>\n\n<p>So is that what you're expecting?</p>\n\n<p>I'm a little confused.</p>\n" }, { "answer_id": 113215, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 0, "selected": false, "text": "<p><em>NOTE: please edit the question itself, rather than replying with an answer -- this is not a discussion thread, and they can re-order themselves at any time</em></p>\n\n<p>If you're searching for all Contents that are marked with any one of a set of tags:</p>\n\n<pre><code>IEnumerable&lt;Tag&gt; otherTags;\n...\nvar query = from content in contentQuery\n where content.Tags.Intersection(otherTags).Any()\n select content;\n</code></pre>\n\n<p>It looks like you might be using LINQ To SQL, in which case it might be better if you write a stored procedure to do this one: using LINQ to do this will probably not run on SQL Server -- it's very likely it will try to pull down everything from <code>contentQuery</code> and fetch all the <code>.Tags</code> collections. I'd have to actually set up a server to check that, though.</p>\n" }, { "answer_id": 126832, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The error is related to the 'tags' variable. LINQ to Entities does not support a parameter that is a collection of values. Simply calling tags.AsQueryable() -- as suggested in an ealier answer -- will not work either because the default in-memory LINQ query provider is not compatible with LINQ to Entities (or other relational providers).</p>\n\n<p>As a workaround, you can manually build up the filter using the expression API (see <a href=\"http://forums.microsoft.com/forums/ShowPost.aspx?PostID=3914701&amp;SiteID=1\" rel=\"nofollow noreferrer\">this forum post</a>) and apply it as follows:</p>\n\n<pre><code>var filter = BuildContainsExpression&lt;Element, string&gt;(e =&gt; e.Name, tags.Select(t =&gt; t.Name));\nvar query = source.Where(e =&gt; e.NestedValues.Any(filter));\n</code></pre>\n" }, { "answer_id": 131551, "author": "Phobis", "author_id": 19854, "author_profile": "https://Stackoverflow.com/users/19854", "pm_score": 5, "selected": true, "text": "<p>After reading about the <a href=\"http://www.albahari.com/nutshell/predicatebuilder.aspx\" rel=\"noreferrer\">PredicateBuilder</a>, reading all of the wonderful posts that people sent to me, posting on other sites, and then reading more on <a href=\"http://blogs.msdn.com/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx\" rel=\"noreferrer\">Combining Predicates</a> and <a href=\"http://msdn.microsoft.com/en-us/library/bb738681.aspx\" rel=\"noreferrer\">Canonical Function Mapping</a>.. oh and I picked up a bit from <a href=\"http://tomasp.net/blog/linq-expand.aspx\" rel=\"noreferrer\">Calling functions in LINQ queries</a> (some of these classes were taken from these pages). </p>\n\n<p>I FINALLY have a solution!!! Though there is a piece that is a bit hacked... </p>\n\n<p>Let's get the hacked piece over with :(</p>\n\n<p>I had to use reflector and copy the ExpressionVisitor class that is marked as internal. I then had to make some minor changes to it, to get it to work. I had to create two exceptions (because it was newing internal exceptions. I also had to change the ReadOnlyCollection() method's return from:</p>\n\n<pre><code>return sequence.ToReadOnlyCollection&lt;Expression&gt;();\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>return sequence.AsReadOnly();\n</code></pre>\n\n<p>I would post the class, but it is quite large and I don't want to clutter this post any more than it's already going to be. I hope that in the future that class can be removed from my library and that Microsoft will make it public. Moving on...</p>\n\n<p>I added a ParameterRebinder class:</p>\n\n<pre><code>public class ParameterRebinder : ExpressionVisitor {\n private readonly Dictionary&lt;ParameterExpression, ParameterExpression&gt; map;\n\n public ParameterRebinder(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map) {\n this.map = map ?? new Dictionary&lt;ParameterExpression, ParameterExpression&gt;();\n }\n\n public static Expression ReplaceParameters(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map, Expression exp) {\n return new ParameterRebinder(map).Visit(exp);\n }\n\n internal override Expression VisitParameter(ParameterExpression p) {\n ParameterExpression replacement;\n if (map.TryGetValue(p, out replacement)) {\n p = replacement;\n }\n return base.VisitParameter(p);\n }\n }\n</code></pre>\n\n<p>Then I added a ExpressionExtensions class:</p>\n\n<pre><code>public static class ExpressionExtensions {\n public static Expression&lt;T&gt; Compose&lt;T&gt;(this Expression&lt;T&gt; first, Expression&lt;T&gt; second, Func&lt;Expression, Expression, Expression&gt; merge) {\n // build parameter map (from parameters of second to parameters of first)\n var map = first.Parameters.Select((f, i) =&gt; new { f, s = second.Parameters[i] }).ToDictionary(p =&gt; p.s, p =&gt; p.f);\n\n // replace parameters in the second lambda expression with parameters from the first\n var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);\n\n // apply composition of lambda expression bodies to parameters from the first expression \n return Expression.Lambda&lt;T&gt;(merge(first.Body, secondBody), first.Parameters);\n }\n\n public static Expression&lt;Func&lt;T, bool&gt;&gt; And&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second) {\n return first.Compose(second, Expression.And);\n }\n\n public static Expression&lt;Func&lt;T, bool&gt;&gt; Or&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second) {\n return first.Compose(second, Expression.Or);\n }\n }\n</code></pre>\n\n<p>And the last class I added was PredicateBuilder:</p>\n\n<pre><code>public static class PredicateBuilder {\n public static Expression&lt;Func&lt;T, bool&gt;&gt; True&lt;T&gt;() { return f =&gt; true; }\n public static Expression&lt;Func&lt;T, bool&gt;&gt; False&lt;T&gt;() { return f =&gt; false; }\n\n}\n</code></pre>\n\n<p>This is my result... I was able to execute this code and get back the resulting \"content\" entities that have matching \"tag\" entities from the tags that I was searching for!</p>\n\n<pre><code> public static IList&lt;Content&gt; GetAllContentByTags(IList&lt;Tag&gt; tags) {\n IQueryable&lt;Content&gt; contentQuery = ...\n\n Expression&lt;Func&lt;Content, bool&gt;&gt; predicate = PredicateBuilder.False&lt;Content&gt;();\n\n foreach (Tag individualTag in tags) {\n Tag tagParameter = individualTag;\n predicate = predicate.Or(p =&gt; p.Tags.Any(tag =&gt; tag.Name.Equals(tagParameter.Name)));\n }\n\n IQueryable&lt;Content&gt; resultExpressions = contentQuery.Where(predicate);\n\n return resultExpressions.ToList();\n }\n</code></pre>\n\n<p>Please let me know if anyone needs help with this same thing, if you would like me to send you files for this, or just need more info.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
So, I am using the Linq entity framework. I have 2 entities: `Content` and `Tag`. They are in a many-to-many relationship with one another. `Content` can have many `Tags` and `Tag` can have many `Contents`. So I am trying to write a query to select all contents where any tags names are equal to `blah` The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for `Contains` (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&SiteID=1> Edit 1 ------ [I ended up finding my own answer.](https://stackoverflow.com/questions/110314/linq-to-entities-building-where-clauses-to-test-collections-within-a-many-to-ma#131551)
After reading about the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx), reading all of the wonderful posts that people sent to me, posting on other sites, and then reading more on [Combining Predicates](http://blogs.msdn.com/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx) and [Canonical Function Mapping](http://msdn.microsoft.com/en-us/library/bb738681.aspx).. oh and I picked up a bit from [Calling functions in LINQ queries](http://tomasp.net/blog/linq-expand.aspx) (some of these classes were taken from these pages). I FINALLY have a solution!!! Though there is a piece that is a bit hacked... Let's get the hacked piece over with :( I had to use reflector and copy the ExpressionVisitor class that is marked as internal. I then had to make some minor changes to it, to get it to work. I had to create two exceptions (because it was newing internal exceptions. I also had to change the ReadOnlyCollection() method's return from: ``` return sequence.ToReadOnlyCollection<Expression>(); ``` To: ``` return sequence.AsReadOnly(); ``` I would post the class, but it is quite large and I don't want to clutter this post any more than it's already going to be. I hope that in the future that class can be removed from my library and that Microsoft will make it public. Moving on... I added a ParameterRebinder class: ``` public class ParameterRebinder : ExpressionVisitor { private readonly Dictionary<ParameterExpression, ParameterExpression> map; public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) { this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>(); } public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp) { return new ParameterRebinder(map).Visit(exp); } internal override Expression VisitParameter(ParameterExpression p) { ParameterExpression replacement; if (map.TryGetValue(p, out replacement)) { p = replacement; } return base.VisitParameter(p); } } ``` Then I added a ExpressionExtensions class: ``` public static class ExpressionExtensions { public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge) { // build parameter map (from parameters of second to parameters of first) var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); // replace parameters in the second lambda expression with parameters from the first var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // apply composition of lambda expression bodies to parameters from the first expression return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters); } public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.And); } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.Or); } } ``` And the last class I added was PredicateBuilder: ``` public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T>() { return f => true; } public static Expression<Func<T, bool>> False<T>() { return f => false; } } ``` This is my result... I was able to execute this code and get back the resulting "content" entities that have matching "tag" entities from the tags that I was searching for! ``` public static IList<Content> GetAllContentByTags(IList<Tag> tags) { IQueryable<Content> contentQuery = ... Expression<Func<Content, bool>> predicate = PredicateBuilder.False<Content>(); foreach (Tag individualTag in tags) { Tag tagParameter = individualTag; predicate = predicate.Or(p => p.Tags.Any(tag => tag.Name.Equals(tagParameter.Name))); } IQueryable<Content> resultExpressions = contentQuery.Where(predicate); return resultExpressions.ToList(); } ``` Please let me know if anyone needs help with this same thing, if you would like me to send you files for this, or just need more info.
110,325
<p>Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped.</p>
[ { "answer_id": 110372, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 4, "selected": true, "text": "<p>Create a trigger that processes on INSERT. This trigger will do a validation check on your date field. If it fails the validation, then do an insert into your separate table, and you can also choose to continue the insert or not allow it to go through.</p>\n\n<p>an <strong>important</strong> note: by default triggers do not fire on bulk inserts (BCP &amp; SSIS included). To get this to work, you'll need to specify that you want the trigger to fire, using something like:</p>\n\n<pre><code>BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS )\n</code></pre>\n" }, { "answer_id": 110382, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 0, "selected": false, "text": "<p>You're saying there's a column full of dates in the file, and you want that data to go into a column of type \"datetime\" in a table in a SQL database? And it'll blow up if one of the values from the file isn't a valid date? I just wanted to make sure I understand this right.</p>\n\n<p>You could create another, temporary, table in the SQL database, of the same structure as the table you want the data from the file to end up in, but with every column of type varchar(255) or something. Sucking the data out of the file and into that table shouldn't fail whether any of the dates is valid or not.</p>\n\n<p>Then, in SQL, you could massage the data however you want. You could use a <a href=\"http://www.jackdonnell.com/articles/SQL_CURSOR.htm\" rel=\"nofollow noreferrer\">cursor</a> to select all of the records from the temporary table and loop through them. For each record, you could use the T-SQL <a href=\"http://doc.ddart.net/mssql/sql70/ia-iz_32.htm\" rel=\"nofollow noreferrer\">ISDATE</a> function to conditionally insert the values from the current record into one table or another.</p>\n\n<p>I'm saying, get the data into the database and then run script like this:</p>\n\n<pre><code>// **this is untested, there could be syntax errors**\n\n// if we have tables like this:\nCREATE TABLE tempoary (id VARCHAR(255), theDate VARCHAR(255), somethingElse VARCHAR(255))\nCREATE TABLE theGood (id INT, theDate DATETIME, somethingElse VARCHAR(255))\nCREATE TABLE theBad (id INT, theDate VARCHAR(255))\n\n// then after getting the data into [tempoary], do this:\nDECLARE tempCursor CURSOR\nFOR SELECT id, theDate, somethingElse FROM temporary\n\nOPEN tempCursor\n\nDECLARE @id VARCHAR(255)\nDECLARE @theDate VARCHAR(255)\nDECLARE @somethingElse VARCHAR(255)\n\nFETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse\nWhile (@@FETCH_STATUS &lt;&gt; -1)\nBEGIN\n IF ISDATE(@theDate)\n BEGIN\n INSERT INTO theGood (id, theDate, somethingElse)\n VALUES (CONVERT(INT, @id), CONVERT(DATETIME, theDate), somethingElse)\n END\n ELSE\n BEGIN\n INSERT INTO theBad (id, theDate)\n VALUES (CONVERT(INT, @id), theDate)\n END\n FETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse\nEND\nCLOSE tempCursor\nDEALLOCATE tempCursor\n</code></pre>\n" }, { "answer_id": 110527, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "<p>Yeah, if you are using DTS, you should just import into a staging table that uses varchar instead of dates and then massage the data into the proper tables afterwords.</p>\n" }, { "answer_id": 111989, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>The problem with What Matt said is that you should not use a cursor to manipulate the data afterwards especially if you have millions of records. CUrsoprs are extremely inefficient and should be avoided.</p>\n\n<p>Use batch processing instead.</p>\n\n<p>But by all means use his idea of a staging table. I wouldn' ever consider importing directly into a production table as too many things can happen over time to change the data in the input file and cause problems.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19857/" ]
Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped.
Create a trigger that processes on INSERT. This trigger will do a validation check on your date field. If it fails the validation, then do an insert into your separate table, and you can also choose to continue the insert or not allow it to go through. an **important** note: by default triggers do not fire on bulk inserts (BCP & SSIS included). To get this to work, you'll need to specify that you want the trigger to fire, using something like: ``` BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS ) ```
110,332
<p>I have an <code>NSArray</code> and I'd like to create a new <code>NSArray</code> with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a <code>BOOL</code>.</p> <p>I can create an <code>NSMutableArray</code>, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.</p> <p>Is there a better way?</p>
[ { "answer_id": 110343, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 8, "selected": true, "text": "<p><code>NSArray</code> and <code>NSMutableArray</code> provide methods to filter array contents. <code>NSArray</code> provides <strong>filteredArrayUsingPredicate:</strong> which returns a new array containing objects in the receiver that match the specified predicate. <code>NSMutableArray</code> adds <strong>filterUsingPredicate:</strong> which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.</p>\n\n<pre><code>NSMutableArray *array =\n [NSMutableArray arrayWithObjects:@\"Bill\", @\"Ben\", @\"Chris\", @\"Melissa\", nil];\n\nNSPredicate *bPredicate =\n [NSPredicate predicateWithFormat:@\"SELF beginswith[c] 'b'\"];\nNSArray *beginWithB =\n [array filteredArrayUsingPredicate:bPredicate];\n// beginWithB contains { @\"Bill\", @\"Ben\" }.\n\nNSPredicate *sPredicate =\n [NSPredicate predicateWithFormat:@\"SELF contains[c] 's'\"];\n[array filteredArrayUsingPredicate:sPredicate];\n// array now contains { @\"Chris\", @\"Melissa\" }\n</code></pre>\n" }, { "answer_id": 308108, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 4, "selected": false, "text": "<p>Assuming that your objects are all of a similar type you could add a method as a category of their base class that calls the function you're using for your criteria. Then create an NSPredicate object that refers to that method.</p>\n\n<p>In some category define your method that uses your function</p>\n\n<pre><code>@implementation BaseClass (SomeCategory)\n- (BOOL)myMethod {\n return someComparisonFunction(self, whatever);\n}\n@end\n</code></pre>\n\n<p>Then wherever you'll be filtering:</p>\n\n<pre><code>- (NSArray *)myFilteredObjects {\n NSPredicate *pred = [NSPredicate predicateWithFormat:@\"myMethod = TRUE\"];\n return [myArray filteredArrayUsingPredicate:pred];\n}\n</code></pre>\n\n<p>Of course, if your function only compares against properties reachable from within your class it may just be easier to convert the function's conditions to a predicate string.</p>\n" }, { "answer_id": 3857136, "author": "Clay Bridges", "author_id": 45813, "author_profile": "https://Stackoverflow.com/users/45813", "pm_score": 6, "selected": false, "text": "<p>If you are OS X 10.6/iOS 4.0 or later, you're probably better off with blocks than NSPredicate. See <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html\" rel=\"noreferrer\"><code>-[NSArray indexesOfObjectsPassingTest:]</code></a> or write your own category to add a handy <code>-select:</code> or <code>-filter:</code> method (<a href=\"http://parmanoir.com/8_ways_to_use_Blocks_in_Snow_Leopard\" rel=\"noreferrer\">example</a>).</p>\n\n<p>Want somebody else to write that category, test it, etc.? Check out <a href=\"http://zwaldowski.github.com/BlocksKit\" rel=\"noreferrer\">BlocksKit</a> (<a href=\"http://cocoadocs.org/docsets/BlocksKit/2.2.0/Categories/NSArray+BlocksKit.html\" rel=\"noreferrer\">array docs</a>). And there are <strong>many</strong> more examples to be found by, say, searching for e.g. <a href=\"http://www.google.com/search?client=safari&amp;rls=en&amp;q=nsarray+block+category+select&amp;ie=UTF-8&amp;oe=UTF-8\" rel=\"noreferrer\">\"nsarray block category select\"</a>.</p>\n" }, { "answer_id": 13288927, "author": "pckill", "author_id": 934710, "author_profile": "https://Stackoverflow.com/users/934710", "pm_score": 6, "selected": false, "text": "<p>Based on an answer by Clay Bridges, here is an example of filtering using blocks (change <code>yourArray</code> to your array variable name and <code>testFunc</code> to the name of your testing function):</p>\n\n<pre><code>yourArray = [yourArray objectsAtIndexes:[yourArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {\n return [self testFunc:obj];\n}]];\n</code></pre>\n" }, { "answer_id": 15809114, "author": "Durai Amuthan.H", "author_id": 730807, "author_profile": "https://Stackoverflow.com/users/730807", "pm_score": 2, "selected": false, "text": "<p><code>NSPredicate</code> is nextstep's way of constructing condition to filter a collection (<code>NSArray</code>, <code>NSSet</code>, <code>NSDictionary</code>).</p>\n\n<p>For example consider two arrays <code>arr</code> and <code>filteredarr</code>:</p>\n\n<pre><code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"SELF contains[c] %@\",@\"c\"];\n\nfilteredarr = [NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];\n</code></pre>\n\n<p>the filteredarr will surely have the items that contains the character c alone.</p>\n\n<p>to make it easy to remember those who little sql background it is </p>\n\n<pre><code>*--select * from tbl where column1 like '%a%'--*\n</code></pre>\n\n<p><strong>1)select * from tbl</strong> --> collection</p>\n\n<p><strong>2)column1 like '%a%'</strong> --> <code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"SELF contains[c] %@\",@\"c\"];</code></p>\n\n<p><strong>3)select * from tbl where column1 like '%a%'</strong> --></p>\n\n<pre><code>[NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];\n</code></pre>\n\n<p>I hope this helps </p>\n" }, { "answer_id": 19517418, "author": "Stuart", "author_id": 429427, "author_profile": "https://Stackoverflow.com/users/429427", "pm_score": 7, "selected": false, "text": "<p>There are loads of ways to do this, but by far the neatest is surely using <code>[NSPredicate predicateWithBlock:]</code>:</p>\n<pre><code>NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {\n return [object shouldIKeepYou]; // Return YES for each object you want in filteredArray.\n}]];\n</code></pre>\n<p>I think that's about as concise as it gets.</p>\n<hr />\n<h2>Swift:</h2>\n<p>For those working with <code>NSArray</code>s in Swift, you may prefer this <em>even more</em> concise version:</p>\n<pre><code>let filteredArray = array.filter { $0.shouldIKeepYou() }\n</code></pre>\n<p><code>filter</code> is just a method on <code>Array</code> (<code>NSArray</code> is implicitly bridged to Swift’s <code>Array</code>). It takes one argument: a closure that takes one object in the array and returns a <code>Bool</code>. In your closure, just return <code>true</code> for any objects you want in the filtered array.</p>\n" }, { "answer_id": 39212304, "author": "Jordi Puigdellívol", "author_id": 478020, "author_profile": "https://Stackoverflow.com/users/478020", "pm_score": 0, "selected": false, "text": "<p>Checkout this library</p>\n\n<p><a href=\"https://github.com/BadChoice/Collection\" rel=\"nofollow\">https://github.com/BadChoice/Collection</a></p>\n\n<p>It comes with lots of easy array functions to never write a loop again</p>\n\n<p>So you can just do:</p>\n\n<pre><code>NSArray* youngHeroes = [self.heroes filter:^BOOL(Hero *object) {\n return object.age.intValue &lt; 20;\n}];\n</code></pre>\n\n<p>or</p>\n\n<pre><code>NSArray* oldHeroes = [self.heroes reject:^BOOL(Hero *object) {\n return object.age.intValue &lt; 20;\n}];\n</code></pre>\n" }, { "answer_id": 53385048, "author": "jalmatari", "author_id": 1896440, "author_profile": "https://Stackoverflow.com/users/1896440", "pm_score": 0, "selected": false, "text": "<p>The Best and easy Way is to create this method And Pass Array And Value:</p>\n\n<pre><code>- (NSArray *) filter:(NSArray *)array where:(NSString *)key is:(id)value{\n NSMutableArray *temArr=[[NSMutableArray alloc] init];\n for(NSDictionary *dic in self)\n if([dic[key] isEqual:value])\n [temArr addObject:dic];\n return temArr;\n}\n</code></pre>\n" }, { "answer_id": 65767962, "author": "Dan Rosenstark", "author_id": 8047, "author_profile": "https://Stackoverflow.com/users/8047", "pm_score": 0, "selected": false, "text": "<p>Another category method you could use:</p>\n<pre><code>- (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block {\n NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {\n return block(obj);\n }];\n\n return [self objectsAtIndexes:filteredIndexes];\n}\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
I have an `NSArray` and I'd like to create a new `NSArray` with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a `BOOL`. I can create an `NSMutableArray`, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it. Is there a better way?
`NSArray` and `NSMutableArray` provide methods to filter array contents. `NSArray` provides **filteredArrayUsingPredicate:** which returns a new array containing objects in the receiver that match the specified predicate. `NSMutableArray` adds **filterUsingPredicate:** which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example. ``` NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil]; NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"]; NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate]; // beginWithB contains { @"Bill", @"Ben" }. NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 's'"]; [array filteredArrayUsingPredicate:sPredicate]; // array now contains { @"Chris", @"Melissa" } ```
110,336
<p>Here's my issue: I need to close a process, already running, from a C# program. The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never have a main window. </p> <p>The other requirement that I have is that the application be <strong>closed</strong> not <strong>killed</strong>. I need it to write it's memory buffers to disk - and killing it causes data loss.</p> <p>Here's what I tried so far:</p> <pre><code> foreach (Process proc in Process.GetProcesses()) { if (proc.ProcessName.ToLower().StartsWith("myapp")) { if (proc.MainWindowHandle.ToInt32() != 0) { proc.CloseMainWindow(); proc.Close(); //proc.Kill(); &lt;--- not good! } } } </code></pre> <p>I've added the <strong>if</strong> clause, after discovering that <strong>MainWindowHandle == 0</strong> when the window was minimized. Removing the <strong>if</strong> doesn't help. Neither the <strong>CloseMainWindow()</strong> nor the <strong>Close()</strong> work. The <strong>Kill()</strong> does, but as mentioned above - it's not what I need.</p> <p>Any idea would be accepted, including the use of arcane Win32 API functions :)</p>
[ { "answer_id": 110401, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 1, "selected": false, "text": "<p>If it's on the taskbar, it'll have a window. Or did you mean that it's in the taskbar notification area (aka the SysTray)? In which case, it'll still have a window.</p>\n\n<p>Win32 applications don't really have a \"main window\", except by convention (the main window is the one that calls PostQuitMessage in response to WM_DESTROY, causing the message loop to exit).</p>\n\n<p>With the program running, run Spy++. To find all of the windows owned by a process, you should select Spy -> Processes from the main menu. This will display a tree of processes. From there, you can drill down to threads, and then to windows. This will tell you which windows the process has. Note down the window class and caption. With these, you can use FindWindow (or EnumWindows) to find the window handle in future.</p>\n\n<p>With the window handle, you can send a WM_CLOSE or WM_SYSCOMMAND/SC_CLOSE (equivalent to clicking on the 'X' on the window caption) message. This ought to cause the program to shut down nicely.</p>\n\n<p>Note that I'm talking from a Win32 point-of-view here. You might need to use P/Invoke or other tricks to get this to work from a .NET program.</p>\n" }, { "answer_id": 110413, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 2, "selected": false, "text": "<p>This should work:</p>\n\n<pre><code>[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\nprivate static extern IntPtr FindWindow(string className, string windowName);\n[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\nprivate static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);\n\nprivate const int WM_CLOSE = 0x10;\nprivate const int WM_QUIT = 0x12;\n\npublic void SearchAndDestroy(string windowName) \n{\n IntPtr hWnd = FindWindow(null, windowName);\n if (hWnd == IntPtr.Zero)\n throw new Exception(\"Couldn't find window!\");\n SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);\n}\n</code></pre>\n\n<p>Since some windows don't respond to <code>WM_CLOSE</code>, <code>WM_QUIT</code> might have to be sent instead. These declarations should work on both 32bit and 64bit.</p>\n" }, { "answer_id": 111095, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": -1, "selected": false, "text": "<p>Question to clarify why you're attempting this: If the only user interface on the process is the system tray icon, why would you want to kill that and but leave the process running? How would the user access the process? And if the machine is \"unattended\", why concern yourself with the tray icon?</p>\n" }, { "answer_id": 111276, "author": "Traveling Tech Guy", "author_id": 19856, "author_profile": "https://Stackoverflow.com/users/19856", "pm_score": 1, "selected": true, "text": "<p>Here are some answers and clarifications:</p>\n\n<p><strong>rpetrich</strong>:\nTried your method before and the problem is, I don't know the window name, it differs from user to user, version to version - just the exe name remains constant. All I have is the process name. And as you can see in the code above the MainWindowHandle of the process is 0.</p>\n\n<p><strong>Roger</strong>:\nYes, I did mean the taskbar notification area - thanks for the clarification.\nI <em>NEED</em> to call PostQuitMessage. I just don't know how, given a processs only, and not a Window.</p>\n\n<p><strong>Craig</strong>:\nI'd be glad to explain the situation: the application has a command line interface, allowing you to specify parameters that dictate what it would do and where will it save the results. But once it's running, the only way to stop it and get the results is right-click it in the tray notification are and select 'exit'.</p>\n\n<p>Now my users want to script/batch the app. They had absolutely no problem starting it from a batch (just specify the exe name and and a bunch of flags) but then got stuck with a running process. Assuming no one will change the process to provide an API to stop it while running (it's quite old), I need a way to artificially close it.</p>\n\n<p>Similarly, on unattended computers, the script to start the process can be started by a task scheduling or operations control program, but there's no way to shut the process down.</p>\n\n<p>Hope that clarifies my situation, and again, thanks everyone who's trying to help!</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19856/" ]
Here's my issue: I need to close a process, already running, from a C# program. The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never have a main window. The other requirement that I have is that the application be **closed** not **killed**. I need it to write it's memory buffers to disk - and killing it causes data loss. Here's what I tried so far: ``` foreach (Process proc in Process.GetProcesses()) { if (proc.ProcessName.ToLower().StartsWith("myapp")) { if (proc.MainWindowHandle.ToInt32() != 0) { proc.CloseMainWindow(); proc.Close(); //proc.Kill(); <--- not good! } } } ``` I've added the **if** clause, after discovering that **MainWindowHandle == 0** when the window was minimized. Removing the **if** doesn't help. Neither the **CloseMainWindow()** nor the **Close()** work. The **Kill()** does, but as mentioned above - it's not what I need. Any idea would be accepted, including the use of arcane Win32 API functions :)
Here are some answers and clarifications: **rpetrich**: Tried your method before and the problem is, I don't know the window name, it differs from user to user, version to version - just the exe name remains constant. All I have is the process name. And as you can see in the code above the MainWindowHandle of the process is 0. **Roger**: Yes, I did mean the taskbar notification area - thanks for the clarification. I *NEED* to call PostQuitMessage. I just don't know how, given a processs only, and not a Window. **Craig**: I'd be glad to explain the situation: the application has a command line interface, allowing you to specify parameters that dictate what it would do and where will it save the results. But once it's running, the only way to stop it and get the results is right-click it in the tray notification are and select 'exit'. Now my users want to script/batch the app. They had absolutely no problem starting it from a batch (just specify the exe name and and a bunch of flags) but then got stuck with a running process. Assuming no one will change the process to provide an API to stop it while running (it's quite old), I need a way to artificially close it. Similarly, on unattended computers, the script to start the process can be started by a task scheduling or operations control program, but there's no way to shut the process down. Hope that clarifies my situation, and again, thanks everyone who's trying to help!
110,341
<p>Ok, I realize this situation is somewhat unusual, but I need to establish a TCP connection (the 3-way handshake) using only raw sockets (in C, in linux) -- i.e. I need to construct the IP headers and TCP headers myself. I'm writing a server (so I have to first respond to the incoming SYN packet), and for whatever reason I can't seem to get it right. Yes, I realize that a SOCK_STREAM will handle this for me, but for reasons I don't want to go into that isn't an option.</p> <p>The tutorials I've found online on using raw sockets all describe how to build a SYN flooder, but this is somewhat easier than actually establishing a TCP connection, since you don't have to construct a response based on the original packet. I've gotten the SYN flooder examples working, and I can read the incoming SYN packet just fine from the raw socket, but I'm still having trouble creating a valid SYN/ACK response to an incoming SYN from the client.</p> <p>So, does anyone know a good tutorial on using raw sockets that goes beyond creating a SYN flooder, or does anyone have some code that could do this (using SOCK_RAW, and not SOCK_STREAM)? I would be very grateful.</p> <hr> <p>MarkR is absolutely right -- the problem is that the kernel is sending reset packets in response to the initial packet because it thinks the port is closed. The kernel is beating me to the response and the connection dies. I was using tcpdump to monitor the connection already -- I should have been more observant and noticed that there were TWO replies one of which was a reset that was screwing things up, as well as the response my program created. D'OH!</p> <p>The solution that seems to work best is to use an iptables rule, as suggested by MarkR, to block the outbound packets. However, there's an easier way to do it than using the mark option, as suggested. I just match whether the reset TCP flag is set. During the course of a normal connection this is unlikely to be needed, and it doesn't really matter to my application if I block all outbound reset packets from the port being used. This effectively blocks the kernel's unwanted response, but not my own packets. If the port my program is listening on is 9999 then the iptables rule looks like this:</p> <pre><code>iptables -t filter -I OUTPUT -p tcp --sport 9999 --tcp-flags RST RST -j DROP </code></pre>
[ { "answer_id": 110349, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 1, "selected": false, "text": "<p>I don't have a tutorial, but I recently used <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wireshark</a> to good effect to debug some raw sockets programming I was doing. If you capture the packets you're sending, wireshark will do a good job of showing you if they're malformed or not. It's useful for comparing to a normal connection too.</p>\n" }, { "answer_id": 110416, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 2, "selected": false, "text": "<p>I can't help you out on any tutorials.</p>\n\n<p>But I can give you some advice on the tools that you could use to assist in debugging.</p>\n\n<p>First off, as <a href=\"https://stackoverflow.com/users/14032/bmdhacks\">bmdhacks</a> has suggested, get yourself a copy of <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">wireshark</a> (or tcpdump - but wireshark is easier to use). Capture a good handshake. Make sure that you save this.</p>\n\n<p>Capture one of your handshakes that fails. Wireshark has quite good packet parsing and error checking, so if there's a straightforward error it will probably tell you.</p>\n\n<p>Next, get yourself a copy of <a href=\"http://tcpreplay.synfin.net/\" rel=\"nofollow noreferrer\">tcpreplay</a>. This should also include a tool called \"tcprewrite\".\ntcprewrite will allow you to split your previously saved capture files into two - one for each side of the handshake.\nYou can then use tcpreplay to play back one side of the handshake so you have a consistent set of packets to play with.</p>\n\n<p>Then you use wireshark (again) to check your responses.</p>\n" }, { "answer_id": 110428, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 4, "selected": false, "text": "<p>You want to implement part of a TCP stack in userspace... this is ok, some other apps do this.</p>\n\n<p>One problem you will come across is that the kernel will be sending out (generally negative, unhelpful) replies to incoming packets. This is going to screw up any communication you attempt to initiate.</p>\n\n<p>One way to avoid this is to use an IP address and interface that the kernel does not have its own IP stack using- which is fine but you will need to deal with link-layer stuff (specifically, arp) yourself. That would require a socket lower than IPPROTO_IP, SOCK_RAW - you need a packet socket (I think).</p>\n\n<p>It may also be possible to block the kernel's responses using an iptables rule- but I rather suspect that the rules will apply to your own packets as well somehow, unless you can manage to get them treated differently (perhaps applying a netfilter \"mark\" to your own packets?)</p>\n\n<p>Read the man pages</p>\n\n<p>socket(7)\nip(7)\npacket(7)</p>\n\n<p>Which explain about various options and ioctls which apply to types of sockets.</p>\n\n<p>Of course you'll need a tool like Wireshark to inspect what's going on. You will need several machines to test this, I recommend using vmware (or similar) to reduce the amount of hardware required.</p>\n\n<p>Sorry I can't recommend a specific tutorial.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 110470, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There are structures for IP and TCP headers declared in netinet/ip.h &amp; netinet/tcp.h respectively. You may want to look at the other headers in this directory for extra macros &amp; stuff that may be of use. </p>\n\n<p>You send a packet with the SYN flag set and a random sequence number (x). You should receive a SYN+ACK from the other side. This packet will have an acknowledgement number (y) that indicates the next sequence number the other side is expecting to receive as well as another sequence number (z). You send back an ACK packet that has sequence number x+1 and ack number z+1 to complete the connection. </p>\n\n<p>You also need to make sure you calculate appropriate TCP/IP checksums &amp; fill out the remainder of the header for the packets you send. Also, don't forget about things like host &amp; network byte order.</p>\n\n<p>TCP is defined in RFC 793, available here: <a href=\"http://www.faqs.org/rfcs/rfc793.html\" rel=\"nofollow noreferrer\">http://www.faqs.org/rfcs/rfc793.html</a></p>\n" }, { "answer_id": 959855, "author": "Tom Hennen", "author_id": 6839, "author_profile": "https://Stackoverflow.com/users/6839", "pm_score": 0, "selected": false, "text": "<p>Depending on what you're trying to do it may be easier to get existing software to handle the TCP handshaking for you.</p>\n\n<p>One open source IP stack is lwIP (<a href=\"http://savannah.nongnu.org/projects/lwip/\" rel=\"nofollow noreferrer\">http://savannah.nongnu.org/projects/lwip/</a>) which provides a full tcp/ip stack. It is very possible to get it running in user mode using either SOCK_RAW or pcap.</p>\n" }, { "answer_id": 11720631, "author": "youjustreadthis", "author_id": 1506928, "author_profile": "https://Stackoverflow.com/users/1506928", "pm_score": 2, "selected": false, "text": "<p>I realise that this is an old thread, but here's a tutorial that goes beyond the normal SYN flooders: <a href=\"http://www.enderunix.org/docs/en/rawipspoof/\" rel=\"nofollow\">http://www.enderunix.org/docs/en/rawipspoof/</a> </p>\n\n<p>Hope it might be of help to someone.</p>\n" }, { "answer_id": 13198988, "author": "A G", "author_id": 1671227, "author_profile": "https://Stackoverflow.com/users/1671227", "pm_score": 0, "selected": false, "text": "<p>if you are using raw sockets, if you send using different source mac address to the actual one, linux will ignore the response packet and not send an rst.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19860/" ]
Ok, I realize this situation is somewhat unusual, but I need to establish a TCP connection (the 3-way handshake) using only raw sockets (in C, in linux) -- i.e. I need to construct the IP headers and TCP headers myself. I'm writing a server (so I have to first respond to the incoming SYN packet), and for whatever reason I can't seem to get it right. Yes, I realize that a SOCK\_STREAM will handle this for me, but for reasons I don't want to go into that isn't an option. The tutorials I've found online on using raw sockets all describe how to build a SYN flooder, but this is somewhat easier than actually establishing a TCP connection, since you don't have to construct a response based on the original packet. I've gotten the SYN flooder examples working, and I can read the incoming SYN packet just fine from the raw socket, but I'm still having trouble creating a valid SYN/ACK response to an incoming SYN from the client. So, does anyone know a good tutorial on using raw sockets that goes beyond creating a SYN flooder, or does anyone have some code that could do this (using SOCK\_RAW, and not SOCK\_STREAM)? I would be very grateful. --- MarkR is absolutely right -- the problem is that the kernel is sending reset packets in response to the initial packet because it thinks the port is closed. The kernel is beating me to the response and the connection dies. I was using tcpdump to monitor the connection already -- I should have been more observant and noticed that there were TWO replies one of which was a reset that was screwing things up, as well as the response my program created. D'OH! The solution that seems to work best is to use an iptables rule, as suggested by MarkR, to block the outbound packets. However, there's an easier way to do it than using the mark option, as suggested. I just match whether the reset TCP flag is set. During the course of a normal connection this is unlikely to be needed, and it doesn't really matter to my application if I block all outbound reset packets from the port being used. This effectively blocks the kernel's unwanted response, but not my own packets. If the port my program is listening on is 9999 then the iptables rule looks like this: ``` iptables -t filter -I OUTPUT -p tcp --sport 9999 --tcp-flags RST RST -j DROP ```
You want to implement part of a TCP stack in userspace... this is ok, some other apps do this. One problem you will come across is that the kernel will be sending out (generally negative, unhelpful) replies to incoming packets. This is going to screw up any communication you attempt to initiate. One way to avoid this is to use an IP address and interface that the kernel does not have its own IP stack using- which is fine but you will need to deal with link-layer stuff (specifically, arp) yourself. That would require a socket lower than IPPROTO\_IP, SOCK\_RAW - you need a packet socket (I think). It may also be possible to block the kernel's responses using an iptables rule- but I rather suspect that the rules will apply to your own packets as well somehow, unless you can manage to get them treated differently (perhaps applying a netfilter "mark" to your own packets?) Read the man pages socket(7) ip(7) packet(7) Which explain about various options and ioctls which apply to types of sockets. Of course you'll need a tool like Wireshark to inspect what's going on. You will need several machines to test this, I recommend using vmware (or similar) to reduce the amount of hardware required. Sorry I can't recommend a specific tutorial. Good luck.
110,354
<p>I want to do this:</p> <pre><code>e.className = t; </code></pre> <p>Where t is the name of a style I have defined in a stylesheet.</p>
[ { "answer_id": 110357, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the <a href=\"http://www.w3.org/TR/DOM-Level-2-Style/\" rel=\"nofollow noreferrer\">DOM Level 2 Style</a> interface. e.g.,</p>\n\n<pre><code>button.style.fontFamily = \"Verdana, Arial, sans-serif\";\n</code></pre>\n\n<p>where <code>button</code> is (presumably) a button object. :-)</p>\n" }, { "answer_id": 110361, "author": "jonah", "author_id": 19861, "author_profile": "https://Stackoverflow.com/users/19861", "pm_score": 5, "selected": true, "text": "<p>If <code>e</code> is a reference to a DOM element and you have a class like this: <code>.t {color:green;}</code> then you want reference the class name as a string:</p>\n\n<pre><code>e.className = 't';\n</code></pre>\n" }, { "answer_id": 113938, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": "<p>Not only that works, but it's even a best practice.</p>\n\n<p>You definitively want to separate the data format (xHTML) from the design (CSS) and the behaviour (javascript).</p>\n\n<p>So it's far better to just add and remove classes in JS according to event while the esthetic concerns are delegated to css styles.</p>\n\n<p>E.G : Coloring an error message in red.</p>\n\n<p>CSS</p>\n\n<pre><code>.error\n{\n color: red;\n}\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>var error=document.getElementById('error');\nerror.className='error';\n</code></pre>\n\n<p>N.B :</p>\n\n<ul>\n<li>This snippet is just an example. In real life you would use js just for that.</li>\n<li>document.getElementById is not always interoperable. Better to use a JS framework to handle that. I personally use JQuery.</li>\n</ul>\n" }, { "answer_id": 64066221, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here is the example that add and remove the class using jQuery.</p>\n<pre><code>// js\n $(&quot;p:first&quot;).addClass(&quot;t&quot;);\n $(&quot;p:first&quot;).removeClass(&quot;t&quot;);\n\n// css\n .t {\n backgound: red\n }\n</code></pre>\n" }, { "answer_id": 72700153, "author": "Mouzam Ali", "author_id": 7188711, "author_profile": "https://Stackoverflow.com/users/7188711", "pm_score": 0, "selected": false, "text": "<pre><code>document.getElementById('id').className = 't'\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059/" ]
I want to do this: ``` e.className = t; ``` Where t is the name of a style I have defined in a stylesheet.
If `e` is a reference to a DOM element and you have a class like this: `.t {color:green;}` then you want reference the class name as a string: ``` e.className = 't'; ```
110,378
<p>How can I change the width of a textarea form element if I used ModelForm to create it?</p> <p>Here is my product class:</p> <pre><code>class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product </code></pre> <p>And the template code...</p> <pre><code>{% for f in form %} {{ f.name }}:{{ f }} {% endfor %} </code></pre> <p><code>f</code> is the actual form element...</p>
[ { "answer_id": 110414, "author": "zuber", "author_id": 9812, "author_profile": "https://Stackoverflow.com/users/9812", "pm_score": 8, "selected": true, "text": "<p><strong>The easiest way for your use case is to use CSS</strong>. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS.</p>\n\n<p>Example for <code>long_desc</code> field in your ProductForm (when your form does not have a custom prefix):</p>\n\n<pre><code>#id_long_desc {\n width: 300px;\n height: 200px;\n}\n</code></pre>\n\n<p><strong>Second approach</strong> is to pass the <code>attrs</code> keyword to your widget constructor.</p>\n\n<pre><code>class ProductForm(ModelForm):\n long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))\n short_desc = forms.CharField(widget=forms.Textarea)\n class Meta:\n model = Product\n</code></pre>\n\n<p>It's <a href=\"http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs\" rel=\"noreferrer\">described in Django documentation</a>.</p>\n\n<p><strong>Third approach</strong> is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor.</p>\n\n<pre><code>class ProductForm(ModelForm):\n long_desc = forms.CharField(widget=forms.Textarea)\n short_desc = forms.CharField(widget=forms.Textarea)\n class Meta:\n model = Product\n\n # Edit by bryan\n def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor\n self.fields['long_desc'].widget.attrs['cols'] = 10\n self.fields['long_desc'].widget.attrs['rows'] = 20\n</code></pre>\n\n<p>This approach has the following advantages:</p>\n\n<ul>\n<li>You can define widget attributes for fields that are generated automatically from your model without redefining whole fields.</li>\n<li>It doesn't depend on the prefix of your form.</li>\n</ul>\n" }, { "answer_id": 640680, "author": "bryan", "author_id": 73049, "author_profile": "https://Stackoverflow.com/users/73049", "pm_score": 4, "selected": false, "text": "<p>Excellent answer by zuber, but I believe there's an error in the example code for the third approach. The constructor should be:</p>\n\n<pre><code>def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor\n self.fields['long_desc'].widget.attrs['cols'] = 10\n self.fields['long_desc'].widget.attrs['cols'] = 20\n</code></pre>\n\n<p>The Field objects have no 'attrs' attributes, but their widgets do.</p>\n" }, { "answer_id": 25192228, "author": "bergdesign", "author_id": 1186380, "author_profile": "https://Stackoverflow.com/users/1186380", "pm_score": 4, "selected": false, "text": "<p>In the event that you're using an add-on like Grappelli that makes heavy use of styles, you may find that any overridden row and col attributes get ignored because of CSS selectors acting on your widget. This could happen when using zuber's excellent Second or Third approach above.</p>\n\n<p>In this case, simply use the First Approach blended with either the Second or Third Approach by setting a 'style' attribute instead of the 'rows' and 'cols' attributes.</p>\n\n<p>Here's an example modifying <strong>init</strong> in the Third Approach above:</p>\n\n<pre><code>def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor\n self.fields['short_desc'].widget.attrs['style'] = 'width:400px; height:40px;'\n self.fields['long_desc'].widget.attrs['style'] = 'width:800px; height:80px;'\n</code></pre>\n" }, { "answer_id": 49065416, "author": "Cubiczx", "author_id": 2053708, "author_profile": "https://Stackoverflow.com/users/2053708", "pm_score": 1, "selected": false, "text": "<p>Set row and your css class in your admin model view:</p>\n\n<pre><code>'explicacion': AutosizedTextarea(attrs={'rows': 5, 'class': 'input-xxlarge', 'style': 'width: 99% !important; resize: vertical !important;'}),\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
How can I change the width of a textarea form element if I used ModelForm to create it? Here is my product class: ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product ``` And the template code... ``` {% for f in form %} {{ f.name }}:{{ f }} {% endfor %} ``` `f` is the actual form element...
**The easiest way for your use case is to use CSS**. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS. Example for `long_desc` field in your ProductForm (when your form does not have a custom prefix): ``` #id_long_desc { width: 300px; height: 200px; } ``` **Second approach** is to pass the `attrs` keyword to your widget constructor. ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20})) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product ``` It's [described in Django documentation](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs). **Third approach** is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor. ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product # Edit by bryan def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['long_desc'].widget.attrs['cols'] = 10 self.fields['long_desc'].widget.attrs['rows'] = 20 ``` This approach has the following advantages: * You can define widget attributes for fields that are generated automatically from your model without redefining whole fields. * It doesn't depend on the prefix of your form.
110,384
<p>I am looking to set the result action from a failed IAuthorizationFilter. However I am unsure how to create an ActionResult from inside the Filter. The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working. Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable?</p> <p>Doesn't work:</p> <pre><code> [AttributeUsage(AttributeTargets.Method)] public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext context) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = View("User/Login"); } } } </code></pre>
[ { "answer_id": 110630, "author": "Jeremy Skinner", "author_id": 8560, "author_profile": "https://Stackoverflow.com/users/8560", "pm_score": 2, "selected": true, "text": "<p>You can instantiate the appropriate ActionResult directly, then set it on the context. For example:</p>\n\n<pre><code>public void OnAuthorization(AuthorizationContext context)\n{\n if (!context.HttpContext.User.Identity.IsAuthenticated)\n {\n context.Result = new ViewResult { ViewName = \"Whatever\" };\n }\n}\n</code></pre>\n" }, { "answer_id": 111522, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": false, "text": "<p>You should look at the implementation of IAuthorizationFilter that comes with the MVC framework, AuthorizeAttribute. If you are using forms authentication, there's no need for you to set the result to User/Login. You can raise a 401 HTTP status response and ASP.NET Will redirect to the login page for you.</p>\n\n<p>The one issue with setting the result to user/login is that the user's address bar is not updated, so they will be on the login page, but the URL won't match. For some people, this is not an issue. But some people want their site's URL to correspond to what the user sees in their browser.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
I am looking to set the result action from a failed IAuthorizationFilter. However I am unsure how to create an ActionResult from inside the Filter. The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working. Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable? Doesn't work: ``` [AttributeUsage(AttributeTargets.Method)] public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext context) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = View("User/Login"); } } } ```
You can instantiate the appropriate ActionResult directly, then set it on the context. For example: ``` public void OnAuthorization(AuthorizationContext context) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = new ViewResult { ViewName = "Whatever" }; } } ```
110,385
<p>I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below.</p> <p>I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue.</p> <ul> <li>Is there a better way to do this?</li> <li>Is it a good idea to unhook are rehook the event handlers like I did.</li> </ul> <p>Here's the code. </p> <pre><code>private Queue&lt;CheckBox&gt; favAttributesLimiter - new Queue&lt;CheckBox&gt;(); private const int MaxFavoredAttributes = 5; private void favoredAttributes_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.Checked) { if (favAttributesLimiter.Count == MaxFavoredAttributes) { CheckBox oldest = favAttributesLimiter.Dequeue(); oldest.CheckedChanged -= favoredAttributes_CheckedChanged; oldest.Checked = false; oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged); } favAttributesLimiter.Enqueue(cb); } else // cb.Checked == false { if (favAttributesLimiter.Contains(cb)) { var list = favAttributesLimiter.ToList(); list.Remove(cb); favAttributesLimiter=new Queue&lt;CheckBox&gt;(list); } } } </code></pre> <p>Edit: <br /> <a href="https://stackoverflow.com/questions/110385/limiting-a-group-of-checkboxes-to-a-certain-amount-of-checks#110398">Chakrit</a> answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user.</p>
[ { "answer_id": 110398, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 3, "selected": true, "text": "<p>I think you are looking for a <a href=\"http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx\" rel=\"nofollow noreferrer\">LinkedList</a>.</p>\n\n<p>Use <code>AddLast</code> instead of <code>Enqueue</code> and <code>RemoveFirst</code> instead of <code>Dequeue</code> and for removing something in the middle, just use a normal <code>Remove</code>.</p>\n" }, { "answer_id": 110407, "author": "David L Morris", "author_id": 3137, "author_profile": "https://Stackoverflow.com/users/3137", "pm_score": 2, "selected": false, "text": "<p>Just in case you haven't thought of it this way around. </p>\n\n<p>For a usability point of view, presumably you have some text saying something like \"click no more than 4 check boxes\".</p>\n\n<p>In which case, why not simply keep a count of the number of checked boxes, and prevent any changes to the 5th box (until of course there are only 3 check boxes). </p>\n" }, { "answer_id": 110508, "author": "jasonmray", "author_id": 17230, "author_profile": "https://Stackoverflow.com/users/17230", "pm_score": 2, "selected": false, "text": "<p>One thing to ask yourself is: do you really want to implement this type of behavior with checkboxes? Checkboxes already have a well-understood behavior from a user point of view, and having a seemingly random box become unchecked when a new one is checked will likely be very confusing or maybe even frustrating for the average user.</p>\n\n<p>Maybe consider something like a listbox with add/remove buttons, where the design of the list gives the user a visual cue that there is a max of (say) four items. As a reference, I'm thinking something along the lines of the <a href=\"http://www.iescreenshot.com/images/faq_inst_12.gif\" rel=\"nofollow noreferrer\">toolbar customizing dialog in IE</a>.</p>\n\n<p>Perhaps not the answer you were looking for, but something to consider.</p>\n" }, { "answer_id": 110523, "author": "Sargun Dhillon", "author_id": 10432, "author_profile": "https://Stackoverflow.com/users/10432", "pm_score": 1, "selected": false, "text": "<p>What I've done before is have a multicolumn selection menu like this: <br /></p>\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;----></p>\n\n\nchoices:selected\nchoice-1-empty box-\nchoice-2-empty box-\nchoice-3-empty box-\nchoice-4-empty box-\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n\n\n\n<p>Then people could highlight a \"choice-1\" and hit the right button. Suddenly the second column would be populated by the items in the first. Then you can disable the arrow after 3 choices have been added, and pop up a message saying, \"You may only select three choices.\" This makes far more sense compared to other options. It would be far easier for the user.</p>\n" }, { "answer_id": 113621, "author": "mat_geek", "author_id": 11032, "author_profile": "https://Stackoverflow.com/users/11032", "pm_score": 0, "selected": false, "text": "<p>If you ask a user to pick form a list of options and limit the number of choices it is likely that the first choice is there primary choice.</p>\n\n<p>e.g. Pick two, you will never have any of what you don't choose:</p>\n\n<ul>\n<li>Money</li>\n<li>Power</li>\n<li>Sex</li>\n<li>Excitement</li>\n<li>Gadgets</li>\n<li>Army of Coders.</li>\n</ul>\n\n<p>Was your first choice you primary choice?</p>\n\n<p>If you want to use check boxes, simply disable all the unchecked ones when the the second one is checked.</p>\n" }, { "answer_id": 113651, "author": "mat_geek", "author_id": 11032, "author_profile": "https://Stackoverflow.com/users/11032", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Is it a good idea to unhook are rehook\n the event handlers like I did.</p>\n</blockquote>\n\n<p>That depends.</p>\n\n<p>Is it Windows Forms? Windows Forms run on top of the WinAPI which mean that event handler is really just a function called by the message dispatch loop in the main thread. As such the functions do not need to be re-entrant and it is \"safe\".</p>\n\n<p>But, you must do your error handling and catch any exceptions like failed allocations <em>within</em> your event handler or your application will terminate.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1880/" ]
I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below. I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue. * Is there a better way to do this? * Is it a good idea to unhook are rehook the event handlers like I did. Here's the code. ``` private Queue<CheckBox> favAttributesLimiter - new Queue<CheckBox>(); private const int MaxFavoredAttributes = 5; private void favoredAttributes_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.Checked) { if (favAttributesLimiter.Count == MaxFavoredAttributes) { CheckBox oldest = favAttributesLimiter.Dequeue(); oldest.CheckedChanged -= favoredAttributes_CheckedChanged; oldest.Checked = false; oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged); } favAttributesLimiter.Enqueue(cb); } else // cb.Checked == false { if (favAttributesLimiter.Contains(cb)) { var list = favAttributesLimiter.ToList(); list.Remove(cb); favAttributesLimiter=new Queue<CheckBox>(list); } } } ``` Edit: [Chakrit](https://stackoverflow.com/questions/110385/limiting-a-group-of-checkboxes-to-a-certain-amount-of-checks#110398) answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user.
I think you are looking for a [LinkedList](http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx). Use `AddLast` instead of `Enqueue` and `RemoveFirst` instead of `Dequeue` and for removing something in the middle, just use a normal `Remove`.
110,430
<p>Do you write one test per function/method, with multiple checks in the test, or a test for each check?</p>
[ { "answer_id": 110434, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 2, "selected": false, "text": "<p>A test case for each check. It's more granular. It makes it much easier to see what specific test case failed.</p>\n" }, { "answer_id": 110438, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 3, "selected": false, "text": "<p>BDD (Behavior Driven Development)</p>\n\n<p>Though I'm still learning, it's basically TDD organized/focused around how your software will actually be used... NOT how it will be developed/built.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Behavior_Driven_Development\" rel=\"noreferrer\">Wikipedia</a>\n<a href=\"http://behaviour-driven.org/\" rel=\"noreferrer\">General Info</a></p>\n\n<p>BTW as far as whether to do multiple asserts per test method I would recommend trying it both ways. Sometimes you'll see where one strategy left you in a bind and it'll start making sense why you <em>normally</em> just use one assert per method.</p>\n" }, { "answer_id": 110441, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 1, "selected": false, "text": "<p>I would suggest a test case for every check.\nThe more you keep atomic, the better your results are!</p>\n\n<p>Keeping multiple checks in a single tests will help you generate report for how much functionality needs to be corrected.</p>\n\n<p>Keeping atomic test case will show you the overall quality !</p>\n" }, { "answer_id": 110443, "author": "Binil Thomas", "author_id": 3973, "author_profile": "https://Stackoverflow.com/users/3973", "pm_score": 0, "selected": false, "text": "<p>A testcase per check. If you name the method appropriately, it can provide valuable hint towards the problem when one of these tests cause a regression failure.</p>\n" }, { "answer_id": 110444, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 3, "selected": false, "text": "<p>I have a test per <strong>capability</strong> the function is offering. Each test may have several assertions, however. \nThe name of the testcase indicates the capability being tested.</p>\n\n<p>Generally, for one function, I have several \"sunny day\" tests and one or a few \"rainy day\" scenario, depending of its complexity. </p>\n" }, { "answer_id": 110445, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 2, "selected": false, "text": "<p>I write at least one test per method, and somtimes more if the method requires some different setUp to test the good cases and the bad cases.</p>\n\n<p>But you should <strong>NEVER</strong> test more than one method in one unit test. It reduce the amount of work and error in <em>fixing</em> your test in case your API changes.</p>\n" }, { "answer_id": 110461, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 6, "selected": true, "text": "<p>One test per check and super descriptive names, per instance:</p>\n\n<pre><code>@Test\npublic void userCannotVoteDownWhenScoreIsLessThanOneHundred() {\n ...\n}\n</code></pre>\n\n<p>Both only one assertion and using good names gives me a better report when a test fails. They scream to me: \"You broke THAT rule!\".</p>\n" }, { "answer_id": 110516, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 0, "selected": false, "text": "<p>I try to separate out Database tests and Business Logic Tests (using <a href=\"http://en.wikipedia.org/wiki/Behavior_Driven_Development\" rel=\"nofollow noreferrer\" title=\"Wikipedia - Behaviour Driven Development\">BDD</a> as others here recommend), running the Database ones first ensures your Database is in a good state before asking your application to play with it.</p>\n\n<p>There's a good <a href=\"http://www.dotnetrocks.com/default.aspx?showNum=312\" rel=\"nofollow noreferrer\" title=\"Andy Leonard on .Net Rocks!\">podcast show with Andy Leonard on what it involves and how to do it</a>, and if you'd like a bit more information, I've written a <a href=\"http://www.fatlemon.co.uk/2008/02/how-far-should-your-unit-tests-go/\" rel=\"nofollow noreferrer\" title=\"FatLemon - How far should your unit tests go?\">blog post on the subject</a> (shameless plug ;o)</p>\n" }, { "answer_id": 110531, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 1, "selected": false, "text": "<p>In general one testcase per check. When tests are grouped around a particular function it makes refactoring (eg removing or splitting) that function more difficult because the tests also need a lot of changes. It is much better to write the tests for each type of behaviour that you want from the class. Sometimes when testing a particular behaviour it makes sense to have multiple checks per test case. However, as the tests become more complicated it makes them harder to change when something in the class changes.</p>\n" }, { "answer_id": 110563, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 1, "selected": false, "text": "<p>In Java/Eclipse/JUnit I use two source directories (src and test) with the same tree.\nIf I have a <strong>src/com/mycompany/whatever/TestMePlease</strong> with methods worth testing (e.g. <strong>deleteAll(List&lt;?&gt; stuff) throws MyException</strong>) I create a <strong>test/com/mycompany/whatever/TestMePleaseTest</strong> with methods to test differente use case/scenarios:</p>\n\n<pre><code>@Test\npublic void deleteAllWithNullInput() { ... }\n\n@Test(expect=\"MyException.class\") // not sure about actual syntax here :-P\npublic void deleteAllWithEmptyInput() { ... }\n\n@Test\npublic void deleteAllWithSingleLineInput() { ... }\n\n@Test\npublic void deleteAllWithMultipleLinesInput() { ... }\n</code></pre>\n\n<p>Having different checks is simpler to handle for me. </p>\n\n<p>Nonetheless, since every test should be consistent, if I want my initial data set to stay unaltered I sometimes have, for example, to create stuff and delete it in the same check to insure every other test find the data set pristine:</p>\n\n<pre><code>@Test\npublic void insertAndDelete() { \n assertTrue(/*stuff does not exist yet*/);\n createStuff();\n assertTrue(/*stuff does exist now*/);\n deleteStuff();\n assertTrue(/*stuff does not exist anymore*/);\n}\n</code></pre>\n\n<p>Don't know if there are smarter ways to do that, to tell you the truth... </p>\n" }, { "answer_id": 110609, "author": "Christophe Herreman", "author_id": 17255, "author_profile": "https://Stackoverflow.com/users/17255", "pm_score": 1, "selected": false, "text": "<p>I like to have a test per check in a method and have a meaningfull name for the test-method. For instance:</p>\n\n<p>testAddUser_shouldThrowIllegalArgumentExceptionWhenUserIsNull</p>\n" }, { "answer_id": 110618, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 2, "selected": false, "text": "<p>I think that the rule of single assertion is a little too strict. In my unit tests, I try to follow the rule of <strong>single group of assertions</strong> -- you can use more than one assertion in one test method, as long as you do the checks one after another (you don't change the state of tested class between the assertions).</p>\n\n<p>So, in Python, I believe a test like this is <strong>correct</strong>:</p>\n\n<pre><code>def testGetCountReturnsCountAndEnd(self):\n count, endReached = self.handler.getCount()\n self.assertEqual(count, 0)\n self.assertTrue(endReached)\n</code></pre>\n\n<p>but this one should be <strong>split</strong> into two test methods:</p>\n\n<pre><code>def testGetCountReturnsOneAfterPut(self):\n self.assertEqual(self.handler.getCount(), 0)\n self.handler.put('foo')\n self.assertEqual(self.handler.getCount(), 1)\n</code></pre>\n\n<p>Of course, in case of long and frequently used groups of assertions, I like to create custom assertion methods -- these are especially useful for comparing complex objects.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
Do you write one test per function/method, with multiple checks in the test, or a test for each check?
One test per check and super descriptive names, per instance: ``` @Test public void userCannotVoteDownWhenScoreIsLessThanOneHundred() { ... } ``` Both only one assertion and using good names gives me a better report when a test fails. They scream to me: "You broke THAT rule!".
110,436
<p>Any recommended practices for cleaning up "header spaghetti" which is causing extremely slow compilation times (Linux/Unix)?</p> <p>Is there any equvalent to "#pragma once" with GCC?<br> (found conflicting messages regarding this)</p> <p>Thanks.</p>
[ { "answer_id": 110448, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 1, "selected": false, "text": "<p>In headers: include headers only if you can't use forward declaration, but always #include any file that you need (include dependencies are evil!).</p>\n" }, { "answer_id": 110463, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 1, "selected": false, "text": "<p>As mentioned in the other answer, you should definitely use forward declarations whenever possible. To my knowledge, GCC doesn't have anything equivalent to #pragma once, which is why I stick to the old fashion style of include guards.</p>\n" }, { "answer_id": 110476, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Thanks for the replies, but the question is regarding existing code which includes strict \"include order\" etc.\nThe question is whether there are any tools/scripts to clarify what is actually going on.</p>\n\n<p>Header guards arent the solution as they dont prevent the compiler from reading the whole file again and again and ...</p>\n" }, { "answer_id": 110489, "author": "jasonmray", "author_id": 17230, "author_profile": "https://Stackoverflow.com/users/17230", "pm_score": 3, "selected": false, "text": "<p>I've read that GCC considers <code>#pragma once</code> deprecated, although even <code>#pragma once</code> can only do so much to speed things up.</p>\n\n<p>To try to untangle the <code>#include</code> spaghetti, you can look into <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">doxygen</a>. It should be able to generate graphs of included headers, which may give you an edge on simplifying things. I can't recall the details offhand, but the graph features may require you to install <a href=\"http://www.graphviz.org/\" rel=\"nofollow noreferrer\">GraphViz</a> and tell doxygen the path where it can find GraphViz's dotty.exe.</p>\n\n<p>Another approach you might consider if compile time is your primary concern is setting up <a href=\"http://en.wikipedia.org/wiki/Precompiled_headers\" rel=\"nofollow noreferrer\">Precompiled Headers</a>.</p>\n" }, { "answer_id": 110506, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "<p>Use one or more of those for speeding up the build time</p>\n\n<ol>\n<li>Use Precompiled Headers</li>\n<li>Use a caching mechanism (scons for example)</li>\n<li>Use a distributed build system ( distcc, Incredibuild($) )</li>\n</ol>\n" }, { "answer_id": 110608, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 4, "selected": true, "text": "<p>Assuming you're familiar with \"include guards\" (#ifdef at the begining of the header..), an additional way of speeding up build time is by using external include guards.\nIt was discussed in \"<a href=\"http://vig.pearsoned.com/store/product/1,1207,store-15080_isbn-0201633620,00.html\" rel=\"noreferrer\">Large Scale C++ Software Design</a>\". The idea is that classic include guards, unlike #pragma once, do not spare you the preprocessor parsing required to ignore the header from the 2nd time on (i.e. it still has to parse and look for the start and end of the include guard. With external include guards you place the #ifdef's around the #include line itself.</p>\n\n<p>So it looks like this:</p>\n\n<pre><code>#ifndef MY_HEADER\n#include \"myheader.h\"\n#endif\n</code></pre>\n\n<p>and of course within the H file you have the classic include guard</p>\n\n<pre><code>#ifndef MY_HEADER\n#define MY_HEADER\n\n// content of header\n\n#endif\n</code></pre>\n\n<p>This way the myheader.h file isn't even opened / parsed by the preprocessor, and it can save you a lot of time in large projects, especially when header files sit on shared remote locations, as they sometimes do.</p>\n\n<p>again, it's all in that book. hth</p>\n" }, { "answer_id": 110676, "author": "Richard", "author_id": 19897, "author_profile": "https://Stackoverflow.com/users/19897", "pm_score": 3, "selected": false, "text": "<p>If you want to do a complete cleanup and have the time to do it then the best solution is to delete all the #includes in all the files (except for obvious ones e.g. abc.h in abc.cpp) and then compile the project. Add the necessary forward declaration or header to fix the first error and then repeat until you comple cleanly.</p>\n\n<p>This doesn't fix underlying problems that can result in include issues, but it does ensure that the only includes are the required ones.</p>\n" }, { "answer_id": 110685, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.gimpel.com/\" rel=\"nofollow noreferrer\">PC-Lint</a> will go a long way to cleaning up spaghetti headers. Also it will solve other problems for you too like uninitialised variables going unseen, etc.</p>\n" }, { "answer_id": 110737, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "<p>Richard was somewhat right (Why his solution was noted down?).</p>\n\n<p>Anyway, all C/C++ headers should use internal include guards.</p>\n\n<p>This said, either:</p>\n\n<p>1 - Your legacy code is not really maintained anymore, and you should use pre-compiled headers (which are a hack, but hey... Your need is to speed up your compilation, not refactor unmaintained code)</p>\n\n<p>2 - Your legacy code is still living. Then, you either use the precompiled headers and/or the guards/external guards for a temporary solution, but in the end, you'll need to remove all your includes, one .C or .CPP at a time, and compile each .C or .CPP file one at a time, correcting their includes with forward-declarations or includes when necessary (or even breaking a large include into smaller ones to be sure each .C or .CPP file will get only the headers it needs). Anyway, testing and removing obsolete includes is part of maintenance of a project, so...</p>\n\n<p>My own experience with precompiled headers was not exactly a good one, because half the time, the compiler could not find a symbol I had defined, and so I tried a full \"clean/rebuild\", to be sure it was not the precompiled header that was obsolete. So my guess is to use it for external libraries you won't even touch (like the STL, C API headers, Boost, whatever). Still, my own experience was with Visual C++ 6, so I guess (hope?) they got it right, now.</p>\n\n<p>Now, one last thing: Headers should always be self-sufficient. That means that if the inclusion of headers depends on order of inclusion, then you have a problem. For example, if you can write:</p>\n\n<pre><code>#include \"AAA.hpp\"\n#include \"BBB.hpp\"\n</code></pre>\n\n<p>But not:</p>\n\n<pre><code>#include \"BBB.hpp\"\n#include \"AAA.hpp\"\n</code></pre>\n\n<p>because BBB depends on AAA, then all you have is a dependency you never acknowledged in the code. Not acknowledging it with a define will only make your compilation a nightmare. BBB should include AAA, too (even if it could be somewhat slower: in the end, forward-declarations will anyway clean useless includes, so you should have a faster compile timer).</p>\n" }, { "answer_id": 111264, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 1, "selected": false, "text": "<p>As onebyone.livejournal.com commented in a response to your question, some compilers support <a href=\"http://www.eskimo.com/~hottub/software/include/index.html\" rel=\"nofollow noreferrer\">include guard optimization</a>, which the page I linked defines as follows:</p>\n\n<blockquote>\n <p>The include guard optimisation is when a compiler recognises the internal include guard idiom described above and takes steps to avoid opening the file multiple times. The compiler can look at an include file, strip out comments and white space and work out if the whole of the file is within the include guards. If it is, it stores the filename and include guard condition in a map. The next time the compiler is asked to include the file, it can check the include guard condition and make the decision whether to skip the file or #include it without needing to open the file. </p>\n</blockquote>\n\n<p>Then again, you already answered that external include guards are not the answer to your question. For disentangling header files that must be included in a specific order, I would suggest the following:</p>\n\n<ul>\n<li>Each <code>.c</code> or <code>.cpp</code> file should <code>#include</code> the corresponding <code>.h</code> file first, and the rest of its <code>#include</code> directives should be sorted alphabetically. You will usually get build errors when this breaks unstated dependencies between header files.</li>\n<li>If you have a header file that defines global typedefs for basic types or global <code>#define</code> directives that are used for most of the code, each <code>.h</code> file should <code>#include</code> that file first, and the rest of its <code>#include</code> directives should be sorted alphabetically.</li>\n<li>When these changes cause compile errors, you will usually have to add an explicit dependency from one header file to another, in the form of an <code>#include</code>.</li>\n<li>When these changes do not cause compile errors, they might cause behavioral changes. Hopefully you have some sort of test suite that you can use to verify the functionality of your application.</li>\n</ul>\n\n<p>It also sounds like part of the problem might be that incremental builds are much slower than they ought to be. This situation can be improved with forward declarations or a distributed build system, as others have pointed out.</p>\n" }, { "answer_id": 226190, "author": "Enno", "author_id": 30404, "author_profile": "https://Stackoverflow.com/users/30404", "pm_score": 2, "selected": false, "text": "<p>I read the other day about a neat trick to reduce header dependencies: Write a script that will</p>\n<ul>\n<li>find all #include statements</li>\n<li>remove one statement at a time and recompiles</li>\n<li>if compilation fails, add the include statement back in</li>\n</ul>\n<p>At the end, you'll hopefully end up with the minimum of required includes in your code. You could write a similar script that re-arranges includes to find out if they are self-sufficient, or require other headers to be included before them (include the header first, see if compilation fails, report it). That should go some way to cleaning up your code.</p>\n<p>Some more notes:</p>\n<ul>\n<li>Modern compilers (gcc among them) recognize header guards, and optimize in the same way as pragma once would, only opening the file once.</li>\n<li><h1>pragma once can be problematic when the same file has different names in the filesystem (i.e. with soft-links)</h1>\n</li>\n<li>gcc supports #pragma once, but calls it &quot;obsolete&quot;</li>\n<li><h1>pragma once isn't supported by all compilers, and not part of the C standard</h1>\n</li>\n<li>not only compilers can be problematic. Tools like Incredibuild also have issues with #pragma once</li>\n</ul>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Any recommended practices for cleaning up "header spaghetti" which is causing extremely slow compilation times (Linux/Unix)? Is there any equvalent to "#pragma once" with GCC? (found conflicting messages regarding this) Thanks.
Assuming you're familiar with "include guards" (#ifdef at the begining of the header..), an additional way of speeding up build time is by using external include guards. It was discussed in "[Large Scale C++ Software Design](http://vig.pearsoned.com/store/product/1,1207,store-15080_isbn-0201633620,00.html)". The idea is that classic include guards, unlike #pragma once, do not spare you the preprocessor parsing required to ignore the header from the 2nd time on (i.e. it still has to parse and look for the start and end of the include guard. With external include guards you place the #ifdef's around the #include line itself. So it looks like this: ``` #ifndef MY_HEADER #include "myheader.h" #endif ``` and of course within the H file you have the classic include guard ``` #ifndef MY_HEADER #define MY_HEADER // content of header #endif ``` This way the myheader.h file isn't even opened / parsed by the preprocessor, and it can save you a lot of time in large projects, especially when header files sit on shared remote locations, as they sometimes do. again, it's all in that book. hth
110,451
<p>I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There <em>are</em> templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere?</p>
[ { "answer_id": 110502, "author": "adondai", "author_id": 19713, "author_profile": "https://Stackoverflow.com/users/19713", "pm_score": 2, "selected": false, "text": "<p>If you are a student you could get the full Visual Studio 2008 from <a href=\"http://dreamspark.com\" rel=\"nofollow noreferrer\">DreamSpark</a> for free.</p>\n" }, { "answer_id": 158146, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Mike,</p>\n\n<p>Visual Web Developer 2008 Express will help you in working with WCF Projects.</p>\n\n<p>I have the following... </p>\n\n<p>Microsoft Visual Studio 2008\nVersion 9.0.30729.1 SP\nMicrosoft .NET Framework\nVersion 3.5 SP1</p>\n\n<p>Hope this helps.</p>\n\n<p>Sanjeev</p>\n" }, { "answer_id": 676745, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>If you have both Visual Web Developer (VWD) 2008 and Visual C# (VC#) 2008 installed you can copy templates between them. The VWD template files live in (by default):</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress\n</code></pre>\n\n<p>The VC# templates live in:</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VCSExpress\n</code></pre>\n\n<p>Simply copy the templates between the two directories, they might not match exactly but they should be close enough to make sense, for instance I copied the project templates from VC# into VWD by copying files from:</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VCSExpress\\ProjectTemplates\\1033\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress\\ProjectTemplates\\CSharp\\Windows\\1033\n</code></pre>\n\n<p>The templates won't appear straight away in the template browser. For VWD you need to run:</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress.exe /installvstemplates\n</code></pre>\n\n<p>For VC# you run:</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VCSExpress.exe /installvstemplates\n</code></pre>\n" }, { "answer_id": 1650136, "author": "Jminadeo", "author_id": 199695, "author_profile": "https://Stackoverflow.com/users/199695", "pm_score": 0, "selected": false, "text": "<p>As a be aware follow-up, I also had to run </p>\n\n<p>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress.exe /ResetSettings</p>\n\n<p><strong>After</strong> copying the templates and running the </p>\n\n<p>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress.exe /installvstemplats</p>\n\n<p>The IDE was crashing when it tried to enumerate the C# project templates tree. After running the ResetSettings, the tree iterated and the new templates were present.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14607/" ]
I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There *are* templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere?
If you have both Visual Web Developer (VWD) 2008 and Visual C# (VC#) 2008 installed you can copy templates between them. The VWD template files live in (by default): ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress ``` The VC# templates live in: ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress ``` Simply copy the templates between the two directories, they might not match exactly but they should be close enough to make sense, for instance I copied the project templates from VC# into VWD by copying files from: ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress\ProjectTemplates\1033 ``` into: ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress\ProjectTemplates\CSharp\Windows\1033 ``` The templates won't appear straight away in the template browser. For VWD you need to run: ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress.exe /installvstemplates ``` For VC# you run: ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress.exe /installvstemplates ```
110,498
<p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
[ { "answer_id": 110547, "author": "olt", "author_id": 19759, "author_profile": "https://Stackoverflow.com/users/19759", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://linux.die.net/diveintopython/html/http_web_services/redirects.html\" rel=\"nofollow noreferrer\">Dive Into Python</a> has a good chapter on handling redirects with urllib2. Another solution is <a href=\"https://docs.python.org/2/library/httplib.html\" rel=\"nofollow noreferrer\">httplib</a>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; import httplib\n&gt;&gt;&gt; conn = httplib.HTTPConnection(\"www.bogosoft.com\")\n&gt;&gt;&gt; conn.request(\"GET\", \"\")\n&gt;&gt;&gt; r1 = conn.getresponse()\n&gt;&gt;&gt; print r1.status, r1.reason\n301 Moved Permanently\n&gt;&gt;&gt; print r1.getheader('Location')\nhttp://www.bogosoft.com/new/location\n</code></pre>\n" }, { "answer_id": 110808, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": false, "text": "<p>I second olt's pointer to <a href=\"http://www.diveintopython.org/http_web_services/redirects.html\" rel=\"noreferrer\">Dive into Python</a>. Here's an implementation using urllib2 redirect handlers, more work than it should be? Maybe, shrug.</p>\n\n<pre><code>import sys\nimport urllib2\n\nclass RedirectHandler(urllib2.HTTPRedirectHandler):\n def http_error_301(self, req, fp, code, msg, headers): \n result = urllib2.HTTPRedirectHandler.http_error_301( \n self, req, fp, code, msg, headers) \n result.status = code \n raise Exception(\"Permanent Redirect: %s\" % 301)\n\n def http_error_302(self, req, fp, code, msg, headers):\n result = urllib2.HTTPRedirectHandler.http_error_302(\n self, req, fp, code, msg, headers) \n result.status = code \n raise Exception(\"Temporary Redirect: %s\" % 302)\n\ndef main(script_name, url):\n opener = urllib2.build_opener(RedirectHandler)\n urllib2.install_opener(opener)\n print urllib2.urlopen(url).read()\n\nif __name__ == \"__main__\":\n main(*sys.argv) \n</code></pre>\n" }, { "answer_id": 111066, "author": "Ashish", "author_id": 19607, "author_profile": "https://Stackoverflow.com/users/19607", "pm_score": 3, "selected": false, "text": "<p>i suppose this would help</p>\n\n<pre><code>from httplib2 import Http\ndef get_html(uri,num_redirections=0): # put it as 0 for not to follow redirects\nconn = Http()\nreturn conn.request(uri,redirections=num_redirections)\n</code></pre>\n" }, { "answer_id": 5352695, "author": "Carles Barrobés", "author_id": 166761, "author_profile": "https://Stackoverflow.com/users/166761", "pm_score": 4, "selected": false, "text": "<p>This is a urllib2 handler that will not follow redirects:</p>\n\n<pre><code>class NoRedirectHandler(urllib2.HTTPRedirectHandler):\n def http_error_302(self, req, fp, code, msg, headers):\n infourl = urllib.addinfourl(fp, headers, req.get_full_url())\n infourl.status = code\n infourl.code = code\n return infourl\n http_error_300 = http_error_302\n http_error_301 = http_error_302\n http_error_303 = http_error_302\n http_error_307 = http_error_302\n\nopener = urllib2.build_opener(NoRedirectHandler())\nurllib2.install_opener(opener)\n</code></pre>\n" }, { "answer_id": 9494012, "author": "Tzury Bar Yochay", "author_id": 9296, "author_profile": "https://Stackoverflow.com/users/9296", "pm_score": 3, "selected": false, "text": "<p>The shortest way however is</p>\n\n<pre><code>class NoRedirect(urllib2.HTTPRedirectHandler):\n def redirect_request(self, req, fp, code, msg, hdrs, newurl):\n pass\n\nnoredir_opener = urllib2.build_opener(NoRedirect())\n</code></pre>\n" }, { "answer_id": 10587613, "author": "Ian Mackinnon", "author_id": 201665, "author_profile": "https://Stackoverflow.com/users/201665", "pm_score": 3, "selected": false, "text": "<p>The <code>redirections</code> keyword in the <code>httplib2</code> request method is a red herring. Rather than return the first request it will raise a <code>RedirectLimit</code> exception if it receives a redirection status code. To return the inital response you need to set <code>follow_redirects</code> to <code>False</code> on the <code>Http</code> object:</p>\n\n<pre><code>import httplib2\nh = httplib2.Http()\nh.follow_redirects = False\n(response, body) = h.request(\"http://example.com\")\n</code></pre>\n" }, { "answer_id": 14678220, "author": "Marian", "author_id": 1228491, "author_profile": "https://Stackoverflow.com/users/1228491", "pm_score": 9, "selected": true, "text": "<p>Here is the <a href=\"http://docs.python-requests.org/en/latest/\" rel=\"noreferrer\">Requests</a> way:</p>\n\n<pre><code>import requests\nr = requests.get('http://github.com', allow_redirects=False)\nprint(r.status_code, r.headers['Location'])\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2168/" ]
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
Here is the [Requests](http://docs.python-requests.org/en/latest/) way: ``` import requests r = requests.get('http://github.com', allow_redirects=False) print(r.status_code, r.headers['Location']) ```
110,512
<p>I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server.</p> <p>I'd like to move 7 of these applications to mod_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app.</p> <p>As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level.</p> <p>What configuration gotchas should I look out for with this type of setup?</p>
[ { "answer_id": 110799, "author": "tomtaylor", "author_id": 19079, "author_profile": "https://Stackoverflow.com/users/19079", "pm_score": 3, "selected": true, "text": "<p>I would probably just move all the apps to mod_rails, as the performance seems comparable to Mongrel and there's less administration overhead.</p>\n\n<p>With regards to configuration gotchas, just make sure that you allow your public directory, or you'll find static assets failing:</p>\n\n<pre><code>&lt;Directory \"/var/www/app/current/public\"&gt;\n Options FollowSymLinks\n AllowOverride None\n Order allow,deny\n Allow from all\n&lt;/Directory&gt;\n</code></pre>\n\n<p>Aside from that, if you know how to configure Apache, mod_rails is very painless.</p>\n" }, { "answer_id": 110873, "author": "Subimage", "author_id": 10596, "author_profile": "https://Stackoverflow.com/users/10596", "pm_score": 1, "selected": false, "text": "<p>Ended up moving everything to mod_rails.</p>\n\n<p>Works like a champ!</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10596/" ]
I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server. I'd like to move 7 of these applications to mod\_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app. As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level. What configuration gotchas should I look out for with this type of setup?
I would probably just move all the apps to mod\_rails, as the performance seems comparable to Mongrel and there's less administration overhead. With regards to configuration gotchas, just make sure that you allow your public directory, or you'll find static assets failing: ``` <Directory "/var/www/app/current/public"> Options FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> ``` Aside from that, if you know how to configure Apache, mod\_rails is very painless.
110,536
<p>I have the following code:</p> <pre><code>string prefix = "OLD:"; Func&lt;string, string&gt; prependAction = (x =&gt; prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); </code></pre> <p>Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console.</p> <p>Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to:</p> <pre><code>Func&lt;string, string&gt; prependAction = (x =&gt; "OLD:" + x); </code></pre> <p>The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize. </p> <p>The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method:</p> <pre><code>string prefix = "NEW:"; var prepender = new Prepender {Prefix = prefix}; Func&lt;string, string&gt; prependAction = prepender.Prepend; prefix = "OLD:"; Console.WriteLine(prependAction("brownie")); </code></pre> <p>With helper class:</p> <pre><code>[Serializable] public class Prepender { public string Prefix { get; set; } public string Prepend(string str) { return Prefix + str; } } </code></pre> <p>This seems like a lot of extra work to get the compiler to be "dumb".</p>
[ { "answer_id": 110540, "author": "Dested", "author_id": 11137, "author_profile": "https://Stackoverflow.com/users/11137", "pm_score": -1, "selected": false, "text": "<p>What about this</p>\n\n<pre><code>string prefix = \"OLD:\";\nstring _prefix=prefix;\nFunc&lt;string, string&gt; prependAction = (x =&gt; _prefix + x);\nprefix = \"NEW:\";\nConsole.WriteLine(prependAction(\"brownie\"));\n</code></pre>\n" }, { "answer_id": 110541, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": -1, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>string prefix = \"OLD:\";\nstring prefixCopy = prefix;\nFunc&lt;string, string&gt; prependAction = (x =&gt; prefixCopy + x);\nprefix = \"NEW:\";\nConsole.WriteLine(prependAction(\"brownie\"));\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 110542, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 1, "selected": false, "text": "<p>Lambdas automatically 'suck' in local variables, I'm afraid that's simply how they work by definition.</p>\n" }, { "answer_id": 110546, "author": "Bittercoder", "author_id": 4843, "author_profile": "https://Stackoverflow.com/users/4843", "pm_score": 0, "selected": false, "text": "<p>This is a pretty common problem i.e. variables being modified by a closure unintentionally - a far simpler solution is just to go:</p>\n\n<pre><code>string prefix = \"OLD:\";\nvar actionPrefix = prefix;\nFunc&lt;string, string&gt; prependAction = (x =&gt; actionPrefix + x);\nprefix = \"NEW:\";\nConsole.WriteLine(prependAction(\"brownie\"));\n</code></pre>\n\n<p>If you're using resharper it will actually identify the places in your code where you're at risk of causing unexpected side effects such as this - so if the file is \"all green\" your code should be OK.</p>\n\n<p>I think in some ways it would have been nice if we had some syntactic sugar to handle this situation so we could have written it as a one-liner i.e.</p>\n\n<pre><code>Func&lt;string, string&gt; prependAction = (x =&gt; ~prefix + x);\n</code></pre>\n\n<p>Where some prefix operator would cause the variable's value to be evaluated prior to constructing the anonymous delegate/function.</p>\n" }, { "answer_id": 110555, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "<p>There are already several answers here explaining how you can avoid the lambda \"lifting\" your variable. Unfortunately that does not solve your underlying problem. Being unable to serialize the lambda has nothing to do with the lambda having \"lifted\" your variable. If the lambda expression needs an instance of a non-serialize class to compute, it makes perfect sense that it cannot be serialized.</p>\n\n<p>Depending on what you actually are trying to do (I can't quite decide from your post), a solution would be to move the non-serializable part of the lambda outside.</p>\n\n<p>For example, instead of:</p>\n\n<pre><code>NonSerializable nonSerializable = new NonSerializable();\nFunc&lt;string, string&gt; prependAction = (x =&gt; nonSerializable.ToString() + x);\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>NonSerializable nonSerializable = new NonSerializable();\nstring prefix = nonSerializable.ToString();\nFunc&lt;string, string&gt; prependAction = (x =&gt; prefix + x);\n</code></pre>\n" }, { "answer_id": 110565, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": -1, "selected": false, "text": "<p>Well, if we're gonna talk about \"problems\" here, lambdas come from the functional programming world, and in a purely functional programming langauge, <em>there are no assignments</em> and so your problem would never arise because prefix's value could never change. I understand C# thinks it's cool to import ideas from functional programs (because FP <em>is</em> cool!) but it's very hard to make it pretty, because C# is and will always be an imperative programming language.</p>\n" }, { "answer_id": 110598, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "<p>I get the problem now: the lambda refers to the containing class which might not be serializable. Then do something like this:</p>\n\n<pre><code>public void static Func&lt;string, string&gt; MakePrependAction(String prefix){\n return (x =&gt; prefix + x);\n}\n</code></pre>\n\n<p>(Note the static keyword.) Then the lambda needs not reference the containing class.</p>\n" }, { "answer_id": 110639, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 4, "selected": true, "text": "<p>I see the underlying problem now. It is deeper than I first thought. Basically the solution is to modify the expression tree before serializing it, by replacing all subtrees that do not depend on the parameters with constant nodes. This is apparently called \"funcletization\".\nThere is an explanation of it <a href=\"http://social.msdn.microsoft.com/Forums/en-US/67f63b9a-ea44-4428-aea0-5dcdb61e918b/binding-lambdas-when-they-are-closures\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 110647, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>Just make another closure...</p>\n\n<p>Say, something like:</p>\n\n<pre><code>var prepend = \"OLD:\";\n\nFunc&lt;string, Func&lt;string, string&gt;&gt; makePrepender = x =&gt; y =&gt; (x + y);\nFunc&lt;string, string&gt; oldPrepend = makePrepender(prepend);\n\nprepend = \"NEW:\";\n\nConsole.WriteLine(oldPrepend(\"Brownie\"));\n</code></pre>\n\n<p>Havn't tested it yet as I don't have access to VS at the moment, but normally, this is how I solve such problem.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600/" ]
I have the following code: ``` string prefix = "OLD:"; Func<string, string> prependAction = (x => prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); ``` Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console. Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to: ``` Func<string, string> prependAction = (x => "OLD:" + x); ``` The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize. The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method: ``` string prefix = "NEW:"; var prepender = new Prepender {Prefix = prefix}; Func<string, string> prependAction = prepender.Prepend; prefix = "OLD:"; Console.WriteLine(prependAction("brownie")); ``` With helper class: ``` [Serializable] public class Prepender { public string Prefix { get; set; } public string Prepend(string str) { return Prefix + str; } } ``` This seems like a lot of extra work to get the compiler to be "dumb".
I see the underlying problem now. It is deeper than I first thought. Basically the solution is to modify the expression tree before serializing it, by replacing all subtrees that do not depend on the parameters with constant nodes. This is apparently called "funcletization". There is an explanation of it [here](http://social.msdn.microsoft.com/Forums/en-US/67f63b9a-ea44-4428-aea0-5dcdb61e918b/binding-lambdas-when-they-are-closures).
110,562
<p>I need to write a function that receives a property as a parameter and execute its getter.</p> <p>If I needed to pass a function/delegate I would have used:</p> <pre><code>delegate RET FunctionDelegate&lt;T, RET&gt;(T t); void func&lt;T, RET&gt;(FunctionDelegate function, T param, ...) { ... return function.Invoke(param); } </code></pre> <p>Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?</p>
[ { "answer_id": 110569, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 2, "selected": false, "text": "<p>Properties are simply syntactic sugar for methods.</p>\n\n<p>I don't think you can modify a property such that it becomes some entity \"whose getter you can call\".</p>\n\n<p>You can however create a method GetPropertyValue() and pass that around as if it were a delegate.</p>\n" }, { "answer_id": 110599, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>@Dror Helper,</p>\n\n<p>I'm afraid you can't do it that way. Compiler generates get_PropertyName and set_PropertyName methods but they are not accessible without using Reflection. IMO best you can do is create function that takes <strong>System.Reflection.ProperyInfo</strong> and <strong>System.Object</strong> params and returns propInfo.GetValue(obj, null);</p>\n" }, { "answer_id": 110621, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 4, "selected": true, "text": "<p>You can use reflection, you can get a MethodInfo object for the get/set accessors and call it's Invoke method.</p>\n\n<p>The code example assumes you have both a get and set accessors and you really have to add error handling if you want to use this in production code:</p>\n\n<p>For example to get the value of property Foo of object obj you can write:</p>\n\n<pre><code>value = obj.GetType().GetProperty(\"Foo\").GetAccessors()[0].Invoke(obj,null);\n</code></pre>\n\n<p>to set it:</p>\n\n<pre><code>obj.GetType().GetProperty(\"Foo\").GetAccessors()[1].Invoke(obj,new object[]{value});\n</code></pre>\n\n<p>So you can pass obj.GetType().GetProperty(\"Foo\").GetAccessors()[0] to your method and execute it's Invoke method.</p>\n\n<p>an easier way is to use anonymous methods (this will work in .net 2.0 or later), let's use a slightly modified version of your code example:</p>\n\n<pre><code>delegate RET FunctionDelegate&lt;T, RET&gt;(T t);\n\nvoid func&lt;T, RET&gt;(FunctionDelegate&lt;T,RET&gt; function, T param, ...)\n{\n ...\n return function(param);\n}\n</code></pre>\n\n<p>for a property named Foo of type int that is part of a class SomeClass:</p>\n\n<pre><code>SomeClass obj = new SomeClass();\nfunc&lt;SomeClass,int&gt;(delegate(SomeClass o){return o.Foo;},obj);\n</code></pre>\n" }, { "answer_id": 110634, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 1, "selected": false, "text": "<p>Re: aku's answer:</p>\n\n<p>Then you have to obtain that property info first. It seems \"use reflection\" is the standard answer to the harder C# questions, but reflection yields not-so-pretty hard-to-maintain code. Dror, why not just create a delegate that reads the property for you? It's a simple one-liner and is probably the quickest and prettiest solution to your problem.</p>\n" }, { "answer_id": 4132483, "author": "Bartosz Pierzchlewicz", "author_id": 194520, "author_profile": "https://Stackoverflow.com/users/194520", "pm_score": 4, "selected": false, "text": "<p>You can also write something like:</p>\n\n<pre><code>static void Method&lt;T, U&gt;(this T obj, Expression&lt;Func&lt;T, U&gt;&gt; property)\n {\n var memberExpression = property.Body as MemberExpression;\n //getter\n U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null);\n //setter\n obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null);\n }\n</code></pre>\n\n<p>and example of invocation:</p>\n\n<pre><code>DbComputerSet cs = new DbComputerSet();\ncs.Method&lt;DbComputerSet, string&gt;(set =&gt; set.Code);\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11361/" ]
I need to write a function that receives a property as a parameter and execute its getter. If I needed to pass a function/delegate I would have used: ``` delegate RET FunctionDelegate<T, RET>(T t); void func<T, RET>(FunctionDelegate function, T param, ...) { ... return function.Invoke(param); } ``` Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?
You can use reflection, you can get a MethodInfo object for the get/set accessors and call it's Invoke method. The code example assumes you have both a get and set accessors and you really have to add error handling if you want to use this in production code: For example to get the value of property Foo of object obj you can write: ``` value = obj.GetType().GetProperty("Foo").GetAccessors()[0].Invoke(obj,null); ``` to set it: ``` obj.GetType().GetProperty("Foo").GetAccessors()[1].Invoke(obj,new object[]{value}); ``` So you can pass obj.GetType().GetProperty("Foo").GetAccessors()[0] to your method and execute it's Invoke method. an easier way is to use anonymous methods (this will work in .net 2.0 or later), let's use a slightly modified version of your code example: ``` delegate RET FunctionDelegate<T, RET>(T t); void func<T, RET>(FunctionDelegate<T,RET> function, T param, ...) { ... return function(param); } ``` for a property named Foo of type int that is part of a class SomeClass: ``` SomeClass obj = new SomeClass(); func<SomeClass,int>(delegate(SomeClass o){return o.Foo;},obj); ```
110,575
<p>Earlier today a question was asked regarding <a href="https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d">input validation strategies in web apps</a>.</p> <p>The top answer, at time of writing, suggests in <code>PHP</code> just using <code>htmlspecialchars</code> and <code>mysql_real_escape_string</code>. </p> <p>My question is: Is this always enough? Is there more we should know? Where do these functions break down?</p>
[ { "answer_id": 110576, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 9, "selected": true, "text": "<p>When it comes to database queries, always try and use prepared parameterised queries. The <code>mysqli</code> and <code>PDO</code> libraries support this. This is infinitely safer than using escaping functions such as <code>mysql_real_escape_string</code>.</p>\n\n<p>Yes, <code>mysql_real_escape_string</code> is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors.</p>\n\n<p>Imagine the following SQL:</p>\n\n<pre><code>$result = \"SELECT fields FROM table WHERE id = \".mysql_real_escape_string($_POST['id']);\n</code></pre>\n\n<p>You should be able to see that this is vulnerable to exploit.<br>\nImagine the <code>id</code> parameter contained the common attack vector:</p>\n\n<pre><code>1 OR 1=1\n</code></pre>\n\n<p>There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us:</p>\n\n<pre><code>SELECT fields FROM table WHERE id= 1 OR 1=1\n</code></pre>\n\n<p>Which is a lovely SQL injection vector and would allow the attacker to return all the rows.\nOr</p>\n\n<pre><code>1 or is_admin=1 order by id limit 1\n</code></pre>\n\n<p>which produces</p>\n\n<pre><code>SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1\n</code></pre>\n\n<p>Which allows the attacker to return the first administrator's details in this completely fictional example.</p>\n\n<p>Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that <code>1 OR 1=1</code> is not a valid literal.</p>\n\n<p>As for <code>htmlspecialchars()</code>. That's a minefield of its own.</p>\n\n<p>There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what. </p>\n\n<p>Firstly, if you are inside an HTML tag, you are in real trouble. Look at</p>\n\n<pre><code>echo '&lt;img src= \"' . htmlspecialchars($_GET['imagesrc']) . '\" /&gt;';\n</code></pre>\n\n<p>We're already inside an HTML tag, so we don't need &lt; or > to do anything dangerous. Our attack vector could just be <code>javascript:alert(document.cookie)</code></p>\n\n<p>Now resultant HTML looks like</p>\n\n<pre><code>&lt;img src= \"javascript:alert(document.cookie)\" /&gt;\n</code></pre>\n\n<p>The attack gets straight through. </p>\n\n<p>It gets worse. Why? because <code>htmlspecialchars</code> (when called this way) only encodes double quotes and not single. So if we had </p>\n\n<pre><code>echo \"&lt;img src= '\" . htmlspecialchars($_GET['imagesrc']) . \". /&gt;\";\n</code></pre>\n\n<p>Our evil attacker can now inject whole new parameters</p>\n\n<pre><code>pic.png' onclick='location.href=xxx' onmouseover='...\n</code></pre>\n\n<p>gives us</p>\n\n<pre><code>&lt;img src='pic.png' onclick='location.href=xxx' onmouseover='...' /&gt;\n</code></pre>\n\n<p>In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">XSS cheat sheet</a> for examples on how diverse vectors can be</p>\n\n<p>Even if you use <code>htmlspecialchars($string)</code> outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors.</p>\n\n<p>The most effective you can be is to use the a combination of mb_convert_encoding and htmlentities as follows.</p>\n\n<pre><code>$str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');\n$str = htmlentities($str, ENT_QUOTES, 'UTF-8');\n</code></pre>\n\n<p>Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off.</p>\n\n<p>For a more in-depth study to the multibyte problems, see <a href=\"https://stackoverflow.com/a/12118602/1820\">https://stackoverflow.com/a/12118602/1820</a></p>\n" }, { "answer_id": 110596, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 3, "selected": false, "text": "<p>In addition to Cheekysoft's excellent answer:</p>\n\n<ul>\n<li>Yes, they will keep you safe, but only if they're used absolutely correctly. Use them incorrectly and you will still be vulnerable, and may have other problems (for example data corruption)</li>\n<li>Please use parameterised queries instead (as stated above). You can use them through e.g. PDO or via a wrapper like PEAR DB</li>\n<li>Make sure that magic_quotes_gpc and magic_quotes_runtime are off at all times, and never get accidentally turned on, not even briefly. These are an early and deeply misguided attempt by PHP's developers to prevent security problems (which destroys data)</li>\n</ul>\n\n<p>There isn't really a silver bullet for preventing HTML injection (e.g. cross site scripting), but you may be able to achieve it more easily if you're using a library or templating system for outputting HTML. Read the documentation for that for how to escape things appropriately.</p>\n\n<p>In HTML, things need to be escaped differently depending on context. This is especially true of strings being placed into Javascript.</p>\n" }, { "answer_id": 116237, "author": "BrilliantWinter", "author_id": 20579, "author_profile": "https://Stackoverflow.com/users/20579", "pm_score": 2, "selected": false, "text": "<p>I would definitely agree with the above posts, but I have one small thing to add in reply to Cheekysoft's answer, specifically:</p>\n\n<blockquote>\n <p>When it comes to database queries,\n always try and use prepared\n parameterised queries. The mysqli and\n PDO libraries support this. This is\n infinitely safer than using escaping\n functions such as\n mysql_real_escape_string.</p>\n \n <p>Yes, mysql_real_escape_string is\n effectively just a string escaping\n function. It is not a magic bullet.\n All it will do is escape dangerous\n characters in order that they can be\n safe to use in a single query string.\n However, if you do not sanitise your\n inputs beforehand, then you will be\n vulnerable to certain attack vectors.</p>\n \n <p>Imagine the following SQL:</p>\n \n <p>$result = \"SELECT fields FROM table\n WHERE id =\n \".mysql_real_escape_string($_POST['id']);</p>\n \n <p>You should be able to see that this is\n vulnerable to exploit. Imagine the id\n parameter contained the common attack\n vector:</p>\n \n <p>1 OR 1=1</p>\n \n <p>There's no risky chars in there to\n encode, so it will pass straight\n through the escaping filter. Leaving\n us:</p>\n \n <p>SELECT fields FROM table WHERE id = 1\n OR 1=1</p>\n</blockquote>\n\n<p>I coded up a quick little function that I put in my database class that will strip out anything that isnt a number. It uses preg_replace, so there is prob a bit more optimized function, but it works in a pinch...</p>\n\n<pre><code>function Numbers($input) {\n $input = preg_replace(\"/[^0-9]/\",\"\", $input);\n if($input == '') $input = 0;\n return $input;\n}\n</code></pre>\n\n<p>So instead of using</p>\n\n<blockquote>\n <p>$result = \"SELECT fields FROM table WHERE id = \".mysqlrealescapestring(\"1 OR 1=1\");</p>\n</blockquote>\n\n<p>I would use</p>\n\n<blockquote>\n <p>$result = \"SELECT fields FROM table WHERE id = \".Numbers(\"1 OR 1=1\");</p>\n</blockquote>\n\n<p>and it would safely run the query</p>\n\n<blockquote>\n <p>SELECT fields FROM table WHERE id = 111</p>\n</blockquote>\n\n<p>Sure, that just stopped it from displaying the correct row, but I dont think that is a big issue for whoever is trying to inject sql into your site ;)</p>\n" }, { "answer_id": 116305, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 2, "selected": false, "text": "<p>An important piece of this puzzle is contexts. Someone sending \"1 OR 1=1\" as the ID is not a problem if you quote every argument in your query:</p>\n\n<pre><code>SELECT fields FROM table WHERE id='\".mysql_real_escape_string($_GET['id']).\"'\"\n</code></pre>\n\n<p>Which results in:</p>\n\n<pre><code>SELECT fields FROM table WHERE id='1 OR 1=1'\n</code></pre>\n\n<p>which is ineffectual. Since you're escaping the string, the input cannot break out of the string context. I've tested this as far as version 5.0.45 of MySQL, and using a string context for an integer column does not cause any problems.</p>\n" }, { "answer_id": 7654297, "author": "cnizzardini", "author_id": 530151, "author_profile": "https://Stackoverflow.com/users/530151", "pm_score": 2, "selected": false, "text": "<pre><code>$result = \"SELECT fields FROM table WHERE id = \".(INT) $_GET['id'];\n</code></pre>\n\n<p>Works well, even better on 64 bit systems. Beware of your systems limitations on addressing large numbers though, but for database ids this works great 99% of the time.</p>\n\n<p>You should be using a single function/method for cleaning your values as well. Even if this function is just a wrapper for mysql_real_escape_string(). Why? Because one day when an exploit to your preferred method of cleaning data is found you only have to update it one place, rather than a system-wide find and replace.</p>\n" }, { "answer_id": 42865322, "author": "Jarett L", "author_id": 7703090, "author_profile": "https://Stackoverflow.com/users/7703090", "pm_score": -1, "selected": false, "text": "<p>why, oh WHY, would you <strong>not</strong> include quotes around user input in your sql statement? seems quite silly not to! including quotes in your sql statement would render \"1 or 1=1\" a fruitless attempt, no?</p>\n\n<p>so now, you'll say, \"what if the user includes a quote (or double quotes) in the input?\"</p>\n\n<p>well, easy fix for that: just remove user input'd quotes. eg: <code>input =~ s/'//g;</code>. now, it seems to me anyway, that user input would be secured...</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1820/" ]
Earlier today a question was asked regarding [input validation strategies in web apps](https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d). The top answer, at time of writing, suggests in `PHP` just using `htmlspecialchars` and `mysql_real_escape_string`. My question is: Is this always enough? Is there more we should know? Where do these functions break down?
When it comes to database queries, always try and use prepared parameterised queries. The `mysqli` and `PDO` libraries support this. This is infinitely safer than using escaping functions such as `mysql_real_escape_string`. Yes, `mysql_real_escape_string` is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors. Imagine the following SQL: ``` $result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']); ``` You should be able to see that this is vulnerable to exploit. Imagine the `id` parameter contained the common attack vector: ``` 1 OR 1=1 ``` There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us: ``` SELECT fields FROM table WHERE id= 1 OR 1=1 ``` Which is a lovely SQL injection vector and would allow the attacker to return all the rows. Or ``` 1 or is_admin=1 order by id limit 1 ``` which produces ``` SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1 ``` Which allows the attacker to return the first administrator's details in this completely fictional example. Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that `1 OR 1=1` is not a valid literal. As for `htmlspecialchars()`. That's a minefield of its own. There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what. Firstly, if you are inside an HTML tag, you are in real trouble. Look at ``` echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />'; ``` We're already inside an HTML tag, so we don't need < or > to do anything dangerous. Our attack vector could just be `javascript:alert(document.cookie)` Now resultant HTML looks like ``` <img src= "javascript:alert(document.cookie)" /> ``` The attack gets straight through. It gets worse. Why? because `htmlspecialchars` (when called this way) only encodes double quotes and not single. So if we had ``` echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />"; ``` Our evil attacker can now inject whole new parameters ``` pic.png' onclick='location.href=xxx' onmouseover='... ``` gives us ``` <img src='pic.png' onclick='location.href=xxx' onmouseover='...' /> ``` In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the [XSS cheat sheet](http://ha.ckers.org/xss.html) for examples on how diverse vectors can be Even if you use `htmlspecialchars($string)` outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors. The most effective you can be is to use the a combination of mb\_convert\_encoding and htmlentities as follows. ``` $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8'); $str = htmlentities($str, ENT_QUOTES, 'UTF-8'); ``` Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off. For a more in-depth study to the multibyte problems, see <https://stackoverflow.com/a/12118602/1820>
110,584
<p>I have a document library with about 50 available content types. This document library is divided into several folders. When a user cliks the "New" button in a folder, all available content types are offered. I need to limit the content types according to the folder. For example, in the folder "Legal" a want to have only content types containing legal documents. I tried to use the UniqueContentTypeOrder property of SPFolder but it does not work. What is wrong?</p> <p>private void CreateFolder(SPFolder parent, string name) { SPFolder z = parent.SubFolders.Add(name); List col = new List();</p> <pre><code> foreach (SPContentType type in myDocumentLibrary.ContentTypes) { if (ContentTypeMatchesName(name, type)) { col.Add(type); } } z.UniqueContentTypeOrder = col; z.Update(); } </code></pre>
[ { "answer_id": 110711, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 3, "selected": true, "text": "<p>Have you looked at <a href=\"http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5%2D28d9%2D464f%2Db1c9%2D91e07c8f7e47&amp;ID=56\" rel=\"nofollow noreferrer\">this</a> article by Ton Stegeman?</p>\n" }, { "answer_id": 110795, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 0, "selected": false, "text": "<p>I think Magnus' answer will be exactly what you need but why are you storing to many content types and document types in one library? Wouldn't it make more sense to have more than one document library? this would make it much more easily managed.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19884/" ]
I have a document library with about 50 available content types. This document library is divided into several folders. When a user cliks the "New" button in a folder, all available content types are offered. I need to limit the content types according to the folder. For example, in the folder "Legal" a want to have only content types containing legal documents. I tried to use the UniqueContentTypeOrder property of SPFolder but it does not work. What is wrong? private void CreateFolder(SPFolder parent, string name) { SPFolder z = parent.SubFolders.Add(name); List col = new List(); ``` foreach (SPContentType type in myDocumentLibrary.ContentTypes) { if (ContentTypeMatchesName(name, type)) { col.Add(type); } } z.UniqueContentTypeOrder = col; z.Update(); } ```
Have you looked at [this](http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5%2D28d9%2D464f%2Db1c9%2D91e07c8f7e47&ID=56) article by Ton Stegeman?
110,587
<p>in a DB2 trigger, I need to compare the value of a CLOB field. Something like:</p> <pre><code>IF OLD_ROW.CLOB_FIELD != UPDATED_ROW.CLOB_FIELD </code></pre> <p>but "!=" does not work for comparing CLOBs.</p> <p>What is the way to compare it?</p> <p><strong>Edited to add:</strong></p> <p>My trigger needs to do some action if the Clob field was changed during an update. This is the reason I need to compare the 2 CLOBs in the trigger code. <strong>I'm looking for some detailed information on how this can be done</strong></p>
[ { "answer_id": 110797, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 1, "selected": false, "text": "<p>I believe it's not possible to use these kind of operators on CLOB fields, because of the way they're stored.</p>\n" }, { "answer_id": 111501, "author": "igelkott", "author_id": 2052165, "author_profile": "https://Stackoverflow.com/users/2052165", "pm_score": 3, "selected": false, "text": "<p>Calculate the md5 (or other) hash of the clobs and then compare these. Initial calculation will be slow but comparison is fast and easy. This could be a good method if the bulk of your data doesn't change very often.</p>\n\n<p>One way to calculate md5 is through a java statement in your trigger. Save these in the same table (if possible) or build a simple auxiliary table.</p>\n" }, { "answer_id": 113519, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 3, "selected": false, "text": "<p>Iglekott's idea is a good one, with a caveat:</p>\n\n<p>Be careful with compare-by-hash if your data is likely to get attacked. It is not currently computationally feasible to generate a hash collision for a specific MD5 value, but it is possible to generate two different inputs that will produce the same MD5 (therefore not triggering your code). It is also possible to generate two different strings with <em>the same prefix</em> that hash to the same value. </p>\n\n<p>If that kind of attack can lead to the integrity of your system being compromised, and that's a concern, you want to explore other options. The easiest would be simply switching the hash functions, SHA-2 does not have currently known vulnerabilities.</p>\n\n<p>If this isn't a concern -- hell, go with CRC. You aren't going for cryptographic security here. Just don't go with a cryptographically weak function if this stuff is getting installed on a smartbomb, 'mkay? :-)</p>\n" }, { "answer_id": 266524, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 3, "selected": false, "text": "<p>In Oracle 10g you can use DBMS_LOB.compare() API.</p>\n\n<p>Example:</p>\n\n<pre><code>select * from table t where dbms_lob.compare(t.clob1, t.clob2) != 0\n</code></pre>\n\n<p>Full API:</p>\n\n<pre><code>DBMS_LOB.COMPARE (\n lob_1 IN BLOB,\n lob_2 IN BLOB,\n amount IN INTEGER := 4294967295,\n offset_1 IN INTEGER := 1,\n offset_2 IN INTEGER := 1)\n RETURN INTEGER;\n\nDBMS_LOB.COMPARE (\n lob_1 IN CLOB CHARACTER SET ANY_CS,\n lob_2 IN CLOB CHARACTER SET lob_1%CHARSET,\n amount IN INTEGER := 4294967295,\n offset_1 IN INTEGER := 1,\n offset_2 IN INTEGER := 1)\n RETURN INTEGER; \n\nDBMS_LOB.COMPARE (\n lob_1 IN BFILE,\n lob_2 IN BFILE,\n amount IN INTEGER,\n offset_1 IN INTEGER := 1,\n offset_2 IN INTEGER := 1)\n RETURN INTEGER;\n</code></pre>\n" }, { "answer_id": 266540, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": -1, "selected": false, "text": "<p>Does DB2 use <code>!=</code> for not equals? The ANSI SQL Standard uses <code>&lt;&gt;</code> for not equals.</p>\n" }, { "answer_id": 1004514, "author": "Fred Sobotka", "author_id": 123875, "author_profile": "https://Stackoverflow.com/users/123875", "pm_score": 2, "selected": false, "text": "<p>If the CLOBs are 32K or less, you can cast them as VARCHAR, which allows comparison, LIKE, and various SQL string functions.</p>\n\n<p>Otherwise, you may want to consider adding a column to contain the hash of the CLOB and change the application(s) to keep that hash up to date whenever the CLOB is updated.</p>\n" }, { "answer_id": 1007646, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 2, "selected": false, "text": "<p>The md5 idea is probably the best, but another alternative is to create a special trigger that only fires when your CLOB field is updated.</p>\n\n<p>According to the <a href=\"http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0000931.htm\" rel=\"nofollow noreferrer\">syntax diagram</a>, you would define the trigger as:</p>\n\n<pre><code>CREATE TRIGGER trig_name AFTER UPDATE OF CLOB_FIELD \n//trigger body goes here\n</code></pre>\n\n<p>This is assuming that your application (or whoever is updating the table) is smart enough to update the CLOB field ONLY WHEN there has been a change made to the clob field, and not every time your table is updated.</p>\n" }, { "answer_id": 12289777, "author": "Paul Muller", "author_id": 1650247, "author_profile": "https://Stackoverflow.com/users/1650247", "pm_score": 0, "selected": false, "text": "<p>Just declare the trigger to fire if that particular column is updated.</p>\n\n<pre><code>create trigger T_TRIG on T \nbefore update of CLOB_COL\n...\n</code></pre>\n" }, { "answer_id": 13784374, "author": "ramazan polat", "author_id": 234775, "author_profile": "https://Stackoverflow.com/users/234775", "pm_score": 0, "selected": false, "text": "<p>Generating a hash value and comparing them is the best way IMHO.</p>\n\n<p>Here is the untested code:</p>\n\n<pre><code>...\ndeclare leftClobHash integer;\ndeclare rightClobHash integer;\nset leftClobHash = (\n SELECT DBMS_UTILITY.GET_HASH_VALUE(OLD_ROW.CLOB_FIELD,100,1024) AS HASH_VALUE \n FROM SYSIBM.SYSDUMMY1);\nset rightClobHash = (\n SELECT DBMS_UTILITY.GET_HASH_VALUE(UPDATED_ROW.CLOB_FIELD,100,1024) AS HASH_VALUE \n FROM SYSIBM.SYSDUMMY1);\n\nIF leftClobHash != rightClobHash\n...\n</code></pre>\n\n<p>Note that you need EXECUTE privilege on the DBMS_UTILITY module. You can find more information about the provided SQL PL code in the following links.</p>\n\n<ul>\n<li>Declaring variables: <a href=\"http://www.sqlpl-guide.com/DECLARE\" rel=\"nofollow\">http://www.sqlpl-guide.com/DECLARE</a> </li>\n<li>Setting values for variables: <a href=\"http://www.sqlpl-guide.com/SET\" rel=\"nofollow\">http://www.sqlpl-guide.com/SET</a> </li>\n<li>Generating Hash: <a href=\"http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.sql.rtn.doc%2Fdoc%2Fr0055167.html\" rel=\"nofollow\">http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.sql.rtn.doc%2Fdoc%2Fr0055167.html</a></li>\n<li>More on DBMS_UTILITY module: <a href=\"http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.sql.rtn.doc%2Fdoc%2Fr0055155.html\" rel=\"nofollow\">http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.sql.rtn.doc%2Fdoc%2Fr0055155.html</a></li>\n</ul>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11710/" ]
in a DB2 trigger, I need to compare the value of a CLOB field. Something like: ``` IF OLD_ROW.CLOB_FIELD != UPDATED_ROW.CLOB_FIELD ``` but "!=" does not work for comparing CLOBs. What is the way to compare it? **Edited to add:** My trigger needs to do some action if the Clob field was changed during an update. This is the reason I need to compare the 2 CLOBs in the trigger code. **I'm looking for some detailed information on how this can be done**
Calculate the md5 (or other) hash of the clobs and then compare these. Initial calculation will be slow but comparison is fast and easy. This could be a good method if the bulk of your data doesn't change very often. One way to calculate md5 is through a java statement in your trigger. Save these in the same table (if possible) or build a simple auxiliary table.
110,749
<p>How would you write a regular expression to convert mark down into HTML? For example, you would type in the following:</p> <pre><code>This would be *italicized* text and this would be **bold** text </code></pre> <p>This would then need to be converted to:</p> <pre><code>This would be &lt;em&gt;italicized&lt;/em&gt; text and this would be &lt;strong&gt;bold&lt;/strong&gt; text </code></pre> <p>Very similar to the mark down edit control used by stackoverflow.</p> <p><strong>Clarification</strong></p> <p>For what it is worth, I am using C#. Also, these are the <strong>only</strong> real tags/markdown that I want to allow. The amount of text being converted would be less than 300 characters or so.</p>
[ { "answer_id": 110754, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 3, "selected": false, "text": "<p>A single regex won't do. Every text markup will have it's own html translator. Better look into how the existing converters are implemented to get an idea on how it works.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Markdown#See_also\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Markdown#See_also</a></p>\n" }, { "answer_id": 110769, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 4, "selected": true, "text": "<p>The best way is to find a version of the Markdown library ported to whatever language you are using (you did not specify in your question). </p>\n\n<hr>\n\n<p>Now that you have clarified that you only want STRONG and EM to be processed, and that you are using C#, I recommend you take a look at <a href=\"http://www.aspnetresources.com/blog/markdown_announced.aspx\" rel=\"noreferrer\">Markdown.NET</a> to see how those tags are implemented. As you can see, it is in fact two expressions. Here is the code:</p>\n\n<pre><code>private string DoItalicsAndBold (string text)\n{\n // &lt;strong&gt; must go first:\n text = Regex.Replace (text, @\"(\\*\\*|__) (?=\\S) (.+?[*_]*) (?&lt;=\\S) \\1\", \n new MatchEvaluator (BoldEvaluator),\n RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n\n // Then &lt;em&gt;:\n text = Regex.Replace (text, @\"(\\*|_) (?=\\S) (.+?) (?&lt;=\\S) \\1\",\n new MatchEvaluator (ItalicsEvaluator),\n RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n return text;\n}\n\nprivate string ItalicsEvaluator (Match match)\n{\n return string.Format (\"&lt;em&gt;{0}&lt;/em&gt;\", match.Groups[2].Value);\n}\n\nprivate string BoldEvaluator (Match match)\n{\n return string.Format (\"&lt;strong&gt;{0}&lt;/strong&gt;\", match.Groups[2].Value);\n}\n</code></pre>\n" }, { "answer_id": 110831, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 1, "selected": false, "text": "<p>I don't know about C# specifically, but in perl it would be:</p>\n<pre><code>\\\\\\*\\\\\\*(.*?)\\\\\\*\\\\\\*/\n\\&lt; bold\\&gt;$1\\&lt;\\/bold\\&gt;/g\n</code></pre>\n<pre><code>\\\\\\*(.\\*?)\\\\\\*/\n\\&lt; em\\&gt;$1\\&lt;\\/em\\&gt;/g\n</code></pre>\n" }, { "answer_id": 110850, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 0, "selected": false, "text": "<p>I came across the following <a href=\"http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html\" rel=\"nofollow noreferrer\">post</a> that recommends to not do this. In my case though I am looking to keep it simple, but thought I would post this per <a href=\"https://stackoverflow.com/users/11830/jop\">jop's</a> recommendation in case someone else wanted to do this.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
How would you write a regular expression to convert mark down into HTML? For example, you would type in the following: ``` This would be *italicized* text and this would be **bold** text ``` This would then need to be converted to: ``` This would be <em>italicized</em> text and this would be <strong>bold</strong> text ``` Very similar to the mark down edit control used by stackoverflow. **Clarification** For what it is worth, I am using C#. Also, these are the **only** real tags/markdown that I want to allow. The amount of text being converted would be less than 300 characters or so.
The best way is to find a version of the Markdown library ported to whatever language you are using (you did not specify in your question). --- Now that you have clarified that you only want STRONG and EM to be processed, and that you are using C#, I recommend you take a look at [Markdown.NET](http://www.aspnetresources.com/blog/markdown_announced.aspx) to see how those tags are implemented. As you can see, it is in fact two expressions. Here is the code: ``` private string DoItalicsAndBold (string text) { // <strong> must go first: text = Regex.Replace (text, @"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1", new MatchEvaluator (BoldEvaluator), RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); // Then <em>: text = Regex.Replace (text, @"(\*|_) (?=\S) (.+?) (?<=\S) \1", new MatchEvaluator (ItalicsEvaluator), RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); return text; } private string ItalicsEvaluator (Match match) { return string.Format ("<em>{0}</em>", match.Groups[2].Value); } private string BoldEvaluator (Match match) { return string.Format ("<strong>{0}</strong>", match.Groups[2].Value); } ```
110,763
<p>I've built a wrapper over NumbericUpDown control. The wrapper is generic and can support int? and double?</p> <p>I would like to write a method that will do the following.</p> <pre><code>public partial class NullableNumericUpDown&lt;T&gt; : UserControl where T : struct { private NumbericUpDown numericUpDown; private T? Getvalue() { T? value = numericUpDown.Value as T?; // &lt;-- this is null :) thus my question return value; }} </code></pre> <p>of course there is no cast between decimal and double? or int? so I need to use a certain way of converting. I would like to avoid switch or if expressions.</p> <p>What would you do?</p> <p>To clarify my question I've provided more code...</p>
[ { "answer_id": 110772, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>It's not clear how you gonna use it.\nIf you want double create GetDouble() method, for integers - GetInteger()</p>\n\n<p>EDIT:</p>\n\n<p>Ok, now I think I understand your use case</p>\n\n<p>Try this:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\n\nstatic Nullable&lt;T&gt; ConvertFromString&lt;T&gt;(string value) where T:struct\n{\n TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));\n if (converter != null &amp;&amp; !string.IsNullOrEmpty(value))\n {\n try\n {\n return (T)converter.ConvertFrom(value);\n }\n catch (Exception e) // Unfortunately Converter throws general Exception\n {\n return null;\n }\n }\n\n return null;\n}\n\n...\n\ndouble? @double = ConvertFromString&lt;double&gt;(\"1.23\");\nConsole.WriteLine(@double); // prints 1.23\n\nint? @int = ConvertFromString&lt;int&gt;(\"100\");\nConsole.WriteLine(@int); // prints 100\n\nlong? @long = ConvertFromString&lt;int&gt;(\"1.1\");\nConsole.WriteLine(@long.HasValue); // prints False\n</code></pre>\n" }, { "answer_id": 110790, "author": "lotsoffreetime", "author_id": 18248, "author_profile": "https://Stackoverflow.com/users/18248", "pm_score": 0, "selected": false, "text": "<p>Since this method will always return the result of</p>\n\n<pre><code>numericUpDown.Value\n</code></pre>\n\n<p>you have no cause for the value to be converted to anything other than Decimal. Are you trying to solve a problem you don't have?</p>\n" }, { "answer_id": 112672, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<pre><code>public class FromDecimal&lt;T&gt; where T : struct, IConvertible\n{\n public T GetFromDecimal(decimal Source)\n {\n T myValue = default(T);\n myValue = (T) Convert.ChangeType(Source, myValue.GetTypeCode());\n return myValue;\n }\n}\n\npublic class FromDecimalTestClass\n{\n public void TestMethod()\n {\n decimal a = 1.1m;\n var Inter = new FromDecimal&lt;int&gt;();\n int x = Inter.GetFromDecimal(a);\n int? y = Inter.GetFromDecimal(a);\n Console.WriteLine(\"{0} {1}\", x, y);\n\n var Doubler = new FromDecimal&lt;double&gt;();\n double dx = Doubler.GetFromDecimal(a);\n double? dy = Doubler.GetFromDecimal(a);\n Console.WriteLine(\"{0} {1}\", dx, dy);\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>private T? Getvalue()\n{\n T? value = null;\n if (this.HasValue)\n value = new FromDecimal&lt;T&gt;().GetFromDecimal(NumericUpDown);\n return value;\n}\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11659/" ]
I've built a wrapper over NumbericUpDown control. The wrapper is generic and can support int? and double? I would like to write a method that will do the following. ``` public partial class NullableNumericUpDown<T> : UserControl where T : struct { private NumbericUpDown numericUpDown; private T? Getvalue() { T? value = numericUpDown.Value as T?; // <-- this is null :) thus my question return value; }} ``` of course there is no cast between decimal and double? or int? so I need to use a certain way of converting. I would like to avoid switch or if expressions. What would you do? To clarify my question I've provided more code...
It's not clear how you gonna use it. If you want double create GetDouble() method, for integers - GetInteger() EDIT: Ok, now I think I understand your use case Try this: ``` using System; using System.ComponentModel; static Nullable<T> ConvertFromString<T>(string value) where T:struct { TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter != null && !string.IsNullOrEmpty(value)) { try { return (T)converter.ConvertFrom(value); } catch (Exception e) // Unfortunately Converter throws general Exception { return null; } } return null; } ... double? @double = ConvertFromString<double>("1.23"); Console.WriteLine(@double); // prints 1.23 int? @int = ConvertFromString<int>("100"); Console.WriteLine(@int); // prints 100 long? @long = ConvertFromString<int>("1.1"); Console.WriteLine(@long.HasValue); // prints False ```
110,801
<p>I've tried cpan and cpanp shell and I keep getting:</p> <pre><code>ExtUtils::PkgConfig requires the pkg-config utility, but it doesn't seem to be in your PATH. Is it correctly installed? </code></pre> <p>What is the pkg-config utility and how do I install it? </p> <p>Updates: </p> <ul> <li>OS: Windows</li> <li>This module is a prerequisite for the File::Extractor module</li> </ul>
[ { "answer_id": 110840, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://pkgconfig.freedesktop.org/wiki/\" rel=\"nofollow noreferrer\">http://pkgconfig.freedesktop.org/wiki/</a></p>\n\n<p>pkg-config is a helper tool used when compiling applications and libraries.\nDepending on your OS, you might be able to get a binary distribution (try apt-get on Ubuntu, for example), otherwise you can get the source from their web site.</p>\n" }, { "answer_id": 110842, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 2, "selected": false, "text": "<p>pkg-config is used for when you are compiling applcations and libraries. It's really used for inserting the right command line arguments.</p>\n\n<p>It comes installed on most new releases of linux, but is pretty common if it's not there initially so it shouldn't be too hard to find.</p>\n\n<p>Here's how to install it on ubuntu:</p>\n\n<pre><code> sudo apt-get install pkg-config\n</code></pre>\n\n<p>Here's the wikipedia page:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Pkg-config\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Pkg-config</a></p>\n" }, { "answer_id": 111235, "author": "Notitze", "author_id": 9411, "author_profile": "https://Stackoverflow.com/users/9411", "pm_score": 2, "selected": false, "text": "<p>I found the Windows binaries for the pkg-config utility here: \n<a href=\"http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/\" rel=\"nofollow noreferrer\">http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/</a></p>\n\n<p>(Link was found here: <a href=\"http://www.go-evolution.org/Building_Evolution_on_Windows\" rel=\"nofollow noreferrer\">http://www.go-evolution.org/Building_Evolution_on_Windows</a>)</p>\n\n<p>Update: straight download link from <a href=\"http://www.gtk.org/download-windows.html\" rel=\"nofollow noreferrer\">gtk.org</a> : <a href=\"http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/pkg-config-0.23-2.zip\" rel=\"nofollow noreferrer\">pkg-config-0.23-2.zip</a></p>\n\n<p>Thanks for the pointers!</p>\n" }, { "answer_id": 111238, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>look here:\n<a href=\"http://gtk2-perl.sourceforge.net/win32/howto_build_gtk2perl_win32.html\" rel=\"nofollow noreferrer\">http://gtk2-perl.sourceforge.net/win32/howto_build_gtk2perl_win32.html</a>\nI found this page by googling for ExtUtils::PkgConfig and \"PPM\" (Actvestates Perl Package Manager).</p>\n" }, { "answer_id": 6740367, "author": "Terrence Brannon", "author_id": 149741, "author_profile": "https://Stackoverflow.com/users/149741", "pm_score": 0, "selected": false, "text": "<p>A better source for Windows binaries for pkg-config is <a href=\"http://www.gtk.org/download/win64.php\" rel=\"nofollow\">the gtk site</a></p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9411/" ]
I've tried cpan and cpanp shell and I keep getting: ``` ExtUtils::PkgConfig requires the pkg-config utility, but it doesn't seem to be in your PATH. Is it correctly installed? ``` What is the pkg-config utility and how do I install it? Updates: * OS: Windows * This module is a prerequisite for the File::Extractor module
look here: <http://gtk2-perl.sourceforge.net/win32/howto_build_gtk2perl_win32.html> I found this page by googling for ExtUtils::PkgConfig and "PPM" (Actvestates Perl Package Manager).
110,867
<p>I have a public property set in my form of type <code>ListE&lt;T&gt;</code> where:</p> <pre><code>public class ListE&lt;T&gt; : IList&lt;T&gt;, ICollection&lt;T&gt;, IEnumerable&lt;T&gt;, IList, ICollection, IEnumerable </code></pre> <p>Yeah, it's a mouthful, but that's what the Designer requires for it to show up as an editable collection in the Properties window. Which it does! So, I click the little [..] button to edit the collection, and then click Add to add an item to the collection.</p> <blockquote> <p>Arithmetic operation resulted in an overflow.</p> </blockquote> <p>Now, this is a very basic List, little more than an expanding array. The only part that comes close to arithmetic in the whole thing is in the expand function, and even that uses a left shift rather than a multiplication, so that won't overflow. This all makes me think that this exception is being raised inside the Designer, perhaps caused by some small inattention to implementation detail on my part, but I can't find a way to test or debug that scenario. Does anyone have any smart ideas?</p> <p>EDIT: Yes, I can use the property successfully, well even manually, ie. in the <code>OnLoad</code> handler, and I suppose that's what I'll have to resort to if I can't get this working, but that wouldn't be ideal. :(</p>
[ { "answer_id": 111065, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 0, "selected": false, "text": "<p>One place to start would be that it may be doing math with your ListE`1::Count property. If that has some subtle flaw (i.e. it is more complicated than return this.innerList.Count) it could be causing the designer to arithmetic overflow on some operation. Normally arithmetic overflows do not occur unless specifically asked for using the</p>\n\n<pre><code>checked\n{\n // ...\n}\n</code></pre>\n\n<p>syntax.</p>\n" }, { "answer_id": 111278, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "<p>I can't understand what's motivating you to attempt to reinvent the List&lt;T&gt; wheel in that way, but to answer your question: I would add a line \"System.Diagnostics.Debugger.Break()\" to the constructor of your class.</p>\n\n<p>Then try to use it in the designer, and you'll get a popup asking you if you want to attach a debugger. Attach a second instance of Visual Studio as a debugger, and you'll be able to set some breakpoints in your code and start debugging.</p>\n" }, { "answer_id": 125544, "author": "Brian ONeil", "author_id": 21371, "author_profile": "https://Stackoverflow.com/users/21371", "pm_score": 0, "selected": false, "text": "<p>You don't have to add the Debugger.Break(); call to your code to debug it. You can just open a different instance of VS and attach to the one that you using it in and you should be able to debug it with no issues (just make sure that you have the symbols loaded).</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
I have a public property set in my form of type `ListE<T>` where: ``` public class ListE<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable ``` Yeah, it's a mouthful, but that's what the Designer requires for it to show up as an editable collection in the Properties window. Which it does! So, I click the little [..] button to edit the collection, and then click Add to add an item to the collection. > > Arithmetic operation resulted in an overflow. > > > Now, this is a very basic List, little more than an expanding array. The only part that comes close to arithmetic in the whole thing is in the expand function, and even that uses a left shift rather than a multiplication, so that won't overflow. This all makes me think that this exception is being raised inside the Designer, perhaps caused by some small inattention to implementation detail on my part, but I can't find a way to test or debug that scenario. Does anyone have any smart ideas? EDIT: Yes, I can use the property successfully, well even manually, ie. in the `OnLoad` handler, and I suppose that's what I'll have to resort to if I can't get this working, but that wouldn't be ideal. :(
I can't understand what's motivating you to attempt to reinvent the List<T> wheel in that way, but to answer your question: I would add a line "System.Diagnostics.Debugger.Break()" to the constructor of your class. Then try to use it in the designer, and you'll get a popup asking you if you want to attach a debugger. Attach a second instance of Visual Studio as a debugger, and you'll be able to set some breakpoints in your code and start debugging.
110,887
<p>Is there a way to read a module's configuration ini file? </p> <p>For example I installed php-eaccelerator (<a href="http://eaccelerator.net" rel="nofollow noreferrer">http://eaccelerator.net</a>) and it put a <code>eaccelerator.ini</code> file in <code>/etc/php.d</code>. My PHP installation wont read this <code>.ini</code> file because the <code>--with-config-file-scan-dir</code> option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings?</p>
[ { "answer_id": 110899, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 1, "selected": false, "text": "<p>The standard way in this instance is to copy the relevant .ini lines to the bottom of the php.ini file. There is no 'include \"file.ini\"' functionality in the php.ini file itself.</p>\n\n<p>You can't do it at run time either, since the extension has already been initialised by then.</p>\n" }, { "answer_id": 110907, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": true, "text": "<p>This is just a wild guess, but try to add all the directives from eaccelerator.ini to php.ini. First create a <code>&lt;?php phpinfo(); ?&gt;</code> and check where it's located.</p>\n\n<p>For example, try this:</p>\n\n<pre><code>[eAccelerator]\nextension=\"eaccelerator.so\"\neaccelerator.shm_size=\"32\"\neaccelerator.cache_dir=\"/tmp\"\neaccelerator.enable=\"1\"\neaccelerator.optimizer=\"1\"\neaccelerator.check_mtime=\"1\"\neaccelerator.debug=\"0\"\neaccelerator.filter=\"\"\neaccelerator.shm_max=\"0\"\neaccelerator.shm_ttl=\"0\"\neaccelerator.shm_prune_period=\"0\"\neaccelerator.shm_only=\"0\"\neaccelerator.compress=\"1\"\neaccelerator.compress_level=\"9\"\n</code></pre>\n\n<p>Another thing you could do is set all the settings on run-time using ini_set(). I am not sure if that works though or how effective that is. :) I am not familiar with eAccelerator to know for sure.</p>\n" }, { "answer_id": 110965, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "<p>If using Apache, and mod-php, you can configure/override some php settings locally with a <a href=\"http://www.php.net/manual/en/apache.configuration.php\" rel=\"nofollow noreferrer\">.htaccess file</a>. Your webserver has to \"AlloweOverride\" appropriately in the main config file to allow you to override these settings locally. In my experience, many hosting companies will let you set php settings via htaccess.</p>\n\n<p>(thanks commenter for pointing out this only works with mod-php)</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983/" ]
Is there a way to read a module's configuration ini file? For example I installed php-eaccelerator (<http://eaccelerator.net>) and it put a `eaccelerator.ini` file in `/etc/php.d`. My PHP installation wont read this `.ini` file because the `--with-config-file-scan-dir` option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings?
This is just a wild guess, but try to add all the directives from eaccelerator.ini to php.ini. First create a `<?php phpinfo(); ?>` and check where it's located. For example, try this: ``` [eAccelerator] extension="eaccelerator.so" eaccelerator.shm_size="32" eaccelerator.cache_dir="/tmp" eaccelerator.enable="1" eaccelerator.optimizer="1" eaccelerator.check_mtime="1" eaccelerator.debug="0" eaccelerator.filter="" eaccelerator.shm_max="0" eaccelerator.shm_ttl="0" eaccelerator.shm_prune_period="0" eaccelerator.shm_only="0" eaccelerator.compress="1" eaccelerator.compress_level="9" ``` Another thing you could do is set all the settings on run-time using ini\_set(). I am not sure if that works though or how effective that is. :) I am not familiar with eAccelerator to know for sure.
110,894
<p>I've got C# code that accesses MySQL through ODBC.</p> <p>It creates a transaction, does a few thousand insert commands, and then commits. Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way?</p>
[ { "answer_id": 110915, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "<p>It's hard to say without seeing your code, but I'm assuming you are executing the statements one at a time. So, you will get one round trip per insert statement.</p>\n\n<p>In MSSql you can execute multiple inserts in a single statement:</p>\n\n<pre><code>cmd.ExecuteNonQuery \"insert table values (1) insert table values (2)\"\n</code></pre>\n\n<p>So you can create a big string and execute it (I think it will have a limit), I assume this will work for MySQL.</p>\n\n<p>Also in MSSQL you have a batch inserter (lookup \"SqlBulkCopy\"), in MySQL perhaps try <a href=\"http://dev.mysql.com/doc/refman/5.0/en/load-data.html\" rel=\"nofollow noreferrer\">loading the data from a temp file</a>. </p>\n" }, { "answer_id": 110918, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>It does one round trip per query you submit (regardless of whether it's in a transaction or not).</p>\n\n<p>It is possible, in MySQL, to use \"extended insert\" syntax which allows you to insert several (or indeed, many) rows in a single statement. This is generally considered a Good Thing.</p>\n" }, { "answer_id": 110921, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": -1, "selected": false, "text": "<p>When using MySQL 4.x a few years ago, we ran into a hard limit on query size that was not configurable. </p>\n\n<p>This probably won't help you much as:</p>\n\n<ol>\n<li>I don't remember what the hard limit was.</li>\n<li>You're probably not using MySQL 4.x. </li>\n<li>We weren't using transactions.</li>\n</ol>\n\n<p>Good luck!</p>\n" }, { "answer_id": 110932, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": false, "text": "<p>A round trip to the DB server is not the same as a round trip to the database on disk. </p>\n\n<p>Before you decide that the round trips are a bottleneck, do some actual measurements. </p>\n\n<p>There are ways to insert multiple rows with a single insert, depending on your DBMS. Before you invest the coding effort, figure out whether it's likely to do you any good.</p>\n" }, { "answer_id": 110955, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 5, "selected": true, "text": "<p>MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time:</p>\n\n<pre><code>INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015);\n</code></pre>\n\n<p>I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead of parsing and communication by batching them yourself.</p>\n" }, { "answer_id": 1200174, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It depends on where you invoke the SQL statement. I tried it once with MySQL JDBC driver and got an error saying the limit is 1MB but it is configurable. </p>\n\n<p>I didn't bother to try to configure it and just split the SQL statements into smaller pieces.</p>\n" }, { "answer_id": 4565648, "author": "thushara", "author_id": 485391, "author_profile": "https://Stackoverflow.com/users/485391", "pm_score": 2, "selected": false, "text": "<p>There is no limit on the number of rows per se; The limit is on the number of bytes transferred to the server.</p>\n\n<p>You could build the bulk insert up to the number of bytes specified in 'max allowed packet'. If I wanted to use the least amount of inserts I would try that. </p>\n" }, { "answer_id": 20706664, "author": "siefca", "author_id": 617851, "author_profile": "https://Stackoverflow.com/users/617851", "pm_score": 0, "selected": false, "text": "<p>The limit of data that will be send depends on your server so the maximal length of multiple insert statements is automagically adjusted to fit. The bottleneck is a packet length and a buffer length.</p>\n\n<p>See the <code>net_buffer_length</code> and <code>max_allowed_packet</code> variable descriptions for more info:</p>\n\n<p><a href=\"https://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_net_buffer_length\" rel=\"nofollow\">https://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_net_buffer_length</a>\n<a href=\"https://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_max_allowed_packet\" rel=\"nofollow\">https://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_max_allowed_packet</a></p>\n\n<p>In some cases you can adjust these (e.g. when dumping data) to not generate inserts that are too long yet preserve multiple inserts. Be aware that if you have some blobs in your tables or any other long values that might exceede values of the mentioned variables you may get errors or incomplete data.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11208/" ]
I've got C# code that accesses MySQL through ODBC. It creates a transaction, does a few thousand insert commands, and then commits. Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way?
MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time: ``` INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015); ``` I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead of parsing and communication by batching them yourself.
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function to exit my application?</p>
[ { "answer_id": 110929, "author": "Matt Gregory", "author_id": 10577, "author_profile": "https://Stackoverflow.com/users/10577", "pm_score": 6, "selected": false, "text": "<pre><code>def quit()\n root.quit()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>def quit()\n root.destroy()\n</code></pre>\n" }, { "answer_id": 111011, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 2, "selected": false, "text": "<p>The usual method to exit a Python program:</p>\n\n<pre><code>sys.exit()\n</code></pre>\n\n<p>(to which you can also pass an exit status) or </p>\n\n<pre><code>raise SystemExit\n</code></pre>\n\n<p>will work fine in a Tkinter program.</p>\n" }, { "answer_id": 294199, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>import tkinter as tk\n\ndef quit(root):\n root.destroy()\n\nroot = tk.Tk()\ntk.Button(root, text=&quot;Quit&quot;, command=lambda root=root:quit(root)).pack()\nroot.mainloop()\n</code></pre>\n" }, { "answer_id": 15577605, "author": "aki92", "author_id": 2142721, "author_profile": "https://Stackoverflow.com/users/2142721", "pm_score": 8, "selected": true, "text": "<p><strong>You should use <code>destroy()</code> to close a Tkinter window.</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>from Tkinter import * \n#use tkinter instead of Tkinter (small, not capital T) if it doesn't work\n#as it was changed to tkinter in newer Python versions\n\nroot = Tk()\nButton(root, text=&quot;Quit&quot;, command=root.destroy).pack() #button to close the window\nroot.mainloop()\n</code></pre>\n<hr />\n<p><strong>Explanation:</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>root.quit()\n</code></pre>\n<p>The above line just <em><strong>bypasses</strong></em> the <code>root.mainloop()</code>, i.e., <code>root.mainloop()</code> will still be running <em><strong>in the background</strong></em> if <code>quit()</code> command is executed.</p>\n<pre class=\"lang-py prettyprint-override\"><code>root.destroy()\n</code></pre>\n<p>While <code>destroy()</code> command vanishes out <code>root.mainloop()</code>, i.e., <code>root.mainloop()</code> stops. <code>&lt;window&gt;.destroy()</code> <em><strong>completely</strong></em> destroys and <em>closes</em> the window.</p>\n<p>So, if you want to exit and close the program completely, you should use <code>root.destroy()</code>, as it stops the <code>mainloop()</code> and destroys the window and all its widgets.</p>\n<p>But if you want to run some infinite loop and don't want to destroy your Tkinter window and want to execute some code after the <code>root.mainloop()</code> line, you should use <code>root.quit()</code>. Example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from Tkinter import *\ndef quit():\n global root\n root.quit()\n\nroot = Tk()\nwhile True:\n Button(root, text=&quot;Quit&quot;, command=quit).pack()\n root.mainloop()\n #do something\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/questions/2307464/what-is-the-difference-between-root-destroy-and-root-quit\">What is the difference between root.destroy() and root.quit()?</a>.</p>\n" }, { "answer_id": 18852907, "author": "TreeDoNotSplit", "author_id": 2788026, "author_profile": "https://Stackoverflow.com/users/2788026", "pm_score": 3, "selected": false, "text": "<p>I think you wrongly understood the quit function of Tkinter. This function does not require you to define.</p>\n\n<p>First, you should modify your function as follows:</p>\n\n<pre><code>from Tkinter import *\nroot = Tk()\nButton(root, text=\"Quit\", command=root.quit).pack()\nroot.mainloop()\n</code></pre>\n\n<p>Then, you should use '.pyw' suffix to save this files and double-click the '.pyw' file to run your GUI, this time, you can end the GUI with a click of the Button, and you can also find that there will be no unpleasant DOS window. (If you run the '.py' file, the quit function will fail.)</p>\n" }, { "answer_id": 39174800, "author": "Martin Guiles", "author_id": 6763094, "author_profile": "https://Stackoverflow.com/users/6763094", "pm_score": 3, "selected": false, "text": "<p>Illumination in case of confusion...</p>\n\n<pre><code>def quit(self):\n self.destroy()\n exit()\n</code></pre>\n\n<p>A) destroy() stops the mainloop and kills the window, but leaves python running</p>\n\n<p>B) exit() stops the whole process</p>\n\n<p>Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to \"end\" a tkinter program.</p>\n" }, { "answer_id": 44122214, "author": "RAD", "author_id": 5153622, "author_profile": "https://Stackoverflow.com/users/5153622", "pm_score": 1, "selected": false, "text": "<p>In <code>idlelib.PyShell</code> module, <code>root</code> variable of type <code>Tk</code> is defined to be global</p>\n\n<p>At the end of <code>PyShell.main()</code> function it calls <code>root.mainloop()</code> function which is an infinite loop and it runs till the loop is interrupted by <code>root.quit()</code> function. Hence, <code>root.quit()</code> will only interrupt the execution of <code>mainloop</code></p>\n\n<p>In order to destroy all widgets pertaining to that idlelib window, <code>root.destroy()</code> needs to be called, which is the last line of <code>idlelib.PyShell.main()</code> function.</p>\n" }, { "answer_id": 51495698, "author": "Ian Gabaraev", "author_id": 9612362, "author_profile": "https://Stackoverflow.com/users/9612362", "pm_score": 2, "selected": false, "text": "<p>The easiest way would be to click the red button (leftmost on macOS and rightmost on Windows).\nIf you want to bind a specific function to a button widget, you can do this:</p>\n\n<pre><code>class App:\n def __init__(self, master)\n frame = Tkinter.Frame(master)\n frame.pack()\n self.quit_button = Tkinter.Button(frame, text = 'Quit', command = frame.quit)\n self.quit_button.pack()\n</code></pre>\n\n<p>Or, to make things a little more complex, use protocol handlers and the <code>destroy()</code> method.</p>\n\n<pre><code>import tkMessageBox\n\ndef confirmExit():\n if tkMessageBox.askokcancel('Quit', 'Are you sure you want to exit?'):\n root.destroy()\nroot = Tk()\nroot.protocol('WM_DELETE_WINDOW', confirmExit)\nroot.mainloop()\n</code></pre>\n" }, { "answer_id": 53041670, "author": "Nukyi", "author_id": 10324360, "author_profile": "https://Stackoverflow.com/users/10324360", "pm_score": 2, "selected": false, "text": "<p>In case anyone wants to bind their Escape button to closing the entire GUI:</p>\n\n<pre><code>master = Tk()\nmaster.title(\"Python\")\n\ndef close(event):\n sys.exit()\n\nmaster.bind('&lt;Escape&gt;',close)\nmaster.mainloop()\n</code></pre>\n" }, { "answer_id": 53755060, "author": "LenyaKap", "author_id": 10784099, "author_profile": "https://Stackoverflow.com/users/10784099", "pm_score": 0, "selected": false, "text": "<p>For menu bars:</p>\n\n<pre><code>def quit():\n root.destroy()\n\nmenubar = Menu(root)\nfilemenu = Menu(menubar, tearoff=0)\n\nfilemenu.add_separator()\n\nfilemenu.add_command(label=\"Exit\", command=quit)\nmenubar.add_cascade(label=\"menubarname\", menu=filemenu)\nroot.config(menu=menubar)\nroot.mainloop()\n</code></pre>\n" }, { "answer_id": 55536097, "author": "BruhDev", "author_id": 10686694, "author_profile": "https://Stackoverflow.com/users/10686694", "pm_score": 2, "selected": false, "text": "<p>you only need to type this:</p>\n\n<pre><code>root.destroy()\n</code></pre>\n\n<p>and you don't even need the quit() function cause when you set that as commmand it will quit the entire program.</p>\n" }, { "answer_id": 55957531, "author": "kourosh", "author_id": 11007580, "author_profile": "https://Stackoverflow.com/users/11007580", "pm_score": 0, "selected": false, "text": "<p>I use below codes for the exit of Tkinter window:</p>\n\n<pre><code>from tkinter import*\nroot=Tk()\nroot.bind(\"&lt;Escape&gt;\",lambda q:root.destroy())\nroot.mainloop()\n</code></pre>\n\n<p>or </p>\n\n<pre><code>from tkinter import*\nroot=Tk()\nButton(root,text=\"exit\",command=root.destroy).pack()\nroot.mainloop()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>from tkinter import*\nroot=Tk()\nButton(root,text=\"quit\",command=quit).pack()\nroot.mainloop()\n</code></pre>\n\n<p>or </p>\n\n<pre><code>from tkinter import*\nroot=Tk()\nButton(root,text=\"exit\",command=exit).pack()\nroot.mainloop()\n</code></pre>\n" }, { "answer_id": 57989602, "author": "Ozzius", "author_id": 4520574, "author_profile": "https://Stackoverflow.com/users/4520574", "pm_score": 0, "selected": false, "text": "<p>Code snippet below. I'm providing a small scenario.</p>\n\n<pre><code>import tkinter as tk\nfrom tkinter import *\n\nroot = Tk()\n\ndef exit():\n if askokcancel(\"Quit\", \"Do you really want to quit?\"):\n root.destroy()\n\nmenubar = Menu(root, background='#000099', foreground='white',\n activebackground='#004c99', activeforeground='white')\n\nfileMenu = Menu(menubar, tearoff=0, background=\"grey\", foreground='black',\n activebackground='#004c99', activeforeground='white')\nmenubar.add_cascade(label='File', menu=fileMenu)\n\nfileMenu.add_command(label='Exit', command=exit)\n\nroot.config(bg='#2A2C2B',menu=menubar)\n\nif __name__ == '__main__':\n root.mainloop()\n</code></pre>\n\n<p>I have created a blank window here &amp; add file menu option on the same window(root window), where I only add one option <strong>exit</strong>. </p>\n\n<p>Then simply <strong>run mainloop</strong> for <strong>root</strong>. </p>\n\n<p>Try to do it once</p>\n" }, { "answer_id": 61335741, "author": "snookso", "author_id": 13298841, "author_profile": "https://Stackoverflow.com/users/13298841", "pm_score": -1, "selected": false, "text": "<p>There is a simple one-line answer:</p>\n\n<p>Write - <code>exit()</code> in the command</p>\n\n<p>That's it!</p>\n" }, { "answer_id": 66198672, "author": "Geetansh G", "author_id": 13010024, "author_profile": "https://Stackoverflow.com/users/13010024", "pm_score": 0, "selected": false, "text": "<p>Of course you can assign the command to the button as follows, however, if you are making a UI, it is recommended to assign the same command to the &quot;X&quot; button:</p>\n<pre><code>def quit(self): # Your exit routine\n self.root.destroy()\n\nself.root.protocol(&quot;WM_DELETE_WINDOW&quot;, self.quit) # Sets the command for the &quot;X&quot; button \n\nButton(text=&quot;Quit&quot;, command=self.quit) # No ()\n\n</code></pre>\n" }, { "answer_id": 68531313, "author": "UnlinedBus", "author_id": 16516820, "author_profile": "https://Stackoverflow.com/users/16516820", "pm_score": 1, "selected": false, "text": "<p>I normally use the default tkinter <code>quit</code> function, but you can do your own, like this:</p>\n<pre><code>from tkinter import *\nfrom tkinter.ttk import *\n\nwindow = Tk()\nwindow.geometry('700x700') # 700p x 700p screen\n\ndef quit(self):\n proceed = messagebox.askyesno('Quit', 'Quit?')\n proceed = bool(proceed) # So it is a bool\n\n if proceed:\n window.quit()\n else:\n # You don't really need to do this\n pass\n\nbtn1 = Button(window, text='Quit', command=lambda: quit(None))\n\nwindow.mainloop()\n</code></pre>\n" }, { "answer_id": 68562764, "author": "Gonzalez", "author_id": 16466088, "author_profile": "https://Stackoverflow.com/users/16466088", "pm_score": 2, "selected": false, "text": "<p>you dont have to open up a function to close you window, unless you're doing something more complicated:</p>\n<pre><code>from Tkinter import *\n\nroot = Tk()\nButton(root, text=&quot;Quit&quot;, command=root.destroy).pack()\nroot.mainloop()\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
How do I end a Tkinter program? Let's say I have this code: ``` from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() ``` How should I define the `quit` function to exit my application?
**You should use `destroy()` to close a Tkinter window.** ```py from Tkinter import * #use tkinter instead of Tkinter (small, not capital T) if it doesn't work #as it was changed to tkinter in newer Python versions root = Tk() Button(root, text="Quit", command=root.destroy).pack() #button to close the window root.mainloop() ``` --- **Explanation:** ```py root.quit() ``` The above line just ***bypasses*** the `root.mainloop()`, i.e., `root.mainloop()` will still be running ***in the background*** if `quit()` command is executed. ```py root.destroy() ``` While `destroy()` command vanishes out `root.mainloop()`, i.e., `root.mainloop()` stops. `<window>.destroy()` ***completely*** destroys and *closes* the window. So, if you want to exit and close the program completely, you should use `root.destroy()`, as it stops the `mainloop()` and destroys the window and all its widgets. But if you want to run some infinite loop and don't want to destroy your Tkinter window and want to execute some code after the `root.mainloop()` line, you should use `root.quit()`. Example: ```py from Tkinter import * def quit(): global root root.quit() root = Tk() while True: Button(root, text="Quit", command=quit).pack() root.mainloop() #do something ``` See [What is the difference between root.destroy() and root.quit()?](https://stackoverflow.com/questions/2307464/what-is-the-difference-between-root-destroy-and-root-quit).
111,026
<p>Which is the best way to store a 2D array in c# in order to optimize performance when performing lots of arithmetic on the elements in the array?</p> <p>We have large (approx 1.5G) arrays, which for example we want to multiply with each other element by element. Performance is critical. The context in which this is done is in c#. Is there any smart way of storing the arrays and iterating over them? Could we write these parts in unmanaged C++ and will this really increase performance? The arrays need to be accessible to the rest of the c# program. </p> <p>Currently (in c) the array is stored as a single long vector. We perform calculations on each element in the array and overwrite the old value. The calculations are usually unique for each element in the vector.</p> <p>Timing experiments show that storing and iterating over the data as an array in C# is slower than storing it as a 2D array. I would like to know if there is an even better way of handling the data. The specific arithmetics performed are not relevant for the question.</p>
[ { "answer_id": 111046, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 3, "selected": false, "text": "<p>For best array performance, make sure you're using a single dimension array with lower index of 0.</p>\n\n<p>To access the elements of the array as fast as possible, you can use unsafe pointers like so:</p>\n\n<pre><code>int[] array = Enumerable.Range(0, 1000).ToArray();\n\nint count = 0;\nunsafe {\n fixed (int* pArray = array) {\n for (int i = 0; i &lt; array.Length; i++) {\n count += *(pArray + i);\n }\n }\n}\n</code></pre>\n\n<p><strong>EDIT</strong> Drat! Didn't notice you said 2D array. This trick won't work with a multi-dimensional array so I'm not sure how much help it will be. Although you could turn any array into a single-dimension array by doing some arithmetic on the array index. Just depends on if you care about the performance hit in indexing the array or in iterating over the array.</p>\n" }, { "answer_id": 111073, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 3, "selected": false, "text": "<p>Anna,</p>\n\n<p>Here is a great page that discusses the performance difference between tradition scientific programming languages (fortran, C++) and c#.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc163995.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163995.aspx</a></p>\n\n<p>According to the article C#, when using rectangular arrays (2d) can be a very good performer. Here is a graph that shows the difference in performance between jagged arrays (an array of arrays) and rectangular arrays (multi-dimensional) arrays.</p>\n\n<p><a href=\"http://i.msdn.microsoft.com/cc163995.fig08.gif\" rel=\"noreferrer\">alt text http://i.msdn.microsoft.com/cc163995.fig08.gif</a></p>\n\n<p>I would suggest experimenting yourself, and use the Performance Analysis in VS 2008 to compare.</p>\n\n<p>If using C# is \"fast enough\" then your application will be that much easier to maintain.</p>\n\n<p>Good Luck!</p>\n" }, { "answer_id": 111088, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 2, "selected": false, "text": "<p>If you download F#, and reference one of the runtime libraries (I think it's FSharp.PowerPack), and use Microsoft.FSharp.Maths.Matrix. It optimises itself based on whether you are using a dense or sparse matrix.</p>\n" }, { "answer_id": 111136, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": "<p>Do you iterate the matrix by row or by colum or both? Do you always access nearby elements or do you do random accesses on the matrix.</p>\n\n<p>If there is some locality in your accesses but you're not accessing it sequential (typical in matrix multiplication for example) then you can get a <em>huge</em> performance difference by storing your matrix in a more cache-friendly way.</p>\n\n<p>A pretty easy way to do that is to write a little access function to turn your row/colum indices into an index and work on a one dimensional matrix, the cache-friendy way.</p>\n\n<p>The function should group nearby coordinates into nearby indices. The morton-order can be used if you work on power of two sizes. For non-power sizes you can often bring just the lowest 4 bits into morton order and use normal index-arithmetic for the upper bits. You'll still get a significant speed-up, even if the coordinate to index conversion looks seems to be a costly operation.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Z-order_(curve)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Z-order_(curve)</a> &lt;-- sorry, can't link that SO does not like URL's with a dash in it. You have to cut'n'paste.</p>\n\n<p>A speed up of factor 10 and more are realistic btw. It depends on the algorithm you ron over your matrices though.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044/" ]
Which is the best way to store a 2D array in c# in order to optimize performance when performing lots of arithmetic on the elements in the array? We have large (approx 1.5G) arrays, which for example we want to multiply with each other element by element. Performance is critical. The context in which this is done is in c#. Is there any smart way of storing the arrays and iterating over them? Could we write these parts in unmanaged C++ and will this really increase performance? The arrays need to be accessible to the rest of the c# program. Currently (in c) the array is stored as a single long vector. We perform calculations on each element in the array and overwrite the old value. The calculations are usually unique for each element in the vector. Timing experiments show that storing and iterating over the data as an array in C# is slower than storing it as a 2D array. I would like to know if there is an even better way of handling the data. The specific arithmetics performed are not relevant for the question.
For best array performance, make sure you're using a single dimension array with lower index of 0. To access the elements of the array as fast as possible, you can use unsafe pointers like so: ``` int[] array = Enumerable.Range(0, 1000).ToArray(); int count = 0; unsafe { fixed (int* pArray = array) { for (int i = 0; i < array.Length; i++) { count += *(pArray + i); } } } ``` **EDIT** Drat! Didn't notice you said 2D array. This trick won't work with a multi-dimensional array so I'm not sure how much help it will be. Although you could turn any array into a single-dimension array by doing some arithmetic on the array index. Just depends on if you care about the performance hit in indexing the array or in iterating over the array.
111,097
<p><strong>EDIT:</strong> This was formerly more explicitly titled: - "<strong>Best solution to stop Kontiki's KHOST.EXE from loading automatically at start-up on Windows XP?</strong>"</p> <p>Essentially, whenever the <strong><a href="http://www.channel4.com/4od/index.html" rel="nofollow noreferrer">40D</a></strong> application is run it sets up <strong>khost.exe</strong> to automatically start-up with Windows. This is annoying as it increases my boot up time by a couple of minutes and I don't even use the P2P aspect of 4OD anyway.</p> <p>The registry keys that are set are:</p> <pre><code>Command: C:\Program Files\Kontiki\KHost.exe -all Description: kdx Location: HKU\S-1-5-21-1757981266-1960408961-839522115-1003\SOFTWARE\Microsoft\Windows\CurrentVersion\Run Name: kdx Setting ID: User: LAPTOP\Me Command: "C:\Program Files\Kontiki\KHost.exe" -all Description: 4oD Location: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run Name: 4oD Setting ID: User: All Users </code></pre> <p>I'm assuming some kind of <strong>start-up</strong> or <strong>shut-down</strong> <strong>script</strong> to delete these registry keys would be the best solution, but I'm not that up with <strong>.vbs</strong> or <strong>.bat</strong> scripting or where I'd put them to automatically run at an appropriate time.</p> <p>I know there is a <strong><a href="http://odmonitor.blogspot.com/" rel="nofollow noreferrer">TV On-Demand Monitor application</a></strong>, but I don't really need to be running yet another process, I just need to delete the registry keys as I describe above.</p>
[ { "answer_id": 111134, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "<p>Why not just copy the executable to some other name, and put a do-nothing exe in its place. Then change your shortcuts to the copied and renamed EXE. If the program is sensitive to its name, then point your shortcuts to a VBS file to temporarily rename the EXE file.</p>\n" }, { "answer_id": 111137, "author": "beakersoft", "author_id": 19638, "author_profile": "https://Stackoverflow.com/users/19638", "pm_score": 2, "selected": true, "text": "<p>for the vb script you would use something like this:</p>\n\n<pre><code>Dim WSHShell\nSet WSHShell = WScript.CreateObject(\"WScript.Shell\")\n'repeat the line below for each key to delete \nWSHShell.RegDelete \"[Location of Key]\"\n</code></pre>\n\n<p>Just drop the code into a text file and re-name it something like shutdown,vbs.</p>\n\n<p>As for when to run it, if you are in a corporate environment you could use a group policy and set it as a machine shutdown script. Alternatively, see this page <a href=\"http://www.msfn.org/board/lofiversion/index.php/t40945.html\" rel=\"nofollow noreferrer\">here</a> about adding it manually</p>\n" }, { "answer_id": 111154, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "<p>Another method:</p>\n\n<p>Create a VBS file that runs the program and then deletes the registry keys.</p>\n\n<pre><code>Set objShell = CreateObject(\"WScript.Shell\") \n\nobjShell.Exec(\"C:\\Program Files\\Kontiki\\KHost.exe\")\n\nstrRoot = \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\4oD\" \nstrDelete = objShell.RegDelete(strRoot) \n...\n</code></pre>\n\n<p>And point your shortcuts at that.</p>\n" }, { "answer_id": 111198, "author": "Pascal T.", "author_id": 19816, "author_profile": "https://Stackoverflow.com/users/19816", "pm_score": 1, "selected": false, "text": "<p>Should I suggest you give a try to AutoIt (<a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">http://www.autoitscript.com/autoit3/</a>), a freeware scripting language designed for automating the Windows GUI and general scripting.</p>\n\n<p>If you choose to use it, the AutoIt code for your need would be a 2-liner:</p>\n\n<pre><code>RegDelete(\"YourKey\", \"YourValue\");\nShutDown(1);\n</code></pre>\n\n<p>And you can compile it into a standalone exe that can run on any computer (no runtime library needed)</p>\n" }, { "answer_id": 111394, "author": "Matt", "author_id": 17759, "author_profile": "https://Stackoverflow.com/users/17759", "pm_score": 2, "selected": false, "text": "<p><strong>What I ended up doing in the end:</strong></p>\n\n<p><strong>1)</strong> Stopped <strong>40D</strong> from the task tray with a <strong>right-click</strong> > <strong>exit</strong> which terminated the <strong>Khost.exe</strong> process.</p>\n\n<p><strong>2)</strong> Opened <strong>Start</strong> > <strong>All Programs</strong> > <strong>Administrative Tools</strong> > <strong>Services</strong> and stopped <strong>KService</strong> then set the <strong>Startup Type</strong> to '<strong>Manual</strong>'.</p>\n\n<p><strong>3)</strong> Created a <strong><em>ShutdownScript.vbs</em></strong> with the following content:</p>\n\n<pre><code>Set SH = CreateObject(\"WScript.Shell\")\n\nRemoveRegKey \"HKU\\S-1-5-21-1757981266-1960408961-839522115-1003\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\kdx\"\nRemoveRegKey \"HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\kdx\"\nRemoveRegKey \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\4oD\"\n\nShutdown\n\nSet Shell = Nothing\nSet SH = Nothing\nWScript.Quit\n\nSub RemoveRegKey(sKey)\n On Error Resume Next\n SH.RegDelete sKey\nEnd Sub\n\nSub Shutdown()\n SH.Run \"shutdown -s -t 1\", 0, TRUE\nEnd Sub\n</code></pre>\n\n<p><strong>4)</strong> Put a <strong>shortcut</strong> to the script in my <strong>Start Menu</strong> and now use that to shut the PC down.</p>\n\n<p>Now <strong>40D</strong> will work when I need it, and all I have to do is quit it and shutdown with the script to stop it auto-starting everytime I boot up the PC.</p>\n\n<p><strong>THANKS FOR ALL YOUR HELP WITH THIS! :)</strong></p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17759/" ]
**EDIT:** This was formerly more explicitly titled: - "**Best solution to stop Kontiki's KHOST.EXE from loading automatically at start-up on Windows XP?**" Essentially, whenever the **[40D](http://www.channel4.com/4od/index.html)** application is run it sets up **khost.exe** to automatically start-up with Windows. This is annoying as it increases my boot up time by a couple of minutes and I don't even use the P2P aspect of 4OD anyway. The registry keys that are set are: ``` Command: C:\Program Files\Kontiki\KHost.exe -all Description: kdx Location: HKU\S-1-5-21-1757981266-1960408961-839522115-1003\SOFTWARE\Microsoft\Windows\CurrentVersion\Run Name: kdx Setting ID: User: LAPTOP\Me Command: "C:\Program Files\Kontiki\KHost.exe" -all Description: 4oD Location: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run Name: 4oD Setting ID: User: All Users ``` I'm assuming some kind of **start-up** or **shut-down** **script** to delete these registry keys would be the best solution, but I'm not that up with **.vbs** or **.bat** scripting or where I'd put them to automatically run at an appropriate time. I know there is a **[TV On-Demand Monitor application](http://odmonitor.blogspot.com/)**, but I don't really need to be running yet another process, I just need to delete the registry keys as I describe above.
for the vb script you would use something like this: ``` Dim WSHShell Set WSHShell = WScript.CreateObject("WScript.Shell") 'repeat the line below for each key to delete WSHShell.RegDelete "[Location of Key]" ``` Just drop the code into a text file and re-name it something like shutdown,vbs. As for when to run it, if you are in a corporate environment you could use a group policy and set it as a machine shutdown script. Alternatively, see this page [here](http://www.msfn.org/board/lofiversion/index.php/t40945.html) about adding it manually
111,102
<p>How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?</p> <p>I have seen <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" rel="noreferrer">the Scheme example</a> given on Wikipedia, but unfortunately it did not help.</p>
[ { "answer_id": 111111, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 14, "selected": true, "text": "<p>A closure is a pairing of:</p>\n<ol>\n<li>A function and</li>\n<li>A reference to that function's outer scope (lexical environment)</li>\n</ol>\n<p>A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.</p>\n<p>Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to &quot;see&quot; variables declared outside the function, regardless of when and where the function is called.</p>\n<p>If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.</p>\n<p>In the following code, <code>inner</code> forms a closure with the lexical environment of the execution context created when <code>foo</code> is invoked, <em>closing over</em> variable <code>secret</code>:</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>function foo() {\n const secret = Math.trunc(Math.random() * 100)\n return function inner() {\n console.log(`The secret number is ${secret}.`)\n }\n}\nconst f = foo() // `secret` is not directly accessible from outside `foo`\nf() // The only way to retrieve `secret`, is to invoke `f`</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>In other words: in JavaScript, functions carry a reference to a private &quot;box of state&quot;, to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.</p>\n<p>And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.</p>\n<p>If JavaScript did not have closures, then more states would have to be passed between functions <em>explicitly</em>, making parameter lists longer and code noisier.</p>\n<p>So, if you want a function to always have access to a private piece of state, you can use a closure.</p>\n<p>...and frequently we <em>do</em> want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality.</p>\n<p>In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, <code>secret</code> remains available to the function object <code>inner</code>, <em>after</em> it has been returned from <code>foo</code>.</p>\n<h2>Uses of Closures</h2>\n<p>Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.</p>\n<h3>Private Instance Variables</h3>\n<p>In the following code, the function <code>toString</code> closes over the details of the car.</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>function Car(manufacturer, model, year, color) {\n return {\n toString() {\n return `${manufacturer} ${model} (${year}, ${color})`\n }\n }\n}\n\nconst car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver')\nconsole.log(car.toString())</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Functional Programming</h3>\n<p>In the following code, the function <code>inner</code> closes over both <code>fn</code> and <code>args</code>.</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>function curry(fn) {\n const args = []\n return function inner(arg) {\n if(args.length === fn.length) return fn(...args)\n args.push(arg)\n return inner\n }\n}\n\nfunction add(a, b) {\n return a + b\n}\n\nconst curriedAdd = curry(add)\nconsole.log(curriedAdd(2)(3)()) // 5</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Event-Oriented Programming</h3>\n<p>In the following code, function <code>onClick</code> closes over variable <code>BACKGROUND_COLOR</code>.</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>const $ = document.querySelector.bind(document)\nconst BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)'\n\nfunction onClick() {\n $('body').style.background = BACKGROUND_COLOR\n}\n\n$('button').addEventListener('click', onClick)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button&gt;Set background color&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Modularization</h3>\n<p>In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions <code>tick</code> and <code>toString</code> close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our code.</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>let namespace = {};\n\n(function foo(n) {\n let numbers = []\n\n function format(n) {\n return Math.trunc(n)\n }\n\n function tick() {\n numbers.push(Math.random() * 100)\n }\n\n function toString() {\n return numbers.map(format)\n }\n\n n.counter = {\n tick,\n toString\n }\n}(namespace))\n\nconst counter = namespace.counter\ncounter.tick()\ncounter.tick()\nconsole.log(counter.toString())</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Examples</h2>\n<h3>Example 1</h3>\n<p>This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables <em>themselves</em>. It is as though the stack-frame stays alive in memory even after the outer function exits.</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>function foo() {\n let x = 42\n let inner = () =&gt; console.log(x)\n x = x + 1\n return inner\n}\n\nfoo()() // logs 43</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Example 2</h3>\n<p>In the following code, three methods <code>log</code>, <code>increment</code>, and <code>update</code> all close over the same lexical environment.</p>\n<p>And every time <code>createObject</code> is called, a new execution context (stack frame) is created and a completely new variable <code>x</code>, and a new set of functions (<code>log</code> etc.) are created, that close over this new variable.</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>function createObject() {\n let x = 42;\n return {\n log() { console.log(x) },\n increment() { x++ },\n update(value) { x = value }\n }\n}\n\nconst o = createObject()\no.increment()\no.log() // 43\no.update(5)\no.log() // 5\nconst p = createObject()\np.log() // 42</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Example 3</h3>\n<p>If you are using variables declared using <code>var</code>, be careful you understand which variable you are closing over. Variables declared using <code>var</code> are hoisted. This is much less of a problem in modern JavaScript due to the introduction of <code>let</code> and <code>const</code>.</p>\n<p>In the following code, each time around the loop, a new function <code>inner</code> is created, which closes over <code>i</code>. But because <code>var i</code> is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of <code>i</code> (3) is printed, three times.</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>function foo() {\n var result = []\n for (var i = 0; i &lt; 3; i++) {\n result.push(function inner() { console.log(i) } )\n }\n\n return result\n}\n\nconst result = foo()\n// The following will print `3`, three times...\nfor (var i = 0; i &lt; 3; i++) {\n result[i]() \n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Final points:</h2>\n<ul>\n<li>Whenever a function is declared in JavaScript closure is created.</li>\n<li>Returning a <code>function</code> from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.</li>\n<li>Whenever you use <code>eval()</code> inside a function, a closure is used. The text you <code>eval</code> can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using <code>eval('var foo = …')</code>.</li>\n<li>When you use <code>new Function(…)</code> (the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function\" rel=\"noreferrer\">Function constructor</a>) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.</li>\n<li>A closure in JavaScript is like keeping a reference (<strong>NOT</strong> a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.</li>\n<li>A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.</li>\n<li>A new set of local variables is created every time a function is called.</li>\n</ul>\n<h2>Links</h2>\n<ul>\n<li>Douglas Crockford's simulated <a href=\"http://www.crockford.com/javascript/private.html\" rel=\"noreferrer\">private attributes and private methods</a> for an object, using closures.</li>\n<li>A great explanation of how closures can <a href=\"https://www.codeproject.com/Articles/12231/Memory-Leakage-in-Internet-Explorer-revisited\" rel=\"noreferrer\">cause memory leaks in IE</a> if you are not careful.</li>\n<li>MDN documentation on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"noreferrer\">JavaScript Closures</a>.</li>\n</ul>\n" }, { "answer_id": 111114, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 9, "selected": false, "text": "<p><strong>TLDR</strong></p>\n\n<p>A closure is a link between a function and its outer lexical (ie. as-written) environment, such that the identifiers (variables, parameters, function declarations etc) defined within that environment are visible from within the function, regardless of when or from where the function is invoked.</p>\n\n<p><strong>Details</strong></p>\n\n<p>In the terminology of the ECMAScript specification, a closure can be said to be implemented by the <a href=\"https://www.ecma-international.org/ecma-262/10.0/index.html#sec-functioninitialize\" rel=\"noreferrer\"><code>[[Environment]]</code></a> reference of every function-object, which points to the <a href=\"https://www.ecma-international.org/ecma-262/10.0/index.html#sec-lexical-environments\" rel=\"noreferrer\">lexical environment</a> within which the function is defined.</p>\n\n<p>When a function is invoked via the internal <a href=\"https://www.ecma-international.org/ecma-262/10.0/index.html#sec-ecmascript-function-objects-call-thisargument-argumentslist\" rel=\"noreferrer\"><code>[[Call]]</code></a> method, the <a href=\"https://www.ecma-international.org/ecma-262/10.0/index.html#sec-functioninitialize\" rel=\"noreferrer\"><code>[[Environment]]</code></a> reference on the function-object is copied into the <em>outer environment reference</em> of the <a href=\"https://www.ecma-international.org/ecma-262/10.0/index.html#sec-environment-records\" rel=\"noreferrer\">environment record</a> of the newly-created <a href=\"https://www.ecma-international.org/ecma-262/10.0/index.html#sec-execution-contexts\" rel=\"noreferrer\">execution context</a> (stack frame).</p>\n\n<p>In the following example, function <code>f</code> closes over the lexical environment of the global execution context:</p>\n\n<pre><code>function f() {}\n</code></pre>\n\n<p>In the following example, function <code>h</code> closes over the lexical environment of function <code>g</code>, which, in turn, closes over the lexical environment of the global execution context.</p>\n\n<pre><code>function g() {\n function h() {}\n}\n</code></pre>\n\n<p>If an inner function is returned by an outer, then the outer lexical environment will persist after the outer function has returned. This is because the outer lexical environment needs to be available if the inner function is eventually invoked.</p>\n\n<p>In the following example, function <code>j</code> closes over the lexical environment of function <code>i</code>, meaning that variable <code>x</code> is visible from inside function <code>j</code>, long after function <code>i</code> has completed execution:</p>\n\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>function i() {\r\n var x = 'mochacchino'\r\n return function j() {\r\n console.log('Printing the value of x, from within function j: ', x)\r\n }\r\n} \r\n\r\nconst k = i()\r\nsetTimeout(k, 500) // invoke k (which is j) after 500ms</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In a closure, the variables in the outer lexical environment <em>themselves</em> are available, <em>not</em> copies.</p>\n\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>function l() {\r\n var y = 'vanilla';\r\n\r\n return {\r\n setY: function(value) {\r\n y = value;\r\n },\r\n logY: function(value) {\r\n console.log('The value of y is: ', y);\r\n }\r\n }\r\n}\r\n\r\nconst o = l()\r\no.logY() // The value of y is: vanilla\r\no.setY('chocolate')\r\no.logY() // The value of y is: chocolate</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The chain of lexical environments, linked between execution contexts via outer environment references, forms a <em>scope chain</em> and defines the identifiers visible from any given function.</p>\n\n<p><strong>Please note that in an attempt to improve clarity and accuracy, this answer has been substantially changed from the original.</strong></p>\n" }, { "answer_id": 111119, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 9, "selected": false, "text": "<p>Closures are hard to explain because they are used to make some behaviour work that everybody intuitively expects to work anyway. I find the best way to explain them (and the way that <em>I</em> learned what they do) is to imagine the situation without them:</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>const makePlus = function(x) {\n return function(y) { return x + y; };\n}\n\nconst plus5 = makePlus(5);\nconsole.log(plus5(3));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>What would happen here if JavaScript <em>didn't</em> know closures? Just replace the call in the last line by its method body (which is basically what function calls do) and you get:</p>\n<pre><code>console.log(x + 3);\n</code></pre>\n<p>Now, where's the definition of <code>x</code>? We didn't define it in the current scope. The only solution is to let <code>plus5</code> <em>carry</em> its scope (or rather, its parent's scope) around. This way, <code>x</code> is well-defined and it is bound to the value 5.</p>\n" }, { "answer_id": 111200, "author": "Ali", "author_id": 8689, "author_profile": "https://Stackoverflow.com/users/8689", "pm_score": 12, "selected": false, "text": "<p>Every function in JavaScript maintains a link to its outer lexical environment. A lexical environment is a map of all the names (eg. variables, parameters) within a scope, with their values.</p>\n\n<p>So, whenever you see the <code>function</code> keyword, code inside that function has access to variables declared outside the function.</p>\n\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>function foo(x) {\r\n var tmp = 3;\r\n\r\n function bar(y) {\r\n console.log(x + y + (++tmp)); // will log 16\r\n }\r\n\r\n bar(10);\r\n}\r\n\r\nfoo(2);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This will log <code>16</code> because function <code>bar</code> closes over the parameter <code>x</code> and the variable <code>tmp</code>, both of which exist in the lexical environment of outer function <code>foo</code>.</p>\n\n<p>Function <code>bar</code>, together with its link with the lexical environment of function <code>foo</code> is a closure. </p>\n\n<p>A function doesn't have to <em>return</em> in order to create a closure. Simply by virtue of its declaration, every function closes over its enclosing lexical environment, forming a closure.</p>\n\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>function foo(x) {\r\n var tmp = 3;\r\n\r\n return function (y) {\r\n console.log(x + y + (++tmp)); // will also log 16\r\n }\r\n}\r\n\r\nvar bar = foo(2);\r\nbar(10); // 16\r\nbar(10); // 17</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The above function will also log 16, because the code inside <code>bar</code> can still refer to argument <code>x</code> and variable <code>tmp</code>, even though they are no longer directly in scope.</p>\n\n<p>However, since <code>tmp</code> is still hanging around inside <code>bar</code>'s closure, it is available to be incremented. It will be incremented each time you call <code>bar</code>.</p>\n\n<p>The simplest example of a closure is this:</p>\n\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 a = 10;\r\n\r\nfunction test() {\r\n console.log(a); // will output 10\r\n console.log(b); // will output 6\r\n}\r\nvar b = 6;\r\ntest();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>When a JavaScript function is invoked, a new execution context <code>ec</code> is created. Together with the function arguments and the target object, this execution context also receives a link to the lexical environment of the calling execution context, meaning the variables declared in the outer lexical environment (in the above example, both <code>a</code> and <code>b</code>) are available from <code>ec</code>.</p>\n\n<p>Every function creates a closure because every function has a link to its outer lexical environment. </p>\n\n<p>Note that variables <em>themselves</em> are visible from within a closure, <em>not</em> copies.</p>\n" }, { "answer_id": 112252, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 7, "selected": false, "text": "<p>A closure is where an inner function has access to variables in its outer function. That's probably the simplest one-line explanation you can get for closures.</p>\n" }, { "answer_id": 2600408, "author": "dlaliberte", "author_id": 311389, "author_profile": "https://Stackoverflow.com/users/311389", "pm_score": 9, "selected": false, "text": "<p>This is an attempt to clear up several (possible) misunderstandings about closures that appear in some of the other answers.</p>\n\n<ul>\n<li><strong>A closure is not only created when you return an inner function.</strong> In fact, the enclosing function <em>does not need to return at all</em> in order for its closure to be created. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be called immediately or any time later. Therefore, the closure of the enclosing function is probably created <em>as soon as the enclosing function is called</em> since any inner function has access to that closure whenever the inner function is called, before or after the enclosing function returns. </li>\n<li><strong>A closure does not reference a copy of the <em>old values</em> of variables in its scope.</strong> The variables themselves are part of the closure, and so the value seen when accessing one of those variables is the latest value at the time it is accessed. This is why inner functions created inside of loops can be tricky, since each one has access to the same outer variables rather than grabbing a copy of the variables at the time the function is created or called.</li>\n<li><strong>The \"variables\" in a closure include any named functions</strong> declared within the function. They also include arguments of the function. A closure also has access to its containing closure's variables, all the way up to the global scope.</li>\n<li><strong>Closures use memory, but they don't cause memory leaks</strong> since JavaScript by itself cleans up its own circular structures that are not referenced. Internet&nbsp;Explorer memory leaks involving closures are created when it fails to disconnect DOM attribute values that reference closures, thus maintaining references to possibly circular structures.</li>\n</ul>\n" }, { "answer_id": 2673546, "author": "someisaac", "author_id": 167166, "author_profile": "https://Stackoverflow.com/users/167166", "pm_score": 7, "selected": false, "text": "<p>Example for the first point by dlaliberte:</p>\n\n<blockquote>\n <p>A closure is not only created when you return an inner function. In fact, the enclosing function does not need to return at all. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be used immediately. Therefore, the closure of the enclosing function probably already exists at the time that enclosing function was called since any inner function has access to it as soon as it is called.</p>\n</blockquote>\n\n<pre><code>var i;\nfunction foo(x) {\n var tmp = 3;\n i = function (y) {\n console.log(x + y + (++tmp));\n }\n}\nfoo(2);\ni(3);\n</code></pre>\n" }, { "answer_id": 2673583, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 8, "selected": false, "text": "<h2><a href=\"https://stackoverflow.com/questions/1700514/how-do-you-explain-closure-to-a-5-year-old/1700627#1700627\">Can you explain closures to a 5-year-old?*</a></h2>\n<p>I still think <a href=\"http://code.google.com/apis/ajax/playground/?exp=maps#closure_simple\" rel=\"noreferrer\">Google's explanation</a> works very well and is concise:</p>\n<pre><code>/*\n* When a function is defined in another function and it\n* has access to the outer function's context even after\n* the outer function returns.\n*\n* An important concept to learn in JavaScript.\n*/\n\nfunction outerFunction(someNum) {\n var someString = 'Hey!';\n var content = document.getElementById('content');\n function innerFunction() {\n content.innerHTML = someNum + ': ' + someString;\n content = null; // Internet Explorer memory leak for DOM reference\n }\n innerFunction();\n}\n\nouterFunction(1);​\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/N0mn0.png\" alt=\"Proof that this example creates a closure even if the inner function doesn't return\" /></p>\n<p><sub>*A C# question</sub></p>\n" }, { "answer_id": 4926486, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 8, "selected": false, "text": "<p>I wrote a blog post a while back explaining closures. Here's what I said about closures in terms of <strong>why</strong> you'd want one.</p>\n\n<blockquote>\n <p>Closures are a way to let a function\n have <strong>persistent, private variables</strong> -\n that is, variables that only one\n function knows about, where it can\n keep track of info from previous times\n that it was run.</p>\n</blockquote>\n\n<p>In that sense, they let a function act a bit like an object with private attributes.</p>\n\n<p>Full post:</p>\n\n<p><a href=\"http://sleeplessgeek.blogspot.com/2009/12/so-what-are-these-closure-thingys.html\" rel=\"noreferrer\">So what are these closure thingys?</a></p>\n" }, { "answer_id": 5099447, "author": "John Pick", "author_id": 251034, "author_profile": "https://Stackoverflow.com/users/251034", "pm_score": 6, "selected": false, "text": "<p>JavaScript functions can access their:</p>\n\n<ol>\n<li>Arguments</li>\n<li>Locals (that is, their local variables and local functions)</li>\n<li>Environment, which includes:\n\n<ul>\n<li>globals, including the DOM</li>\n<li>anything in outer functions</li>\n</ul></li>\n</ol>\n\n<p>If a function accesses its environment, then the function is a closure.</p>\n\n<p>Note that outer functions are not required, though they do offer benefits I don't discuss here. By accessing data in its environment, a closure keeps that data alive. In the subcase of outer/inner functions, an outer function can create local data and eventually exit, and yet, if any inner function(s) survive after the outer function exits, then the inner function(s) keep the outer function's local data alive.</p>\n\n<p>Example of a closure that uses the global environment:</p>\n\n<p>Imagine that the Stack Overflow Vote-Up and Vote-Down button events are implemented as closures, voteUp_click and voteDown_click, that have access to external variables isVotedUp and isVotedDown, which are defined globally. (For simplicity's sake, I am referring to StackOverflow's Question Vote buttons, not the array of Answer Vote buttons.)</p>\n\n<p>When the user clicks the VoteUp button, the voteUp_click function checks whether isVotedDown == true to determine whether to vote up or merely cancel a down vote. Function voteUp_click is a closure because it is accessing its environment.</p>\n\n<pre><code>var isVotedUp = false;\nvar isVotedDown = false;\n\nfunction voteUp_click() {\n if (isVotedUp)\n return;\n else if (isVotedDown)\n SetDownVote(false);\n else\n SetUpVote(true);\n}\n\nfunction voteDown_click() {\n if (isVotedDown)\n return;\n else if (isVotedUp)\n SetUpVote(false);\n else\n SetDownVote(true);\n}\n\nfunction SetUpVote(status) {\n isVotedUp = status;\n // Do some CSS stuff to Vote-Up button\n}\n\nfunction SetDownVote(status) {\n isVotedDown = status;\n // Do some CSS stuff to Vote-Down button\n}\n</code></pre>\n\n<p>All four of these functions are closures as they all access their environment.</p>\n" }, { "answer_id": 6472397, "author": "Jacob Swartwood", "author_id": 777919, "author_profile": "https://Stackoverflow.com/users/777919", "pm_score": 11, "selected": false, "text": "<p>FOREWORD: this answer was written when the question was:</p>\n\n<blockquote>\n <p>Like the old Albert said : \"If you can't explain it to a six-year old, you really don't understand it yourself.”. Well I tried to explain JS closures to a 27 years old friend and completely failed.</p>\n \n <p>Can anybody consider that I am 6 and strangely interested in that subject ?</p>\n</blockquote>\n\n<p>I'm pretty sure I was one of the only people that attempted to take the initial question literally. Since then, the question has mutated several times, so my answer may now seem incredibly silly &amp; out of place. Hopefully the general idea of the story remains fun for some.</p>\n\n<hr>\n\n<p>I'm a big fan of analogy and metaphor when explaining difficult concepts, so let me try my hand with a story.</p>\n\n<p><strong>Once upon a time:</strong></p>\n\n<p>There was a princess...</p>\n\n<pre><code>function princess() {\n</code></pre>\n\n<p>She lived in a wonderful world full of adventures. She met her Prince Charming, rode around her world on a unicorn, battled dragons, encountered talking animals, and many other fantastical things.</p>\n\n<pre><code> var adventures = [];\n\n function princeCharming() { /* ... */ }\n\n var unicorn = { /* ... */ },\n dragons = [ /* ... */ ],\n squirrel = \"Hello!\";\n\n /* ... */\n</code></pre>\n\n<p>But she would always have to return back to her dull world of chores and grown-ups.</p>\n\n<pre><code> return {\n</code></pre>\n\n<p>And she would often tell them of her latest amazing adventure as a princess.</p>\n\n<pre><code> story: function() {\n return adventures[adventures.length - 1];\n }\n };\n}\n</code></pre>\n\n<p>But all they would see is a little girl...</p>\n\n<pre><code>var littleGirl = princess();\n</code></pre>\n\n<p>...telling stories about magic and fantasy.</p>\n\n<pre><code>littleGirl.story();\n</code></pre>\n\n<p>And even though the grown-ups knew of real princesses, they would never believe in the unicorns or dragons because they could never see them. The grown-ups said that they only existed inside the little girl's imagination.</p>\n\n<p>But we know the real truth; that the little girl with the princess inside...</p>\n\n<p>...is really a princess with a little girl inside.</p>\n" }, { "answer_id": 6756814, "author": "StewShack", "author_id": 815682, "author_profile": "https://Stackoverflow.com/users/815682", "pm_score": 6, "selected": false, "text": "<p>You're having a sleep over and you invite Dan.\nYou tell Dan to bring one XBox controller.</p>\n\n<p>Dan invites Paul.\nDan asks Paul to bring one controller. How many controllers were brought to the party?</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function sleepOver(howManyControllersToBring) {\n\n var numberOfDansControllers = howManyControllersToBring;\n\n return function danInvitedPaul(numberOfPaulsControllers) {\n var totalControllers = numberOfDansControllers + numberOfPaulsControllers;\n return totalControllers;\n }\n}\n\nvar howManyControllersToBring = 1;\n\nvar inviteDan = sleepOver(howManyControllersToBring);\n\n// The only reason Paul was invited is because Dan was invited. \n// So we set Paul's invitation = Dan's invitation.\n\nvar danInvitedPaul = inviteDan(howManyControllersToBring);\n\nalert(\"There were \" + danInvitedPaul + \" controllers brought to the party.\");\n</code></pre>\n" }, { "answer_id": 6825315, "author": "Nathan Whitehead", "author_id": 232725, "author_profile": "https://Stackoverflow.com/users/232725", "pm_score": 7, "selected": false, "text": "<p>I put together an interactive JavaScript tutorial to explain how closures work.\n<a href=\"http://nathansjslessons.appspot.com\" rel=\"noreferrer\">What's a Closure?</a></p>\n\n<p>Here's one of the examples:</p>\n\n<pre><code>var create = function (x) {\n var f = function () {\n return x; // We can refer to x here!\n };\n return f;\n};\n// 'create' takes one argument, creates a function\n\nvar g = create(42);\n// g is a function that takes no arguments now\n\nvar y = g();\n// y is 42 here\n</code></pre>\n" }, { "answer_id": 6883759, "author": "mykhal", "author_id": 234248, "author_profile": "https://Stackoverflow.com/users/234248", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"noreferrer\">Wikipedia on closures</a>:</p>\n\n<blockquote>\n <p>In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.</p>\n</blockquote>\n\n<p>Technically, in <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"noreferrer\">JavaScript</a>, <strong>every function is a closure</strong>. It always has an access to variables defined in the surrounding scope.</p>\n\n<p>Since <strong>scope-defining construction in JavaScript is a function</strong>, not a code block like in many other languages, <strong>what we usually mean by <em>closure</em> in JavaScript</strong> is a <strong>function working with nonlocal variables defined in already executed surrounding function</strong>.</p>\n\n<p>Closures are often used for creating functions with some hidden private data (but it's not always the case).</p>\n\n<pre><code>var db = (function() {\n // Create a hidden object, which will hold the data\n // it's inaccessible from the outside.\n var data = {};\n\n // Make a function, which will provide some access to the data.\n return function(key, val) {\n if (val === undefined) { return data[key] } // Get\n else { return data[key] = val } // Set\n }\n // We are calling the anonymous surrounding function,\n // returning the above inner function, which is a closure.\n})();\n\ndb('x') // -&gt; undefined\ndb('x', 1) // Set x to 1\ndb('x') // -&gt; 1\n// It's impossible to access the data object itself.\n// We are able to get or set individual it.\n</code></pre>\n\n<p>ems</p>\n\n<p>The example above is using an anonymous function, which was executed once. But it does not have to be. It can be named (e.g. <code>mkdb</code>) and executed later, generating a database function each time it is invoked. Every generated function will have its own hidden database object. Another usage example of closures is when we don't return a function, but an object containing multiple functions for different purposes, each of those function having access to the same data.</p>\n" }, { "answer_id": 7285658, "author": "dlaliberte", "author_id": 311389, "author_profile": "https://Stackoverflow.com/users/311389", "pm_score": 10, "selected": false, "text": "<p>Taking the question seriously, we should find out what a typical 6-year-old is capable of cognitively, though admittedly, one who is interested in JavaScript is not so typical. </p>\n\n<p>On <a href=\"http://www.howkidsdevelop.com/5-7years.html\" rel=\"noreferrer\">Childhood Development: 5 to 7 Years </a> it says:</p>\n\n<blockquote>\n <p>Your child will be able to follow two-step directions. For example, if you say to your child, \"Go to the kitchen and get me a trash bag\" they will be able to remember that direction.</p>\n</blockquote>\n\n<p>We can use this example to explain closures, as follows:</p>\n\n<blockquote>\n <p>The kitchen is a closure that has a local variable, called <code>trashBags</code>. There is a function inside the kitchen called <code>getTrashBag</code> that gets one trash bag and returns it.</p>\n</blockquote>\n\n<p>We can code this in JavaScript like this:</p>\n\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>function makeKitchen() {\r\n var trashBags = ['A', 'B', 'C']; // only 3 at first\r\n\r\n return {\r\n getTrashBag: function() {\r\n return trashBags.pop();\r\n }\r\n };\r\n}\r\n\r\nvar kitchen = makeKitchen();\r\n\r\nconsole.log(kitchen.getTrashBag()); // returns trash bag C\r\nconsole.log(kitchen.getTrashBag()); // returns trash bag B\r\nconsole.log(kitchen.getTrashBag()); // returns trash bag A</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Further points that explain why closures are interesting:</p>\n\n<ul>\n<li>Each time <code>makeKitchen()</code> is called, a new closure is created with its own separate <code>trashBags</code>.</li>\n<li>The <code>trashBags</code> variable is local to the inside of each kitchen and is not accessible outside, but the inner function on the <code>getTrashBag</code> property does have access to it. </li>\n<li>Every function call creates a closure, but there would be no need to keep the closure around unless an inner function, which has access to the inside of the closure, can be called from outside the closure. Returning the object with the <code>getTrashBag</code> function does that here.</li>\n</ul>\n" }, { "answer_id": 10437122, "author": "Gerardo Lima", "author_id": 394042, "author_profile": "https://Stackoverflow.com/users/394042", "pm_score": 6, "selected": false, "text": "<p>I know there are plenty of solutions already, but I guess that this small and simple script can be useful to demonstrate the concept:</p>\n\n<pre><code>// makeSequencer will return a \"sequencer\" function\nvar makeSequencer = function() {\n var _count = 0; // not accessible outside this function\n var sequencer = function () {\n return _count++;\n }\n return sequencer;\n}\n\nvar fnext = makeSequencer();\nvar v0 = fnext(); // v0 = 0;\nvar v1 = fnext(); // v1 = 1;\nvar vz = fnext._count // vz = undefined\n</code></pre>\n" }, { "answer_id": 11658891, "author": "goonerify", "author_id": 1445318, "author_profile": "https://Stackoverflow.com/users/1445318", "pm_score": 4, "selected": false, "text": "<p>After a function is invoked, it goes out of scope. If that function contains something like a callback function, then that callback function is still in scope. If the callback function references some local variable in the immediate environment of the parent function, then naturally you'd expect that variable to be inaccessible to the callback function and return undefined.</p>\n\n<p>Closures ensure that any property that is referenced by the callback function is available for use by that function, even when its parent function may have gone out of scope.</p>\n" }, { "answer_id": 12122448, "author": "Jérôme Verstrynge", "author_id": 520957, "author_profile": "https://Stackoverflow.com/users/520957", "pm_score": 4, "selected": false, "text": "<p>From a personal <a href=\"http://tshikatshikaaa.blogspot.nl/2012/08/purpose-of-javascript-closure.html\" rel=\"noreferrer\">blog post</a>:</p>\n\n<p>By default, JavaScript knows two types of scopes: global and local.</p>\n\n<pre><code>var a = 1;\n\nfunction b(x) {\n var c = 2;\n return x * c;\n}\n</code></pre>\n\n<p>In the above code, variable a and function b are available from anywhere in the code (that is, globally). Variable <code>c</code> is only available within the <code>b</code> function scope (that is, local). Most software developers won't be happy with this lack of scope flexibility, especially in large programs.</p>\n\n<p>JavaScript closures help solving that issue by tying a function with a context:</p>\n\n<pre><code>function a(x) {\n return function b(y) {\n return x + y;\n }\n}\n</code></pre>\n\n<p>Here, function <code>a</code> returns a function called <code>b</code>. Since <code>b</code> is defined within <code>a</code>, it automatically has access to whatever is defined in <code>a</code>, that is, <code>x</code> in this example. This is why <code>b</code> can return <code>x</code> + <code>y</code> without declaring <code>x</code>.</p>\n\n<pre><code>var c = a(3);\n</code></pre>\n\n<p>Variable <code>c</code> is assigned the result of a call to a with parameter 3. That is, an instance of function <code>b</code> where <code>x</code> = 3. In other words, <code>c</code> is now a function equivalent to:</p>\n\n<pre><code>var c = function b(y) {\n return 3 + y;\n}\n</code></pre>\n\n<p>Function <code>b</code> remembers that <code>x</code> = 3 in its context. Therefore:</p>\n\n<pre><code>var d = c(4);\n</code></pre>\n\n<p>will assign the value 3 + 4 to <code>d</code>, that is 7.</p>\n\n<p><strong>Remark</strong>: If someone modifies the value of <code>x</code> (say <code>x</code> = 22) after the instance of function <code>b</code> has been created, this will be reflected in <code>b</code> too. Hence a later call to <code>c</code>(4) would return 22 + 4, that is 26.</p>\n\n<p>Closures can also be used to limit the scope of variables and methods declared globally:</p>\n\n<pre><code>(function () {\n var f = \"Some message\";\n alert(f);\n})();\n</code></pre>\n\n<p>The above is a closure where the function has no name, no argument and is called immediately. The highlighted code, which declares a global variable <code>f</code>, limits the scopes of <code>f</code> to the closure.</p>\n\n<p>Now, there is a common JavaScript caveat where closures can help:</p>\n\n<pre><code>var a = new Array();\n\nfor (var i=0; i&lt;2; i++) {\n a[i]= function(x) { return x + i ; }\n}\n</code></pre>\n\n<p>From the above, most would assume that array <code>a</code> would be initialized as follows:</p>\n\n<pre><code>a[0] = function (x) { return x + 0 ; }\na[1] = function (x) { return x + 1 ; }\na[2] = function (x) { return x + 2 ; }\n</code></pre>\n\n<p>In reality, this is how a is initialized, since the last value of <code>i</code> in the context is 2:</p>\n\n<pre><code>a[0] = function (x) { return x + 2 ; }\na[1] = function (x) { return x + 2 ; }\na[2] = function (x) { return x + 2 ; }\n</code></pre>\n\n<p>The solution is:</p>\n\n<pre><code>var a = new Array();\n\nfor (var i=0; i&lt;2; i++) {\n a[i]= function(tmp) {\n return function (x) { return x + tmp ; }\n } (i);\n}\n</code></pre>\n\n<p>The argument/variable <code>tmp</code> holds a local copy of the changing value of <code>i</code> when creating function instances.</p>\n" }, { "answer_id": 13074647, "author": "srgstm", "author_id": 875940, "author_profile": "https://Stackoverflow.com/users/875940", "pm_score": 6, "selected": false, "text": "<p>A function in JavaScript is not just a reference to a set of instructions (as in C language), but it also includes a hidden data structure which is composed of references to all nonlocal variables it uses (captured variables). Such two-piece functions are called closures. Every function in JavaScript can be considered a closure.</p>\n\n<p>Closures are functions with a state. It is somewhat similar to \"this\" in the sense that \"this\" also provides state for a function but function and \"this\" are separate objects (\"this\" is just a fancy parameter, and the only way to bind it permanently to a function is to create a closure). While \"this\" and function always live separately, a function cannot be separated from its closure and the language provides no means to access captured variables.</p>\n\n<p>Because all these external variables referenced by a lexically nested function are actually local variables in the chain of its lexically enclosing functions (global variables can be assumed to be local variables of some root function), and every single execution of a function creates new instances of its local variables, it follows that every execution of a function returning (or otherwise transferring it out, such as registering it as a callback) a nested function creates a new closure (with its own potentially unique set of referenced nonlocal variables which represent its execution context).</p>\n\n<p>Also, it must be understood that local variables in JavaScript are created not on the stack frame, but on the heap and destroyed only when no one is referencing them. When a function returns, references to its local variables are decremented, but they can still be non-null if during the current execution they became part of a closure and are still referenced by its lexically nested functions (which can happen only if the references to these nested functions were returned or otherwise transferred to some external code).</p>\n\n<p>An example:</p>\n\n<pre><code>function foo (initValue) {\n //This variable is not destroyed when the foo function exits.\n //It is 'captured' by the two nested functions returned below.\n var value = initValue;\n\n //Note that the two returned functions are created right now.\n //If the foo function is called again, it will return\n //new functions referencing a different 'value' variable.\n return {\n getValue: function () { return value; },\n setValue: function (newValue) { value = newValue; }\n }\n}\n\nfunction bar () {\n //foo sets its local variable 'value' to 5 and returns an object with\n //two functions still referencing that local variable\n var obj = foo(5);\n\n //Extracting functions just to show that no 'this' is involved here\n var getValue = obj.getValue;\n var setValue = obj.setValue;\n\n alert(getValue()); //Displays 5\n setValue(10);\n alert(getValue()); //Displays 10\n\n //At this point getValue and setValue functions are destroyed\n //(in reality they are destroyed at the next iteration of the garbage collector).\n //The local variable 'value' in the foo is no longer referenced by\n //anything and is destroyed too.\n}\n\nbar();\n</code></pre>\n" }, { "answer_id": 13658697, "author": "ketan", "author_id": 783815, "author_profile": "https://Stackoverflow.com/users/783815", "pm_score": 4, "selected": false, "text": "<p>Closures are a means through which inner functions can refer to the variables present in their outer enclosing function after their parent functions have already terminated.</p>\n\n<pre><code>// A function that generates a new function for adding numbers.\nfunction addGenerator( num ) {\n // Return a simple function for adding two numbers\n // with the first number borrowed from the generator\n return function( toAdd ) {\n return num + toAdd\n };\n}\n\n// addFive now contains a function that takes one argument,\n// adds five to it, and returns the resulting number.\nvar addFive = addGenerator( 5 );\n// We can see here that the result of the addFive function is 9,\n// when passed an argument of 4.\nalert( addFive( 4 ) == 9 );\n</code></pre>\n" }, { "answer_id": 15097817, "author": "jondavidjohn", "author_id": 555384, "author_profile": "https://Stackoverflow.com/users/555384", "pm_score": 9, "selected": false, "text": "<h1>The Straw Man</h1>\n<p>I need to know how many times a button has been clicked and do something on every third click...</p>\n<h2>Fairly Obvious Solution</h2>\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>// Declare counter outside event handler's scope\nvar counter = 0;\nvar element = document.getElementById('button');\n\nelement.addEventListener(\"click\", function() {\n // Increment outside counter\n counter++;\n\n if (counter === 3) {\n // Do something every third time\n console.log(\"Third time's the charm!\");\n\n // Reset counter\n counter = 0;\n }\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button id=\"button\"&gt;Click Me!&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Now this will work, but it does encroach into the outer scope by adding a variable, whose sole purpose is to keep track of the count. In some situations, this would be preferable as your outer application might need access to this information. But in this case, we are only changing every third click's behavior, so it is preferable to <strong>enclose this functionality inside the event handler</strong>.</p>\n<h2>Consider this option</h2>\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 element = document.getElementById('button');\n\nelement.addEventListener(\"click\", (function() {\n // init the count to 0\n var count = 0;\n\n return function(e) { // &lt;- This function becomes the click handler\n count++; // and will retain access to the above `count`\n\n if (count === 3) {\n // Do something every third time\n console.log(\"Third time's the charm!\");\n\n //Reset counter\n count = 0;\n }\n };\n})());</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button id=\"button\"&gt;Click Me!&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Notice a few things here.</p>\n<p>In the above example, I am using the closure behavior of JavaScript. <strong>This behavior allows any function to have access to the scope in which it was created, indefinitely.</strong> To practically apply this, I immediately invoke a function that returns another function, and because the function I'm returning has access to the internal count variable (because of the closure behavior explained above) this results in a private scope for usage by the resulting function... Not so simple? Let's dilute it down...</p>\n<p><strong>A simple one-line closure</strong></p>\n<pre><code>// _______________________Immediately invoked______________________\n// | |\n// | Scope retained for use ___Returned as the____ |\n// | only by returned function | value of func | |\n// | | | | | |\n// v v v v v v\nvar func = (function() { var a = 'val'; return function() { alert(a); }; })();\n</code></pre>\n<p>All variables outside the returned function are available to the returned function, but they are not directly available to the returned function object...</p>\n<pre><code>func(); // Alerts &quot;val&quot;\nfunc.a; // Undefined\n</code></pre>\n<p>Get it? So in our primary example, the count variable is contained within the closure and always available to the event handler, so it retains its state from click to click.</p>\n<p>Also, this private variable state is <strong>fully</strong> accessible, for both readings and assigning to its private scoped variables.</p>\n<p>There you go; you're now fully encapsulating this behavior.</p>\n<p><strong><a href=\"http://jondavidjohn.com/javascript-closure-explained-using-events/\" rel=\"noreferrer\">Full Blog Post</a></strong> (including jQuery considerations)</p>\n" }, { "answer_id": 15208427, "author": "dmi3y", "author_id": 1401973, "author_profile": "https://Stackoverflow.com/users/1401973", "pm_score": 6, "selected": false, "text": "<p>Okay, talking with a 6-year old child, I would possibly use following associations.</p>\n\n<blockquote>\n <p>Imagine - you are playing with your little brothers and sisters in the entire house, and you are moving around with your toys and brought some of them into your older brother's room. After a while your brother returned from the school and went to his room, and he locked inside it, so now you could not access toys left there anymore in a direct way. But you could knock the door and ask your brother for that toys. This is called toy's <em>closure</em>; your brother made it up for you, and he is now into outer <em>scope</em>.</p>\n</blockquote>\n\n<p>Compare with a situation when a door was locked by draft and nobody inside (general function execution), and then some local fire occur and burn down the room (garbage collector:D), and then a new room was build and now you may leave another toys there (new function instance), but never get the same toys which were left in the first room instance.</p>\n\n<p>For an advanced child I would put something like the following. It is not perfect, but it makes you feel about what it is:</p>\n\n<pre><code>function playingInBrothersRoom (withToys) {\n // We closure toys which we played in the brother's room. When he come back and lock the door\n // your brother is supposed to be into the outer [[scope]] object now. Thanks god you could communicate with him.\n var closureToys = withToys || [],\n returnToy, countIt, toy; // Just another closure helpers, for brother's inner use.\n\n var brotherGivesToyBack = function (toy) {\n // New request. There is not yet closureToys on brother's hand yet. Give him a time.\n returnToy = null;\n if (toy &amp;&amp; closureToys.length &gt; 0) { // If we ask for a specific toy, the brother is going to search for it.\n\n for ( countIt = closureToys.length; countIt; countIt--) {\n if (closureToys[countIt - 1] == toy) {\n returnToy = 'Take your ' + closureToys.splice(countIt - 1, 1) + ', little boy!';\n break;\n }\n }\n returnToy = returnToy || 'Hey, I could not find any ' + toy + ' here. Look for it in another room.';\n }\n else if (closureToys.length &gt; 0) { // Otherwise, just give back everything he has in the room.\n returnToy = 'Behold! ' + closureToys.join(', ') + '.';\n closureToys = [];\n }\n else {\n returnToy = 'Hey, lil shrimp, I gave you everything!';\n }\n console.log(returnToy);\n }\n return brotherGivesToyBack;\n}\n// You are playing in the house, including the brother's room.\nvar toys = ['teddybear', 'car', 'jumpingrope'],\n askBrotherForClosuredToy = playingInBrothersRoom(toys);\n\n// The door is locked, and the brother came from the school. You could not cheat and take it out directly.\nconsole.log(askBrotherForClosuredToy.closureToys); // Undefined\n\n// But you could ask your brother politely, to give it back.\naskBrotherForClosuredToy('teddybear'); // Hooray, here it is, teddybear\naskBrotherForClosuredToy('ball'); // The brother would not be able to find it.\naskBrotherForClosuredToy(); // The brother gives you all the rest\naskBrotherForClosuredToy(); // Nothing left in there\n</code></pre>\n\n<p>As you can see, the toys left in the room are still accessible via the brother and no matter if the room is locked. Here is <a href=\"http://jsbin.com/ubakor/9/edit\" rel=\"noreferrer\">a jsbin</a> to play around with it.</p>\n" }, { "answer_id": 15306767, "author": "mjmoody383", "author_id": 549155, "author_profile": "https://Stackoverflow.com/users/549155", "pm_score": 6, "selected": false, "text": "<p>I'd simply point them to the <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures\">Mozilla Closures page</a>. It's the best, most <strong>concise and simple explanation</strong> of closure basics and practical usage that I've found. It is highly recommended to anyone learning JavaScript.</p>\n\n<p>And yes, I'd even recommend it to a 6-year old -- if the 6-year old is learning about closures, then it's logical they're ready to comprehend the <em>concise and simple explanation</em> provided in the article.</p>\n" }, { "answer_id": 15340037, "author": "Jean-Baptiste Yunès", "author_id": 719263, "author_profile": "https://Stackoverflow.com/users/719263", "pm_score": 4, "selected": false, "text": "<p>If you want to explain it to a six-year old child then you must find something very much simpler and NO code.</p>\n\n<p>Just tell the child that he is \"open\", which says that he is able to have relations with some others, his friends. At some point in time, he has determined friends (we can know the names of his friends), that is a closure. If you take a picture of him and his friends then he is \"closed\" relatively to his friendship ability. But in general, he is \"open\". During his whole life he will have many different sets of friends. One of these sets is a closure.</p>\n" }, { "answer_id": 16205049, "author": "Jim", "author_id": 1811102, "author_profile": "https://Stackoverflow.com/users/1811102", "pm_score": 4, "selected": false, "text": "<p>I found very clear chapter 8 section 6, \"Closures,\" of <em>JavaScript: The Definitive Guide</em> by David Flanagan, 6th edition, O'Reilly, 2011. I'll try to paraphrase. </p>\n\n<ol>\n<li><p>When a function is invoked, a new object is created to hold the local variables for that invocation. </p></li>\n<li><p>A function's scope depends on its declaration location, not its execution location.</p></li>\n</ol>\n\n<p>Now, assume an inner function declared within an outer function and referring to variables of that outer function. Further assume the outer function returns the inner function, as a function. Now there is an external reference to whatever values were in the inner function's scope (which, by our assumptions, includes values from the outer function).</p>\n\n<p>JavaScript will preserve those values, as they have remained in scope of the current execution thanks to being passed out of the completed outer function. All functions are closures, but the closures of interest are the inner functions which, in our assumed scenario, preserve outer function values within their \"enclosure\" (I hope I'm using language correctly here) when they (the inner functions) are returned from outer functions. I know this doesn't meet the six-year-old requirement, but hopefully it is still helpful.</p>\n" }, { "answer_id": 16376253, "author": "moha297", "author_id": 159765, "author_profile": "https://Stackoverflow.com/users/159765", "pm_score": 4, "selected": false, "text": "<p>A function is executed in the scope of the object/function in which it is defined. The said function can access the variables defined in the object/function where it has been defined while it is executing.</p>\n\n<p>And just take it literally.... as the code is written :P</p>\n" }, { "answer_id": 16463983, "author": "Charlie", "author_id": 479836, "author_profile": "https://Stackoverflow.com/users/479836", "pm_score": 5, "selected": false, "text": "<p>For a six-year-old?</p>\n\n<p>You and your family live in the mythical town of Ann Ville. You have a friend who lives next door, so you call them and ask them to come out and play. You dial:</p>\n\n<blockquote>\n <p>000001 (jamiesHouse)</p>\n</blockquote>\n\n<p>After a month, you and your family move out of Ann Ville to the next town, but you and your friend still keep in touch, so now you have to dial the area code for the town that your friend lives in, before dialling their 'proper' number:</p>\n\n<blockquote>\n <p>001 000001 (annVille.jamiesHouse)</p>\n</blockquote>\n\n<p>A year after that, your parents move to a whole new country, but you and your friend still keep in touch, so after bugging your parents to let you make international rate calls, you now dial:</p>\n\n<blockquote>\n <p>01 001 000001 (myOldCountry.annVille.jamiesHouse)</p>\n</blockquote>\n\n<p>Strangely though, after moving to your new country, you and your family just so happen to move to a new town called Ann Ville... and you just so happen to make friends with some new person called Jamie... You give them a call...</p>\n\n<blockquote>\n <p>000001 (jamiesHouse)</p>\n</blockquote>\n\n<p>Spooky...</p>\n\n<p>So spooky in fact, that you tell Jamie from your old country about it... You have a good laugh about it. So one day, you and your family take a holiday back to the old country. You visit your old town (Ann Ville), and go to visit Jamie...</p>\n\n<ul>\n<li>\"Really? Another Jamie? In Ann Ville? In your new country!!?\"</li>\n<li>\"Yeah... Let's call them...\"</li>\n</ul>\n\n<blockquote>\n <p>02 001 000001 (myNewCountry.annVille.jamiesHouse)</p>\n</blockquote>\n\n<p>Opinions?</p>\n\n<p><em>What's more, I have a load of questions about the patience of a modern six-year-old...</em></p>\n" }, { "answer_id": 16597261, "author": "Stupid Stupid", "author_id": 2391385, "author_profile": "https://Stackoverflow.com/users/2391385", "pm_score": 6, "selected": false, "text": "<p>An answer for a six-year-old (assuming he knows what a function is and what a variable is, and what data is):</p>\n\n<p>Functions can return data. One kind of data you can return from a function is another function. When that new function gets returned, all the variables and arguments used in the function that created it don't go away. Instead, that parent function \"closes.\" In other words, nothing can look inside of it and see the variables it used except for the function it returned. That new function has a special ability to look back inside the function that created it and see the data inside of it.</p>\n\n<pre><code>function the_closure() {\n var x = 4;\n return function () {\n return x; // Here, we look back inside the_closure for the value of x\n }\n}\n\nvar myFn = the_closure();\nmyFn(); //=&gt; 4\n</code></pre>\n\n<p>Another really simple way to explain it is in terms of scope:</p>\n\n<p>Any time you create a smaller scope inside of a larger scope, the smaller scope will always be able to see what is in the larger scope.</p>\n" }, { "answer_id": 16945392, "author": "Arman", "author_id": 1847185, "author_profile": "https://Stackoverflow.com/users/1847185", "pm_score": 4, "selected": false, "text": "<p>I'm sure, <a href=\"https://en.wikipedia.org/wiki/Albert_Einstein\" rel=\"nofollow\">Einstein</a> didn't say it with a direct expectation for us to pick any esoteric brainstormer thing and run over six-year-olds with futile attempts to get those 'crazy' (and what is even worse for them-boring) things to their childish minds :) If I were six years old I wouldn't like to have such parents or wouldn't make friendship with such boring philanthropists, sorry :)</p>\n\n<p>Anyway, for babies, <strong>closure</strong> is simply a <strong>hug</strong>, I guess, whatever way you try to explain :) And when you hug a friend of yours then you both kind of share anything you guys have at the moment. It's a rite of passage, once you've hugged somebody you're showing her trust and willingness to let her do with you a lot of things you don't allow and would hide from others. It's an act of friendship :).</p>\n\n<p>I really don't know how to explain it to 5-6 years old babies. I neither think they will appreciate any JavaScript code snippets like:</p>\n\n<pre><code>function Baby(){\n this.iTrustYou = true;\n}\n\nBaby.prototype.hug = function (baby) {\n var smiles = 0;\n\n if (baby.iTrustYou) {\n return function() {\n smiles++;\n alert(smiles);\n };\n }\n};\n\nvar\n arman = new Baby(\"Arman\"),\n morgan = new Baby(\"Morgana\");\n\nvar hug = arman.hug(morgan);\nhug();\nhug();\n</code></pre>\n\n<p>For children only:</p>\n\n<p><strong>Closure</strong> is <strong>hug</strong></p>\n\n<p><strong>Bug</strong> is <strong>fly</strong></p>\n\n<p><strong>KISS</strong> is <strong>smooch!</strong> :)</p>\n" }, { "answer_id": 16959645, "author": "Max Tkachenko", "author_id": 1393791, "author_profile": "https://Stackoverflow.com/users/1393791", "pm_score": 9, "selected": false, "text": "<p>OK, 6-year-old closures fan. Do you want to hear the simplest example of closure?</p>\n\n<p>Let's imagine the next situation: a driver is sitting in a car. That car is inside a plane. Plane is in the airport. The ability of driver to access things outside his car, but inside the plane, even if that plane leaves an airport, is a closure. That's it. When you turn 27, look at the <a href=\"https://stackoverflow.com/a/111200/1393791\">more detailed explanation</a> or at the example below.</p>\n\n<p>Here is how I can convert my plane story into the code.</p>\n\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 plane = function(defaultAirport) {\r\n\r\n var lastAirportLeft = defaultAirport;\r\n\r\n var car = {\r\n driver: {\r\n startAccessPlaneInfo: function() {\r\n setInterval(function() {\r\n console.log(\"Last airport was \" + lastAirportLeft);\r\n }, 2000);\r\n }\r\n }\r\n };\r\n car.driver.startAccessPlaneInfo();\r\n\r\n return {\r\n leaveTheAirport: function(airPortName) {\r\n lastAirportLeft = airPortName;\r\n }\r\n }\r\n}(\"Boryspil International Airport\");\r\n\r\nplane.leaveTheAirport(\"John F. Kennedy\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 17200991, "author": "Chev", "author_id": 498624, "author_profile": "https://Stackoverflow.com/users/498624", "pm_score": 8, "selected": false, "text": "<p>I tend to learn better by GOOD/BAD comparisons. I like to see working code followed by non-working code that someone is likely to encounter. I put together <a href=\"http://jsfiddle.net/KMQZK/\" rel=\"nofollow noreferrer\">a jsFiddle</a> that does a comparison and tries to boil down the differences to the simplest explanations I could come up with.</p>\n<h2>Closures done right:</h2>\n<pre><code>console.log('CLOSURES DONE RIGHT');\n\nvar arr = [];\n\nfunction createClosure(n) {\n return function () {\n return 'n = ' + n;\n }\n}\n\nfor (var index = 0; index &lt; 10; index++) {\n arr[index] = createClosure(index);\n}\n\nfor (var index of arr) {\n console.log(arr[index]());\n}\n</code></pre>\n<ul>\n<li><p>In the above code <code>createClosure(n)</code> is invoked in every iteration of the loop. Note that I named the variable <code>n</code> to highlight that it is a <strong>new</strong> variable created in a new function scope and is not the same variable as <code>index</code> which is bound to the outer scope.</p>\n</li>\n<li><p>This creates a new scope and <code>n</code> is bound to that scope; this means we have 10 separate scopes, one for each iteration.</p>\n</li>\n<li><p><code>createClosure(n)</code> returns a function that returns the n within that scope.</p>\n</li>\n<li><p>Within each scope <code>n</code> is bound to whatever value it had when <code>createClosure(n)</code> was invoked so the nested function that gets returned will always return the value of <code>n</code> that it had when <code>createClosure(n)</code> was invoked.</p>\n</li>\n</ul>\n<h2>Closures done wrong:</h2>\n<pre><code>console.log('CLOSURES DONE WRONG');\n\nfunction createClosureArray() {\n var badArr = [];\n\n for (var index = 0; index &lt; 10; index++) {\n badArr[index] = function () {\n return 'n = ' + index;\n };\n }\n return badArr;\n}\n\nvar badArr = createClosureArray();\n\nfor (var index of badArr) {\n console.log(badArr[index]());\n}\n</code></pre>\n<ul>\n<li><p>In the above code the loop was moved within the <code>createClosureArray()</code> function and the function now just returns the completed array, which at first glance seems more intuitive.</p>\n</li>\n<li><p>What might not be obvious is that since <code>createClosureArray()</code> is only invoked once only one scope is created for this function instead of one for every iteration of the loop.</p>\n</li>\n<li><p>Within this function a variable named <code>index</code> is defined. The loop runs and adds functions to the array that return <code>index</code>. Note that <code>index</code> is defined within the <code>createClosureArray</code> function which only ever gets invoked one time.</p>\n</li>\n<li><p>Because there was only one scope within the <code>createClosureArray()</code> function, <code>index</code> is only bound to a value within that scope. In other words, each time the loop changes the value of <code>index</code>, it changes it for everything that references it within that scope.</p>\n</li>\n<li><p>All of the functions added to the array return the SAME <code>index</code> variable from the parent scope where it was defined instead of 10 different ones from 10 different scopes like the first example. The end result is that all 10 functions return the same variable from the same scope.</p>\n</li>\n<li><p>After the loop finished and <code>index</code> was done being modified the end value was 10, therefore every function added to the array returns the value of the single <code>index</code> variable which is now set to 10.</p>\n</li>\n</ul>\n<h2>Result</h2>\n<blockquote>\n<p>CLOSURES DONE RIGHT<br />\nn = 0<br />\nn = 1<br />\nn = 2<br />\nn = 3<br />\nn = 4<br />\nn = 5<br />\nn = 6<br />\nn = 7<br />\nn = 8<br />\nn = 9</p>\n<p>CLOSURES DONE WRONG<br />\nn = 10<br />\nn = 10<br />\nn = 10<br />\nn = 10<br />\nn = 10<br />\nn = 10<br />\nn = 10<br />\nn = 10<br />\nn = 10<br />\nn = 10</p>\n</blockquote>\n" }, { "answer_id": 17254359, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 5, "selected": false, "text": "<h2>Given the following function</h2>\n\n<pre><code>function person(name, age){\n\n var name = name;\n var age = age;\n\n function introduce(){\n alert(\"My name is \"+name+\", and I'm \"+age);\n }\n\n return introduce;\n}\n\nvar a = person(\"Jack\",12);\nvar b = person(\"Matt\",14);\n</code></pre>\n\n<p>Everytime the function <code>person</code> is called a new closure is created. While variables <code>a</code> and <code>b</code> have the same <code>introduce</code> function, it is linked to different closures. And that closure will still exist even after the function <code>person</code> finishes execution.</p>\n\n<p><img src=\"https://i.stack.imgur.com/LDEhE.png\" alt=\"Enter image description here\"></p>\n\n<pre><code>a(); //My name is Jack, and I'm 12\nb(); //My name is Matt, and I'm 14\n</code></pre>\n\n<p>An abstract closures could be represented to something like this:</p>\n\n<pre><code>closure a = {\n name: \"Jack\",\n age: 12,\n call: function introduce(){\n alert(\"My name is \"+name+\", and I'm \"+age);\n }\n}\n\nclosure b = {\n name: \"Matt\",\n age: 14,\n call: function introduce(){\n alert(\"My name is \"+name+\", and I'm \"+age);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Assuming you know how a <code>class</code> in another language work, I will make an analogy.</p>\n\n<p>Think like</p>\n\n<ul>\n<li>JavaScript <code>function</code> as a <code>constructor</code></li>\n<li><code>local variables</code> as <code>instance properties</code></li>\n<li>these <code>properties</code> are private</li>\n<li><code>inner functions</code> as <code>instance methods</code></li>\n</ul>\n\n<p>Everytime a <code>function</code> is called</p>\n\n<ul>\n<li>A new <code>object</code> containing all local variables will be created.</li>\n<li>Methods of this object have access to <code>\"properties\"</code> of that instance object.</li>\n</ul>\n" }, { "answer_id": 17256320, "author": "Raul Martins", "author_id": 1482415, "author_profile": "https://Stackoverflow.com/users/1482415", "pm_score": 3, "selected": false, "text": "<p>Considering the question is about explaining it simply as if to a <strong>6-year-old</strong>, my answer would be:</p>\n\n<p><strong>\"When you declare a function in JavaScript it has forever access to all the variables and functions that were available in the line before that function declaration. The function and all the outer variables and functions that it has access to is what we call a closure.\"</strong></p>\n" }, { "answer_id": 17308587, "author": "Matt", "author_id": 706054, "author_profile": "https://Stackoverflow.com/users/706054", "pm_score": 8, "selected": false, "text": "<h2><strong>Closures are simple:</strong></h2>\n\n<p>The following simple example covers all the main points of JavaScript closures.<sup>*</sup>\n&nbsp;</p>\n\n<p>Here is a factory that produces calculators that can add and multiply:</p>\n\n<pre><code>function make_calculator() {\n var n = 0; // this calculator stores a single number n\n return {\n add: function(a) {\n n += a;\n return n;\n },\n multiply: function(a) {\n n *= a;\n return n;\n }\n };\n}\n\nfirst_calculator = make_calculator();\nsecond_calculator = make_calculator();\n\nfirst_calculator.add(3); // returns 3\nsecond_calculator.add(400); // returns 400\n\nfirst_calculator.multiply(11); // returns 33\nsecond_calculator.multiply(10); // returns 4000\n</code></pre>\n\n<p><strong>The key point:</strong> Each call to <code>make_calculator</code> creates a new local variable <code>n</code>, which continues to be usable by that calculator's <code>add</code> and <code>multiply</code> functions long after <code>make_calculator</code> returns.</p>\n\n<p><em>If you are familiar with stack frames, these calculators seem strange: How can they keep accessing <code>n</code> after <code>make_calculator</code> returns? The answer is to imagine that JavaScript doesn't use \"stack frames\", but instead uses \"heap frames\", which can persist after the function call that made them returns.</em></p>\n\n<p>Inner functions like <code>add</code> and <code>multiply</code>, which access variables declared in an outer function<sup>**</sup>, are called <em>closures</em>.</p>\n\n<p><strong>That is pretty much all there is to closures.</strong></p>\n\n<p><br></p>\n\n<hr>\n\n<p><sup><sup>*</sup> For example, it covers all the points in the \"Closures for Dummies\" article given in <a href=\"https://stackoverflow.com/a/111111/706054\">another answer</a>, except example 6, which simply shows that variables can be used before they are declared, a nice fact to know but completely unrelated to closures. It also covers all the points in <a href=\"https://stackoverflow.com/a/111200/706054\">the accepted answer</a>, except for the points (1) that functions copy their arguments into local variables (the named function arguments), and (2) that copying numbers creates a new number, but copying an object reference gives you another reference to the same object. These are also good to know but again completely unrelated to closures. It is also very similar to the example in <a href=\"https://stackoverflow.com/a/111114/706054\">this answer</a> but a bit shorter and less abstract. It does not cover the point of <a href=\"https://stackoverflow.com/a/17200991/706054\">this answer</a> or <a href=\"https://stackoverflow.com/questions/111102/how-do-javascript-closures-work/17308587?noredirect=1#comment26377355_111111\">this comment</a>, which is that JavaScript makes it difficult to plug the <em>current</em> value of a loop variable into your inner function: The \"plugging in\" step can only be done with a helper function that encloses your inner function and is invoked on each loop iteration. (Strictly speaking, the inner function accesses the helper function's copy of the variable, rather than having anything plugged in.) Again, very useful when creating closures, but not part of what a closure is or how it works. There is additional confusion due to closures working differently in functional languages like ML, where variables are bound to values rather than to storage space, providing a constant stream of people who understand closures in a way (namely the \"plugging in\" way) that is simply incorrect for JavaScript, where variables are always bound to storage space, and never to values. </sup></p>\n\n<p><sup><sup>**</sup> Any outer function, if several are nested, or even in the global context, as <a href=\"https://stackoverflow.com/a/5099447/706054\">this answer</a> points out clearly.</sup></p>\n" }, { "answer_id": 18277558, "author": "Taye", "author_id": 2076015, "author_profile": "https://Stackoverflow.com/users/2076015", "pm_score": 3, "selected": false, "text": "<p>A closure is basically creating two things :\n- a function\n- a private scope that only that function can access</p>\n\n<p>It is like putting some coating around a function.</p>\n\n<p>So to a 6-years-old, it could be explained by giving an analogy. Let's say I build a robot. That robot can do many things. Among those things, I programmed it to count the number of birds he sees in the sky. Each time he has seen 25 birds, he should tell me how many birds he has seen since the beginning.</p>\n\n<p>I don't know how many birds he has seen unless he has told me. Only he knows. That's the private scope. That's basically the robot's memory. Let's say I gave him 4&nbsp;GB.</p>\n\n<p>Telling me how many birds he has seen is the returned function. I also created that.</p>\n\n<p>That analogy is a bit sucky, but someone could improve it I guess.</p>\n" }, { "answer_id": 19496348, "author": "cube", "author_id": 354992, "author_profile": "https://Stackoverflow.com/users/354992", "pm_score": 3, "selected": false, "text": "<p>The word <em>closure</em> simply refers to being able to access <em>objects</em> (six-year-old: things) that are <em>closed</em> (six-year-old: private) within a <em>function</em> (six-year-old: box). Even if the <em>function</em> (six-year-old: box) is out of <em>scope</em> (six-year-old: sent far away).</p>\n" }, { "answer_id": 21353238, "author": "roland", "author_id": 313353, "author_profile": "https://Stackoverflow.com/users/313353", "pm_score": 5, "selected": false, "text": "<p>The more I think about closure the more I see it as a 2-step process: <strong>init - action</strong></p>\n\n<pre><code>init: pass first what's needed...\naction: in order to achieve something for later execution.\n</code></pre>\n\n<p>To a 6-year old, I'd emphasize on the <em>practical aspect</em> of closure:</p>\n\n<pre><code>Daddy: Listen. Could you bring mum some milk (2).\nTom: No problem.\nDaddy: Take a look at the map that Daddy has just made: mum is there and daddy is here.\nDaddy: But get ready first. And bring the map with you (1), it may come in handy\nDaddy: Then off you go (3). Ok?\nTom: A piece of cake!\n</code></pre>\n\n<p><strong>Example</strong>: <em>Bring some milk to mum (=action). First get ready and bring the map (=init).</em></p>\n\n<pre><code>function getReady(map) {\n var cleverBoy = 'I examine the ' + map;\n return function(what, who) {\n return 'I bring ' + what + ' to ' + who + 'because + ' cleverBoy; //I can access the map\n }\n}\nvar offYouGo = getReady('daddy-map');\noffYouGo('milk', 'mum');\n</code></pre>\n\n<p>Because if you bring with you a very important piece of information (the map), you're knowledgeable enough to execute other similar actions:</p>\n\n<pre><code>offYouGo('potatoes', 'great mum');\n</code></pre>\n\n<p>To a developer I'd make a parallel between closures and <a href=\"http://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"noreferrer\">OOP</a>.\nThe <strong>init phase</strong> is similar to passing arguments to a constructor in a traditional OO language; the <strong>action phase</strong> is ultimately the method you call to achieve what you want. And the method has access these init arguments using a mechanism called <em>closure</em>.</p>\n\n<p>See my another answer illustrating the parallelism between OO and closures:</p>\n\n<p><em><a href=\"https://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript/21352366#21352366\">How to &quot;properly&quot; create a custom object in JavaScript?</a></em></p>\n" }, { "answer_id": 21839381, "author": "Magne", "author_id": 380607, "author_profile": "https://Stackoverflow.com/users/380607", "pm_score": 8, "selected": false, "text": "<p>The original question had a quote:</p>\n<blockquote>\n<p>If you can't explain it to a six-year old, you really don't understand it yourself.</p>\n</blockquote>\n<p>This is how I'd try to explain it to an actual six-year-old:</p>\n<p>You know how grown-ups can own a house, and they call it home? When a mom has a child, the child doesn't really own anything, right? But its parents own a house, so whenever someone asks &quot;Where's your home?&quot;, the child can answer &quot;that house!&quot;, and point to the house of its parents.</p>\n<p>A &quot;Closure&quot; is the ability of the child to always (even if abroad) be able to refer to its home, even though it's really the parent's who own the house.</p>\n" }, { "answer_id": 22365177, "author": "Nick Manning", "author_id": 1763217, "author_profile": "https://Stackoverflow.com/users/1763217", "pm_score": 2, "selected": false, "text": "<h1>The simplest, shortest, most-easy-to-understand answer:</h1>\n<p>A closure is a block of code where each line can reference the same set of variables with the same variable names.</p>\n<p>If &quot;this&quot; means something different than it does somewhere else, then you know it is two different closures.</p>\n" }, { "answer_id": 22508288, "author": "Juan Garcia", "author_id": 1802325, "author_profile": "https://Stackoverflow.com/users/1802325", "pm_score": 4, "selected": false, "text": "<p>If you understand it well you can explain it simple. And the simplest way is abstracting it from the context. Code aside, even programming aside. A metaphor example will do it better.</p>\n\n<p>Let's imagine that a function is a room whose walls are of glass, but they are special glass, like the ones in an interrogation room. From outside they are opaque, from inside they are transparent. It can be rooms inside other rooms, and the only way of contact is a phone.</p>\n\n<p>If you call from the outside, you don't know what is in it, but you know that the people inside will do a task if you give them certain information. They can see outside, so they can ask you for stuff that are outside and make changes to that stuff, but you can't change what it is inside from the outside, you don't even see (know) what it is inside. The people inside that room you are calling see what it is outside, but not what it is inside the rooms in that room, so they interact with them the way you are doing from outside. The people inside the most inner rooms can see many things, but the people of the most outer room don't even know about the most inner rooms' existence.</p>\n\n<p>For each call to an inner room, the people in that room keeps a record of the information about that specific call, and they are so good doing that that they never mistake one call stuff with other call stuff.</p>\n\n<p>Rooms are functions, visibility is scope, people doing task is statements, stuff are objects, phone calls are function calls, phone call information is arguments, call records are scope instances, the most outer room is the global object.</p>\n" }, { "answer_id": 22533155, "author": "Ravi", "author_id": 1000849, "author_profile": "https://Stackoverflow.com/users/1000849", "pm_score": 4, "selected": false, "text": "<p>Even though many beautiful definitions of JavaScript closures exists on the Internet, I am trying to start explaining my six-year-old friend with my favourite definitions of closure which helped me to understand the closure much better.</p>\n\n<p><strong>What is a Closure?</strong></p>\n\n<p>A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.</p>\n\n<p>A closure is the local variables for a function - kept alive after the function has returned.</p>\n\n<p>Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created in.</p>\n\n<p>Closures are an extension of the concept of scope. With closures, functions have access to variables that were available in the scope where the function was created.</p>\n\n<p>A closure is a stack-frame which is not deallocated when the function returns. (As if a 'stack-frame' were malloc'ed instead of being on the stack!)</p>\n\n<p>Languages such as Java provide the ability to declare methods private, meaning that they can only be called by other methods in the same class. JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures.</p>\n\n<p>A \"closure\" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that \"closes\" the expression).</p>\n\n<p>Closures are an abstraction mechanism that allow you to separate concerns very cleanly.</p>\n\n<p><strong>Uses of Closures:</strong></p>\n\n<p>Closures are useful in hiding the implementation of functionality while still revealing the interface.</p>\n\n<p>You can emulate the encapsulation concept in JavaScript using closures.</p>\n\n<p>Closures are used extensively in <a href=\"http://en.wikipedia.org/wiki/JQuery\">jQuery</a> and <a href=\"http://en.wikipedia.org/wiki/Node.js\">Node.js</a>.</p>\n\n<p>While object literals are certainly easy to create and convenient for storing data, closures are often a better choice for creating static singleton namespaces in a large web application.</p>\n\n<p><strong>Example of Closures:</strong></p>\n\n<p>Assuming my 6-year-old friend get to know addition very recently in his primary school, I felt this example of adding the two numbers would be the simplest and apt for the six-year-old to learn the closure.</p>\n\n<p><strong>Example 1: Closure is achieved here by returning a function.</strong></p>\n\n<pre><code>function makeAdder(x) {\n return function(y) {\n return x + y;\n };\n}\n\nvar add5 = makeAdder(5);\nvar add10 = makeAdder(10);\n\nconsole.log(add5(2)); // 7\nconsole.log(add10(2)); // 12\n</code></pre>\n\n<p><strong>Example 2: Closure is achieved here by returning an object literal.</strong></p>\n\n<pre><code>function makeAdder(x) {\n return {\n add: function(y){\n return x + y;\n }\n }\n}\n\nvar add5 = makeAdder(5);\nconsole.log(add5.add(2));//7\n\nvar add10 = makeAdder(10);\nconsole.log(add10.add(2));//12\n</code></pre>\n\n<p><strong>Example 3: Closures in jQuery</strong></p>\n\n<pre><code>$(function(){\n var name=\"Closure is easy\";\n $('div').click(function(){\n $('p').text(name);\n });\n});\n</code></pre>\n\n<p><strong>Useful Links:</strong></p>\n\n<ul>\n<li><em><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures\">Closures</a></em> (Mozilla Developer Network)</li>\n<li><em><a href=\"http://javascriptissexy.com/understand-javascript-closures-with-ease/\">Understand JavaScript Closures With Ease</a></em></li>\n</ul>\n\n<p>Thanks to the above links which helps me to understand and explain closure better.</p>\n" }, { "answer_id": 22721884, "author": "williambq", "author_id": 1200607, "author_profile": "https://Stackoverflow.com/users/1200607", "pm_score": 3, "selected": false, "text": "<p>I have read all of these before in the past, and they are all very informative. Some come very close to getting the simple explanation and then get complex or remain abstract, defeating the purpose and failing to show a very simple real world use. </p>\n\n<p>Though combing through all the examples and explanations you get a good idea of what closures are and aren't via comments and code, I was still unsatisfied with a very simple illustration that helped me get a closures usefulness without getting so complex. My wife wants to learn coding and I figured I needed to be able to show here not only what, but why, and and how.</p>\n\n<p>I am not sure a six year old will get this, but I think it might be a little closer to demonstrating a simple case in a real world way that might acually be useful and that is easily understandable.</p>\n\n<p>One of the best (or closest to simplest) is the retelling of Morris' Closures for Dummies example.</p>\n\n<p>Taking the \"SayHi2Bob\" concept just one step further demonstrates the two basic things you can glean from reading all the answers:</p>\n\n<ol>\n<li>Closures have access to the containing function's variables.</li>\n<li>Closures persist in their own memory space (and thus are useful for all kinds of oop-y instantiation stuff)</li>\n</ol>\n\n<p>Proving and demonstrating this to myself, I made a little fiddle:</p>\n\n<p><a href=\"http://jsfiddle.net/9ZMyr/2/\">http://jsfiddle.net/9ZMyr/2/</a></p>\n\n<pre><code>function sayHello(name) {\n var text = 'Hello ' + name; // Local variable\n console.log(text);\n var sayAlert = function () {\n alert(text);\n }\n return sayAlert;\n}\n\nsayHello(); \n/* This will write 'Hello undefined' to the console (in Chrome anyway), \nbut will not alert though since it returns a function handle to nothing). \nSince no handle or reference is created, I imagine a good js engine would \ndestroy/dispose of the internal sayAlert function once it completes. */\n\n// Create a handle/reference/instance of sayHello() using the name 'Bob'\nsayHelloBob = sayHello('Bob');\nsayHelloBob();\n\n// Create another handle or reference to sayHello with a different name\nsayHelloGerry = sayHello('Gerry');\nsayHelloGerry();\n\n/* Now calling them again demonstrates that each handle or reference contains its own \nunique local variable memory space. They remain in memory 'forever' \n(or until your computer/browser explode) */\nsayHelloBob();\nsayHelloGerry();\n</code></pre>\n\n<p>This demonstrates both of the basic concepts you should get about closures. </p>\n\n<p>In simple terms to explain the why this is useful, I have a base function to which I can make references or handles that contain unique data which persists within that memory reference. I don't have to rewrite the function for each time I want to say someone's name. I have encapsulated that routine and made it reusable.</p>\n\n<p>To me this leads to at least the basic concepts of constructors, oop practices, singletons vs instantiated instances with their own data, etc. etc.</p>\n\n<p>If you start a neophyte with this, then you can move on to more complex object property/member based calls, and hopefully the concepts carry.</p>\n" }, { "answer_id": 22832931, "author": "Bhojendra Rauniyar", "author_id": 2138752, "author_profile": "https://Stackoverflow.com/users/2138752", "pm_score": 4, "selected": false, "text": "<p>A closure is created when the inner function is somehow made available to any scope outside the outer function.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>var outer = function(params){ //Outer function defines a variable called params\n var inner = function(){ // Inner function has access to the params variable of the outer function\n return params;\n }\n return inner; //Return inner function exposing it to outer scope\n},\nmyFunc = outer(\"myParams\");\nmyFunc(); //Returns \"myParams\"\n</code></pre>\n" }, { "answer_id": 23711357, "author": "Pawel Furmaniak", "author_id": 221315, "author_profile": "https://Stackoverflow.com/users/221315", "pm_score": 3, "selected": false, "text": "<p>Closure is when a function is <strong>closed</strong> in a way that it was defined in a namespace which is immutable by the time the function is called.</p>\n\n<p>In JavaScript, it happens when you:</p>\n\n<ul>\n<li>Define one function inside the other function</li>\n<li>The inner function is called after the outer function returned</li>\n</ul>\n\n\n\n<pre><code>// 'name' is resolved in the namespace created for one invocation of bindMessage\n// the processor cannot enter this namespace by the time displayMessage is called\nfunction bindMessage(name, div) {\n\n function displayMessage() {\n alert('This is ' + name);\n }\n\n $(div).click(displayMessage);\n}\n</code></pre>\n" }, { "answer_id": 23984252, "author": "nomen", "author_id": 738762, "author_profile": "https://Stackoverflow.com/users/738762", "pm_score": 3, "selected": false, "text": "<p>I think it is valuable to take a step back, and examine a more general notion of a \"closure\" -- the so-called \"join operator\".</p>\n\n<p>In mathematics, a \"join\" operator is a function on a partially ordered set which returns the smallest object greater than or equal to its arguments. In symbols, join [a,b] = d such that d >= a and d >= b, but there does not exist an e such that d > e >= a or d > e >= b.</p>\n\n<p>So the join gives you the smallest thing \"bigger\" than the parts.</p>\n\n<p>Now, note that JavaScript scopes are a partially ordered structure. So that there is a sensible notion of a join. In particular, a join of scopes is the smallest scope bigger than the original scopes. That scope is called the <strong>closure</strong>.</p>\n\n<p>So a closure for the variables a, b, c is the smallest scope (in the lattice of scopes for your program!) that brings a, b, and c into scope.</p>\n" }, { "answer_id": 24123501, "author": "Magne", "author_id": 380607, "author_profile": "https://Stackoverflow.com/users/380607", "pm_score": 4, "selected": false, "text": "<p>A closure is a block of code which meets three criteria:</p>\n\n<ul>\n<li><p>It can be passed around as a value and</p></li>\n<li><p>executed on demand by anyone who has that value, at which time</p></li>\n<li><p>it can refer to variables from the context in which it was created\n(that is, it is closed with respect to variable access, in the\nmathematical sense of the word \"closed\").</p></li>\n</ul>\n\n<p>(The word \"closure\" actually has an imprecise meaning, and some people don't think that criterion #1 is part of the definition. I think it is.)</p>\n\n<p>Closures are a mainstay of functional languages, but they are present in many other languages as well (for example, Java's anonymous inner classes). You can do cool stuff with them: they allow deferred execution and some elegant tricks of style.</p>\n\n<p>By: Paul Cantrell, @ <a href=\"http://innig.net/software/ruby/closures-in-ruby\">http://innig.net/software/ruby/closures-in-ruby</a></p>\n" }, { "answer_id": 24944994, "author": "b_dev", "author_id": 290150, "author_profile": "https://Stackoverflow.com/users/290150", "pm_score": 4, "selected": false, "text": "<p>Imagine there is a very large park in your town where you see a magician called Mr. Coder starting baseball games in different corners of the park using his magic wand, called JavaScript.</p>\n\n<p>Naturally each baseball game has the exact same rules and each game has its own score board.</p>\n\n<p>Naturally, the scores of one baseball game are completely separate from the other games.</p>\n\n<p>A closure is the special way Mr.Coder keeps the scoring of all his magical baseball games separate.</p>\n" }, { "answer_id": 26602035, "author": "Mayur Randive", "author_id": 3145245, "author_profile": "https://Stackoverflow.com/users/3145245", "pm_score": 5, "selected": false, "text": "<p>Here is a simple real-time scenario. Just read it through, and you will understand how we have used closure here (see how seat number is changing).</p>\n\n<p>All other examples explained previously are also very good to understand the concept.</p>\n\n<pre><code>function movieBooking(movieName) {\n var bookedSeatCount = 0;\n return function(name) {\n ++bookedSeatCount ;\n alert( name + \" - \" + movieName + \", Seat - \" + bookedSeatCount )\n };\n};\n\nvar MI1 = movieBooking(\"Mission Impossible 1 \");\nvar MI2 = movieBooking(\"Mission Impossible 2 \");\n\nMI1(\"Mayur\");\n// alert\n// Mayur - Mission Impossible 1, Seat - 1\n\nMI1(\"Raju\");\n// alert\n// Raju - Mission Impossible 1, Seat - 2\n\nMI2(\"Priyanka\");\n// alert\n// Raja - Mission Impossible 2, Seat - 1\n</code></pre>\n" }, { "answer_id": 26620526, "author": "grateful", "author_id": 3441335, "author_profile": "https://Stackoverflow.com/users/3441335", "pm_score": 6, "selected": false, "text": "<p>As a father of a 6-year-old, currently teaching young children (and a relative novice to coding with no formal education so corrections will be required), I think the lesson would stick best through hands-on play. If the 6-year-old is ready to understand what a closure is, then they are old enough to have a go themselves. I'd suggest pasting the code into jsfiddle.net, explaining a bit, and leaving them alone to concoct a unique song. The explanatory text below is probably more appropriate for a 10 year old.</p>\n\n<pre><code>function sing(person) {\n\n var firstPart = \"There was \" + person + \" who swallowed \";\n\n var fly = function() {\n var creature = \"a fly\";\n var result = \"Perhaps she'll die\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n var spider = function() {\n var creature = \"a spider\";\n var result = \"that wiggled and jiggled and tickled inside her\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n var bird = function() {\n var creature = \"a bird\";\n var result = \"How absurd!\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n var cat = function() {\n var creature = \"a cat\";\n var result = \"Imagine That!\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n fly();\n spider();\n bird();\n cat();\n}\n\nvar person=\"an old lady\";\n\nsing(person);\n</code></pre>\n\n<p><strong>INSTRUCTIONS</strong></p>\n\n<p>DATA: Data is a collection of facts. It can be numbers, words, measurements, observations or even just descriptions of things. You can't touch it, smell it or taste it. You can write it down, speak it and hear it. You could use it to <em>create</em> touch smell and taste using a computer. It can be made useful by a computer using code.</p>\n\n<p>CODE: All the writing above is called <em>code</em>. It is written in JavaScript.</p>\n\n<p>JAVASCRIPT: JavaScript is a language. Like English or French or Chinese are languages. There are lots of languages that are understood by computers and other electronic processors. For JavaScript to be understood by a computer it needs an interpreter. Imagine if a teacher who only speaks Russian comes to teach your class at school. When the teacher says \"все садятся\", the class would not understand. But luckily you have a Russian pupil in your class who tells everyone this means \"everybody sit down\" - so you all do. The class is like a computer and the Russian pupil is the interpreter. For JavaScript the most common interpreter is called a browser.</p>\n\n<p>BROWSER: When you connect to the Internet on a computer, tablet or phone to visit a website, you use a browser. Examples you may know are Internet Explorer, Chrome, Firefox and Safari. The browser can understand JavaScript and tell the computer what it needs to do. The JavaScript instructions are called functions.</p>\n\n<p>FUNCTION: A function in JavaScript is like a factory. It might be a little factory with only one machine inside. Or it might contain many other little factories, each with many machines doing different jobs. In a real life clothes factory you might have reams of cloth and bobbins of thread going in and T-shirts and jeans coming out. Our JavaScript factory only processes data, it can't sew, drill a hole or melt metal. In our JavaScript factory data goes in and data comes out.</p>\n\n<p>All this data stuff sounds a bit boring, but it is really very cool; we might have a function that tells a robot what to make for dinner. Let's say I invite you and your friend to my house. You like chicken legs best, I like sausages, your friend always wants what you want and my friend does not eat meat.</p>\n\n<p>I haven't got time to go shopping, so the function needs to know what we have in the fridge to make decisions. Each ingredient has a different cooking time and we want everything to be served hot by the robot at the same time. We need to provide the function with the data about what we like, the function could 'talk' to the fridge, and the function could control the robot.</p>\n\n<p>A function normally has a name, parentheses and braces. Like this:</p>\n\n<pre><code>function cookMeal() { /* STUFF INSIDE THE FUNCTION */ }\n</code></pre>\n\n<p><em>Note that <code>/*...*/</code> and <code>//</code> stop code being read by the browser.</em></p>\n\n<p>NAME: You can call a function just about whatever word you want. The example \"cookMeal\" is typical in joining two words together and giving the second one a capital letter at the beginning - but this is not necessary. It can't have a space in it, and it can't be a number on its own.</p>\n\n<p>PARENTHESES: \"Parentheses\" or <code>()</code> are the letter box on the JavaScript function factory's door or a post box in the street for sending packets of information to the factory. Sometimes the postbox might be marked <em>for example</em> <code>cookMeal(you, me, yourFriend, myFriend, fridge, dinnerTime)</code>, in which case you know what data you have to give it.</p>\n\n<p>BRACES: \"Braces\" which look like this <code>{}</code> are the tinted windows of our factory. From inside the factory you can see out, but from the outside you can't see in.</p>\n\n<p><strong>THE LONG CODE EXAMPLE ABOVE</strong></p>\n\n<p>Our code begins with the word <em>function</em>, so we know that it is one! Then the name of the function <em>sing</em> - that's my own description of what the function is about. Then parentheses <em>()</em>. The parentheses are always there for a function. Sometimes they are empty, and sometimes they have something in. This one has a word in: <code>(person)</code>. After this there is a brace like this <code>{</code> . This marks the start of the function <em>sing()</em>. It has a partner which marks the end of <em>sing()</em> like this <code>}</code></p>\n\n<pre><code>function sing(person) { /* STUFF INSIDE THE FUNCTION */ }\n</code></pre>\n\n<p>So this function might have something to do with singing, and might need some data about a person. It has instructions inside to do something with that data.</p>\n\n<p>Now, after the function <em>sing()</em>, near the end of the code is the line</p>\n\n<pre><code>var person=\"an old lady\";\n</code></pre>\n\n<p>VARIABLE: The letters <em>var</em> stand for \"variable\". A variable is like an envelope. On the outside this envelope is marked \"person\". On the inside it contains a slip of paper with the information our function needs, some letters and spaces joined together like a piece of string (it's called a string) that make a phrase reading \"an old lady\". Our envelope could contain other kinds of things like numbers (called integers), instructions (called functions), lists (called <em>arrays</em>). Because this variable is written outside of all the braces <code>{}</code>, and because you can see out through the tinted windows when you are inside the braces, this variable can be seen from anywhere in the code. We call this a 'global variable'.</p>\n\n<p>GLOBAL VARIABLE: <em>person</em> is a global variable, meaning that if you change its value from \"an old lady\" to \"a young man\", the <em>person</em> will keep being a young man until you decide to change it again and that any other function in the code can see that it's a young man. Press the <kbd>F12</kbd> button or look at the Options settings to open the developer console of a browser and type \"person\" to see what this value is. Type <code>person=\"a young man\"</code> to change it and then type \"person\" again to see that it has changed.</p>\n\n<p>After this we have the line</p>\n\n<pre><code>sing(person);\n</code></pre>\n\n<p>This line is calling the function, as if it were calling a dog</p>\n\n<blockquote>\n <p>\"Come on <em>sing</em>, Come and get <em>person</em>!\"</p>\n</blockquote>\n\n<p>When the browser has loaded the JavaScript code an reached this line, it will start the function. I put the line at the end to make sure that the browser has all the information it needs to run it.</p>\n\n<p>Functions define actions - the main function is about singing. It contains a variable called <em>firstPart</em> which applies to the singing about the person that applies to each of the verses of the song: \"There was \" + person + \" who swallowed\". If you type <em>firstPart</em> into the console, you won't get an answer because the variable is locked up in a function - the browser can't see inside the tinted windows of the braces.</p>\n\n<p>CLOSURES: The closures are the smaller functions that are inside the big <em>sing()</em> function. The little factories inside the big factory. They each have their own braces which mean that the variables inside them can't be seen from the outside. That's why the names of the variables (<em>creature</em> and <em>result</em>) can be repeated in the closures but with different values. If you type these variable names in the console window, you won't get its value because it's hidden by two layers of tinted windows.</p>\n\n<p>The closures all know what the <em>sing()</em> function's variable called <em>firstPart</em> is, because they can see out from their tinted windows.</p>\n\n<p>After the closures come the lines</p>\n\n<pre><code>fly();\nspider();\nbird();\ncat();\n</code></pre>\n\n<p>The sing() function will call each of these functions in the order they are given. Then the sing() function's work will be done.</p>\n" }, { "answer_id": 26860224, "author": "Shushanth Pallegar", "author_id": 4229768, "author_profile": "https://Stackoverflow.com/users/4229768", "pm_score": 5, "selected": false, "text": "<p>In JavaScript closures are awesome and unique, where variables or arguments are available to inner functions, and they will be alive even after the outer function has returned. Closures are used in most of the design patterns in JS</p>\n<pre><code>function getFullName(a, b) {\n return a + b;\n}\n\nfunction makeFullName(fn) {\n\n return function(firstName) {\n\n return function(secondName) {\n\n return fn(firstName, secondName);\n\n }\n }\n}\n\nmakeFullName(getFullName)(&quot;Stack&quot;)(&quot;overflow&quot;); // Stackoverflow\n</code></pre>\n" }, { "answer_id": 28442157, "author": "PsyChip", "author_id": 1381841, "author_profile": "https://Stackoverflow.com/users/1381841", "pm_score": 4, "selected": false, "text": "<p>Maybe you should consider an object-oriented structure instead of inner functions. For example:</p>\n<pre><code> var calculate = {\n number: 0,\n init: function (num) {\n this.number = num;\n },\n add: function (val) {\n this.number += val;\n },\n rem: function (val) {\n this.number -= val;\n }\n };\n</code></pre>\n<p>And read the result from the calculate.number variable, who needs &quot;return&quot; anyway.</p>\n<pre><code>//Addition\nFirst think about scope which defines what variable you have to access to (In Javascript);\n\n//there are two kinds of scope\nGlobal Scope which include variable declared outside function or curly brace\n\nlet globalVariable = &quot;foo&quot;;\n</code></pre>\n<p>One thing to keep in mind is once you've declared a global variable you can use it anywhere in your code even in function;</p>\n<p>Local Scope which include variable that are usable only in a specific part of your code:</p>\n<p>Function scope is when you declare a variable in a function you can access the variable only within the function</p>\n<pre><code>function User(){\n let name = &quot;foo&quot;;\n alert(name);\n}\nalert(name);//error\n\n//Block scope is when you declare a variable within a block then you can access that variable only within a block \n{\n let user = &quot;foo&quot;;\n alert(user);\n}\nalert(user);\n//Uncaught ReferenceError: user is not defined at.....\n\n//A Closure\n\nfunction User(fname){\n return function(lname){\n return fname + &quot; &quot; lname;\n }\n}\nlet names = User(&quot;foo&quot;);\nalert(names(&quot;bar&quot;));\n\n//When you create a function within a function you've created a closure, in our example above since the outer function is returned the inner function got access to outer function's scope\n</code></pre>\n" }, { "answer_id": 28507451, "author": "floribon", "author_id": 1501926, "author_profile": "https://Stackoverflow.com/users/1501926", "pm_score": 7, "selected": false, "text": "<p><strong>I do not understand why the answers are so complex here.</strong></p>\n<p>Here is a closure:</p>\n<pre><code>var a = 42;\n\nfunction b() { return a; }\n</code></pre>\n<p>Yes. You probably use that many times a day.</p>\n<br>\n<blockquote>\n<p>There is no reason to believe closures are a complex design hack to address specific problems. No, closures are just about using a variable that comes from a higher scope <strong>from the perspective of where the function was declared (not run)</strong>.</p>\n<p>Now what it <em>allows</em> you to do can be more spectacular, see other answers.</p>\n</blockquote>\n" }, { "answer_id": 28816564, "author": "Michael Dziedzic", "author_id": 4171115, "author_profile": "https://Stackoverflow.com/users/4171115", "pm_score": 6, "selected": false, "text": "<p>Perhaps a little beyond all but the most precocious of six-year-olds, but a few examples that helped make the concept of closure in JavaScript click for me.</p>\n\n<p>A closure is a function that has access to another function's scope (its variables and functions). The easiest way to create a closure is with a function within a function; the reason being that in JavaScript a function always has access to its containing function’s scope.</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-js lang-js prettyprint-override\"><code>function outerFunction() {\r\n var outerVar = \"monkey\";\r\n \r\n function innerFunction() {\r\n alert(outerVar);\r\n }\r\n \r\n innerFunction();\r\n}\r\n\r\nouterFunction();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>ALERT: monkey</p>\n\n<p>In the above example, outerFunction is called which in turn calls innerFunction. Note how outerVar is available to innerFunction, evidenced by its correctly alerting the value of outerVar.</p>\n\n<p>Now consider the following:</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-js lang-js prettyprint-override\"><code>function outerFunction() {\r\n var outerVar = \"monkey\";\r\n \r\n function innerFunction() {\r\n return outerVar;\r\n }\r\n \r\n return innerFunction;\r\n}\r\n\r\nvar referenceToInnerFunction = outerFunction();\r\nalert(referenceToInnerFunction());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>ALERT: monkey</p>\n\n<p>referenceToInnerFunction is set to outerFunction(), which simply returns a reference to innerFunction. When referenceToInnerFunction is called, it returns outerVar. Again, as above, this demonstrates that innerFunction has access to outerVar, a variable of outerFunction. Furthermore, it is interesting to note that it retains this access even after outerFunction has finished executing.</p>\n\n<p>And here is where things get really interesting. If we were to get rid of outerFunction, say set it to null, you might think that referenceToInnerFunction would loose its access to the value of outerVar. But this is not the case. </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-js lang-js prettyprint-override\"><code>function outerFunction() {\r\n var outerVar = \"monkey\";\r\n \r\n function innerFunction() {\r\n return outerVar;\r\n }\r\n \r\n return innerFunction;\r\n}\r\n\r\nvar referenceToInnerFunction = outerFunction();\r\nalert(referenceToInnerFunction());\r\n\r\nouterFunction = null;\r\nalert(referenceToInnerFunction());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>ALERT: monkey\nALERT: monkey</p>\n\n<p>But how is this so? How can referenceToInnerFunction still know the value of outerVar now that outerFunction has been set to null?</p>\n\n<p>The reason that referenceToInnerFunction can still access the value of outerVar is because when the closure was first created by placing innerFunction inside of outerFunction, innerFunction added a reference to outerFunction’s scope (its variables and functions) to its scope chain. What this means is that innerFunction has a pointer or reference to all of outerFunction’s variables, including outerVar. So even when outerFunction has finished executing, or even if it is deleted or set to null, the variables in its scope, like outerVar, stick around in memory because of the outstanding reference to them on the part of the innerFunction that has been returned to referenceToInnerFunction. To truly release outerVar and the rest of outerFunction’s variables from memory you would have to get rid of this outstanding reference to them, say by setting referenceToInnerFunction to null as well.</p>\n\n<p>//////////</p>\n\n<p>Two other things about closures to note. First, the closure will always have access to the last values of its containing function.</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-js lang-js prettyprint-override\"><code>function outerFunction() {\r\n var outerVar = \"monkey\";\r\n \r\n function innerFunction() {\r\n alert(outerVar);\r\n }\r\n \r\n outerVar = \"gorilla\";\r\n\r\n innerFunction();\r\n}\r\n\r\nouterFunction();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>ALERT: gorilla</p>\n\n<p>Second, when a closure is created, it retains a reference to all of its enclosing function’s variables and functions; it doesn’t get to pick and choose. And but so, closures should be used sparingly, or at least carefully, as they can be memory intensive; a lot of variables can be kept in memory long after a containing function has finished executing.</p>\n" }, { "answer_id": 29525677, "author": "Rafael Eyng", "author_id": 1717979, "author_profile": "https://Stackoverflow.com/users/1717979", "pm_score": 5, "selected": false, "text": "<p>(I am not taking the 6-years-old thing into account.)</p>\n\n<p>In a language like JavaScript, where you can pass functions as parameters to other functions (languages where functions are <em>first class citizens</em>), you will often find yourself doing something like:</p>\n\n<pre><code>var name = 'Rafael';\n\nvar sayName = function() {\n console.log(name);\n};\n</code></pre>\n\n<p>You see, <code>sayName</code> doesn't have the definition for the <code>name</code> variable, but it does use the value of <code>name</code> that was defined outside of <code>sayName</code> (in a parent scope).</p>\n\n<p>Let's say you pass <code>sayName</code> as a parameter to another function, that will call <code>sayName</code> as a callback:</p>\n\n<pre><code>functionThatTakesACallback(sayName);\n</code></pre>\n\n<p>Note that:</p>\n\n<ol>\n<li><code>sayName</code> will be called from inside <code>functionThatTakesACallback</code> (assume that, since I haven't implemented <code>functionThatTakesACallback</code> in this example).</li>\n<li>When <code>sayName</code> is called, it will log the value of the <code>name</code> variable.</li>\n<li><code>functionThatTakesACallback</code> doesn't define a <code>name</code> variable (well, it could, but it wouldn't matter, so assume it doesn't).</li>\n</ol>\n\n<p>So we have <code>sayName</code> being called inside <code>functionThatTakesACallback</code> and referring to a <code>name</code> variable that is not defined inside <code>functionThatTakesACallback</code>.</p>\n\n<p>What happens then? A <code>ReferenceError: name is not defined</code>?</p>\n\n<p>No! The value of <code>name</code> is captured inside a <strong>closure</strong>. You can think of this closure as <strong>context associated to a function</strong>, that holds the values that were available where that function was defined.</p>\n\n<p>So: Even though <code>name</code> is not in scope where the function <code>sayName</code> will be called (inside <code>functionThatTakesACallback</code>), <code>sayName</code> can access the value for <code>name</code> that is captured in the closure associated with <code>sayName</code>.</p>\n\n<p>--</p>\n\n<p>From the book <em>Eloquent JavaScript</em>:</p>\n\n<blockquote>\n <p>A good mental model is to think of function values as containing both the code in their body and the environment in which they are created. When called, the function body sees its original environment, not the environment in which the call is made.</p>\n</blockquote>\n" }, { "answer_id": 29639524, "author": "Andy", "author_id": 200224, "author_profile": "https://Stackoverflow.com/users/200224", "pm_score": 5, "selected": false, "text": "<p>Here's the most Zen answer I can give:</p>\n\n<p>What would you expect this code to do? Tell me in a comment before you run it. I'm curious!</p>\n\n<pre><code>function foo() {\n var i = 1;\n return function() {\n console.log(i++);\n }\n}\n\nvar bar = foo();\nbar();\nbar();\nbar();\n\nvar baz = foo();\nbaz();\nbaz();\nbaz();\n</code></pre>\n\n<p>Now open the console in your browser (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd> or <kbd>F12</kbd>, hopefully) and paste the code in and hit <kbd>Enter</kbd>.</p>\n\n<p>If this code printed what you expect (JavaScript newbies - ignore the \"undefined\" at the end), then you already have <em>wordless understanding</em>. <em>In words</em>, the variable <code>i</code> is part of the inner function <em>instance's</em> closure.</p>\n\n<p>I put it this way because, once I understood that this code is putting instances of <code>foo()</code>'s inner function in <code>bar</code> and <code>baz</code> and then calling them via those variables, nothing else surprised me.</p>\n\n<p>But if I'm wrong and the console output surprised you, let me know!</p>\n" }, { "answer_id": 29693176, "author": "Dinesh Kanivu", "author_id": 2768137, "author_profile": "https://Stackoverflow.com/users/2768137", "pm_score": 5, "selected": false, "text": "<p>I believe in shorter explanations, so see the below image.</p>\n\n<p><img src=\"https://i.stack.imgur.com/qbv6M.jpg\" alt=\"Enter image description here\"></p>\n\n<p><code>function f1()</code> ..> Light Red Box</p>\n\n<p><code>function f2()</code> ..> Red Small Box</p>\n\n<p>Here we have two functions, <code>f1()</code> and <code>f2()</code>. f2() is inner to f1().\nf1() has a variable, <code>var x = 10</code>.</p>\n\n<p>When invoking the function <code>f1()</code>, <code>f2()</code> can access the value of <code>var x = 10</code>.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>function f1() {\n var x=10;\n\n function f2() {\n console.log(x)\n }\n\n return f2\n\n}\nf1()\n</code></pre>\n\n<p><code>f1()</code> invoking here:</p>\n\n<p><img src=\"https://i.stack.imgur.com/zg4UT.jpg\" alt=\"Enter image description here\"></p>\n" }, { "answer_id": 29932159, "author": "Javier La Banca", "author_id": 4175684, "author_profile": "https://Stackoverflow.com/users/4175684", "pm_score": 3, "selected": false, "text": "<p>The easiest use case I can think of to explain <strong>JavaScript closures</strong> is the Module Pattern. In the Module Pattern you define a function and call it immediately afterwards in what is called an Immediately Invoked Function Expression (IIFE). <strong>Everything that you write inside that function has private scope because it's defined inside the closure</strong>, thus allowing you to \"simulate\" privacy in JavaScript. Like so:</p>\n\n<pre><code> var Closure = (function () {\n // This is a closure\n // Any methods, variables and properties you define here are \"private\"\n // and can't be accessed from outside the function.\n\n //This is a private variable\n var foo = \"\";\n\n //This is a private method\n var method = function(){\n\n }\n})();\n</code></pre>\n\n<p>If, on the other hand, you'd like to make one or multiple variables or methods visible outside the closure, you can return them inside an object literal. Like so:</p>\n\n<pre><code>var Closure = (function () {\n // This is a closure\n // Any methods, variables and properties you define here are \"private\"\n // and can't be accessed from outside the function.\n\n //This is a private variable\n var foo = \"\";\n\n //This is a private method\n var method = function(){\n\n }\n\n //The method will be accessible from outside the closure\n return {\n method: method\n }\n\n})();\n\nClosure.method();\n</code></pre>\n\n<p>Hope it helps.\nRegards,</p>\n" }, { "answer_id": 29932217, "author": "Mike Robinson", "author_id": 4811873, "author_profile": "https://Stackoverflow.com/users/4811873", "pm_score": 2, "selected": false, "text": "<p><em>Also...</em> Perhaps we should cut your 27-year-old friend a little <em>slack,</em> because the entire concept of \"closures\" really <strong>is(!)</strong> ... <em>voodoo!</em> </p>\n\n<p>By that I mean: <em>(a)</em> you do not, intuitively, expect it ...AND... <em>(b)</em> when someone takes the time to explain it to you, you certainly do not expect it to <em>work!</em></p>\n\n<p>Intuition tells you that \"this must be nonsense... <em>surely</em> it must result in some kind of syntax-error or something!\" <em>How on earth(!)</em> could you, in effect, \"pull a function from 'the middle of' wherever-it's-at,\" such that you could [still!] actually have read/write access to the context of \"wherever-it-<em>was</em>-at?!\"</p>\n\n<p>When you finally realize that such a thing is <em>possible,</em> then ... sure ... anyone's <em>after-the-fact</em> reaction would be: \"whoa-a-a-a(!)... kew-el-l-l-l...(!!!)\"</p>\n\n<p>But there will be a \"big counter-intuitive hurdle\" to overcome, first. Intuition gives you plenty of utterly-plausible expectations that such a thing would be \"of <em>course,</em> absolutely nonsensical and therefore quite impossible.\"</p>\n\n<p>Like I said: \"it's voodoo.\"</p>\n" }, { "answer_id": 29945428, "author": "enb081", "author_id": 2063910, "author_profile": "https://Stackoverflow.com/users/2063910", "pm_score": 4, "selected": false, "text": "<p>A closure is <strong><em>a function within a function</em></strong> that has access to its \"parent\" function's variables and parameters.</p>\n\n<p>Example:</p>\n\n<pre><code>function showPostCard(Sender, Receiver) {\n\n var PostCardMessage = \" Happy Spring!!! Love, \";\n\n function PreparePostCard() {\n return \"Dear \" + Receiver + PostCardMessage + Sender;\n }\n\n return PreparePostCard();\n}\nshowPostCard(\"Granny\", \"Olivia\");\n</code></pre>\n" }, { "answer_id": 30173047, "author": "Tero Tolonen", "author_id": 2287682, "author_profile": "https://Stackoverflow.com/users/2287682", "pm_score": 7, "selected": false, "text": "<blockquote>\n<p>The children will never forget the secrets they have shared with their parents, even after their parents are\ngone. This is what closures are for functions.</p>\n</blockquote>\n<p>The secrets for JavaScript functions are the private variables</p>\n<pre><code>var parent = function() {\n var name = &quot;Mary&quot;; // secret\n}\n</code></pre>\n<p>Every time you call it, the local variable &quot;name&quot; is created and given the name &quot;Mary&quot;. And every time the function exits the variable is lost and the name is forgotten.</p>\n<p>As you may guess, because the variables are re-created every time the function is called, and nobody else will know them, there must be a secret place where they are stored. It could be called <strong>Chamber of Secrets</strong> or <strong>stack</strong> or <strong>local scope</strong> but it doesn't matter. We know they are there, somewhere, hidden in the memory.</p>\n<p>But, in JavaScript, there is this very special thing that functions which are created inside other functions, can also know the local variables of their parents and keep them as long as they live.</p>\n<pre><code>var parent = function() {\n var name = &quot;Mary&quot;;\n var child = function(childName) {\n // I can also see that &quot;name&quot; is &quot;Mary&quot;\n }\n}\n</code></pre>\n<p>So, as long as we are in the parent -function, it can create one or more child functions which do share the secret variables from the secret place.</p>\n<p>But the sad thing is, if the child is also a private variable of its parent function, it would also die when the parent ends, and the secrets would die with them.</p>\n<p>So to live, the child has to leave before it's too late</p>\n<pre><code>var parent = function() {\n var name = &quot;Mary&quot;;\n var child = function(childName) {\n return &quot;My name is &quot; + childName +&quot;, child of &quot; + name; \n }\n return child; // child leaves the parent -&gt;\n}\nvar child = parent(); // &lt; - and here it is outside \n</code></pre>\n<p>And now, even though Mary is &quot;no longer running&quot;, the memory of her is not lost and her child will always remember her name and other secrets they shared during their time together.</p>\n<p>So, if you call the child &quot;Alice&quot;, she will respond</p>\n<pre><code>child(&quot;Alice&quot;) =&gt; &quot;My name is Alice, child of Mary&quot;\n</code></pre>\n<p>That's all there is to tell.</p>\n" }, { "answer_id": 30519095, "author": "Harry Robbins", "author_id": 4926814, "author_profile": "https://Stackoverflow.com/users/4926814", "pm_score": 4, "selected": false, "text": "<p>A closure is something many JavaScript developers use all the time, but we take it for granted. How it works is not that complicated. Understanding how to use it purposefully <em>is</em> complex.</p>\n\n<p>At its simplest definition (as other answers have pointed out), a closure is basically a function defined inside another function. And that inner function has access to variables defined in the scope of the outer function. The most common practice that you'll see using closures is defining variables and functions in the global scope, and having access to those variables in the function scope of that function.</p>\n\n<pre><code>var x = 1;\nfunction myFN() {\n alert(x); //1, as opposed to undefined.\n}\n// Or\nfunction a() {\n var x = 1;\n function b() {\n alert(x); //1, as opposed to undefined.\n }\n b();\n}\n</code></pre>\n\n<p>So what?</p>\n\n<p>A closure isn't that special to a JavaScript user until you think about what life would be like without them. In other languages, variables used in a function get cleaned up when that function returns. In the above, x would have been a \"null pointer\", and you'd need to establish a getter and setter and start passing references. Doesn't sound like JavaScript right? Thank the mighty closure.</p>\n\n<p>Why should I care?</p>\n\n<p>You don't really have to be aware of closures to use them. But as others have also pointed out, they can be <strong>leveraged</strong> to create faux private variables. Until you get to needing private variables, just use them like you always have.</p>\n" }, { "answer_id": 31374952, "author": "TastyCode", "author_id": 949827, "author_profile": "https://Stackoverflow.com/users/949827", "pm_score": 3, "selected": false, "text": "<p>I like Kyle Simpson's definition of a closure: </p>\n\n<blockquote>\n <p>Closure is when a function is able to remember and access its lexical\n scope even when that function is executing outside its lexical scope.</p>\n</blockquote>\n\n<p>Lexical scope is when an inner scope can access its outer scope.</p>\n\n<p>Here is a modified example he provides in his book series 'You Don't Know JS: Scopes &amp; Closures'. </p>\n\n<pre><code>function foo() {\n var a = 2;\n\n function bar() {\n console.log( a );\n }\n return bar;\n}\n\nfunction test() {\n var bz = foo();\n bz();\n}\n\n// prints 2. Here function bar referred by var bz is outside \n// its lexical scope but it can still access it\ntest(); \n</code></pre>\n" }, { "answer_id": 31608312, "author": "Mohammed Safeer", "author_id": 2293686, "author_profile": "https://Stackoverflow.com/users/2293686", "pm_score": 4, "selected": false, "text": "<p>The following example is a simple illustration of a JavaScript closure.\nThis is the closure function, which returns a function, with access to its local variable x,</p>\n\n<pre><code>function outer(x){\n return function inner(y){\n return x+y;\n }\n}\n</code></pre>\n\n<p>Invoke the function like this:</p>\n\n<pre><code>var add10 = outer(10);\nadd10(20); // The result will be 30\nadd10(40); // The result will be 50\n\nvar add20 = outer(20);\nadd20(20); // The result will be 40\nadd20(40); // The result will be 60\n</code></pre>\n" }, { "answer_id": 32025281, "author": "Saber", "author_id": 1262198, "author_profile": "https://Stackoverflow.com/users/1262198", "pm_score": 6, "selected": false, "text": "<p>The author of <em><a href=\"http://javascript.info/tutorial/closures\" rel=\"noreferrer\">Closures</a></em> has explained closures pretty well, explaining the reason why we need them and also explaining LexicalEnvironment which is necessary to understanding closures. <br/>\nHere is the summary:</p>\n\n<p>What if a variable is accessed, but it isn’t local? Like here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/SLlVB.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SLlVB.png\" alt=\"Enter image description here\"></a></p>\n\n<p>In this case, the interpreter finds the variable in the\nouter <a href=\"http://javascript.info/tutorial/initialization\" rel=\"noreferrer\"><code>LexicalEnvironment</code></a> object.</p>\n\n<p>The process consists of two steps:</p>\n\n<ol>\n<li>First, when a function f is created, it is not created in an empty\nspace. There is a current LexicalEnvironment object. In the case\nabove, it’s window (a is undefined at the time of function\ncreation).</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/0KBin.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0KBin.png\" alt=\"Enter image description here\"></a></p>\n\n<p>When a function is created, it gets a hidden property, named [[Scope]], which references the current LexicalEnvironment.</p>\n\n<p><a href=\"https://i.stack.imgur.com/U3yt7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/U3yt7.png\" alt=\"Enter image description here\"></a></p>\n\n<p>If a variable is read, but can not be found anywhere, an error is generated.</p>\n\n<p><strong>Nested functions</strong></p>\n\n<p>Functions can be nested one inside another, forming a chain of LexicalEnvironments which can also be called a scope chain.</p>\n\n<p><a href=\"https://i.stack.imgur.com/2hUwr.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/2hUwr.png\" alt=\"Enter image description here\"></a></p>\n\n<p>So, function g has access to g, a and f.</p>\n\n<p><strong>Closures</strong></p>\n\n<p>A nested function may continue to live after the outer function has finished:</p>\n\n<p><a href=\"https://i.stack.imgur.com/S1mlB.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/S1mlB.png\" alt=\"Enter image description here\"></a></p>\n\n<p>Marking up LexicalEnvironments:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BzUNi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/BzUNi.png\" alt=\"Enter image description here\"></a></p>\n\n<p>As we see, <code>this.say</code> is a property in the user object, so it continues to live after User completed.</p>\n\n<p>And if you remember, when <code>this.say</code> is created, it (as every function) gets an internal reference <code>this.say.[[Scope]]</code> to the current LexicalEnvironment. So, the LexicalEnvironment of the current User execution stays in memory. All variables of User also are its properties, so they are also carefully kept, not junked as usually.</p>\n\n<p><strong>The whole point is to ensure that if the inner function wants to access an outer variable in the future, it is able to do so.</strong></p>\n\n<p>To summarize:</p>\n\n<ol>\n<li>The inner function keeps a reference to the outer\nLexicalEnvironment.</li>\n<li>The inner function may access variables from it\nany time even if the outer function is finished.</li>\n<li>The browser keeps the LexicalEnvironment and all its properties (variables) in memory until there is an inner function which references it.</li>\n</ol>\n\n<p>This is called a closure.</p>\n" }, { "answer_id": 32348248, "author": "Dmitry Frank", "author_id": 1099240, "author_profile": "https://Stackoverflow.com/users/1099240", "pm_score": 4, "selected": false, "text": "<p>Meet the <strong>illustrated explanation</strong>: <em><a href=\"http://dmitryfrank.com/articles/js_closures\">How do JavaScript closures work behind the scenes</a></em>.</p>\n\n<p>The article explains how the scope objects (or <code>LexicalEnvironment</code>s) are allocated and used in an intuitive way. Like, for this simple script:</p>\n\n<pre><code>\"use strict\";\n\nvar foo = 1;\nvar bar = 2;\n\nfunction myFunc() {\n //-- Define local-to-function variables\n var a = 1;\n var b = 2;\n var foo = 3;\n}\n\n//-- And then, call it:\nmyFunc();\n</code></pre>\n\n<p>When executing the top-level code, we have the following arrangement of scope objects:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bwjyg.png\"><img src=\"https://i.stack.imgur.com/bwjyg.png\" alt=\"Enter image description here\"></a></p>\n\n<p>And when <code>myFunc()</code> is called, we have the following scope chain:</p>\n\n<p><a href=\"https://i.stack.imgur.com/zRu5Z.png\"><img src=\"https://i.stack.imgur.com/zRu5Z.png\" alt=\"Enter image description here\"></a></p>\n\n<p>Understanding of how scope objects are created, used and deleted is a key to having a big picture and to understand how do closures work under the hood.</p>\n\n<p>See the aforementioned article for all the details.</p>\n" }, { "answer_id": 33072285, "author": "David Rosson", "author_id": 1068700, "author_profile": "https://Stackoverflow.com/users/1068700", "pm_score": 3, "selected": false, "text": "<p>The best way is to explain these concepts incrementally:</p>\n\n<p><strong>Variables</strong></p>\n\n<pre><code>console.log(x);\n// undefined\n</code></pre>\n\n<p>Here, <code>undefined</code> is JavaScript's way of saying \"I have no idea what <code>x</code> means.\"</p>\n\n<blockquote>\n <p>Variables are like tags.</p>\n</blockquote>\n\n<p>You can say, tag <code>x</code> points to value <code>42</code>:</p>\n\n<pre><code>var x = 42;\nconsole.log(x);\n// 42\n</code></pre>\n\n<p>Now JavaScript knows what <code>x</code> means.</p>\n\n<blockquote>\n <p>You can also re-assign a variable.</p>\n</blockquote>\n\n<p>Make tag <code>x</code> point to a different value:</p>\n\n<pre><code>x = 43;\nconsole.log(x);\n// 43\n</code></pre>\n\n<p>Now <code>x</code> means something else.</p>\n\n<p><strong>Scope</strong></p>\n\n<blockquote>\n <p>When you make a function, the function has its own \"box\" for variables.</p>\n</blockquote>\n\n<pre><code>function A() {\n var x = 42;\n}\n\nconsole.log(x);\n\n// undefined\n</code></pre>\n\n<p>From outside the box, you cannot see what's inside the box.</p>\n\n<p>But from inside the box, you can see what's outside that box:</p>\n\n<pre><code>var x = 42;\n\nfunction A() {\n console.log(x);\n}\n\n// 42\n</code></pre>\n\n<blockquote>\n <p>Inside function <code>A</code>, you have \"scope access\" to <code>x</code>.</p>\n</blockquote>\n\n<p>Now if you have two boxes side-by-side:</p>\n\n<pre><code>function A() {\n var x = 42;\n}\n\nfunction B() {\n console.log(x);\n}\n\n// undefined\n</code></pre>\n\n<blockquote>\n <p>Inside function <code>B</code>, you have no access to variables inside function <code>A</code>.</p>\n</blockquote>\n\n<p>But if you put define function <code>B</code> inside function <code>A</code>:</p>\n\n<pre><code>function A() {\n\n var x = 42;\n\n function B() {\n console.log(x);\n }\n\n}\n\n// 42\n</code></pre>\n\n<p>You now have \"scope access\".</p>\n\n<p><strong>Functions</strong></p>\n\n<p>In JavaScript, you run a function by calling it:</p>\n\n<pre><code>function A() {\n console.log(42);\n}\n</code></pre>\n\n<p>Like this:</p>\n\n<pre><code>A();\n\n// 42\n</code></pre>\n\n<p><strong>Functions as Values</strong></p>\n\n<p>In JavaScript, you can point a tag to a function, just like pointing to a number:</p>\n\n<pre><code>var a = function() {\n console.log(42);\n};\n</code></pre>\n\n<blockquote>\n <p>Variable <code>a</code> now means a function, you can run it.</p>\n</blockquote>\n\n<pre><code>a();\n// 42\n</code></pre>\n\n<p>You can also pass this variable around:</p>\n\n<pre><code>setTimeout(a, 1000);\n</code></pre>\n\n<p>In a second (1000 milliseconds), the function <code>a</code> points to is called:</p>\n\n<pre><code>// 42\n</code></pre>\n\n<p><strong>Closure Scope</strong></p>\n\n<p>Now when you define functions, those functions have access to their outer scopes.</p>\n\n<p>When you pass functions around as values, it would be troublesome if that access is lost.</p>\n\n<blockquote>\n <p>In JavaScript, functions keep their access to outer scope variables.\n Even when they are passed around to be run somewhere else.</p>\n</blockquote>\n\n<pre><code>var a = function() {\n\n var text = 'Hello!'\n\n var b = function() {\n console.log(text);\n // inside function `b`, you have access to `text`\n };\n\n // but you want to run `b` later, rather than right away\n setTimeout(b, 1000);\n\n}\n</code></pre>\n\n<p>What happens now?</p>\n\n<pre><code>// 'Hello!'\n</code></pre>\n\n<p>Or consider this:</p>\n\n<pre><code>var c;\n\nvar a = function() {\n\n var text = 'Hello!'\n\n var b = function() {\n console.log(text);\n // inside function `b`, you have access to `text`\n };\n\n c = b;\n\n}\n\n// now we are out side of function `a`\n// call `a` so the code inside `a` runs\na(); \n\n// now `c` has a value that is a function\n// because what happened when `a` ran\n\n// when you run `c`\nc();\n\n// 'Hello!'\n</code></pre>\n\n<blockquote>\n <p>You can still access variables in the closure scope.</p>\n</blockquote>\n\n<p>Even though <code>a</code> has finished running, and now you are running <code>c</code> outside of <code>a</code>.</p>\n\n<p>What just happened here is called '<strong><em>closure</em></strong>' in JavaScript.</p>\n" }, { "answer_id": 33279345, "author": "Ron Deijkers", "author_id": 2240490, "author_profile": "https://Stackoverflow.com/users/2240490", "pm_score": 4, "selected": false, "text": "<p><strong>Pinocchio: Closures in 1883 (over a century before JavaScript)</strong></p>\n\n<p>I think it can best be explained to a 6-year-old with a nice adventure... The part of the <a href=\"https://en.wikipedia.org/wiki/The_Adventures_of_Pinocchio\" rel=\"noreferrer\">Adventures of Pinocchio</a> where Pinocchio is being swallowed by an oversized dogfish...</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var tellStoryOfPinocchio = function(original) {\r\n\r\n // Prepare for exciting things to happen\r\n var pinocchioFindsMisterGeppetto;\r\n var happyEnding;\r\n\r\n // The story starts where Pinocchio searches for his 'father'\r\n var pinocchio = {\r\n name: 'Pinocchio',\r\n location: 'in the sea',\r\n noseLength: 2\r\n };\r\n\r\n // Is it a dog... is it a fish...\r\n // The dogfish appears, however there is no such concept as the belly\r\n // of the monster, there is just a monster...\r\n var terribleDogfish = {\r\n swallowWhole: function(snack) {\r\n // The swallowing of Pinocchio introduces a new environment (for the\r\n // things happening inside it)...\r\n // The BELLY closure... with all of its guts and attributes\r\n var mysteriousLightLocation = 'at Gepetto\\'s ship';\r\n\r\n // Yes: in my version of the story the monsters mouth is directly\r\n // connected to its belly... This might explain the low ratings\r\n // I had for biology...\r\n var mouthLocation = 'in the monsters mouth and then outside';\r\n\r\n var puppet = snack;\r\n\r\n\r\n puppet.location = 'inside the belly';\r\n alert(snack.name + ' is swallowed by the terrible dogfish...');\r\n\r\n // Being inside the belly, Pinocchio can now experience new adventures inside it\r\n pinocchioFindsMisterGeppetto = function() {\r\n // The event of Pinocchio finding Mister Geppetto happens inside the\r\n // belly and so it makes sence that it refers to the things inside\r\n // the belly (closure) like the mysterious light and of course the\r\n // hero Pinocchio himself!\r\n alert(puppet.name + ' sees a mysterious light (also in the belly of the dogfish) in the distance and swims to it to find Mister Geppetto! He survived on ship supplies for two years after being swallowed himself. ');\r\n puppet.location = mysteriousLightLocation;\r\n\r\n alert(puppet.name + ' tells Mister Geppetto he missed him every single day! ');\r\n puppet.noseLength++;\r\n }\r\n\r\n happyEnding = function() {\r\n // The escape of Pinocchio and Mister Geppetto happens inside the belly:\r\n // it refers to Pinocchio and the mouth of the beast.\r\n alert('After finding Mister Gepetto, ' + puppet.name + ' and Mister Gepetto travel to the mouth of the monster.');\r\n alert('The monster sleeps with its mouth open above the surface of the water. They escape through its mouth. ');\r\n puppet.location = mouthLocation;\r\n if (original) {\r\n alert(puppet.name + ' is eventually hanged for his innumerable faults. ');\r\n } else {\r\n alert(puppet.name + ' is eventually turned into a real boy and they all lived happily ever after...');\r\n }\r\n }\r\n }\r\n }\r\n\r\n alert('Once upon a time...');\r\n alert('Fast forward to the moment that Pinocchio is searching for his \\'father\\'...');\r\n alert('Pinocchio is ' + pinocchio.location + '.');\r\n terribleDogfish.swallowWhole(pinocchio);\r\n alert('Pinocchio is ' + pinocchio.location + '.');\r\n pinocchioFindsMisterGeppetto();\r\n alert('Pinocchio is ' + pinocchio.location + '.');\r\n happyEnding();\r\n alert('Pinocchio is ' + pinocchio.location + '.');\r\n\r\n if (pinocchio.noseLength &gt; 2)\r\n console.log('Hmmm... apparently a little white lie was told. ');\r\n}\r\n\r\ntellStoryOfPinocchio(false);\r\n\r\n </code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 33525748, "author": "Eugene Tiurin", "author_id": 2676500, "author_profile": "https://Stackoverflow.com/users/2676500", "pm_score": 4, "selected": false, "text": "<h1>Closures are simple</h1>\n<p>You probably shouldn't tell a six-year old about closures, but if you do, you might say that closure gives an ability to gain access to a variable declared in some other function scope.</p>\n<p><a href=\"https://i.stack.imgur.com/OX92v.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OX92v.png\" alt=\"enter image description here\" /></a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getA() {\n var a = [];\n\n // this action happens later,\n // after the function returned\n // the `a` value\n setTimeout(function() {\n a.splice(0, 0, 1, 2, 3, 4, 5);\n });\n\n return a;\n}\n\nvar a = getA();\nout('What is `a` length?');\nout('`a` length is ' + a.length);\n\nsetTimeout(function() {\n out('No wait...');\n out('`a` length is ' + a.length);\n out('OK :|')\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;pre id=\"output\"&gt;&lt;/pre&gt;\n\n&lt;script&gt;\n function out(k) {\n document.getElementById('output').innerHTML += '&gt; ' + k + '\\n';\n }\n&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 33531512, "author": "Gerard ONeill", "author_id": 1331672, "author_profile": "https://Stackoverflow.com/users/1331672", "pm_score": 2, "selected": false, "text": "<p>A closure is a function that has access to information from the environment it was defined in.</p>\n\n<p>For some, the information is the <em>value</em> in the environment at the time of creation. For others, the information is the variables in the environment at the time of creation.</p>\n\n<p>If the lexical environment that the closure refers to belongs to a function that has exited, then (in the case of a closure referring to the variables in the environment) those lexical variables will continue to exist for reference by the closure.</p>\n\n<p>A closure can be thought of a special case of global variables -- with a private copy created just for the function.</p>\n\n<p>Or it can be thought of as a method where the environment is a specific instance of an object whose properties are the variables in the environment.</p>\n\n<p>The former (closure as environment) similar to the latter where the environment copy is a context variable passed to each function in the former, and the instance variables form a context variable in the latter.</p>\n\n<p>So a closure is a way to call a function without having to specify the context explicitly as a parameter or as the object in a method invocation.</p>\n\n<pre><code>var closure = createclosure(varForClosure);\nclosure(param1); // closure has access to whatever createclosure gave it access to,\n // including the parameter storing varForClosure.\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>var contextvar = varForClosure; // use a struct for storing more than one..\ncontextclosure(contextvar, param1);\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>var contextobj = new contextclass(varForClosure);\ncontextobj-&gt;objclosure(param1);\n</code></pre>\n\n<p>For maintainable code, I recommend the object oriented way. However for a quick and easy set of tasks (for example creating a callback), a closure can become natural and more clear, especially in the context of lamda or anonymous functions.</p>\n" }, { "answer_id": 33544287, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>A closure is a function having access to the parent scope, even after the parent function has closed.</p>\n</blockquote>\n\n<pre><code>var add = (function() {\n var counter = 0;\n return function() {\n return counter += 1;\n }\n})();\n\nadd();\nadd();\nadd();\n// The counter is now 3\n</code></pre>\n\n<p>Example explained:</p>\n\n<ul>\n<li>The variable <code>add</code> is assigned the return value of a self-invoking function.</li>\n<li>The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.</li>\n<li>This way add becomes a function. The \"wonderful\" part is that it can access the counter in the parent scope.</li>\n<li>This is called a JavaScript closure. It makes it possible for a function to have \"private\" variables.</li>\n<li>The counter is protected by the scope of the anonymous function, and can only be changed using the add function.</li>\n</ul>\n\n<p><a href=\"http://www.w3schools.com/js/js_function_closures.asp\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 33570436, "author": "ejectamenta", "author_id": 1740850, "author_profile": "https://Stackoverflow.com/users/1740850", "pm_score": 3, "selected": false, "text": "<p>For a six-year-old ...</p>\n\n<p>Do you know what objects are?</p>\n\n<p>Objects are things that have properties and do stuff.</p>\n\n<p>One of the most important things about closures is that they let you make objects in JavaScript. Objects in JavaScript are just functions and closures that lets JavaScript store the value of the property for the object once it has been created.</p>\n\n<p>Objects are very useful and keep everything nice and organised. Different objects can do different jobs and working together objects can do complicated things.</p>\n\n<p>It's lucky that JavaScript has closures for making objects, otherwise everything would become a messy nightmare.</p>\n" }, { "answer_id": 33904070, "author": "NinjaBeetle", "author_id": 1509007, "author_profile": "https://Stackoverflow.com/users/1509007", "pm_score": 3, "selected": false, "text": "<p>There once was a caveman </p>\n\n<pre><code>function caveman {\n</code></pre>\n\n<p>who had a very special rock,</p>\n\n<pre><code>var rock = \"diamond\";\n</code></pre>\n\n<p>You could not get the rock yourself because it was in the caveman's private cave. Only the caveman knew how to find and get the rock.</p>\n\n<pre><code>return {\n getRock: function() {\n return rock;\n }\n};\n}\n</code></pre>\n\n<p>Luckily, he was a friendly caveman, and if you were willing to wait for his return, he would gladly get it for you.</p>\n\n<pre><code>var friend = caveman();\nvar rock = friend.getRock();\n</code></pre>\n\n<p>Pretty smart caveman.</p>\n" }, { "answer_id": 33961224, "author": "Pao Im", "author_id": 1256497, "author_profile": "https://Stackoverflow.com/users/1256497", "pm_score": 3, "selected": false, "text": "<p>Closures in JavaScript are associated with concept of scopes.</p>\n<p>Prior to es6, there is no block level scope, there is only function level scope in JS.</p>\n<p>That means whenever there is a need for block level scope, we need to wrap it inside a function.</p>\n<p>Check this simple and interesting example, how closure solves this issue in ES5</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>// let say we can only use a traditional for loop, not the forEach\n\nfor (var i = 0; i &lt; 10; i++) {\n \n setTimeout(function() {\n console.log('without closure the visited index - '+ i)\n })\n}\n\n// this will print 10 times 'visited index - 10', which is not correct\n\n/**\nExpected output is \n\nvisited index - 0\nvisited index - 1\n.\n.\n.\nvisited index - 9\n\n**/\n\n// we can solve it by using closure concept \n //by using an IIFE (Immediately Invoked Function Expression)\n\n\n// --- updated code ---\n\nfor (var i = 0; i &lt; 10; i++) {\n (function (i) {\n setTimeout(function() {\n console.log('with closure the visited index - '+ i)\n })\n })(i);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>NB: this can easily be solved by using es6 <code>let</code> instead of <code>var</code>, as let creates lexical scope.</p>\n<hr />\n<h2>In simple word, Closure in JS is nothing but accessing function scope.</h2>\n" }, { "answer_id": 34531380, "author": "Nikhil Ranjan", "author_id": 1125824, "author_profile": "https://Stackoverflow.com/users/1125824", "pm_score": 4, "selected": false, "text": "<p>To understand closures you have to get down to the program and literally execute as if you are the run time. Let's look at this simple piece of code:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kWR82.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kWR82.png\" alt=\"Enter image description here\"></a></p>\n\n<p>JavaScript runs the code in two phases:</p>\n\n<ul>\n<li>Compilation Phase // JavaScript is not a pure interpreted language</li>\n<li>Execution Phase</li>\n</ul>\n\n<p>When JavaScript goes through the compilation phase it extract out the declarations of variables and functions. This is called hoisting. Functions encountered in this phase are saved as text blobs in memory also known as lambda. After compilation JavaScript enters the execution phase where it assigns all the values and runs the function. To run the function it prepares the execution context by assigning memory from the heap and repeating the compilation and execution phase for the function. This memory area is called scope of the function. There is a global scope when execution starts. Scopes are the key in understanding closures.</p>\n\n<p>In this example, in first go, variable <code>a</code> is defined and then <code>f</code> is defined in the compilation phase. All undeclared variables are saved in the global scope. In the execution phase <code>f</code> is called with an argument. <code>f</code>'s scope is assigned and the compilation and execution phase is repeated for it.</p>\n\n<p>Arguments are also saved in this local scope for <code>f</code>. Whenever a local execution context or scope is created it contain a reference pointer to its parent scope. All variable access follows this lexical scope chain to find its value. If a variable is not found in the local scope it follows the chain and find it in its parent scope. This is also why a local variable overrides variables in the parent scope. The parent scope is called the \"Closure\" for local a scope or function.</p>\n\n<p>Here when <code>g</code>'s scope is being set up it got a lexical pointer to its parents scope of <code>f</code>. The scope of <code>f</code> is the closure for <code>g</code>. In JavaScript, if there is some reference to functions, objects or scopes if you can reach them somehow, it will not get garbage collected. So when myG is running, it has a pointer to scope of <code>f</code> which is its closure. This area of memory will not get garbage collected even <code>f</code> has returned. This is a closure as far as the runtime is concerned.</p>\n\n<h2>SO WHAT IS A CLOSURE?</h2>\n\n<ul>\n<li>It is an implicit, permanent link between a function and its scope chain...</li>\n<li>A function definition's (lambda) hidden <code>[[scope]]</code> reference.</li>\n<li>Holds the scope chain (preventing garbage collection).</li>\n<li>It is used and copied as the \"outer environment reference\" anytime the function is run.</li>\n</ul>\n\n<h2>IMPLICIT CLOSURE</h2>\n\n<pre><code>var data = \"My Data!\";\nsetTimeout(function() {\n console.log(data); // Prints \"My Data!\"\n}, 3000);\n</code></pre>\n\n<h2>EXPLICIT CLOSURES</h2>\n\n<pre><code>function makeAdder(n) {\n var inc = n;\n var sum = 0;\n return function add() {\n sum = sum + inc;\n return sum;\n };\n}\n\nvar adder3 = makeAdder(3);\n</code></pre>\n\n<p>A very interesting talk on closures and more is <em><a href=\"https://www.youtube.com/watch?v=QyUFheng6J0\" rel=\"noreferrer\">Arindam Paul - JavaScript VM internals, EventLoop, Async and ScopeChains</a></em>.</p>\n" }, { "answer_id": 34831990, "author": "devlighted", "author_id": 5791848, "author_profile": "https://Stackoverflow.com/users/5791848", "pm_score": 3, "selected": false, "text": "<p>This is how a beginner wrapped one's head around Closures like a function is wrapped inside of a functions body also known as <strong>Closures</strong>.</p>\n\n<p>Definition from the book Speaking JavaScript \"A closure is a function plus the connection to the scope in which the function was created\" -<em>Dr.Axel Rauschmayer</em></p>\n\n<p>So what could that look like? Here is an example</p>\n\n<pre><code>function newCounter() {\n var counter = 0;\n return function increment() {\n counter += 1;\n }\n}\n\nvar counter1 = newCounter();\nvar counter2 = newCounter();\n\ncounter1(); // Number of events: 1\ncounter1(); // Number of events: 2\ncounter2(); // Number of events: 1\ncounter1(); // Number of events: 3\n</code></pre>\n\n<p><em>newCounter</em> closes over <em>increment</em>, <em>counter</em> can be referenced to and accessed by <em>increment</em>.</p>\n\n<p><em>counter1</em> and <em>counter2</em> will keep track of their own value.</p>\n\n<p>Simple but hopefully a clear perspective of what a closure is around all these great and advanced answers.</p>\n" }, { "answer_id": 35250157, "author": "soundyogi", "author_id": 3293027, "author_profile": "https://Stackoverflow.com/users/3293027", "pm_score": 3, "selected": false, "text": "<h2>Functions containing no free variables are called pure functions.</h2>\n<h2>Functions containing one or more free variables are called closures.</h2>\n<pre><code>var pure = function pure(x){\n return x \n // only own environment is used\n}\n\nvar foo = &quot;bar&quot;\n\nvar closure = function closure(){\n return foo\n // foo is free variable from the outer environment\n}\n</code></pre>\n<p><sup>src: <a href=\"https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure\" rel=\"noreferrer\">https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure</a></sup></p>\n" }, { "answer_id": 36017683, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>MDN explains it best I think:</p>\n\n<blockquote>\n <p>Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.</p>\n</blockquote>\n\n<p>A closure always has an outer function and an inner function. The inner function is where all the work happens, and the outer function is just the environment that preserves the scope where the inner function was created. In this way, the inner function of a closure 'remembers' the environment/scope in which it was created. The most classic example is a counter function:</p>\n\n<pre><code>var closure = function() {\n var count = 0;\n return function() {\n count++;\n console.log(count);\n };\n};\n\nvar counter = closure();\n\ncounter() // returns 1\ncounter() // returns 2\ncounter() // returns 3\n</code></pre>\n\n<p>In the above code, <code>count</code> is preserved by the outer function (environment function), so that every time you call <code>counter()</code>, the inner function (work function) can increment it.</p>\n" }, { "answer_id": 36424854, "author": "Abrar Jahin", "author_id": 2193439, "author_profile": "https://Stackoverflow.com/users/2193439", "pm_score": 5, "selected": false, "text": "<p>Closures allow JavaScript programmers to write better code. Creative, expressive, and concise. We frequently use closures in JavaScript, and, no matter our JavaScript experience, we undoubtedly encounter them time and again. Closures might appear complex but hopefully, after you read this, closures will be much more easily understood and thus more appealing for your everyday JavaScript programming tasks.</p>\n\n<p>You should be familiar with <a href=\"http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/\"><strong><em>JavaScript variable scope</em></strong></a> before you read further because to understand closures you must understand JavaScript’s variable scope.</p>\n\n<h2>What is a closure?</h2>\n\n<p>A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.</p>\n\n<p>The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.</p>\n\n<p>You create a closure by adding a function inside another function.</p>\n\n<p><strong>A Basic Example of Closures in JavaScript:</strong>
</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function showName (firstName, lastName) {
\r\n var nameIntro = \"Your name is \";\r\n // this inner function has access to the outer function's variables, including the parameter\r\n ​function makeFullName () {
 \r\n​ return nameIntro + firstName + \" \" + lastName;
 \r\n }\r\n​\r\n​ return makeFullName ();
\r\n}
\r\n​\r\nshowName (\"Michael\", \"Jackson\"); // Your name is Michael Jackson
</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.</p>\n\n<p><strong>A Classic jQuery Example of Closures:</strong>
</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(function() {\r\n​\r\n​ var selections = []; \r\n $(\".niners\").click(function() { // this closure has access to the selections variable​\r\n selections.push (this.prop(\"name\")); // update the selections variable in the outer function's scope​\r\n });\r\n​});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Closures’ Rules and Side Effects</h2>\n\n<p><strong>1. Closures have access to the outer function’s variable even after the outer function returns:</strong></p>\n\n<p>One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function celebrityName (firstName) {\r\n var nameIntro = \"This celebrity is \";\r\n // this inner function has access to the outer function's variables, including the parameter​\r\n function lastName (theLastName) {\r\n return nameIntro + firstName + \" \" + theLastName;\r\n }\r\n return lastName;\r\n}\r\n​\r\n​var mjName = celebrityName (\"Michael\"); // At this juncture, the celebrityName outer function has returned.​\r\n​\r\n​// The closure (lastName) is called here after the outer function has returned above​\r\n​// Yet, the closure still has access to the outer function's variables and parameter​\r\nmjName (\"Jackson\"); // This celebrity is Michael Jackson
</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>2. Closures store references to the outer function’s variables:</strong></p>\n\n<p>They do not store the actual value. 
Closures get more interesting when the value of the outer function’s variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables example first demonstrated by Douglas Crockford:
</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function celebrityID () {\r\n var celebrityID = 999;\r\n // We are returning an object with some inner functions​\r\n // All the inner functions have access to the outer function's variables​\r\n return {\r\n getID: function () {\r\n // This inner function will return the UPDATED celebrityID variable​\r\n // It will return the current value of celebrityID, even after the changeTheID function changes it​\r\n return celebrityID;\r\n },\r\n setID: function (theNewID) {\r\n // This inner function will change the outer function's variable anytime​\r\n celebrityID = theNewID;\r\n }\r\n }\r\n​\r\n}\r\n​\r\n​var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.​\r\nmjID.getID(); // 999​\r\nmjID.setID(567); // Changes the outer function's variable​\r\nmjID.getID(); // 567: It returns the updated celebrityId variable
</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>3. Closures Gone Awry</strong></p>\n\n<p>Because closures have access to the updated values of the outer function’s variables, they can also lead to bugs when the outer function’s variable changes with a for loop. Thus:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// This example is explained in detail below (just after this code box).​\r\n​function celebrityIDCreator (theCelebrities) {\r\n var i;\r\n var uniqueID = 100;\r\n for (i = 0; i &lt; theCelebrities.length; i++) {\r\n theCelebrities[i][\"id\"] = function () {\r\n return uniqueID + i;\r\n }\r\n }\r\n \r\n return theCelebrities;\r\n}\r\n​\r\n​var actionCelebs = [{name:\"Stallone\", id:0}, {name:\"Cruise\", id:0}, {name:\"Willis\", id:0}];\r\n​\r\n​var createIdForActionCelebs = celebrityIDCreator (actionCelebs);\r\n​\r\n​var stalloneID = createIdForActionCelebs [0];

 console.log(stalloneID.id()); // 103</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<hr>\n\n<h2>More can be found here-</h2>\n\n<ol>\n<li><p><a href=\"http://javascript.info/tutorial/closures\">http://javascript.info/tutorial/closures</a></p></li>\n<li><p><a href=\"http://www.javascriptkit.com/javatutors/closures.shtml\">http://www.javascriptkit.com/javatutors/closures.shtml</a></p></li>\n</ol>\n" }, { "answer_id": 38686313, "author": "christian Nguyen", "author_id": 4225143, "author_profile": "https://Stackoverflow.com/users/4225143", "pm_score": 4, "selected": false, "text": "<p>Version picture for this answer: <strong>[Resolved]</strong></p>\n\n<p>Just forget about scope every thing and remember: When a variable needed somewhere, javascript will not destroy it. The variable always point to newest value.</p>\n\n<p><strong>Example 1:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/ckxN9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ckxN9.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Example 2:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/dAmCA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/dAmCA.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Example 3:</strong>\n<a href=\"https://i.stack.imgur.com/HRXgp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/HRXgp.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 39012806, "author": "Alexis", "author_id": 5168153, "author_profile": "https://Stackoverflow.com/users/5168153", "pm_score": 3, "selected": false, "text": "<p>Closure are not difficult to understand. It depends only from the point of view.</p>\n\n<p>I personally like to use them in cases of daily life.</p>\n\n<pre><code>function createCar()\n{\n var rawMaterial = [/* lots of object */];\n function transformation(rawMaterials)\n {\n /* lots of changement here */\n return transformedMaterial;\n }\n var transformedMaterial = transformation(rawMaterial);\n function assemblage(transformedMaterial)\n {\n /*Assemblage of parts*/\n return car;\n }\n return assemblage(transformedMaterial);\n}\n</code></pre>\n\n<p>We only need to go through certain steps in particular cases. As for the transformation of materials is only useful when you have the parts.</p>\n" }, { "answer_id": 39589063, "author": "Durgesh Pandey", "author_id": 5030579, "author_profile": "https://Stackoverflow.com/users/5030579", "pm_score": 4, "selected": false, "text": "<p><strong>Closures</strong> are a somewhat advanced, and often misunderstood feature of the JavaScript language. Simply put, closures are objects that contain a function and a reference to the environment in which the function was created. However, in order to fully understand closures, there are two other features of the JavaScript language that must first be understood―first-class functions and inner functions.</p>\n\n<p><strong>First-Class Functions</strong></p>\n\n<p>In programming languages, functions are considered to be first-class citizens if they can be manipulated like any other data type. For example, first-class functions can be constructed at runtime and assigned to variables. They can also be passed to, and returned by other functions. In addition to meeting the previously mentioned criteria, JavaScript functions also have their own properties and methods. The following example shows some of the capabilities of first-class functions. In the example, two functions are created and assigned to the variables “foo” and “bar”. The function stored in “foo” displays a dialog box, while “bar” simply returns whatever argument is passed to it. The last line of the example does several things. First, the function stored in “bar” is called with “foo” as its argument. “bar” then returns the “foo” function reference. Finally, the returned “foo” reference is called, causing “Hello World!” to be displayed.</p>\n\n<pre><code>var foo = function() {\n alert(\"Hello World!\");\n};\n\nvar bar = function(arg) {\n return arg;\n};\n\nbar(foo)();\n</code></pre>\n\n<p><strong>Inner Functions</strong></p>\n\n<p>Inner functions, also referred to as nested functions, are functions that are defined inside of another function (referred to as the outer function). Each time the outer function is called, an instance of the inner function is created. The following example shows how inner functions are used. In this case, add() is the outer function. Inside of add(), the doAdd() inner function is defined and called.</p>\n\n<pre><code>function add(value1, value2) {\n function doAdd(operand1, operand2) {\n return operand1 + operand2;\n }\n\n return doAdd(value1, value2);\n}\n\nvar foo = add(1, 2);\n// foo equals 3\n</code></pre>\n\n<p>One important characteristic of inner functions is that they have implicit access to the outer function’s scope. This means that the inner function can use the variables, arguments, etc. of the outer function. In the previous example, the “<em>value1</em>” and “<em>value2</em>” arguments of add() were passed to <em>doAdd()</em> as the “<em>operand1</em>” and “operand2” arguments. However, this is unnecessary because <em>doAdd()</em> has direct access to “<em>value1</em>” and “<em>value2</em>”. The previous example has been rewritten below to show how <em>doAdd()</em> can use “<em>value1</em>” and “<em>value2</em>”.</p>\n\n<pre><code>function add(value1, value2) {\n function doAdd() {\n return value1 + value2;\n }\n\n return doAdd();\n}\n\nvar foo = add(1, 2);\n// foo equals 3\n</code></pre>\n\n<blockquote>\n <p><strong>Creating Closures</strong></p>\n \n <p>A closure is created when an inner function is made accessible from\n outside of the function that created it. This typically occurs when an\n outer function returns an inner function. When this happens, the\n inner function maintains a reference to the environment in which it\n was created. This means that it remembers all of the variables (and\n their values) that were in scope at the time. The following example\n shows how a closure is created and used.</p>\n</blockquote>\n\n<pre><code>function add(value1) {\n return function doAdd(value2) {\n return value1 + value2;\n };\n}\n\nvar increment = add(1);\nvar foo = increment(2);\n// foo equals 3\n</code></pre>\n\n<p>There are a number of things to note about this example.</p>\n\n<p>The add() function returns its inner function doAdd(). By returning a reference to an inner function, a closure is created.\n“value1” is a local variable of add(), and a non-local variable of doAdd(). Non-local variables refer to variables that are neither in the local nor the global scope. “value2” is a local variable of doAdd().\nWhen add(1) is called, a closure is created and stored in “increment”. In the closure’s referencing environment, “value1” is bound to the value one. Variables that are bound are also said to be closed over. This is where the name closure comes from.\nWhen increment(2) is called, the closure is entered. This means that doAdd() is called, with the “value1” variable holding the value one. The closure can essentially be thought of as creating the following function.</p>\n\n<pre><code>function increment(value2) {\n return 1 + value2;\n}\n</code></pre>\n\n<blockquote>\n <p><strong>When to Use Closures</strong></p>\n \n <p>Closures can be used to accomplish many things. They are very useful\n for things like configuring callback functions with parameters. This\n section covers two scenarios where closures can make your life as a\n developer much simpler.</p>\n</blockquote>\n\n<p><strong>Working With Timers</strong></p>\n\n<p>Closures are useful when used in conjunction with the <em>setTimeout()</em> and <em>setInterval()</em> functions. To be more specific, closures allow you to pass arguments to the callback functions of <em>setTimeout()</em> and <em>setInterval()</em>. For example, the following code prints the string “some message” once per second by calling <em>showMessage()</em>.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;title&gt;Closures&lt;/title&gt;\n &lt;meta charset=\"UTF-8\" /&gt;\n &lt;script&gt;\n window.addEventListener(\"load\", function() {\n window.setInterval(showMessage, 1000, \"some message&lt;br /&gt;\");\n });\n\n function showMessage(message) {\n document.getElementById(\"message\").innerHTML += message;\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;span id=\"message\"&gt;&lt;/span&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Unfortunately, Internet Explorer does not support passing callback arguments via setInterval(). Instead of displaying “some message”, Internet Explorer displays “undefined” (since no value is actually passed to showMessage()). To work around this issue, a closure can be created which binds the “message” argument to the desired value. The closure can then be used as the callback function for setInterval(). To illustrate this concept, the JavaScript code from the previous example has been rewritten below to use a closure.</p>\n\n<pre><code>window.addEventListener(\"load\", function() {\n var showMessage = getClosure(\"some message&lt;br /&gt;\");\n\n window.setInterval(showMessage, 1000);\n});\n\nfunction getClosure(message) {\n function showMessage() {\n document.getElementById(\"message\").innerHTML += message;\n }\n\n return showMessage;\n}\n</code></pre>\n\n<p><strong>Emulating Private Data</strong></p>\n\n<p>Many object-oriented languages support the concept of private member data. However, JavaScript is not a pure object-oriented language and does not support private data. But, it is possible to emulate private data using closures. Recall that a closure contains a reference to the environment in which it was originally created―which is now out of scope. Since the variables in the referencing environment are only accessible from the closure function, they are essentially private data.</p>\n\n<p>The following example shows a constructor for a simple Person class. When each Person is created, it is given a name via the “<em>name</em>” argument. Internally, the Person stores its name in the “<em>_name</em>” variable. Following good object-oriented programming practices, the method <em>getName()</em> is also provided for retrieving the name.</p>\n\n<pre><code>function Person(name) {\n this._name = name;\n\n this.getName = function() {\n return this._name;\n };\n}\n</code></pre>\n\n<p>There is still one major problem with the Person class. Because JavaScript does not support private data, there is nothing stopping somebody else from coming along and changing the name. For example, the following code creates a Person named Colin, and then changes its name to Tom.</p>\n\n<pre><code>var person = new Person(\"Colin\");\n\nperson._name = \"Tom\";\n// person.getName() now returns \"Tom\"\n</code></pre>\n\n<p>Personally, I wouldn’t like it if just anyone could come along and legally change my name. In order to stop this from happening, a closure can be used to make the “_name” variable private. The Person constructor has been rewritten below using a closure. Note that “_name” is now a local variable of the Person constructor instead of an object property. A closure is formed because the outer function, <em>Person()</em> exposes an inner function by creating the public <em>getName()</em> method.</p>\n\n<pre><code>function Person(name) {\n var _name = name;\n\n this.getName = function() {\n return _name;\n };\n}\n</code></pre>\n\n<p>Now, when getName() is called, it is guaranteed to return the value that was originally passed to the constructor. It is still possible for someone to add a new “_name” property to the object, but the internal workings of the object will not be affected as long as they refer to the variable bound by the closure. The following code shows that the “_name” variable is, indeed, private.</p>\n\n<pre><code>var person = new Person(\"Colin\");\n\nperson._name = \"Tom\";\n// person._name is \"Tom\" but person.getName() returns \"Colin\"\n</code></pre>\n\n<blockquote>\n <p><strong>When Not to Use Closures</strong></p>\n \n <p>It is important to understand how closures work and when to use them.\n It is equally important to understand when they are not the right tool\n for the job at hand. Overusing closures can cause scripts to execute\n slowly and consume unnecessary memory. And because closures are so\n simple to create, it is possible to misuse them without even knowing\n it. This section covers several scenarios where closures should be\n used with caution.</p>\n</blockquote>\n\n<p><strong>In Loops</strong></p>\n\n<p>Creating closures within loops can have misleading results. An example of this is shown below. In this example, three buttons are created. When “button1” is clicked, an alert should be displayed that says “Clicked button 1”. Similar messages should be shown for “button2” and “button3”. However, when this code is run, all of the buttons show “Clicked button 4”. This is because, by the time one of the buttons is clicked, the loop has finished executing, and the loop variable has reached its final value of four.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;title&gt;Closures&lt;/title&gt;\n &lt;meta charset=\"UTF-8\" /&gt;\n &lt;script&gt;\n window.addEventListener(\"load\", function() {\n for (var i = 1; i &lt; 4; i++) {\n var button = document.getElementById(\"button\" + i);\n\n button.addEventListener(\"click\", function() {\n alert(\"Clicked button \" + i);\n });\n }\n });\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;input type=\"button\" id=\"button1\" value=\"One\" /&gt;\n &lt;input type=\"button\" id=\"button2\" value=\"Two\" /&gt;\n &lt;input type=\"button\" id=\"button3\" value=\"Three\" /&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>To solve this problem, the closure must be decoupled from the actual loop variable. This can be done by calling a new function, which in turn creates a new referencing environment. The following example shows how this is done. The loop variable is passed to the getHandler() function. getHandler() then returns a closure that is independent of the original “for” loop.</p>\n\n<pre><code>function getHandler(i) {\n return function handler() {\n alert(\"Clicked button \" + i);\n };\n}\nwindow.addEventListener(\"load\", function() {\n for (var i = 1; i &lt; 4; i++) {\n var button = document.getElementById(\"button\" + i);\n button.addEventListener(\"click\", getHandler(i));\n }\n});\n</code></pre>\n\n<blockquote>\n <p><strong>Unnecessary Use in Constructors</strong></p>\n \n <p>Constructor functions are another common source of closure misuse.\n We’ve seen how closures can be used to emulate private data. However,\n it is overkill to implement methods as closures if they don’t actually\n access the private data. The following example revisits the Person\n class, but this time adds a sayHello() method which doesn’t use the\n private data.</p>\n</blockquote>\n\n<pre><code>function Person(name) {\n var _name = name;\n\n this.getName = function() {\n return _name;\n };\n\n this.sayHello = function() {\n alert(\"Hello!\");\n };\n}\n</code></pre>\n\n<blockquote>\n <p>Each time a Person is instantiated, time is spent creating the\n sayHello() method. If many Person objects are created, this becomes a\n waste of time. A better approach would be to add sayHello() to the\n Person prototype. By adding to the prototype, all Person objects can\n share the same method. This saves time in the constructor by not\n having to create a closure for each instance. The previous example is\n rewritten below with the extraneous closure moved into the prototype.</p>\n</blockquote>\n\n<pre><code>function Person(name) {\n var _name = name;\n\n this.getName = function() {\n return _name;\n };\n}\n\nPerson.prototype.sayHello = function() {\n alert(\"Hello!\");\n};\n</code></pre>\n\n<p><strong>Things to Remember</strong></p>\n\n<ul>\n<li>Closures contain a function and a reference to the environment in\nwhich the function was created.</li>\n<li>A closure is formed when an outer function exposes an inner function.\nClosures can be used to easily pass parameters to callback functions.</li>\n<li>Private data can be emulated by using closures. This is common in\nobject-oriented programming and namespace design.</li>\n<li>Closures should be not overused in constructors. Adding to the\nprototype is a better idea.</li>\n</ul>\n\n<p><a href=\"https://www.sitepoint.com/javascript-closures-demystified/\">Link</a></p>\n" }, { "answer_id": 41773215, "author": "poushy", "author_id": 7417348, "author_profile": "https://Stackoverflow.com/users/7417348", "pm_score": 3, "selected": false, "text": "<p>My perspective of Closures:</p>\n\n<p><strong><em>Closures can be compared to a book, with a bookmark, on a bookshelf.</em></strong></p>\n\n<p>Suppose you have read a book, and you like some page in the book. You put in a bookmark at that page to track it.</p>\n\n<p>Now once you finish reading the book, you do not need the book anymore, except, you want to have access to that page. You could have just cut out the page, but then you would loose the context on the story. So you put the book back in your bookshelf with the bookmark.</p>\n\n<p>This is similar to a closure. The book is the outer function, and the page is your inner function, which gets returned, from the outer function. The bookmark is the reference to your page, and the context of the story is the lexical scope, which you need to retain. The bookshelf is the function stack, which cannot be cleaned up of the old books, till you hold onto the page.</p>\n\n<p><strong><em>Code Example:</em></strong></p>\n\n<pre><code>function book() {\n var pages = [....]; //array of pages in your book\n var bookMarkedPage = 20; //bookmarked page number\n function getPage(){\n return pages[bookMarkedPage];\n }\n return getPage;\n}\n\nvar myBook = book(),\n myPage = myBook.getPage();\n</code></pre>\n\n<p>When you run the <code>book()</code> function, you are allocating memory in the stack for the function to run in. But since it returns a function, the memory cannot be released, as the inner function has access to the variables from the context outside it, in this case 'pages' and 'bookMarkedPage'.</p>\n\n<p>So effectively calling <code>book()</code> returns a reference to a closure, i.e not only a function, but a reference to the book and it's context, i.e. a reference to the function <em>getPage</em>, state of <em>pages</em> and <em>bookMarkedPage</em> variables.</p>\n\n<p><strong><em>Some points to consider:</em></strong></p>\n\n<p><strong>Point 1:</strong>\nThe bookshelf, just like the function stack has limited space, so use it wisely.</p>\n\n<p><strong>Point 2:</strong>\nThink about the fact, whether you need to hold onto the entire book when you just want to track a single page. You can release part of the memory, by not storing all the pages in the book when the closure is returned.</p>\n\n<p><em>This is my perspective of Closures. Hope it helps, and if anyone thinks that this is not correct, please do let me know, as I am very interested to understand even more about scopes and closures!</em> </p>\n" }, { "answer_id": 42947217, "author": "zak.http", "author_id": 5897353, "author_profile": "https://Stackoverflow.com/users/5897353", "pm_score": 2, "selected": false, "text": "<p>A closure is simply when a function have access to its outside scope even after the scope's function has finished executing. \nExample: </p>\n\n<pre><code>function multiplier(n) {\n function multiply(x) {\n return n*x;\n }\n return mutliply;\n}\n\nvar 10xmultiplier = multiplier(10);\nvar x = 10xmultiplier(5); // x= 50\n</code></pre>\n\n<p>we can see that even after multiplier has finished executing, the inner function multiply gets still access to the value of x which is 10 in this example.</p>\n\n<p>A very common use of closures is currying (the same example above) where we spice our function progressively with parameters instead of supplying all of the arguments at once.</p>\n\n<p>We can achieve this because Javascript (in addition to the prototypal OOP) allows as to program in a functional fashion where higher order functions can take other functions as arguments (fisrt class functions).\n<a href=\"https://www.google.ae/url?sa=t&amp;source=web&amp;rct=j&amp;url=https://en.m.wikipedia.org/wiki/Functional_programming&amp;ved=0ahUKEwjaqeyM5enSAhUF7BQKHYyCBCUQFggZMAA&amp;usg=AFQjCNHcEMds9EmEfJfjtHIvLZhAivGFFQ&amp;sig2=rXB-1kc0AEVYLNy4fhGSmw\" rel=\"nofollow noreferrer\">functional programming in wikipedia</a></p>\n\n<p>I highly recommend you to read this book by Kyle Simpson: <a href=\"https://github.com/getify/You-Dont-Know-JS\" rel=\"nofollow noreferrer\">2</a> one part of the book series is dedicated to closures and it is called scope and closures.\n<a href=\"https://github.com/getify/You-Dont-Know-JS\" rel=\"nofollow noreferrer\">you don't know js: free reading on github</a></p>\n" }, { "answer_id": 43321420, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 3, "selected": false, "text": "<p>Let's start from here, As defined on MDN: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"noreferrer\"><strong>Closures</strong></a> are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.</p>\n\n<p><strong>Lexical scoping</strong><br>\nConsider the following:</p>\n\n<pre><code>function init() {\n var name = 'Mozilla'; // name is a local variable created by init\n function displayName() { // displayName() is the inner function, a closure\n alert(name); // use variable declared in the parent function \n }\n displayName(); \n}\ninit();\n</code></pre>\n\n<p>init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is only available within the body of the init() function. The displayName() function has no local variables of its own. However, because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().</p>\n\n<pre><code>function init() {\n var name = \"Mozilla\"; // name is a local variable created by init\n function displayName() { // displayName() is the inner function, a closure\n alert (name); // displayName() uses variable declared in the parent function \n }\n displayName(); \n}\ninit();\n</code></pre>\n\n<p>Run the code and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word \"lexical\" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.</p>\n\n<p><strong>Closure</strong><br>\nNow consider the following example:</p>\n\n<pre><code>function makeFunc() {\n var name = 'Mozilla';\n function displayName() {\n alert(name);\n }\n return displayName;\n}\n\nvar myFunc = makeFunc();\nmyFunc();\n</code></pre>\n\n<p>Running this code has exactly the same effect as the previous example of the init() function above: this time, the string \"Mozilla\" will be displayed in a JavaScript alert box. What's different — and interesting — is that the displayName() inner function is returned from the outer function before being executed.</p>\n\n<p>At first glance, it may seem unintuitive that this code still works. In some programming languages, the local variables within a function exist only for the duration of that function's execution. Once makeFunc() has finished executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.</p>\n\n<p>The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created. In this case, myFunc is a reference to the instance of the function displayName created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use and \"Mozilla\" is passed to alert.</p>\n\n<p>Here's a slightly more interesting example — a makeAdder function:</p>\n\n<pre><code>function makeAdder(x) {\n return function(y) {\n return x + y;\n };\n}\n\nvar add5 = makeAdder(5);\nvar add10 = makeAdder(10);\n\nconsole.log(add5(2)); // 7\nconsole.log(add10(2)); // 12\n</code></pre>\n\n<p>In this example, we have defined a function makeAdder(x), which takes a single argument, x, and returns a new function. The function it returns takes a single argument, y, and returns the sum of x and y.</p>\n\n<p>In essence, makeAdder is a function factory — it creates functions which can add a specific value to their argument. In the above example we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10.</p>\n\n<p>add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.</p>\n\n<p><strong>Practical closures</strong></p>\n\n<p>Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.</p>\n\n<p>Consequently, you can use a closure anywhere that you might normally use an object with only a single method.</p>\n\n<p>Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.</p>\n\n<p>For instance, suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:</p>\n\n<pre><code>body {\n font-family: Helvetica, Arial, sans-serif;\n font-size: 12px;\n}\n\nh1 {\n font-size: 1.5em;\n}\n\nh2 {\n font-size: 1.2em;\n}\n</code></pre>\n\n<p>Our interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units.\nHere's the JavaScript:</p>\n\n<pre><code>function makeSizer(size) {\n return function() {\n document.body.style.fontSize = size + 'px';\n };\n}\n\nvar size12 = makeSizer(12);\nvar size14 = makeSizer(14);\nvar size16 = makeSizer(16);\n</code></pre>\n\n<p>size12, size14, and size16 are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:</p>\n\n<pre><code>document.getElementById('size-12').onclick = size12;\ndocument.getElementById('size-14').onclick = size14;\ndocument.getElementById('size-16').onclick = size16;\n\n&lt;a href=\"#\" id=\"size-12\"&gt;12&lt;/a&gt;\n&lt;a href=\"#\" id=\"size-14\"&gt;14&lt;/a&gt;\n&lt;a href=\"#\" id=\"size-16\"&gt;16&lt;/a&gt;\n\n\nfunction makeSizer(size) {\n return function() {\n document.body.style.fontSize = size + 'px';\n };\n}\n\nvar size12 = makeSizer(12);\nvar size14 = makeSizer(14);\nvar size16 = makeSizer(16);\n\ndocument.getElementById('size-12').onclick = size12;\ndocument.getElementById('size-14').onclick = size14;\ndocument.getElementById('size-16').onclick = size16;\n</code></pre>\n\n<p>for reading more about closures, visit the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"noreferrer\">link on MDN</a></p>\n" }, { "answer_id": 43554849, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 4, "selected": false, "text": "<p>This answer is a summary of this youtube video <a href=\"https://www.youtube.com/watch?v=FYrtnS3X_Lw\" rel=\"noreferrer\">Javascript Closures</a>. So full credits to that video.</p>\n\n<p><em>Closures are nothing but Stateful functions which maintain states of their private variables.</em> </p>\n\n<p>Normally when you make a call to a function as shown in the below figure. The variables are created on a stack ( running RAM memory) used and then disallocated.</p>\n\n<p><a href=\"https://i.stack.imgur.com/QVZg5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QVZg5.png\" alt=\"enter image description here\"></a></p>\n\n<p>But now there are situations where we want to maintain this state of the function thats where Javascript closures comes to use. A closure is a function inside function with a return call as shown in the below code.</p>\n\n<p><a href=\"https://i.stack.imgur.com/u8UIi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/u8UIi.png\" alt=\"enter image description here\"></a></p>\n\n<p>So the closure code for the counter function above looks something as shown below.Its a function inside function with a return statement.</p>\n\n<pre><code>function Counter() {\n var counter = 0;\n\n var Increment = function () {\n counter++;\n alert(counter);\n }\n return {\n Increment\n }\n }\n</code></pre>\n\n<p>So now if you make a call the counter will increment in other words the function call maintains states.</p>\n\n<pre><code>var x = Counter(); // get the reference of the closure\nx.Increment(); // Displays 1\nx.Increment(); // Display 2 ( Maintains the private variables)\n</code></pre>\n\n<p>But now the biggest question whats the use of such stateful function. Stateful functions are building blocks to implement OOP concept like abstraction ,encapsulation and creating self contained modules.</p>\n\n<p>So whatever you want encapsulated you can put it as private and things to be exposed to public should be put in return statement. Also these components are self contained isolated objects so they do not pollute global variables.</p>\n\n<p>A object which follows OOP principles is self contained , follows abstraction , follows encapsulation and so. With out closures in Javascript this is difficult to implement.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tJ5Mm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tJ5Mm.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 43634757, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>A closure is a function having access to the parent scope, even after the parent function has closed.</p>\n</blockquote>\n\n<p>So basically a closure is a function of another function. We can say like a child function.</p>\n\n<blockquote>\n <p>A closure is an inner function that has access to the outer\n (enclosing) function’s variables—scope chain. The closure has three\n scope chains: it has access to its own scope (variables defined\n between its curly brackets), it has access to the outer function’s\n variables, and it has access to the global variables.</p>\n \n <p>The inner function has access not only to the outer function’s\n variables but also to the outer function’s parameters. Note that the\n inner function cannot call the outer function’s arguments object,\n however, even though it can call the outer function’s parameters\n directly.</p>\n \n <p>You create a closure by adding a function inside another function.</p>\n</blockquote>\n\n<p>Also, it's very useful method which is used in many famous frameworks including <code>Angular</code>, <code>Node.js</code> and <code>jQuery</code>:</p>\n\n<blockquote>\n <p>Closures are used extensively in Node.js; they are workhorses in\n Node.js’ asynchronous, non-blocking architecture. Closures are also\n frequently used in jQuery and just about every piece of JavaScript\n code you read.</p>\n</blockquote>\n\n<p>But how the closures look like in a real-life coding?\nLook at this simple sample code:</p>\n\n<pre><code>function showName(firstName, lastName) {\n var nameIntro = \"Your name is \";\n // this inner function has access to the outer function's variables, including the parameter\n function makeFullName() {\n return nameIntro + firstName + \" \" + lastName;\n }\n return makeFullName();\n }\n\n console.log(showName(\"Michael\", \"Jackson\")); // Your name is Michael Jackson\n</code></pre>\n\n<p>Also, this is classic closure way in jQuery which every javascript and jQuery developers used it a lot:</p>\n\n<pre><code>$(function() {\n var selections = [];\n $(\".niners\").click(function() { // this closure has access to the selections variable\n selections.push(this.prop(\"name\")); // update the selections variable in the outer function's scope\n });\n});\n</code></pre>\n\n<p>But why we use closures? when we use it in an actual programming?\nwhat are the practical use of closures? the below is a good explanation and example by MDN:</p>\n\n<p><strong>Practical closures</strong></p>\n\n<blockquote>\n <p>Closures are useful because they let you associate some data (the\n lexical environment) with a function that operates on that data. This\n has obvious parallels to object oriented programming, where objects\n allow us to associate some data (the object's properties) with one or\n more methods.</p>\n \n <p>Consequently, you can use a closure anywhere that you might normally\n use an object with only a single method.</p>\n \n <p>Situations where you might want to do this are particularly common on\n the web. Much of the code we write in front-end JavaScript is\n event-based — we define some behavior, then attach it to an event that\n is triggered by the user (such as a click or a keypress). Our code is\n generally attached as a callback: a single function which is executed\n in response to the event.</p>\n \n <p>For instance, suppose we wish to add some buttons to a page that\n adjust the text size. One way of doing this is to specify the\n font-size of the body element in pixels, then set the size of the\n other elements on the page (such as headers) using the relative em\n unit:</p>\n</blockquote>\n\n<p>Read the code below and run the code to see how closure help us here to easily make separate functions for each sections:</p>\n\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>//javascript\r\nfunction makeSizer(size) {\r\n return function() {\r\n document.body.style.fontSize = size + 'px';\r\n };\r\n}\r\n\r\nvar size12 = makeSizer(12);\r\nvar size14 = makeSizer(14);\r\nvar size16 = makeSizer(16);\r\n\r\ndocument.getElementById('size-12').onclick = size12;\r\ndocument.getElementById('size-14').onclick = size14;\r\ndocument.getElementById('size-16').onclick = size16;</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/*css*/\r\nbody {\r\n font-family: Helvetica, Arial, sans-serif;\r\n font-size: 12px;\r\n}\r\n\r\nh1 {\r\n font-size: 1.5em;\r\n}\r\n\r\nh2 {\r\n font-size: 1.2em;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!--html&gt;&lt;!--&gt;\r\n&lt;p&gt;Some paragraph text&lt;/p&gt;\r\n&lt;h1&gt;some heading 1 text&lt;/h1&gt;\r\n&lt;h2&gt;some heading 2 text&lt;/h2&gt;\r\n\r\n&lt;a href=\"#\" id=\"size-12\"&gt;12&lt;/a&gt;\r\n&lt;a href=\"#\" id=\"size-14\"&gt;14&lt;/a&gt;\r\n&lt;a href=\"#\" id=\"size-16\"&gt;16&lt;/a&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>For further study about closures, I recommend you to visit this page by MDN:\n<a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Closures\" rel=\"noreferrer\">https://developer.mozilla.org/en/docs/Web/JavaScript/Closures</a></p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves? I have seen [the Scheme example](http://en.wikipedia.org/wiki/Scheme_%28programming_language%29) given on Wikipedia, but unfortunately it did not help.
A closure is a pairing of: 1. A function and 2. A reference to that function's outer scope (lexical environment) A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values. Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called. If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain. In the following code, `inner` forms a closure with the lexical environment of the execution context created when `foo` is invoked, *closing over* variable `secret`: ```js function foo() { const secret = Math.trunc(Math.random() * 100) return function inner() { console.log(`The secret number is ${secret}.`) } } const f = foo() // `secret` is not directly accessible from outside `foo` f() // The only way to retrieve `secret`, is to invoke `f` ``` In other words: in JavaScript, functions carry a reference to a private "box of state", to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation. And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++. If JavaScript did not have closures, then more states would have to be passed between functions *explicitly*, making parameter lists longer and code noisier. So, if you want a function to always have access to a private piece of state, you can use a closure. ...and frequently we *do* want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality. In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, `secret` remains available to the function object `inner`, *after* it has been returned from `foo`. Uses of Closures ---------------- Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need. ### Private Instance Variables In the following code, the function `toString` closes over the details of the car. ```js function Car(manufacturer, model, year, color) { return { toString() { return `${manufacturer} ${model} (${year}, ${color})` } } } const car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver') console.log(car.toString()) ``` ### Functional Programming In the following code, the function `inner` closes over both `fn` and `args`. ```js function curry(fn) { const args = [] return function inner(arg) { if(args.length === fn.length) return fn(...args) args.push(arg) return inner } } function add(a, b) { return a + b } const curriedAdd = curry(add) console.log(curriedAdd(2)(3)()) // 5 ``` ### Event-Oriented Programming In the following code, function `onClick` closes over variable `BACKGROUND_COLOR`. ```js const $ = document.querySelector.bind(document) const BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)' function onClick() { $('body').style.background = BACKGROUND_COLOR } $('button').addEventListener('click', onClick) ``` ```html <button>Set background color</button> ``` ### Modularization In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions `tick` and `toString` close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our code. ```js let namespace = {}; (function foo(n) { let numbers = [] function format(n) { return Math.trunc(n) } function tick() { numbers.push(Math.random() * 100) } function toString() { return numbers.map(format) } n.counter = { tick, toString } }(namespace)) const counter = namespace.counter counter.tick() counter.tick() console.log(counter.toString()) ``` Examples -------- ### Example 1 This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables *themselves*. It is as though the stack-frame stays alive in memory even after the outer function exits. ```js function foo() { let x = 42 let inner = () => console.log(x) x = x + 1 return inner } foo()() // logs 43 ``` ### Example 2 In the following code, three methods `log`, `increment`, and `update` all close over the same lexical environment. And every time `createObject` is called, a new execution context (stack frame) is created and a completely new variable `x`, and a new set of functions (`log` etc.) are created, that close over this new variable. ```js function createObject() { let x = 42; return { log() { console.log(x) }, increment() { x++ }, update(value) { x = value } } } const o = createObject() o.increment() o.log() // 43 o.update(5) o.log() // 5 const p = createObject() p.log() // 42 ``` ### Example 3 If you are using variables declared using `var`, be careful you understand which variable you are closing over. Variables declared using `var` are hoisted. This is much less of a problem in modern JavaScript due to the introduction of `let` and `const`. In the following code, each time around the loop, a new function `inner` is created, which closes over `i`. But because `var i` is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of `i` (3) is printed, three times. ```js function foo() { var result = [] for (var i = 0; i < 3; i++) { result.push(function inner() { console.log(i) } ) } return result } const result = foo() // The following will print `3`, three times... for (var i = 0; i < 3; i++) { result[i]() } ``` Final points: ------------- * Whenever a function is declared in JavaScript closure is created. * Returning a `function` from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution. * Whenever you use `eval()` inside a function, a closure is used. The text you `eval` can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using `eval('var foo = …')`. * When you use `new Function(…)` (the [Function constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function. * A closure in JavaScript is like keeping a reference (**NOT** a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain. * A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked. * A new set of local variables is created every time a function is called. Links ----- * Douglas Crockford's simulated [private attributes and private methods](http://www.crockford.com/javascript/private.html) for an object, using closures. * A great explanation of how closures can [cause memory leaks in IE](https://www.codeproject.com/Articles/12231/Memory-Leakage-in-Internet-Explorer-revisited) if you are not careful. * MDN documentation on [JavaScript Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
111,129
<p>I have a table which is referenced by foreign keys on many other tables. In my program if I want to delete one of these rows I need to first search for dependencies and present them to the user - "This object depends on x from table y, z from table q, etc". I also expect the number of tables which have foreign keys to this table to grow considerably over time. </p> <p>Is the information_schema database a good way to do a search for all dependencies? I tried to query it to retrieve a list of all tables which have foreign keys to my table, then iterate over the result and select all entries from each table where the foreign key value matches the value the user is trying to delete. The query I have is as follows:</p> <pre><code>SELECT * FROM `KEY_COLUMN_USAGE` kcu LEFT JOIN TABLE_CONSTRAINTS tc ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME WHERE tc.CONSTRAINT_TYPE='FOREIGN KEY' AND (kcu.REFERENCED_TABLE_SCHEMA='db') AND (kcu.REFERENCED_TABLE_NAME = 'testtable') </code></pre> <p>which works perfectly for determining the tables which I need to search, however it is <em>very</em> slow. The query takes around 1 to 2 seconds at best to execute on my development machine, which will reduce a lot when I run it on my production server, but will still be quite slow.</p> <p>I need to know if it's a bad idea to use information_schema in this way. If not, how I can extract better performance from the query. Is the query I'm using solid or is there a better way to do it? If so, how best should I tackle this problem from a maintainability perspective.</p>
[ { "answer_id": 111146, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 2, "selected": false, "text": "<p>I think this is exactly the sort of thing that INFORMATION_SCHEMA is intended for.</p>\n" }, { "answer_id": 111179, "author": "Pascal T.", "author_id": 19816, "author_profile": "https://Stackoverflow.com/users/19816", "pm_score": 3, "selected": true, "text": "<p>Dvorak is right, INFORMATION_SCHEMA is intended for that.</p>\n\n<p>Concerning your performance concerns, there are several ways you can improve the performance</p>\n\n<ul>\n<li><p>Easy way, but not much improvement will come from it:\nStore the info in a static variable. At least the query will occur only once per page</p></li>\n<li><p>Use persistent caching : The alternative PHP cache can help you (see <a href=\"http://fr3.php.net/manual/en/book.apc.php\" rel=\"nofollow noreferrer\">http://fr3.php.net/manual/en/book.apc.php</a>).\nThe info you'll get from the information schema is a good candidate to store in a persistent cache.</p></li>\n<li><p>Use a ORM library, such as doctrine (<a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">http://www.doctrine-project.org/</a>)\nA look at the file lib/Doctrine/Import/Mysql.php will show that it does exactly what you need, and much more.</p></li>\n</ul>\n" }, { "answer_id": 111214, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "<p>Using INFORMATION_SCHEMA for this is OK on static or administrative systems but is not recommended for a transactional application function as INFORMATION_SCHEMA is probably implemented as views on top of the native system data dictionary.</p>\n\n<p>This would be a fairly inefficient way to do a generic 'D' operation for a CRUD library. Also, on many systems (Oracle comes to mind) the system data dictionary is actually implemented as views on a lower level data structure. This means that the native system data dictionary may also not be suitable for this either. The system data dictionary may also change from version to version.</p>\n\n<p>There should be relatively few instances where a straight 'delete' of a record and all of its children is the right way to go. Doing this as a generic function may get you little practical beneift. Also, if the foreign keys are not present in the database you will get orphaned children lying about as this approach is dependent on the FK's being present to know which children to delete.</p>\n" }, { "answer_id": 1620699, "author": "virtualeyes", "author_id": 185840, "author_profile": "https://Stackoverflow.com/users/185840", "pm_score": 1, "selected": false, "text": "<p>Slows my applications to a crawl, but I need the foreign key constraint data to get everything hooked together properly.</p>\n\n<p>The delays are huge when querying information schema, and make a page that used to load instantly, load in 3-4 seconds.</p>\n\n<p>Well, at least foreign key constraints are available in MySQL 5, that makes for more robust application development, but obviously at a cost.</p>\n\n<p>People have been complaining about this issue since 2006 based on my Google searches, and the problem remains -- must not be an easy fix ;--(</p>\n" }, { "answer_id": 3543907, "author": "miket3", "author_id": 427924, "author_profile": "https://Stackoverflow.com/users/427924", "pm_score": 2, "selected": false, "text": "<p>I was looking into this as well. I want to use the KEY_COLUMN_USAGE for some CRUD. And I noticed that there aren't any keys or indexes available on these tables. That could be the reason for poor performance.</p>\n" }, { "answer_id": 6069057, "author": "Denis de Bernardy", "author_id": 417194, "author_profile": "https://Stackoverflow.com/users/417194", "pm_score": 1, "selected": false, "text": "<p>In case this ever gets found on google, it's also worth noting that the information_schema occasionally differs from what is returned by <code>show create table</code>.</p>\n\n<p>There's a good example of this in this <a href=\"https://dba.stackexchange.com/questions/2817/why-does-mysql-not-have-hash-indices-on-myisam-or-innodb/2818#2818\">DBA Stack Exchange thread</a>. After executing this command:</p>\n\n<pre><code>create table rolando (num int not null, primary key (num) using hash);\n</code></pre>\n\n<p>Check the results:</p>\n\n<pre><code>mysql&gt; show create table rolando\\G\n (...)\n PRIMARY KEY (`num`) USING HASH\n\nmysql&gt; show indexes from rolando;\n(...) | Index_type | (...)\n(...) | BTREE | (...)\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004/" ]
I have a table which is referenced by foreign keys on many other tables. In my program if I want to delete one of these rows I need to first search for dependencies and present them to the user - "This object depends on x from table y, z from table q, etc". I also expect the number of tables which have foreign keys to this table to grow considerably over time. Is the information\_schema database a good way to do a search for all dependencies? I tried to query it to retrieve a list of all tables which have foreign keys to my table, then iterate over the result and select all entries from each table where the foreign key value matches the value the user is trying to delete. The query I have is as follows: ``` SELECT * FROM `KEY_COLUMN_USAGE` kcu LEFT JOIN TABLE_CONSTRAINTS tc ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME WHERE tc.CONSTRAINT_TYPE='FOREIGN KEY' AND (kcu.REFERENCED_TABLE_SCHEMA='db') AND (kcu.REFERENCED_TABLE_NAME = 'testtable') ``` which works perfectly for determining the tables which I need to search, however it is *very* slow. The query takes around 1 to 2 seconds at best to execute on my development machine, which will reduce a lot when I run it on my production server, but will still be quite slow. I need to know if it's a bad idea to use information\_schema in this way. If not, how I can extract better performance from the query. Is the query I'm using solid or is there a better way to do it? If so, how best should I tackle this problem from a maintainability perspective.
Dvorak is right, INFORMATION\_SCHEMA is intended for that. Concerning your performance concerns, there are several ways you can improve the performance * Easy way, but not much improvement will come from it: Store the info in a static variable. At least the query will occur only once per page * Use persistent caching : The alternative PHP cache can help you (see <http://fr3.php.net/manual/en/book.apc.php>). The info you'll get from the information schema is a good candidate to store in a persistent cache. * Use a ORM library, such as doctrine (<http://www.doctrine-project.org/>) A look at the file lib/Doctrine/Import/Mysql.php will show that it does exactly what you need, and much more.
111,135
<p>I write my app in VS 2008 and so use all the fanciful stuffs such as LINQ, object initializers etc. Now can my app run on machines that have only .Net 2.0 runtime, but no .Net 3.5 runtime? .Net 3.5 runtime is a huge download, as all of you might know.</p>
[ { "answer_id": 111143, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": -1, "selected": false, "text": "<p>No, they can not.</p>\n" }, { "answer_id": 111145, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>You can run it on .NET 2.0 if you don't use .NET 3.5 libraries. See <a href=\"http://weblogs.asp.net/scottgu/archive/2007/06/20/vs-2008-multi-targeting-support.aspx\" rel=\"nofollow noreferrer\">Visual Studio multi-targeting support</a> You can use <a href=\"http://www.albahari.com/nutshell/linqbridge.html\" rel=\"nofollow noreferrer\">LinqBridge</a> to use Linq queries on .NET 2.0</p>\n\n<p>For details, see MSVS multi-targeting <a href=\"http://channel9.msdn.com/posts/DanielMoth/Multitargeting-in-Visual-Studio-2008/\" rel=\"nofollow noreferrer\">screencast</a> by Daniel Moth on Channel9.</p>\n" }, { "answer_id": 111149, "author": "Kinlan", "author_id": 1798387, "author_profile": "https://Stackoverflow.com/users/1798387", "pm_score": 0, "selected": false, "text": "<p>In most cases probably not, whilst .Net 3.5 still excute with the .Net 2.0 CLR there are a lot of <em>new</em> libraries and functionality that you are very likely to use such as the code that defines the extension methods that will not be available to your clients that don't have .Net 3.5 installed.</p>\n\n<p>You can use VS2008 to target .Net 2.0. I think it is a property on the Solution element.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Microsoft_.NET#Microsoft_.NET\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Microsoft_.NET#Microsoft_.NET</a> has a lot of information.</p>\n" }, { "answer_id": 111152, "author": "Valery", "author_id": 8468, "author_profile": "https://Stackoverflow.com/users/8468", "pm_score": 0, "selected": false, "text": "<p>You need to install it .Net 3.5 if you want to use its features. </p>\n" }, { "answer_id": 111153, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 4, "selected": true, "text": "<p>What you can use is for example the <em>var</em> keyword, auto-getters and auto-setters, object initializers. I.e. syntactic sugar that is compiled to 2.0 code.</p>\n\n<p>What you can't use is functionality that resides in .Net framework 3.0 and 3.5 library. For example LINQ.</p>\n\n<p>You can try for yourself what you can and can't use by setting target platform in Visual Studio to .Net Framework 2.0. The compiler will complain when you use things from Framework 3.0 and 3.5.</p>\n\n<p>You can use Extension Methods with a little trick: Creating this class to your project</p>\n\n<pre><code>namespace System.Runtime.CompilerServices\n{\n public class ExtensionAttribute : Attribute { }\n}\n</code></pre>\n\n<p>Extension Methods are actually also compiled to 2.0 code, but the compiler needs this class to be defined. Read about it <a href=\"http://www.danielmoth.com/Blog/2007/05/using-extension-methods-in-fx-20.html\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 111159, "author": "BinaryMisfit", "author_id": 146270, "author_profile": "https://Stackoverflow.com/users/146270", "pm_score": 1, "selected": false, "text": "<p>I would recommend looking at <a href=\"http://www.hanselman.com/smallestdotnet/\" rel=\"nofollow noreferrer\" title=\"Smallest DotNet\">Smallest DotNet</a> to find a smaller version of the framework when deploying application for Framework 3.0 and 3.5.</p>\n" }, { "answer_id": 111449, "author": "PoppaVein", "author_id": 14889, "author_profile": "https://Stackoverflow.com/users/14889", "pm_score": 0, "selected": false, "text": "<p>If cost is not a factor, you might consider runtime virtualization software such as VMWare ThinApp or Xenocode Postbuild, both of which allow .NET applications to run without having to install the .NET runtime.</p>\n" }, { "answer_id": 138437, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://evain.net/blog/articles/2008/09/14/c-3-and-linq-on-net-2\" rel=\"nofollow noreferrer\">This article from Jean-Baptiste Evain</a> explains how you can use C# 3.0 and LINQ and targeting machines on which there is only .NET 2.0 runtime installed.</p>\n\n<p>The idea is to use System.Core <a href=\"http://www.mono-project.com/\" rel=\"nofollow noreferrer\">Mono</a> implementation, which is licensed under the MIT/X11 license.</p>\n\n<p><em>Note : This answer was first provided to a <a href=\"https://stackoverflow.com/questions/138393/can-you-run-a-version-3-net-binary-on-a-version-2-clr-install#138426\">duplicated question</a>.</em></p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I write my app in VS 2008 and so use all the fanciful stuffs such as LINQ, object initializers etc. Now can my app run on machines that have only .Net 2.0 runtime, but no .Net 3.5 runtime? .Net 3.5 runtime is a huge download, as all of you might know.
What you can use is for example the *var* keyword, auto-getters and auto-setters, object initializers. I.e. syntactic sugar that is compiled to 2.0 code. What you can't use is functionality that resides in .Net framework 3.0 and 3.5 library. For example LINQ. You can try for yourself what you can and can't use by setting target platform in Visual Studio to .Net Framework 2.0. The compiler will complain when you use things from Framework 3.0 and 3.5. You can use Extension Methods with a little trick: Creating this class to your project ``` namespace System.Runtime.CompilerServices { public class ExtensionAttribute : Attribute { } } ``` Extension Methods are actually also compiled to 2.0 code, but the compiler needs this class to be defined. Read about it [here](http://www.danielmoth.com/Blog/2007/05/using-extension-methods-in-fx-20.html)
111,155
<p>How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?</p>
[ { "answer_id": 111160, "author": "Matt Gregory", "author_id": 10577, "author_profile": "https://Stackoverflow.com/users/10577", "pm_score": 8, "selected": false, "text": "<p>Tkinter supports a mechanism called <a href=\"http://web.archive.org/web/20201111215134/http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols\" rel=\"noreferrer\"><em>protocol handlers</em></a>. Here, the term <em>protocol</em> refers to the interaction between the application and the window manager. The most commonly used protocol is called <code>WM_DELETE_WINDOW</code>, and is used to define what happens when the user explicitly closes a window using the window manager.</p>\n<p>You can use the <code>protocol</code> method to <em>install a handler</em> for this protocol (the widget must be a <code>Tk</code> or <code>Toplevel</code> widget):</p>\n<p>Here you have a concrete example:</p>\n<pre><code>import tkinter as tk\nfrom tkinter import messagebox\n\nroot = tk.Tk()\n\ndef on_closing():\n if messagebox.askokcancel(&quot;Quit&quot;, &quot;Do you want to quit?&quot;):\n root.destroy()\n\nroot.protocol(&quot;WM_DELETE_WINDOW&quot;, on_closing)\nroot.mainloop()\n</code></pre>\n" }, { "answer_id": 14819661, "author": "Honest Abe", "author_id": 1217270, "author_profile": "https://Stackoverflow.com/users/1217270", "pm_score": 5, "selected": false, "text": "<p>Matt has shown one classic modification of the close button.<br />\nThe other is to have the close button minimize the window.<br />\nYou can reproduced this behavior by having the <a href=\"https://wiki.tcl-lang.org/page/wm+iconify\" rel=\"noreferrer\"><em>iconify</em></a> method<br />\nbe the <a href=\"https://www.tcl.tk/man/tcl8.4/TkCmd/wm.htm#M39\" rel=\"noreferrer\"><em>protocol</em></a> method's second argument.</p>\n<p>Here's a working example, tested on Windows 7 &amp; 10:</p>\n<pre><code># Python 3\nimport tkinter\nimport tkinter.scrolledtext as scrolledtext\n\nroot = tkinter.Tk()\n# make the top right close button minimize (iconify) the main window\nroot.protocol(&quot;WM_DELETE_WINDOW&quot;, root.iconify)\n# make Esc exit the program\nroot.bind('&lt;Escape&gt;', lambda e: root.destroy())\n\n# create a menu bar with an Exit command\nmenubar = tkinter.Menu(root)\nfilemenu = tkinter.Menu(menubar, tearoff=0)\nfilemenu.add_command(label=&quot;Exit&quot;, command=root.destroy)\nmenubar.add_cascade(label=&quot;File&quot;, menu=filemenu)\nroot.config(menu=menubar)\n\n# create a Text widget with a Scrollbar attached\ntxt = scrolledtext.ScrolledText(root, undo=True)\ntxt['font'] = ('consolas', '12')\ntxt.pack(expand=True, fill='both')\n\nroot.mainloop()\n</code></pre>\n<p>In this example we give the user two new exit options:<br />\nthe classic File → Exit, and also the <kbd>Esc</kbd> button.</p>\n" }, { "answer_id": 49803010, "author": "Apostolos", "author_id": 5615873, "author_profile": "https://Stackoverflow.com/users/5615873", "pm_score": 4, "selected": false, "text": "<p>Depending on the Tkinter activity, and especially when using Tkinter.after, stopping this activity with <code>destroy()</code> -- even by using protocol(), a button, etc. -- will disturb this activity (\"while executing\" error) rather than just terminate it. The best solution in almost every case is to use a flag. Here is a simple, silly example of how to use it (although I am certain that most of you don't need it! :)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from Tkinter import *\n\ndef close_window():\n global running\n running = False # turn off while loop\n print( \"Window closed\")\n\nroot = Tk()\nroot.protocol(\"WM_DELETE_WINDOW\", close_window)\ncv = Canvas(root, width=200, height=200)\ncv.pack()\n\nrunning = True;\n# This is an endless loop stopped only by setting 'running' to 'False'\nwhile running: \n for i in range(200): \n if not running: \n break\n cv.create_oval(i, i, i+1, i+1)\n root.update() \n</code></pre>\n\n<p>This terminates graphics activity nicely. You only need to check <code>running</code> at the right place(s).</p>\n" }, { "answer_id": 56730063, "author": "SF12 Study", "author_id": 11152082, "author_profile": "https://Stackoverflow.com/users/11152082", "pm_score": 0, "selected": false, "text": "<p>Try The Simple Version:</p>\n\n<pre><code>import tkinter\n\nwindow = Tk()\n\nclosebutton = Button(window, text='X', command=window.destroy)\nclosebutton.pack()\n\nwindow.mainloop()\n\n</code></pre>\n\n<p>Or If You Want To Add More Commands:</p>\n\n<pre><code>import tkinter\n\nwindow = Tk()\n\n\ndef close():\n window.destroy()\n #More Functions\n\n\nclosebutton = Button(window, text='X', command=close)\nclosebutton.pack()\n\nwindow.mainloop()\n</code></pre>\n" }, { "answer_id": 58469034, "author": "Mitch McMabers", "author_id": 8874388, "author_profile": "https://Stackoverflow.com/users/8874388", "pm_score": 3, "selected": false, "text": "<p><em>I'd like to thank the answer by Apostolos for bringing this to my attention. Here's a much more detailed example for Python 3 in the year 2019, with a clearer description and example code.</em></p>\n\n<hr>\n\n<h2>Beware of the fact that <code>destroy()</code> (or not having a custom window closing handler at all) will destroy the window <em>and all of its running callbacks</em> instantly when the user closes it.</h2>\n\n<p>This can be bad for you, depending on your current Tkinter activity, and especially when using <code>tkinter.after</code> (periodic callbacks). You might be using a callback which processes some data and writes to disk... in that case, you obviously want the data writing to finish without being abruptly killed.</p>\n\n<p>The best solution for that is to use a flag. So when the user requests window closing, you mark that as a flag, and then react to it.</p>\n\n<p><em>(Note: I normally design GUIs as nicely encapsulated classes and separate worker threads, and I definitely don't use \"global\" (I use class instance variables instead), but this is meant to be a simple, stripped-down example to demonstrate how Tk abruptly kills your periodic callbacks when the user closes the window...)</em></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from tkinter import *\nimport time\n\n# Try setting this to False and look at the printed numbers (1 to 10)\n# during the work-loop, if you close the window while the periodic_call\n# worker is busy working (printing). It will abruptly end the numbers,\n# and kill the periodic callback! That's why you should design most\n# applications with a safe closing callback as described in this demo.\nsafe_closing = True\n\n# ---------\n\nbusy_processing = False\nclose_requested = False\n\ndef close_window():\n global close_requested\n close_requested = True\n print(\"User requested close at:\", time.time(), \"Was busy processing:\", busy_processing)\n\nroot = Tk()\nif safe_closing:\n root.protocol(\"WM_DELETE_WINDOW\", close_window)\nlbl = Label(root)\nlbl.pack()\n\ndef periodic_call():\n global busy_processing\n\n if not close_requested:\n busy_processing = True\n for i in range(10):\n print((i+1), \"of 10\")\n time.sleep(0.2)\n lbl[\"text\"] = str(time.time()) # Will error if force-closed.\n root.update() # Force redrawing since we change label multiple times in a row.\n busy_processing = False\n root.after(500, periodic_call)\n else:\n print(\"Destroying GUI at:\", time.time())\n try: # \"destroy()\" can throw, so you should wrap it like this.\n root.destroy()\n except:\n # NOTE: In most code, you'll wanna force a close here via\n # \"exit\" if the window failed to destroy. Just ensure that\n # you have no code after your `mainloop()` call (at the\n # bottom of this file), since the exit call will cause the\n # process to terminate immediately without running any more\n # code. Of course, you should NEVER have code after your\n # `mainloop()` call in well-designed code anyway...\n # exit(0)\n pass\n\nroot.after_idle(periodic_call)\nroot.mainloop()\n</code></pre>\n\n<p>This code will show you that the <code>WM_DELETE_WINDOW</code> handler runs even while our custom <code>periodic_call()</code> is busy in the middle of work/loops!</p>\n\n<p>We use some pretty exaggerated <code>.after()</code> values: 500 milliseconds. This is just meant to make it very easy for you to see the difference between closing while the periodic call is busy, or not... If you close while the numbers are updating, you will see that the <code>WM_DELETE_WINDOW</code> happened <em>while</em> your periodic call \"was busy processing: True\". If you close while the numbers are paused (meaning that the periodic callback isn't processing at that moment), you see that the close happened while it's \"not busy\".</p>\n\n<p>In real-world usage, your <code>.after()</code> would use something like 30-100 milliseconds, to have a responsive GUI. This is just a demonstration to help you understand how to protect yourself against Tk's default \"instantly interrupt all work when closing\" behavior.</p>\n\n<p>In summary: Make the <code>WM_DELETE_WINDOW</code> handler set a flag, and then check that flag periodically and manually <code>.destroy()</code> the window when it's safe (when your app is done with all work).</p>\n\n<p>PS: You can also use <code>WM_DELETE_WINDOW</code> to <em>ask</em> the user if they REALLY want to close the window; and if they answer no, you don't set the flag. It's very simple. You just show a messagebox in your <code>WM_DELETE_WINDOW</code> and set the flag based on the user's answer.</p>\n" }, { "answer_id": 64890879, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>i say a lot simpler way would be using the <code>break</code> command, like</p>\n<pre><code>import tkinter as tk\nwin=tk.Tk\ndef exit():\n break\nbtn= tk.Button(win, text=&quot;press to exit&quot;, command=exit)\nwin.mainloop()\n</code></pre>\n<p>OR use <code>sys.exit()</code></p>\n<pre><code>import tkinter as tk\nimport sys\nwin=tk.Tk\ndef exit():\n sys.exit\nbtn= tk.Button(win, text=&quot;press to exit&quot;, command=exit)\nwin.mainloop()\n</code></pre>\n" }, { "answer_id": 65171949, "author": "Nah", "author_id": 13604316, "author_profile": "https://Stackoverflow.com/users/13604316", "pm_score": 4, "selected": false, "text": "<p>If you want to change what the x button does or make it so that you cannot close it at all try this.</p>\n<pre><code>yourwindow.protocol(&quot;WM_DELETE_WINDOW&quot;, whatever)\n</code></pre>\n<p>then defy what &quot;whatever&quot; means</p>\n<pre><code>def whatever():\n # Replace this with your own event for example:\n print(&quot;oi don't press that button&quot;)\n</code></pre>\n<p>You can also make it so that when you close that window you can call it back like this</p>\n<pre><code>yourwindow.withdraw() \n</code></pre>\n<p>This hides the window but does not close it</p>\n<pre><code>yourwindow.deiconify()\n</code></pre>\n<p>This makes the window visible again</p>\n" }, { "answer_id": 65713080, "author": "NISHANT MISHRA", "author_id": 14708788, "author_profile": "https://Stackoverflow.com/users/14708788", "pm_score": 1, "selected": false, "text": "<p>You should use destroy() to close a tkinter window.</p>\n<pre><code> from Tkinter import *\n root = Tk()\n Button(root, text=&quot;Quit&quot;, command=root.destroy).pack()\n root.mainloop()\n</code></pre>\n<p>Explanation:</p>\n<p><code>root.quit()</code>\nThe above line just Bypasses the <code>root.mainloop()</code> i.e <code>root.mainloop()</code> will still be running in background if <code>quit()</code> command is executed.</p>\n<p><code>root.destroy()</code>\nWhile <code>destroy()</code> command vanish out <code>root.mainloop()</code> i.e <code>root.mainloop()</code> stops.</p>\n<p>So as you just want to quit the program so you should use <code>root.destroy()</code> as it will it stop the mainloop()`.</p>\n<p>But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after <code>root.mainloop()</code> line then you should use <code>root.quit()</code>.\nEx:</p>\n<pre><code>from Tkinter import *\ndef quit():\n global root\n root.quit()\n\nroot = Tk()\nwhile True:\n Button(root, text=&quot;Quit&quot;, command=quit).pack()\n root.mainloop()\n #do something\n</code></pre>\n" }, { "answer_id": 69030155, "author": "Yangelixx", "author_id": 15254308, "author_profile": "https://Stackoverflow.com/users/15254308", "pm_score": 1, "selected": false, "text": "<p>The easiest code is:</p>\n<pre><code>from tkinter import *\nwindow = Tk()\n</code></pre>\n<p>For hiding the window : <code>window.withdraw()</code></p>\n<p>For appearing the window : <code>window.deiconify()</code></p>\n<p>For exiting from the window : <code>exit()</code></p>\n<p>For exiting from the window(If you've made a .exe file) :</p>\n<pre><code>from tkinter import *\nimport sys\nwindow = Tk()\nsys.exit()\n</code></pre>\n<p>And of course you have to place a button and use the codes above in a function so you can type the function's name in the command part of the button</p>\n" }, { "answer_id": 71549519, "author": "Sytze", "author_id": 18514044, "author_profile": "https://Stackoverflow.com/users/18514044", "pm_score": 0, "selected": false, "text": "<p>you can use:</p>\n<pre class=\"lang-py prettyprint-override\"><code>root = Tk()\ndef func():\n print('not clossed')\nroot.protocol('wm_delete_window', func)\nroot.mainloop()\n</code></pre>\n" }, { "answer_id": 74022858, "author": "hahaly", "author_id": 20019148, "author_profile": "https://Stackoverflow.com/users/20019148", "pm_score": 0, "selected": false, "text": "<pre><code>def on_closing():\n if messagebox.askokcancel(&quot;Quit&quot;, &quot;would you like to quit&quot;):\n window.destroy()\n\n\nwindow.protocol(&quot;WM_DELETE_WINDOW&quot;, on_closing)\n</code></pre>\n<p>you can handle a window close event like this, if you wanna do something else just change the things that happen in the on_closing() function.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?
Tkinter supports a mechanism called [*protocol handlers*](http://web.archive.org/web/20201111215134/http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols). Here, the term *protocol* refers to the interaction between the application and the window manager. The most commonly used protocol is called `WM_DELETE_WINDOW`, and is used to define what happens when the user explicitly closes a window using the window manager. You can use the `protocol` method to *install a handler* for this protocol (the widget must be a `Tk` or `Toplevel` widget): Here you have a concrete example: ``` import tkinter as tk from tkinter import messagebox root = tk.Tk() def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): root.destroy() root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop() ```
111,194
<p>I have a web app which connects to a server using a TCP connection and reads a binary document which it then writes to its response object. In other words it's transferring a file from a backend server using a custom protocol and returning that file to its client through HTTP.</p> <p>The server sends a status code and a mime type, which I read successfully and then writes the contents of the file and closes the socket. This seems to work fine.</p> <p>The client (a C# web app), reads the data:</p> <pre><code> private NetworkStream stream_; public void WriteDocument(HttpResponse response) { while (stream_.DataAvailable) { const int bufsize = 4 * 1024; byte[] buffer = new byte[bufsize]; int nbytes = stream_.Read(buffer, 0, bufsize); if (nbytes &gt; 0) { if (nbytes &lt; bufsize) Array.Resize&lt;byte&gt;(ref buffer, nbytes); response.BinaryWrite(buffer); } } response.End(); } </code></pre> <p>This seems to always exit the read loop before all the data has arrived. What am I doing wrong?</p>
[ { "answer_id": 111212, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>Here's what I do. Usually the content length is desired to know when to end the data storing loop. If your protocol does not send the amount of data to expect as a header then it should send some marker to signal the end of transmission. </p>\n\n<p>The DataAvailable property just signals if there's data to read from the socket NOW, it doesn't (and cannot) know if there's more data to be sent or not. To check that the socket is still open you can test for stream_.Socket.Connected &amp;&amp; stream_.Socket.Readable</p>\n\n<pre><code> public static byte[] doFetchBinaryUrl(string url)\n {\n BinaryReader rdr;\n HttpWebResponse res;\n try\n {\n res = fetch(url);\n rdr = new BinaryReader(res.GetResponseStream());\n }\n catch (NullReferenceException nre)\n {\n return new byte[] { };\n }\n int len = int.Parse(res.GetResponseHeader(\"Content-Length\"));\n byte[] rv = new byte[len];\n for (int i = 0; i &lt; len - 1; i++)\n {\n rv[i] = rdr.ReadByte();\n }\n res.Close();\n return rv;\n }\n</code></pre>\n" }, { "answer_id": 111221, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": true, "text": "<p>I would use the <code>OutputStream</code> directly with a general-purpose function. With the <code>Stream</code>, you can control <code>Flush</code>.</p>\n\n<pre><code> public void WriteDocument(HttpResponse response) {\n StreamCopy(response.OutputStream, stream_);\n response.End();\n }\n\n public static void StreamCopy(Stream dest, Stream src) {\n byte[] buffer = new byte[4 * 1024];\n int n = 1;\n while (n &gt; 0) {\n n = src.Read(buffer, 0, buffer.Length);\n dest.Write(buffer, 0, n);\n }\n dest.Flush();\n }\n</code></pre>\n" }, { "answer_id": 111332, "author": "m_eiman", "author_id": 18820, "author_profile": "https://Stackoverflow.com/users/18820", "pm_score": 1, "selected": false, "text": "<p>Not sure how things work in .Net, but in most environments I've worked in Read() returns 0 bytes when the connection is closed. So you'd do something like:</p>\n\n<pre>\nchar buffer[4096];\nint num_read;\n\nwhile ( num_read = src.Read(sizeof(buffer)) > 0 )\n{\n dst.Write(buffer, num_read);\n}\n</pre>\n" }, { "answer_id": 249848, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "<p>The root of your problem is this line:</p>\n\n<pre><code>while (stream_.DataAvailable)\n</code></pre>\n\n<p>DataAvailable simply means there's data in the stream buffer ready to be read and processed. It makes no guarantee about the 'end' of the stream having been reached. In particular, DataAvailable can be false if there's any pause in transmission, or if your sender is slower than your reader. </p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
I have a web app which connects to a server using a TCP connection and reads a binary document which it then writes to its response object. In other words it's transferring a file from a backend server using a custom protocol and returning that file to its client through HTTP. The server sends a status code and a mime type, which I read successfully and then writes the contents of the file and closes the socket. This seems to work fine. The client (a C# web app), reads the data: ``` private NetworkStream stream_; public void WriteDocument(HttpResponse response) { while (stream_.DataAvailable) { const int bufsize = 4 * 1024; byte[] buffer = new byte[bufsize]; int nbytes = stream_.Read(buffer, 0, bufsize); if (nbytes > 0) { if (nbytes < bufsize) Array.Resize<byte>(ref buffer, nbytes); response.BinaryWrite(buffer); } } response.End(); } ``` This seems to always exit the read loop before all the data has arrived. What am I doing wrong?
I would use the `OutputStream` directly with a general-purpose function. With the `Stream`, you can control `Flush`. ``` public void WriteDocument(HttpResponse response) { StreamCopy(response.OutputStream, stream_); response.End(); } public static void StreamCopy(Stream dest, Stream src) { byte[] buffer = new byte[4 * 1024]; int n = 1; while (n > 0) { n = src.Read(buffer, 0, buffer.Length); dest.Write(buffer, 0, n); } dest.Flush(); } ```
111,234
<p>Now that it's clear <a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
[ { "answer_id": 111251, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 4, "selected": false, "text": "<p>A Callable is an object that has the <code>__call__</code> method. This means you can fake callable functions or do neat things like <a href=\"http://www.python.org/dev/peps/pep-0309/\" rel=\"noreferrer\">Partial Function Application</a> where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as <a href=\"http://en.wikipedia.org/wiki/Currying\" rel=\"noreferrer\">Currying</a> in functional programming circles).</p>\n\n<p>Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.</p>\n\n<pre><code>[nigel@k9 ~]$ python\nPython 2.5 (r25:51908, Nov 6 2007, 15:55:44) \n[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; 'aaa'() # &lt;== Here we attempt to call a string.\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nTypeError: 'str' object is not callable\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 111252, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 3, "selected": false, "text": "<p>Quite simply, a \"callable\" is something that can be called like a method. The built in function \"callable()\" will tell you whether something appears to be callable, as will checking for a <strong>call</strong> property. Functions are callable as are classes, class instances can be callable. See more about this <a href=\"http://docs.python.org/lib/built-in-funcs.html\" rel=\"noreferrer\">here</a> and <a href=\"http://www.peterbe.com/plog/callable-python-objects\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 111253, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 2, "selected": false, "text": "<p>It's something you can put \"(args)\" after and expect it to work. A callable is usually a method or a class. Methods get called, classes get instantiated.</p>\n" }, { "answer_id": 111255, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 9, "selected": true, "text": "<p>A callable is anything that can be called. </p>\n\n<p>The <a href=\"http://svn.python.org/projects/python/trunk/Objects/object.c\" rel=\"noreferrer\">built-in <em>callable</em> (PyCallable_Check in objects.c)</a> checks if the argument is either:</p>\n\n<ul>\n<li>an instance of a class with a <code>__call__</code> method or</li>\n<li>is of a type that has a non null <em>tp_call</em> (c struct) member which indicates callability otherwise (such as in functions, methods etc.)</li>\n</ul>\n\n<p>The method named <code>__call__</code> is (<a href=\"https://docs.python.org/3/reference/datamodel.html#object.__call__\" rel=\"noreferrer\">according to the documentation</a>)</p>\n\n<blockquote>\n <p>Called when the instance is ''called'' as a function</p>\n</blockquote>\n\n<h2>Example</h2>\n\n<pre><code>class Foo:\n def __call__(self):\n print 'called'\n\nfoo_instance = Foo()\nfoo_instance() #this is calling the __call__ method\n</code></pre>\n" }, { "answer_id": 111267, "author": "MvdD", "author_id": 18044, "author_profile": "https://Stackoverflow.com/users/18044", "pm_score": 3, "selected": false, "text": "<p><code>__call__</code> makes any object be callable as a function.</p>\n\n<p>This example will output 8:</p>\n\n<pre><code>class Adder(object):\n def __init__(self, val):\n self.val = val\n\n def __call__(self, val):\n return self.val + val\n\nfunc = Adder(5)\nprint func(3)\n</code></pre>\n" }, { "answer_id": 111371, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": false, "text": "<p>In Python a callable is an object which type has a <code>__call__</code> method:</p>\n\n<pre><code>&gt;&gt;&gt; class Foo:\n... pass\n... \n&gt;&gt;&gt; class Bar(object):\n... pass\n... \n&gt;&gt;&gt; type(Foo).__call__(Foo)\n&lt;__main__.Foo instance at 0x711440&gt;\n&gt;&gt;&gt; type(Bar).__call__(Bar)\n&lt;__main__.Bar object at 0x712110&gt;\n&gt;&gt;&gt; def foo(bar):\n... return bar\n... \n&gt;&gt;&gt; type(foo).__call__(foo, 42)\n42\n</code></pre>\n\n<p>As simple as that :)</p>\n\n<p>This of course can be overloaded:</p>\n\n<pre><code>&gt;&gt;&gt; class Foo(object):\n... def __call__(self):\n... return 42\n... \n&gt;&gt;&gt; f = Foo()\n&gt;&gt;&gt; f()\n42\n</code></pre>\n" }, { "answer_id": 115349, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": false, "text": "<p>From Python's sources <a href=\"http://svn.python.org/view/python/trunk/Objects/object.c?rev=64962&amp;view=markup\" rel=\"noreferrer\">object.c</a>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>/* Test whether an object can be called */\n\nint\nPyCallable_Check(PyObject *x)\n{\n if (x == NULL)\n return 0;\n if (PyInstance_Check(x)) {\n PyObject *call = PyObject_GetAttrString(x, \"__call__\");\n if (call == NULL) {\n PyErr_Clear();\n return 0;\n }\n /* Could test recursively but don't, for fear of endless\n recursion if some joker sets self.__call__ = self */\n Py_DECREF(call);\n return 1;\n }\n else {\n return x-&gt;ob_type-&gt;tp_call != NULL;\n }\n}\n</code></pre>\n\n<p>It says:</p>\n\n<ol>\n<li>If an object is an instance of some class then it is callable <em>iff</em> it has <code>__call__</code> attribute.</li>\n<li>Else the object <code>x</code> is callable <em>iff</em> <code>x-&gt;ob_type-&gt;tp_call != NULL</code></li>\n</ol>\n\n<p>Desciption of <a href=\"http://docs.python.org/api/type-structs.html\" rel=\"noreferrer\"><code>tp_call</code> field</a>:</p>\n\n<blockquote>\n <p><code>ternaryfunc tp_call</code> An optional\n pointer to a function that implements\n calling the object. This should be\n NULL if the object is not callable.\n The signature is the same as for\n PyObject_Call(). This field is\n inherited by subtypes.</p>\n</blockquote>\n\n<p>You can always use built-in <code>callable</code> function to determine whether given object is callable or not; or better yet just call it and catch <code>TypeError</code> later. <code>callable</code> is removed in Python 3.0 and 3.1, use <code>callable = lambda o: hasattr(o, '__call__')</code> or <code>isinstance(o, collections.Callable)</code>.</p>\n\n<p>Example, a simplistic cache implementation:</p>\n\n<pre><code>class Cached:\n def __init__(self, function):\n self.function = function\n self.cache = {}\n\n def __call__(self, *args):\n try: return self.cache[args]\n except KeyError:\n ret = self.cache[args] = self.function(*args)\n return ret \n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>@Cached\ndef ack(x, y):\n return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1) \n</code></pre>\n\n<p>Example from standard library, file <a href=\"http://svn.python.org/projects/python/trunk/Lib/site.py\" rel=\"noreferrer\"><code>site.py</code></a>, definition of built-in <code>exit()</code> and <code>quit()</code> functions:</p>\n\n<pre><code>class Quitter(object):\n def __init__(self, name):\n self.name = name\n def __repr__(self):\n return 'Use %s() or %s to exit' % (self.name, eof)\n def __call__(self, code=None):\n # Shells like IDLE catch the SystemExit, but listen when their\n # stdin wrapper is closed.\n try:\n sys.stdin.close()\n except:\n pass\n raise SystemExit(code)\n__builtin__.quit = Quitter('quit')\n__builtin__.exit = Quitter('exit')\n</code></pre>\n" }, { "answer_id": 139469, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 5, "selected": false, "text": "<p>A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions.</p>\n\n<p>Every time you define a function python creates a callable object. \nIn example, you could define the function <strong>func</strong> in these ways (it's the same):</p>\n\n<pre><code>class a(object):\n def __call__(self, *args):\n print 'Hello'\n\nfunc = a()\n\n# or ... \ndef func(*args):\n print 'Hello'\n</code></pre>\n\n<p>You could use this method instead of methods like <strong>doit</strong> or <strong>run</strong>, I think it's just more clear to see obj() than obj.doit()</p>\n" }, { "answer_id": 10489545, "author": "cobie", "author_id": 634135, "author_profile": "https://Stackoverflow.com/users/634135", "pm_score": 2, "selected": false, "text": "<p>callables implement the <code>__call__</code> special method so any object with such a method is callable.</p>\n" }, { "answer_id": 15581536, "author": "hcalves", "author_id": 128942, "author_profile": "https://Stackoverflow.com/users/128942", "pm_score": 5, "selected": false, "text": "<p>Let me explain backwards:</p>\n\n<p>Consider this...</p>\n\n<pre><code>foo()\n</code></pre>\n\n<p>... as syntactic sugar for:</p>\n\n<pre><code>foo.__call__()\n</code></pre>\n\n<p>Where <code>foo</code> can be any object that responds to <code>__call__</code>. When I say any object, I mean it: built-in types, your own classes and their instances.</p>\n\n<p>In the case of built-in types, when you write:</p>\n\n<pre><code>int('10')\nunicode(10)\n</code></pre>\n\n<p>You're essentially doing:</p>\n\n<pre><code>int.__call__('10')\nunicode.__call__(10)\n</code></pre>\n\n<p>That's also why you don't have <code>foo = new int</code> in Python: you just make the class object return an instance of it on <code>__call__</code>. The way Python solves this is very elegant in my opinion.</p>\n" }, { "answer_id": 39591208, "author": "Ravi Singh", "author_id": 6733259, "author_profile": "https://Stackoverflow.com/users/6733259", "pm_score": 2, "selected": false, "text": "<p>To check function or method of class is callable or not that means we can call that function.</p>\n\n<pre><code>Class A:\n def __init__(self,val):\n self.val = val\n def bar(self):\n print \"bar\"\n\nobj = A() \ncallable(obj.bar)\nTrue\ncallable(obj.__init___)\nFalse\ndef foo(): return \"s\"\ncallable(foo)\nTrue\ncallable(foo())\nFalse\n</code></pre>\n" }, { "answer_id": 43271804, "author": "maris", "author_id": 3853452, "author_profile": "https://Stackoverflow.com/users/3853452", "pm_score": 0, "selected": false, "text": "<p>Callable is a type or class of &quot;Build-in function or Method&quot; with a method\n<strong>call</strong></p>\n<pre><code>&gt;&gt;&gt; type(callable)\n&lt;class 'builtin_function_or_method'&gt;\n&gt;&gt;&gt;\n</code></pre>\n<p>Example:\n<strong>print</strong> is a callable object. With a build-in function <strong><strong>call</strong></strong>\nWhen you invoke the <strong>print</strong> function, Python creates an <strong>object of type print</strong> and invokes its method <strong><strong>call</strong></strong> passing the parameters if any.</p>\n<pre><code>&gt;&gt;&gt; type(print)\n&lt;class 'builtin_function_or_method'&gt;\n&gt;&gt;&gt; print.__call__(10)\n10\n&gt;&gt;&gt; print(10)\n10\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 74549262, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 0, "selected": false, "text": "<p>A class, function, method and object which has <code>__call__()</code> are <strong>callable</strong>.</p>\n<p>You can check if callable with <a href=\"https://docs.python.org/3/library/functions.html#callable\" rel=\"nofollow noreferrer\"><strong>callable()</strong></a> which returns <code>True</code> if callable and returns <code>False</code> if not callable as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Class1:\n def __call__(self):\n print(&quot;__call__&quot;)\n\nclass Class2:\n pass\n\ndef func():\n pass\n\nprint(callable(Class1)) # Class1\nprint(callable(Class2)) # Class2\n\nprint(callable(Class1())) # Class1 object\nprint(callable(Class2())) # Class2 object\n\nprint(callable(func)) # func\n</code></pre>\n<p>Then, only <strong><code>Class2</code> object</strong> which doesn't have <code>__call__()</code> is not callable returning <code>False</code> as shown below:</p>\n<pre class=\"lang-none prettyprint-override\"><code>True # Class1\nTrue # Class2\nTrue # Class1 object\nFalse # Class2 object\nTrue # func\n</code></pre>\n<p>In addition, all of them below are not callable returning <code>False</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(callable(&quot;Hello&quot;)) # &quot;str&quot; type\nprint(callable(100)) # &quot;int&quot; type\nprint(callable(100.23)) # &quot;float&quot; type\nprint(callable(100 + 2j)) # &quot;complex&quot; type\nprint(callable(True)) # &quot;bool&quot; type\nprint(callable(None)) # &quot;NoneType&quot;\nprint(callable([])) # &quot;list&quot; type\nprint(callable(())) # &quot;tuple&quot; type\nprint(callable({})) # &quot;dict&quot; type\nprint(callable({&quot;&quot;})) # &quot;set&quot; type\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>False # &quot;str&quot; type\nFalse # &quot;int&quot; type\nFalse # &quot;float&quot; type\nFalse # &quot;complex&quot; type\nFalse # &quot;bool&quot; type\nFalse # &quot;NoneType&quot;\nFalse # &quot;list&quot; type\nFalse # &quot;tuple&quot; type\nFalse # &quot;dict&quot; type\nFalse # &quot;set&quot; type\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
Now that it's clear [what a metaclass is](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means. I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using `__init__` and `__new__` lead to wonder what this bloody `__call__` can be used for. Could you give me some explanations, including examples with the magic method ?
A callable is anything that can be called. The [built-in *callable* (PyCallable\_Check in objects.c)](http://svn.python.org/projects/python/trunk/Objects/object.c) checks if the argument is either: * an instance of a class with a `__call__` method or * is of a type that has a non null *tp\_call* (c struct) member which indicates callability otherwise (such as in functions, methods etc.) The method named `__call__` is ([according to the documentation](https://docs.python.org/3/reference/datamodel.html#object.__call__)) > > Called when the instance is ''called'' as a function > > > Example ------- ``` class Foo: def __call__(self): print 'called' foo_instance = Foo() foo_instance() #this is calling the __call__ method ```
111,281
<ul> <li>VMware server 1.0.7 installed with vmware-package</li> <li>Debian GNU/Linux testing (lenny)</li> <li>Kernel 2.6.26-1-686</li> </ul> <p>There were several compile problems when trying to build the binary kernel modules from the vmware-server-kernel-source package made by vmware-package from the VMware server tarball. Recently VMware has updated their kernel module sources so as to make them compatible with kernel 2.6.25, but they broke again with 2.6.26.</p> <pre><code>vmmon-only/linux/driver.c:146: error: unknown field 'nopage' specified in initializer vmmon-only/linux/driver.c:147: warning: initialization from incompatible pointer type vmmon-only/linux/driver.c:150: error: unknown field 'nopage' specified in initializer vmmon-only/linux/driver.c:151: warning: initialization from incompatible pointer type </code></pre> <p>That's only the first error, but there are other compile problems (in vmnet-only).</p> <p>Many advice on forums are to use vmware-any-any instead, but that has its own problems (see <a href="https://stackoverflow.com/questions/109877/unknown-ioctl-2062-2065-2066-from-vmmon-when-starting-a-vm-vmware-server-107-fo">my other question</a>).</p> <p>As you can see from my own answer below, I've solved the problem by fixing the incompatiblities, and came up with a <a href="http://pastebin.com/f200c4eb0" rel="nofollow noreferrer">patch</a>. Now I'd like VMware to include it in future releases, to save me and others trouble of applying it by hand after every VMware or kernel upgrade. Question: where/how do I submit such fixes to VMware?</p>
[ { "answer_id": 111309, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 0, "selected": false, "text": "<p>Did you try searching the <a href=\"http://www.vmware.com/support/\" rel=\"nofollow noreferrer\">VMware support website</a>? This has been <a href=\"http://kb.vmware.com/selfservice/search.do?cmd=displayKC&amp;docType=kc&amp;externalId=150-150690xml4\" rel=\"nofollow noreferrer\">asked in the VMware forums</a>.</p>\n" }, { "answer_id": 111343, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 2, "selected": false, "text": "<p>I've bludgeoned the kernel module into working with the 2.6.26 kernel. Here is <a href=\"http://pastebin.com/f200c4eb0\" rel=\"nofollow noreferrer\">my patch</a>.</p>\n" }, { "answer_id": 118896, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 0, "selected": false, "text": "<p>Perhaps <a href=\"http://open-vm-tools.sourceforge.net/contribute.php\" rel=\"nofollow noreferrer\">http://open-vm-tools.sourceforge.net/contribute.php</a> ?</p>\n" }, { "answer_id": 151123, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 1, "selected": true, "text": "<p>I wrote a support request to VMware, and they assured me that my patch will reach the VMware server team.</p>\n" }, { "answer_id": 306886, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks for this great effort..</p>\n\n<p>I've used it to get VMWare Server 1.08 running on OpenFiler. The vmware-any-any patch was also suggested but I couldn't start a guest VM because of the 'not enough physical memory' error.</p>\n\n<p>Now my vm's are running happily again :)</p>\n" }, { "answer_id": 561797, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks a lot Alexey!\nThis sorted stuff out for myself and a colleague of mine.</p>\n\n<p>Had the same issue as Bruce with the any-any patch.</p>\n\n<p>One thing, I noticed that the patch was missing the @@'s at the beginning.. I've done a new pastebin that has them in it (curse their highlighting thing!)</p>\n\n<p>It's here: <a href=\"http://pastebin.com/f2ea13d45\" rel=\"nofollow noreferrer\">http://pastebin.com/f2ea13d45</a></p>\n\n<p>Thanks,\nChris</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10682/" ]
* VMware server 1.0.7 installed with vmware-package * Debian GNU/Linux testing (lenny) * Kernel 2.6.26-1-686 There were several compile problems when trying to build the binary kernel modules from the vmware-server-kernel-source package made by vmware-package from the VMware server tarball. Recently VMware has updated their kernel module sources so as to make them compatible with kernel 2.6.25, but they broke again with 2.6.26. ``` vmmon-only/linux/driver.c:146: error: unknown field 'nopage' specified in initializer vmmon-only/linux/driver.c:147: warning: initialization from incompatible pointer type vmmon-only/linux/driver.c:150: error: unknown field 'nopage' specified in initializer vmmon-only/linux/driver.c:151: warning: initialization from incompatible pointer type ``` That's only the first error, but there are other compile problems (in vmnet-only). Many advice on forums are to use vmware-any-any instead, but that has its own problems (see [my other question](https://stackoverflow.com/questions/109877/unknown-ioctl-2062-2065-2066-from-vmmon-when-starting-a-vm-vmware-server-107-fo)). As you can see from my own answer below, I've solved the problem by fixing the incompatiblities, and came up with a [patch](http://pastebin.com/f200c4eb0). Now I'd like VMware to include it in future releases, to save me and others trouble of applying it by hand after every VMware or kernel upgrade. Question: where/how do I submit such fixes to VMware?
I wrote a support request to VMware, and they assured me that my patch will reach the VMware server team.
111,282
<p>I'm modifying some code in which the original author built a web page by using an array thusly:</p> <pre><code> $output[]=$stuff_from_database; $output[]='more stuff'; // etc echo join('',$output); </code></pre> <p>Can anyone think of a reason why this would be preferable (or vice versa) to:</p> <pre><code> $output =$stuff_from_database; $output .='more stuff'; // etc echo $output; </code></pre>
[ { "answer_id": 111289, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 0, "selected": false, "text": "<p>The bottom will reallocate the $output string repeatedly, whereas I believe the top will just store each piece in an array, and then join them all at the end. The original example may end up being faster as a result. If this isn't performance sensitive, then I would probably append, not join.</p>\n" }, { "answer_id": 111310, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>It was probably written by someone who comes from a language where strings are immutable and thus concatenation is expensive. PHP is not one of them as the following tests show. So the second approach is performance wise, better. The only other reason that I can think of to use the first approach is to be able to replace some part of the array with another, but that means to keep track of the indexes, which is not specified.</p>\n\n<pre><code>~$ cat join.php\n&lt;?php\n\nfor ($i=0;$i&lt;50000;$i++) {\n$output[] = \"HI $i\\n\";\n}\n\necho join('',$output);\n?&gt;\n\n\n~$ time for i in `seq 100`; do php join.php &gt;&gt; outjoin ; done\n\nreal 0m19.145s\nuser 0m12.045s\nsys 0m3.216s\n\n~$ cat dot.php\n&lt;?php\n\nfor ($i=0;$i&lt;50000;$i++) {\n$output.= \"HI $i\\n\";\n}\n\necho $output;\n?&gt;\n\n\n~$ time for i in `seq 100`; do php dot.php &gt;&gt; outdot ; done\n\nreal 0m15.530s\nuser 0m8.985s\nsys 0m2.260s\n</code></pre>\n" }, { "answer_id": 111325, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "<p>If joined with <code>implode()</code> or <code>join()</code>, PHP is able to better optimize that. It goes through all strings in your list, calculates the length and allocates the required space and fills the space. In comparison with the \".=\" it has to constantly <code>free()</code> and <code>malloc()</code> the space for the string.</p>\n" }, { "answer_id": 111342, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p><b>&lt;<b></b>!-- Redacted Previous Comment --></b></p>\n\n<p>It would appear I had an error in my code so i was doing a no-op and forgot to check.</p>\n\n<p>It would appear Contary to previous testing, and reading previous blogs on the topic, \nthe following conclusions are actually ( tested ) <strong>untrue</strong> at least for all variants of the above code I can permute. </p>\n\n<ol>\n<li><strong>UNTRUE</strong>: String interpolation is slower than string concatenation. (!) </li>\n<li><strong>UNTRUE</strong>: SprintF is fastest.</li>\n</ol>\n\n<p>In actual tests, Sprintf was the <em>slowest</em> and interpolation was <em>fastest</em> </p>\n\n<pre>\nPHP 5.2.6-pl7-gentoo (cli) (built: Sep 21 2008 13:43:03) \nCopyright (c) 1997-2008 The PHP Group\nZend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies\n with Xdebug v2.0.3, Copyright (c) 2002-2007, by Derick Rethans\n</pre>\n\n<p>It may be conditional to my setup, but its still odd. :/</p>\n" }, { "answer_id": 111624, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 2, "selected": false, "text": "<p>This is a little off topic, but </p>\n\n<pre><code>$output =$stuff_from_database;\n$output .='more stuff';\n// etc\necho $output;\n</code></pre>\n\n<p>Is far slower than:</p>\n\n<pre><code>echo = $stuff_from_database;\necho 'more stuff';\n</code></pre>\n\n<p>In fact, the fastest way to build a string in PHP is:</p>\n\n<pre><code>ob_start();\necho = $stuff_from_database;\necho 'more stuff';\n$output = ob_get_contents();\nob_end_clean();\n</code></pre>\n\n<p>Due to the way that output buffers work and such, it is the fastest way to build a string. Obviously you would only do this if you really need to optimize sting building as it is ugly and doesn't lead to easy reading of the code. And everyone one knows that \"Premature optimization is the root of all evil\".</p>\n" }, { "answer_id": 113898, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 2, "selected": false, "text": "<p>Again, a little bit off topic (not very far), but if you were aiming to put something between the array items being output, then if there was only a few lines to concatenate, join(', ', $output) would do it easily and quickly enough. This would be easier to write, and avoids having to check for the end of the list (where you would not want a trailing ',').</p>\n\n<p>For programmer time, as it is on the order of 1000's of times more expensive than a cpu cycle, I'd usually just throw it into a join if it wasn't going to be run 10,0000+ times per second.</p>\n\n<p>Post-coding micro-optimisation like this is very rarely worth it in terms of time taken vs cpu time saved.</p>\n" }, { "answer_id": 115145, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 1, "selected": false, "text": "<p>I think the fastest way to do it is with echoes. It's not as pretty and probably not enough faster to be worth the cost in readability.</p>\n\n<pre><code>echo $stuff_from_database\n , 'more stuff'\n , 'yet more'\n // etc\n , 'last stuff';\n</code></pre>\n" }, { "answer_id": 124992, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This part of the code is not performance sensitive; it is used to format and display a user's shopping cart info on a low-traffic website. Also, the array (or string) is built from scratch each time and there is no need to address or search for specific elements. It sounds like the array is somewhat more efficient, but I guess it doesn't matter either way for this use. Thanks for all of the info!</p>\n" }, { "answer_id": 125004, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 0, "selected": false, "text": "<p>If you're generating a list (e.g. a shopping cart), you should have some code that generates the HTML from each entry fetched from the database.</p>\n\n<pre><code>for ($prod in $cart)\n{\n $prod-&gt;printHTML();\n}\n</code></pre>\n\n<p>Or something like that. That way, the code becomes a lot cleaner. Of course, this assumes that you've got nice code with objects, rather than a whole moronic mess like my company does (and is replacing).</p>\n" }, { "answer_id": 791863, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<p>It has already been said, but I think a distinct answer will help.</p>\n\n<p>The original programmer wrote it that way because he thought it was faster. In fact, under PHP 4, it really was faster, especially for large strings.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm modifying some code in which the original author built a web page by using an array thusly: ``` $output[]=$stuff_from_database; $output[]='more stuff'; // etc echo join('',$output); ``` Can anyone think of a reason why this would be preferable (or vice versa) to: ``` $output =$stuff_from_database; $output .='more stuff'; // etc echo $output; ```
It was probably written by someone who comes from a language where strings are immutable and thus concatenation is expensive. PHP is not one of them as the following tests show. So the second approach is performance wise, better. The only other reason that I can think of to use the first approach is to be able to replace some part of the array with another, but that means to keep track of the indexes, which is not specified. ``` ~$ cat join.php <?php for ($i=0;$i<50000;$i++) { $output[] = "HI $i\n"; } echo join('',$output); ?> ~$ time for i in `seq 100`; do php join.php >> outjoin ; done real 0m19.145s user 0m12.045s sys 0m3.216s ~$ cat dot.php <?php for ($i=0;$i<50000;$i++) { $output.= "HI $i\n"; } echo $output; ?> ~$ time for i in `seq 100`; do php dot.php >> outdot ; done real 0m15.530s user 0m8.985s sys 0m2.260s ```
111,287
<p>Is it possible to put the results from more than one query on more than one table into a TClientDataset?</p> <p>Just something like</p> <pre><code>SELECT * from t1; SELECT * from t2; SELECT * from t3; </code></pre> <p>I can't seem to figure out a way to get a data provider (SetProvider) to pull in results from more than one table at a time.</p>
[ { "answer_id": 111305, "author": "Chris Woodruff", "author_id": 7001, "author_profile": "https://Stackoverflow.com/users/7001", "pm_score": 1, "selected": true, "text": "<p>There is not a way to have multiple table data in the same TClientDataSet like you referenced. The TClientDataSet holds a single cursor for a single dataset.</p>\n" }, { "answer_id": 111324, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "<p>The only way would be to join the tables. But then you have to provide the criteria of the join through joined foreign keys.</p>\n\n<pre><code>select * from t1, t2, t3 where t1.key = t2.key and t2.key = t3.key;\n</code></pre>\n\n<p>Now suppose you came up with a key (like LineNr) that would allow for such a join. You then could use a full outer join to include all records (important if not all tables have the same number of rows). But this would somehow be a hack. Be sure not to take auto_number for the key, as it does not reuse keys and therefore tends to leave holes in the numbering, resulting in many lines that are only partially filled with values.</p>\n\n<p>If you want to populate a clientdataset from multiple tables that have the same set of fields, you can use the UNION operator to do so. This will just use the same columns and combine all rows into one table.</p>\n" }, { "answer_id": 112219, "author": "Nick Hodges", "author_id": 2044, "author_profile": "https://Stackoverflow.com/users/2044", "pm_score": 4, "selected": false, "text": "<p><code>ClientDatasets</code> can contain fields that are themselves other datasets. So if you want to create three tables in a single dataset, create three <code>ClientDatasets</code> holding the three result sets that you want, and then you can put them into a single <code>ClientDataSet</code>.</p>\n\n<p>This article:</p>\n\n<p><a href=\"http://dn.codegear.com/article/29001\" rel=\"nofollow noreferrer\">http://dn.codegear.com/article/29001</a></p>\n\n<p>shows you how to do it both at runtime and at designtime. Pay particular attention to the section entitled:</p>\n\n<p>\"Creating a <code>ClientDataSet's</code> Structure at Runtime using <code>TFields</code>\"</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19658/" ]
Is it possible to put the results from more than one query on more than one table into a TClientDataset? Just something like ``` SELECT * from t1; SELECT * from t2; SELECT * from t3; ``` I can't seem to figure out a way to get a data provider (SetProvider) to pull in results from more than one table at a time.
There is not a way to have multiple table data in the same TClientDataSet like you referenced. The TClientDataSet holds a single cursor for a single dataset.
111,341
<p>I've got two tables:</p> <pre><code>TableA ------ ID, Name TableB ------ ID, SomeColumn, TableA_ID (FK for TableA) </code></pre> <p>The relationship is one row of <code>TableA</code> - many of <code>TableB</code>.</p> <p>Now, I want to see a result like this:</p> <pre><code>ID Name SomeColumn 1. ABC X, Y, Z (these are three different rows) 2. MNO R, S </code></pre> <p>This won't work (multiple results in a subquery):</p> <pre><code>SELECT ID, Name, (SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID) FROM TableA </code></pre> <p>This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of <code>TableA</code>. </p> <p>Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of <code>TableA</code>. </p> <p>I'm not sure if a UDF, utilizing COALESCE or something similar might work?</p>
[ { "answer_id": 111347, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": false, "text": "<p>I think you are on the right track with COALESCE. See here for an example of building a comma-delimited string:</p>\n\n<p><a href=\"http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string\" rel=\"noreferrer\">http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string</a></p>\n" }, { "answer_id": 111356, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 0, "selected": false, "text": "<p>You may need to provide some more details for a more precise response.</p>\n\n<p>Since your dataset seems kind of narrow, you might consider just using a row per result and performing the post-processing at the client. </p>\n\n<p>So if you are really looking to make the server do the work return a result set like </p>\n\n<pre><code>ID Name SomeColumn\n1 ABC X\n1 ABC Y\n1 ABC Z\n2 MNO R\n2 MNO S\n</code></pre>\n\n<p>which of course is a simple INNER JOIN on ID</p>\n\n<p>Once you have the resultset back at the client, maintain a variable called CurrentName and use that as a trigger when to stop collecting SomeColumn into the useful thing you want it to do.</p>\n" }, { "answer_id": 111360, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 4, "selected": false, "text": "<p>In MySQL there is a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat\" rel=\"noreferrer\">group_concat</a> function that will return what you're asking for.</p>\n\n<pre><code>SELECT TableA.ID, TableA.Name, group_concat(TableB.SomeColumn) \nas SomColumnGroup FROM TableA LEFT JOIN TableB ON \nTableB.TableA_ID = TableA.ID\n</code></pre>\n" }, { "answer_id": 111382, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>Assuming you only have WHERE clauses on table A create a stored procedure thus:</p>\n\n<pre><code>SELECT Id, Name From tableA WHERE ...\n\nSELECT tableA.Id AS ParentId, Somecolumn \nFROM tableA INNER JOIN tableB on TableA.Id = TableB.F_Id \nWHERE ...\n</code></pre>\n\n<p>Then fill a DataSet ds with it. Then</p>\n\n<pre><code>ds.Relations.Add(\"foo\", ds.Tables[0].Columns(\"Id\"), ds.Tables[1].Columns(\"ParentId\"));\n</code></pre>\n\n<p>Finally you can add a repeater in the page that puts the commas for every line</p>\n\n<pre><code> &lt;asp:DataList ID=\"Subcategories\" DataKeyField=\"ParentCatId\" \nDataSource='&lt;%# Container.DataItem.CreateChildView(\"foo\") %&gt;' RepeatColumns=\"1\"\n RepeatDirection=\"Horizontal\" ItemStyle-HorizontalAlign=\"left\" ItemStyle-VerticalAlign=\"top\" \nrunat=\"server\" &gt;\n</code></pre>\n\n<p>In this way you will do it client side but with only one query, passing minimal data between database and frontend</p>\n" }, { "answer_id": 111413, "author": "Donnie Thomas", "author_id": 6939, "author_profile": "https://Stackoverflow.com/users/6939", "pm_score": 7, "selected": true, "text": "<h3>1. Create the UDF:</h3>\n\n<pre><code>CREATE FUNCTION CombineValues\n(\n @FK_ID INT -- The foreign key from TableA which is used \n -- to fetch corresponding records\n)\nRETURNS VARCHAR(8000)\nAS\nBEGIN\nDECLARE @SomeColumnList VARCHAR(8000);\n\nSELECT @SomeColumnList =\n COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) \nFROM TableB C\nWHERE C.FK_ID = @FK_ID;\n\nRETURN \n(\n SELECT @SomeColumnList\n)\nEND\n</code></pre>\n\n<h3>2. Use in subquery:</h3>\n\n<pre><code>SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA\n</code></pre>\n\n<h3>3. If you are using stored procedure you can do like this:</h3>\n\n<pre><code>CREATE PROCEDURE GetCombinedValues\n @FK_ID int\nAs\nBEGIN\nDECLARE @SomeColumnList VARCHAR(800)\nSELECT @SomeColumnList =\n COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) \nFROM TableB\nWHERE FK_ID = @FK_ID \n\nSelect *, @SomeColumnList as SelectedIds\n FROM \n TableA\n WHERE \n FK_ID = @FK_ID \nEND\n</code></pre>\n" }, { "answer_id": 1939718, "author": "ravi", "author_id": 235972, "author_profile": "https://Stackoverflow.com/users/235972", "pm_score": -1, "selected": false, "text": "<p>Solution below:</p>\n\n<pre><code>SELECT GROUP_CONCAT(field_attr_best_weekday_value)as RAVI\nFROM content_field_attr_best_weekday LEFT JOIN content_type_attraction\n on content_field_attr_best_weekday.nid = content_type_attraction.nid\nGROUP BY content_field_attr_best_weekday.nid\n</code></pre>\n\n<p>Use this, you also can change the Joins</p>\n" }, { "answer_id": 1940311, "author": "priyanka.sarkar", "author_id": 111663, "author_profile": "https://Stackoverflow.com/users/111663", "pm_score": 7, "selected": false, "text": "<p>Even this will serve the purpose</p>\n\n<p><strong>Sample data</strong></p>\n\n<pre><code>declare @t table(id int, name varchar(20),somecolumn varchar(MAX))\ninsert into @t\n select 1,'ABC','X' union all\n select 1,'ABC','Y' union all\n select 1,'ABC','Z' union all\n select 2,'MNO','R' union all\n select 2,'MNO','S'\n</code></pre>\n\n<p><strong>Query:</strong></p>\n\n<pre><code>SELECT ID,Name,\n STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))\n FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name\n FOR XML PATH('')),1,1,'') SOMECOLUMN\nFROM @T T1\nGROUP BY id,Name\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>ID Name SomeColumn\n1 ABC X,Y,Z\n2 MNO R,S\n</code></pre>\n" }, { "answer_id": 9277260, "author": "rsda", "author_id": 1209113, "author_profile": "https://Stackoverflow.com/users/1209113", "pm_score": -1, "selected": false, "text": "<p>I have reviewed all the answers. I think in database insertion should be like:</p>\n\n<pre><code>ID Name SomeColumn\n1. ABC ,X,Y Z (these are three different rows)\n2. MNO ,R,S\n</code></pre>\n\n<p>The comma should be at previous end and do searching by like <code>%,X,%</code></p>\n" }, { "answer_id": 10400760, "author": "ATHAR", "author_id": 1368148, "author_profile": "https://Stackoverflow.com/users/1368148", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT t.ID, \n t.NAME, \n (SELECT t1.SOMECOLUMN \n FROM TABLEB t1 \n WHERE t1.F_ID = T.TABLEA.ID) \nFROM TABLEA t; \n</code></pre>\n\n<p>This will work for selecting from different table using sub query.</p>\n" }, { "answer_id": 38003777, "author": "mrogunlana", "author_id": 3816706, "author_profile": "https://Stackoverflow.com/users/3816706", "pm_score": 0, "selected": false, "text": "<p>I tried the solution priyanka.sarkar mentioned and the didn't quite get it working as the OP asked. Here's the solution I ended up with:</p>\n\n<pre><code>SELECT ID, \n SUBSTRING((\n SELECT ',' + T2.SomeColumn\n FROM @T T2 \n WHERE WHERE T1.id = T2.id\n FOR XML PATH('')), 2, 1000000)\n FROM @T T1\nGROUP BY ID\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6939/" ]
I've got two tables: ``` TableA ------ ID, Name TableB ------ ID, SomeColumn, TableA_ID (FK for TableA) ``` The relationship is one row of `TableA` - many of `TableB`. Now, I want to see a result like this: ``` ID Name SomeColumn 1. ABC X, Y, Z (these are three different rows) 2. MNO R, S ``` This won't work (multiple results in a subquery): ``` SELECT ID, Name, (SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID) FROM TableA ``` This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of `TableA`. Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of `TableA`. I'm not sure if a UDF, utilizing COALESCE or something similar might work?
### 1. Create the UDF: ``` CREATE FUNCTION CombineValues ( @FK_ID INT -- The foreign key from TableA which is used -- to fetch corresponding records ) RETURNS VARCHAR(8000) AS BEGIN DECLARE @SomeColumnList VARCHAR(8000); SELECT @SomeColumnList = COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) FROM TableB C WHERE C.FK_ID = @FK_ID; RETURN ( SELECT @SomeColumnList ) END ``` ### 2. Use in subquery: ``` SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA ``` ### 3. If you are using stored procedure you can do like this: ``` CREATE PROCEDURE GetCombinedValues @FK_ID int As BEGIN DECLARE @SomeColumnList VARCHAR(800) SELECT @SomeColumnList = COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) FROM TableB WHERE FK_ID = @FK_ID Select *, @SomeColumnList as SelectedIds FROM TableA WHERE FK_ID = @FK_ID END ```
111,345
<p>Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want):</p> <pre><code>using System; using System.Drawing; namespace Test { class Program { static void Main(string[] args) { Image img = new Bitmap("test.png"); System.Console.WriteLine(img.Width + " x " + img.Height); } } } </code></pre>
[ { "answer_id": 111349, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 4, "selected": false, "text": "<p>Have you tried using the WPF Imaging classes? <code>System.Windows.Media.Imaging.BitmapDecoder</code>, etc.?</p>\n\n<p>I believe some effort was into making sure those codecs only read a subset of the file in order to determine header information. It's worth a check.</p>\n" }, { "answer_id": 111383, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": -1, "selected": false, "text": "<p>It's going to depend on the file format. Usually they will state it up in the early bytes of the file. And, usually, a good image-reading implementation will take that into account. I can't point you to one for .NET though.</p>\n" }, { "answer_id": 111762, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>Yes, you can absolutely do this and the code depends on the file format. I work for an imaging vendor (<a href=\"http://www.atalasoft.com\" rel=\"nofollow noreferrer\">Atalasoft</a>), and our product provides a GetImageInfo() for every codec that does the minimum to find out dimensions and some other easy to get data.</p>\n\n<p>If you want to roll your own, I suggest starting with <a href=\"http://wotsit.org\" rel=\"nofollow noreferrer\">wotsit.org</a>, which has detailed specs for pretty much all image formats and you will see how to identify the file and also where information in it can be found.</p>\n\n<p>If you are comfortable working with C, then the free jpeglib can be used to get this information too. I would bet that you can do this with .NET libraries, but I don't know how.</p>\n" }, { "answer_id": 112266, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 4, "selected": false, "text": "<p>I was looking for something similar a few months earlier. I wanted to read the type, version, height and width of a GIF image but couldn’t find anything useful online.</p>\n\n<p>Fortunately in case of GIF, all the required information was in the first 10 bytes:</p>\n\n<pre><code>Type: Bytes 0-2\nVersion: Bytes 3-5\nHeight: Bytes 6-7\nWidth: Bytes 8-9\n</code></pre>\n\n<p>PNG are slightly more complex (width and height are 4-bytes each):</p>\n\n<pre><code>Width: Bytes 16-19\nHeight: Bytes 20-23\n</code></pre>\n\n<p>As mentioned above, <a href=\"http://www.wotsit.org/\" rel=\"nofollow noreferrer\">wotsit</a> is a good site for detailed specs on image and data formats though the PNG specs at <a href=\"http://www.libpng.org/pub/png/spec/1.1/PNG-Contents.html\" rel=\"nofollow noreferrer\">pnglib</a> are much more detailed. However, I think the Wikipedia entry on <a href=\"https://en.wikipedia.org/wiki/Portable_Network_Graphics\" rel=\"nofollow noreferrer\">PNG</a> and <a href=\"http://en.wikipedia.org/wiki/Graphics_Interchange_Format\" rel=\"nofollow noreferrer\">GIF</a> formats is the best place to start.</p>\n\n<p>Here’s my original code for checking GIFs, I have also slapped together something for PNGs:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.IO;\nusing System.Text;\n\npublic class ImageSizeTest\n{\n public static void Main()\n {\n byte[] bytes = new byte[10];\n\n string gifFile = @\"D:\\Personal\\Images&amp;Pics\\iProduct.gif\";\n using (FileStream fs = File.OpenRead(gifFile))\n {\n fs.Read(bytes, 0, 10); // type (3 bytes), version (3 bytes), width (2 bytes), height (2 bytes)\n }\n displayGifInfo(bytes);\n\n string pngFile = @\"D:\\Personal\\Images&amp;Pics\\WaveletsGamma.png\";\n using (FileStream fs = File.OpenRead(pngFile))\n {\n fs.Seek(16, SeekOrigin.Begin); // jump to the 16th byte where width and height information is stored\n fs.Read(bytes, 0, 8); // width (4 bytes), height (4 bytes)\n }\n displayPngInfo(bytes);\n }\n\n public static void displayGifInfo(byte[] bytes)\n {\n string type = Encoding.ASCII.GetString(bytes, 0, 3);\n string version = Encoding.ASCII.GetString(bytes, 3, 3);\n\n int width = bytes[6] | bytes[7] &lt;&lt; 8; // byte 6 and 7 contain the width but in network byte order so byte 7 has to be left-shifted 8 places and bit-masked to byte 6\n int height = bytes[8] | bytes[9] &lt;&lt; 8; // same for height\n\n Console.WriteLine(\"GIF\\nType: {0}\\nVersion: {1}\\nWidth: {2}\\nHeight: {3}\\n\", type, version, width, height);\n }\n\n public static void displayPngInfo(byte[] bytes)\n {\n int width = 0, height = 0;\n\n for (int i = 0; i &lt;= 3; i++)\n {\n width = bytes[i] | width &lt;&lt; 8;\n height = bytes[i + 4] | height &lt;&lt; 8; \n }\n\n Console.WriteLine(\"PNG\\nWidth: {0}\\nHeight: {1}\\n\", width, height); \n }\n}\n</code></pre>\n" }, { "answer_id": 112711, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 8, "selected": true, "text": "<p>Your best bet as always is to find a well tested library. However, you said that is difficult, so here is some dodgy largely untested code that should work for a fair number of cases:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.IO;\nusing System.Linq;\n\nnamespace ImageDimensions\n{\n public static class ImageHelper\n {\n const string errorMessage = \"Could not recognize image format.\";\n\n private static Dictionary&lt;byte[], Func&lt;BinaryReader, Size&gt;&gt; imageFormatDecoders = new Dictionary&lt;byte[], Func&lt;BinaryReader, Size&gt;&gt;()\n {\n { new byte[]{ 0x42, 0x4D }, DecodeBitmap},\n { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },\n { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },\n { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },\n { new byte[]{ 0xff, 0xd8 }, DecodeJfif },\n };\n\n /// &lt;summary&gt;\n /// Gets the dimensions of an image.\n /// &lt;/summary&gt;\n /// &lt;param name=\"path\"&gt;The path of the image to get the dimensions of.&lt;/param&gt;\n /// &lt;returns&gt;The dimensions of the specified image.&lt;/returns&gt;\n /// &lt;exception cref=\"ArgumentException\"&gt;The image was of an unrecognized format.&lt;/exception&gt;\n public static Size GetDimensions(string path)\n {\n using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)))\n {\n try\n {\n return GetDimensions(binaryReader);\n }\n catch (ArgumentException e)\n {\n if (e.Message.StartsWith(errorMessage))\n {\n throw new ArgumentException(errorMessage, \"path\", e);\n }\n else\n {\n throw e;\n }\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Gets the dimensions of an image.\n /// &lt;/summary&gt;\n /// &lt;param name=\"path\"&gt;The path of the image to get the dimensions of.&lt;/param&gt;\n /// &lt;returns&gt;The dimensions of the specified image.&lt;/returns&gt;\n /// &lt;exception cref=\"ArgumentException\"&gt;The image was of an unrecognized format.&lt;/exception&gt; \n public static Size GetDimensions(BinaryReader binaryReader)\n {\n int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x =&gt; x.Length).First().Length;\n\n byte[] magicBytes = new byte[maxMagicBytesLength];\n\n for (int i = 0; i &lt; maxMagicBytesLength; i += 1)\n {\n magicBytes[i] = binaryReader.ReadByte();\n\n foreach(var kvPair in imageFormatDecoders)\n {\n if (magicBytes.StartsWith(kvPair.Key))\n {\n return kvPair.Value(binaryReader);\n }\n }\n }\n\n throw new ArgumentException(errorMessage, \"binaryReader\");\n }\n\n private static bool StartsWith(this byte[] thisBytes, byte[] thatBytes)\n {\n for(int i = 0; i &lt; thatBytes.Length; i+= 1)\n {\n if (thisBytes[i] != thatBytes[i])\n {\n return false;\n }\n }\n return true;\n }\n\n private static short ReadLittleEndianInt16(this BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(short)];\n for (int i = 0; i &lt; sizeof(short); i += 1)\n {\n bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt16(bytes, 0);\n }\n\n private static int ReadLittleEndianInt32(this BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(int)];\n for (int i = 0; i &lt; sizeof(int); i += 1)\n {\n bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt32(bytes, 0);\n }\n\n private static Size DecodeBitmap(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(16);\n int width = binaryReader.ReadInt32();\n int height = binaryReader.ReadInt32();\n return new Size(width, height);\n }\n\n private static Size DecodeGif(BinaryReader binaryReader)\n {\n int width = binaryReader.ReadInt16();\n int height = binaryReader.ReadInt16();\n return new Size(width, height);\n }\n\n private static Size DecodePng(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(8);\n int width = binaryReader.ReadLittleEndianInt32();\n int height = binaryReader.ReadLittleEndianInt32();\n return new Size(width, height);\n }\n\n private static Size DecodeJfif(BinaryReader binaryReader)\n {\n while (binaryReader.ReadByte() == 0xff)\n {\n byte marker = binaryReader.ReadByte();\n short chunkLength = binaryReader.ReadLittleEndianInt16();\n\n if (marker == 0xc0)\n {\n binaryReader.ReadByte();\n\n int height = binaryReader.ReadLittleEndianInt16();\n int width = binaryReader.ReadLittleEndianInt16();\n return new Size(width, height);\n }\n\n binaryReader.ReadBytes(chunkLength - 2);\n }\n\n throw new ArgumentException(errorMessage);\n }\n }\n}\n</code></pre>\n\n<p>Hopefully the code is fairly obvious. To add a new file format you add it to <code>imageFormatDecoders</code> with the key being an array of the \"magic bits\" which appear at the beginning of every file of the given format and the value being a function which extracts the size from the stream. Most formats are simple enough, the only real stinker is jpeg.</p>\n" }, { "answer_id": 113323, "author": "Jan Zich", "author_id": 15716, "author_profile": "https://Stackoverflow.com/users/15716", "pm_score": 3, "selected": false, "text": "<p>Based on the answers so far and some additional searching, it seems that in the .NET 2 class library there is no functionality for it. So I decided to write my own. Here is a very rough version of it. At the moment, I needed it only for JPG’s. So it completes the answer posted by Abbas.</p>\n\n<p>There is no error checking or any other verification, but I currently need it for a limited task, and it can be eventually easily added. I tested it on some number of images, and it usually does not read more that 6K from an image. I guess it depends on the amount of the EXIF data.</p>\n\n<pre><code>using System;\nusing System.IO;\n\nnamespace Test\n{\n\n class Program\n {\n\n static bool GetJpegDimension(\n string fileName,\n out int width,\n out int height)\n {\n\n width = height = 0;\n bool found = false;\n bool eof = false;\n\n FileStream stream = new FileStream(\n fileName,\n FileMode.Open,\n FileAccess.Read);\n\n BinaryReader reader = new BinaryReader(stream);\n\n while (!found || eof)\n {\n\n // read 0xFF and the type\n reader.ReadByte();\n byte type = reader.ReadByte();\n\n // get length\n int len = 0;\n switch (type)\n {\n // start and end of the image\n case 0xD8: \n case 0xD9: \n len = 0;\n break;\n\n // restart interval\n case 0xDD: \n len = 2;\n break;\n\n // the next two bytes is the length\n default: \n int lenHi = reader.ReadByte();\n int lenLo = reader.ReadByte();\n len = (lenHi &lt;&lt; 8 | lenLo) - 2;\n break;\n }\n\n // EOF?\n if (type == 0xD9)\n eof = true;\n\n // process the data\n if (len &gt; 0)\n {\n\n // read the data\n byte[] data = reader.ReadBytes(len);\n\n // this is what we are looking for\n if (type == 0xC0)\n {\n width = data[1] &lt;&lt; 8 | data[2];\n height = data[3] &lt;&lt; 8 | data[4];\n found = true;\n }\n\n }\n\n }\n\n reader.Close();\n stream.Close();\n\n return found;\n\n }\n\n static void Main(string[] args)\n {\n foreach (string file in Directory.GetFiles(args[0]))\n {\n int w, h;\n GetJpegDimension(file, out w, out h);\n System.Console.WriteLine(file + \": \" + w + \" x \" + h);\n }\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 9687096, "author": "Koray", "author_id": 1266873, "author_profile": "https://Stackoverflow.com/users/1266873", "pm_score": 5, "selected": false, "text": "<pre><code>using (FileStream file = new FileStream(this.ImageFileName, FileMode.Open, FileAccess.Read))\n{\n using (Image tif = Image.FromStream(stream: file, \n useEmbeddedColorManagement: false,\n validateImageData: false))\n {\n float width = tif.PhysicalDimension.Width;\n float height = tif.PhysicalDimension.Height;\n float hresolution = tif.HorizontalResolution;\n float vresolution = tif.VerticalResolution;\n }\n}\n</code></pre>\n\n<p>the <code>validateImageData</code> set to <code>false</code> prevents GDI+ from performing costly analysis of the image data, thus severely decreasing load time. <a href=\"https://stackoverflow.com/questions/420337/validateimagedata-parameter-and-image-fromstream\">This question</a> sheds more light on the subject.</p>\n" }, { "answer_id": 13073341, "author": "Danny D", "author_id": 557516, "author_profile": "https://Stackoverflow.com/users/557516", "pm_score": 2, "selected": false, "text": "<p>I did this for PNG file </p>\n\n<pre><code> var buff = new byte[32];\n using (var d = File.OpenRead(file))\n { \n d.Read(buff, 0, 32);\n }\n const int wOff = 16;\n const int hOff = 20; \n var Widht =BitConverter.ToInt32(new[] {buff[wOff + 3], buff[wOff + 2], buff[wOff + 1], buff[wOff + 0],},0);\n var Height =BitConverter.ToInt32(new[] {buff[hOff + 3], buff[hOff + 2], buff[hOff + 1], buff[hOff + 0],},0);\n</code></pre>\n" }, { "answer_id": 60667939, "author": "bang", "author_id": 611084, "author_profile": "https://Stackoverflow.com/users/611084", "pm_score": 3, "selected": false, "text": "<p>Updated ICR's answer to support progressive jPegs &amp; WebP as well :)</p>\n\n<pre><code>internal static class ImageHelper\n{\n const string errorMessage = \"Could not recognise image format.\";\n\n private static Dictionary&lt;byte[], Func&lt;BinaryReader, Size&gt;&gt; imageFormatDecoders = new Dictionary&lt;byte[], Func&lt;BinaryReader, Size&gt;&gt;()\n {\n { new byte[] { 0x42, 0x4D }, DecodeBitmap },\n { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },\n { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },\n { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },\n { new byte[] { 0xff, 0xd8 }, DecodeJfif },\n { new byte[] { 0x52, 0x49, 0x46, 0x46 }, DecodeWebP },\n };\n\n /// &lt;summary&gt; \n /// Gets the dimensions of an image. \n /// &lt;/summary&gt; \n /// &lt;param name=\"path\"&gt;The path of the image to get the dimensions of.&lt;/param&gt; \n /// &lt;returns&gt;The dimensions of the specified image.&lt;/returns&gt; \n /// &lt;exception cref=\"ArgumentException\"&gt;The image was of an unrecognised format.&lt;/exception&gt; \n public static Size GetDimensions(BinaryReader binaryReader)\n {\n int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x =&gt; x.Length).First().Length;\n byte[] magicBytes = new byte[maxMagicBytesLength];\n for(int i = 0; i &lt; maxMagicBytesLength; i += 1)\n {\n magicBytes[i] = binaryReader.ReadByte();\n foreach(var kvPair in imageFormatDecoders)\n {\n if(StartsWith(magicBytes, kvPair.Key))\n {\n return kvPair.Value(binaryReader);\n }\n }\n }\n\n throw new ArgumentException(errorMessage, \"binaryReader\");\n }\n\n private static bool StartsWith(byte[] thisBytes, byte[] thatBytes)\n {\n for(int i = 0; i &lt; thatBytes.Length; i += 1)\n {\n if(thisBytes[i] != thatBytes[i])\n {\n return false;\n }\n }\n\n return true;\n }\n\n private static short ReadLittleEndianInt16(BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(short)];\n\n for(int i = 0; i &lt; sizeof(short); i += 1)\n {\n bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt16(bytes, 0);\n }\n\n private static int ReadLittleEndianInt32(BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(int)];\n for(int i = 0; i &lt; sizeof(int); i += 1)\n {\n bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt32(bytes, 0);\n }\n\n private static Size DecodeBitmap(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(16);\n int width = binaryReader.ReadInt32();\n int height = binaryReader.ReadInt32();\n return new Size(width, height);\n }\n\n private static Size DecodeGif(BinaryReader binaryReader)\n {\n int width = binaryReader.ReadInt16();\n int height = binaryReader.ReadInt16();\n return new Size(width, height);\n }\n\n private static Size DecodePng(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(8);\n int width = ReadLittleEndianInt32(binaryReader);\n int height = ReadLittleEndianInt32(binaryReader);\n return new Size(width, height);\n }\n\n private static Size DecodeJfif(BinaryReader binaryReader)\n {\n while(binaryReader.ReadByte() == 0xff)\n {\n byte marker = binaryReader.ReadByte();\n short chunkLength = ReadLittleEndianInt16(binaryReader);\n if(marker == 0xc0 || marker == 0xc2) // c2: progressive\n {\n binaryReader.ReadByte();\n int height = ReadLittleEndianInt16(binaryReader);\n int width = ReadLittleEndianInt16(binaryReader);\n return new Size(width, height);\n }\n\n if(chunkLength &lt; 0)\n {\n ushort uchunkLength = (ushort)chunkLength;\n binaryReader.ReadBytes(uchunkLength - 2);\n }\n else\n {\n binaryReader.ReadBytes(chunkLength - 2);\n }\n }\n\n throw new ArgumentException(errorMessage);\n }\n\n private static Size DecodeWebP(BinaryReader binaryReader)\n {\n binaryReader.ReadUInt32(); // Size\n binaryReader.ReadBytes(15); // WEBP, VP8 + more\n binaryReader.ReadBytes(3); // SYNC\n\n var width = binaryReader.ReadUInt16() &amp; 0b00_11111111111111; // 14 bits width\n var height = binaryReader.ReadUInt16() &amp; 0b00_11111111111111; // 14 bits height\n\n return new Size(width, height);\n }\n\n}\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15716/" ]
Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want): ``` using System; using System.Drawing; namespace Test { class Program { static void Main(string[] args) { Image img = new Bitmap("test.png"); System.Console.WriteLine(img.Width + " x " + img.Height); } } } ```
Your best bet as always is to find a well tested library. However, you said that is difficult, so here is some dodgy largely untested code that should work for a fair number of cases: ``` using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; namespace ImageDimensions { public static class ImageHelper { const string errorMessage = "Could not recognize image format."; private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>() { { new byte[]{ 0x42, 0x4D }, DecodeBitmap}, { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif }, { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif }, { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng }, { new byte[]{ 0xff, 0xd8 }, DecodeJfif }, }; /// <summary> /// Gets the dimensions of an image. /// </summary> /// <param name="path">The path of the image to get the dimensions of.</param> /// <returns>The dimensions of the specified image.</returns> /// <exception cref="ArgumentException">The image was of an unrecognized format.</exception> public static Size GetDimensions(string path) { using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(path))) { try { return GetDimensions(binaryReader); } catch (ArgumentException e) { if (e.Message.StartsWith(errorMessage)) { throw new ArgumentException(errorMessage, "path", e); } else { throw e; } } } } /// <summary> /// Gets the dimensions of an image. /// </summary> /// <param name="path">The path of the image to get the dimensions of.</param> /// <returns>The dimensions of the specified image.</returns> /// <exception cref="ArgumentException">The image was of an unrecognized format.</exception> public static Size GetDimensions(BinaryReader binaryReader) { int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length; byte[] magicBytes = new byte[maxMagicBytesLength]; for (int i = 0; i < maxMagicBytesLength; i += 1) { magicBytes[i] = binaryReader.ReadByte(); foreach(var kvPair in imageFormatDecoders) { if (magicBytes.StartsWith(kvPair.Key)) { return kvPair.Value(binaryReader); } } } throw new ArgumentException(errorMessage, "binaryReader"); } private static bool StartsWith(this byte[] thisBytes, byte[] thatBytes) { for(int i = 0; i < thatBytes.Length; i+= 1) { if (thisBytes[i] != thatBytes[i]) { return false; } } return true; } private static short ReadLittleEndianInt16(this BinaryReader binaryReader) { byte[] bytes = new byte[sizeof(short)]; for (int i = 0; i < sizeof(short); i += 1) { bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte(); } return BitConverter.ToInt16(bytes, 0); } private static int ReadLittleEndianInt32(this BinaryReader binaryReader) { byte[] bytes = new byte[sizeof(int)]; for (int i = 0; i < sizeof(int); i += 1) { bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte(); } return BitConverter.ToInt32(bytes, 0); } private static Size DecodeBitmap(BinaryReader binaryReader) { binaryReader.ReadBytes(16); int width = binaryReader.ReadInt32(); int height = binaryReader.ReadInt32(); return new Size(width, height); } private static Size DecodeGif(BinaryReader binaryReader) { int width = binaryReader.ReadInt16(); int height = binaryReader.ReadInt16(); return new Size(width, height); } private static Size DecodePng(BinaryReader binaryReader) { binaryReader.ReadBytes(8); int width = binaryReader.ReadLittleEndianInt32(); int height = binaryReader.ReadLittleEndianInt32(); return new Size(width, height); } private static Size DecodeJfif(BinaryReader binaryReader) { while (binaryReader.ReadByte() == 0xff) { byte marker = binaryReader.ReadByte(); short chunkLength = binaryReader.ReadLittleEndianInt16(); if (marker == 0xc0) { binaryReader.ReadByte(); int height = binaryReader.ReadLittleEndianInt16(); int width = binaryReader.ReadLittleEndianInt16(); return new Size(width, height); } binaryReader.ReadBytes(chunkLength - 2); } throw new ArgumentException(errorMessage); } } } ``` Hopefully the code is fairly obvious. To add a new file format you add it to `imageFormatDecoders` with the key being an array of the "magic bits" which appear at the beginning of every file of the given format and the value being a function which extracts the size from the stream. Most formats are simple enough, the only real stinker is jpeg.
111,405
<p>I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF.</p> <p>Thanks in advance, Yet another LaTeX user</p>
[ { "answer_id": 111506, "author": "finrod", "author_id": 8295, "author_profile": "https://Stackoverflow.com/users/8295", "pm_score": 2, "selected": true, "text": "<p>If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG format, and use the following code:</p>\n\n<pre><code>%in the document preamble\n\\usepackage{graphicx}\n\n%in the document, in the place where you want to put your image\n\\includegraphics{image_filename_without_extension}\n</code></pre>\n\n<p>When the image is a PNG or JPG file (there are some more, I don't remember which ones ATM), you can compile the file with pdfLaTeX, but not with the normal LaTeX (i.e. you can produce a PDF, but not DVI or PS).<br>\nOf course normally, if everything works fine, it's nice to have one copy of the image in EPS, and another in, say, PNG -- this way you can compile easily both to PDF, and to PS.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 114168, "author": "lmsasu", "author_id": 11464, "author_profile": "https://Stackoverflow.com/users/11464", "pm_score": 0, "selected": false, "text": "<p>Thanks for reply. I have solved the problem: the dvi crashed because I have installed Miktex with the User Account Control enabled. I have disabled it, reinstalled and now it's working (with UAC still disabled). </p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11464/" ]
I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF. Thanks in advance, Yet another LaTeX user
If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG format, and use the following code: ``` %in the document preamble \usepackage{graphicx} %in the document, in the place where you want to put your image \includegraphics{image_filename_without_extension} ``` When the image is a PNG or JPG file (there are some more, I don't remember which ones ATM), you can compile the file with pdfLaTeX, but not with the normal LaTeX (i.e. you can produce a PDF, but not DVI or PS). Of course normally, if everything works fine, it's nice to have one copy of the image in EPS, and another in, say, PNG -- this way you can compile easily both to PDF, and to PS. Hope that helps.
111,407
<p>I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.</p> <p>Does anyone know of a fix for this?</p> <p>Thanks!</p>
[ { "answer_id": 111409, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "<pre><code>$(document).ready(function() {\n // Fix background image caching problem\n if (jQuery.browser.msie) {\n try { \n document.execCommand(\"BackgroundImageCache\", false, true); \n } catch(err) {}\n }\n};\n</code></pre>\n\n<p><a href=\"http://osdir.com/ml/lang.javascript.jquery/2006-09/msg01932.html\" rel=\"nofollow noreferrer\">Apparently</a>.</p>\n" }, { "answer_id": 111670, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 3, "selected": false, "text": "<p>Just let IE6 flicker. I don't think it's worth it to invest time in a dying browser when your base functionality works well enough. If you're worried about flickering for accessibility reasons, just sniff for IE6 and replace the animation with a generic show() and hide() instead. I recommend avoiding complicated code for edge cases that don't matter.</p>\n" }, { "answer_id": 421705, "author": "Pavel Lishin", "author_id": 13089, "author_profile": "https://Stackoverflow.com/users/13089", "pm_score": 2, "selected": false, "text": "<p>Oli's fix only seems to apply to flickering backgrounds, which is not the case here.</p>\n\n<p>Ryan McGeary's advice is solid, except for when the client/your boss absolutely demand that IE6 not act like it has fetal alcohol syndrome.</p>\n\n<p>I found the solution here: <a href=\"http://groups.google.com/group/jquery-dev/browse_thread/thread/85c2d334fae35d85\" rel=\"nofollow noreferrer\">Slide effect bugs in IE 6 and 7 since version 1.1.3</a></p>\n\n<p>Added a doctype declaration to the top of the file (why wasn't it there before? who knows!) and the flicker vanished, never to be seen again.</p>\n" }, { "answer_id": 1157294, "author": "Mike Gardiner", "author_id": 126663, "author_profile": "https://Stackoverflow.com/users/126663", "pm_score": 6, "selected": true, "text": "<p>Apologies for the extra comment (I can't upvote or comment on Pavel's answer), but adding a DOCTYPE fixed this issue for me, and the slideUp/Down/Toggle effects now work correctly in IE7.</p>\n\n<p>See <a href=\"http://www.alistapart.com/articles/doctype/\" rel=\"noreferrer\">A List Apart</a> for more information on DOCTYPES, or you can try specifying the fairly lenient 4/Transitional:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n\"http://www.w3.org/TR/html4/loose.dtd\"&gt;\n</code></pre>\n" }, { "answer_id": 1792653, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I posted a quick fix solution over at <a href=\"http://blog.clintonbeattie.com/how-to-solve-the-jquery-flickering-content-problem/\" rel=\"nofollow noreferrer\">http://blog.clintonbeattie.com/how-to-solve-the-jquery-flickering-content-problem/</a></p>\n\n<p>In short, add overflow:hidden to the containing element that you are sliding in/out. Hope this helps!</p>\n" }, { "answer_id": 2374174, "author": "sergiopereira", "author_id": 21420, "author_profile": "https://Stackoverflow.com/users/21420", "pm_score": 2, "selected": false, "text": "<p>From what I've heard and tried (including the other suggestions here) there are still situations where the flicker will continue to be noticeable, especially when you don't have the choice of easily leaving quirks mode.\nIn my case I had to stay on quirks mode for now and the other suggestions still didn't fix the problem for me. I ended up adding a little workaround until we can finally leave quirks mode:</p>\n\n<pre><code>//Start the slideUp effect lasting 500ms\n$('#element').slideUp(500);\n\n//Abort the effect just before it finishes and force hide()\n//I had to play with the timeout interval until I found one that\n// looked exactly right. 400ms worked for me.\nsetTimeout(function() {\n $('#element').stop(true, true).hide(); \n}, 400);\n</code></pre>\n" }, { "answer_id": 3894024, "author": "Benxamin", "author_id": 218119, "author_profile": "https://Stackoverflow.com/users/218119", "pm_score": 1, "selected": false, "text": "<p>I'm working with a carousel that has marked-up copy over some background slides. The slide transition is a fade. Everything's fine so far. </p>\n\n<p>But some parts of the copy fade-in after the slide loads. And then fade-out right before the slide transition. This copy, an unordered list of links (<code>UL &gt; LI*2 &gt; A</code>), faded-in over the slide background. This, too, is fine in every browser <em>except IE</em>. IE had a flickering background on the UL. </p>\n\n<p>What was happening is that there were two simultaneous fade-Ins running: the background image on the slide &amp; the UL. I used <a href=\"https://stackoverflow.com/users/21420/sergiopereira\">sergio's</a> prototyping <strong>setTimeout</strong> function to run the UL fadeIn() after the slide had completed loading. Then, I called another setTimeout to make the slide transition right after the UL fadeOut(). </p>\n\n<p><strong>setTimeout</strong> is your friend when combating IE flicker. </p>\n" }, { "answer_id": 4012505, "author": "ghusse", "author_id": 380086, "author_profile": "https://Stackoverflow.com/users/380086", "pm_score": 2, "selected": false, "text": "<p>This code does not depends on the browser (no browser detection), works great and reproduces the behaviour of the method .slideUp</p>\n\n<pre><code>$(\"#element\").animate({\n height: 1, // Avoiding sliding to 0px (flash on IE)\n paddingTop: \"hide\",\n paddingBottom: \"hide\"\n })\n // Then hide\n .animate({display:\"hide\"},{queue:true});\n</code></pre>\n" }, { "answer_id": 5106027, "author": "Kees C. Bakker", "author_id": 201482, "author_profile": "https://Stackoverflow.com/users/201482", "pm_score": 1, "selected": false, "text": "<p>We had the same problem today. Not only in IE6, but also in IE8! I've fixed it by <strong>hiding the div somewhat earlier</strong>, by using a timeout:</p>\n\n<pre><code>var pane = $('.ColorPane');\nvar speed = 500;\nwindow.setTimeout(function() { pane.css('display', 'none'); }, speed - 100);\npane.slideUp(speed);\n</code></pre>\n\n<p>Hope it helps some of you out there.</p>\n" }, { "answer_id": 7899887, "author": "saeraphin", "author_id": 1014105, "author_profile": "https://Stackoverflow.com/users/1014105", "pm_score": 2, "selected": false, "text": "<p>Dunno if someone will read this answer, but here is a workaround for those who, like me, can't add a document type to the page (thank you Sharepoint 2007 default templates) without spending a few days on a complete template revision.</p>\n\n<p>On a DOCTYPE-less document, the flickering occurs when an element height reaches 0. So the workaround I've found is to animate my elements to an height of 1px, rather than 0.</p>\n\n<p>Like this:</p>\n\n<pre><code>$(\".slider\").click(function (e) {\n $(this).animate({\"height\" : \"1px\"});\n});\n</code></pre>\n\n<p>Hope it will help.</p>\n\n<p>N.B: don't forget that in order to slideDown the element, you have to previously store its initial height somehow (node property, rel attribute hack, etc).</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396/" ]
I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear. Does anyone know of a fix for this? Thanks!
Apologies for the extra comment (I can't upvote or comment on Pavel's answer), but adding a DOCTYPE fixed this issue for me, and the slideUp/Down/Toggle effects now work correctly in IE7. See [A List Apart](http://www.alistapart.com/articles/doctype/) for more information on DOCTYPES, or you can try specifying the fairly lenient 4/Transitional: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> ```
111,426
<p>I'm taking a course in computational complexity and have so far had an impression that it won't be of much help to a developer. </p> <p>I might be wrong but if you have gone down this path before, could you please provide an example of how the complexity theory helped you in your work? Tons of thanks.</p>
[ { "answer_id": 111444, "author": "David Ameller", "author_id": 19689, "author_profile": "https://Stackoverflow.com/users/19689", "pm_score": 0, "selected": false, "text": "<p>A good example could be when your boss tells you to do some program and you can demonstrate by using the computational complexity theory that what your boss is asking you to do is not possible.</p>\n" }, { "answer_id": 111446, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "<p>There are points in time when you will face problems that require thinking about them. There are many real world problems that require manipulation of large set of data...</p>\n\n<p>Examples are:</p>\n\n<ul>\n<li>Maps application... like Google Maps - how would you process the road line data worldwide and draw them? and you need to draw them fast!</li>\n<li>Logistics application... think traveling sales man on steroids</li>\n<li>Data mining... all big enterprises requires one, how would you mine a database containing 100 tables and 10m+ rows and come up with a useful results before the trends get outdated?</li>\n</ul>\n\n<p>Taking a course in computational complexity will help you in analyzing and choosing/creating algorithms that are efficient for such scenarios.</p>\n\n<p>Believe me, something as simple as reducing a coefficient, say from T(3n) down to T(2n) can make a HUGE differences when the \"n\" is measured in days if not months.</p>\n" }, { "answer_id": 111452, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>It's extremely important. If you don't understand how to estimate and figure out how long your algorithms will take to run, then you will end up writing some pretty slow code. I think about compuational complexity all the time when writing algorithms. It's something that should always be on your mind when programming.</p>\n\n<p>This is especially true in many cases because while your app may work fine on your desktop computer with a small test data set, it's important to understand how quickly your app will respond once you go live with it, and there are hundreds of thousands of people using it.</p>\n" }, { "answer_id": 111483, "author": "reinierpost", "author_id": 17945, "author_profile": "https://Stackoverflow.com/users/17945", "pm_score": 0, "selected": false, "text": "<p>Yes, my knowledge of sorting algorithms came in handy one day when I had to sort a stack of student exams. I used merge sort (but not quicksort or heapsort). When programming, I just employ whatever sorting routine the library offers. ( haven't had to sort really large amount of data yet.)</p>\n\n<p>I do use complexity theory in programming all the time, mostly in deciding which data structures to use, but also in when deciding whether or when to sort things, and for many other decisions.</p>\n" }, { "answer_id": 111489, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": 3, "selected": false, "text": "<p>For most types of programming work the theory part and proofs may not be useful in themselves but what they're doing is try to give you the intuition of being able to immediately say \"this algorithm is O(n^2) so we can't run it on these one million data points\". Even in the most elementary processing of large amounts of data you'll be running into this.</p>\n\n<p>Thinking quickly complexity theory has been important to me in business data processing, GIS, graphics programming and understanding algorithms in general. It's one of the most useful lessons you can get from CS studies compared to what you'd generally self-study otherwise.</p>\n" }, { "answer_id": 111510, "author": "Stefan Rusek", "author_id": 19704, "author_profile": "https://Stackoverflow.com/users/19704", "pm_score": 3, "selected": false, "text": "<p>While it is true that one can get really far in software development without the slightest understanding of algorithmic complexity. I find I use my knowledge of complexity all the time; though, at this point it is often without realizing it. The two things that learning about complexity gives you as a software developer are a way to compare non-similar algorithms that do the same thing (sorting algorithms are the classic example, but most people don't actually write their own sorts). The more useful thing that it gives you is a way to quickly describe an algorithm.</p>\n\n<p>For example, consider SQL. SQL is used every day by a very large number of programmers. If you were to see the following query, your understanding of the query is very different if you've studied complexity.</p>\n\n<pre><code>SELECT User.*, COUNT(Order.*) OrderCount FROM User Join Order ON User.UserId = Order.UserId\n</code></pre>\n\n<p>If you have studied complexity, then you would understand if someone said it was O(n^2) for a certain DBMS. Without complexity theory, the person would have to explain about table scans and such. If we add an index to the Order table</p>\n\n<pre><code>CREATE INDEX ORDER_USERID ON Order(UserId)\n</code></pre>\n\n<p>Then the above query might be O(n log n), which would make a huge difference for a large DB, but for a small one, it is nothing at all.</p>\n\n<p>One might argue that complexity theory is not needed to understand how databases work, and they would be correct, but complexity theory gives a language for thinking about and talking about algorithms working on data.</p>\n" }, { "answer_id": 111514, "author": "sergtk", "author_id": 13441, "author_profile": "https://Stackoverflow.com/users/13441", "pm_score": 0, "selected": false, "text": "<p>'<strong>yes</strong>' and '<strong>no</strong>'</p>\n\n<p><strong>yes</strong>) I frequently use <a href=\"http://en.wikipedia.org/wiki/O_notation\" rel=\"nofollow noreferrer\">big O-notation</a> when developing and implementing algorithms.\nE.g. when you should handle 10^3 items and complexity of the first algorithm is O(n log(n)) and of the second one O(n^3), you simply can say that first algorithm is almost real time while the second require considerable calculations.</p>\n\n<p>Sometimes knowledges about <a href=\"http://en.wikipedia.org/wiki/Complexity_classes_P_and_NP\" rel=\"nofollow noreferrer\">NP complexities classes</a> can be useful. It can help you to realize that you can stop thinking about inventing efficient algorithm when some NP-complete problem can be reduced to the problem you are thinking about. </p>\n\n<p><strong>no</strong>) What I have described above is a small part of the complexities theory. As a result it is difficult to say that I use it, I use minor-minor part of it.</p>\n\n<p>I should admit that there are many software development project which don't touch algorithm development or usage of them in sophisticated way. In such cases complexity theory is useless. Ordinary users of algorithms frequently operate using words 'fast' and 'slow', 'x seconds' etc.</p>\n" }, { "answer_id": 111861, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 7, "selected": true, "text": "<p>O(1): Plain code without loops. Just flows through. Lookups in a lookup table are O(1), too.</p>\n\n<p>O(log(n)): efficiently optimized algorithms. Example: binary tree algorithms and binary search. Usually doesn't hurt. You're lucky if you have such an algorithm at hand.</p>\n\n<p>O(n): a single loop over data. Hurts for very large n.</p>\n\n<p>O(n*log(n)): an algorithm that does some sort of divide and conquer strategy. Hurts for large n. Typical example: merge sort</p>\n\n<p>O(n*n): a nested loop of some sort. Hurts even with small n. Common with naive matrix calculations. You want to avoid this sort of algorithm if you can.</p>\n\n<p>O(n^x for x>2): a wicked construction with multiple nested loops. Hurts for very small n. </p>\n\n<p>O(x^n, n! and worse): freaky (and often recursive) algorithms you don't want to have in production code except in very controlled cases, for very small n and if there really is no better alternative. Computation time may explode with n=n+1.</p>\n\n<p>Moving your algorithm down from a higher complexity class can make your algorithm fly. Think of Fourier transformation which has an O(n*n) algorithm that was unusable with 1960s hardware except in rare cases. Then Cooley and Tukey made some clever complexity reductions by re-using already calculated values. That led to the widespread introduction of FFT into signal processing. And in the end it's also why Steve Jobs made a fortune with the iPod.</p>\n\n<p>Simple example: Naive C programmers write this sort of loop:</p>\n\n<pre><code>for (int cnt=0; cnt &lt; strlen(s) ; cnt++) {\n /* some code */\n}\n</code></pre>\n\n<p>That's an O(n*n) algorithm because of the implementation of strlen(). Nesting loops leads to multiplication of complexities inside the big-O. O(n) inside O(n) gives O(n*n). O(n^3) inside O(n) gives O(n^4). In the example, precalculating the string length will immediately turn the loop into O(n). <a href=\"http://www.joelonsoftware.com/articles/fog0000000319.html\" rel=\"noreferrer\">Joel has also written about this.</a></p>\n\n<p>Yet the complexity class is not everything. You have to keep an eye on the size of n. Reworking an O(n*log(n)) algorithm to O(n) won't help if the number of (now linear) instructions grows massively due to the reworking. And if n is small anyway, optimizing won't give much bang, too.</p>\n" }, { "answer_id": 111961, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": false, "text": "<p>Computers are not smart, they will do whatever you instruct them to do. Compilers can optimize code a bit for you, but they can't optimize algorithms. Human brain works differently and that is why you need to understand the Big O. Consider calculating Fibonacci numbers. We all know F(n) = F(n-1) + F(n-2), and starting with 1,1 you can easily calculate following numbers without much effort, in linear time. But if you tell computer to calculate it with that formula (recursively), it wouldn't be linear (at least, in imperative languages). Somehow, our brain optimized algorithm, but compiler can't do this. So, you have to <strong>work</strong> on the <strong>algorithm</strong> to make it better. </p>\n\n<p>And then, you need training, to spot brain optimizations which look so obvious, to see when code might be ineffective, to know patterns for bad and good algorithms (in terms of computational complexity) and so on. Basically, those courses serve several things:</p>\n\n<ul>\n<li>understand executional patterns and data structures and what effect they have on the time your program needs to finish; </li>\n<li>train your mind to spot potential problems in algorithm, when it could be inefficient on large data sets. Or understand the results of profiling;</li>\n<li>learn well-known ways to improve algorithms by reducing their computational complexity; </li>\n<li>prepare yourself to pass an interview in the cool company :)</li>\n</ul>\n" }, { "answer_id": 115447, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 2, "selected": false, "text": "<p>Yes, I frequently use Big-O notation, or rather, I use the thought processes behind it, not the notation itself. Largely because so few developers in the organization(s) I frequent understand it. I don't mean to be disrespectful to those people, but in my experience, knowledge of this stuff is one of those things that \"sorts the men from the boys\".</p>\n\n<p>I wonder if this is one of those questions that can only receive \"yes\" answers? It strikes me that the set of people that understand computational complexity is roughly equivalent to the set of people that think it's important. So, anyone that might answer no perhaps doesn't understand the question and therefore would skip on to the next question rather than pause to respond. Just a thought ;-)</p>\n" }, { "answer_id": 115525, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 1, "selected": false, "text": "<p>There's lots of good advice here, and I'm sure most programmers have used their complexity knowledge once in a while.</p>\n\n<p>However I should say understanding computational complexity is of extreme importance in the field of Games! Yes you heard it, that \"useless\" stuff is the kind of stuff game programming lives on. </p>\n\n<p>I'd bet very few professionals probably care about the Big-O as much as game programmers.</p>\n" }, { "answer_id": 116223, "author": "quick_dry", "author_id": 3716, "author_profile": "https://Stackoverflow.com/users/3716", "pm_score": 0, "selected": false, "text": "<p>@Martin: Can you please elaborate on the thought processes behind it?</p>\n\n<p>it might not be so explicit as sitting down and working out the Big-O notation for a solution, but it creates an awareness of the problem - and that steers you towards looking for a more efficient answer and away from problems in approaches you might take. e.g. O(n*n) versus something faster e.g. searching for words stored in a list versus stored in a trie (contrived example)</p>\n\n<p>I find that it makes a difference with what data structures I'll choose to use, and how I'll work on large numbers of records.</p>\n" }, { "answer_id": 145650, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 1, "selected": false, "text": "<p>I use complexity calculations regularly, largely because I work in the geospatial domain with very large datasets, e.g. processes involving millions and occasionally billions of cartesian coordinates. Once you start hitting multi-dimensional problems, complexity can be a real issue, as greedy algorithms that would be O(n) in one dimension suddenly hop to O(n^3) in three dimensions and it doesn't take much data to create a serious bottleneck. As I mentioned in <a href=\"https://stackoverflow.com/questions/133008/what-is-big-o-notation-do-you-use-it#143916\">a similar post</a>, you also see big O notation becoming cumbersome when you start dealing with groups of complex objects of varying size. The order of complexity can also be very data dependent, with typical cases performing much better than general cases for well designed <a href=\"http://en.wikipedia.org/wiki/Ad_hoc\" rel=\"nofollow noreferrer\">ad hoc</a> algorithms.</p>\n\n<p>It is also worth testing your algorithms under a profiler to see if what you have designed is what you have achieved. I find most bottlenecks are resolved much better with algorithm tweaking than improved processor speed for all the obvious reasons.</p>\n\n<p>For more reading on general algorithms and their complexities I found <a href=\"http://www.cs.princeton.edu/~rs/\" rel=\"nofollow noreferrer\">Sedgewicks work</a> both informative and accessible. For spatial algorithms, <a href=\"http://maven.smith.edu/~orourke/\" rel=\"nofollow noreferrer\">O'Rourkes</a> book on computational geometry is excellent.</p>\n" }, { "answer_id": 160305, "author": "Marcin", "author_id": 21640, "author_profile": "https://Stackoverflow.com/users/21640", "pm_score": 1, "selected": false, "text": "<p>In your normal life, not near a computer you should apply concepts of complexity and parallel processing. This will allow you to be more efficient. Cache coherency. That sort of thing.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ]
I'm taking a course in computational complexity and have so far had an impression that it won't be of much help to a developer. I might be wrong but if you have gone down this path before, could you please provide an example of how the complexity theory helped you in your work? Tons of thanks.
O(1): Plain code without loops. Just flows through. Lookups in a lookup table are O(1), too. O(log(n)): efficiently optimized algorithms. Example: binary tree algorithms and binary search. Usually doesn't hurt. You're lucky if you have such an algorithm at hand. O(n): a single loop over data. Hurts for very large n. O(n\*log(n)): an algorithm that does some sort of divide and conquer strategy. Hurts for large n. Typical example: merge sort O(n\*n): a nested loop of some sort. Hurts even with small n. Common with naive matrix calculations. You want to avoid this sort of algorithm if you can. O(n^x for x>2): a wicked construction with multiple nested loops. Hurts for very small n. O(x^n, n! and worse): freaky (and often recursive) algorithms you don't want to have in production code except in very controlled cases, for very small n and if there really is no better alternative. Computation time may explode with n=n+1. Moving your algorithm down from a higher complexity class can make your algorithm fly. Think of Fourier transformation which has an O(n\*n) algorithm that was unusable with 1960s hardware except in rare cases. Then Cooley and Tukey made some clever complexity reductions by re-using already calculated values. That led to the widespread introduction of FFT into signal processing. And in the end it's also why Steve Jobs made a fortune with the iPod. Simple example: Naive C programmers write this sort of loop: ``` for (int cnt=0; cnt < strlen(s) ; cnt++) { /* some code */ } ``` That's an O(n\*n) algorithm because of the implementation of strlen(). Nesting loops leads to multiplication of complexities inside the big-O. O(n) inside O(n) gives O(n\*n). O(n^3) inside O(n) gives O(n^4). In the example, precalculating the string length will immediately turn the loop into O(n). [Joel has also written about this.](http://www.joelonsoftware.com/articles/fog0000000319.html) Yet the complexity class is not everything. You have to keep an eye on the size of n. Reworking an O(n\*log(n)) algorithm to O(n) won't help if the number of (now linear) instructions grows massively due to the reworking. And if n is small anyway, optimizing won't give much bang, too.
111,436
<p>I want to have my PHP application labeled with the revision number which it uses, but I don't want to use <a href="http://en.wikipedia.org/wiki/CruiseControl" rel="nofollow noreferrer">CruiseControl</a> or update a file and upload it every time. How should I do it?</p>
[ { "answer_id": 111459, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 4, "selected": false, "text": "<p>Assuming your webroot is a checked-out copy of the subversion tree, you could parse the /.svn/entries file and hook out the revision number (4th line here)...</p>\n\n<p>In PHP:</p>\n\n<pre><code>$svn = File('.svn/entries');\n$svnrev = $svn[3];\nunset($svn);\n</code></pre>\n" }, { "answer_id": 111463, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"https://stackoverflow.com/questions/163/how-do-i-sync-the-svn-revision-number-with-my-aspnet-web-site#166\">this answer</a>:</p>\n\n<blockquote>\n <p>You can do it by adding the following\n anywhere in your code</p>\n</blockquote>\n\n<pre><code>$Id:$ \n</code></pre>\n\n<blockquote>\n <p>So for example Jeff did:</p>\n</blockquote>\n\n<pre><code>&lt;div id=\"svnrevision\"&gt;svn revision: $Id:$&lt;/div&gt;\n</code></pre>\n\n<blockquote>\n <p>and when checked in the\n server replaced $Id:$ with the current\n revision number. I also found <a href=\"http://www.compuphase.com/svnrev.htm\" rel=\"nofollow noreferrer\">this reference</a>.</p>\n \n <p>There is also $Date:$, $Rev:$,\n $Revision:$</p>\n</blockquote>\n" }, { "answer_id": 111467, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>In most cases the code on the server would actually contain an \"Export\" of the code, not a checkout, and therefore not contain the .svn folders. At least that's the setup I see most often. Do others actually check out their code onto the web server?</p>\n" }, { "answer_id": 111471, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 2, "selected": false, "text": "<p>The easiest way is to use the Subversion \"Keyword Substitution\". There is a guide <a href=\"http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html\" rel=\"nofollow noreferrer\">here</a> in the SVN book (<em><a href=\"http://svnbook.red-bean.com/\" rel=\"nofollow noreferrer\">Version Control with Subversion</a></em>).</p>\n\n<p>You'll basically just have to add the text $Rev$ somewhere in your file.\nThen enable the keyword in your repository. On checkout SVN will substitute the revision number into the file.</p>\n" }, { "answer_id": 111480, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 2, "selected": false, "text": "<p>You can get close with <a href=\"http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html\" rel=\"nofollow noreferrer\">SVN Keywords</a>. Add $Revision$ where you want the revision to show, but that will only show the last revision that particular file was changed, so you would have to make a change to the file each time. Getting the global revision number isn't possible without some sort of external script, or a post-commit hook.</p>\n" }, { "answer_id": 116010, "author": "daremon", "author_id": 6346, "author_profile": "https://Stackoverflow.com/users/6346", "pm_score": 7, "selected": true, "text": "<p>SVN keywords is not a good solution. As others pointed out adding $Revision$ in a file only affects <strong>the specific file</strong>, which may not change for a long time.</p>\n\n<p>Remembering to \"edit\" a file (by adding or removing a blank line) before every commit is pointless. You could as well just type the revision by hand.</p>\n\n<p>One good way to do it (that I know of) is to have an automated deployment process (which is always a good thing) and using the command svnversion. Here is what I do:</p>\n\n<p>Wherever I need the revision I do an include: <code>&lt;?php include 'version.php'; ?&gt;</code>. This \"version.php\" file only has the revision number. Moreover it is not part of the repository (it set to be ignored). Here is how I create it:</p>\n\n<p>1) On projects where SVN is installed on the server, I also use it for deployment. Getting the latest version to the server I have a script that among other things does the following (it runs on the server):</p>\n\n<pre><code>cd /var/www/project\nsvn update\nrm version.php\nsvnversion &gt; version.php\n</code></pre>\n\n<p>2) On projects where SVN is not installed my deployment script is more complex: it creates the version.php file locally, zips the code, uploads and extracts it</p>\n" }, { "answer_id": 1809114, "author": "Andrei Iarus", "author_id": 220075, "author_profile": "https://Stackoverflow.com/users/220075", "pm_score": 0, "selected": false, "text": "<p>Another possibility to do this is to run a cron that executes the steps described in the \"Deploy Process\" (assuming it is a *nix/FreeBSD server).</p>\n" }, { "answer_id": 1809189, "author": "Christoffer", "author_id": 160574, "author_profile": "https://Stackoverflow.com/users/160574", "pm_score": 2, "selected": false, "text": "<p>You could also do it like this:</p>\n\n<pre><code>$status = @shell_exec('svnversion '.realpath(__FILE__));\nif ( preg_match('/\\d+/', $status, $match) ) {\n echo 'Revision: '.$match[0];\n}\n</code></pre>\n" }, { "answer_id": 2374022, "author": "fijiaaron", "author_id": 12982, "author_profile": "https://Stackoverflow.com/users/12982", "pm_score": 2, "selected": false, "text": "<p>See my response to the similar question <em><a href=\"https://stackoverflow.com/questions/975083/mark-svn-export-with-revision/2373900#2373900\">&quot;Mark&quot; svn export with revision</a></em>.</p>\n\n<p>If you capture the revision number when you export you can use:</p>\n\n<pre><code>svn export /path/to/repository | grep ^Exported &gt; revision.txt\n</code></pre>\n\n<p>To strip everything but the revision number, you can pipe it through this sed command:</p>\n\n<pre><code>svn export /path/to/repository | grep ^Exported | sed 's/^[^0-9]\\+\\([0-9]\\+\\).*/\\1/' &gt; revision.txt\n</code></pre>\n" }, { "answer_id": 4832538, "author": "Jonathon Hill", "author_id": 168815, "author_profile": "https://Stackoverflow.com/users/168815", "pm_score": 0, "selected": false, "text": "<p>If performance is an issue, then you could do:</p>\n\n<pre><code>exec('svn info /path/to/repository', $output);\n$svn_ver = (int) trim(substr($output[4], strpos($output[4], ':')));\n</code></pre>\n\n<p>This of course depends on your having done a checkout, and the presence of the svn command.</p>\n" }, { "answer_id": 5816437, "author": "Mark", "author_id": 489960, "author_profile": "https://Stackoverflow.com/users/489960", "pm_score": 2, "selected": false, "text": "<p>Bit late now, but use a Subversion post-commit hook. In your repository's hooks folder, create a shell script like this one:</p>\n\n<pre><code>#!/bin/bash\n\nREPOS=\"$1\"\nREV=\"$2\"\n\ncd /web/root\nrm -f /web/root/templates/base.html\n/usr/bin/svn update\n/bin/sed -i s/REVISION/$REV/ /web/root/templates/base.html\n</code></pre>\n\n<p>This particular example assumes your live site is in /web/root and the development code is held elsewhere. When you commit a dev change, the script deletes the prior live template (to avoid conflict messages), runs the update and replaces occurrences of REVISION in the template with the actual revision number.</p>\n\n<p>More on hooks <a href=\"http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html#svn.reposadmin.create.hooks\" rel=\"nofollow\">here</a></p>\n" }, { "answer_id": 6550918, "author": "Nathan J.B.", "author_id": 808732, "author_profile": "https://Stackoverflow.com/users/808732", "pm_score": 3, "selected": false, "text": "<p>This is how I got it to work.\nIf your server is setup to allow <a href=\"http://php.net/manual/en/function.shell-exec.php\">shell_exec</a> AND you have SVN installed just run:</p>\n\n<pre><code>$revision = `svnversion`;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$revision = shell_exec('svnversion');\n</code></pre>\n" }, { "answer_id": 26094811, "author": "Inpassor", "author_id": 4090262, "author_profile": "https://Stackoverflow.com/users/4090262", "pm_score": 1, "selected": false, "text": "<pre><code>$svn_rev=file_get_contents('/path.to.repository/db/current');\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19929/" ]
I want to have my PHP application labeled with the revision number which it uses, but I don't want to use [CruiseControl](http://en.wikipedia.org/wiki/CruiseControl) or update a file and upload it every time. How should I do it?
SVN keywords is not a good solution. As others pointed out adding $Revision$ in a file only affects **the specific file**, which may not change for a long time. Remembering to "edit" a file (by adding or removing a blank line) before every commit is pointless. You could as well just type the revision by hand. One good way to do it (that I know of) is to have an automated deployment process (which is always a good thing) and using the command svnversion. Here is what I do: Wherever I need the revision I do an include: `<?php include 'version.php'; ?>`. This "version.php" file only has the revision number. Moreover it is not part of the repository (it set to be ignored). Here is how I create it: 1) On projects where SVN is installed on the server, I also use it for deployment. Getting the latest version to the server I have a script that among other things does the following (it runs on the server): ``` cd /var/www/project svn update rm version.php svnversion > version.php ``` 2) On projects where SVN is not installed my deployment script is more complex: it creates the version.php file locally, zips the code, uploads and extracts it
111,460
<p>I'm working on serial port, transmitting and receiving data to some hardware at 8bit data. I would like to store it as string to facilitate comparison, and preset data are stored as string or hex format in xml file. I found out that only when using Encoding.Default which is ANSI encoding then the 8bit data is converted properly and easily reversible. ASCII encoding will only works for 7bit data, and UTF8 or UTF7 doesn't works well too, since I'm using some character from 1-255. Encoding.Default would be just fine, but I read on MSDN that it's dependent on OS codepage setting, which means it might behave differently on different codepage configured. I use GetBytes() and GetString extensively using the Encoding, but would like a failsafe and portable method that works all the time at any configuration. Any idea or better suggestion for this?</p>
[ { "answer_id": 111468, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>Why not just use an array of bytes instead? It would have none of the encoding problems you're likely to suffer with the text approach.</p>\n" }, { "answer_id": 111508, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": -1, "selected": false, "text": "<p>You could use base64 encoding to convert from byte to string and back. No problems with code pages or weird characters that way, and it'll be more space-efficient than hex.</p>\n\n<pre><code>byte[] toEncode; \nstring encoded = System.Convert.ToBase64String(toEncode);\n</code></pre>\n" }, { "answer_id": 111523, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 1, "selected": false, "text": "<p><s>Use the Hebrew codepage for Windows-1255. Its 8 bit.<br/>\nEncoding enc = Encoding.GetEncoding(\"windows-1255\");</s></p>\n\n<p>I missunderstod you when you wrote \"1-255\", thought you where refereing to characters in codepage 1255.</p>\n" }, { "answer_id": 111541, "author": "KovBal", "author_id": 19998, "author_profile": "https://Stackoverflow.com/users/19998", "pm_score": 2, "selected": false, "text": "<p>I think you should use a byte array instead. For comparison you can use some method like this:</p>\n\n<pre><code>static bool CompareRange(byte[] a, byte[] b, int index, int count)\n{\n bool res = true;\n for(int i = index; i &lt; index + count; i++)\n {\n res &amp;= a[i] == b[i];\n }\n return res;\n}\n</code></pre>\n" }, { "answer_id": 111549, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": true, "text": "<p>Latin-1 aka ISO-8859-1 aka codepage 28591 is a useful codepage for this scenario, as it maps values in the range 128-255 unchanged. The following are interchangeable:</p>\n\n<pre><code>Encoding.GetEncoding(28591)\nEncoding.GetEncoding(\"Latin1\")\nEncoding.GetEncoding(\"iso-8859-1\")\n</code></pre>\n\n<p>The following code illustrates the fact that for Latin1, unlike Encoding.Default, all characters in the range 0-255 are mapped unchanged:</p>\n\n<pre><code>static void Main(string[] args)\n{\n\n Console.WriteLine(\"Test Default Encoding returned {0}\", TestEncoding(Encoding.Default));\n Console.WriteLine(\"Test Latin1 Encoding returned {0}\", TestEncoding(Encoding.GetEncoding(\"Latin1\")));\n Console.ReadLine();\n return;\n}\n\nprivate static bool CompareBytes(char[] chars, byte[] bytes)\n{\n bool result = true;\n if (chars.Length != bytes.Length)\n {\n Console.WriteLine(\"Length mismatch {0} bytes and {1} chars\" + bytes.Length, chars.Length);\n return false;\n }\n for (int i = 0; i &lt; chars.Length; i++)\n {\n int charValue = (int)chars[i];\n if (charValue != (int)bytes[i])\n {\n Console.WriteLine(\"Byte at index {0} value {1:X4} does not match char {2:X4}\", i, (int) bytes[i], charValue);\n result = false;\n }\n }\n return result;\n}\nprivate static bool TestEncoding(Encoding encoding)\n{\n byte[] inputBytes = new byte[256];\n for (int i = 0; i &lt; 256; i++)\n {\n inputBytes[i] = (byte) i;\n }\n\n char[] outputChars = encoding.GetChars(inputBytes);\n Console.WriteLine(\"Comparing input bytes and output chars\");\n if (!CompareBytes(outputChars, inputBytes)) return false;\n\n byte[] outputBytes = encoding.GetBytes(outputChars);\n Console.WriteLine(\"Comparing output bytes and output chars\");\n if (!CompareBytes(outputChars, outputBytes)) return false;\n\n return true;\n}\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20007/" ]
I'm working on serial port, transmitting and receiving data to some hardware at 8bit data. I would like to store it as string to facilitate comparison, and preset data are stored as string or hex format in xml file. I found out that only when using Encoding.Default which is ANSI encoding then the 8bit data is converted properly and easily reversible. ASCII encoding will only works for 7bit data, and UTF8 or UTF7 doesn't works well too, since I'm using some character from 1-255. Encoding.Default would be just fine, but I read on MSDN that it's dependent on OS codepage setting, which means it might behave differently on different codepage configured. I use GetBytes() and GetString extensively using the Encoding, but would like a failsafe and portable method that works all the time at any configuration. Any idea or better suggestion for this?
Latin-1 aka ISO-8859-1 aka codepage 28591 is a useful codepage for this scenario, as it maps values in the range 128-255 unchanged. The following are interchangeable: ``` Encoding.GetEncoding(28591) Encoding.GetEncoding("Latin1") Encoding.GetEncoding("iso-8859-1") ``` The following code illustrates the fact that for Latin1, unlike Encoding.Default, all characters in the range 0-255 are mapped unchanged: ``` static void Main(string[] args) { Console.WriteLine("Test Default Encoding returned {0}", TestEncoding(Encoding.Default)); Console.WriteLine("Test Latin1 Encoding returned {0}", TestEncoding(Encoding.GetEncoding("Latin1"))); Console.ReadLine(); return; } private static bool CompareBytes(char[] chars, byte[] bytes) { bool result = true; if (chars.Length != bytes.Length) { Console.WriteLine("Length mismatch {0} bytes and {1} chars" + bytes.Length, chars.Length); return false; } for (int i = 0; i < chars.Length; i++) { int charValue = (int)chars[i]; if (charValue != (int)bytes[i]) { Console.WriteLine("Byte at index {0} value {1:X4} does not match char {2:X4}", i, (int) bytes[i], charValue); result = false; } } return result; } private static bool TestEncoding(Encoding encoding) { byte[] inputBytes = new byte[256]; for (int i = 0; i < 256; i++) { inputBytes[i] = (byte) i; } char[] outputChars = encoding.GetChars(inputBytes); Console.WriteLine("Comparing input bytes and output chars"); if (!CompareBytes(outputChars, inputBytes)) return false; byte[] outputBytes = encoding.GetBytes(outputChars); Console.WriteLine("Comparing output bytes and output chars"); if (!CompareBytes(outputChars, outputBytes)) return false; return true; } ```
111,461
<p>I see a lot of example code for C# classes that does this:</p> <pre><code>public class Point { public int x { get; set; } public int y { get; set; } } </code></pre> <p>Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:</p> <pre><code>public class Point { private int _x; private int _y; public int x { get { return _x; } set { _x = value; } } public int y { get { return _y; } set { _y = value; } } } </code></pre> <p>My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?</p> <pre><code>public class Point { public int x; public int y; } </code></pre> <p>To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.</p>
[ { "answer_id": 111474, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 3, "selected": false, "text": "<p>It encapsulates setting and accessing of those members. If some time from now a developer for the code needs to change logic when a member is accessed or set it can be done without changing the contract of the class.</p>\n" }, { "answer_id": 111476, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 0, "selected": false, "text": "<p>You never know if you might not need some translation of the data later. You are prepared for that if you hide away your members. Users of your class wont notice if you add the translation since the interface remains the same.</p>\n" }, { "answer_id": 111477, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 0, "selected": false, "text": "<p>The biggest difrence is that, if ever you change your internal structure, you can still maintain the getters and setters as is, changing their internal logic without hurting the users of your API.</p>\n" }, { "answer_id": 111484, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 5, "selected": false, "text": "<p>It's also much simpler to change it to this later:</p>\n\n<pre><code>public int x { get; private set; }\n</code></pre>\n" }, { "answer_id": 111493, "author": "Dexter", "author_id": 10717, "author_profile": "https://Stackoverflow.com/users/10717", "pm_score": 7, "selected": true, "text": "<p>I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes.</p>\n\n<p><a href=\"https://blog.codinghorror.com/properties-vs-public-variables/\" rel=\"noreferrer\">Jeff Atwood</a> dealt with this a few years ago. The most important point he retrospectively noted is that changing from a field to a property is a <a href=\"http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx\" rel=\"noreferrer\">breaking change</a> in your code; anything that consumes it must be recompiled to work with the new class interface, so if anything outside of your control is consuming your class you might have problems.</p>\n" }, { "answer_id": 111498, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>If you have to change how you get x and y in this case, you could just add the properties later. This is what I find most confusing. If you use public member variables, you can easily change that to a property later on, and use private variables called _x and _y if you need to store the value internally. </p>\n" }, { "answer_id": 111515, "author": "Rob Pilkington", "author_id": 1623, "author_profile": "https://Stackoverflow.com/users/1623", "pm_score": 3, "selected": false, "text": "<p>The idea is that even if the underlying data structure needs to change, the public interface to the class won't have to be changed.</p>\n\n<p>C# can treat properties and variables differently at times. For example, you <a href=\"http://msdn.microsoft.com/en-us/library/w86s7x04.aspx\" rel=\"noreferrer\">can't pass properties as ref or out parameters</a>. So if you need to change the data structure for some reason and you were using public variables and now you need to use properties, your interface will have to change and now code that accesses property x may not longer compile like it did when it was variable x:</p>\n\n<pre><code>Point pt = new Point();\nif(Int32.TryParse(userInput, out pt.x))\n{\n Console.WriteLine(\"x = {0}\", pt.x);\n Console.WriteLine(\"x must be a public variable! Otherwise, this won't compile.\");\n}\n</code></pre>\n\n<p>Using properties from the start avoids this, and you can feel free to tweak the underlying implementation as much as you need to without breaking client code.</p>\n" }, { "answer_id": 111525, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>AFAIK the generated CIL interface is different. If you change a public member to a property you are changing it's public interface and need to rebuild every file that uses that class. This is not necessary if you only change the implementation of the getters and setters.</p>\n" }, { "answer_id": 111539, "author": "TheZenker", "author_id": 10552, "author_profile": "https://Stackoverflow.com/users/10552", "pm_score": 2, "selected": false, "text": "<p>Also to be considered is the effect of the change to public members when it comes to binding and serialization. Both of these often rely on public properties to retrieve and set values.</p>\n" }, { "answer_id": 111548, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 1, "selected": false, "text": "<p>Maybe just making fields public you could leads you to a more <a href=\"http://www.martinfowler.com/bliki/AnemicDomainModel.html\" rel=\"nofollow noreferrer\">Anemic Domain Model</a>.</p>\n\n<p>Kind Regards</p>\n" }, { "answer_id": 123835, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 0, "selected": false, "text": "<p>Setters and getters are bad in principle (they are a bad OO smell--I'll stop short of saying they are an anti-pattern because they really are necessary sometimes).</p>\n<p>No, there is technically no difference and when I really want to share access to an object these days, I occasionally make it public final instead of adding a getter.</p>\n<p>The way setters and getters were &quot;Sold&quot; is that you might need to know that someone is getting a value or changing one--which only makes sense with primitives.</p>\n<p>Property bag objects like DAOs, DTOs and display objects are excluded from this rule because these aren't objects in a real &quot;OO Design&quot; meaning of the word Object. (You don't think of &quot;Passing Messages&quot; to a DTO or bean--those are simply a pile of attribute/value pairs by design).</p>\n" }, { "answer_id": 777461, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 3, "selected": false, "text": "<p>Setter and Getter enables you to add additional abstraction layer and in pure OOP you should always access the objects via the interface they are providing to the outside world ...</p>\n\n<p>Consider this code, which will save you in asp.net and which it would not be possible without the level of abstraction provided by the setters and getters: </p>\n\n<pre><code>class SomeControl\n{\n\nprivate string _SomeProperty ;\npublic string SomeProperty \n{\n if ( _SomeProperty == null ) \n return (string)Session [ \"SomeProperty\" ] ;\n else \n return _SomeProperty ; \n}\n}\n</code></pre>\n" }, { "answer_id": 1391566, "author": "Nap", "author_id": 121859, "author_profile": "https://Stackoverflow.com/users/121859", "pm_score": 3, "selected": false, "text": "<p>Since auto implemented getters takes the same name for the property and the actual private storage variables. How can you change it in the future? I think the point being said is that use the auto implemented instead of field so that you can change it in the future if in case you need to add logic to getter and setter.</p>\n\n<p>For example:</p>\n\n<pre><code>public string x { get; set; }\n</code></pre>\n\n<p>and for example you already use the x a lot of times and you do not want to break your code.</p>\n\n<p>How do you change the auto getter setter... for example for setter you only allow setting a valid telephone number format... how do you change the code so that only the class is to be change?</p>\n\n<p>My idea is add a new private variable and add the same x getter and setter.</p>\n\n<pre><code>private string _x;\n\npublic string x { \n get {return _x}; \n set {\n if (Datetime.TryParse(value)) {\n _x = value;\n }\n }; \n}\n</code></pre>\n\n<p>Is this what you mean by making it flexible?</p>\n" }, { "answer_id": 1391576, "author": "NotDan", "author_id": 3291, "author_profile": "https://Stackoverflow.com/users/3291", "pm_score": 2, "selected": false, "text": "<p>Also, you can put breakpoints on getters and setters, but you can't on fields. </p>\n" }, { "answer_id": 1391629, "author": "MrLane", "author_id": 150759, "author_profile": "https://Stackoverflow.com/users/150759", "pm_score": 1, "selected": false, "text": "<p>It is also worth noting that you can't make Auto Properties Readonly and you cannot initialise them inline. Both of these are things I would like to see in a future release of .NET, but I believe you can do neither in .NET 4.0.</p>\n\n<p>The only times I use a backing field with properties these days is when my class implements INotifyPropertyChanged and I need to fire the OnPropertyChanged event when a property is changed.</p>\n\n<p>Also in these situations I set the backing fields directly when values are passed in from a constructor (no need to try and fire the OnPropertyChangedEvent (which would be NULL at this time anyway), anywhere else I use the property itself.</p>\n" }, { "answer_id": 58932004, "author": "jihed", "author_id": 11415255, "author_profile": "https://Stackoverflow.com/users/11415255", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>why we dont just use public fields instead of using properties then\n call accessors ( get,set ) when we dont need to make validations ?</p>\n</blockquote>\n\n<ol>\n<li>A property is a member that provides a flexible mechanism to read only or write only</li>\n<li>Properties can be overridden but fields can't be.</li>\n</ol>\n" }, { "answer_id": 59797248, "author": "zar", "author_id": 841330, "author_profile": "https://Stackoverflow.com/users/841330", "pm_score": 0, "selected": false, "text": "<p>Adding getter and setter makes the variable a property as in working in Wpf/C#.</p>\n\n<p>If it's just a public member variable, it's not accessible from XAML because it's not a property (even though its public member variable).</p>\n\n<p>If it has setter and getter, then its accessible from XAML because now its a property.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19688/" ]
I see a lot of example code for C# classes that does this: ``` public class Point { public int x { get; set; } public int y { get; set; } } ``` Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties: ``` public class Point { private int _x; private int _y; public int x { get { return _x; } set { _x = value; } } public int y { get { return _y; } set { _y = value; } } } ``` My question is why. Is there any functional difference between doing the above and just making these members public fields, like below? ``` public class Point { public int x; public int y; } ``` To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.
I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes. [Jeff Atwood](https://blog.codinghorror.com/properties-vs-public-variables/) dealt with this a few years ago. The most important point he retrospectively noted is that changing from a field to a property is a [breaking change](http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx) in your code; anything that consumes it must be recompiled to work with the new class interface, so if anything outside of your control is consuming your class you might have problems.
111,478
<p>Why is it wrong to use <code>std::auto_ptr&lt;&gt;</code> with standard containers?</p>
[ { "answer_id": 111492, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 6, "selected": false, "text": "<p>The <strong>copy semantics</strong> of <code>auto_ptr</code> are not compatible with the containers.</p>\n\n<p>Specifically, copying one <code>auto_ptr</code> to another does not create two equal objects since one has lost its ownership of the pointer.</p>\n\n<p>More specifically, copying an <code>auto_ptr</code> causes one of the copies to let go of the pointer. Which of these remains in the container is not defined. Therefore, you can randomly lose access to pointers if you store <code>auto_ptrs</code> in the containers.</p>\n" }, { "answer_id": 111511, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 4, "selected": false, "text": "<p>The STL containers need to be able to copy the items you store in them, and are designed to expect the original and the copy to be equivalent. auto pointer objects have a completely different contract, whereby copying creates a transfer of ownership. This means that containers of auto_ptr will exhibit strange behaviour, depending on usage.</p>\n\n<p>There is a detailed description of what can go wrong in Effective STL (Scott Meyers) item 8 and also a not-so-detailed description in Effective C++ (Scott Meyers) item 13.</p>\n" }, { "answer_id": 111526, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 4, "selected": false, "text": "<p>STL containers store copies of contained items. When an auto_ptr is copied, it sets the old ptr to null. Many container methods are broken by this behavior.</p>\n" }, { "answer_id": 111531, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 8, "selected": true, "text": "<p>The C++ Standard says that an STL element must be \"copy-constructible\" and \"assignable.\" In other words, an element must be able to be assigned or copied and the two elements are logically independent. <code>std::auto_ptr</code> does not fulfill this requirement.</p>\n\n<p>Take for example this code:</p>\n\n<pre><code>class X\n{\n};\n\nstd::vector&lt;std::auto_ptr&lt;X&gt; &gt; vecX;\nvecX.push_back(new X);\n\nstd::auto_ptr&lt;X&gt; pX = vecX[0]; // vecX[0] is assigned NULL.\n</code></pre>\n\n<p>To overcome this limitation, you should use the <a href=\"http://msdn.microsoft.com/en-us/library/ee410601.aspx\" rel=\"noreferrer\"><code>std::unique_ptr</code></a>, <a href=\"http://msdn.microsoft.com/en-us/library/bb982026.aspx\" rel=\"noreferrer\"><code>std::shared_ptr</code></a> or <a href=\"http://msdn.microsoft.com/en-us/library/bb982126.aspx\" rel=\"noreferrer\"><code>std::weak_ptr</code></a> smart pointers or the boost equivalents if you don't have C++11. <a href=\"http://www.boost.org/doc/libs/1_54_0/libs/smart_ptr/smart_ptr.htm\" rel=\"noreferrer\">Here is the boost library documentation for these smart pointers.</a> </p>\n" }, { "answer_id": 3120715, "author": "Lazer", "author_id": 113124, "author_profile": "https://Stackoverflow.com/users/113124", "pm_score": 5, "selected": false, "text": "<p>Two super excellent articles on the subject:</p>\n\n<ul>\n<li><a href=\"http://ootips.org/yonat/4dev/smart-pointers.html\" rel=\"noreferrer\">Smart Pointers - What, Why, Which?</a></li>\n<li><a href=\"http://www.gotw.ca/gotw/025.htm\" rel=\"noreferrer\">Guru of the Week #25</a></li>\n</ul>\n" }, { "answer_id": 13141169, "author": "Alex Bitek", "author_id": 313113, "author_profile": "https://Stackoverflow.com/users/313113", "pm_score": 2, "selected": false, "text": "<p><em>C++03 Standard (ISO-IEC 14882-2003)</em> says in clause 20.4.5 paragraph 3:</p>\n\n<blockquote>\n <p>[...]\n [<strong>Note: [...]\n auto_ptr does not meet the CopyConstructible and Assignable requirements for Standard Library\n container elements and thus instantiating a Standard Library container\n with an auto_ptr results in undefined behavior. — end note</strong>]</p>\n</blockquote>\n\n<p><em>C++11 Standard (ISO-IEC 14882-2011)</em> says in appendix D.10.1 paragraph 3:</p>\n\n<blockquote>\n <p>[...]\n <strong>Note: [...] Instances of auto_ptr meet the requirements of\n MoveConstructible and MoveAssignable, but do not meet the requirements\n of CopyConstructible and CopyAssignable. — end note ]</strong></p>\n</blockquote>\n\n<p><em>C++14 Standard (ISO-IEC 14882-2014)</em> says in appendix C.4.2\n Annex D: compatibility features: </p>\n\n<blockquote>\n <p><strong><em>Change</em>: The class templates auto_ptr, unary_function, and binary_function, the function templates random_shuffle, and the\n function templates (and their return types) ptr_fun, mem_fun,\n mem_fun_ref, bind1st, and bind2nd are not defined.<br>\n <em>Rationale</em>: Superseded by new features.<br>\n <em>Effect on original feature</em>: Valid C ++ 2014 code that uses these class templates and function templates may fail to compile in this\n International Standard.</strong></p>\n</blockquote>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19129/" ]
Why is it wrong to use `std::auto_ptr<>` with standard containers?
The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. `std::auto_ptr` does not fulfill this requirement. Take for example this code: ``` class X { }; std::vector<std::auto_ptr<X> > vecX; vecX.push_back(new X); std::auto_ptr<X> pX = vecX[0]; // vecX[0] is assigned NULL. ``` To overcome this limitation, you should use the [`std::unique_ptr`](http://msdn.microsoft.com/en-us/library/ee410601.aspx), [`std::shared_ptr`](http://msdn.microsoft.com/en-us/library/bb982026.aspx) or [`std::weak_ptr`](http://msdn.microsoft.com/en-us/library/bb982126.aspx) smart pointers or the boost equivalents if you don't have C++11. [Here is the boost library documentation for these smart pointers.](http://www.boost.org/doc/libs/1_54_0/libs/smart_ptr/smart_ptr.htm)
111,504
<p>I'm trying to create a UDF in <code>SQL Server 2005 Express</code> as below:</p> <pre><code>CREATE FUNCTION [CombineValues] () RETURNS VARCHAR(8000) AS BEGIN DECLARE @CuisineList VARCHAR(8000); RETURN ( SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines ) END </code></pre> <p>Cuisines has the structure:</p> <pre><code>CuisineID INT PK, Cuisine VARCHAR(20) </code></pre> <p>When I try to create the function as above, I get an error: </p> <blockquote> <p>Msg 102, Level 15, State 1, Procedure CombineValues, Line 10 Incorrect syntax near '='.</p> </blockquote> <p>What am I doing wrong?</p>
[ { "answer_id": 111509, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>try changing SELECT to SET and then end your function by SELECT (ing) your @CuisineList</p>\n" }, { "answer_id": 111520, "author": "Donnie Thomas", "author_id": 6939, "author_profile": "https://Stackoverflow.com/users/6939", "pm_score": 0, "selected": false, "text": "<p>Hojou, your suggestion didn't work, but something similar did:</p>\n\n<pre><code>CREATE FUNCTION [CombineValues] ()\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n\nDECLARE @CuisineList VARCHAR(8000);\n\nSELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines;\n\nRETURN \n(\nSELECT @CuisineList\n)\nEND\n</code></pre>\n\n<p>I would like to mark this as the answer, but since I am the one who asked this question, I'm not sure this is appropriate? Any suggestions? Please feel feel to comment.</p>\n" }, { "answer_id": 111592, "author": "TMarshall", "author_id": 8847, "author_profile": "https://Stackoverflow.com/users/8847", "pm_score": 1, "selected": true, "text": "<p>This answer is from the original poster, Wild Thing. Please do not vote it up or down.</p>\n\n<pre><code>CREATE FUNCTION [CombineValues] ()\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n\nDECLARE @CuisineList VARCHAR(8000);\n\nSELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines;\n\nRETURN \n(\nSELECT @CuisineList\n)\nEND\n</code></pre>\n" }, { "answer_id": 112429, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 1, "selected": false, "text": "<p>You need to be careful when using this method. This may not affect you now, for this query, but please keep this in mind for future applications of this method.</p>\n\n<p>The problem occurs when you have a NULL value in your list. When this happens, you will get incorrect results.</p>\n\n<p>For example, if your original table looks like this...</p>\n\n<pre><code>1 Blah\n2 NULL\n3 Foo\n4 Cracker\n</code></pre>\n\n<p>Your function will return Foo, Cracker. The first value, Blah, will be missed by this function call. It is very easy to accommodate this, with a slight alteration to your function, like this...</p>\n\n<pre><code>CREATE FUNCTION [CombineValues] ()\nRETURNS VARCHAR(8000)\nAS\nBEGIN\n\nDECLARE @CuisineList VARCHAR(8000);\n SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + \n CAST(Cuisine AS varchar(20))\n FROM Cuisines\n WHERE Cuisine Is Not NULL\n\nRETURN @CuisineList\nEND\n</code></pre>\n\n<p>By testing for NOT NULL, you will eliminate this potential problem. </p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6939/" ]
I'm trying to create a UDF in `SQL Server 2005 Express` as below: ``` CREATE FUNCTION [CombineValues] () RETURNS VARCHAR(8000) AS BEGIN DECLARE @CuisineList VARCHAR(8000); RETURN ( SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines ) END ``` Cuisines has the structure: ``` CuisineID INT PK, Cuisine VARCHAR(20) ``` When I try to create the function as above, I get an error: > > Msg 102, Level 15, State 1, Procedure CombineValues, Line 10 Incorrect > syntax near '='. > > > What am I doing wrong?
This answer is from the original poster, Wild Thing. Please do not vote it up or down. ``` CREATE FUNCTION [CombineValues] () RETURNS VARCHAR(8000) AS BEGIN DECLARE @CuisineList VARCHAR(8000); SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines; RETURN ( SELECT @CuisineList ) END ```
111,529
<p>Is there any way to create the <em>query parameters</em> for doing a <em>GET request</em> in JavaScript?</p> <p>Just like in Python you have <a href="http://web.archive.org/web/20080926234926/http://docs.python.org:80/lib/module-urllib.html" rel="noreferrer"><code>urllib.urlencode()</code></a>, which takes in a dictionary (or list of two tuples) and creates a string like <code>'var1=value1&amp;var2=value2'</code>.</p>
[ { "answer_id": 111533, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 3, "selected": false, "text": "<p>If you are using <a href=\"http://www.prototypejs.org\" rel=\"noreferrer\">Prototype</a> there is <a href=\"http://www.prototypejs.org/api/form/serialize\" rel=\"noreferrer\">Form.serialize</a></p>\n\n<p>If you are using <a href=\"http://www.jquery.com/\" rel=\"noreferrer\">jQuery</a> there is <a href=\"http://docs.jquery.com/Ajax/serialize\" rel=\"noreferrer\">Ajax/serialize</a></p>\n\n<p>I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.</p>\n" }, { "answer_id": 111537, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": -1, "selected": false, "text": "<p>This <a href=\"http://web.archive.org/web/20120407213044/http://www.phpbuilder.com:80/board/showthread.php?t=10318476\" rel=\"nofollow noreferrer\">thread</a> points to some code for escaping URLs in php. There's <code>escape()</code> and <code>unescape()</code> which will do most of the work, but the you need add a couple extra things.</p>\n\n<pre><code>function urlencode(str) {\nstr = escape(str);\nstr = str.replace('+', '%2B');\nstr = str.replace('%20', '+');\nstr = str.replace('*', '%2A');\nstr = str.replace('/', '%2F');\nstr = str.replace('@', '%40');\nreturn str;\n}\n\nfunction urldecode(str) {\nstr = str.replace('+', ' ');\nstr = unescape(str);\nreturn str;\n}\n</code></pre>\n" }, { "answer_id": 111545, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 9, "selected": true, "text": "<p>Here you go:</p>\n\n<pre><code>function encodeQueryData(data) {\n const ret = [];\n for (let d in data)\n ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));\n return ret.join('&amp;');\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };\nconst querystring = encodeQueryData(data);\n</code></pre>\n" }, { "answer_id": 12040639, "author": "Manav", "author_id": 141220, "author_profile": "https://Stackoverflow.com/users/141220", "pm_score": 6, "selected": false, "text": "<p><strong>functional</strong></p>\n\n<pre><code>function encodeData(data) {\n return Object.keys(data).map(function(key) {\n return [key, data[key]].map(encodeURIComponent).join(\"=\");\n }).join(\"&amp;\");\n} \n</code></pre>\n" }, { "answer_id": 19100387, "author": "Mat Ryer", "author_id": 117601, "author_profile": "https://Stackoverflow.com/users/117601", "pm_score": 3, "selected": false, "text": "<p>We've just released <a href=\"https://github.com/stretchr/arg.js\" rel=\"noreferrer\">arg.js</a>, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:</p>\n\n<pre><code>var querystring = Arg.url({name: \"Mat\", state: \"CO\"});\n</code></pre>\n\n<p>And reading works:</p>\n\n<pre><code>var name = Arg(\"name\");\n</code></pre>\n\n<p>or getting the whole lot:</p>\n\n<pre><code>var params = Arg.all();\n</code></pre>\n\n<p>and if you care about the difference between <code>?query=true</code> and <code>#hash=true</code> then you can use the <code>Arg.query()</code> and <code>Arg.hash()</code> methods.</p>\n" }, { "answer_id": 31599255, "author": "Kirby", "author_id": 266531, "author_profile": "https://Stackoverflow.com/users/266531", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/382818/zabba\">Zabba</a> has provided in a comment on the currently accepted answer a suggestion that to me is the best solution: use <a href=\"http://api.jquery.com/jQuery.param/\" rel=\"noreferrer\">jQuery.param()</a>.</p>\n\n<p>If I use <code>jQuery.param()</code> on the data in the original question, then the code is simply:</p>\n\n<pre><code>const params = jQuery.param({\n var1: 'value',\n var2: 'value'\n});\n</code></pre>\n\n<p>The variable <code>params</code> will be</p>\n\n<pre><code>\"var1=value&amp;var2=value\"\n</code></pre>\n\n<p>For more complicated examples, inputs and outputs, see the <a href=\"http://api.jquery.com/jQuery.param/\" rel=\"noreferrer\">jQuery.param()</a> documentation.</p>\n" }, { "answer_id": 40488487, "author": "Clayton K. N. Passos", "author_id": 3119452, "author_profile": "https://Stackoverflow.com/users/3119452", "pm_score": 2, "selected": false, "text": "<p>A little modification to typescript:</p>\n\n<pre><code> public encodeData(data: any): string {\n return Object.keys(data).map((key) =&gt; {\n return [key, data[key]].map(encodeURIComponent).join(\"=\");\n }).join(\"&amp;\");\n }\n</code></pre>\n" }, { "answer_id": 44273682, "author": "pscl", "author_id": 1628461, "author_profile": "https://Stackoverflow.com/users/1628461", "pm_score": 3, "selected": false, "text": "<p>Just like to revisit this almost 10 year old question. In this era of off-the-shelf programming, your best bet is to set your project up using a dependency manager (<code>npm</code>). There is an entire cottage industry of libraries out there that encode query strings and take care of all the edge cases. This is one of the more popular ones -</p>\n\n<p><a href=\"https://www.npmjs.com/package/query-string\" rel=\"noreferrer\">https://www.npmjs.com/package/query-string</a></p>\n" }, { "answer_id": 49326302, "author": "eaorak", "author_id": 1095213, "author_profile": "https://Stackoverflow.com/users/1095213", "pm_score": 3, "selected": false, "text": "<p>This should do the job:</p>\n\n<pre><code>const createQueryParams = params =&gt; \n Object.keys(params)\n .map(k =&gt; `${k}=${encodeURI(params[k])}`)\n .join('&amp;');\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>const params = { name : 'John', postcode: 'W1 2DL'}\nconst queryParams = createQueryParams(params)\n</code></pre>\n\n<p>Result: </p>\n\n<pre><code>name=John&amp;postcode=W1%202DL\n</code></pre>\n" }, { "answer_id": 50436226, "author": "Przemek", "author_id": 959552, "author_profile": "https://Stackoverflow.com/users/959552", "pm_score": 4, "selected": false, "text": "<h2>ES2017 (ES8)</h2>\n\n<p>Making use of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"noreferrer\"><code>Object.entries()</code></a>, which returns an array of object's <code>[key, value]</code> pairs. For example, for <code>{a: 1, b: 2}</code> it would return <code>[['a', 1], ['b', 2]]</code>. It is not supported (and won't be) only by IE.</p>\n\n<h3>Code:</h3>\n\n<pre><code>const buildURLQuery = obj =&gt;\n Object.entries(obj)\n .map(pair =&gt; pair.map(encodeURIComponent).join('='))\n .join('&amp;');\n</code></pre>\n\n<h3>Example:</h3>\n\n<pre><code>buildURLQuery({name: 'John', gender: 'male'});\n</code></pre>\n\n<h3>Result:</h3>\n\n<pre><code>\"name=John&amp;gender=male\"\n</code></pre>\n" }, { "answer_id": 52028292, "author": "Andrew Palmer", "author_id": 4089018, "author_profile": "https://Stackoverflow.com/users/4089018", "pm_score": 8, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"noreferrer\">URLSearchParams</a> has increasing browser support.</p>\n\n<pre><code>const data = {\n var1: 'value1',\n var2: 'value2'\n};\n\nconst searchParams = new URLSearchParams(data);\n\n// searchParams.toString() === 'var1=value1&amp;var2=value2'\n</code></pre>\n\n<p>Node.js offers the <a href=\"https://nodejs.org/api/querystring.html\" rel=\"noreferrer\">querystring</a> module.</p>\n\n<pre><code>const querystring = require('querystring');\n\nconst data = {\n var1: 'value1',\n var2: 'value2'\n};\n\nconst searchParams = querystring.stringify(data);\n\n// searchParams === 'var1=value1&amp;var2=value2'\n</code></pre>\n" }, { "answer_id": 64260142, "author": "Roman Morozov", "author_id": 13278378, "author_profile": "https://Stackoverflow.com/users/13278378", "pm_score": 0, "selected": false, "text": "<p>I have improved the function of <a href=\"https://stackoverflow.com/a/111545/13278378\">shog9`s</a> to handle array values</p>\n<pre class=\"lang-js prettyprint-override\"><code>function encodeQueryData(data) {\n const ret = [];\n for (let d in data) {\n if (typeof data[d] === 'object' || typeof data[d] === 'array') {\n for (let arrD in data[d]) {\n ret.push(`${encodeURIComponent(d)}[]=${encodeURIComponent(data[d][arrD])}`)\n }\n } else if (typeof data[d] === 'null' || typeof data[d] === 'undefined') {\n ret.push(encodeURIComponent(d))\n } else {\n ret.push(`${encodeURIComponent(d)}=${encodeURIComponent(data[d])}`)\n }\n\n }\n return ret.join('&amp;');\n}\n\n</code></pre>\n<h2>Example</h2>\n<pre class=\"lang-js prettyprint-override\"><code>let data = {\n user: 'Mark'\n fruits: ['apple', 'banana']\n}\n\nencodeQueryData(data) // user=Mark&amp;fruits[]=apple&amp;fruits[]=banana\n</code></pre>\n" }, { "answer_id": 68150539, "author": "EuberDeveloper", "author_id": 10140665, "author_profile": "https://Stackoverflow.com/users/10140665", "pm_score": 0, "selected": false, "text": "<p>By using <a href=\"https://www.npmjs.com/package/queryencoder\" rel=\"nofollow noreferrer\">queryencoder</a>, you can have some nice-to-have options, such custom date formatters, nested objects and decide if a <code>val: true</code> will be just <code>value</code> or <code>value=true</code>.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const { encode } = require('queryencoder');\n\nconst object = {\n date: new Date('1999-04-23')\n};\n\n// The result is 'date=1999-04-23'\nconst queryUrl = encode(object, {\n dateParser: date =&gt; date.toISOString().slice(0, 10)\n});\n</code></pre>\n" }, { "answer_id": 70941990, "author": "Patrick José Pereira", "author_id": 7988054, "author_profile": "https://Stackoverflow.com/users/7988054", "pm_score": 0, "selected": false, "text": "<p>Here is an example:</p>\n<pre><code>let my_url = new URL(&quot;https://stackoverflow.com&quot;)\nmy_url.pathname = &quot;/questions&quot;\n\nconst parameters = {\n title: &quot;just&quot;,\n body: 'test'\n}\n\nObject.entries(parameters).forEach(([name, value]) =&gt; my_url.searchParams.set(name, value))\n\nconsole.log(my_url.href)\n\n</code></pre>\n" }, { "answer_id": 73678107, "author": "Amir Achhodi", "author_id": 11386802, "author_profile": "https://Stackoverflow.com/users/11386802", "pm_score": 2, "selected": false, "text": "<p>The built-in <code>URL</code> class provides a convenient interface for creating and parsing URLs.</p>\n<p>There are no networking methods that require exactly a <code>URL</code> object, strings are good enough. So technically we don’t have to use <code>URL</code>. But sometimes it can be really helpful.</p>\n<p> Example</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>let url = new URL(\"https://google.com/search\");\nurl.searchParams.set('var1', \"value1\");\nurl.searchParams.set('var2', \"value2\");\nurl.searchParams.set('var3', \"value3\");\n\nconsole.log(url)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
Is there any way to create the *query parameters* for doing a *GET request* in JavaScript? Just like in Python you have [`urllib.urlencode()`](http://web.archive.org/web/20080926234926/http://docs.python.org:80/lib/module-urllib.html), which takes in a dictionary (or list of two tuples) and creates a string like `'var1=value1&var2=value2'`.
Here you go: ``` function encodeQueryData(data) { const ret = []; for (let d in data) ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d])); return ret.join('&'); } ``` Usage: ``` const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 }; const querystring = encodeQueryData(data); ```
111,587
<p>How do I name a result group in a Regex? (.Net)</p>
[ { "answer_id": 111594, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": false, "text": "<pre><code>(?&lt;NameOfGroup&gt;[a-z]*)\n</code></pre>\n\n<p>Use the ? syntax like in the sample above.</p>\n" }, { "answer_id": 111607, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<pre><code>(?&lt;first&gt;group)(?'second'group). \n</code></pre>\n\n<p><a href=\"http://www.regular-expressions.info/named.html\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info/named.html</a></p>\n" }, { "answer_id": 111610, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": true, "text": "<pre><code>(?&lt;NAME&gt;EXPRESSION) or (?'NAME'EXPRESSION)\n</code></pre>\n" }, { "answer_id": 2308326, "author": "Fadrian Sudaman", "author_id": 276556, "author_profile": "https://Stackoverflow.com/users/276556", "pm_score": 0, "selected": false, "text": "<pre><code>(?&lt;name&gt;.*)\n</code></pre>\n\n<p>Substitute with whatever you want to call your group. whatever follow is the regular expression you expect to parse and match the result to the group. </p>\n\n<p>See my post this morning on example how to parse a file list for name and number index</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2307865/how-to-get-files-from-1-to-n-in-a-particular-pattern/2308012#2308012\">How to get files from 1 to n in a particular pattern?</a></p>\n" }, { "answer_id": 65258881, "author": "RKTM", "author_id": 14617408, "author_profile": "https://Stackoverflow.com/users/14617408", "pm_score": 0, "selected": false, "text": "<pre><code>(?&lt;name&gt;subpattern)\n</code></pre>\n<p>Where &lt; name &gt; is the name of the group, and subpattern is the code\nFor e.g.</p>\n<pre><code>(?&lt;words&gt;\\w+)\n</code></pre>\n<p>same thing as <code>\\w+</code> but named it &quot;words&quot;</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
How do I name a result group in a Regex? (.Net)
``` (?<NAME>EXPRESSION) or (?'NAME'EXPRESSION) ```
111,630
<p>Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):</p> <pre><code>HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL); </code></pre> <p>I'm using native C++ with the Windows API, no managed code.</p>
[ { "answer_id": 111661, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 3, "selected": true, "text": "<p>I believe it has got nothing to do with your code, but you need to set up a proper <strong>manifest</strong> file to get the themed controls.</p>\n\n<p>Some info here: <a href=\"http://msdn.microsoft.com/en-us/library/aa374191(VS.85).aspx\" rel=\"nofollow noreferrer\">@msdn.com</a> and here: <a href=\"http://blogs.msdn.com/cheller/archive/2006/08/24/718757.aspx\" rel=\"nofollow noreferrer\">@blogs.msdn.com</a></p>\n\n<p>You can see a difference between application with and without manifest here: <a href=\"http://www.heaventools.com/PE_Explorer_resource_XP_Wizard.htm\" rel=\"nofollow noreferrer\">heaventools.com</a></p>\n" }, { "answer_id": 112617, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 3, "selected": false, "text": "<p>To add a manifest to the application you need create a MyApp.manifest file and add it to the application resource file:</p>\n\n<pre><code>//-- This define is normally part of the SDK but define it if this \n//-- is an older version of the SDK.\n#ifndef RT_MANIFEST\n#define RT_MANIFEST 24\n#endif\n\n//-- Add the MyApp XP Manifest file\nCREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST \"MyApp.manifest\"\n</code></pre>\n\n<p>With newer versions of <em>Visual Studio</em> there is a <em>Manifest Tool</em> tab found in the project settings and the <em>Additional Manifest Files</em> field found on this tab can also be used to define the manifest file.</p>\n\n<p>Here is a simple MyApp.manifest file for a Win32 application:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?&gt;\n&lt;assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\"&gt;\n&lt;assemblyIdentity\n version=\"1.0.0.1\"\n processorArchitecture=\"X86\"\n name=\"Microsoft.Windows.MyApp\"\n type=\"win32\"\n/&gt;\n&lt;description&gt;MyApp&lt;/description&gt;\n&lt;/assembly&gt;\n</code></pre>\n\n<p>If you application depends on the other dlls these details can also be added to the manifest and Windows will use this information to make sure your application always uses the correct versions of these dependent dlls.</p>\n\n<p>For example here are the manifest dependency details for the common control and version 8.0 C runtime libraries:</p>\n\n<pre><code>&lt;dependentAssembly&gt;\n &lt;assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.Windows.Common-Controls\"\n version=\"6.0.0.0\"\n processorArchitecture=\"X86\"\n publicKeyToken=\"6595b64144ccf1df\"\n language=\"*\"\n /&gt;\n&lt;/dependentAssembly&gt;\n&lt;dependentAssembly&gt;\n &lt;assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.VC80.CRT\"\n version=\"8.0.50608.0\"\n processorArchitecture=\"x86\"\n publicKeyToken=\"1fc8b3b9a1e18e3b\" /&gt;\n&lt;/dependentAssembly&gt;\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467/" ]
Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment): ``` HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL); ``` I'm using native C++ with the Windows API, no managed code.
I believe it has got nothing to do with your code, but you need to set up a proper **manifest** file to get the themed controls. Some info here: [@msdn.com](http://msdn.microsoft.com/en-us/library/aa374191(VS.85).aspx) and here: [@blogs.msdn.com](http://blogs.msdn.com/cheller/archive/2006/08/24/718757.aspx) You can see a difference between application with and without manifest here: [heaventools.com](http://www.heaventools.com/PE_Explorer_resource_XP_Wizard.htm)
111,687
<p>Is it absolutely critical that I always close Syslog when I'm done using it? Is there a huge negative impact from not doing so?</p> <p>If it turns out that I definitely need to, what's a good way to do it? I'm opening Syslog in my class constructor and I don't see a way to do class destructors in Ruby, and currently have something resembling this:</p> <pre><code>class Foo def initialize @@log = Syslog.open("foo") end end </code></pre> <p>I don't immediately see the place where the <code>Syslog.close</code> call should be, but what do you recommend?</p>
[ { "answer_id": 111724, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": true, "text": "<p>The open method accepts a block. Do something like this:</p>\n\n<pre><code>class Foo\n def do_something\n Syslog.open do\n # work with the syslog here\n end\n end\nend\n</code></pre>\n" }, { "answer_id": 111805, "author": "whoisjake", "author_id": 2609, "author_profile": "https://Stackoverflow.com/users/2609", "pm_score": 1, "selected": false, "text": "<p>It looks like you're opening it as a class variable... so the proper way would be to do...</p>\n\n<pre><code>class Foo\n def initialize\n @@log = Syslog.open(\"foo\")\n end\n\n def Foo.finalize(id)\n @@log.close if @@log\n end\nend\n</code></pre>\n\n<p>Though this is not necesssarily predictable or supported. It's the way to do it if you're going to keep the code the way you do.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
Is it absolutely critical that I always close Syslog when I'm done using it? Is there a huge negative impact from not doing so? If it turns out that I definitely need to, what's a good way to do it? I'm opening Syslog in my class constructor and I don't see a way to do class destructors in Ruby, and currently have something resembling this: ``` class Foo def initialize @@log = Syslog.open("foo") end end ``` I don't immediately see the place where the `Syslog.close` call should be, but what do you recommend?
The open method accepts a block. Do something like this: ``` class Foo def do_something Syslog.open do # work with the syslog here end end end ```
111,700
<p>It's the weekend, so I relax from spending all week programming by writing a hobby project.</p> <p>I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below)</p> <p>I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes.</p> <p>I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory.</p> <p>The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, </p> <pre><code>0 - BRK 1 - ORA (D,X) 2 - COP b </code></pre> <p>etc</p> <p>However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. </p> <p>Is anyone familiar with this CPU's memory model?</p> <p>EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here.</p> <p><strong>EDIT:</strong> Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :)</p> <p>I uploaded the source:</p> <p><a href="https://archive.codeplex.com/?p=cpu6502" rel="nofollow noreferrer">https://archive.codeplex.com/?p=cpu6502</a></p> <p>If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :)</p>
[ { "answer_id": 111737, "author": "Brendan Kidwell", "author_id": 13958, "author_profile": "https://Stackoverflow.com/users/13958", "pm_score": 1, "selected": false, "text": "<p>This book might help: <a href=\"http://www.atariarchives.org/mlb/\" rel=\"nofollow noreferrer\">http://www.atariarchives.org/mlb/</a></p>\n\n<p>Also, try examing any other 6502 aseembler/simulator/debugger out there to see how Assembly gets coded as Machine Language.</p>\n" }, { "answer_id": 111742, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 5, "selected": true, "text": "<p>The opcode takes one byte, and the operands are in the following bytes. Check out the byte size column <a href=\"http://www.atariarchives.org/2bml/chapter_10.php\" rel=\"noreferrer\">here</a>, for instance.</p>\n" }, { "answer_id": 111754, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<p>If you look into references like <a href=\"http://www.atarimax.com/jindroush.atari.org/aopc.html\" rel=\"nofollow noreferrer\">http://www.atarimax.com/jindroush.atari.org/aopc.html</a>, you will see that each opcode has an encoding specified as:</p>\n\n<pre><code>HEX LEN TIM\n</code></pre>\n\n<p>The HEX is your 1-byte opcode. Immediately following it is LEN bytes of its argument. Consult the reference to see what those arguments are. The TIM data is important for emulators - it is the number of clock cycles this instruction takes to execute. You will need this to get your timing correct.</p>\n\n<p>These values (LEN, TIM) are not encoded in the opcode itself. You need to store this data in your program loader/executer. It's just a big lookup table. Or you can define a mini-language to encode the data and reader.</p>\n" }, { "answer_id": 111777, "author": "gbarry", "author_id": 19512, "author_profile": "https://Stackoverflow.com/users/19512", "pm_score": 1, "selected": false, "text": "<p>The 6502 manuals are on the Web, at various history sites. The KIM-1 shipped with them. Maybe more in them than you need to know. </p>\n" }, { "answer_id": 513897, "author": "stu", "author_id": 12386, "author_profile": "https://Stackoverflow.com/users/12386", "pm_score": 0, "selected": false, "text": "<p>The apple II roms included a dissassembler, I think that's what it was called, and it would show you in a nice format the hex opcodes and the 3 character opcode and the operands.</p>\n\n<p>So given how little memory was available, they managed to shove in the operand byte count (always 0, 1 or 2) the 3 character opcode for the entire 6502 instruction set into a really small space, because there's really not that much of it.</p>\n\n<p>If you can dig up an apple II rom, you can just cut and paste from there...</p>\n" }, { "answer_id": 49349585, "author": "nenchev", "author_id": 1322108, "author_profile": "https://Stackoverflow.com/users/1322108", "pm_score": 0, "selected": false, "text": "<p>The 6502 has different addressing modes, the same instruction has several different opcodes depending on it's addressing mode. Take a look at the following links which describes the different ways a 6502 can retrieve data from memory, or directly out of ROM.</p>\n\n<p><a href=\"http://obelisk.me.uk/6502/addressing.html#IMM\" rel=\"nofollow noreferrer\">http://obelisk.me.uk/6502/addressing.html#IMM</a></p>\n" }, { "answer_id": 55264610, "author": "i486", "author_id": 2417459, "author_profile": "https://Stackoverflow.com/users/2417459", "pm_score": 1, "selected": false, "text": "<p>This is better - 6502 Instruction Set matrix:</p>\n\n<p><a href=\"https://www.masswerk.at/6502/6502_instruction_set.html\" rel=\"nofollow noreferrer\">https://www.masswerk.at/6502/6502_instruction_set.html</a></p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
It's the weekend, so I relax from spending all week programming by writing a hobby project. I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below) I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes. I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory. The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, ``` 0 - BRK 1 - ORA (D,X) 2 - COP b ``` etc However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. Is anyone familiar with this CPU's memory model? EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here. **EDIT:** Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :) I uploaded the source: <https://archive.codeplex.com/?p=cpu6502> If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :)
The opcode takes one byte, and the operands are in the following bytes. Check out the byte size column [here](http://www.atariarchives.org/2bml/chapter_10.php), for instance.
111,769
<p>I searched the net and handbook, but I only managed to learn what is the masked package, and not how to install it. I did find some commands, but they don't seem to work on 2008 (looking at it, it seems those are for earlier versions). I have something like this:</p> <pre><code>localhost ~ # emerge flamerobin Calculating dependencies !!! All ebuilds that could satisfy "dev-db/flamerobin" have been masked. !!! One of the following masked packages is required to complete your request: - dev-db/flamerobin-0.8.6 (masked by: ~x86 keyword) - dev-db/flamerobin-0.8.3 (masked by: ~x86 keyword) </code></pre> <p>I would like to install version 0.8.6, but don't know how? I found some instructions, but they tell me to edit or write to some files under /etc/portage. However, I don't have /etc/portage on my system:</p> <pre><code>localhost ~ # ls /etc/portage ls: cannot access /etc/portage: No such file or directory </code></pre>
[ { "answer_id": 111779, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Simply mkdir /etc/portage and edit as mentioned here: <a href=\"http://gentoo-wiki.com/TIP_Dealing_with_masked_packages#But_you_want_to_install_the_package_anyway\" rel=\"nofollow noreferrer\">http://gentoo-wiki.com/TIP_Dealing_with_masked_packages#But_you_want_to_install_the_package_anyway</a>...</p>\n" }, { "answer_id": 455780, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 3, "selected": false, "text": "<p>There are two different kinds of masks in gentoo. Keyword masks and package masks. A keyword mask means that the package is either not supported (or untested) by your architecture, or still in testing. A package mask means that the package is masked for another reason (and for most users it is not smart to unmask). The solutions are:</p>\n\n<ul>\n<li>Add a line to <code>/etc/portage/package.keywords</code> (Check <code>man portage</code> in the <code>package.keywords</code> section). This is for the keyword problems.</li>\n<li>Add a line to <code>/etc/portage/package.unmask</code> for \"package.mask\" problems (you can also use package.mask for the converse). This is in the same man file, under the section <code>package.unmask</code>. I advise to use versioned atoms here to avoid shooting in your own foot with really broken future versions a couple of months down the line.</li>\n</ul>\n" }, { "answer_id": 4129388, "author": "Hans", "author_id": 485416, "author_profile": "https://Stackoverflow.com/users/485416", "pm_score": 2, "selected": false, "text": "<p>These days there's also a more 'automated' solution, called \"autounmask\". No more file editing needed to unmask!</p>\n\n<p>The great benefit of the package is, it also unmasks / handles keywords of dependencies if needed. It's provided in the package app-portage/autounmask.</p>\n\n<p><em>/etc/portage/package.keywords</em> and<br>\n<em>/etc/portage/package.unmask</em> </p>\n\n<p>can be directories as well nowadays (but autounmask handles single files as well). In those directories, multiple can place multiple \"autounmask\" files, one file in each dir per \"unmask\"-package. If you use single files instead of dirs, 'autounmask' will place some kind of header / footer, and this way it becomes easy to remove \"unmasks\" if wanted.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
I searched the net and handbook, but I only managed to learn what is the masked package, and not how to install it. I did find some commands, but they don't seem to work on 2008 (looking at it, it seems those are for earlier versions). I have something like this: ``` localhost ~ # emerge flamerobin Calculating dependencies !!! All ebuilds that could satisfy "dev-db/flamerobin" have been masked. !!! One of the following masked packages is required to complete your request: - dev-db/flamerobin-0.8.6 (masked by: ~x86 keyword) - dev-db/flamerobin-0.8.3 (masked by: ~x86 keyword) ``` I would like to install version 0.8.6, but don't know how? I found some instructions, but they tell me to edit or write to some files under /etc/portage. However, I don't have /etc/portage on my system: ``` localhost ~ # ls /etc/portage ls: cannot access /etc/portage: No such file or directory ```
Simply mkdir /etc/portage and edit as mentioned here: <http://gentoo-wiki.com/TIP_Dealing_with_masked_packages#But_you_want_to_install_the_package_anyway>...
111,792
<p>For example:</p> <pre><code>root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 }); </code></pre> <p>or:</p> <pre><code>root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 }); </code></pre>
[ { "answer_id": 111803, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 3, "selected": true, "text": "<p>I've done it both ways.. IMO it depends on the complexity of the initialization.</p>\n\n<p>If it is simple 2 or 3 properties I will initialize on one line generally, but if i'm setting up an object with values for insertion into a database or something that has alot of properties i'll break it out like your second example.</p>\n\n<pre><code>Income income = new Income\n{\n Initials = something,\n CheckNumber = something,\n CheckDate = something,\n BranchNumber = something\n};\n</code></pre>\n\n<p>or</p>\n\n<pre><code>return new Report.ReportData { ReportName = something, Formulas = something};\n</code></pre>\n" }, { "answer_id": 111807, "author": "Joannes Vermorel", "author_id": 18858, "author_profile": "https://Stackoverflow.com/users/18858", "pm_score": 1, "selected": false, "text": "<p>Both notations are fine. I would simply suggest to use the first (1-line) notation whenever your line stay within 100 characters, and switch to the second (multi-line) notation whenever the expression is longer.</p>\n" }, { "answer_id": 111836, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "<p>For longer stuff I do it this way:</p>\n\n<pre><code>root.Nodes.Add(new TNode() {\n Foo1 = bar1, \n Foo2 = bar2, \n Foo3 = bar3\n});\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
For example: ``` root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 }); ``` or: ``` root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 }); ```
I've done it both ways.. IMO it depends on the complexity of the initialization. If it is simple 2 or 3 properties I will initialize on one line generally, but if i'm setting up an object with values for insertion into a database or something that has alot of properties i'll break it out like your second example. ``` Income income = new Income { Initials = something, CheckNumber = something, CheckDate = something, BranchNumber = something }; ``` or ``` return new Report.ReportData { ReportName = something, Formulas = something}; ```
111,866
<p>In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object?</p> <p>Thanks,</p> <p>Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do;</p> <pre><code>iterator it = someList.begin(); while (it != someList.end()) { if (shouldRemove(it)) it = someList.erase(it); } </code></pre>
[ { "answer_id": 111890, "author": "Nathan Kinsinger", "author_id": 20045, "author_profile": "https://Stackoverflow.com/users/20045", "pm_score": 3, "selected": false, "text": "<p>Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.</p>\n" }, { "answer_id": 111893, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 1, "selected": false, "text": "<p>Why don't you add the objects to be removed to another NSMutableArray. When you are finished iterating, you can remove the objects that you have collected.</p>\n" }, { "answer_id": 111895, "author": "Jens Ayton", "author_id": 6443, "author_profile": "https://Stackoverflow.com/users/6443", "pm_score": 4, "selected": false, "text": "<p>Either use loop counting down over indices:</p>\n\n<pre><code>for (NSInteger i = array.count - 1; i &gt;= 0; --i) {\n</code></pre>\n\n<p>or make a copy with the objects you want to keep.</p>\n\n<p>In particular, do not use a <code>for (id object in array)</code> loop or <code>NSEnumerator</code>.</p>\n" }, { "answer_id": 111905, "author": "Pokot0", "author_id": 20042, "author_profile": "https://Stackoverflow.com/users/20042", "pm_score": 3, "selected": false, "text": "<p>this should do it:</p>\n\n<pre><code> NSMutableArray* myArray = ....;\n\n int i;\n for(i=0; i&lt;[myArray count]; i++) {\n id element = [myArray objectAtIndex:i];\n if(element == ...) {\n [myArray removeObjectAtIndex:i];\n i--;\n }\n }\n</code></pre>\n\n<p>hope this helps...</p>\n" }, { "answer_id": 112101, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>In a more declarative way, depending on the criteria matching the items to remove you could use:</p>\n\n<pre><code>[theArray filterUsingPredicate:aPredicate]\n</code></pre>\n\n<p>@Nathan should be very efficient</p>\n" }, { "answer_id": 112194, "author": "Cyber Oliveira", "author_id": 9793, "author_profile": "https://Stackoverflow.com/users/9793", "pm_score": 1, "selected": false, "text": "<p>How about swapping the elements you want to delete with the 'n'th element, 'n-1'th element and so on?</p>\n\n<p>When you're done you resize the array to 'previous size - number of swaps'</p>\n" }, { "answer_id": 112519, "author": "Christopher Ashworth", "author_id": 20021, "author_profile": "https://Stackoverflow.com/users/20021", "pm_score": 10, "selected": true, "text": "<p>For clarity I like to make an initial loop where I collect the items to delete. Then I delete them. Here's a sample using Objective-C 2.0 syntax:</p>\n\n<pre><code>NSMutableArray *discardedItems = [NSMutableArray array];\n\nfor (SomeObjectClass *item in originalArrayOfItems) {\n if ([item shouldBeDiscarded])\n [discardedItems addObject:item];\n}\n\n[originalArrayOfItems removeObjectsInArray:discardedItems];\n</code></pre>\n\n<p>Then there is no question about whether indices are being updated correctly, or other little bookkeeping details.</p>\n\n<p>Edited to add:</p>\n\n<p>It's been noted in other answers that the inverse formulation should be faster. i.e. If you iterate through the array and compose a new array of objects to keep, instead of objects to discard. That may be true (although what about the memory and processing cost of allocating a new array, and discarding the old one?) but even if it's faster it may not be as big a deal as it would be for a naive implementation, because NSArrays do not behave like \"normal\" arrays. They talk the talk but they walk a different walk. <a href=\"http://ridiculousfish.com/blog/posts/array.html\" rel=\"noreferrer\">See a good analysis here:</a></p>\n\n<p>The inverse formulation may be faster, but I've never needed to care whether it is, because the above formulation has always been fast enough for my needs.</p>\n\n<p>For me the take-home message is to use whatever formulation is clearest to you. Optimize only if necessary. I personally find the above formulation clearest, which is why I use it. But if the inverse formulation is clearer to you, go for it.</p>\n" }, { "answer_id": 113258, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 1, "selected": false, "text": "<p>If all objects in your array are unique or you want to remove all occurrences of an object when found, you could fast enumerate on an array copy and use [NSMutableArray removeObject:] to remove the object from the original.</p>\n\n<pre><code>NSMutableArray *myArray;\nNSArray *myArrayCopy = [NSArray arrayWithArray:myArray];\n\nfor (NSObject *anObject in myArrayCopy) {\n if (shouldRemove(anObject)) {\n [myArray removeObject:anObject];\n }\n}\n</code></pre>\n" }, { "answer_id": 126088, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 5, "selected": false, "text": "<p>Some of the other answers would have poor performance on very large arrays, because methods like <code>removeObject:</code> and <code>removeObjectsInArray:</code> involve doing a linear search of the receiver, which is a waste because you already know where the object is. Also, any call to <code>removeObjectAtIndex:</code> will have to copy values from the index to the end of the array up by one slot at a time.</p>\n\n<p>More efficient would be the following:</p>\n\n<pre><code>NSMutableArray *array = ...\nNSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];\nfor (id object in array) {\n if (! shouldRemove(object)) {\n [itemsToKeep addObject:object];\n }\n}\n[array setArray:itemsToKeep];\n</code></pre>\n\n<p>Because we set the capacity of <code>itemsToKeep</code>, we don't waste any time copying values during a resize. We don't modify the array in place, so we are free to use Fast Enumeration. Using <code>setArray:</code> to replace the contents of <code>array</code> with <code>itemsToKeep</code> will be efficient. Depending on your code, you could even replace the last line with:</p>\n\n<pre><code>[array release];\narray = [itemsToKeep retain];\n</code></pre>\n\n<p>So there isn't even a need to copy values, only swap a pointer.</p>\n" }, { "answer_id": 129942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>You can use NSpredicate to remove items from your mutable array. This requires no for loops.</p>\n\n<p>For example if you have an NSMutableArray of names, you can create a predicate like this one:</p>\n\n<pre><code>NSPredicate *caseInsensitiveBNames = \n[NSPredicate predicateWithFormat:@\"SELF beginswith[c] 'b'\"];\n</code></pre>\n\n<p>The following line will leave you with an array that contains only names starting with b.</p>\n\n<pre><code>[namesArray filterUsingPredicate:caseInsensitiveBNames];\n</code></pre>\n\n<p>If you have trouble creating the predicates you need, use this <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/Predicates/predicates.html\" rel=\"noreferrer\">apple developer link</a>.</p>\n" }, { "answer_id": 1019929, "author": "Corey Floyd", "author_id": 48311, "author_profile": "https://Stackoverflow.com/users/48311", "pm_score": 6, "selected": false, "text": "<p>One more variation. So you get readability and good performace:</p>\n\n<pre><code>NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];\nSomeObjectClass *item;\nNSUInteger index = 0;\n\nfor (item in originalArrayOfItems) {\n if ([item shouldBeDiscarded])\n [discardedItems addIndex:index];\n index++;\n}\n\n[originalArrayOfItems removeObjectsAtIndexes:discardedItems];\n</code></pre>\n" }, { "answer_id": 3065805, "author": "Kaiser", "author_id": 369808, "author_profile": "https://Stackoverflow.com/users/369808", "pm_score": 1, "selected": false, "text": "<p>benzado's anwser above is what you should do for preformace. In one of my applications removeObjectsInArray took a running time of 1 minute, just adding to a new array took .023 seconds. </p>\n" }, { "answer_id": 8972160, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 1, "selected": false, "text": "<p>I define a category that lets me filter using a block, like this:</p>\n\n<pre><code>@implementation NSMutableArray (Filtering)\n\n- (void)filterUsingTest:(BOOL (^)(id obj, NSUInteger idx))predicate {\n NSMutableIndexSet *indexesFailingTest = [[NSMutableIndexSet alloc] init];\n\n NSUInteger index = 0;\n for (id object in self) {\n if (!predicate(object, index)) {\n [indexesFailingTest addIndex:index];\n }\n ++index;\n }\n [self removeObjectsAtIndexes:indexesFailingTest];\n\n [indexesFailingTest release];\n}\n\n@end\n</code></pre>\n\n<p>which can then be used like this:</p>\n\n<pre><code>[myMutableArray filterUsingTest:^BOOL(id obj, NSUInteger idx) {\n return [self doIWantToKeepThisObject:obj atIndex:idx];\n}];\n</code></pre>\n" }, { "answer_id": 12020354, "author": "zavié", "author_id": 284811, "author_profile": "https://Stackoverflow.com/users/284811", "pm_score": 4, "selected": false, "text": "<p>For iOS 4+ or OS X 10.6+, Apple added <code>passingTest</code> series of APIs in <code>NSMutableArray</code>, like <code>– indexesOfObjectsPassingTest:</code>. A solution with such API would be:</p>\n\n<pre><code>NSIndexSet *indexesToBeRemoved = [someList indexesOfObjectsPassingTest:\n ^BOOL(id obj, NSUInteger idx, BOOL *stop) {\n return [self shouldRemove:obj];\n}];\n[someList removeObjectsAtIndexes:indexesToBeRemoved];\n</code></pre>\n" }, { "answer_id": 16905821, "author": "user1032657", "author_id": 1032657, "author_profile": "https://Stackoverflow.com/users/1032657", "pm_score": 4, "selected": false, "text": "<p>I did a performance test using 4 different methods. Each test iterated through all elements in a 100,000 element array, and removed every 5th item. The results did not vary much with/ without optimization. These were done on an iPad 4:</p>\n\n<p>(1) <code>removeObjectAtIndex:</code> -- <strong>271 ms</strong></p>\n\n<p>(2) <code>removeObjectsAtIndexes:</code> -- <strong>1010 ms</strong> (because building the index set takes ~700 ms; otherwise this is basically the same as calling removeObjectAtIndex: for each item)</p>\n\n<p>(3) <code>removeObjects:</code> -- <strong>326 ms</strong></p>\n\n<p>(4) make a new array with objects passing the test -- <strong>17 ms</strong></p>\n\n<p>So, creating a new array is by far the fastest. The other methods are all comparable, except that using removeObjectsAtIndexes: will be worse with more items to remove, because of the time needed to build the index set.</p>\n" }, { "answer_id": 18456913, "author": "Hot Licks", "author_id": 581994, "author_profile": "https://Stackoverflow.com/users/581994", "pm_score": 6, "selected": false, "text": "<p>This is a very simple problem. You just iterate backwards:</p>\n\n<pre><code>for (NSInteger i = array.count - 1; i &gt;= 0; i--) {\n ElementType* element = array[i];\n if ([element shouldBeRemoved]) {\n [array removeObjectAtIndex:i];\n }\n}\n</code></pre>\n\n<p>This is a very common pattern.</p>\n" }, { "answer_id": 18478113, "author": "Matjan", "author_id": 1137246, "author_profile": "https://Stackoverflow.com/users/1137246", "pm_score": 3, "selected": false, "text": "<p>Here's the easy and clean way. I like to duplicate my array right in the fast enumeration call:</p>\n\n<pre><code>for (LineItem *item in [NSArray arrayWithArray:self.lineItems]) \n{\n if ([item.toBeRemoved boolValue] == YES) \n {\n [self.lineItems removeObject:item];\n }\n}\n</code></pre>\n\n<p>This way you enumerate through a copy of the array being deleted from, both holding the same objects. An NSArray holds object pointers only so this is totally fine memory/performance wise.</p>\n" }, { "answer_id": 18478301, "author": "vikingosegundo", "author_id": 106435, "author_profile": "https://Stackoverflow.com/users/106435", "pm_score": 4, "selected": false, "text": "<p>Nowadays you can use reversed block-based enumeration. A simple example code:</p>\n\n<pre><code>NSMutableArray *array = [@[@{@\"name\": @\"a\", @\"shouldDelete\": @(YES)},\n @{@\"name\": @\"b\", @\"shouldDelete\": @(NO)},\n @{@\"name\": @\"c\", @\"shouldDelete\": @(YES)},\n @{@\"name\": @\"d\", @\"shouldDelete\": @(NO)}] mutableCopy];\n\n[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if([obj[@\"shouldDelete\"] boolValue])\n [array removeObjectAtIndex:idx];\n}];\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>(\n {\n name = b;\n shouldDelete = 0;\n },\n {\n name = d;\n shouldDelete = 0;\n }\n)\n</code></pre>\n\n<hr>\n\n<p>another option with just one line of code:</p>\n\n<pre><code>[array filterUsingPredicate:[NSPredicate predicateWithFormat:@\"shouldDelete == NO\"]];\n</code></pre>\n" }, { "answer_id": 31913311, "author": "aremvee", "author_id": 1542458, "author_profile": "https://Stackoverflow.com/users/1542458", "pm_score": 0, "selected": false, "text": "<p>Iterating backwards-ly was my favourite for years , but for a long time I never encountered the case where the 'deepest' ( highest count) object was removed first. Momentarily before the pointer moves on to the next index there ain't anything and it crashes. </p>\n\n<p>Benzado's way is the closest to what i do now but I never realised there would be the stack reshuffle after every remove.</p>\n\n<p>under Xcode 6 this works</p>\n\n<pre><code>NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];\n\n for (id object in array)\n {\n if ( [object isNotEqualTo:@\"whatever\"]) {\n [itemsToKeep addObject:object ];\n }\n }\n array = nil;\n array = [[NSMutableArray alloc]initWithArray:itemsToKeep];\n</code></pre>\n" }, { "answer_id": 32246289, "author": "Werner Altewischer", "author_id": 480467, "author_profile": "https://Stackoverflow.com/users/480467", "pm_score": 1, "selected": false, "text": "<p>A nicer implementation could be to use the category method below on NSMutableArray.</p>\n\n<pre><code>@implementation NSMutableArray(BMCommons)\n\n- (void)removeObjectsWithPredicate:(BOOL (^)(id obj))predicate {\n if (predicate != nil) {\n NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:self.count];\n for (id obj in self) {\n BOOL shouldRemove = predicate(obj);\n if (!shouldRemove) {\n [newArray addObject:obj];\n }\n }\n [self setArray:newArray];\n }\n}\n\n@end\n</code></pre>\n\n<p>The predicate block can be implemented to do processing on each object in the array. If the predicate returns true the object is removed.</p>\n\n<p>An example for a date array to remove all dates that lie in the past:</p>\n\n<pre><code>NSMutableArray *dates = ...;\n[dates removeObjectsWithPredicate:^BOOL(id obj) {\n NSDate *date = (NSDate *)obj;\n return [date timeIntervalSinceNow] &lt; 0;\n}];\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object? Thanks, Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do; ``` iterator it = someList.begin(); while (it != someList.end()) { if (shouldRemove(it)) it = someList.erase(it); } ```
For clarity I like to make an initial loop where I collect the items to delete. Then I delete them. Here's a sample using Objective-C 2.0 syntax: ``` NSMutableArray *discardedItems = [NSMutableArray array]; for (SomeObjectClass *item in originalArrayOfItems) { if ([item shouldBeDiscarded]) [discardedItems addObject:item]; } [originalArrayOfItems removeObjectsInArray:discardedItems]; ``` Then there is no question about whether indices are being updated correctly, or other little bookkeeping details. Edited to add: It's been noted in other answers that the inverse formulation should be faster. i.e. If you iterate through the array and compose a new array of objects to keep, instead of objects to discard. That may be true (although what about the memory and processing cost of allocating a new array, and discarding the old one?) but even if it's faster it may not be as big a deal as it would be for a naive implementation, because NSArrays do not behave like "normal" arrays. They talk the talk but they walk a different walk. [See a good analysis here:](http://ridiculousfish.com/blog/posts/array.html) The inverse formulation may be faster, but I've never needed to care whether it is, because the above formulation has always been fast enough for my needs. For me the take-home message is to use whatever formulation is clearest to you. Optimize only if necessary. I personally find the above formulation clearest, which is why I use it. But if the inverse formulation is clearer to you, go for it.
111,928
<p>I can print with <code>printf</code> as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?</p> <p>I am running gcc.</p> <pre><code>printf(&quot;%d %x %o\n&quot;, 10, 10, 10); //prints &quot;10 A 12\n&quot; print(&quot;%b\n&quot;, 10); // prints &quot;%b\n&quot; </code></pre>
[ { "answer_id": 111938, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 3, "selected": false, "text": "<p>There is no formatting function in the C standard library to output binary like that. All the format operations the printf family supports are towards human readable text.</p>\n" }, { "answer_id": 111946, "author": "rlerallut", "author_id": 20055, "author_profile": "https://Stackoverflow.com/users/20055", "pm_score": 3, "selected": false, "text": "<p>Some runtimes support \"%b\" although that is not a standard.</p>\n\n<p>Also see here for an interesting discussion:</p>\n\n<p><a href=\"http://bytes.com/forum/thread591027.html\" rel=\"noreferrer\">http://bytes.com/forum/thread591027.html</a></p>\n\n<p>HTH</p>\n" }, { "answer_id": 112084, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 2, "selected": false, "text": "<p>No standard and portable way.</p>\n\n<p>Some implementations provide <a href=\"http://en.wikibooks.org/wiki/C_Programming/C_Reference/stdlib.h/itoa\" rel=\"nofollow noreferrer\">itoa()</a>, but it's not going to be in most, and it has a somewhat crummy interface. But the code is behind the link and should let you implement your own formatter pretty easily.</p>\n" }, { "answer_id": 112947, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 7, "selected": false, "text": "<p>There isn't a binary conversion specifier in glibc normally.</p>\n\n<p>It is possible to add custom conversion types to the printf() family of functions in glibc. See <A HREF=\"http://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html\" rel=\"noreferrer\"> register_printf_function</A> for details. You could add a custom %b conversion for your own use, if it simplifies the application code to have it available.</p>\n\n<p>Here is an <a href=\"http://codingrelic.geekhold.com/2008/12/printf-acular.html\" rel=\"noreferrer\">example</a> of how to implement a custom printf formats in glibc.</p>\n" }, { "answer_id": 112956, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 7, "selected": false, "text": "<p>Here is a quick hack to demonstrate techniques to do what you want.</p>\n<pre><code>#include &lt;stdio.h&gt; /* printf */\n#include &lt;string.h&gt; /* strcat */\n#include &lt;stdlib.h&gt; /* strtol */\n\nconst char *byte_to_binary\n(\n int x\n)\n{\n static char b[9];\n b[0] = '\\0';\n\n int z;\n for (z = 128; z &gt; 0; z &gt;&gt;= 1)\n {\n strcat(b, ((x &amp; z) == z) ? &quot;1&quot; : &quot;0&quot;);\n }\n\n return b;\n}\n\nint main\n(\n void\n)\n{\n {\n /* binary string to int */\n\n char *tmp;\n char *b = &quot;0101&quot;;\n\n printf(&quot;%d\\n&quot;, strtol(b, &amp;tmp, 2));\n }\n\n {\n /* byte to binary string */\n\n printf(&quot;%s\\n&quot;, byte_to_binary(5));\n }\n \n return 0;\n}\n</code></pre>\n" }, { "answer_id": 113788, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 3, "selected": false, "text": "<p>Maybe a bit OT, but if you need this only for debuging to understand or retrace some binary operations you are doing, you might take a look on wcalc (a simple console calculator). With the -b options you get binary output.</p>\n\n<p>e.g.</p>\n\n<pre>\n$ wcalc -b \"(256 | 3) & 0xff\"\n = 0b11\n</pre>\n" }, { "answer_id": 657202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre class=\"lang-c prettyprint-override\"><code>const char* byte_to_binary(int x)\n{\n static char b[sizeof(int)*8+1] = {0};\n int y;\n long long z;\n\n for (z = 1LL&lt;&lt;sizeof(int)*8-1, y = 0; z &gt; 0; z &gt;&gt;= 1, y++) {\n b[y] = (((x &amp; z) == z) ? '1' : '0');\n }\n b[y] = 0;\n\n return b;\n}\n</code></pre>\n" }, { "answer_id": 830010, "author": "Rick Regan", "author_id": 100914, "author_profile": "https://Stackoverflow.com/users/100914", "pm_score": 0, "selected": false, "text": "<p>Even for the runtime libraries that DO support %b it seems it's only for integer values.</p>\n\n<p>If you want to print floating-point values in binary, I wrote some code you can find at <a href=\"http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/\" rel=\"nofollow noreferrer\">http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/</a> .</p>\n" }, { "answer_id": 1078422, "author": "mrwes", "author_id": 82848, "author_profile": "https://Stackoverflow.com/users/82848", "pm_score": 3, "selected": false, "text": "<p>This code should handle your needs up to 64 bits.\nI created two functions: <code>pBin</code> and <code>pBinFill</code>. Both do the same thing, but <code>pBinFill</code> fills in the leading spaces with the fill character provided by its last argument.\nThe test function generates some test data, then prints it out using the <code>pBinFill</code> function.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define kDisplayWidth 64\n\nchar* pBin(long int x,char *so)\n{\n char s[kDisplayWidth+1];\n int i = kDisplayWidth;\n s[i--] = 0x00; // terminate string\n do { // fill in array from right to left\n s[i--] = (x &amp; 1) ? '1' : '0'; // determine bit\n x &gt;&gt;= 1; // shift right 1 bit\n } while (x &gt; 0);\n i++; // point to last valid character\n sprintf(so, &quot;%s&quot;, s+i); // stick it in the temp string string\n return so;\n}\n\nchar* pBinFill(long int x, char *so, char fillChar)\n{\n // fill in array from right to left\n char s[kDisplayWidth+1];\n int i = kDisplayWidth;\n s[i--] = 0x00; // terminate string\n do { // fill in array from right to left\n s[i--] = (x &amp; 1) ? '1' : '0';\n x &gt;&gt;= 1; // shift right 1 bit\n } while (x &gt; 0);\n while (i &gt;= 0) s[i--] = fillChar; // fill with fillChar \n sprintf(so, &quot;%s&quot;, s);\n return so;\n}\n\nvoid test()\n{\n char so[kDisplayWidth+1]; // working buffer for pBin\n long int val = 1;\n do {\n printf(&quot;%ld =\\t\\t%#lx =\\t\\t0b%s\\n&quot;, val, val, pBinFill(val, so, '0'));\n val *= 11; // generate test data\n } while (val &lt; 100000000);\n}\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>00000001 = 0x000001 = 0b00000000000000000000000000000001\n00000011 = 0x00000b = 0b00000000000000000000000000001011\n00000121 = 0x000079 = 0b00000000000000000000000001111001\n00001331 = 0x000533 = 0b00000000000000000000010100110011\n00014641 = 0x003931 = 0b00000000000000000011100100110001\n00161051 = 0x02751b = 0b00000000000000100111010100011011\n01771561 = 0x1b0829 = 0b00000000000110110000100000101001\n19487171 = 0x12959c3 = 0b00000001001010010101100111000011\n</code></pre>\n" }, { "answer_id": 3208376, "author": "William Whyte", "author_id": 289138, "author_profile": "https://Stackoverflow.com/users/289138", "pm_score": 8, "selected": false, "text": "<p>Hacky but works for me:</p>\n\n<pre><code>#define BYTE_TO_BINARY_PATTERN \"%c%c%c%c%c%c%c%c\"\n#define BYTE_TO_BINARY(byte) \\\n (byte &amp; 0x80 ? '1' : '0'), \\\n (byte &amp; 0x40 ? '1' : '0'), \\\n (byte &amp; 0x20 ? '1' : '0'), \\\n (byte &amp; 0x10 ? '1' : '0'), \\\n (byte &amp; 0x08 ? '1' : '0'), \\\n (byte &amp; 0x04 ? '1' : '0'), \\\n (byte &amp; 0x02 ? '1' : '0'), \\\n (byte &amp; 0x01 ? '1' : '0') \n</code></pre>\n\n\n\n<pre><code>printf(\"Leading text \"BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));\n</code></pre>\n\n<p>For multi-byte types </p>\n\n<pre><code>printf(\"m: \"BYTE_TO_BINARY_PATTERN\" \"BYTE_TO_BINARY_PATTERN\"\\n\",\n BYTE_TO_BINARY(m&gt;&gt;8), BYTE_TO_BINARY(m));\n</code></pre>\n\n<p>You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to <code>BYTE_TO_BINARY</code>) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.</p>\n" }, { "answer_id": 3829834, "author": "olli", "author_id": 462729, "author_profile": "https://Stackoverflow.com/users/462729", "pm_score": 2, "selected": false, "text": "<pre><code>void print_ulong_bin(const unsigned long * const var, int bits) {\n int i;\n\n #if defined(__LP64__) || defined(_LP64)\n if( (bits &gt; 64) || (bits &lt;= 0) )\n #else\n if( (bits &gt; 32) || (bits &lt;= 0) )\n #endif\n return;\n\n for(i = 0; i &lt; bits; i++) { \n printf(\"%lu\", (*var &gt;&gt; (bits - 1 - i)) &amp; 0x01);\n }\n}\n</code></pre>\n\n<p>should work - untested.</p>\n" }, { "answer_id": 3974138, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p><strong>Print Binary for Any Datatype</strong></p>\n<pre class=\"lang-c prettyprint-override\"><code>// Assumes little endian\nvoid printBits(size_t const size, void const * const ptr)\n{\n unsigned char *b = (unsigned char*) ptr;\n unsigned char byte;\n int i, j;\n \n for (i = size-1; i &gt;= 0; i--) {\n for (j = 7; j &gt;= 0; j--) {\n byte = (b[i] &gt;&gt; j) &amp; 1;\n printf(&quot;%u&quot;, byte);\n }\n }\n puts(&quot;&quot;);\n}\n</code></pre>\n<p>Test:</p>\n<pre class=\"lang-c prettyprint-override\"><code>int main(int argv, char* argc[])\n{\n int i = 23;\n uint ui = UINT_MAX;\n float f = 23.45f;\n printBits(sizeof(i), &amp;i);\n printBits(sizeof(ui), &amp;ui);\n printBits(sizeof(f), &amp;f);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 3989932, "author": "Adam", "author_id": 483309, "author_profile": "https://Stackoverflow.com/users/483309", "pm_score": 0, "selected": false, "text": "<pre><code>void PrintBinary( int Value, int Places, char* TargetString)\n{\n int Mask;\n\n Mask = 1 &lt;&lt; Places;\n\n while( Places--) {\n Mask &gt;&gt;= 1; /* Preshift, because we did one too many above */\n *TargetString++ = (Value &amp; Mask)?'1':'0';\n }\n *TargetString = 0; /* Null terminator for C string */\n}\n</code></pre>\n\n<p>The calling function \"owns\" the string...:</p>\n\n<pre><code>char BinaryString[17];\n...\nPrintBinary( Value, 16, BinaryString);\nprintf( \"yadda yadda %s yadda...\\n\", BinaryString);\n</code></pre>\n\n<p>Depending on your CPU, most of the operations in PrintBinary render to one or very few machine instructions.</p>\n" }, { "answer_id": 4007806, "author": "rakesh jha", "author_id": 485523, "author_profile": "https://Stackoverflow.com/users/485523", "pm_score": 2, "selected": false, "text": "<pre><code>#include &lt;stdio.h&gt;\n#include &lt;conio.h&gt;\n\nvoid main()\n{\n clrscr();\n printf(\"Welcome\\n\\n\\n\");\n unsigned char x='A';\n char ch_array[8];\n for(int i=0; x!=0; i++)\n {\n ch_array[i] = x &amp; 1;\n x = x &gt;&gt;1;\n }\n for(--i; i&gt;=0; i--)\n printf(\"%d\", ch_array[i]);\n\n getch();\n}\n</code></pre>\n" }, { "answer_id": 4839583, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 4, "selected": false, "text": "<p>Here's a version of the function that does not suffer from reentrancy issues or limits on the size/type of the argument:</p>\n<pre><code>#define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1)\n\nchar *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE])\n{\n char *s = buf + FMT_BUF_SIZE;\n *--s = 0;\n if (!x) *--s = '0';\n for (; x; x /= 2) *--s = '0' + x%2;\n return s;\n}\n</code></pre>\n<p>Note that this code would work just as well for any base between 2 and 10 if you just replace the 2's by the desired base. Usage is:</p>\n<pre><code>char tmp[FMT_BUF_SIZE];\nprintf(&quot;%s\\n&quot;, binary_fmt(x, tmp));\n</code></pre>\n<p>Where <code>x</code> is any integral expression.</p>\n" }, { "answer_id": 6546683, "author": "Ben Cordero", "author_id": 824683, "author_profile": "https://Stackoverflow.com/users/824683", "pm_score": 2, "selected": false, "text": "<pre><code>/* Convert an int to it's binary representation */\n\nchar *int2bin(int num, int pad)\n{\n char *str = malloc(sizeof(char) * (pad+1));\n if (str) {\n str[pad]='\\0';\n while (--pad&gt;=0) {\n str[pad] = num &amp; 1 ? '1' : '0';\n num &gt;&gt;= 1;\n }\n } else {\n return \"\";\n }\n return str;\n}\n\n/* example usage */\n\nprintf(\"The number 5 in binary is %s\", int2bin(5, 4));\n/* \"The number 5 in binary is 0101\" */\n</code></pre>\n" }, { "answer_id": 6724041, "author": "paniq", "author_id": 81145, "author_profile": "https://Stackoverflow.com/users/81145", "pm_score": 3, "selected": false, "text": "<p>I optimized the top solution for size and C++-ness, and got to this solution:</p>\n\n<pre><code>inline std::string format_binary(unsigned int x)\n{\n static char b[33];\n b[32] = '\\0';\n\n for (int z = 0; z &lt; 32; z++) {\n b[31-z] = ((x&gt;&gt;z) &amp; 0x1) ? '1' : '0';\n }\n\n return b;\n}\n</code></pre>\n" }, { "answer_id": 6770517, "author": "luser droog", "author_id": 733077, "author_profile": "https://Stackoverflow.com/users/733077", "pm_score": 0, "selected": false, "text": "<p>Is there a printf converter to print in binary format?</p>\n\n<p>There's no standard printf format specifier to accomplish \"binary\" output. Here's the alternative I devised when I needed it.</p>\n\n<p>Mine works for any base from 2 to 36. It fans the digits out into the calling frames of recursive invocations, until it reaches a digit smaller than the base. Then it \"traverses\" backwards, filling the buffer s forwards, and returning. The return value is the size used or -1 if the buffer isn't large enough to hold the string.</p>\n\n<pre><code>int conv_rad (int num, int rad, char *s, int n) {\n char *vec = \"0123456789\" \"ABCDEFGHIJKLM\" \"NOPQRSTUVWXYZ\";\n int off;\n if (n == 0) return 0;\n if (num &lt; rad) { *s = vec[num]; return 1; }\n off = conv_rad(num/rad, rad, s, n);\n if ((off == n) || (off == -1)) return -1;\n s[off] = vec[num%rad];\n return off+1;\n}\n</code></pre>\n\n<p><em>One big caveat:</em> This function was designed for use with \"Pascal\"-style strings which carry their length around. Consequently <code>conv_rad</code>, as written, does not nul-terminate the buffer. For more general C uses, it will probably need a simple wrapper to nul-terminate. Or for printing, just change the assignments to <code>putchar()</code>s.</p>\n" }, { "answer_id": 7137520, "author": "eMPee584", "author_id": 200509, "author_profile": "https://Stackoverflow.com/users/200509", "pm_score": 2, "selected": false, "text": "<p>I liked the code by paniq, the static buffer is a good idea. However it fails if you want multiple binary formats in a single printf() because it always returns the same pointer and overwrites the array. </p>\n\n<p>Here's a C style drop-in that rotates pointer on a split buffer.</p>\n\n<pre><code>char *\nformat_binary(unsigned int x)\n{\n #define MAXLEN 8 // width of output format\n #define MAXCNT 4 // count per printf statement\n static char fmtbuf[(MAXLEN+1)*MAXCNT];\n static int count = 0;\n char *b;\n count = count % MAXCNT + 1;\n b = &amp;fmtbuf[(MAXLEN+1)*count];\n b[MAXLEN] = '\\0';\n for (int z = 0; z &lt; MAXLEN; z++) { b[MAXLEN-1-z] = ((x&gt;&gt;z) &amp; 0x1) ? '1' : '0'; }\n return b;\n}\n</code></pre>\n" }, { "answer_id": 8869174, "author": "Yola", "author_id": 312896, "author_profile": "https://Stackoverflow.com/users/312896", "pm_score": 2, "selected": false, "text": "<p>Next will show to you memory layout:</p>\n\n<pre><code>#include &lt;limits&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\ntemplate&lt;class T&gt; string binary_text(T dec, string byte_separator = \" \") {\n char* pch = (char*)&amp;dec;\n string res;\n for (int i = 0; i &lt; sizeof(T); i++) {\n for (int j = 1; j &lt; 8; j++) {\n res.append(pch[i] &amp; 1 ? \"1\" : \"0\");\n pch[i] /= 2;\n }\n res.append(byte_separator);\n }\n return res;\n}\n\nint main() {\n cout &lt;&lt; binary_text(5) &lt;&lt; endl;\n cout &lt;&lt; binary_text(.1) &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 9287543, "author": "TechplexEngineer", "author_id": 429544, "author_profile": "https://Stackoverflow.com/users/429544", "pm_score": 4, "selected": false, "text": "<p>None of the previously posted answers are exactly what I was looking for, so I wrote one. It is super simple to use <code>%B</code> with the <code>printf</code>!</p>\n<pre class=\"lang-c prettyprint-override\"><code>/*\n * File: main.c\n * Author: Techplex.Engineer\n *\n * Created on February 14, 2012, 9:16 PM\n */\n\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;printf.h&gt;\n#include &lt;math.h&gt;\n#include &lt;string.h&gt;\n\nstatic int printf_arginfo_M(const struct printf_info *info, size_t n, int *argtypes)\n{\n /* &quot;%M&quot; always takes one argument, a pointer to uint8_t[6]. */\n if (n &gt; 0) {\n argtypes[0] = PA_POINTER;\n }\n return 1;\n}\n\nstatic int printf_output_M(FILE *stream, const struct printf_info *info, const void *const *args)\n{\n int value = 0;\n int len;\n\n value = *(int **) (args[0]);\n\n // Beginning of my code ------------------------------------------------------------\n char buffer [50] = &quot;&quot;; // Is this bad?\n char buffer2 [50] = &quot;&quot;; // Is this bad?\n int bits = info-&gt;width;\n if (bits &lt;= 0)\n bits = 8; // Default to 8 bits\n\n int mask = pow(2, bits - 1);\n while (mask &gt; 0) {\n sprintf(buffer, &quot;%s&quot;, ((value &amp; mask) &gt; 0 ? &quot;1&quot; : &quot;0&quot;));\n strcat(buffer2, buffer);\n mask &gt;&gt;= 1;\n }\n strcat(buffer2, &quot;\\n&quot;);\n // End of my code --------------------------------------------------------------\n len = fprintf(stream, &quot;%s&quot;, buffer2);\n return len;\n}\n\nint main(int argc, char** argv)\n{\n register_printf_specifier('B', printf_output_M, printf_arginfo_M);\n\n printf(&quot;%4B\\n&quot;, 65);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n" }, { "answer_id": 12974661, "author": "kapilddit", "author_id": 555911, "author_profile": "https://Stackoverflow.com/users/555911", "pm_score": 3, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>char buffer [33];\nitoa(value, buffer, 2);\nprintf(\"\\nbinary: %s\\n\", buffer);\n</code></pre>\n\n<p>For more ref., see <em><a href=\"https://stackoverflow.com/questions/6373093/how-to-print-binary-number-via-printf\">How to print binary number via printf</a></em>.</p>\n" }, { "answer_id": 15909072, "author": "Leo", "author_id": 518018, "author_profile": "https://Stackoverflow.com/users/518018", "pm_score": 2, "selected": false, "text": "<p>Here is a small variation of <em>paniq</em>'s solution that uses templates to allow printing of 32 and 64 bit integers:</p>\n\n<pre><code>template&lt;class T&gt;\ninline std::string format_binary(T x)\n{\n char b[sizeof(T)*8+1] = {0};\n\n for (size_t z = 0; z &lt; sizeof(T)*8; z++)\n b[sizeof(T)*8-1-z] = ((x&gt;&gt;z) &amp; 0x1) ? '1' : '0';\n\n return std::string(b);\n}\n</code></pre>\n\n<p>And can be used like:</p>\n\n<pre><code>unsigned int value32 = 0x1e127ad;\nprintf( \" 0x%x: %s\\n\", value32, format_binary(value32).c_str() );\n\nunsigned long long value64 = 0x2e0b04ce0;\nprintf( \"0x%llx: %s\\n\", value64, format_binary(value64).c_str() );\n</code></pre>\n\n<p>Here is the result:</p>\n\n<pre><code> 0x1e127ad: 00000001111000010010011110101101\n0x2e0b04ce0: 0000000000000000000000000000001011100000101100000100110011100000\n</code></pre>\n" }, { "answer_id": 17380787, "author": "Moses", "author_id": 983798, "author_profile": "https://Stackoverflow.com/users/983798", "pm_score": 0, "selected": false, "text": "<p>It might be not very efficient but it's quite simple. Try this:</p>\n\n<pre><code>tmp1 = 1;\nwhile(inint/tmp1 &gt; 1) {\n tmp1 &lt;&lt;= 1;\n}\ndo {\n printf(\"%d\", tmp2=inint/tmp1);\n inint -= tmp1*tmp2;\n} while((tmp1 &gt;&gt;= 1) &gt; 0);\nprintf(\" \");\n</code></pre>\n" }, { "answer_id": 19470143, "author": "hiteshradia", "author_id": 1980274, "author_profile": "https://Stackoverflow.com/users/1980274", "pm_score": 0, "selected": false, "text": "<p>Here's is a very simple one:</p>\n\n<pre><code>int print_char_to_binary(char ch)\n{\n int i;\n for (i=7; i&gt;=0; i--)\n printf(\"%hd \", ((ch &amp; (1&lt;&lt;i))&gt;&gt;i));\n printf(\"\\n\");\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 19885112, "author": "Shahbaz", "author_id": 912144, "author_profile": "https://Stackoverflow.com/users/912144", "pm_score": 6, "selected": false, "text": "<p>You could use a small table to improve speed<sup>1</sup>. Similar techniques are useful in the embedded world, for example, to invert a byte:</p>\n\n<pre><code>const char *bit_rep[16] = {\n [ 0] = \"0000\", [ 1] = \"0001\", [ 2] = \"0010\", [ 3] = \"0011\",\n [ 4] = \"0100\", [ 5] = \"0101\", [ 6] = \"0110\", [ 7] = \"0111\",\n [ 8] = \"1000\", [ 9] = \"1001\", [10] = \"1010\", [11] = \"1011\",\n [12] = \"1100\", [13] = \"1101\", [14] = \"1110\", [15] = \"1111\",\n};\n\nvoid print_byte(uint8_t byte)\n{\n printf(\"%s%s\", bit_rep[byte &gt;&gt; 4], bit_rep[byte &amp; 0x0F]);\n}\n</code></pre>\n\n<p><sup>1</sup> I'm mostly referring to embedded applications where optimizers are not so aggressive and the speed difference is visible.</p>\n" }, { "answer_id": 19940043, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 2, "selected": false, "text": "<p>Yet another approach to print in binary: <strong>Convert the integer first</strong>.</p>\n\n<p>To print <code>6</code> in binary, change <code>6</code> to <code>110</code>, then print <code>\"110\"</code>.</p>\n\n<p>Bypasses <code>char buf[]</code> issues.<br>\n<code>printf()</code> format specifiers, flags, &amp; fields like <code>\"%08lu\"</code>, <code>\"%*lX\"</code> still readily usable.<br>\nNot only binary (base 2), this method expandable to other bases up to 16.<br>\nLimited to smallish integer values. </p>\n\n<pre><code>#include &lt;stdint.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;inttypes.h&gt;\n\nunsigned long char_to_bin10(char ch) {\n unsigned char uch = ch;\n unsigned long sum = 0;\n unsigned long power = 1;\n while (uch) {\n if (uch &amp; 1) {\n sum += power;\n }\n power *= 10;\n uch /= 2;\n }\n return sum;\n}\n\nuint64_t uint16_to_bin16(uint16_t u) {\n uint64_t sum = 0;\n uint64_t power = 1;\n while (u) {\n if (u &amp; 1) {\n sum += power;\n }\n power *= 16;\n u /= 2;\n }\n return sum;\n}\n\nvoid test(void) {\n printf(\"%lu\\n\", char_to_bin10(0xF1));\n // 11110001\n printf(\"%\" PRIX64 \"\\n\", uint16_to_bin16(0xF731));\n // 1111011100110001\n}\n</code></pre>\n" }, { "answer_id": 22511317, "author": "Marko", "author_id": 1873877, "author_profile": "https://Stackoverflow.com/users/1873877", "pm_score": 2, "selected": false, "text": "<p>I just want to post my solution. It's used to get zeroes and ones of one byte, but calling this function few times can be used for larger data blocks. I use it for 128 bit or larger structs. You can also modify it to use size_t as input parameter and pointer to data you want to print, so it can be size independent. But it works for me quit well as it is.</p>\n\n<pre><code>void print_binary(unsigned char c)\n{\n unsigned char i1 = (1 &lt;&lt; (sizeof(c)*8-1));\n for(; i1; i1 &gt;&gt;= 1)\n printf(\"%d\",(c&amp;i1)!=0);\n}\n\nvoid get_binary(unsigned char c, unsigned char bin[])\n{\n unsigned char i1 = (1 &lt;&lt; (sizeof(c)*8-1)), i2=0;\n for(; i1; i1&gt;&gt;=1, i2++)\n bin[i2] = ((c&amp;i1)!=0);\n}\n</code></pre>\n" }, { "answer_id": 25108449, "author": "ideasman42", "author_id": 432509, "author_profile": "https://Stackoverflow.com/users/432509", "pm_score": 5, "selected": false, "text": "<p>Based on @William Whyte's answer, this is a macro that provides <code>int8</code>,<code>16</code>,<code>32</code> &amp; <code>64</code> versions, reusing the <code>INT8</code> macro to avoid repetition.</p>\n\n<pre><code>/* --- PRINTF_BYTE_TO_BINARY macro's --- */\n#define PRINTF_BINARY_PATTERN_INT8 \"%c%c%c%c%c%c%c%c\"\n#define PRINTF_BYTE_TO_BINARY_INT8(i) \\\n (((i) &amp; 0x80ll) ? '1' : '0'), \\\n (((i) &amp; 0x40ll) ? '1' : '0'), \\\n (((i) &amp; 0x20ll) ? '1' : '0'), \\\n (((i) &amp; 0x10ll) ? '1' : '0'), \\\n (((i) &amp; 0x08ll) ? '1' : '0'), \\\n (((i) &amp; 0x04ll) ? '1' : '0'), \\\n (((i) &amp; 0x02ll) ? '1' : '0'), \\\n (((i) &amp; 0x01ll) ? '1' : '0')\n\n#define PRINTF_BINARY_PATTERN_INT16 \\\n PRINTF_BINARY_PATTERN_INT8 PRINTF_BINARY_PATTERN_INT8\n#define PRINTF_BYTE_TO_BINARY_INT16(i) \\\n PRINTF_BYTE_TO_BINARY_INT8((i) &gt;&gt; 8), PRINTF_BYTE_TO_BINARY_INT8(i)\n#define PRINTF_BINARY_PATTERN_INT32 \\\n PRINTF_BINARY_PATTERN_INT16 PRINTF_BINARY_PATTERN_INT16\n#define PRINTF_BYTE_TO_BINARY_INT32(i) \\\n PRINTF_BYTE_TO_BINARY_INT16((i) &gt;&gt; 16), PRINTF_BYTE_TO_BINARY_INT16(i)\n#define PRINTF_BINARY_PATTERN_INT64 \\\n PRINTF_BINARY_PATTERN_INT32 PRINTF_BINARY_PATTERN_INT32\n#define PRINTF_BYTE_TO_BINARY_INT64(i) \\\n PRINTF_BYTE_TO_BINARY_INT32((i) &gt;&gt; 32), PRINTF_BYTE_TO_BINARY_INT32(i)\n/* --- end macros --- */\n\n#include &lt;stdio.h&gt;\nint main() {\n long long int flag = 1648646756487983144ll;\n printf(\"My Flag \"\n PRINTF_BINARY_PATTERN_INT64 \"\\n\",\n PRINTF_BYTE_TO_BINARY_INT64(flag));\n return 0;\n}\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>My Flag 0001011011100001001010110111110101111000100100001111000000101000\n</code></pre>\n\n<p>For readability you may want to add a separator for eg:</p>\n\n<pre><code>My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000\n</code></pre>\n" }, { "answer_id": 25502488, "author": "andre.barata", "author_id": 2536704, "author_profile": "https://Stackoverflow.com/users/2536704", "pm_score": 2, "selected": false, "text": "<p>Here's how I did it for an unsigned int</p>\n\n<pre><code>void printb(unsigned int v) {\n unsigned int i, s = 1&lt;&lt;((sizeof(v)&lt;&lt;3)-1); // s = only most significant bit at 1\n for (i = s; i; i&gt;&gt;=1) printf(\"%d\", v &amp; i || 0 );\n}\n</code></pre>\n" }, { "answer_id": 26154541, "author": "SeattleOrBayArea", "author_id": 927370, "author_profile": "https://Stackoverflow.com/users/927370", "pm_score": 2, "selected": false, "text": "<p>A small utility function in C to do this while solving a bit manipulation problem. This goes over the string checking each set bit using a mask (1&lt;\n\n<pre><code>void\nprintStringAsBinary(char * input)\n{\n char * temp = input;\n int i = 7, j =0;;\n int inputLen = strlen(input);\n\n /* Go over the string, check first bit..bit by bit and print 1 or 0\n **/\n\n for (j = 0; j &lt; inputLen; j++) {\n printf(\"\\n\");\n while (i&gt;=0) {\n if (*temp &amp; (1 &lt;&lt; i)) {\n printf(\"1\");\n } else {\n printf(\"0\");\n }\n i--;\n }\n temp = temp+1;\n i = 7;\n printf(\"\\n\");\n }\n}\n</code></pre>\n" }, { "answer_id": 26970214, "author": "GutiMac", "author_id": 4211031, "author_profile": "https://Stackoverflow.com/users/4211031", "pm_score": 0, "selected": false, "text": "<pre><code>void binario(int num) {\n for(int i=0;i&lt;32;i++){\n (num&amp;(1&lt;i))? printf(\"1\"):\n printf(\"0\");\n } \n printf(\"\\n\");\n}\n</code></pre>\n" }, { "answer_id": 27627015, "author": "danijar", "author_id": 1079110, "author_profile": "https://Stackoverflow.com/users/1079110", "pm_score": 5, "selected": false, "text": "<p>Print the least significant bit and shift it out on the right. Doing this until the integer becomes zero prints the binary representation without leading zeros but in reversed order. Using recursion, the order can be corrected quite easily.</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid print_binary(unsigned int number)\n{\n if (number &gt;&gt; 1) {\n print_binary(number &gt;&gt; 1);\n }\n putc((number &amp; 1) ? '1' : '0', stdout);\n}\n</code></pre>\n<p>To me, this is one of the cleanest solutions to the problem. If you like <code>0b</code> prefix and a trailing new line character, I suggest wrapping the function.</p>\n<p><a href=\"https://ideone.com/aXc7hA\" rel=\"noreferrer\">Online demo</a></p>\n" }, { "answer_id": 28796910, "author": "kapil", "author_id": 3888438, "author_profile": "https://Stackoverflow.com/users/3888438", "pm_score": 3, "selected": false, "text": "<p>The following recursive function might be useful:</p>\n\n<pre><code>void bin(int n)\n{\n /* Step 1 */\n if (n &gt; 1)\n bin(n/2);\n /* Step 2 */\n printf(\"%d\", n % 2);\n}\n</code></pre>\n" }, { "answer_id": 31660310, "author": "luart", "author_id": 1814353, "author_profile": "https://Stackoverflow.com/users/1814353", "pm_score": 2, "selected": false, "text": "<p><em>One statement generic</em> conversion of <em>any integral type</em> into the binary string representation using <em>standard</em> library:</p>\n\n<pre><code>#include &lt;bitset&gt;\nMyIntegralType num = 10;\nprint(\"%s\\n\",\n std::bitset&lt;sizeof(num) * 8&gt;(num).to_string().insert(0, \"0b\").c_str()\n); // prints \"0b1010\\n\"\n</code></pre>\n\n<p><a href=\"https://katyscode.wordpress.com/2012/05/12/printing-numbers-in-binary-format-in-c/\" rel=\"nofollow\">Or just:</a> <code>std::cout &lt;&lt; std::bitset&lt;sizeof(num) * 8&gt;(num);</code></p>\n" }, { "answer_id": 34641674, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 4, "selected": false, "text": "<blockquote>\n<p>Is there a printf converter to print in binary format?</p>\n</blockquote>\n<p>The <code>printf()</code> family is only able to print integers in base 8, 10, and 16 using the standard specifiers directly. I suggest creating a function that converts the number to a string per code's particular needs.</p>\n<p>[Edit 2022] This is expected to change with the next version of C which implements <code>&quot;%b&quot;</code>.</p>\n<blockquote>\n<p>Binary constants such as 0b10101010, and %b conversion specifier for printf() function family <a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\">C2x</a></p>\n</blockquote>\n<hr />\n<p><strong>To print in any base [2-36]</strong></p>\n<p>All other answers so far have at least one of these limitations.</p>\n<ol>\n<li><p>Use static memory for the return buffer. This limits the number of times the function may be used as an argument to <code>printf()</code>.</p>\n</li>\n<li><p>Allocate memory requiring the calling code to free pointers.</p>\n</li>\n<li><p>Require the calling code to explicitly provide a suitable buffer.</p>\n</li>\n<li><p>Call <code>printf()</code> directly. This obliges a new function for to <code>fprintf()</code>, <code>sprintf()</code>, <code>vsprintf()</code>, etc.</p>\n</li>\n<li><p>Use a reduced integer range.</p>\n</li>\n</ol>\n<p>The following has <strong>none of the above limitation</strong>. It does require C99 or later and use of <code>&quot;%s&quot;</code>. It uses a <a href=\"https://en.cppreference.com/w/c/language/compound_literal\" rel=\"nofollow noreferrer\"><em>compound literal</em></a> to provide the buffer space. It has no trouble with multiple calls in a <code>printf()</code>.</p>\n<pre><code>#include &lt;assert.h&gt;\n#include &lt;limits.h&gt;\n#define TO_BASE_N (sizeof(unsigned)*CHAR_BIT + 1)\n\n// v--compound literal--v\n#define TO_BASE(x, b) my_to_base((char [TO_BASE_N]){&quot;&quot;}, (x), (b))\n\n// Tailor the details of the conversion function as needed\n// This one does not display unneeded leading zeros\n// Use return value, not `buf`\nchar *my_to_base(char buf[TO_BASE_N], unsigned i, int base) {\n assert(base &gt;= 2 &amp;&amp; base &lt;= 36);\n char *s = &amp;buf[TO_BASE_N - 1];\n *s = '\\0';\n do {\n s--;\n *s = &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;[i % base];\n i /= base;\n } while (i);\n\n // Could employ memmove here to move the used buffer to the beginning\n // size_t len = &amp;buf[TO_BASE_N] - s;\n // memmove(buf, s, len);\n\n return s;\n}\n\n#include &lt;stdio.h&gt;\nint main(void) {\n int ip1 = 0x01020304;\n int ip2 = 0x05060708;\n printf(&quot;%s %s\\n&quot;, TO_BASE(ip1, 16), TO_BASE(ip2, 16));\n printf(&quot;%s %s\\n&quot;, TO_BASE(ip1, 2), TO_BASE(ip2, 2));\n puts(TO_BASE(ip1, 8));\n puts(TO_BASE(ip1, 36));\n return 0;\n}\n</code></pre>\n<p>Output</p>\n<pre><code>1020304 5060708\n1000000100000001100000100 101000001100000011100001000\n100401404\nA2F44\n</code></pre>\n" }, { "answer_id": 34688422, "author": "Grzegorz Szpetkowski", "author_id": 586873, "author_profile": "https://Stackoverflow.com/users/586873", "pm_score": 0, "selected": false, "text": "<p>The following function returns binary representation of given unsigned integer using pointer arithmetic without leading zeros: </p>\n\n<pre><code>const char* toBinaryString(unsigned long num)\n{\n static char buffer[CHAR_BIT*sizeof(num)+1];\n char* pBuffer = &amp;buffer[sizeof(buffer)-1];\n\n do *--pBuffer = '0' + (num &amp; 1);\n while (num &gt;&gt;= 1);\n return pBuffer;\n}\n</code></pre>\n\n<p>Note that there is no need to explicity set <code>NUL</code> terminator, because <code>buffer</code> repesents an object with <em>static storage duration</em>, that is already filled with all-zeros.</p>\n\n<p>This can be easily adapted to <code>unsigned long long</code> (or another unsigned integer) by simply modifing type of <code>num</code> formal parameter.</p>\n\n<p>The <code>CHAR_BIT</code> requires <code>&lt;limits.h&gt;</code> to be included.</p>\n\n<p>Here is an example usage:</p>\n\n<pre><code>int main(void)\n{\n printf(\"&gt;&gt;&gt;%20s&lt;&lt;&lt;\\n\", toBinaryString(1));\n printf(\"&gt;&gt;&gt;%-20s&lt;&lt;&lt;\\n\", toBinaryString(254));\n return 0;\n}\n</code></pre>\n\n<p>with its desired output as:</p>\n\n<pre><code>&gt;&gt;&gt; 1&lt;&lt;&lt;\n&gt;&gt;&gt;11111110 &lt;&lt;&lt;\n</code></pre>\n" }, { "answer_id": 36270476, "author": "SarahGaidi", "author_id": 3559270, "author_profile": "https://Stackoverflow.com/users/3559270", "pm_score": 2, "selected": false, "text": "<p>My solution:</p>\n\n<pre><code>long unsigned int i;\nfor(i = 0u; i &lt; sizeof(integer) * CHAR_BIT; i++) {\n if(integer &amp; LONG_MIN)\n printf(\"1\");\n else\n printf(\"0\");\n integer &lt;&lt;= 1;\n}\nprintf(\"\\n\");\n</code></pre>\n" }, { "answer_id": 39401342, "author": "Geyslan G. Bem", "author_id": 2776344, "author_profile": "https://Stackoverflow.com/users/2776344", "pm_score": 3, "selected": false, "text": "<h2>Print bits from any type using less code and resources</h2>\n<p>This approach has as attributes:</p>\n<ul>\n<li>Works with variables and literals.</li>\n<li>Doesn't iterate all bits when not necessary.</li>\n<li>Call printf only when complete a byte (not unnecessarily for all bits).</li>\n<li>Works for any type.</li>\n<li>Works with little and big endianness (uses GCC #defines for checking).</li>\n<li>May work with hardware that char isn't a byte (eight bits). (Tks @supercat)</li>\n<li>Uses typeof() that isn't C standard but is largely defined.</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;string.h&gt;\n#include &lt;limits.h&gt;\n\n#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n#define for_endian(size) for (int i = 0; i &lt; size; ++i)\n#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n#define for_endian(size) for (int i = size - 1; i &gt;= 0; --i)\n#else\n#error &quot;Endianness not detected&quot;\n#endif\n\n#define printb(value) \\\n({ \\\n typeof(value) _v = value; \\\n __printb((typeof(_v) *) &amp;_v, sizeof(_v)); \\\n})\n\n#define MSB_MASK 1 &lt;&lt; (CHAR_BIT - 1)\n\nvoid __printb(void *value, size_t size)\n{\n unsigned char uc;\n unsigned char bits[CHAR_BIT + 1];\n\n bits[CHAR_BIT] = '\\0';\n for_endian(size) {\n uc = ((unsigned char *) value)[i];\n memset(bits, '0', CHAR_BIT);\n for (int j = 0; uc &amp;&amp; j &lt; CHAR_BIT; ++j) {\n if (uc &amp; MSB_MASK)\n bits[j] = '1';\n uc &lt;&lt;= 1;\n }\n printf(&quot;%s &quot;, bits);\n }\n printf(&quot;\\n&quot;);\n}\n\nint main(void)\n{\n uint8_t c1 = 0xff, c2 = 0x44;\n uint8_t c3 = c1 + c2;\n\n printb(c1);\n printb((char) 0xff);\n printb((short) 0xff);\n printb(0xff);\n printb(c2);\n printb(0x44);\n printb(0x4411ff01);\n printb((uint16_t) c3);\n printb('A');\n printf(&quot;\\n&quot;);\n\n return 0;\n}\n</code></pre>\n<h2>Output</h2>\n<pre class=\"lang-sh prettyprint-override\"><code>$ ./printb \n11111111 \n11111111 \n00000000 11111111 \n00000000 00000000 00000000 11111111 \n01000100 \n00000000 00000000 00000000 01000100 \n01000100 00010001 11111111 00000001 \n00000000 01000011 \n00000000 00000000 00000000 01000001 \n</code></pre>\n<hr />\n<p>I have used <strong>another</strong> approach (<a href=\"https://github.com/c0defellas/bitprint/blob/master/bitprint.h\" rel=\"nofollow noreferrer\"><strong>bitprint.h</strong></a>) to fill a table with all bytes (as bit strings) and print them based on the input/index byte. It's worth taking a look.</p>\n" }, { "answer_id": 42247968, "author": "Jan Turoň", "author_id": 343721, "author_profile": "https://Stackoverflow.com/users/343721", "pm_score": 1, "selected": false, "text": "<p>There is also an idea to convert the number to hexadecimal format and then to decode each hexadecimal cipher to four \"bits\" (ones and zeros). <code>sprintf</code> can do bit operations for us:</p>\n\n<pre><code>const char* binary(int n) {\n static const char binnums[16][5] = { \"0000\",\"0001\",\"0010\",\"0011\",\n \"0100\",\"0101\",\"0110\",\"0111\",\"1000\",\"1001\",\"1010\",\"1011\",\"1100\",\"1101\",\"1110\",\"1111\" };\n static const char* hexnums = \"0123456789abcdef\";\n static char inbuffer[16], outbuffer[4*16];\n const char *i;\n sprintf(inbuffer,\"%x\",n); // hexadecimal n -&gt; inbuffer\n for(i=inbuffer; *i!=0; ++i) { // for each hexadecimal cipher\n int d = strchr(hexnums,*i) - hexnums; // store its decimal value to d\n char* o = outbuffer+(i-inbuffer)*4; // shift four characters in outbuffer\n sprintf(o,\"%s\",binnums[d]); // place binary value of d there\n }\n return strchr(outbuffer,'1'); // omit leading zeros\n}\n\nputs(binary(42)); // outputs 101010\n</code></pre>\n" }, { "answer_id": 45041802, "author": "Kresimir", "author_id": 1127700, "author_profile": "https://Stackoverflow.com/users/1127700", "pm_score": 2, "selected": false, "text": "<p>Maybe someone will find this solution useful:</p>\n\n<pre><code>void print_binary(int number, int num_digits) {\n int digit;\n for(digit = num_digits - 1; digit &gt;= 0; digit--) {\n printf(\"%c\", number &amp; (1 &lt;&lt; digit) ? '1' : '0');\n }\n}\n</code></pre>\n" }, { "answer_id": 45238104, "author": "Et7f3XIV", "author_id": 7227940, "author_profile": "https://Stackoverflow.com/users/7227940", "pm_score": 2, "selected": false, "text": "<p>Based on @ideasman42's suggestion in his answer, this is a macro that provides <code>int8</code>,<code>16</code>,<code>32</code> &amp; <code>64</code> versions, reusing the <code>INT8</code> macro to avoid repetition.</p>\n\n<pre><code>/* --- PRINTF_BYTE_TO_BINARY macro's --- */\n#define PRINTF_BINARY_SEPARATOR\n#define PRINTF_BINARY_PATTERN_INT8 \"%c%c%c%c%c%c%c%c\"\n#define PRINTF_BYTE_TO_BINARY_INT8(i) \\\n (((i) &amp; 0x80ll) ? '1' : '0'), \\\n (((i) &amp; 0x40ll) ? '1' : '0'), \\\n (((i) &amp; 0x20ll) ? '1' : '0'), \\\n (((i) &amp; 0x10ll) ? '1' : '0'), \\\n (((i) &amp; 0x08ll) ? '1' : '0'), \\\n (((i) &amp; 0x04ll) ? '1' : '0'), \\\n (((i) &amp; 0x02ll) ? '1' : '0'), \\\n (((i) &amp; 0x01ll) ? '1' : '0')\n\n#define PRINTF_BINARY_PATTERN_INT16 \\\n PRINTF_BINARY_PATTERN_INT8 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT8\n#define PRINTF_BYTE_TO_BINARY_INT16(i) \\\n PRINTF_BYTE_TO_BINARY_INT8((i) &gt;&gt; 8), PRINTF_BYTE_TO_BINARY_INT8(i)\n#define PRINTF_BINARY_PATTERN_INT32 \\\n PRINTF_BINARY_PATTERN_INT16 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT16\n#define PRINTF_BYTE_TO_BINARY_INT32(i) \\\n PRINTF_BYTE_TO_BINARY_INT16((i) &gt;&gt; 16), PRINTF_BYTE_TO_BINARY_INT16(i)\n#define PRINTF_BINARY_PATTERN_INT64 \\\n PRINTF_BINARY_PATTERN_INT32 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT32\n#define PRINTF_BYTE_TO_BINARY_INT64(i) \\\n PRINTF_BYTE_TO_BINARY_INT32((i) &gt;&gt; 32), PRINTF_BYTE_TO_BINARY_INT32(i)\n/* --- end macros --- */\n\n#include &lt;stdio.h&gt;\nint main() {\n long long int flag = 1648646756487983144ll;\n printf(\"My Flag \"\n PRINTF_BINARY_PATTERN_INT64 \"\\n\",\n PRINTF_BYTE_TO_BINARY_INT64(flag));\n return 0;\n}\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>My Flag 0001011011100001001010110111110101111000100100001111000000101000\n</code></pre>\n\n<p>For readability you can change :<code>#define PRINTF_BINARY_SEPARATOR</code> to <code>#define PRINTF_BINARY_SEPARATOR \",\"</code> or <code>#define PRINTF_BINARY_SEPARATOR \" \"</code></p>\n\n<p>This will output:</p>\n\n<pre><code>My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000\n</code></pre>\n\n<p>or</p>\n\n<pre><code>My Flag 00010110 11100001 00101011 01111101 01111000 10010000 11110000 00101000\n</code></pre>\n" }, { "answer_id": 46193398, "author": "kapilddit", "author_id": 555911, "author_profile": "https://Stackoverflow.com/users/555911", "pm_score": 0, "selected": false, "text": "<p>Use below function:</p>\n\n<pre><code>void conbin(int num){ \n if(num != 0)\n {\n conbin(num &gt;&gt; 1); \n if (num &amp; 1){\n printf(\"1\");\n }\n else{\n printf(\"0\");\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 48274667, "author": "Akhil", "author_id": 1000676, "author_profile": "https://Stackoverflow.com/users/1000676", "pm_score": 1, "selected": false, "text": "<pre><code>void DisplayBinary(int n)\n{\n int arr[8];\n int top =-1;\n while (n)\n {\n if (n &amp; 1)\n arr[++top] = 1;\n else\n arr[++top] = 0;\n\n n &gt;&gt;= 1;\n }\n for (int i = top ; i &gt; -1;i--)\n {\n printf(\"%d\",arr[i]);\n }\n printf(\"\\n\");\n}\n</code></pre>\n" }, { "answer_id": 49854917, "author": "Rassoul", "author_id": 3153052, "author_profile": "https://Stackoverflow.com/users/3153052", "pm_score": 2, "selected": false, "text": "<pre><code>void DisplayBinary(unsigned int n)\n{\n int l = sizeof(n) * 8;\n for (int i = l - 1 ; i &gt;= 0; i--) {\n printf(\"%x\", (n &amp; (1 &lt;&lt; i)) &gt;&gt; i);\n }\n}\n</code></pre>\n" }, { "answer_id": 50310562, "author": "малин чекуров", "author_id": 9721071, "author_profile": "https://Stackoverflow.com/users/9721071", "pm_score": 3, "selected": false, "text": "<pre><code>void\nprint_binary(unsigned int n)\n{\n unsigned int mask = 0;\n /* this grotesque hack creates a bit pattern 1000... */\n /* regardless of the size of an unsigned int */\n mask = ~mask ^ (~mask &gt;&gt; 1);\n\n for(; mask != 0; mask &gt;&gt;= 1) {\n putchar((n &amp; mask) ? '1' : '0');\n }\n\n}\n</code></pre>\n" }, { "answer_id": 51721063, "author": "Esann ", "author_id": 8623025, "author_profile": "https://Stackoverflow.com/users/8623025", "pm_score": 1, "selected": false, "text": "<p>Do a function and call it</p>\n\n<pre><code>display_binary(int n)\n{\n long int arr[32];\n int arr_counter=0;\n while(n&gt;=1)\n {\n arr[arr_counter++]=n%2;\n n/=2;\n }\n for(int i=arr_counter-1;i&gt;=0;i--)\n {\n printf(\"%d\",arr[i]);\n }\n}\n</code></pre>\n" }, { "answer_id": 53850409, "author": "Robotbugs", "author_id": 986059, "author_profile": "https://Stackoverflow.com/users/986059", "pm_score": 4, "selected": false, "text": "<p>Quick and easy solution:</p>\n\n<pre><code>void printbits(my_integer_type x)\n{\n for(int i=sizeof(x)&lt;&lt;3; i; i--)\n putchar('0'+((x&gt;&gt;(i-1))&amp;1));\n}\n</code></pre>\n\n<p>Works for any size type and for signed and unsigned ints. The '&amp;1' is needed to handle signed ints as the shift may do sign extension.</p>\n\n<p>There are so many ways of doing this. Here's a super simple one for printing 32 bits or n bits from a signed or unsigned 32 bit type (not putting a negative if signed, just printing the actual bits) and no carriage return. Note that i is decremented before the bit shift:</p>\n\n<pre><code>#define printbits_n(x,n) for (int i=n;i;i--,putchar('0'|(x&gt;&gt;i)&amp;1))\n#define printbits_32(x) printbits_n(x,32)\n</code></pre>\n\n<p>What about returning a string with the bits to store or print later? You either can allocate the memory and return it and the user has to free it, or else you return a static string but it will get clobbered if it's called again, or by another thread. Both methods shown:</p>\n\n<pre><code>char *int_to_bitstring_alloc(int x, int count)\n{\n count = count&lt;1 ? sizeof(x)*8 : count;\n char *pstr = malloc(count+1);\n for(int i = 0; i&lt;count; i++)\n pstr[i] = '0' | ((x&gt;&gt;(count-1-i))&amp;1);\n pstr[count]=0;\n return pstr;\n}\n\n#define BITSIZEOF(x) (sizeof(x)*8)\n\nchar *int_to_bitstring_static(int x, int count)\n{\n static char bitbuf[BITSIZEOF(x)+1];\n count = (count&lt;1 || count&gt;BITSIZEOF(x)) ? BITSIZEOF(x) : count;\n for(int i = 0; i&lt;count; i++)\n bitbuf[i] = '0' | ((x&gt;&gt;(count-1-i))&amp;1);\n bitbuf[count]=0;\n return bitbuf;\n}\n</code></pre>\n\n<p>Call with:</p>\n\n<pre><code>// memory allocated string returned which needs to be freed\nchar *pstr = int_to_bitstring_alloc(0x97e50ae6, 17);\nprintf(\"bits = 0b%s\\n\", pstr);\nfree(pstr);\n\n// no free needed but you need to copy the string to save it somewhere else\nchar *pstr2 = int_to_bitstring_static(0x97e50ae6, 17);\nprintf(\"bits = 0b%s\\n\", pstr2);\n</code></pre>\n" }, { "answer_id": 59489894, "author": "brunoais", "author_id": 551625, "author_profile": "https://Stackoverflow.com/users/551625", "pm_score": 0, "selected": false, "text": "<p>This is my take on this subject.</p>\n<p>Advantages to most other examples:</p>\n<ol>\n<li>Uses <code>putchar()</code> which is more efficient than <code>printf()</code> or even (although not as much) <code>puts()</code></li>\n<li>Split into two parts (expected to have code inlined) which allows extra efficiency, if wanted.</li>\n<li>Is based on very fast RISC arithmetic operations (that includes not using division and multiplication)</li>\n</ol>\n<p>Disadvantages to most examples:</p>\n<ol>\n<li>Code is not very straightforward.</li>\n<li><code>print_binary_size()</code> modifies the input variable without a copy.</li>\n</ol>\n<p>Note: The best outcome for this code relies on using <code>-O1</code> or higher in <code>gcc</code> or equivalent.</p>\n<p>Here's the code:</p>\n<pre><code> inline void print_binary_sized(unsigned int number, unsigned int digits) {\n static char ZERO = '0';\n int digitsLeft = digits;\n \n do{\n putchar(ZERO + ((number &gt;&gt; digitsLeft) &amp; 1));\n }while(digitsLeft--);\n }\n\n void print_binary(unsigned int number) {\n int digitsLeft = sizeof(number) * 8;\n \n while((~(number &gt;&gt; digitsLeft) &amp; 1) &amp;&amp; digitsLeft){\n digitsLeft--;\n }\n print_binary_sized(number, digitsLeft);\n }\n</code></pre>\n" }, { "answer_id": 62120014, "author": "jlettvin", "author_id": 1363592, "author_profile": "https://Stackoverflow.com/users/1363592", "pm_score": 0, "selected": false, "text": "<pre><code>// m specifies how many of the low bits are shown.\n// Replace m with sizeof(n) below for all bits and\n// remove it from the parameter list if you like.\n\nvoid print_binary(unsigned long n, unsigned long m) {\n static char show[3] = \"01\";\n unsigned long mask = 1ULL &lt;&lt; (m-1);\n while(mask) {\n putchar(show[!!(n&amp;mask)]); mask &gt;&gt;= 1;\n }\n putchar('\\n');\n}\n</code></pre>\n" }, { "answer_id": 62265806, "author": "NoComprende", "author_id": 6386071, "author_profile": "https://Stackoverflow.com/users/6386071", "pm_score": 1, "selected": false, "text": "<p>My solution returns an int which can then be used in printf. It can also return the bits in big endian or little endian order.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n\nint binary(uint8_t i,int bigEndian)\n{\n int j=0,m = bigEndian ? 1 : 10000000;\n while (i)\n {\n j+=m*(i%2);\n if (bigEndian) m*=10; else m/=10;\n i &gt;&gt;= 1;\n }\n return j;\n}\n\nint main()\n{\n char buf[]=\"ABCDEF\";\n printf(\"\\nbig endian = \");\n for (int i=0; i&lt;5; i++) printf(\"%08d \",binary(buf[i],1));\n printf(\"\\nwee endian = \");\n for (int i=0; i&lt;5; i++) printf(\"%08d \",binary(buf[i],0));\n getchar();\n return 0;\n}\n</code></pre>\n\n<p>Outputs</p>\n\n<pre><code>big endian = 01000001 01000010 01000011 01000100 01000101 01000110\nwee endian = 10000010 01000010 11000010 00100010 10100010 01100010\n</code></pre>\n" }, { "answer_id": 62265841, "author": "Cosmo Sterin", "author_id": 5825820, "author_profile": "https://Stackoverflow.com/users/5825820", "pm_score": 1, "selected": false, "text": "<p>The combination of functions + macro at the end of this answer can help you.</p>\n\n<p>Use it like that:</p>\n\n<pre><code>float float_var = 9.4;\nSHOW_BITS(float_var);\n</code></pre>\n\n<p>Which will output: <code>Variable 'float_var': 01000001 00010110 01100110 01100110</code></p>\n\n<p>Note that it is very general and can work with pretty much any type.\nFor instance:</p>\n\n<pre><code>struct {int a; float b; double c;} struct_var = {1,1.1,1.2};\nSHOW_BITS(struct_var);\n</code></pre>\n\n<p>Which will output: </p>\n\n<pre><code>Variable `struct_var`: 00111111 11110011 00110011 00110011 00110011 00110011 00110011 00110011 00111111 10001100 11001100 11001101 00000000 00000000 00000000 00000001\n</code></pre>\n\n<p>Here's the code:</p>\n\n<pre><code>#define SHOW_BITS(a) ({ \\\n printf(\"Variable `%s`: \", #a);\\\n show_bits(&amp;a, sizeof(a));\\\n})\n\nvoid show_uchar(unsigned char a)\n{\n for(int i = 7; i &gt;= 0; i-= 1) \n printf(\"%d\", ((a &gt;&gt; i) &amp; 1));\n}\n\nvoid show_bits(void* a, size_t s)\n{\n unsigned char* p = (unsigned char*) a;\n for(int i = s-1; i &gt;= 0 ; i -= 1) {\n show_uchar(p[i]);\n printf(\" \");\n }\n printf(\"\\n\");\n}\n</code></pre>\n" }, { "answer_id": 66298184, "author": "skyfire", "author_id": 6302316, "author_profile": "https://Stackoverflow.com/users/6302316", "pm_score": 1, "selected": false, "text": "<pre><code>void print_bits (uintmax_t n)\n{\n for (size_t i = 8 * sizeof (int); i-- != 0;)\n {\n char c;\n if ((n &amp; (1UL &lt;&lt; i)) != 0)\n c = '1';\n else\n c = '0';\n\n printf (&quot;%c&quot;, c);\n\n }\n}\n</code></pre>\n<p>Not a cover-absolutely-everywhere solution but if you want something quick, and easy to understand, I'm suprised no one has proposed this solution yet.</p>\n" }, { "answer_id": 66680811, "author": "D.Deriso", "author_id": 1438550, "author_profile": "https://Stackoverflow.com/users/1438550", "pm_score": 0, "selected": false, "text": "<p>Main.c</p>\n<pre><code>// Based on https://stackoverflow.com/a/112956/1438550\n\n#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n\nconst char *int_to_binary_str(int x, int N_bits){\n static char b[512];\n char *p = b;\n b[0] = '\\0';\n\n for(int i=(N_bits-1); i&gt;=0; i--){\n *p++ = (x &amp; (1&lt;&lt;i)) ? '1' : '0';\n if(!(i%4)) *p++ = ' ';\n }\n return b;\n}\n\nint main() {\n for(int i=31; i&gt;=0; i--){\n printf(&quot;0x%08X %s \\n&quot;, (1&lt;&lt;i), int_to_binary_str((1&lt;&lt;i), 32));\n }\n return 0;\n}\n</code></pre>\n<p>Expected behavior:</p>\n<pre><code>Run:\ngcc -pthread -Wformat=0 -lm -o main main.c; ./main\n\nOutput:\n0x80000000 1000 0000 0000 0000 0000 0000 0000 0000 \n0x40000000 0100 0000 0000 0000 0000 0000 0000 0000 \n0x20000000 0010 0000 0000 0000 0000 0000 0000 0000 \n0x10000000 0001 0000 0000 0000 0000 0000 0000 0000 \n0x08000000 0000 1000 0000 0000 0000 0000 0000 0000 \n0x04000000 0000 0100 0000 0000 0000 0000 0000 0000 \n0x02000000 0000 0010 0000 0000 0000 0000 0000 0000 \n0x01000000 0000 0001 0000 0000 0000 0000 0000 0000 \n0x00800000 0000 0000 1000 0000 0000 0000 0000 0000 \n0x00400000 0000 0000 0100 0000 0000 0000 0000 0000 \n0x00200000 0000 0000 0010 0000 0000 0000 0000 0000 \n0x00100000 0000 0000 0001 0000 0000 0000 0000 0000 \n0x00080000 0000 0000 0000 1000 0000 0000 0000 0000 \n0x00040000 0000 0000 0000 0100 0000 0000 0000 0000 \n0x00020000 0000 0000 0000 0010 0000 0000 0000 0000 \n0x00010000 0000 0000 0000 0001 0000 0000 0000 0000 \n0x00008000 0000 0000 0000 0000 1000 0000 0000 0000 \n0x00004000 0000 0000 0000 0000 0100 0000 0000 0000 \n0x00002000 0000 0000 0000 0000 0010 0000 0000 0000 \n0x00001000 0000 0000 0000 0000 0001 0000 0000 0000 \n0x00000800 0000 0000 0000 0000 0000 1000 0000 0000 \n0x00000400 0000 0000 0000 0000 0000 0100 0000 0000 \n0x00000200 0000 0000 0000 0000 0000 0010 0000 0000 \n0x00000100 0000 0000 0000 0000 0000 0001 0000 0000 \n0x00000080 0000 0000 0000 0000 0000 0000 1000 0000 \n0x00000040 0000 0000 0000 0000 0000 0000 0100 0000 \n0x00000020 0000 0000 0000 0000 0000 0000 0010 0000 \n0x00000010 0000 0000 0000 0000 0000 0000 0001 0000 \n0x00000008 0000 0000 0000 0000 0000 0000 0000 1000 \n0x00000004 0000 0000 0000 0000 0000 0000 0000 0100 \n0x00000002 0000 0000 0000 0000 0000 0000 0000 0010 \n0x00000001 0000 0000 0000 0000 0000 0000 0000 0001 \n</code></pre>\n" }, { "answer_id": 70930112, "author": "roylewilliam", "author_id": 8423241, "author_profile": "https://Stackoverflow.com/users/8423241", "pm_score": 0, "selected": false, "text": "<p>Simple, tested, works for any unsigned integer type. No headaches.</p>\n<pre><code>#include &lt;stdint.h&gt;\n#include &lt;stdio.h&gt;\n\n// Prints the binary representation of any unsigned integer\n// When running, pass 1 to first_call\nvoid printf_binary(unsigned int number, int first_call)\n{\n if (first_call)\n {\n printf(&quot;The binary representation of %d is [&quot;, number);\n }\n if (number &gt;&gt; 1)\n {\n printf_binary(number &gt;&gt; 1, 0);\n putc((number &amp; 1) ? '1' : '0', stdout);\n }\n else \n {\n putc((number &amp; 1) ? '1' : '0', stdout);\n }\n if (first_call)\n {\n printf(&quot;]\\n&quot;);\n }\n}\n</code></pre>\n" }, { "answer_id": 70993946, "author": "Kalcifer", "author_id": 7934600, "author_profile": "https://Stackoverflow.com/users/7934600", "pm_score": 4, "selected": false, "text": "<p>As of February 3rd, 2022, the GNU C Library been updated to <a href=\"https://web.archive.org/web/20221016003354/https://sourceware.org/pipermail/libc-alpha/2022-February/136040.html\" rel=\"nofollow noreferrer\">version 2.35</a>. As a result, <code>%b</code> is now supported to output in binary format.</p>\n<blockquote>\n<p>printf-family functions now support the %b format for output of\nintegers in binary, as specified in draft ISO C2X, and the %B variant\nof that format recommended by draft ISO C2X.</p>\n</blockquote>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8959/" ]
I can print with `printf` as a hex or octal number. Is there a format tag to print as binary, or arbitrary base? I am running gcc. ``` printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n" print("%b\n", 10); // prints "%b\n" ```
Hacky but works for me: ``` #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" #define BYTE_TO_BINARY(byte) \ (byte & 0x80 ? '1' : '0'), \ (byte & 0x40 ? '1' : '0'), \ (byte & 0x20 ? '1' : '0'), \ (byte & 0x10 ? '1' : '0'), \ (byte & 0x08 ? '1' : '0'), \ (byte & 0x04 ? '1' : '0'), \ (byte & 0x02 ? '1' : '0'), \ (byte & 0x01 ? '1' : '0') ``` ``` printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte)); ``` For multi-byte types ``` printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n", BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m)); ``` You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to `BYTE_TO_BINARY`) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.
111,934
<p>I want to create some text in a canvas:</p> <pre><code>myText = self.canvas.create_text(5, 5, anchor=NW, text=&quot;TEST&quot;) </code></pre> <p>Now how do I find the width and height of <code>myText</code>?</p>
[ { "answer_id": 111974, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 5, "selected": true, "text": "<pre><code>bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2)\nwidth = bounds[2] - bounds[0]\nheight = bounds[3] - bounds[1]\n</code></pre>\n<p>See the <a href=\"https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/canvas-methods.html\" rel=\"nofollow noreferrer\">TkInter reference</a>.</p>\n" }, { "answer_id": 35139726, "author": "user3754203", "author_id": 3754203, "author_profile": "https://Stackoverflow.com/users/3754203", "pm_score": 2, "selected": false, "text": "<p>This method seemed to work well if all you are interested in is the width and height of the canvas being considered, using the bounds of the box and then checking the differential works just as well if you want to do it that way.</p>\n\n<pre><code>width = myText.winfo_width() \nheight = myText.winfo_height()\n</code></pre>\n" }, { "answer_id": 72682436, "author": "Ninja Adober Gab", "author_id": 18438874, "author_profile": "https://Stackoverflow.com/users/18438874", "pm_score": 0, "selected": false, "text": "<p>JUST USE THIS FUNCTION:</p>\n<pre><code>def Height(Canvas, Object):\n Height = Canvas.bbox(Object)\n\n return Height[3] - Height[1]\ndef Width(Canvas, Object):\n Width = Canvas.bbox(Object)\n\n return Width[2] - Width[0]\ndef Position(Canvas, Object, X1=False, X2=False, Y1=False, Y2=False):\n Position = Canvas.bbox(Object)\n if X1 == True:\n return Position[0]\n if X2 == True:\n return Position[2]\n if Y1 == True:\n return Position[1]\n if Y2 == True:\n return Position[3]\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
I want to create some text in a canvas: ``` myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST") ``` Now how do I find the width and height of `myText`?
``` bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2) width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] ``` See the [TkInter reference](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/canvas-methods.html).
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
[ { "answer_id": 111952, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<p>Have you taken a look at <a href=\"http://inamidst.com/proj/put/put.py\" rel=\"nofollow noreferrer\">put.py</a>? I've used it in the past. You can also just hack up your own request with urllib.</p>\n" }, { "answer_id": 111968, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 2, "selected": false, "text": "<p>You can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib.</p>\n\n<p><a href=\"http://pycurl.sourceforge.net/\" rel=\"nofollow noreferrer\">http://pycurl.sourceforge.net/</a></p>\n\n<p>\"PyCurl is a Python interface to libcurl.\"</p>\n\n<p>\"libcurl is a free and easy-to-use client-side URL transfer library, ... supports ... HTTP PUT\"</p>\n\n<p>\"The main drawback with PycURL is that it is a relative thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl's C API. \"</p>\n" }, { "answer_id": 111973, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 3, "selected": false, "text": "<p>You should have a look at the <a href=\"http://docs.python.org/lib/module-httplib.html\" rel=\"noreferrer\">httplib module</a>. It should let you make whatever sort of HTTP request you want.</p>\n" }, { "answer_id": 111988, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 8, "selected": false, "text": "<pre><code>import urllib2\nopener = urllib2.build_opener(urllib2.HTTPHandler)\nrequest = urllib2.Request('http://example.org', data='your_put_data')\nrequest.add_header('Content-Type', 'your/contenttype')\nrequest.get_method = lambda: 'PUT'\nurl = opener.open(request)\n</code></pre>\n" }, { "answer_id": 114648, "author": "Mike", "author_id": 19215, "author_profile": "https://Stackoverflow.com/users/19215", "pm_score": 3, "selected": false, "text": "<p>I needed to solve this problem too a while back so that I could act as a client for a RESTful API. I settled on httplib2 because it allowed me to send PUT and DELETE in addition to GET and POST. Httplib2 is not part of the standard library but you can easily get it from the cheese shop.</p>\n" }, { "answer_id": 116122, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 3, "selected": false, "text": "<p>I also recommend <a href=\"http://code.google.com/p/httplib2/\" rel=\"nofollow noreferrer\">httplib2</a> by Joe Gregario. I use this regularly instead of httplib in the standard lib.</p>\n" }, { "answer_id": 3919484, "author": "Spooles", "author_id": 182750, "author_profile": "https://Stackoverflow.com/users/182750", "pm_score": 6, "selected": false, "text": "<p>Httplib seems like a cleaner choice.</p>\n\n<pre><code>import httplib\nconnection = httplib.HTTPConnection('1.2.3.4:1234')\nbody_content = 'BODY CONTENT GOES HERE'\nconnection.request('PUT', '/url/path/to/put/to', body_content)\nresult = connection.getresponse()\n# Now result.status and result.reason contains interesting stuff\n</code></pre>\n" }, { "answer_id": 8259648, "author": "John Carter", "author_id": 459082, "author_profile": "https://Stackoverflow.com/users/459082", "pm_score": 9, "selected": true, "text": "<p>I've used a variety of python HTTP libs in the past, and I've settled on <a href=\"https://requests.readthedocs.io/\" rel=\"nofollow noreferrer\">requests</a> as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:</p>\n<pre><code>payload = {'username': 'bob', 'email': '[email protected]'}\n&gt;&gt;&gt; r = requests.put(&quot;http://somedomain.org/endpoint&quot;, data=payload)\n</code></pre>\n<p>You can then check the response status code with:</p>\n<pre><code>r.status_code\n</code></pre>\n<p>or the response with:</p>\n<pre><code>r.content\n</code></pre>\n<p>Requests has a lot synactic sugar and shortcuts that'll make your life easier.</p>\n" }, { "answer_id": 26045274, "author": "radtek", "author_id": 2023392, "author_profile": "https://Stackoverflow.com/users/2023392", "pm_score": 4, "selected": false, "text": "<p>You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:</p>\n\n<pre><code>pip install requests\n</code></pre>\n\n<p>More on <a href=\"http://docs.python-requests.org/en/latest/user/install/\" rel=\"noreferrer\">installing requests</a>.</p>\n\n<p>Then setup the put request:</p>\n\n<pre><code>import requests\nimport json\nurl = 'https://api.github.com/some/endpoint'\npayload = {'some': 'data'}\n\n# Create your header as required\nheaders = {\"content-type\": \"application/json\", \"Authorization\": \"&lt;auth-key&gt;\" }\n\nr = requests.put(url, data=json.dumps(payload), headers=headers)\n</code></pre>\n\n<p>See the <a href=\"http://docs.python-requests.org/en/latest/user/quickstart/\" rel=\"noreferrer\">quickstart for requests library</a>. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.</p>\n" }, { "answer_id": 44781372, "author": "Wilfred Hughes", "author_id": 509706, "author_profile": "https://Stackoverflow.com/users/509706", "pm_score": 2, "selected": false, "text": "<p>If you want to stay within the standard library, you can subclass <code>urllib2.Request</code>:</p>\n\n<pre><code>import urllib2\n\nclass RequestWithMethod(urllib2.Request):\n def __init__(self, *args, **kwargs):\n self._method = kwargs.pop('method', None)\n urllib2.Request.__init__(self, *args, **kwargs)\n\n def get_method(self):\n return self._method if self._method else super(RequestWithMethod, self).get_method()\n\n\ndef put_request(url, data):\n opener = urllib2.build_opener(urllib2.HTTPHandler)\n request = RequestWithMethod(url, method='PUT', data=data)\n return opener.open(request)\n</code></pre>\n" }, { "answer_id": 48144049, "author": "anthony sottile", "author_id": 812183, "author_profile": "https://Stackoverflow.com/users/812183", "pm_score": 3, "selected": false, "text": "<p>This was made better in python3 and documented in <a href=\"https://docs.python.org/3/library/urllib.request.html\" rel=\"noreferrer\">the stdlib documentation</a></p>\n\n<p>The <code>urllib.request.Request</code> class gained a <code>method=...</code> parameter in python3.</p>\n\n<p>Some sample usage:</p>\n\n<pre><code>req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')\nurllib.request.urlopen(req)\n</code></pre>\n" }, { "answer_id": 59418081, "author": "Adam Erickson", "author_id": 2058131, "author_profile": "https://Stackoverflow.com/users/2058131", "pm_score": 0, "selected": false, "text": "<p>A more proper way of doing this with <code>requests</code> would be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import requests\n\npayload = {'username': 'bob', 'email': '[email protected]'}\n\ntry:\n response = requests.put(url=\"http://somedomain.org/endpoint\", data=payload)\n response.raise_for_status()\nexcept requests.exceptions.RequestException as e:\n print(e)\n raise\n</code></pre>\n\n<p>This raises an exception if there is an error in the HTTP PUT request.</p>\n" }, { "answer_id": 63219845, "author": "Ransaka Ravihara", "author_id": 11745014, "author_profile": "https://Stackoverflow.com/users/11745014", "pm_score": 0, "selected": false, "text": "<h2>Using <a href=\"https://urllib3.readthedocs.io/en/latest/user-guide.html\" rel=\"nofollow noreferrer\"><code>urllib3</code></a></h2>\n<p>To do that, you will need to manually encode query parameters in the URL.</p>\n<pre><code>&gt;&gt;&gt; import urllib3\n&gt;&gt;&gt; http = urllib3.PoolManager()\n&gt;&gt;&gt; from urllib.parse import urlencode\n&gt;&gt;&gt; encoded_args = urlencode({&quot;name&quot;:&quot;Zion&quot;,&quot;salary&quot;:&quot;1123&quot;,&quot;age&quot;:&quot;23&quot;})\n&gt;&gt;&gt; url = 'http://dummy.restapiexample.com/api/v1/update/15410' + encoded_args\n&gt;&gt;&gt; r = http.request('PUT', url)\n&gt;&gt;&gt; import json\n&gt;&gt;&gt; json.loads(r.data.decode('utf-8'))\n{'status': 'success', 'data': [], 'message': 'Successfully! Record has been updated.'}\n</code></pre>\n<h2>Using <a href=\"https://requests.readthedocs.io/en/master/user/quickstart/\" rel=\"nofollow noreferrer\"><code>requests</code></a></h2>\n<pre><code>&gt;&gt;&gt; import requests\n&gt;&gt;&gt; r = requests.put('https://httpbin.org/put', data = {'key':'value'})\n&gt;&gt;&gt; r.status_code\n200\n</code></pre>\n" }, { "answer_id": 66382115, "author": "SuperNova", "author_id": 3464971, "author_profile": "https://Stackoverflow.com/users/3464971", "pm_score": 1, "selected": false, "text": "<p>You can use <code>requests.request</code></p>\n<pre><code>import requests\n\nurl = &quot;https://www.example/com/some/url/&quot;\npayload=&quot;{\\&quot;param1\\&quot;: 1, \\&quot;param1\\&quot;: 2}&quot;\nheaders = {\n 'Authorization': '....',\n 'Content-Type': 'application/json'\n}\n\nresponse = requests.request(&quot;PUT&quot;, url, headers=headers, data=payload)\n\nprint(response.text)\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161922/" ]
I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python?
I've used a variety of python HTTP libs in the past, and I've settled on [requests](https://requests.readthedocs.io/) as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like: ``` payload = {'username': 'bob', 'email': '[email protected]'} >>> r = requests.put("http://somedomain.org/endpoint", data=payload) ``` You can then check the response status code with: ``` r.status_code ``` or the response with: ``` r.content ``` Requests has a lot synactic sugar and shortcuts that'll make your life easier.
111,954
<p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p> <pre><code># File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line </code></pre> <p>Which yields:</p> <pre><code>$ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -&gt; welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... </code></pre> <p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p> <p>Is there a portable way to get an array filled with the directory listing?</p> <p>(The array should only have the folder names.)</p>
[ { "answer_id": 111966, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 8, "selected": true, "text": "<p>Try using <a href=\"https://docs.python.org/3/library/ftplib.html#ftplib.FTP.nlst\" rel=\"noreferrer\"><code>ftp.nlst(dir)</code></a>.</p>\n<p>However, note that if the folder is empty, it might throw an error:</p>\n<pre><code>files = []\n\ntry:\n files = ftp.nlst()\nexcept ftplib.error_perm as resp:\n if str(resp) == &quot;550 No files found&quot;:\n print &quot;No files in this directory&quot;\n else:\n raise\n\nfor f in files:\n print f\n</code></pre>\n" }, { "answer_id": 111978, "author": "Garth Kidd", "author_id": 5700, "author_profile": "https://Stackoverflow.com/users/5700", "pm_score": 2, "selected": false, "text": "<p>There's no standard for the layout of the <code>LIST</code> response. You'd have to write code to handle the most popular layouts. I'd start with Linux <code>ls</code> and Windows Server <code>DIR</code> formats. There's a lot of variety out there, though. </p>\n\n<p>Fall back to the <code>nlst</code> method (returning the result of the <code>NLST</code> command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length. </p>\n" }, { "answer_id": 8474838, "author": "Giampaolo Rodolà", "author_id": 376587, "author_profile": "https://Stackoverflow.com/users/376587", "pm_score": 5, "selected": false, "text": "<p>The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.</p>\n\n<pre><code>import ftplib\nf = ftplib.FTP()\nf.connect(\"localhost\")\nf.login()\nls = []\nf.retrlines('MLSD', ls.append)\nfor entry in ls:\n print entry\n</code></pre>\n\n<p>The code above will print:</p>\n\n<pre><code>modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests\nmodify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2\nmodify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd\nmodify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart\n...\n</code></pre>\n\n<p>Starting from python 3.3, ftplib will provide a specific method to do this:</p>\n\n<ul>\n<li><a href=\"http://bugs.python.org/issue11072\" rel=\"noreferrer\">http://bugs.python.org/issue11072</a></li>\n<li><a href=\"http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535\" rel=\"noreferrer\">http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535</a></li>\n</ul>\n" }, { "answer_id": 24090402, "author": "Steve Saporta", "author_id": 2108698, "author_profile": "https://Stackoverflow.com/users/2108698", "pm_score": 1, "selected": false, "text": "<p>I happen to be stuck with an FTP server (Rackspace Cloud Sites virtual server) that doesn't seem to support MLSD. Yet I need several fields of file information, such as size and timestamp, not just the filename, so I have to use the DIR command. On this server, the output of DIR looks very much like the OP's. In case it helps anyone, here's a little Python class that parses a line of such output to obtain the filename, size and timestamp.</p>\n\n<p>import datetime</p>\n\n<pre><code>class FtpDir:\n def parse_dir_line(self, line):\n words = line.split()\n self.filename = words[8]\n self.size = int(words[4])\n t = words[7].split(':')\n ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]\n self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')\n</code></pre>\n\n<p>Not very portable, I know, but easy to extend or modify to deal with various different FTP servers.</p>\n" }, { "answer_id": 43818506, "author": "Jeeva", "author_id": 4737293, "author_profile": "https://Stackoverflow.com/users/4737293", "pm_score": 0, "selected": false, "text": "<p>This is from Python docs</p>\n\n<pre><code>&gt;&gt;&gt; from ftplib import FTP_TLS\n&gt;&gt;&gt; ftps = FTP_TLS('ftp.python.org')\n&gt;&gt;&gt; ftps.login() # login anonymously before securing control \nchannel\n&gt;&gt;&gt; ftps.prot_p() # switch to secure data connection\n&gt;&gt;&gt; ftps.retrlines('LIST') # list directory content securely\ntotal 9\ndrwxr-xr-x 8 root wheel 1024 Jan 3 1994 .\ndrwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..\ndrwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin\ndrwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc\nd-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming\ndrwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib\ndrwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub\ndrwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr\n-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg\n</code></pre>\n" }, { "answer_id": 43830703, "author": "MTS", "author_id": 7853455, "author_profile": "https://Stackoverflow.com/users/7853455", "pm_score": 0, "selected": false, "text": "<p>That helped me with my code.</p>\n\n<p>When I tried feltering only a type of files and show them on screen by adding a condition that tests on each line.</p>\n\n<p>Like this </p>\n\n<pre><code>elif command == 'ls':\n print(\"directory of \", ftp.pwd())\n data = []\n ftp.dir(data.append)\n\n for line in data:\n x = line.split(\".\")\n formats=[\"gz\", \"zip\", \"rar\", \"tar\", \"bz2\", \"xz\"]\n if x[-1] in formats:\n print (\"-\", line)\n</code></pre>\n" }, { "answer_id": 45684176, "author": "chill_turner", "author_id": 2639868, "author_profile": "https://Stackoverflow.com/users/2639868", "pm_score": 3, "selected": false, "text": "<p>I found my way here while trying to get filenames, last modified stamps, file sizes etc and wanted to add my code. It only took a few minutes to write a loop to parse the <code>ftp.dir(dir_list.append)</code> making use of python std lib stuff like <code>strip()</code> (to clean up the line of text) and <code>split()</code> to create an array.</p>\n\n<pre><code>ftp = FTP('sick.domain.bro')\nftp.login()\nftp.cwd('path/to/data')\n\ndir_list = []\nftp.dir(dir_list.append)\n\n# main thing is identifing which char marks start of good stuff\n# '-rw-r--r-- 1 ppsrt ppsrt 545498 Jul 23 12:07 FILENAME.FOO\n# ^ (that is line[29])\n\nfor line in dir_list:\n print line[29:].strip().split(' ') # got yerself an array there bud!\n # EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is: ``` # File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line ``` Which yields: ``` $ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... ``` I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list. Is there a portable way to get an array filled with the directory listing? (The array should only have the folder names.)
Try using [`ftp.nlst(dir)`](https://docs.python.org/3/library/ftplib.html#ftplib.FTP.nlst). However, note that if the folder is empty, it might throw an error: ``` files = [] try: files = ftp.nlst() except ftplib.error_perm as resp: if str(resp) == "550 No files found": print "No files in this directory" else: raise for f in files: print f ```
112,036
<p>I'm using the AdvancedDataGrid widget and I want two columns to be radio buttons, where each column is it's own RadioButtonGroup. I thought I had all the necessary mxxml, but I'm running into a strange behavior issue. When I scroll up and down, the button change values! The selected button becomes deselected, and unselected ones become selected. Anyone have a clue about this bug? Should I being going about this a different way. -- Here's a stripped down example of what I trying to do.</p> <pre><code>&lt;mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:RadioButtonGroup id="leftAxisGrp" /&gt; &lt;mx:RadioButtonGroup id="rightAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ trace (rightAxisGrp.selection); trace (rightAxisGrp.selection.data.name); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" height="150" width="400" sortExpertMode="true" selectable="false"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn headerText="L" width="25" paddingLeft="6" dataField="left" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="leftAxisGrp" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="R" width="25" paddingLeft="6" dataField="right" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="rightAxisGrp" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="" dataField="name" /&gt; &lt;/mx:columns&gt; &lt;mx:dataProvider&gt; &lt;mx:Array&gt; &lt;mx:Object left="false" right="false" name="Reddish-gray Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Golden-brown Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Northern Rufous Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Sambirano Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Simmons' Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Pygmy Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Brown Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Madame Berthe's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Goodman's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Jolly's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Mittermeier's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Claire's Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Danfoss' Mouse Lemur" /&gt; &lt;mx:Object left="false" right="false" name="Lokobe Mouse Lemur" /&gt; &lt;mx:Object left="true" right="true" name="Bongolava Mouse Lemur" /&gt; &lt;/mx:Array&gt; &lt;/mx:dataProvider&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;/mx:WindowedApplication&gt; </code></pre> <hr> <p><em>UPDATED</em> (thanks bill!)</p> <p>Alright! Go it working. I just had to make a couple of changes from bill's suggestion. Mainly using ArrayCollection with ObjectProxy so it was both bindable and dynamic. One weird thing - I couldn't select a button in the first row if I filled in the array at construction time; I had to delay that until the creationComplete event was fired (which is fine, since I'm going to populate the grid from a db anyway).</p> <pre><code>&lt;mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.utils.ObjectProxy; import mx.collections.ArrayCollection; [Bindable] private var myData:ArrayCollection = new ArrayCollection (); private function selectItem (selObject:Object, property:String) : void { for each (var obj:ObjectProxy in myData) { obj[property] = (obj.name === selObject.name); } readingsGrid.invalidateDisplayList (); } ]]&gt; &lt;/mx:Script&gt; &lt;mx:RadioButtonGroup id="leftAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ selectItem (leftAxisGrp.selectedValue, 'left'); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:RadioButtonGroup id="rightAxisGrp"&gt; &lt;mx:change&gt; &lt;![CDATA[ selectItem (rightAxisGrp.selectedValue, 'right'); ]]&gt; &lt;/mx:change&gt; &lt;/mx:RadioButtonGroup&gt; &lt;mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" dataProvider="{myData}" sortExpertMode="true" height="150" width="400" selectable="false"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn id="leftCol" headerText="L" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="leftAxisGrp" buttonMode="true" value="{data}" selected="{data.left}" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn id="rightCol" headerText="R" width="25" paddingLeft="6" sortable="false"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:RadioButton groupName="rightAxisGrp" buttonMode="true" value="{data}" selected="{data.right}" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:AdvancedDataGridColumn&gt; &lt;mx:AdvancedDataGridColumn headerText="" dataField="name" /&gt; &lt;/mx:columns&gt; &lt;mx:creationComplete&gt; &lt;![CDATA[ myData.addItem(new ObjectProxy ({ left:true, right:true, name:"Golden-brown Mouse Lemur" })); myData.addItem(new ObjectProxy ({ left:false, right:false, name:"Reddish-gray Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Northern Rufous Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Sambirano Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Simmons' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Pygmy Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Brown Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Madame Berthe's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Goodman's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Jolly's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Mittermeier's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Claire's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Danfoss' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Lokobe Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Bongolava Mouse Lemur" })); ]]&gt; &lt;/mx:creationComplete&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;/mx:WindowedApplication&gt; </code></pre>
[ { "answer_id": 112822, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 0, "selected": false, "text": "<p>Reproduced this. Likely to be a ADG bug, we've run into a few here. (Didn't find this one on bugs.adobe.com, but their search sucks).</p>\n\n<p>You could try Flex 3.0.3, or a nightly build <a href=\"http://labs.adobe.com/technologies/flex/sdk/flex3sdk.html\" rel=\"nofollow noreferrer\">here</a> (warning, may be pretty broken), and see if they've fixed it, or you could try implementing a custom renderer, but that is a pain to get right.</p>\n" }, { "answer_id": 115926, "author": "bill d", "author_id": 1798, "author_profile": "https://Stackoverflow.com/users/1798", "pm_score": 2, "selected": true, "text": "<p>What's happening here is that Flex only creates itemRenderer instances for the <em>visible</em> columns. When you scroll around, those instances get recycled. So if you scroll down, the RadioButton object that was drawing the first column of the first row may now have changed to instead be drawing the first column of the seventh row. Flex resets the \"data\" property of the itemRenderer whenever this happens.</p>\n\n<p>So while there are 15 rows of data, there are only ever 12 RadioButtons (6 for the \"left\", and 6 for the \"right\" for the 6 visible rows), not 30 RadioButtons, as you might expect. This isn't a big problem if you're only <em>displaying</em> the selection, but it becomes more of a problem when you allow updates.</p>\n\n<p>To fix the display issue, instead of setting the \"dataField\" on the column, you can bind the RadioButton's \"selected\" property to the itemRenderer's data.left (or right) value. You'll then need to make the items in your dataProvider \"Bindable\".</p>\n\n<p>To fix the update issue, since you'd be binding directly to the dataProvider item values, you need to be sure to update them. Since there's isn't one RadioButton per-item, you'll need another scheme for that. In this case I put in a handler that goes and sets the left/right property of each item to \"false\", except for the \"selected\" one, which gets set to \"true\".</p>\n\n<p>I updated your example code based on these thoughts. Try something like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:Application layout=\"absolute\"\n xmlns:my=\"*\"\n xmlns:mx=\"http://www.adobe.com/2006/mxml\"&gt;\n &lt;mx:RadioButtonGroup id=\"leftAxisGrp\"\n change=\"selectItem(leftAxisGrp.selectedValue, 'left');\"/&gt;\n &lt;mx:RadioButtonGroup id=\"rightAxisGrp\"\n change=\"selectItem(rightAxisGrp.selectedValue, 'right');\"&gt;\n &lt;/mx:RadioButtonGroup&gt;\n &lt;mx:AdvancedDataGrid\n id=\"readingsGrid\"\n designViewDataType=\"flat\"\n height=\"150\" width=\"400\"\n sortExpertMode=\"true\"\n selectable=\"false\"\n dataProvider=\"{adgData.object}\"&gt;\n &lt;mx:columns&gt;\n &lt;mx:AdvancedDataGridColumn\n headerText=\"L\" width=\"25\" paddingLeft=\"6\"\n sortable=\"false\"&gt;\n &lt;mx:itemRenderer&gt;\n &lt;mx:Component&gt;\n &lt;mx:RadioButton groupName=\"leftAxisGrp\" \n value=\"{data}\" selected=\"{data.left}\"/&gt;\n &lt;/mx:Component&gt;\n &lt;/mx:itemRenderer&gt;\n &lt;/mx:AdvancedDataGridColumn&gt;\n &lt;mx:AdvancedDataGridColumn\n headerText=\"R\" width=\"25\" paddingLeft=\"6\"\n sortable=\"false\"&gt;\n &lt;mx:itemRenderer&gt;\n &lt;mx:Component&gt;\n &lt;mx:RadioButton groupName=\"rightAxisGrp\"\n value=\"{data}\" selected=\"{data.right}\"/&gt;\n &lt;/mx:Component&gt;\n &lt;/mx:itemRenderer&gt;\n &lt;/mx:AdvancedDataGridColumn&gt;\n &lt;mx:AdvancedDataGridColumn headerText=\"\" dataField=\"name\" /&gt;\n &lt;/mx:columns&gt;\n &lt;/mx:AdvancedDataGrid&gt;\n &lt;mx:Model id=\"adgData\"&gt;\n &lt;root&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Reddish-gray Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Golden-brown Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Northern Rufous Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Sambirano Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Simmons' Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Pygmy Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Brown Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Madame Berthe's Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Goodman's Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Jolly's Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Mittermeier's Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Claire's Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Danfoss' Mouse Lemur\" /&gt;\n &lt;object left=\"false\" right=\"false\" name=\"Lokobe Mouse Lemur\" /&gt;\n &lt;object left=\"true\" right=\"true\" name=\"Bongolava Mouse Lemur\" /&gt;\n &lt;/root&gt;\n &lt;/mx:Model&gt;\n &lt;mx:Script&gt;\n &lt;![CDATA[\n private function selectItem(selObject:Object, property:String) : void {\n for each(var obj:Object in adgData.object) {\n obj[property] = (obj === selObject);\n }\n readingsGrid.invalidateDisplayList();\n }\n ]]&gt;\n &lt;/mx:Script&gt;\n&lt;/mx:Application&gt;\n</code></pre>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7536/" ]
I'm using the AdvancedDataGrid widget and I want two columns to be radio buttons, where each column is it's own RadioButtonGroup. I thought I had all the necessary mxxml, but I'm running into a strange behavior issue. When I scroll up and down, the button change values! The selected button becomes deselected, and unselected ones become selected. Anyone have a clue about this bug? Should I being going about this a different way. -- Here's a stripped down example of what I trying to do. ``` <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:RadioButtonGroup id="leftAxisGrp" /> <mx:RadioButtonGroup id="rightAxisGrp"> <mx:change> <![CDATA[ trace (rightAxisGrp.selection); trace (rightAxisGrp.selection.data.name); ]]> </mx:change> </mx:RadioButtonGroup> <mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" height="150" width="400" sortExpertMode="true" selectable="false"> <mx:columns> <mx:AdvancedDataGridColumn headerText="L" width="25" paddingLeft="6" dataField="left" sortable="false"> <mx:itemRenderer> <mx:Component> <mx:RadioButton groupName="leftAxisGrp" /> </mx:Component> </mx:itemRenderer> </mx:AdvancedDataGridColumn> <mx:AdvancedDataGridColumn headerText="R" width="25" paddingLeft="6" dataField="right" sortable="false"> <mx:itemRenderer> <mx:Component> <mx:RadioButton groupName="rightAxisGrp" /> </mx:Component> </mx:itemRenderer> </mx:AdvancedDataGridColumn> <mx:AdvancedDataGridColumn headerText="" dataField="name" /> </mx:columns> <mx:dataProvider> <mx:Array> <mx:Object left="false" right="false" name="Reddish-gray Mouse Lemur" /> <mx:Object left="false" right="false" name="Golden-brown Mouse Lemur" /> <mx:Object left="false" right="false" name="Northern Rufous Mouse Lemur" /> <mx:Object left="false" right="false" name="Sambirano Mouse Lemur" /> <mx:Object left="false" right="false" name="Simmons' Mouse Lemur" /> <mx:Object left="false" right="false" name="Pygmy Mouse Lemur" /> <mx:Object left="false" right="false" name="Brown Mouse Lemur" /> <mx:Object left="false" right="false" name="Madame Berthe's Mouse Lemur" /> <mx:Object left="false" right="false" name="Goodman's Mouse Lemur" /> <mx:Object left="false" right="false" name="Jolly's Mouse Lemur" /> <mx:Object left="false" right="false" name="Mittermeier's Mouse Lemur" /> <mx:Object left="false" right="false" name="Claire's Mouse Lemur" /> <mx:Object left="false" right="false" name="Danfoss' Mouse Lemur" /> <mx:Object left="false" right="false" name="Lokobe Mouse Lemur" /> <mx:Object left="true" right="true" name="Bongolava Mouse Lemur" /> </mx:Array> </mx:dataProvider> </mx:AdvancedDataGrid> </mx:WindowedApplication> ``` --- *UPDATED* (thanks bill!) Alright! Go it working. I just had to make a couple of changes from bill's suggestion. Mainly using ArrayCollection with ObjectProxy so it was both bindable and dynamic. One weird thing - I couldn't select a button in the first row if I filled in the array at construction time; I had to delay that until the creationComplete event was fired (which is fine, since I'm going to populate the grid from a db anyway). ``` <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.utils.ObjectProxy; import mx.collections.ArrayCollection; [Bindable] private var myData:ArrayCollection = new ArrayCollection (); private function selectItem (selObject:Object, property:String) : void { for each (var obj:ObjectProxy in myData) { obj[property] = (obj.name === selObject.name); } readingsGrid.invalidateDisplayList (); } ]]> </mx:Script> <mx:RadioButtonGroup id="leftAxisGrp"> <mx:change> <![CDATA[ selectItem (leftAxisGrp.selectedValue, 'left'); ]]> </mx:change> </mx:RadioButtonGroup> <mx:RadioButtonGroup id="rightAxisGrp"> <mx:change> <![CDATA[ selectItem (rightAxisGrp.selectedValue, 'right'); ]]> </mx:change> </mx:RadioButtonGroup> <mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" dataProvider="{myData}" sortExpertMode="true" height="150" width="400" selectable="false"> <mx:columns> <mx:AdvancedDataGridColumn id="leftCol" headerText="L" width="25" paddingLeft="6" sortable="false"> <mx:itemRenderer> <mx:Component> <mx:RadioButton groupName="leftAxisGrp" buttonMode="true" value="{data}" selected="{data.left}" /> </mx:Component> </mx:itemRenderer> </mx:AdvancedDataGridColumn> <mx:AdvancedDataGridColumn id="rightCol" headerText="R" width="25" paddingLeft="6" sortable="false"> <mx:itemRenderer> <mx:Component> <mx:RadioButton groupName="rightAxisGrp" buttonMode="true" value="{data}" selected="{data.right}" /> </mx:Component> </mx:itemRenderer> </mx:AdvancedDataGridColumn> <mx:AdvancedDataGridColumn headerText="" dataField="name" /> </mx:columns> <mx:creationComplete> <![CDATA[ myData.addItem(new ObjectProxy ({ left:true, right:true, name:"Golden-brown Mouse Lemur" })); myData.addItem(new ObjectProxy ({ left:false, right:false, name:"Reddish-gray Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Northern Rufous Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Sambirano Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Simmons' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Pygmy Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Brown Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Madame Berthe's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Goodman's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Jolly's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Mittermeier's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Claire's Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Danfoss' Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Lokobe Mouse Lemur" })); myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Bongolava Mouse Lemur" })); ]]> </mx:creationComplete> </mx:AdvancedDataGrid> </mx:WindowedApplication> ```
What's happening here is that Flex only creates itemRenderer instances for the *visible* columns. When you scroll around, those instances get recycled. So if you scroll down, the RadioButton object that was drawing the first column of the first row may now have changed to instead be drawing the first column of the seventh row. Flex resets the "data" property of the itemRenderer whenever this happens. So while there are 15 rows of data, there are only ever 12 RadioButtons (6 for the "left", and 6 for the "right" for the 6 visible rows), not 30 RadioButtons, as you might expect. This isn't a big problem if you're only *displaying* the selection, but it becomes more of a problem when you allow updates. To fix the display issue, instead of setting the "dataField" on the column, you can bind the RadioButton's "selected" property to the itemRenderer's data.left (or right) value. You'll then need to make the items in your dataProvider "Bindable". To fix the update issue, since you'd be binding directly to the dataProvider item values, you need to be sure to update them. Since there's isn't one RadioButton per-item, you'll need another scheme for that. In this case I put in a handler that goes and sets the left/right property of each item to "false", except for the "selected" one, which gets set to "true". I updated your example code based on these thoughts. Try something like this: ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application layout="absolute" xmlns:my="*" xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:RadioButtonGroup id="leftAxisGrp" change="selectItem(leftAxisGrp.selectedValue, 'left');"/> <mx:RadioButtonGroup id="rightAxisGrp" change="selectItem(rightAxisGrp.selectedValue, 'right');"> </mx:RadioButtonGroup> <mx:AdvancedDataGrid id="readingsGrid" designViewDataType="flat" height="150" width="400" sortExpertMode="true" selectable="false" dataProvider="{adgData.object}"> <mx:columns> <mx:AdvancedDataGridColumn headerText="L" width="25" paddingLeft="6" sortable="false"> <mx:itemRenderer> <mx:Component> <mx:RadioButton groupName="leftAxisGrp" value="{data}" selected="{data.left}"/> </mx:Component> </mx:itemRenderer> </mx:AdvancedDataGridColumn> <mx:AdvancedDataGridColumn headerText="R" width="25" paddingLeft="6" sortable="false"> <mx:itemRenderer> <mx:Component> <mx:RadioButton groupName="rightAxisGrp" value="{data}" selected="{data.right}"/> </mx:Component> </mx:itemRenderer> </mx:AdvancedDataGridColumn> <mx:AdvancedDataGridColumn headerText="" dataField="name" /> </mx:columns> </mx:AdvancedDataGrid> <mx:Model id="adgData"> <root> <object left="false" right="false" name="Reddish-gray Mouse Lemur" /> <object left="false" right="false" name="Golden-brown Mouse Lemur" /> <object left="false" right="false" name="Northern Rufous Mouse Lemur" /> <object left="false" right="false" name="Sambirano Mouse Lemur" /> <object left="false" right="false" name="Simmons' Mouse Lemur" /> <object left="false" right="false" name="Pygmy Mouse Lemur" /> <object left="false" right="false" name="Brown Mouse Lemur" /> <object left="false" right="false" name="Madame Berthe's Mouse Lemur" /> <object left="false" right="false" name="Goodman's Mouse Lemur" /> <object left="false" right="false" name="Jolly's Mouse Lemur" /> <object left="false" right="false" name="Mittermeier's Mouse Lemur" /> <object left="false" right="false" name="Claire's Mouse Lemur" /> <object left="false" right="false" name="Danfoss' Mouse Lemur" /> <object left="false" right="false" name="Lokobe Mouse Lemur" /> <object left="true" right="true" name="Bongolava Mouse Lemur" /> </root> </mx:Model> <mx:Script> <![CDATA[ private function selectItem(selObject:Object, property:String) : void { for each(var obj:Object in adgData.object) { obj[property] = (obj === selObject); } readingsGrid.invalidateDisplayList(); } ]]> </mx:Script> </mx:Application> ```
112,055
<p>I'm looking at a batch file which defines the following variables:</p> <pre><code>set _SCRIPT_DRIVE=%~d0 set _SCRIPT_PATH=%~p0 </code></pre> <ul> <li>What do <code>%~d0</code> or <code>%~p0</code> actually mean?</li> <li>Is there a set of well-known values for things like current directory, drive, parameters to a script?</li> <li>Are there any other similar shortcuts I could use?</li> </ul>
[ { "answer_id": 112071, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 4, "selected": false, "text": "<p>From <em><a href=\"http://www.rgagnon.com/gp/gp-0008.html\" rel=\"noreferrer\" title=\"Filename parsing in batch file and more idioms - Real&#39;s How-to\">Filename parsing in batch file and more idioms - Real's How-to</a></em>:</p>\n\n<p>The path (without drive) where the script is : ~p0</p>\n\n<p>The drive where the script is : ~d0 </p>\n" }, { "answer_id": 112074, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": false, "text": "<p><code>%~d0</code> gives you the drive letter of argument 0 (the script name), <code>%~p0</code> the path.</p>\n" }, { "answer_id": 112120, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 7, "selected": false, "text": "<p>They are enhanced variable substitutions. They modify the %N variables used in batch files. Quite useful if you're into batch programming in Windows.</p>\n\n<pre><code>%~I - expands %I removing any surrounding quotes (\"\")\n%~fI - expands %I to a fully qualified path name\n%~dI - expands %I to a drive letter only\n%~pI - expands %I to a path only\n%~nI - expands %I to a file name only\n%~xI - expands %I to a file extension only\n%~sI - expanded path contains short names only\n%~aI - expands %I to file attributes of file\n%~tI - expands %I to date/time of file\n%~zI - expands %I to size of file\n%~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n</code></pre>\n\n<p>You can find the above by running <a href=\"https://technet.microsoft.com/en-us/library/bb490909.aspx\" rel=\"noreferrer\"><code>FOR /?</code></a>.</p>\n" }, { "answer_id": 112135, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 10, "selected": true, "text": "<p>The magic variables <code>%</code><em>n</em> contains the arguments used to invoke the file: <code>%0</code> is the path to the bat-file itself, <code>%1</code> is the first argument after, <code>%2</code> is the second and so on.</p>\n\n<p>Since the arguments are often file paths, there is some additional syntax to extract parts of the path. <code>~d</code> is drive, <code>~p</code> is the path (without drive), <code>~n</code> is the file name. They can be combined so <code>~dp</code> is drive+path.</p>\n\n<p><code>%~dp0</code> is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.</p>\n\n<p>You can also get other kinds of meta info about the file: <code>~t</code> is the timestamp, <code>~z</code> is the size. </p>\n\n<p>Look <a href=\"http://technet.microsoft.com/en-us/library/bb490890.aspx\" rel=\"noreferrer\">here</a> for a reference for all command line commands. The tilde-magic codes are described under <a href=\"http://technet.microsoft.com/en-us/library/bb490909.aspx\" rel=\"noreferrer\">for</a>.</p>\n" }, { "answer_id": 12484802, "author": "Clewaks", "author_id": 1515947, "author_profile": "https://Stackoverflow.com/users/1515947", "pm_score": 6, "selected": false, "text": "<p>Yes, There are other shortcuts that you can use which are given below. \nIn your command, ~d0 would mean the drive letter of the 0th argument. </p>\n\n<pre><code>~ expands the given variable\nd gets the drive letter only\n0 is the argument you are referencing\n</code></pre>\n\n<p>As the 0th argument is the script path, it gets the drive letter of the path for you. You can use the following shortcuts too.</p>\n\n<pre><code>%~1 - expands %1 removing any surrounding quotes (\")\n%~f1 - expands %1 to a fully qualified path name\n%~d1 - expands %1 to a drive letter only\n%~p1 - expands %1 to a path only\n%~n1 - expands %1 to a file name only\n%~x1 - expands %1 to a file extension only\n%~s1 - expanded path contains short names only\n%~a1 - expands %1 to file attributes\n%~t1 - expands %1 to date/time of file\n%~z1 - expands %1 to size of file\n%~$PATH:1 - searches the directories listed in the PATH\n environment variable and expands %1 to the fully\n qualified name of the first one found. If the\n environment variable name is not defined or the\n file is not found by the search, then this\n modifier expands to the empty string \n\n%~dp1 - expands %1 to a drive letter and path only\n%~nx1 - expands %1 to a file name and extension only\n%~dp$PATH:1 - searches the directories listed in the PATH\n environment variable for %1 and expands to the\n drive letter and path of the first one found.\n%~ftza1 - expands %1 to a DIR like output line\n</code></pre>\n\n<p>This can be also found directly in command prompt when you run CALL /? or FOR /?</p>\n" }, { "answer_id": 13843928, "author": "djangofan", "author_id": 118228, "author_profile": "https://Stackoverflow.com/users/118228", "pm_score": 2, "selected": false, "text": "<p>This code explains the use of the ~tilde character, which was the most confusing thing to me. Once I understood this, it makes things much easier to understand:</p>\n<pre><code>@ECHO off\nSET &quot;PATH=%~dp0;%PATH%&quot;\nECHO %PATH%\nECHO.\nCALL :testargs &quot;these are days&quot; &quot;when the brave endure&quot;\nGOTO :pauseit\n:testargs\nSET ARGS=%~1;%~2;%1;%2\nECHO %ARGS%\nECHO.\nexit /B 0\n:pauseit\npause\n</code></pre>\n" }, { "answer_id": 24362536, "author": "Marvin Thobejane", "author_id": 1358924, "author_profile": "https://Stackoverflow.com/users/1358924", "pm_score": 4, "selected": false, "text": "<p>Another tip that would help a lot is that to set the current directory to a <strong>different drive</strong> one would have to use <strong><code>%~d0</code></strong> first, then <strong><code>cd %~dp0</code></strong>. This will change the directory to the batch file's drive, then change to its folder.</p>\n\n<p>For #oneLinerLovers, <strong><code>cd /d %~dp0</code></strong> will change both the drive and directory :)</p>\n\n<p>Hope this helps someone.</p>\n" }, { "answer_id": 31941357, "author": "Pacerier", "author_id": 632951, "author_profile": "https://Stackoverflow.com/users/632951", "pm_score": 3, "selected": false, "text": "<p>Some gotchas to watch out for:</p>\n\n<p>If you <strong>double-click</strong> the batch file <code>%0</code> will be surrounded by quotes. For example, if you save this file as <code>c:\\test.bat</code>:</p>\n\n<pre><code>@echo %0\n@pause\n</code></pre>\n\n<p>Double-clicking it will open a new command prompt with output:</p>\n\n<pre><code>\"C:\\test.bat\"\n</code></pre>\n\n<p>But if you first open a command prompt and call it directly from that command prompt, <code>%0</code> will refer to whatever you've <strong>typed</strong>. If you type <code>test.bat</code><kbd>Enter</kbd>, the output of <code>%0</code> will have no quotes because you typed no quotes:</p>\n\n<pre><code>c:\\&gt;test.bat\ntest.bat\n</code></pre>\n\n<p>If you type <code>test</code><kbd>Enter</kbd>, the output of <code>%0</code> will have no extension too, because you typed no extension:</p>\n\n<pre><code>c:\\&gt;test\ntest\n</code></pre>\n\n<p>Same for <code>tEsT</code><kbd>Enter</kbd>:</p>\n\n<pre><code>c:\\&gt;tEsT\ntEsT\n</code></pre>\n\n<p>If you type <code>\"test\"</code><kbd>Enter</kbd>, the output of <code>%0</code> will have quotes (since you typed them) but no extension:</p>\n\n<pre><code>c:\\&gt;\"test\"\n\"test\"\n</code></pre>\n\n<p>Lastly, if you type <code>\"C:\\test.bat\"</code>, the output would be exactly as though you've double clicked it:</p>\n\n<pre><code>c:\\&gt;\"C:\\test.bat\"\n\"C:\\test.bat\"\n</code></pre>\n\n<p>Note that these are not all the possible values <code>%0</code> can be because you can call the script from other folders:</p>\n\n<pre><code>c:\\some_folder&gt;/../teST.bAt\n/../teST.bAt\n</code></pre>\n\n<p>All the examples shown above will also affect <code>%~0</code>, because the output of <code>%~0</code> is simply the output of <code>%0</code> minus quotes (if any).</p>\n" }, { "answer_id": 34999149, "author": "zask", "author_id": 5434206, "author_profile": "https://Stackoverflow.com/users/5434206", "pm_score": 0, "selected": false, "text": "<p>It displays the current location of the file or directory that you are currently in. for example; if your batch file was in the desktop directory, then \"%~dp0\" would display the desktop directory. if you wanted it to display the current directory with the current file name you could type \"%~dp0%~n0%~x0\".</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322/" ]
I'm looking at a batch file which defines the following variables: ``` set _SCRIPT_DRIVE=%~d0 set _SCRIPT_PATH=%~p0 ``` * What do `%~d0` or `%~p0` actually mean? * Is there a set of well-known values for things like current directory, drive, parameters to a script? * Are there any other similar shortcuts I could use?
The magic variables `%`*n* contains the arguments used to invoke the file: `%0` is the path to the bat-file itself, `%1` is the first argument after, `%2` is the second and so on. Since the arguments are often file paths, there is some additional syntax to extract parts of the path. `~d` is drive, `~p` is the path (without drive), `~n` is the file name. They can be combined so `~dp` is drive+path. `%~dp0` is therefore pretty useful in a bat: it is the folder in which the executing bat file resides. You can also get other kinds of meta info about the file: `~t` is the timestamp, `~z` is the size. Look [here](http://technet.microsoft.com/en-us/library/bb490890.aspx) for a reference for all command line commands. The tilde-magic codes are described under [for](http://technet.microsoft.com/en-us/library/bb490909.aspx).
112,085
<p>Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this:</p> <pre><code>struct MY_STRUCT { int n1; int n2; }; class CMyStruct : public MY_STRUCT { public: CMyStruct() { memset(this, 0, sizeof(MY_STRUCT)); } }; </code></pre> <p>This trick is often used to initialize Win32 structures and can sometimes set the ubiquitous <strong>cbSize</strong> member.</p> <p>Now, as long as there isn't a virtual function table for the memset call to destroy, is this a safe practice?</p>
[ { "answer_id": 112099, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 2, "selected": false, "text": "<p>Precise layout of a class or structure is not guaranteed in C++, which is why you should not make assumptions about the size of it from the outside (that means if you're not a compiler).</p>\n\n<p>Probably it works, until you find a compiler on which it doesn't, or you throw some vtable into the mix.</p>\n" }, { "answer_id": 112100, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": true, "text": "<h2>PREAMBLE:</h2>\n<p>While my answer is still Ok, I find <a href=\"https://stackoverflow.com/questions/112085/is-this-c-structure-initialization-trick-safe/1315024#1315024\">litb's answer</a> quite superior to mine because:</p>\n<ol>\n<li>It teaches me a trick that I did not know (litb's answers usually have this effect, but this is the first time I write it down)</li>\n<li>It answers exactly the question (that is, initializing the original struct's part to zero)</li>\n</ol>\n<p>So please, consider litb's answer before mine. In fact, I suggest the question's author to consider litb's answer as the right one.</p>\n<h2>Original answer</h2>\n<p>Putting a true object (i.e. std::string) etc. inside will break, because the true object will be initialized before the memset, and then, overwritten by zeroes.</p>\n<p>Using the initialization list doesn't work for g++ (I'm surprised...). Initialize it instead in the CMyStruct constructor body. It will be C++ friendly:</p>\n<pre><code>class CMyStruct : public MY_STRUCT\n{\npublic:\n CMyStruct() { n1 = 0 ; n2 = 0 ; }\n};\n</code></pre>\n<p>P.S.: I assumed you did have <strong>no</strong> control over MY_STRUCT, of course. With control, you would have added the constructor directly inside MY_STRUCT and forgotten about inheritance. Note that you can add non-virtual methods to a C-like struct, and still have it behave as a struct.</p>\n<p>EDIT: Added missing parenthesis, after Lou Franco's comment. Thanks!</p>\n<p>EDIT 2 : I tried the code on g++, and for some reason, using the initialization list does not work. I corrected the code using the body constructor. The solution is still valid, though.</p>\n<p>Please reevaluate my post, as the original code was changed (see changelog for more info).</p>\n<p>EDIT 3 : After reading Rob's comment, I guess he has a point worthy of discussion: &quot;Agreed, but this could be an enormous Win32 structure which may change with a new SDK, so a memset is future proof.&quot;</p>\n<p>I disagree: Knowing Microsoft, it won't change because of their need for perfect backward compatibility. They will create instead an extended MY_STRUCT<b>Ex</b> struct with the same initial layout as MY_STRUCT, with additionnal members at the end, and recognizable through a &quot;size&quot; member variable like the struct used for a RegisterWindow, IIRC.</p>\n<p>So the only valid point remaining from Rob's comment is the &quot;enormous&quot; struct. In this case, perhaps a memset is more convenient, but you will have to make MY_STRUCT a variable member of CMyStruct instead of inheriting from it.</p>\n<p>I see another hack, but I guess this would break because of possible struct alignment problem.</p>\n<p>EDIT 4: Please take a look at Frank Krueger's solution. I can't promise it's portable (I guess it is), but it is still interesting from a technical viewpoint because it shows one case where, in C++, the &quot;this&quot; pointer &quot;address&quot; moves from its base class to its inherited class.</p>\n" }, { "answer_id": 112104, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>If you already have a constructor, why not just initialize it there with n1=0; n2=0; -- that's certainly the more <em>normal</em> way.</p>\n\n<p>Edit: Actually, as paercebal has shown, ctor initialization is even better.</p>\n" }, { "answer_id": 112110, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": false, "text": "<p>This would make me feel much safer as it should work even if there is a <code>vtable</code> (or the compiler will scream).</p>\n\n<pre><code>memset(static_cast&lt;MY_STRUCT*&gt;(this), 0, sizeof(MY_STRUCT));\n</code></pre>\n\n<p>I'm sure your solution will work, but I doubt there are any guarantees to be made when mixing <code>memset</code> and classes.</p>\n" }, { "answer_id": 112116, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 1, "selected": false, "text": "<p>My opinion is no. I'm not sure what it gains either.</p>\n\n<p>As your definition of CMyStruct changes and you add/delete members, this can lead to bugs. Easily.</p>\n\n<p>Create a constructor for CMyStruct that takes a MyStruct has a parameter.</p>\n\n<pre><code>CMyStruct::CMyStruct(MyStruct &amp;)\n</code></pre>\n\n<p>Or something of that sought. You can then initialize a public or private 'MyStruct' member.</p>\n" }, { "answer_id": 112126, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 4, "selected": false, "text": "<p>Much better than a memset, you can use this little trick instead:</p>\n\n<pre><code>MY_STRUCT foo = { 0 };\n</code></pre>\n\n<p>This will initialize all members to 0 (or their default value iirc), no need to specifiy a value for each.</p>\n" }, { "answer_id": 112166, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "<p>This is a perfect example of porting a C idiom to C++ (and why it might not always work...)</p>\n\n<p>The problem you will have with using memset is that in C++, a struct and a class are exactly the same thing except that by default, a struct has public visibility and a class has private visibility.</p>\n\n<p>Thus, what if later on, some well meaning programmer changes MY_STRUCT like so:</p>\n\n<pre><code>\nstruct MY_STRUCT\n{\n int n1;\n int n2;\n\n // Provide a default implementation...\n virtual int add() {return n1 + n2;} \n};\n</code></pre>\n\n<p>By adding that single function, your memset might now cause havoc.\nThere is a detailed discussion in <a href=\"http://groups.google.com/group/comp.lang.c++/browse_thread/thread/43346fe9338fa50b/670fe22433a96c6f?lnk=st&amp;q=memset+class+group%3Acomp.lang.c%2B%2B#670fe22433a96c6f\" rel=\"nofollow noreferrer\">comp.lang.c+</a></p>\n" }, { "answer_id": 112329, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "<p>From an ISO C++ viewpoint, there are two issues:</p>\n\n<p>(1) Is the object a POD? The acronym stands for Plain Old Data, and the standard enumerates what you can't have in a POD (Wikipedia has a good summary). If it's not a POD, you can't memset it.</p>\n\n<p>(2) Are there members for which all-bits-zero is invalid ? On Windows and Unix, the NULL pointer is all bits zero; it need not be. Floating point 0 has all bits zero in IEEE754, which is quite common, and on x86.</p>\n\n<p>Frank Kruegers tip addresses your concerns by restricting the memset to the POD base of the non-POD class.</p>\n" }, { "answer_id": 112353, "author": "Thanatopsis", "author_id": 15936, "author_profile": "https://Stackoverflow.com/users/15936", "pm_score": 1, "selected": false, "text": "<p>Try this - overload new.</p>\n\n<p>EDIT: I should add - This is safe because the memory is zeroed before <em>any</em> constructors are called. Big flaw - only works if object is dynamically allocated.</p>\n\n<pre><code>struct MY_STRUCT\n{\n int n1;\n int n2;\n};\n\nclass CMyStruct : public MY_STRUCT\n{\npublic:\n CMyStruct()\n {\n // whatever\n }\n void* new(size_t size)\n {\n // dangerous\n return memset(malloc(size),0,size);\n // better\n if (void *p = malloc(size))\n {\n return (memset(p, 0, size));\n }\n else\n {\n throw bad_alloc();\n }\n }\n void delete(void *p, size_t size)\n {\n free(p);\n }\n\n};\n</code></pre>\n" }, { "answer_id": 113943, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 2, "selected": false, "text": "<p>The examples have \"unspecified behaviour\".</p>\n\n<p>For a non-POD, the order by which the compiler lays out an object (all bases classes and members) is unspecified (ISO C++ 10/3). Consider the following:</p>\n\n<pre><code>struct A {\n int i;\n};\n\nclass B : public A { // 'B' is not a POD\npublic:\n B ();\n\nprivate:\n int j;\n};\n</code></pre>\n\n<p>This can be laid out as:</p>\n\n<pre><code>[ int i ][ int j ]\n</code></pre>\n\n<p>Or as:</p>\n\n<pre><code>[ int j ][ int i ]\n</code></pre>\n\n<p>Therefore, using memset directly on the address of 'this' is very much unspecified behaviour. One of the answers above, at first glance looks to be safer:</p>\n\n<pre><code> memset(static_cast&lt;MY_STRUCT*&gt;(this), 0, sizeof(MY_STRUCT));\n</code></pre>\n\n<p>I believe, however, that strictly speaking this too results in unspecified behaviour. I cannot find the normative text, however the note in 10/5 says: \"A base class subobject may have a layout (3.7) different from the layout of a most derived object of the same type\". </p>\n\n<p>As a result, I compiler could perform space optimizations with the different members:</p>\n\n<pre><code>struct A {\n char c1;\n};\n\nstruct B {\n char c2;\n char c3;\n char c4;\n int i;\n};\n\nclass C : public A, public B\n{\npublic:\n C () \n : c1 (10);\n {\n memset(static_cast&lt;B*&gt;(this), 0, sizeof(B)); \n }\n};\n</code></pre>\n\n<p>Can be laid out as:</p>\n\n<pre><code>[ char c1 ] [ char c2, char c3, char c4, int i ]\n</code></pre>\n\n<p>On a 32 bit system, due to alighments etc. for 'B', sizeof(B) will most likely be 8 bytes. However, sizeof(C) can also be '8' bytes if the compiler packs the data members. Therefore the call to memset might overwrite the value given to 'c1'.</p>\n" }, { "answer_id": 115878, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "<p>It's a bit of code, but it's reusable; include it once and it should work for any POD. You can pass an instance of this class to any function expecting a MY_STRUCT, or use the GetPointer function to pass it into a function that will modify the structure.</p>\n\n<pre><code>template &lt;typename STR&gt;\nclass CStructWrapper\n{\nprivate:\n STR MyStruct;\n\npublic:\n CStructWrapper() { STR temp = {}; MyStruct = temp;}\n CStructWrapper(const STR &amp;myStruct) : MyStruct(myStruct) {}\n\n operator STR &amp;() { return MyStruct; }\n operator const STR &amp;() const { return MyStruct; }\n\n STR *GetPointer() { return &amp;MyStruct; }\n};\n\nCStructWrapper&lt;MY_STRUCT&gt; myStruct;\nCStructWrapper&lt;ANOTHER_STRUCT&gt; anotherStruct;\n</code></pre>\n\n<p>This way, you don't have to worry about whether NULLs are all 0, or floating point representations. As long as STR is a simple aggregate type, things will work. When STR is not a simple aggregate type, you'll get a compile-time error, so you won't have to worry about accidentally misusing this. Also, if the type contains something more complex, as long as it has a default constructor, you're ok:</p>\n\n<pre><code>struct MY_STRUCT2\n{\n int n1;\n std::string s1;\n};\n\nCStructWrapper&lt;MY_STRUCT2&gt; myStruct2; // n1 is set to 0, s1 is set to \"\";\n</code></pre>\n\n<p>On the downside, it's slower since you're making an extra temporary copy, and the compiler will assign each member to 0 individually, instead of one memset.</p>\n" }, { "answer_id": 116794, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 0, "selected": false, "text": "<p>What I do is use aggregate initialization, but only specifying initializers for members I care about, e.g:</p>\n\n<pre><code>STARTUPINFO si = {\n sizeof si, /*cb*/\n 0, /*lpReserved*/\n 0, /*lpDesktop*/\n \"my window\" /*lpTitle*/\n};\n</code></pre>\n\n<p>The remaining members will be initialized to zeros of the appropriate type (as in Drealmer's post). Here, you are trusting Microsoft not to gratuitously break compatibility by adding new structure members in the middle (a reasonable assumption). This solution strikes me as optimal - one statement, no classes, no memset, no assumptions about the internal representation of floating point zero or null pointers.</p>\n\n<p>I think the hacks involving inheritance are horrible style. Public inheritance means IS-A to most readers. Note also that you're inheriting from a class which isn't designed to be a base. As there's no virtual destructor, clients who delete a derived class instance through a pointer to base will invoke undefined behaviour.</p>\n" }, { "answer_id": 1312950, "author": "jwhitlock", "author_id": 10612, "author_profile": "https://Stackoverflow.com/users/10612", "pm_score": 1, "selected": false, "text": "<p>If MY_STRUCT is your code, and you are happy using a C++ compiler, you can put the constructor there without wrapping in a class:</p>\n\n<pre><code>struct MY_STRUCT\n{\n int n1;\n int n2;\n MY_STRUCT(): n1(0), n2(0) {}\n};\n</code></pre>\n\n<p>I'm not sure about efficiency, but I hate doing tricks when you haven't proved efficiency is needed.</p>\n" }, { "answer_id": 1315024, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": false, "text": "<p>You can simply value-initialize the base, and all its members will be zero'ed out. This is guaranteed</p>\n\n<pre><code>struct MY_STRUCT\n{\n int n1;\n int n2;\n};\n\nclass CMyStruct : public MY_STRUCT\n{\npublic:\n CMyStruct():MY_STRUCT() { }\n};\n</code></pre>\n\n<p>For this to work, there should be no user declared constructor in the base class, like in your example. </p>\n\n<p>No nasty <code>memset</code> for that. It's not guaranteed that <code>memset</code> works in your code, even though it should work in practice. </p>\n" }, { "answer_id": 1623268, "author": "grob", "author_id": 196454, "author_profile": "https://Stackoverflow.com/users/196454", "pm_score": 0, "selected": false, "text": "<p>I assume the structure is provided to you and cannot be modified. If you can change the structure, then the obvious solution is adding a constructor.</p>\n\n<p>Don't over engineer your code with C++ wrappers when all you want is a simple macro to initialise your structure. </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n#define MY_STRUCT(x) MY_STRUCT x = {0}\n\nstruct MY_STRUCT\n{\n int n1;\n int n2;\n};\n\nint main(int argc, char *argv[])\n{\n MY_STRUCT(s);\n\n printf(\"n1(%d),n2(%d)\\n\", s.n1, s.n2);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 6184474, "author": "yau", "author_id": 636486, "author_profile": "https://Stackoverflow.com/users/636486", "pm_score": 1, "selected": false, "text": "<p>Comment on <a href=\"https://stackoverflow.com/questions/112085/is-this-c-structure-initialization-trick-safe/1315024#1315024\">litb's answer</a> (seems I'm not yet allowed to comment directly):</p>\n\n<p>Even with this nice C++-style solution you have to be very careful that you don't apply this naively to a struct containing a non-POD member.</p>\n\n<p>Some compilers then don't initialize correctly anymore.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/2816752/can-a-member-struct-be-zero-init-from-the-constructor-initializer-list-without-ca/2816811#2816811\">this answer to a similar question</a>.\nI personally had the bad experience on VC2008 with an additional std::string.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this: ``` struct MY_STRUCT { int n1; int n2; }; class CMyStruct : public MY_STRUCT { public: CMyStruct() { memset(this, 0, sizeof(MY_STRUCT)); } }; ``` This trick is often used to initialize Win32 structures and can sometimes set the ubiquitous **cbSize** member. Now, as long as there isn't a virtual function table for the memset call to destroy, is this a safe practice?
PREAMBLE: --------- While my answer is still Ok, I find [litb's answer](https://stackoverflow.com/questions/112085/is-this-c-structure-initialization-trick-safe/1315024#1315024) quite superior to mine because: 1. It teaches me a trick that I did not know (litb's answers usually have this effect, but this is the first time I write it down) 2. It answers exactly the question (that is, initializing the original struct's part to zero) So please, consider litb's answer before mine. In fact, I suggest the question's author to consider litb's answer as the right one. Original answer --------------- Putting a true object (i.e. std::string) etc. inside will break, because the true object will be initialized before the memset, and then, overwritten by zeroes. Using the initialization list doesn't work for g++ (I'm surprised...). Initialize it instead in the CMyStruct constructor body. It will be C++ friendly: ``` class CMyStruct : public MY_STRUCT { public: CMyStruct() { n1 = 0 ; n2 = 0 ; } }; ``` P.S.: I assumed you did have **no** control over MY\_STRUCT, of course. With control, you would have added the constructor directly inside MY\_STRUCT and forgotten about inheritance. Note that you can add non-virtual methods to a C-like struct, and still have it behave as a struct. EDIT: Added missing parenthesis, after Lou Franco's comment. Thanks! EDIT 2 : I tried the code on g++, and for some reason, using the initialization list does not work. I corrected the code using the body constructor. The solution is still valid, though. Please reevaluate my post, as the original code was changed (see changelog for more info). EDIT 3 : After reading Rob's comment, I guess he has a point worthy of discussion: "Agreed, but this could be an enormous Win32 structure which may change with a new SDK, so a memset is future proof." I disagree: Knowing Microsoft, it won't change because of their need for perfect backward compatibility. They will create instead an extended MY\_STRUCT**Ex** struct with the same initial layout as MY\_STRUCT, with additionnal members at the end, and recognizable through a "size" member variable like the struct used for a RegisterWindow, IIRC. So the only valid point remaining from Rob's comment is the "enormous" struct. In this case, perhaps a memset is more convenient, but you will have to make MY\_STRUCT a variable member of CMyStruct instead of inheriting from it. I see another hack, but I guess this would break because of possible struct alignment problem. EDIT 4: Please take a look at Frank Krueger's solution. I can't promise it's portable (I guess it is), but it is still interesting from a technical viewpoint because it shows one case where, in C++, the "this" pointer "address" moves from its base class to its inherited class.
112,093
<p>I have a simple list I am using for a horizontal menu:</p> <pre><code>&lt;ul&gt; &lt;h1&gt;Menu&lt;/h1&gt; &lt;li&gt; &lt;a href="/" class="selected"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="/Home"&gt;Forum&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section.</p> <p>Hope this makes sense.</p>
[ { "answer_id": 112106, "author": "Justin Poliey", "author_id": 6967, "author_profile": "https://Stackoverflow.com/users/6967", "pm_score": 5, "selected": true, "text": "<p>The a element is an inline element, meaning it only applies to the text it encloses. If you want the background color to stretch across horizontally, apply the selected class to a block level element. Applying the class to the li element should work fine.</p>\n\n<p>Alternatively, you could add this to the selected class' CSS:</p>\n\n<pre><code>display: block;\n</code></pre>\n\n<p>Which will make the a element display like a block element.</p>\n" }, { "answer_id": 112114, "author": "Josh Hunt", "author_id": 2592, "author_profile": "https://Stackoverflow.com/users/2592", "pm_score": 2, "selected": false, "text": "<p>Would something like this work?</p>\n\n<pre><code>.selected {\n display: block;\n width: 100%;\n background: #BEBEBE;\n}\n</code></pre>\n" }, { "answer_id": 112115, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>Put the selected class on the <code>&lt;li&gt;</code> and not the <code>&lt;a&gt;</code></p>\n" }, { "answer_id": 112150, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p><code>&lt;a&gt;</code> elements are inline by default. This means that they don't establish their own block, they are just part of the text. You want them to establish their own block, so you should use <code>a { display: block; }</code> with an appropriate context. This also enables you to add padding to the <code>&lt;a&gt;</code> elements rather than the <code>&lt;li&gt;</code> elements, making their clickable area larger, and thus easier to use.</p>\n" }, { "answer_id": 112238, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": false, "text": "<p>Everyone is correct that your problem is that anchors are inline elements, but I thought it is also worth mentioning that you have an H1 inside of your list as well. The H1 isn't allowed there and should be pulled out of the UL or placed into an LI tag.</p>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/112093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I have a simple list I am using for a horizontal menu: ``` <ul> <h1>Menu</h1> <li> <a href="/" class="selected">Home</a> </li> <li> <a href="/Home">Forum</a> </li> </ul> ``` When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section. Hope this makes sense.
The a element is an inline element, meaning it only applies to the text it encloses. If you want the background color to stretch across horizontally, apply the selected class to a block level element. Applying the class to the li element should work fine. Alternatively, you could add this to the selected class' CSS: ``` display: block; ``` Which will make the a element display like a block element.